processing_handler.go 13 KB

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