processing_handler.go 13 KB

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