1
0

download.go 5.5 KB

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