processing_handler.go 13 KB

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