download.go 4.9 KB

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