download.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package imagedata
  2. import (
  3. "compress/gzip"
  4. "crypto/tls"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/http/cookiejar"
  10. "time"
  11. "github.com/imgproxy/imgproxy/v3/config"
  12. "github.com/imgproxy/imgproxy/v3/ierrors"
  13. azureTransport "github.com/imgproxy/imgproxy/v3/transport/azure"
  14. fsTransport "github.com/imgproxy/imgproxy/v3/transport/fs"
  15. gcsTransport "github.com/imgproxy/imgproxy/v3/transport/gcs"
  16. s3Transport "github.com/imgproxy/imgproxy/v3/transport/s3"
  17. )
  18. var (
  19. downloadClient *http.Client
  20. enabledSchemes = map[string]struct{}{
  21. "http": {},
  22. "https": {},
  23. }
  24. imageHeadersToStore = []string{
  25. "Cache-Control",
  26. "Expires",
  27. "ETag",
  28. }
  29. // For tests
  30. redirectAllRequestsTo string
  31. )
  32. const msgSourceImageIsUnreachable = "Source image is unreachable"
  33. type ErrorNotModified struct {
  34. Message string
  35. Headers map[string]string
  36. }
  37. func (e *ErrorNotModified) Error() string {
  38. return e.Message
  39. }
  40. func initDownloading() error {
  41. transport := &http.Transport{
  42. Proxy: http.ProxyFromEnvironment,
  43. MaxIdleConns: config.Concurrency,
  44. MaxIdleConnsPerHost: config.Concurrency,
  45. DisableCompression: true,
  46. DialContext: (&net.Dialer{KeepAlive: 600 * time.Second}).DialContext,
  47. }
  48. if config.IgnoreSslVerification {
  49. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  50. }
  51. registerProtocol := func(scheme string, rt http.RoundTripper) {
  52. transport.RegisterProtocol(scheme, rt)
  53. enabledSchemes[scheme] = struct{}{}
  54. }
  55. if config.LocalFileSystemRoot != "" {
  56. registerProtocol("local", fsTransport.New())
  57. }
  58. if config.S3Enabled {
  59. if t, err := s3Transport.New(); err != nil {
  60. return err
  61. } else {
  62. registerProtocol("s3", t)
  63. }
  64. }
  65. if config.GCSEnabled {
  66. if t, err := gcsTransport.New(); err != nil {
  67. return err
  68. } else {
  69. registerProtocol("gs", t)
  70. }
  71. }
  72. if config.ABSEnabled {
  73. if t, err := azureTransport.New(); err != nil {
  74. return err
  75. } else {
  76. registerProtocol("abs", t)
  77. }
  78. }
  79. downloadClient = &http.Client{
  80. Timeout: time.Duration(config.DownloadTimeout) * time.Second,
  81. Transport: transport,
  82. }
  83. return nil
  84. }
  85. func headersToStore(res *http.Response) map[string]string {
  86. m := make(map[string]string)
  87. for _, h := range imageHeadersToStore {
  88. if val := res.Header.Get(h); len(val) != 0 {
  89. m[h] = val
  90. }
  91. }
  92. return m
  93. }
  94. func requestImage(imageURL string, header http.Header, jar *cookiejar.Jar) (*http.Response, error) {
  95. req, err := http.NewRequest("GET", imageURL, nil)
  96. if err != nil {
  97. return nil, ierrors.New(404, err.Error(), msgSourceImageIsUnreachable)
  98. }
  99. if _, ok := enabledSchemes[req.URL.Scheme]; !ok {
  100. return nil, ierrors.New(
  101. 404,
  102. fmt.Sprintf("Unknown sheme: %s", req.URL.Scheme),
  103. msgSourceImageIsUnreachable,
  104. )
  105. }
  106. if jar != nil {
  107. for _, cookie := range jar.Cookies(req.URL) {
  108. req.AddCookie(cookie)
  109. }
  110. }
  111. req.Header.Set("User-Agent", config.UserAgent)
  112. for k, v := range header {
  113. if len(v) > 0 {
  114. req.Header.Set(k, v[0])
  115. }
  116. }
  117. res, err := downloadClient.Do(req)
  118. if err != nil {
  119. return nil, ierrors.New(500, checkTimeoutErr(err).Error(), msgSourceImageIsUnreachable)
  120. }
  121. if res.StatusCode == http.StatusNotModified {
  122. return nil, &ErrorNotModified{Message: "Not Modified", Headers: headersToStore(res)}
  123. }
  124. if res.StatusCode != 200 {
  125. body, _ := ioutil.ReadAll(res.Body)
  126. res.Body.Close()
  127. status := 404
  128. if res.StatusCode >= 500 {
  129. status = 500
  130. }
  131. msg := fmt.Sprintf("Status: %d; %s", res.StatusCode, string(body))
  132. return nil, ierrors.New(status, msg, msgSourceImageIsUnreachable)
  133. }
  134. return res, nil
  135. }
  136. func download(imageURL string, header http.Header, jar *cookiejar.Jar) (*ImageData, error) {
  137. // We use this for testing
  138. if len(redirectAllRequestsTo) > 0 {
  139. imageURL = redirectAllRequestsTo
  140. }
  141. res, err := requestImage(imageURL, header, jar)
  142. if res != nil {
  143. defer res.Body.Close()
  144. }
  145. if err != nil {
  146. return nil, err
  147. }
  148. body := res.Body
  149. contentLength := int(res.ContentLength)
  150. if res.Header.Get("Content-Encoding") == "gzip" {
  151. gzipBody, errGzip := gzip.NewReader(res.Body)
  152. if gzipBody != nil {
  153. defer gzipBody.Close()
  154. }
  155. if errGzip != nil {
  156. return nil, err
  157. }
  158. body = gzipBody
  159. contentLength = 0
  160. }
  161. imgdata, err := readAndCheckImage(body, contentLength)
  162. if err != nil {
  163. return nil, ierrors.Wrap(err, 0)
  164. }
  165. imgdata.Headers = headersToStore(res)
  166. return imgdata, nil
  167. }
  168. func RedirectAllRequestsTo(u string) {
  169. redirectAllRequestsTo = u
  170. }
  171. func StopRedirectingRequests() {
  172. redirectAllRequestsTo = ""
  173. }