1
0

download.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. )
  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 are too big", "Invalid source image")
  24. errSourceImageTypeNotSupported = newError(422, "Source image type not supported", "Invalid source image")
  25. )
  26. const msgSourceImageIsUnreachable = "Source image is unreachable"
  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 conf.MaxSrcDimension > 0 && (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, errSourceImageTypeNotSupported
  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. return ctx, cancel, newError(404, err.Error(), msgSourceImageIsUnreachable)
  88. }
  89. ctx = context.WithValue(ctx, imageTypeCtxKey, imgtype)
  90. ctx = context.WithValue(ctx, imageDataCtxKey, buf)
  91. return ctx, cancel, nil
  92. }
  93. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  94. url := getImageURL(ctx)
  95. if newRelicEnabled {
  96. newRelicCancel := startNewRelicSegment(ctx, "Downloading image")
  97. defer newRelicCancel()
  98. }
  99. if prometheusEnabled {
  100. defer startPrometheusDuration(prometheusDownloadDuration)()
  101. }
  102. req, err := http.NewRequest("GET", url, nil)
  103. if err != nil {
  104. return ctx, func() {}, newError(404, err.Error(), msgSourceImageIsUnreachable)
  105. }
  106. req.Header.Set("User-Agent", conf.UserAgent)
  107. res, err := downloadClient.Do(req)
  108. if err != nil {
  109. return ctx, func() {}, newError(404, err.Error(), msgSourceImageIsUnreachable)
  110. }
  111. defer res.Body.Close()
  112. if res.StatusCode != 200 {
  113. body, _ := ioutil.ReadAll(res.Body)
  114. msg := fmt.Sprintf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  115. return ctx, func() {}, newError(404, msg, msgSourceImageIsUnreachable)
  116. }
  117. return readAndCheckImage(ctx, res)
  118. }
  119. func getImageType(ctx context.Context) imageType {
  120. return ctx.Value(imageTypeCtxKey).(imageType)
  121. }
  122. func getImageData(ctx context.Context) *bytes.Buffer {
  123. return ctx.Value(imageDataCtxKey).(*bytes.Buffer)
  124. }