1
0

download.go 5.9 KB

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