download.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  83. redirects := len(via)
  84. if redirects >= config.MaxRedirects {
  85. return fmt.Errorf("stopped after %d redirects", redirects)
  86. }
  87. return nil
  88. },
  89. }
  90. return nil
  91. }
  92. func headersToStore(res *http.Response) map[string]string {
  93. m := make(map[string]string)
  94. for _, h := range imageHeadersToStore {
  95. if val := res.Header.Get(h); len(val) != 0 {
  96. m[h] = val
  97. }
  98. }
  99. return m
  100. }
  101. func requestImage(imageURL string, header http.Header, jar *cookiejar.Jar) (*http.Response, error) {
  102. req, err := http.NewRequest("GET", imageURL, nil)
  103. if err != nil {
  104. return nil, ierrors.New(404, err.Error(), msgSourceImageIsUnreachable)
  105. }
  106. if _, ok := enabledSchemes[req.URL.Scheme]; !ok {
  107. return nil, ierrors.New(
  108. 404,
  109. fmt.Sprintf("Unknown sheme: %s", req.URL.Scheme),
  110. msgSourceImageIsUnreachable,
  111. )
  112. }
  113. if jar != nil {
  114. for _, cookie := range jar.Cookies(req.URL) {
  115. req.AddCookie(cookie)
  116. }
  117. }
  118. req.Header.Set("User-Agent", config.UserAgent)
  119. for k, v := range header {
  120. if len(v) > 0 {
  121. req.Header.Set(k, v[0])
  122. }
  123. }
  124. res, err := downloadClient.Do(req)
  125. if err != nil {
  126. return nil, ierrors.New(500, checkTimeoutErr(err).Error(), msgSourceImageIsUnreachable)
  127. }
  128. if res.StatusCode == http.StatusNotModified {
  129. return nil, &ErrorNotModified{Message: "Not Modified", Headers: headersToStore(res)}
  130. }
  131. if res.StatusCode != 200 {
  132. body, _ := ioutil.ReadAll(res.Body)
  133. res.Body.Close()
  134. status := 404
  135. if res.StatusCode >= 500 {
  136. status = 500
  137. }
  138. msg := fmt.Sprintf("Status: %d; %s", res.StatusCode, string(body))
  139. return nil, ierrors.New(status, msg, msgSourceImageIsUnreachable)
  140. }
  141. return res, nil
  142. }
  143. func download(imageURL string, header http.Header, jar *cookiejar.Jar) (*ImageData, error) {
  144. // We use this for testing
  145. if len(redirectAllRequestsTo) > 0 {
  146. imageURL = redirectAllRequestsTo
  147. }
  148. res, err := requestImage(imageURL, header, jar)
  149. if res != nil {
  150. defer res.Body.Close()
  151. }
  152. if err != nil {
  153. return nil, err
  154. }
  155. body := res.Body
  156. contentLength := int(res.ContentLength)
  157. if res.Header.Get("Content-Encoding") == "gzip" {
  158. gzipBody, errGzip := gzip.NewReader(res.Body)
  159. if gzipBody != nil {
  160. defer gzipBody.Close()
  161. }
  162. if errGzip != nil {
  163. return nil, err
  164. }
  165. body = gzipBody
  166. contentLength = 0
  167. }
  168. imgdata, err := readAndCheckImage(body, contentLength)
  169. if err != nil {
  170. return nil, ierrors.Wrap(err, 0)
  171. }
  172. imgdata.Headers = headersToStore(res)
  173. return imgdata, nil
  174. }
  175. func RedirectAllRequestsTo(u string) {
  176. redirectAllRequestsTo = u
  177. }
  178. func StopRedirectingRequests() {
  179. redirectAllRequestsTo = ""
  180. }