download.go 5.3 KB

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