1
0

processing_handler.go 13 KB

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