download.go 3.9 KB

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