download.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package main
  2. import (
  3. "compress/gzip"
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "time"
  12. "github.com/imgproxy/imgproxy/v2/imagemeta"
  13. )
  14. var (
  15. downloadClient *http.Client
  16. imageDataCtxKey = ctxKey("imageData")
  17. imageHeadersToStore = []string{
  18. "Cache-Control",
  19. "Expires",
  20. }
  21. errSourceResolutionTooBig = newError(422, "Source image resolution is too big", "Invalid source image")
  22. errSourceFileTooBig = newError(422, "Source image file is too big", "Invalid source image")
  23. errSourceImageTypeNotSupported = newError(422, "Source image type not supported", "Invalid source image")
  24. )
  25. const msgSourceImageIsUnreachable = "Source image is unreachable"
  26. var downloadBufPool *bufPool
  27. type hardLimitReader struct {
  28. r io.Reader
  29. left int
  30. }
  31. func (lr *hardLimitReader) Read(p []byte) (n int, err error) {
  32. if lr.left <= 0 {
  33. return 0, errSourceFileTooBig
  34. }
  35. if len(p) > lr.left {
  36. p = p[0:lr.left]
  37. }
  38. n, err = lr.r.Read(p)
  39. lr.left -= n
  40. return
  41. }
  42. func initDownloading() error {
  43. transport := &http.Transport{
  44. Proxy: http.ProxyFromEnvironment,
  45. MaxIdleConns: conf.Concurrency,
  46. MaxIdleConnsPerHost: conf.Concurrency,
  47. DisableCompression: true,
  48. DialContext: (&net.Dialer{KeepAlive: 600 * time.Second}).DialContext,
  49. }
  50. if conf.IgnoreSslVerification {
  51. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  52. }
  53. if conf.LocalFileSystemRoot != "" {
  54. transport.RegisterProtocol("local", newFsTransport())
  55. }
  56. if conf.S3Enabled {
  57. if t, err := newS3Transport(); err != nil {
  58. return err
  59. } else {
  60. transport.RegisterProtocol("s3", t)
  61. }
  62. }
  63. if conf.GCSEnabled {
  64. if t, err := newGCSTransport(); err != nil {
  65. return err
  66. } else {
  67. transport.RegisterProtocol("gs", t)
  68. }
  69. }
  70. if conf.ABSEnabled {
  71. if t, err := newAzureTransport(); err != nil {
  72. return err
  73. } else {
  74. transport.RegisterProtocol("abs", t)
  75. }
  76. }
  77. downloadClient = &http.Client{
  78. Timeout: time.Duration(conf.DownloadTimeout) * time.Second,
  79. Transport: transport,
  80. }
  81. downloadBufPool = newBufPool("download", conf.Concurrency, conf.DownloadBufferSize)
  82. imagemeta.SetMaxSvgCheckRead(conf.MaxSvgCheckBytes)
  83. return nil
  84. }
  85. func checkDimensions(width, height int) error {
  86. if width*height > conf.MaxSrcResolution {
  87. return errSourceResolutionTooBig
  88. }
  89. return nil
  90. }
  91. func checkTypeAndDimensions(r io.Reader) (imageType, error) {
  92. meta, err := imagemeta.DecodeMeta(r)
  93. if err == imagemeta.ErrFormat {
  94. return imageTypeUnknown, errSourceImageTypeNotSupported
  95. }
  96. if err != nil {
  97. return imageTypeUnknown, wrapError(err, 0)
  98. }
  99. imgtype, imgtypeOk := imageTypes[meta.Format()]
  100. if !imgtypeOk || !imageTypeLoadSupport(imgtype) {
  101. return imageTypeUnknown, errSourceImageTypeNotSupported
  102. }
  103. if err = checkDimensions(meta.Width(), meta.Height()); err != nil {
  104. return imageTypeUnknown, err
  105. }
  106. return imgtype, nil
  107. }
  108. func readAndCheckImage(r io.Reader, contentLength int) (*imageData, error) {
  109. if conf.MaxSrcFileSize > 0 && contentLength > conf.MaxSrcFileSize {
  110. return nil, errSourceFileTooBig
  111. }
  112. buf := downloadBufPool.Get(contentLength)
  113. cancel := func() { downloadBufPool.Put(buf) }
  114. if conf.MaxSrcFileSize > 0 {
  115. r = &hardLimitReader{r: r, left: conf.MaxSrcFileSize}
  116. }
  117. br := newBufReader(r, buf)
  118. imgtype, err := checkTypeAndDimensions(br)
  119. if err != nil {
  120. cancel()
  121. return nil, err
  122. }
  123. if err = br.Flush(); err != nil {
  124. cancel()
  125. return nil, newError(404, err.Error(), msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  126. }
  127. return &imageData{
  128. Data: buf.Bytes(),
  129. Type: imgtype,
  130. cancel: cancel,
  131. }, nil
  132. }
  133. func requestImage(imageURL string) (*http.Response, error) {
  134. req, err := http.NewRequest("GET", imageURL, nil)
  135. if err != nil {
  136. return nil, newError(404, err.Error(), msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  137. }
  138. req.Header.Set("User-Agent", conf.UserAgent)
  139. res, err := downloadClient.Do(req)
  140. if err != nil {
  141. return res, newError(404, err.Error(), msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  142. }
  143. if res.StatusCode != 200 {
  144. body, _ := ioutil.ReadAll(res.Body)
  145. res.Body.Close()
  146. msg := fmt.Sprintf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  147. return res, newError(404, msg, msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  148. }
  149. return res, nil
  150. }
  151. func downloadImage(imageURL string) (*imageData, error) {
  152. res, err := requestImage(imageURL)
  153. if res != nil {
  154. defer res.Body.Close()
  155. }
  156. if err != nil {
  157. return nil, err
  158. }
  159. body := res.Body
  160. contentLength := int(res.ContentLength)
  161. if res.Header.Get("Content-Encoding") == "gzip" {
  162. gzipBody, errGzip := gzip.NewReader(res.Body)
  163. if gzipBody != nil {
  164. defer gzipBody.Close()
  165. }
  166. if errGzip != nil {
  167. return nil, err
  168. }
  169. body = gzipBody
  170. contentLength = 0
  171. }
  172. imgdata, err := readAndCheckImage(body, contentLength)
  173. if err != nil {
  174. return nil, err
  175. }
  176. imgdata.Headers = make(map[string]string)
  177. for _, h := range imageHeadersToStore {
  178. if val := res.Header.Get(h); len(val) != 0 {
  179. imgdata.Headers[h] = val
  180. }
  181. }
  182. return imgdata, nil
  183. }
  184. func downloadImageCtx(ctx context.Context) (context.Context, context.CancelFunc, error) {
  185. imageURL := getImageURL(ctx)
  186. defer startDataDogSpan(ctx, "downloading_image")()
  187. defer startNewRelicSegment(ctx, "Downloading image")()
  188. defer startPrometheusDuration(prometheusDownloadDuration)()
  189. imgdata, err := downloadImage(imageURL)
  190. if err != nil {
  191. return ctx, func() {}, err
  192. }
  193. ctx = context.WithValue(ctx, imageDataCtxKey, imgdata)
  194. return ctx, imgdata.Close, nil
  195. }
  196. func getImageData(ctx context.Context) *imageData {
  197. return ctx.Value(imageDataCtxKey).(*imageData)
  198. }