download.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "strconv"
  13. "time"
  14. _ "image/gif"
  15. _ "image/jpeg"
  16. _ "image/png"
  17. _ "github.com/mat/besticon/ico"
  18. )
  19. var (
  20. downloadClient *http.Client
  21. imageTypeCtxKey = ctxKey("imageType")
  22. imageDataCtxKey = ctxKey("imageData")
  23. errSourceDimensionsTooBig = newError(422, "Source image dimensions are too big", "Invalid source image")
  24. errSourceResolutionTooBig = newError(422, "Source image resolution is too big", "Invalid source image")
  25. errSourceFileTooBig = newError(422, "Source image file is too big", "Invalid source image")
  26. errSourceImageTypeNotSupported = newError(422, "Source image type not supported", "Invalid source image")
  27. )
  28. const msgSourceImageIsUnreachable = "Source image is unreachable"
  29. var downloadBufPool *bufPool
  30. type limitReader struct {
  31. r io.ReadCloser
  32. left int
  33. }
  34. func (lr *limitReader) Read(p []byte) (n int, err error) {
  35. n, err = lr.r.Read(p)
  36. lr.left = lr.left - n
  37. if err == nil && lr.left < 0 {
  38. err = errSourceFileTooBig
  39. }
  40. return
  41. }
  42. func (lr *limitReader) Close() error {
  43. return lr.r.Close()
  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", http.NewFileTransport(http.Dir(conf.LocalFileSystemRoot)))
  58. }
  59. if conf.S3Enabled {
  60. transport.RegisterProtocol("s3", newS3Transport())
  61. }
  62. if len(conf.GCSKey) > 0 {
  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. imgconf, imgtypeStr, err := image.DecodeConfig(r)
  82. if err == image.ErrFormat {
  83. return imageTypeUnknown, errSourceImageTypeNotSupported
  84. }
  85. if err != nil {
  86. return imageTypeUnknown, err
  87. }
  88. imgtype, imgtypeOk := imageTypes[imgtypeStr]
  89. if !imgtypeOk || !vipsTypeSupportLoad[imgtype] {
  90. return imageTypeUnknown, errSourceImageTypeNotSupported
  91. }
  92. if err = checkDimensions(imgconf.Width, imgconf.Height); err != nil {
  93. return imageTypeUnknown, err
  94. }
  95. return imgtype, nil
  96. }
  97. func readAndCheckImage(ctx context.Context, res *http.Response) (context.Context, context.CancelFunc, error) {
  98. var contentLength int
  99. if res.ContentLength > 0 {
  100. contentLength = int(res.ContentLength)
  101. } else {
  102. // ContentLength wasn't set properly, trying to parse the header
  103. contentLength, _ = strconv.Atoi(res.Header.Get("Content-Length"))
  104. }
  105. buf := downloadBufPool.Get(contentLength)
  106. cancel := func() {
  107. downloadBufPool.Put(buf)
  108. }
  109. if contentLength > buf.Cap() {
  110. buf.Grow(contentLength - buf.Len())
  111. }
  112. body := res.Body
  113. if conf.MaxSrcFileSize > 0 {
  114. body = &limitReader{r: body, left: conf.MaxSrcFileSize}
  115. }
  116. imgtype, err := checkTypeAndDimensions(io.TeeReader(body, buf))
  117. if err != nil {
  118. return ctx, cancel, err
  119. }
  120. if _, err = buf.ReadFrom(body); err != nil {
  121. return ctx, cancel, newError(404, err.Error(), msgSourceImageIsUnreachable)
  122. }
  123. ctx = context.WithValue(ctx, imageTypeCtxKey, imgtype)
  124. ctx = context.WithValue(ctx, imageDataCtxKey, buf)
  125. return ctx, cancel, nil
  126. }
  127. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  128. url := getImageURL(ctx)
  129. if newRelicEnabled {
  130. newRelicCancel := startNewRelicSegment(ctx, "Downloading image")
  131. defer newRelicCancel()
  132. }
  133. if prometheusEnabled {
  134. defer startPrometheusDuration(prometheusDownloadDuration)()
  135. }
  136. req, err := http.NewRequest("GET", url, nil)
  137. if err != nil {
  138. return ctx, func() {}, newError(404, err.Error(), msgSourceImageIsUnreachable)
  139. }
  140. req.Header.Set("User-Agent", conf.UserAgent)
  141. res, err := downloadClient.Do(req)
  142. if res != nil {
  143. defer res.Body.Close()
  144. }
  145. if err != nil {
  146. return ctx, func() {}, newError(404, err.Error(), msgSourceImageIsUnreachable)
  147. }
  148. if res.StatusCode != 200 {
  149. body, _ := ioutil.ReadAll(res.Body)
  150. msg := fmt.Sprintf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  151. return ctx, func() {}, newError(404, msg, msgSourceImageIsUnreachable)
  152. }
  153. return readAndCheckImage(ctx, res)
  154. }
  155. func getImageType(ctx context.Context) imageType {
  156. return ctx.Value(imageTypeCtxKey).(imageType)
  157. }
  158. func getImageData(ctx context.Context) *bytes.Buffer {
  159. return ctx.Value(imageDataCtxKey).(*bytes.Buffer)
  160. }