1
0

processing_handler.go 13 KB

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