processing_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 writeOriginContentLengthDebugHeader(ctx context.Context, rw http.ResponseWriter, originData imagedata.ImageData) {
  107. if !config.EnableDebugHeaders {
  108. return
  109. }
  110. size, err := originData.Size()
  111. if err != nil {
  112. checkErr(ctx, "image_data_size", err)
  113. }
  114. rw.Header().Set(httpheaders.XOriginContentLength, strconv.Itoa(size))
  115. }
  116. func writeDebugHeaders(rw http.ResponseWriter, result *processing.Result) {
  117. if !config.EnableDebugHeaders || result == nil {
  118. return
  119. }
  120. rw.Header().Set(httpheaders.XOriginWidth, strconv.Itoa(result.OriginWidth))
  121. rw.Header().Set(httpheaders.XOriginHeight, strconv.Itoa(result.OriginHeight))
  122. rw.Header().Set(httpheaders.XResultWidth, strconv.Itoa(result.ResultWidth))
  123. rw.Header().Set(httpheaders.XResultHeight, strconv.Itoa(result.ResultHeight))
  124. }
  125. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData imagedata.ImageData, originHeaders http.Header) {
  126. var contentDisposition string
  127. if len(po.Filename) > 0 {
  128. contentDisposition = resultData.Format().ContentDisposition(po.Filename, po.ReturnAttachment)
  129. } else {
  130. contentDisposition = resultData.Format().ContentDispositionFromURL(originURL, po.ReturnAttachment)
  131. }
  132. rw.Header().Set(httpheaders.ContentType, resultData.Format().Mime())
  133. rw.Header().Set(httpheaders.ContentDisposition, contentDisposition)
  134. setCacheControl(rw, po.Expires, originHeaders)
  135. setLastModified(rw, originHeaders)
  136. setVary(rw)
  137. setCanonical(rw, originURL)
  138. rw.Header().Set(httpheaders.ContentSecurityPolicy, "script-src 'none'")
  139. resultSize, err := resultData.Size()
  140. if err != nil {
  141. checkErr(r.Context(), "image_data_size", err)
  142. }
  143. rw.Header().Set(httpheaders.ContentLength, strconv.Itoa(resultSize))
  144. rw.WriteHeader(statusCode)
  145. _, err = io.Copy(rw, resultData.Reader())
  146. var ierr *ierrors.Error
  147. if err != nil {
  148. ierr = newResponseWriteError(err)
  149. if config.ReportIOErrors {
  150. sendErr(r.Context(), "IO", ierr)
  151. errorreport.Report(ierr, r)
  152. }
  153. }
  154. router.LogResponse(
  155. reqID, r, statusCode, ierr,
  156. log.Fields{
  157. "image_url": originURL,
  158. "processing_options": po,
  159. },
  160. )
  161. }
  162. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders http.Header) {
  163. setCacheControl(rw, po.Expires, originHeaders)
  164. setVary(rw)
  165. rw.WriteHeader(304)
  166. router.LogResponse(
  167. reqID, r, 304, nil,
  168. log.Fields{
  169. "image_url": originURL,
  170. "processing_options": po,
  171. },
  172. )
  173. }
  174. func sendErr(ctx context.Context, errType string, err error) {
  175. send := true
  176. if ierr, ok := err.(*ierrors.Error); ok {
  177. switch ierr.StatusCode() {
  178. case http.StatusServiceUnavailable:
  179. errType = "timeout"
  180. case 499:
  181. // Don't need to send a "request cancelled" error
  182. send = false
  183. }
  184. }
  185. if send {
  186. metrics.SendError(ctx, errType, err)
  187. }
  188. }
  189. func sendErrAndPanic(ctx context.Context, errType string, err error) {
  190. sendErr(ctx, errType, err)
  191. panic(err)
  192. }
  193. func checkErr(ctx context.Context, errType string, err error) {
  194. if err == nil {
  195. return
  196. }
  197. sendErrAndPanic(ctx, errType, err)
  198. }
  199. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  200. stats.IncRequestsInProgress()
  201. defer stats.DecRequestsInProgress()
  202. ctx := r.Context()
  203. path := r.RequestURI
  204. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  205. path = path[:queryStart]
  206. }
  207. if len(config.PathPrefix) > 0 {
  208. path = strings.TrimPrefix(path, config.PathPrefix)
  209. }
  210. path = strings.TrimPrefix(path, "/")
  211. signature := ""
  212. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  213. signature = path[:signatureEnd]
  214. path = path[signatureEnd:]
  215. } else {
  216. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  217. http.StatusNotFound, "Invalid path: %s", path),
  218. )
  219. }
  220. path = fixPath(path)
  221. if err := security.VerifySignature(signature, path); err != nil {
  222. sendErrAndPanic(ctx, "security", err)
  223. }
  224. po, imageURL, err := options.ParsePath(path, r.Header)
  225. checkErr(ctx, "path_parsing", err)
  226. var imageOrigin any
  227. if u, uerr := url.Parse(imageURL); uerr == nil {
  228. imageOrigin = u.Scheme + "://" + u.Host
  229. }
  230. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  231. errorreport.SetMetadata(r, "Source Image Origin", imageOrigin)
  232. errorreport.SetMetadata(r, "Processing Options", po)
  233. metricsMeta := metrics.Meta{
  234. metrics.MetaSourceImageURL: imageURL,
  235. metrics.MetaSourceImageOrigin: imageOrigin,
  236. metrics.MetaProcessingOptions: po.Diff().Flatten(),
  237. }
  238. metrics.SetMetadata(ctx, metricsMeta)
  239. err = security.VerifySourceURL(imageURL)
  240. checkErr(ctx, "security", err)
  241. if po.Raw {
  242. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  243. return
  244. }
  245. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  246. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  247. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  248. http.StatusUnprocessableEntity,
  249. "Resulting image format is not supported: %s", po.Format,
  250. ))
  251. }
  252. imgRequestHeader := make(http.Header)
  253. var etagHandler etag.Handler
  254. if config.ETagEnabled {
  255. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  256. if etagHandler.SetActualProcessingOptions(po) {
  257. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  258. imgRequestHeader.Set("If-None-Match", imgEtag)
  259. }
  260. }
  261. }
  262. if config.LastModifiedEnabled {
  263. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  264. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  265. }
  266. }
  267. if queueSem != nil {
  268. acquired := queueSem.TryAcquire(1)
  269. if !acquired {
  270. panic(newTooManyRequestsError())
  271. }
  272. defer queueSem.Release(1)
  273. }
  274. // The heavy part starts here, so we need to restrict worker number
  275. func() {
  276. defer metrics.StartQueueSegment(ctx)()
  277. err = processingSem.Acquire(ctx, 1)
  278. if err != nil {
  279. // We don't actually need to check timeout here,
  280. // but it's an easy way to check if this is an actual timeout
  281. // or the request was canceled
  282. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  283. // We should never reach this line as err could be only ctx.Err()
  284. // and we've already checked for it. But beter safe than sorry
  285. sendErrAndPanic(ctx, "queue", err)
  286. }
  287. }()
  288. defer processingSem.Release(1)
  289. stats.IncImagesInProgress()
  290. defer stats.DecImagesInProgress()
  291. statusCode := http.StatusOK
  292. originData, originHeaders, err := func() (imagedata.ImageData, http.Header, error) {
  293. defer metrics.StartDownloadingSegment(ctx, metrics.Meta{
  294. metrics.MetaSourceImageURL: metricsMeta[metrics.MetaSourceImageURL],
  295. metrics.MetaSourceImageOrigin: metricsMeta[metrics.MetaSourceImageOrigin],
  296. })()
  297. downloadOpts := imagedata.DownloadOptions{
  298. Header: imgRequestHeader,
  299. CookieJar: nil,
  300. }
  301. if config.CookiePassthrough {
  302. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  303. checkErr(ctx, "download", err)
  304. }
  305. return imagedata.Download(ctx, imageURL, "source image", downloadOpts, po.SecurityOptions)
  306. }()
  307. var nmErr imagefetcher.NotModifiedError
  308. switch {
  309. case err == nil:
  310. defer originData.Close()
  311. case errors.As(err, &nmErr):
  312. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  313. rw.Header().Set(httpheaders.Etag, etagHandler.GenerateExpectedETag())
  314. }
  315. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers())
  316. return
  317. default:
  318. // This may be a request timeout error or a request cancelled error.
  319. // Check it before moving further
  320. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  321. ierr := ierrors.Wrap(err, 0)
  322. if config.ReportDownloadingErrors {
  323. ierr = ierrors.Wrap(ierr, 0, ierrors.WithShouldReport(true))
  324. }
  325. sendErr(ctx, "download", ierr)
  326. if imagedata.FallbackImage == nil {
  327. panic(ierr)
  328. }
  329. // We didn't panic, so the error is not reported.
  330. // Report it now
  331. if ierr.ShouldReport() {
  332. errorreport.Report(ierr, r)
  333. }
  334. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  335. if config.FallbackImageHTTPCode > 0 {
  336. statusCode = config.FallbackImageHTTPCode
  337. } else {
  338. statusCode = ierr.StatusCode()
  339. }
  340. originData = imagedata.FallbackImage
  341. originHeaders = imagedata.FallbackImageHeaders.Clone()
  342. if config.FallbackImageTTL > 0 {
  343. originHeaders.Set("Fallback-Image", "1")
  344. }
  345. }
  346. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  347. if config.ETagEnabled && statusCode == http.StatusOK {
  348. imgDataMatch, terr := etagHandler.SetActualImageData(originData, originHeaders)
  349. if terr == nil {
  350. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  351. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  352. respondWithNotModified(reqID, r, rw, po, imageURL, originHeaders)
  353. return
  354. }
  355. }
  356. }
  357. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  358. // Skip processing svg with unknown or the same destination imageType
  359. // if it's not forced by AlwaysRasterizeSvg option
  360. // Also skip processing if the format is in SkipProcessingFormats
  361. shouldSkipProcessing := (originData.Format() == po.Format || po.Format == imagetype.Unknown) &&
  362. (slices.Contains(po.SkipProcessingFormats, originData.Format()) ||
  363. originData.Format() == imagetype.SVG && !config.AlwaysRasterizeSvg)
  364. if shouldSkipProcessing {
  365. if originData.Format() == imagetype.SVG && config.SanitizeSvg {
  366. sanitized, svgErr := svg.Sanitize(originData)
  367. checkErr(ctx, "svg_processing", svgErr)
  368. defer sanitized.Close()
  369. writeOriginContentLengthDebugHeader(ctx, rw, originData)
  370. respondWithImage(reqID, r, rw, statusCode, sanitized, po, imageURL, originData, originHeaders)
  371. return
  372. }
  373. writeOriginContentLengthDebugHeader(ctx, rw, originData)
  374. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData, originHeaders)
  375. return
  376. }
  377. if !vips.SupportsLoad(originData.Format()) {
  378. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  379. http.StatusUnprocessableEntity,
  380. "Source image format is not supported: %s", originData.Format(),
  381. ))
  382. }
  383. // At this point we can't allow requested format to be SVG as we can't save SVGs
  384. if po.Format == imagetype.SVG {
  385. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  386. http.StatusUnprocessableEntity,
  387. "Resulting image format is not supported: svg",
  388. ))
  389. }
  390. result, err := func() (*processing.Result, error) {
  391. defer metrics.StartProcessingSegment(ctx, metrics.Meta{
  392. metrics.MetaProcessingOptions: metricsMeta[metrics.MetaProcessingOptions],
  393. })()
  394. return processing.ProcessImage(ctx, originData, po)
  395. }()
  396. checkErr(ctx, "processing", err)
  397. defer result.OutData.Close()
  398. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  399. writeDebugHeaders(rw, result)
  400. writeOriginContentLengthDebugHeader(ctx, rw, originData)
  401. respondWithImage(reqID, r, rw, statusCode, result.OutData, po, imageURL, originData, originHeaders)
  402. }