download.go 3.9 KB

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