processing_handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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, "Processing Options", po)
  208. metricsMeta := metrics.Meta{
  209. metrics.MetaSourceImageURL: imageURL,
  210. metrics.MetaSourceImageOrigin: imageOrigin,
  211. metrics.MetaProcessingOptions: po.Diff().Flatten(),
  212. }
  213. metrics.SetMetadata(ctx, metricsMeta)
  214. err = security.VerifySourceURL(imageURL)
  215. checkErr(ctx, "security", err)
  216. if po.Raw {
  217. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  218. return
  219. }
  220. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  221. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  222. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  223. http.StatusUnprocessableEntity,
  224. "Resulting image format is not supported: %s", po.Format,
  225. ))
  226. }
  227. imgRequestHeader := make(http.Header)
  228. var etagHandler etag.Handler
  229. if config.ETagEnabled {
  230. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  231. if etagHandler.SetActualProcessingOptions(po) {
  232. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  233. imgRequestHeader.Set("If-None-Match", imgEtag)
  234. }
  235. }
  236. }
  237. if config.LastModifiedEnabled {
  238. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  239. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  240. }
  241. }
  242. if queueSem != nil {
  243. acquired := queueSem.TryAcquire(1)
  244. if !acquired {
  245. panic(newTooManyRequestsError())
  246. }
  247. defer queueSem.Release(1)
  248. }
  249. // The heavy part starts here, so we need to restrict worker number
  250. func() {
  251. defer metrics.StartQueueSegment(ctx)()
  252. err = processingSem.Acquire(ctx, 1)
  253. if err != nil {
  254. // We don't actually need to check timeout here,
  255. // but it's an easy way to check if this is an actual timeout
  256. // or the request was canceled
  257. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  258. // We should never reach this line as err could be only ctx.Err()
  259. // and we've already checked for it. But beter safe than sorry
  260. sendErrAndPanic(ctx, "queue", err)
  261. }
  262. }()
  263. defer processingSem.Release(1)
  264. stats.IncImagesInProgress()
  265. defer stats.DecImagesInProgress()
  266. statusCode := http.StatusOK
  267. originData, err := func() (*imagedata.ImageData, error) {
  268. defer metrics.StartDownloadingSegment(ctx, metrics.Meta{
  269. metrics.MetaSourceImageURL: metricsMeta[metrics.MetaSourceImageURL],
  270. metrics.MetaSourceImageOrigin: metricsMeta[metrics.MetaSourceImageOrigin],
  271. })()
  272. downloadOpts := imagedata.DownloadOptions{
  273. Header: imgRequestHeader,
  274. CookieJar: nil,
  275. }
  276. if config.CookiePassthrough {
  277. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  278. checkErr(ctx, "download", err)
  279. }
  280. return imagedata.Download(ctx, imageURL, "source image", downloadOpts, po.SecurityOptions)
  281. }()
  282. var nmErr imagedata.NotModifiedError
  283. switch {
  284. case err == nil:
  285. defer originData.Close()
  286. case errors.As(err, &nmErr):
  287. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  288. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  289. }
  290. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers())
  291. return
  292. default:
  293. // This may be a request timeout error or a request cancelled error.
  294. // Check it before moving further
  295. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  296. ierr := ierrors.Wrap(err, 0)
  297. if config.ReportDownloadingErrors {
  298. ierr = ierrors.Wrap(ierr, 0, ierrors.WithShouldReport(true))
  299. }
  300. sendErr(ctx, "download", ierr)
  301. if imagedata.FallbackImage == nil {
  302. panic(ierr)
  303. }
  304. // We didn't panic, so the error is not reported.
  305. // Report it now
  306. if ierr.ShouldReport() {
  307. errorreport.Report(ierr, r)
  308. }
  309. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  310. if config.FallbackImageHTTPCode > 0 {
  311. statusCode = config.FallbackImageHTTPCode
  312. } else {
  313. statusCode = ierr.StatusCode()
  314. }
  315. originData = imagedata.FallbackImage
  316. }
  317. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  318. if config.ETagEnabled && statusCode == http.StatusOK {
  319. imgDataMatch := etagHandler.SetActualImageData(originData)
  320. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  321. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  322. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers)
  323. return
  324. }
  325. }
  326. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  327. // Skip processing svg with unknown or the same destination imageType
  328. // if it's not forced by AlwaysRasterizeSvg option
  329. // Also skip processing if the format is in SkipProcessingFormats
  330. shouldSkipProcessing := (originData.Type == po.Format || po.Format == imagetype.Unknown) &&
  331. (slices.Contains(po.SkipProcessingFormats, originData.Type) ||
  332. originData.Type == imagetype.SVG && !config.AlwaysRasterizeSvg)
  333. if shouldSkipProcessing {
  334. if originData.Type == imagetype.SVG && config.SanitizeSvg {
  335. sanitized, svgErr := svg.Sanitize(originData)
  336. checkErr(ctx, "svg_processing", svgErr)
  337. defer sanitized.Close()
  338. respondWithImage(reqID, r, rw, statusCode, sanitized, po, imageURL, originData)
  339. return
  340. }
  341. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  342. return
  343. }
  344. if !vips.SupportsLoad(originData.Type) {
  345. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  346. http.StatusUnprocessableEntity,
  347. "Source image format is not supported: %s", originData.Type,
  348. ))
  349. }
  350. // At this point we can't allow requested format to be SVG as we can't save SVGs
  351. if po.Format == imagetype.SVG {
  352. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  353. http.StatusUnprocessableEntity,
  354. "Resulting image format is not supported: svg",
  355. ))
  356. }
  357. // We're going to rasterize SVG. Since librsvg lacks the support of some SVG
  358. // features, we're going to replace them to minimize rendering error
  359. if originData.Type == imagetype.SVG && config.SvgFixUnsupported {
  360. fixed, changed, svgErr := svg.FixUnsupported(originData)
  361. checkErr(ctx, "svg_processing", svgErr)
  362. if changed {
  363. // Since we'll replace origin data, it's better to close it to return
  364. // it's buffer to the pool
  365. originData.Close()
  366. originData = fixed
  367. }
  368. }
  369. resultData, err := func() (*imagedata.ImageData, error) {
  370. defer metrics.StartProcessingSegment(ctx, metrics.Meta{
  371. metrics.MetaProcessingOptions: metricsMeta[metrics.MetaProcessingOptions],
  372. })()
  373. return processing.ProcessImage(ctx, originData, po)
  374. }()
  375. checkErr(ctx, "processing", err)
  376. defer resultData.Close()
  377. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  378. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  379. }