download.go 5.5 KB

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