download.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "image"
  7. "io"
  8. "io/ioutil"
  9. "net"
  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. imageDataCtxKey = ctxKey("imageData")
  20. errSourceDimensionsTooBig = newError(422, "Source image dimensions are too big", "Invalid source image")
  21. errSourceResolutionTooBig = newError(422, "Source image resolution is too big", "Invalid source image")
  22. errSourceFileTooBig = newError(422, "Source image file is 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. type imageData struct {
  28. Data []byte
  29. Type imageType
  30. cancel context.CancelFunc
  31. }
  32. func (d *imageData) Close() {
  33. if d.cancel != nil {
  34. d.cancel()
  35. }
  36. }
  37. type limitReader struct {
  38. r io.Reader
  39. left int
  40. }
  41. func (lr *limitReader) Read(p []byte) (n int, err error) {
  42. n, err = lr.r.Read(p)
  43. lr.left -= n
  44. if err == nil && lr.left < 0 {
  45. err = errSourceFileTooBig
  46. }
  47. return
  48. }
  49. func initDownloading() {
  50. transport := &http.Transport{
  51. Proxy: http.ProxyFromEnvironment,
  52. MaxIdleConns: conf.Concurrency,
  53. MaxIdleConnsPerHost: conf.Concurrency,
  54. DisableCompression: true,
  55. Dial: (&net.Dialer{KeepAlive: 600 * time.Second}).Dial,
  56. }
  57. if conf.IgnoreSslVerification {
  58. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  59. }
  60. if conf.LocalFileSystemRoot != "" {
  61. transport.RegisterProtocol("local", newFsTransport())
  62. }
  63. if conf.S3Enabled {
  64. transport.RegisterProtocol("s3", newS3Transport())
  65. }
  66. if len(conf.GCSKey) > 0 {
  67. transport.RegisterProtocol("gs", newGCSTransport())
  68. }
  69. downloadClient = &http.Client{
  70. Timeout: time.Duration(conf.DownloadTimeout) * time.Second,
  71. Transport: transport,
  72. }
  73. downloadBufPool = newBufPool("download", conf.Concurrency, conf.DownloadBufferSize)
  74. }
  75. func checkDimensions(width, height int) error {
  76. if conf.MaxSrcDimension > 0 && (width > conf.MaxSrcDimension || height > conf.MaxSrcDimension) {
  77. return errSourceDimensionsTooBig
  78. }
  79. if width*height > conf.MaxSrcResolution {
  80. return errSourceResolutionTooBig
  81. }
  82. return nil
  83. }
  84. func checkTypeAndDimensions(r io.Reader) (imageType, error) {
  85. imgconf, imgtypeStr, err := image.DecodeConfig(r)
  86. if err == image.ErrFormat {
  87. return imageTypeUnknown, errSourceImageTypeNotSupported
  88. }
  89. if err != nil {
  90. return imageTypeUnknown, newUnexpectedError(err.Error(), 0)
  91. }
  92. imgtype, imgtypeOk := imageTypes[imgtypeStr]
  93. if !imgtypeOk || !vipsTypeSupportLoad[imgtype] {
  94. return imageTypeUnknown, errSourceImageTypeNotSupported
  95. }
  96. if err = checkDimensions(imgconf.Width, imgconf.Height); err != nil {
  97. return imageTypeUnknown, err
  98. }
  99. return imgtype, nil
  100. }
  101. func readAndCheckImage(r io.Reader, contentLength int) (*imageData, error) {
  102. if conf.MaxSrcFileSize > 0 && contentLength > conf.MaxSrcFileSize {
  103. return nil, errSourceFileTooBig
  104. }
  105. buf := downloadBufPool.Get(contentLength)
  106. cancel := func() { downloadBufPool.Put(buf) }
  107. if conf.MaxSrcFileSize > 0 {
  108. r = &limitReader{r: r, left: conf.MaxSrcFileSize}
  109. }
  110. imgtype, err := checkTypeAndDimensions(io.TeeReader(r, buf))
  111. if err != nil {
  112. cancel()
  113. return nil, err
  114. }
  115. if _, err = buf.ReadFrom(r); err != nil {
  116. cancel()
  117. return nil, newError(404, err.Error(), msgSourceImageIsUnreachable)
  118. }
  119. return &imageData{buf.Bytes(), imgtype, cancel}, nil
  120. }
  121. func requestImage(imageURL string) (*http.Response, error) {
  122. req, err := http.NewRequest("GET", imageURL, nil)
  123. if err != nil {
  124. return nil, newError(404, err.Error(), msgSourceImageIsUnreachable).MarkAsUnexpected()
  125. }
  126. req.Header.Set("User-Agent", conf.UserAgent)
  127. res, err := downloadClient.Do(req)
  128. if err != nil {
  129. return res, newError(404, err.Error(), msgSourceImageIsUnreachable).MarkAsUnexpected()
  130. }
  131. if res.StatusCode != 200 {
  132. body, _ := ioutil.ReadAll(res.Body)
  133. msg := fmt.Sprintf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  134. return res, newError(404, msg, msgSourceImageIsUnreachable).MarkAsUnexpected()
  135. }
  136. return res, nil
  137. }
  138. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  139. imageURL := getImageURL(ctx)
  140. if newRelicEnabled {
  141. newRelicCancel := startNewRelicSegment(ctx, "Downloading image")
  142. defer newRelicCancel()
  143. }
  144. if prometheusEnabled {
  145. defer startPrometheusDuration(prometheusDownloadDuration)()
  146. }
  147. res, err := requestImage(imageURL)
  148. if res != nil {
  149. defer res.Body.Close()
  150. }
  151. if err != nil {
  152. return ctx, func() {}, err
  153. }
  154. imgdata, err := readAndCheckImage(res.Body, int(res.ContentLength))
  155. if err != nil {
  156. return ctx, func() {}, err
  157. }
  158. ctx = context.WithValue(ctx, imageDataCtxKey, imgdata)
  159. return ctx, imgdata.Close, err
  160. }
  161. func getImageData(ctx context.Context) *imageData {
  162. return ctx.Value(imageDataCtxKey).(*imageData)
  163. }