processing_handler.go 13 KB

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