download.go 5.6 KB

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