processing_handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "slices"
  10. "strconv"
  11. "strings"
  12. "time"
  13. log "github.com/sirupsen/logrus"
  14. "golang.org/x/sync/semaphore"
  15. "github.com/imgproxy/imgproxy/v3/config"
  16. "github.com/imgproxy/imgproxy/v3/cookies"
  17. "github.com/imgproxy/imgproxy/v3/errorreport"
  18. "github.com/imgproxy/imgproxy/v3/etag"
  19. "github.com/imgproxy/imgproxy/v3/httpheaders"
  20. "github.com/imgproxy/imgproxy/v3/ierrors"
  21. "github.com/imgproxy/imgproxy/v3/imagedata"
  22. "github.com/imgproxy/imgproxy/v3/imagefetcher"
  23. "github.com/imgproxy/imgproxy/v3/imagetype"
  24. "github.com/imgproxy/imgproxy/v3/imath"
  25. "github.com/imgproxy/imgproxy/v3/metrics"
  26. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  27. "github.com/imgproxy/imgproxy/v3/options"
  28. "github.com/imgproxy/imgproxy/v3/processing"
  29. "github.com/imgproxy/imgproxy/v3/router"
  30. "github.com/imgproxy/imgproxy/v3/security"
  31. "github.com/imgproxy/imgproxy/v3/svg"
  32. "github.com/imgproxy/imgproxy/v3/vips"
  33. )
  34. var (
  35. queueSem *semaphore.Weighted
  36. processingSem *semaphore.Weighted
  37. headerVaryValue string
  38. )
  39. func initProcessingHandler() {
  40. if config.RequestsQueueSize > 0 {
  41. queueSem = semaphore.NewWeighted(int64(config.RequestsQueueSize + config.Workers))
  42. }
  43. processingSem = semaphore.NewWeighted(int64(config.Workers))
  44. vary := make([]string, 0)
  45. if config.AutoWebp ||
  46. config.EnforceWebp ||
  47. config.AutoAvif ||
  48. config.EnforceAvif ||
  49. config.AutoJxl ||
  50. config.EnforceJxl {
  51. vary = append(vary, "Accept")
  52. }
  53. if config.EnableClientHints {
  54. vary = append(vary, "Sec-CH-DPR", "DPR", "Sec-CH-Width", "Width")
  55. }
  56. headerVaryValue = strings.Join(vary, ", ")
  57. }
  58. func setCacheControl(rw http.ResponseWriter, force *time.Time, originHeaders http.Header) {
  59. ttl := -1
  60. if _, ok := originHeaders["Fallback-Image"]; ok && config.FallbackImageTTL > 0 {
  61. ttl = config.FallbackImageTTL
  62. }
  63. if force != nil && (ttl < 0 || force.Before(time.Now().Add(time.Duration(ttl)*time.Second))) {
  64. ttl = imath.Min(config.TTL, imath.Max(0, int(time.Until(*force).Seconds())))
  65. }
  66. if config.CacheControlPassthrough && ttl < 0 && originHeaders != nil {
  67. if val := originHeaders.Get(httpheaders.CacheControl); len(val) > 0 {
  68. rw.Header().Set(httpheaders.CacheControl, val)
  69. return
  70. }
  71. if val := originHeaders.Get(httpheaders.Expires); len(val) > 0 {
  72. if t, err := time.Parse(http.TimeFormat, val); err == nil {
  73. ttl = imath.Max(0, int(time.Until(t).Seconds()))
  74. }
  75. }
  76. }
  77. if ttl < 0 {
  78. ttl = config.TTL
  79. }
  80. if ttl > 0 {
  81. rw.Header().Set(httpheaders.CacheControl, fmt.Sprintf("max-age=%d, public", ttl))
  82. } else {
  83. rw.Header().Set(httpheaders.CacheControl, "no-cache")
  84. }
  85. }
  86. func setLastModified(rw http.ResponseWriter, originHeaders http.Header) {
  87. if config.LastModifiedEnabled {
  88. if val := originHeaders.Get(httpheaders.LastModified); len(val) != 0 {
  89. rw.Header().Set(httpheaders.LastModified, val)
  90. }
  91. }
  92. }
  93. func setVary(rw http.ResponseWriter) {
  94. if len(headerVaryValue) > 0 {
  95. rw.Header().Set(httpheaders.Vary, headerVaryValue)
  96. }
  97. }
  98. func setCanonical(rw http.ResponseWriter, originURL string) {
  99. if config.SetCanonicalHeader {
  100. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  101. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  102. rw.Header().Set("Link", linkHeader)
  103. }
  104. }
  105. }
  106. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData imagedata.ImageData) {
  107. var contentDisposition string
  108. if len(po.Filename) > 0 {
  109. contentDisposition = resultData.Format().ContentDisposition(po.Filename, po.ReturnAttachment)
  110. } else {
  111. contentDisposition = resultData.Format().ContentDispositionFromURL(originURL, po.ReturnAttachment)
  112. }
  113. rw.Header().Set("Content-Type", resultData.Format().Mime())
  114. rw.Header().Set("Content-Disposition", contentDisposition)
  115. setCacheControl(rw, po.Expires, originData.Headers())
  116. setLastModified(rw, originData.Headers())
  117. setVary(rw)
  118. setCanonical(rw, originURL)
  119. if config.EnableDebugHeaders {
  120. originSize, err := originData.Size()
  121. if err != nil {
  122. checkErr(r.Context(), "image_data_size", err)
  123. }
  124. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(originSize))
  125. rw.Header().Set("X-Origin-Width", resultData.Headers().Get("X-Origin-Width"))
  126. rw.Header().Set("X-Origin-Height", resultData.Headers().Get("X-Origin-Height"))
  127. rw.Header().Set("X-Result-Width", resultData.Headers().Get("X-Result-Width"))
  128. rw.Header().Set("X-Result-Height", resultData.Headers().Get("X-Result-Height"))
  129. }
  130. rw.Header().Set("Content-Security-Policy", "script-src 'none'")
  131. resultSize, err := resultData.Size()
  132. if err != nil {
  133. checkErr(r.Context(), "image_data_size", err)
  134. }
  135. rw.Header().Set("Content-Length", strconv.Itoa(resultSize))
  136. rw.WriteHeader(statusCode)
  137. _, err = io.Copy(rw, resultData.Reader())
  138. var ierr *ierrors.Error
  139. if err != nil {
  140. ierr = newResponseWriteError(err)
  141. if config.ReportIOErrors {
  142. sendErr(r.Context(), "IO", ierr)
  143. errorreport.Report(ierr, r)
  144. }
  145. }
  146. router.LogResponse(
  147. reqID, r, statusCode, ierr,
  148. log.Fields{
  149. "image_url": originURL,
  150. "processing_options": po,
  151. },
  152. )
  153. }
  154. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders http.Header) {
  155. setCacheControl(rw, po.Expires, originHeaders)
  156. setVary(rw)
  157. rw.WriteHeader(304)
  158. router.LogResponse(
  159. reqID, r, 304, nil,
  160. log.Fields{
  161. "image_url": originURL,
  162. "processing_options": po,
  163. },
  164. )
  165. }
  166. func sendErr(ctx context.Context, errType string, err error) {
  167. send := true
  168. if ierr, ok := err.(*ierrors.Error); ok {
  169. switch ierr.StatusCode() {
  170. case http.StatusServiceUnavailable:
  171. errType = "timeout"
  172. case 499:
  173. // Don't need to send a "request cancelled" error
  174. send = false
  175. }
  176. }
  177. if send {
  178. metrics.SendError(ctx, errType, err)
  179. }
  180. }
  181. func sendErrAndPanic(ctx context.Context, errType string, err error) {
  182. sendErr(ctx, errType, err)
  183. panic(err)
  184. }
  185. func checkErr(ctx context.Context, errType string, err error) {
  186. if err == nil {
  187. return
  188. }
  189. sendErrAndPanic(ctx, errType, err)
  190. }
  191. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  192. stats.IncRequestsInProgress()
  193. defer stats.DecRequestsInProgress()
  194. ctx := r.Context()
  195. path := r.RequestURI
  196. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  197. path = path[:queryStart]
  198. }
  199. if len(config.PathPrefix) > 0 {
  200. path = strings.TrimPrefix(path, config.PathPrefix)
  201. }
  202. path = strings.TrimPrefix(path, "/")
  203. signature := ""
  204. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  205. signature = path[:signatureEnd]
  206. path = path[signatureEnd:]
  207. } else {
  208. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  209. http.StatusNotFound, "Invalid path: %s", path),
  210. )
  211. }
  212. path = fixPath(path)
  213. if err := security.VerifySignature(signature, path); err != nil {
  214. sendErrAndPanic(ctx, "security", err)
  215. }
  216. po, imageURL, err := options.ParsePath(path, r.Header)
  217. checkErr(ctx, "path_parsing", err)
  218. var imageOrigin any
  219. if u, uerr := url.Parse(imageURL); uerr == nil {
  220. imageOrigin = u.Scheme + "://" + u.Host
  221. }
  222. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  223. errorreport.SetMetadata(r, "Source Image Origin", imageOrigin)
  224. errorreport.SetMetadata(r, "Processing Options", po)
  225. metricsMeta := metrics.Meta{
  226. metrics.MetaSourceImageURL: imageURL,
  227. metrics.MetaSourceImageOrigin: imageOrigin,
  228. metrics.MetaProcessingOptions: po.Diff().Flatten(),
  229. }
  230. metrics.SetMetadata(ctx, metricsMeta)
  231. err = security.VerifySourceURL(imageURL)
  232. checkErr(ctx, "security", err)
  233. if po.Raw {
  234. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  235. return
  236. }
  237. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  238. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  239. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  240. http.StatusUnprocessableEntity,
  241. "Resulting image format is not supported: %s", po.Format,
  242. ))
  243. }
  244. imgRequestHeader := make(http.Header)
  245. var etagHandler etag.Handler
  246. if config.ETagEnabled {
  247. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  248. if etagHandler.SetActualProcessingOptions(po) {
  249. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  250. imgRequestHeader.Set("If-None-Match", imgEtag)
  251. }
  252. }
  253. }
  254. if config.LastModifiedEnabled {
  255. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  256. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  257. }
  258. }
  259. if queueSem != nil {
  260. acquired := queueSem.TryAcquire(1)
  261. if !acquired {
  262. panic(newTooManyRequestsError())
  263. }
  264. defer queueSem.Release(1)
  265. }
  266. // The heavy part starts here, so we need to restrict worker number
  267. func() {
  268. defer metrics.StartQueueSegment(ctx)()
  269. err = processingSem.Acquire(ctx, 1)
  270. if err != nil {
  271. // We don't actually need to check timeout here,
  272. // but it's an easy way to check if this is an actual timeout
  273. // or the request was canceled
  274. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  275. // We should never reach this line as err could be only ctx.Err()
  276. // and we've already checked for it. But beter safe than sorry
  277. sendErrAndPanic(ctx, "queue", err)
  278. }
  279. }()
  280. defer processingSem.Release(1)
  281. stats.IncImagesInProgress()
  282. defer stats.DecImagesInProgress()
  283. statusCode := http.StatusOK
  284. originData, err := func() (imagedata.ImageData, error) {
  285. defer metrics.StartDownloadingSegment(ctx, metrics.Meta{
  286. metrics.MetaSourceImageURL: metricsMeta[metrics.MetaSourceImageURL],
  287. metrics.MetaSourceImageOrigin: metricsMeta[metrics.MetaSourceImageOrigin],
  288. })()
  289. downloadOpts := imagedata.DownloadOptions{
  290. Header: imgRequestHeader,
  291. CookieJar: nil,
  292. }
  293. if config.CookiePassthrough {
  294. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  295. checkErr(ctx, "download", err)
  296. }
  297. return imagedata.Download(ctx, imageURL, "source image", downloadOpts, po.SecurityOptions)
  298. }()
  299. var nmErr imagefetcher.NotModifiedError
  300. switch {
  301. case err == nil:
  302. defer originData.Close()
  303. case errors.As(err, &nmErr):
  304. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  305. rw.Header().Set(httpheaders.Etag, etagHandler.GenerateExpectedETag())
  306. }
  307. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers())
  308. return
  309. default:
  310. // This may be a request timeout error or a request cancelled error.
  311. // Check it before moving further
  312. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  313. ierr := ierrors.Wrap(err, 0)
  314. if config.ReportDownloadingErrors {
  315. ierr = ierrors.Wrap(ierr, 0, ierrors.WithShouldReport(true))
  316. }
  317. sendErr(ctx, "download", ierr)
  318. if imagedata.FallbackImage == nil {
  319. panic(ierr)
  320. }
  321. // We didn't panic, so the error is not reported.
  322. // Report it now
  323. if ierr.ShouldReport() {
  324. errorreport.Report(ierr, r)
  325. }
  326. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  327. if config.FallbackImageHTTPCode > 0 {
  328. statusCode = config.FallbackImageHTTPCode
  329. } else {
  330. statusCode = ierr.StatusCode()
  331. }
  332. originData = imagedata.FallbackImage
  333. }
  334. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  335. if config.ETagEnabled && statusCode == http.StatusOK {
  336. imgDataMatch, terr := etagHandler.SetActualImageData(originData)
  337. if terr == nil {
  338. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  339. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  340. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers())
  341. return
  342. }
  343. }
  344. }
  345. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  346. // Skip processing svg with unknown or the same destination imageType
  347. // if it's not forced by AlwaysRasterizeSvg option
  348. // Also skip processing if the format is in SkipProcessingFormats
  349. shouldSkipProcessing := (originData.Format() == po.Format || po.Format == imagetype.Unknown) &&
  350. (slices.Contains(po.SkipProcessingFormats, originData.Format()) ||
  351. originData.Format() == imagetype.SVG && !config.AlwaysRasterizeSvg)
  352. if shouldSkipProcessing {
  353. if originData.Format() == imagetype.SVG && config.SanitizeSvg {
  354. sanitized, svgErr := svg.Sanitize(originData)
  355. checkErr(ctx, "svg_processing", svgErr)
  356. defer sanitized.Close()
  357. respondWithImage(reqID, r, rw, statusCode, sanitized, po, imageURL, originData)
  358. return
  359. }
  360. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  361. return
  362. }
  363. if !vips.SupportsLoad(originData.Format()) {
  364. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  365. http.StatusUnprocessableEntity,
  366. "Source image format is not supported: %s", originData.Format(),
  367. ))
  368. }
  369. // At this point we can't allow requested format to be SVG as we can't save SVGs
  370. if po.Format == imagetype.SVG {
  371. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  372. http.StatusUnprocessableEntity,
  373. "Resulting image format is not supported: svg",
  374. ))
  375. }
  376. resultData, err := func() (imagedata.ImageData, error) {
  377. defer metrics.StartProcessingSegment(ctx, metrics.Meta{
  378. metrics.MetaProcessingOptions: metricsMeta[metrics.MetaProcessingOptions],
  379. })()
  380. return processing.ProcessImage(ctx, originData, po)
  381. }()
  382. checkErr(ctx, "processing", err)
  383. defer resultData.Close()
  384. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  385. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  386. }