download.go 6.2 KB

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