processing_handler.go 13 KB

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