download.go 4.9 KB

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