download.go 5.2 KB

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