processing_handler.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/url"
  6. "net/http"
  7. "net/http/cookiejar"
  8. "golang.org/x/net/publicsuffix"
  9. "strconv"
  10. "strings"
  11. "time"
  12. log "github.com/sirupsen/logrus"
  13. "github.com/imgproxy/imgproxy/v3/config"
  14. "github.com/imgproxy/imgproxy/v3/errorreport"
  15. "github.com/imgproxy/imgproxy/v3/etag"
  16. "github.com/imgproxy/imgproxy/v3/ierrors"
  17. "github.com/imgproxy/imgproxy/v3/imagedata"
  18. "github.com/imgproxy/imgproxy/v3/imagetype"
  19. "github.com/imgproxy/imgproxy/v3/metrics"
  20. "github.com/imgproxy/imgproxy/v3/options"
  21. "github.com/imgproxy/imgproxy/v3/processing"
  22. "github.com/imgproxy/imgproxy/v3/router"
  23. "github.com/imgproxy/imgproxy/v3/security"
  24. "github.com/imgproxy/imgproxy/v3/vips"
  25. )
  26. var (
  27. processingSem chan struct{}
  28. headerVaryValue string
  29. )
  30. func initProcessingHandler() {
  31. processingSem = make(chan struct{}, config.Concurrency)
  32. vary := make([]string, 0)
  33. if config.EnableWebpDetection || config.EnforceWebp {
  34. vary = append(vary, "Accept")
  35. }
  36. if config.EnableClientHints {
  37. vary = append(vary, "DPR", "Viewport-Width", "Width")
  38. }
  39. headerVaryValue = strings.Join(vary, ", ")
  40. }
  41. func setCacheControl(rw http.ResponseWriter, originHeaders map[string]string) {
  42. var cacheControl, expires string
  43. if config.CacheControlPassthrough && originHeaders != nil {
  44. if val, ok := originHeaders["Cache-Control"]; ok {
  45. cacheControl = val
  46. }
  47. if val, ok := originHeaders["Expires"]; ok {
  48. expires = val
  49. }
  50. }
  51. if len(cacheControl) == 0 && len(expires) == 0 {
  52. cacheControl = fmt.Sprintf("max-age=%d, public", config.TTL)
  53. expires = time.Now().Add(time.Second * time.Duration(config.TTL)).Format(http.TimeFormat)
  54. }
  55. if len(cacheControl) > 0 {
  56. rw.Header().Set("Cache-Control", cacheControl)
  57. }
  58. if len(expires) > 0 {
  59. rw.Header().Set("Expires", expires)
  60. }
  61. }
  62. func setVary(rw http.ResponseWriter) {
  63. if len(headerVaryValue) > 0 {
  64. rw.Header().Set("Vary", headerVaryValue)
  65. }
  66. }
  67. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData *imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData *imagedata.ImageData) {
  68. var contentDisposition string
  69. if len(po.Filename) > 0 {
  70. contentDisposition = resultData.Type.ContentDisposition(po.Filename)
  71. } else {
  72. contentDisposition = resultData.Type.ContentDispositionFromURL(originURL)
  73. }
  74. rw.Header().Set("Content-Type", resultData.Type.Mime())
  75. rw.Header().Set("Content-Disposition", contentDisposition)
  76. if po.Dpr != 1 {
  77. rw.Header().Set("Content-DPR", strconv.FormatFloat(po.Dpr, 'f', 2, 32))
  78. }
  79. if config.SetCanonicalHeader {
  80. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  81. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  82. rw.Header().Set("Link", linkHeader)
  83. }
  84. }
  85. setCacheControl(rw, originData.Headers)
  86. setVary(rw)
  87. if config.EnableDebugHeaders {
  88. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(len(originData.Data)))
  89. rw.Header().Set("X-Origin-Width", resultData.Headers["X-Origin-Width"])
  90. rw.Header().Set("X-Origin-Height", resultData.Headers["X-Origin-Height"])
  91. }
  92. rw.Header().Set("Content-Length", strconv.Itoa(len(resultData.Data)))
  93. rw.WriteHeader(statusCode)
  94. rw.Write(resultData.Data)
  95. router.LogResponse(
  96. reqID, r, statusCode, nil,
  97. log.Fields{
  98. "image_url": originURL,
  99. "processing_options": po,
  100. },
  101. )
  102. }
  103. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders map[string]string) {
  104. setCacheControl(rw, originHeaders)
  105. setVary(rw)
  106. rw.WriteHeader(304)
  107. router.LogResponse(
  108. reqID, r, 304, nil,
  109. log.Fields{
  110. "image_url": originURL,
  111. "processing_options": po,
  112. },
  113. )
  114. }
  115. func cookieJarFromRequest(r *http.Request) (*cookiejar.Jar, error) {
  116. jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
  117. if err != nil {
  118. return nil, err
  119. }
  120. if config.CookiePassthrough && r != nil {
  121. cookieBase := config.CookieBaseURL
  122. if len(cookieBase) == 0 {
  123. scheme := r.Header.Get("X-Forwarded-Proto")
  124. if len(scheme) == 0 {
  125. scheme = "http"
  126. }
  127. host := r.Header.Get("X-Forwarded-Host")
  128. if len(host) == 0 {
  129. host = r.Header.Get("Host")
  130. }
  131. if len(host) == 0 {
  132. cookieBase = ""
  133. } else {
  134. port := r.Header.Get("X-Forwarded-Port")
  135. if len(port) > 0 {
  136. host = host + ":" + port
  137. }
  138. cookieBase = scheme + "://" + host + "/"
  139. }
  140. }
  141. if len(cookieBase) > 0 {
  142. cookieBaseURL, err := url.Parse(cookieBase)
  143. if err != nil {
  144. return nil, err
  145. }
  146. jar.SetCookies(cookieBaseURL, r.Cookies())
  147. }
  148. }
  149. return jar, nil
  150. }
  151. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  152. ctx, timeoutCancel := context.WithTimeout(r.Context(), time.Duration(config.WriteTimeout)*time.Second)
  153. defer timeoutCancel()
  154. var metricsCancel context.CancelFunc
  155. ctx, metricsCancel, rw = metrics.StartRequest(ctx, rw, r)
  156. defer metricsCancel()
  157. path := r.RequestURI
  158. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  159. path = path[:queryStart]
  160. }
  161. if len(config.PathPrefix) > 0 {
  162. path = strings.TrimPrefix(path, config.PathPrefix)
  163. }
  164. path = strings.TrimPrefix(path, "/")
  165. signature := ""
  166. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  167. signature = path[:signatureEnd]
  168. path = path[signatureEnd:]
  169. } else {
  170. panic(ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL"))
  171. }
  172. if err := security.VerifySignature(signature, path); err != nil {
  173. panic(ierrors.New(403, err.Error(), "Forbidden"))
  174. }
  175. po, imageURL, err := options.ParsePath(path, r.Header)
  176. if err != nil {
  177. panic(err)
  178. }
  179. if !security.VerifySourceURL(imageURL) {
  180. panic(ierrors.New(404, fmt.Sprintf("Source URL is not allowed: %s", imageURL), "Invalid source"))
  181. }
  182. jar, err := cookieJarFromRequest(r)
  183. if err != nil {
  184. panic(err)
  185. }
  186. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  187. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  188. panic(ierrors.New(
  189. 422,
  190. fmt.Sprintf("Resulting image format is not supported: %s", po.Format),
  191. "Invalid URL",
  192. ))
  193. }
  194. imgRequestHeader := make(http.Header)
  195. var etagHandler etag.Handler
  196. if config.ETagEnabled {
  197. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  198. if etagHandler.SetActualProcessingOptions(po) {
  199. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  200. imgRequestHeader.Set("If-None-Match", imgEtag)
  201. }
  202. }
  203. }
  204. // The heavy part start here, so we need to restrict concurrency
  205. select {
  206. case processingSem <- struct{}{}:
  207. case <-ctx.Done():
  208. // We don't actually need to check timeout here,
  209. // but it's an easy way to check if this is an actual timeout
  210. // or the request was cancelled
  211. router.CheckTimeout(ctx)
  212. }
  213. defer func() { <-processingSem }()
  214. statusCode := http.StatusOK
  215. originData, err := func() (*imagedata.ImageData, error) {
  216. defer metrics.StartDownloadingSegment(ctx)()
  217. return imagedata.Download(imageURL, "source image", imgRequestHeader, jar)
  218. }()
  219. if err == nil {
  220. defer originData.Close()
  221. } else if nmErr, ok := err.(*imagedata.ErrorNotModified); ok && config.ETagEnabled {
  222. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  223. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers)
  224. return
  225. } else {
  226. ierr, ierrok := err.(*ierrors.Error)
  227. if ierrok {
  228. statusCode = ierr.StatusCode
  229. }
  230. if config.ReportDownloadingErrors && (!ierrok || ierr.Unexpected) {
  231. errorreport.Report(err, r)
  232. }
  233. metrics.SendError(ctx, "download", err)
  234. if imagedata.FallbackImage == nil {
  235. panic(err)
  236. }
  237. log.Warningf("Could not load image %s. Using fallback image. %s", imageURL, err.Error())
  238. if config.FallbackImageHTTPCode > 0 {
  239. statusCode = config.FallbackImageHTTPCode
  240. }
  241. originData = imagedata.FallbackImage
  242. }
  243. router.CheckTimeout(ctx)
  244. if config.ETagEnabled && statusCode == http.StatusOK {
  245. imgDataMatch := etagHandler.SetActualImageData(originData)
  246. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  247. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  248. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers)
  249. return
  250. }
  251. }
  252. router.CheckTimeout(ctx)
  253. if originData.Type == po.Format || po.Format == imagetype.Unknown {
  254. // Don't process SVG
  255. if originData.Type == imagetype.SVG {
  256. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  257. return
  258. }
  259. if len(po.SkipProcessingFormats) > 0 {
  260. for _, f := range po.SkipProcessingFormats {
  261. if f == originData.Type {
  262. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  263. return
  264. }
  265. }
  266. }
  267. }
  268. if !vips.SupportsLoad(originData.Type) {
  269. panic(ierrors.New(
  270. 422,
  271. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  272. "Invalid URL",
  273. ))
  274. }
  275. // At this point we can't allow requested format to be SVG as we can't save SVGs
  276. if po.Format == imagetype.SVG {
  277. panic(ierrors.New(422, "Resulting image format is not supported: svg", "Invalid URL"))
  278. }
  279. resultData, err := func() (*imagedata.ImageData, error) {
  280. defer metrics.StartProcessingSegment(ctx)()
  281. return processing.ProcessImage(ctx, originData, po)
  282. }()
  283. if err != nil {
  284. metrics.SendError(ctx, "processing", err)
  285. panic(err)
  286. }
  287. defer resultData.Close()
  288. router.CheckTimeout(ctx)
  289. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  290. }