download.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. DialContext: (&net.Dialer{KeepAlive: 600 * time.Second}).DialContext,
  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. if conf.ABSEnabled {
  66. if t, err := newAzureTransport(); err != nil {
  67. return err
  68. } else {
  69. transport.RegisterProtocol("abs", t)
  70. }
  71. }
  72. downloadClient = &http.Client{
  73. Timeout: time.Duration(conf.DownloadTimeout) * time.Second,
  74. Transport: transport,
  75. }
  76. downloadBufPool = newBufPool("download", conf.Concurrency, conf.DownloadBufferSize)
  77. imagemeta.SetMaxSvgCheckRead(conf.MaxSvgCheckBytes)
  78. return nil
  79. }
  80. func checkDimensions(width, height int) error {
  81. if conf.MaxSrcDimension > 0 && (width > conf.MaxSrcDimension || height > conf.MaxSrcDimension) {
  82. return errSourceDimensionsTooBig
  83. }
  84. if width*height > conf.MaxSrcResolution {
  85. return errSourceResolutionTooBig
  86. }
  87. return nil
  88. }
  89. func checkTypeAndDimensions(r io.Reader) (imageType, error) {
  90. meta, err := imagemeta.DecodeMeta(r)
  91. if err == imagemeta.ErrFormat {
  92. return imageTypeUnknown, errSourceImageTypeNotSupported
  93. }
  94. if err != nil {
  95. return imageTypeUnknown, newUnexpectedError(err.Error(), 0)
  96. }
  97. imgtype, imgtypeOk := imageTypes[meta.Format()]
  98. if !imgtypeOk || !imageTypeLoadSupport(imgtype) {
  99. return imageTypeUnknown, errSourceImageTypeNotSupported
  100. }
  101. if err = checkDimensions(meta.Width(), meta.Height()); err != nil {
  102. return imageTypeUnknown, err
  103. }
  104. return imgtype, nil
  105. }
  106. func readAndCheckImage(r io.Reader, contentLength int) (*imageData, error) {
  107. if conf.MaxSrcFileSize > 0 && contentLength > conf.MaxSrcFileSize {
  108. return nil, errSourceFileTooBig
  109. }
  110. buf := downloadBufPool.Get(contentLength)
  111. cancel := func() { downloadBufPool.Put(buf) }
  112. if conf.MaxSrcFileSize > 0 {
  113. r = &limitReader{r: r, left: conf.MaxSrcFileSize}
  114. }
  115. imgtype, err := checkTypeAndDimensions(io.TeeReader(r, buf))
  116. if err != nil {
  117. cancel()
  118. return nil, err
  119. }
  120. if _, err = buf.ReadFrom(r); err != nil {
  121. cancel()
  122. return nil, newError(404, err.Error(), msgSourceImageIsUnreachable)
  123. }
  124. return &imageData{buf.Bytes(), imgtype, cancel}, nil
  125. }
  126. func requestImage(imageURL string) (*http.Response, error) {
  127. req, err := http.NewRequest("GET", imageURL, nil)
  128. if err != nil {
  129. return nil, newError(404, err.Error(), msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  130. }
  131. req.Header.Set("User-Agent", conf.UserAgent)
  132. res, err := downloadClient.Do(req)
  133. if err != nil {
  134. return res, newError(404, err.Error(), msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  135. }
  136. if res.StatusCode != 200 {
  137. body, _ := ioutil.ReadAll(res.Body)
  138. msg := fmt.Sprintf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  139. return res, newError(404, msg, msgSourceImageIsUnreachable).SetUnexpected(conf.ReportDownloadingErrors)
  140. }
  141. return res, nil
  142. }
  143. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  144. imageURL := getImageURL(ctx)
  145. if newRelicEnabled {
  146. newRelicCancel := startNewRelicSegment(ctx, "Downloading image")
  147. defer newRelicCancel()
  148. }
  149. if prometheusEnabled {
  150. defer startPrometheusDuration(prometheusDownloadDuration)()
  151. }
  152. res, err := requestImage(imageURL)
  153. if res != nil {
  154. defer res.Body.Close()
  155. }
  156. if err != nil {
  157. return ctx, func() {}, err
  158. }
  159. imgdata, err := readAndCheckImage(res.Body, int(res.ContentLength))
  160. if err != nil {
  161. return ctx, func() {}, err
  162. }
  163. ctx = context.WithValue(ctx, imageDataCtxKey, imgdata)
  164. ctx = context.WithValue(ctx, cacheControlHeaderCtxKey, res.Header.Get("Cache-Control"))
  165. ctx = context.WithValue(ctx, expiresHeaderCtxKey, res.Header.Get("Expires"))
  166. return ctx, imgdata.Close, err
  167. }
  168. func getImageData(ctx context.Context) *imageData {
  169. return ctx.Value(imageDataCtxKey).(*imageData)
  170. }
  171. func getCacheControlHeader(ctx context.Context) string {
  172. str, _ := ctx.Value(cacheControlHeaderCtxKey).(string)
  173. return str
  174. }
  175. func getExpiresHeader(ctx context.Context) string {
  176. str, _ := ctx.Value(expiresHeaderCtxKey).(string)
  177. return str
  178. }