download.go 5.4 KB

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