download.go 3.8 KB

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