download.go 5.7 KB

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