download.go 3.3 KB

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