download.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "image"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "sync"
  13. "time"
  14. _ "image/gif"
  15. _ "image/jpeg"
  16. _ "image/png"
  17. _ "golang.org/x/image/webp"
  18. )
  19. var (
  20. downloadClient *http.Client
  21. imageTypeCtxKey = ctxKey("imageType")
  22. imageDataCtxKey = ctxKey("imageData")
  23. errSourceDimensionsTooBig = errors.New("Source image dimensions are too big")
  24. errSourceResolutionTooBig = errors.New("Source image resolution are too big")
  25. errSourceImageTypeNotSupported = errors.New("Source image type not supported")
  26. )
  27. var downloadBufPool = sync.Pool{
  28. New: func() interface{} {
  29. return new(bytes.Buffer)
  30. },
  31. }
  32. func initDownloading() {
  33. transport := &http.Transport{
  34. Proxy: http.ProxyFromEnvironment,
  35. }
  36. if conf.IgnoreSslVerification {
  37. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  38. }
  39. if conf.LocalFileSystemRoot != "" {
  40. transport.RegisterProtocol("local", http.NewFileTransport(http.Dir(conf.LocalFileSystemRoot)))
  41. }
  42. if conf.S3Enabled {
  43. transport.RegisterProtocol("s3", newS3Transport())
  44. }
  45. if len(conf.GCSKey) > 0 {
  46. transport.RegisterProtocol("gs", newGCSTransport())
  47. }
  48. downloadClient = &http.Client{
  49. Timeout: time.Duration(conf.DownloadTimeout) * time.Second,
  50. Transport: transport,
  51. }
  52. }
  53. func checkDimensions(width, height int) error {
  54. if width > conf.MaxSrcDimension || height > conf.MaxSrcDimension {
  55. return errSourceDimensionsTooBig
  56. }
  57. if width*height > conf.MaxSrcResolution {
  58. return errSourceResolutionTooBig
  59. }
  60. return nil
  61. }
  62. func checkTypeAndDimensions(r io.Reader) (imageType, error) {
  63. imgconf, imgtypeStr, err := image.DecodeConfig(r)
  64. if err != nil {
  65. return imageTypeUnknown, err
  66. }
  67. imgtype, imgtypeOk := imageTypes[imgtypeStr]
  68. if !imgtypeOk || !vipsTypeSupportLoad[imgtype] {
  69. return imageTypeUnknown, errSourceImageTypeNotSupported
  70. }
  71. if err = checkDimensions(imgconf.Width, imgconf.Height); err != nil {
  72. return imageTypeUnknown, err
  73. }
  74. return imgtype, nil
  75. }
  76. func readAndCheckImage(ctx context.Context, res *http.Response) (context.Context, context.CancelFunc, error) {
  77. buf := downloadBufPool.Get().(*bytes.Buffer)
  78. cancel := func() {
  79. buf.Reset()
  80. downloadBufPool.Put(buf)
  81. }
  82. imgtype, err := checkTypeAndDimensions(io.TeeReader(res.Body, buf))
  83. if err != nil {
  84. return ctx, cancel, err
  85. }
  86. if _, err = buf.ReadFrom(res.Body); err == nil {
  87. ctx = context.WithValue(ctx, imageTypeCtxKey, imgtype)
  88. ctx = context.WithValue(ctx, imageDataCtxKey, buf)
  89. }
  90. return ctx, cancel, err
  91. }
  92. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  93. url := getImageURL(ctx)
  94. if newRelicEnabled {
  95. newRelicCancel := startNewRelicSegment(ctx, "Downloading image")
  96. defer newRelicCancel()
  97. }
  98. if prometheusEnabled {
  99. defer startPrometheusDuration(prometheusDownloadDuration)()
  100. }
  101. req, err := http.NewRequest("GET", url, nil)
  102. if err != nil {
  103. return ctx, func() {}, err
  104. }
  105. req.Header.Set("User-Agent", conf.UserAgent)
  106. res, err := downloadClient.Do(req)
  107. if err != nil {
  108. return ctx, func() {}, err
  109. }
  110. defer res.Body.Close()
  111. if res.StatusCode != 200 {
  112. body, _ := ioutil.ReadAll(res.Body)
  113. return ctx, func() {}, fmt.Errorf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  114. }
  115. return readAndCheckImage(ctx, res)
  116. }
  117. func getImageType(ctx context.Context) imageType {
  118. return ctx.Value(imageTypeCtxKey).(imageType)
  119. }
  120. func getImageData(ctx context.Context) *bytes.Buffer {
  121. return ctx.Value(imageDataCtxKey).(*bytes.Buffer)
  122. }