download.go 4.0 KB

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