download.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "image"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "strconv"
  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 = 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. }
  48. if conf.IgnoreSslVerification {
  49. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  50. }
  51. if conf.LocalFileSystemRoot != "" {
  52. transport.RegisterProtocol("local", http.NewFileTransport(http.Dir(conf.LocalFileSystemRoot)))
  53. }
  54. if conf.S3Enabled {
  55. transport.RegisterProtocol("s3", newS3Transport())
  56. }
  57. if len(conf.GCSKey) > 0 {
  58. transport.RegisterProtocol("gs", newGCSTransport())
  59. }
  60. downloadClient = &http.Client{
  61. Timeout: time.Duration(conf.DownloadTimeout) * time.Second,
  62. Transport: transport,
  63. }
  64. downloadBufPool = newBufPool(conf.Concurrency, conf.DownloadBufferSize)
  65. }
  66. func checkDimensions(width, height int) error {
  67. if conf.MaxSrcDimension > 0 && (width > conf.MaxSrcDimension || height > conf.MaxSrcDimension) {
  68. return errSourceDimensionsTooBig
  69. }
  70. if width*height > conf.MaxSrcResolution {
  71. return errSourceResolutionTooBig
  72. }
  73. return nil
  74. }
  75. func checkTypeAndDimensions(r io.Reader) (imageType, error) {
  76. imgconf, imgtypeStr, err := image.DecodeConfig(r)
  77. if err == image.ErrFormat {
  78. return imageTypeUnknown, errSourceImageTypeNotSupported
  79. }
  80. if err != nil {
  81. return imageTypeUnknown, err
  82. }
  83. imgtype, imgtypeOk := imageTypes[imgtypeStr]
  84. if !imgtypeOk || !vipsTypeSupportLoad[imgtype] {
  85. return imageTypeUnknown, errSourceImageTypeNotSupported
  86. }
  87. if err = checkDimensions(imgconf.Width, imgconf.Height); err != nil {
  88. return imageTypeUnknown, err
  89. }
  90. return imgtype, nil
  91. }
  92. func readAndCheckImage(ctx context.Context, res *http.Response) (context.Context, context.CancelFunc, error) {
  93. buf := downloadBufPool.get()
  94. cancel := func() {
  95. downloadBufPool.put(buf)
  96. }
  97. body := res.Body
  98. if conf.MaxSrcFileSize > 0 {
  99. body = &limitReader{r: body, left: conf.MaxSrcFileSize}
  100. }
  101. imgtype, err := checkTypeAndDimensions(io.TeeReader(body, buf))
  102. if err != nil {
  103. return ctx, cancel, err
  104. }
  105. var contentLength int
  106. if res.ContentLength > 0 {
  107. contentLength = int(res.ContentLength)
  108. } else {
  109. // ContentLength wasn't set properly, trying to parse the header
  110. contentLength, _ = strconv.Atoi(res.Header.Get("Content-Length"))
  111. }
  112. if contentLength > buf.Cap() {
  113. buf.Grow(contentLength - buf.Len())
  114. }
  115. if _, err = buf.ReadFrom(body); err != nil {
  116. return ctx, cancel, newError(404, err.Error(), msgSourceImageIsUnreachable)
  117. }
  118. ctx = context.WithValue(ctx, imageTypeCtxKey, imgtype)
  119. ctx = context.WithValue(ctx, imageDataCtxKey, buf)
  120. return ctx, cancel, nil
  121. }
  122. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  123. url := getImageURL(ctx)
  124. if newRelicEnabled {
  125. newRelicCancel := startNewRelicSegment(ctx, "Downloading image")
  126. defer newRelicCancel()
  127. }
  128. if prometheusEnabled {
  129. defer startPrometheusDuration(prometheusDownloadDuration)()
  130. }
  131. req, err := http.NewRequest("GET", url, nil)
  132. if err != nil {
  133. return ctx, func() {}, newError(404, err.Error(), msgSourceImageIsUnreachable)
  134. }
  135. req.Header.Set("User-Agent", conf.UserAgent)
  136. res, err := downloadClient.Do(req)
  137. if err != nil {
  138. return ctx, func() {}, newError(404, err.Error(), msgSourceImageIsUnreachable)
  139. }
  140. defer res.Body.Close()
  141. if res.StatusCode != 200 {
  142. body, _ := ioutil.ReadAll(res.Body)
  143. msg := fmt.Sprintf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  144. return ctx, func() {}, newError(404, msg, msgSourceImageIsUnreachable)
  145. }
  146. return readAndCheckImage(ctx, res)
  147. }
  148. func getImageType(ctx context.Context) imageType {
  149. return ctx.Value(imageTypeCtxKey).(imageType)
  150. }
  151. func getImageData(ctx context.Context) *bytes.Buffer {
  152. return ctx.Value(imageDataCtxKey).(*bytes.Buffer)
  153. }