processing_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. "github.com/imgproxy/imgproxy/v3/config"
  12. "github.com/imgproxy/imgproxy/v3/cookies"
  13. "github.com/imgproxy/imgproxy/v3/errorreport"
  14. "github.com/imgproxy/imgproxy/v3/etag"
  15. "github.com/imgproxy/imgproxy/v3/ierrors"
  16. "github.com/imgproxy/imgproxy/v3/imagedata"
  17. "github.com/imgproxy/imgproxy/v3/imagetype"
  18. "github.com/imgproxy/imgproxy/v3/imath"
  19. "github.com/imgproxy/imgproxy/v3/metrics"
  20. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  21. "github.com/imgproxy/imgproxy/v3/options"
  22. "github.com/imgproxy/imgproxy/v3/processing"
  23. "github.com/imgproxy/imgproxy/v3/router"
  24. "github.com/imgproxy/imgproxy/v3/security"
  25. "github.com/imgproxy/imgproxy/v3/semaphore"
  26. "github.com/imgproxy/imgproxy/v3/svg"
  27. "github.com/imgproxy/imgproxy/v3/vips"
  28. )
  29. var (
  30. queueSem *semaphore.Semaphore
  31. processingSem *semaphore.Semaphore
  32. headerVaryValue string
  33. )
  34. func initProcessingHandler() {
  35. if config.RequestsQueueSize > 0 {
  36. queueSem = semaphore.New(config.RequestsQueueSize + config.Workers)
  37. }
  38. processingSem = semaphore.New(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. rw.Write(resultData.Data)
  120. router.LogResponse(
  121. reqID, r, statusCode, nil,
  122. log.Fields{
  123. "image_url": originURL,
  124. "processing_options": po,
  125. },
  126. )
  127. }
  128. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders map[string]string) {
  129. setCacheControl(rw, po.Expires, originHeaders)
  130. setVary(rw)
  131. rw.WriteHeader(304)
  132. router.LogResponse(
  133. reqID, r, 304, nil,
  134. log.Fields{
  135. "image_url": originURL,
  136. "processing_options": po,
  137. },
  138. )
  139. }
  140. func sendErr(ctx context.Context, errType string, err error) {
  141. send := true
  142. if ierr, ok := err.(*ierrors.Error); ok {
  143. switch ierr.StatusCode {
  144. case http.StatusServiceUnavailable:
  145. errType = "timeout"
  146. case 499:
  147. // Don't need to send a "request cancelled" error
  148. send = false
  149. }
  150. }
  151. if send {
  152. metrics.SendError(ctx, errType, err)
  153. }
  154. }
  155. func sendErrAndPanic(ctx context.Context, errType string, err error) {
  156. sendErr(ctx, errType, err)
  157. panic(err)
  158. }
  159. func checkErr(ctx context.Context, errType string, err error) {
  160. if err == nil {
  161. return
  162. }
  163. sendErrAndPanic(ctx, errType, err)
  164. }
  165. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  166. stats.IncRequestsInProgress()
  167. defer stats.DecRequestsInProgress()
  168. ctx := r.Context()
  169. if queueSem != nil {
  170. token, acquired := queueSem.TryAcquire()
  171. if !acquired {
  172. panic(ierrors.New(429, "Too many requests", "Too many requests"))
  173. }
  174. defer token.Release()
  175. }
  176. path := r.RequestURI
  177. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  178. path = path[:queryStart]
  179. }
  180. if len(config.PathPrefix) > 0 {
  181. path = strings.TrimPrefix(path, config.PathPrefix)
  182. }
  183. path = strings.TrimPrefix(path, "/")
  184. signature := ""
  185. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  186. signature = path[:signatureEnd]
  187. path = path[signatureEnd:]
  188. } else {
  189. sendErrAndPanic(ctx, "path_parsing", ierrors.New(
  190. 404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL",
  191. ))
  192. }
  193. path = fixPath(path)
  194. if err := security.VerifySignature(signature, path); err != nil {
  195. sendErrAndPanic(ctx, "security", ierrors.New(403, err.Error(), "Forbidden"))
  196. }
  197. po, imageURL, err := options.ParsePath(path, r.Header)
  198. checkErr(ctx, "path_parsing", err)
  199. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  200. errorreport.SetMetadata(r, "Processing Options", po)
  201. err = security.VerifySourceURL(imageURL)
  202. checkErr(ctx, "security", err)
  203. if po.Raw {
  204. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  205. return
  206. }
  207. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  208. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  209. sendErrAndPanic(ctx, "path_parsing", ierrors.New(
  210. 422,
  211. fmt.Sprintf("Resulting image format is not supported: %s", po.Format),
  212. "Invalid URL",
  213. ))
  214. }
  215. imgRequestHeader := make(http.Header)
  216. var etagHandler etag.Handler
  217. if config.ETagEnabled {
  218. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  219. if etagHandler.SetActualProcessingOptions(po) {
  220. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  221. imgRequestHeader.Set("If-None-Match", imgEtag)
  222. }
  223. }
  224. }
  225. if config.LastModifiedEnabled {
  226. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  227. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  228. }
  229. }
  230. // The heavy part start here, so we need to restrict worker number
  231. var processingSemToken *semaphore.Token
  232. func() {
  233. defer metrics.StartQueueSegment(ctx)()
  234. var acquired bool
  235. processingSemToken, acquired = processingSem.Acquire(ctx)
  236. if !acquired {
  237. // We don't actually need to check timeout here,
  238. // but it's an easy way to check if this is an actual timeout
  239. // or the request was canceled
  240. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  241. }
  242. }()
  243. defer processingSemToken.Release()
  244. stats.IncImagesInProgress()
  245. defer stats.DecImagesInProgress()
  246. statusCode := http.StatusOK
  247. originData, err := func() (*imagedata.ImageData, error) {
  248. defer metrics.StartDownloadingSegment(ctx)()
  249. downloadOpts := imagedata.DownloadOptions{
  250. Header: imgRequestHeader,
  251. CookieJar: nil,
  252. }
  253. if config.CookiePassthrough {
  254. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  255. checkErr(ctx, "download", err)
  256. }
  257. return imagedata.Download(ctx, imageURL, "source image", downloadOpts, po.SecurityOptions)
  258. }()
  259. if err == nil {
  260. defer originData.Close()
  261. } else if nmErr, ok := err.(*imagedata.ErrorNotModified); ok {
  262. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  263. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  264. }
  265. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers)
  266. return
  267. } else {
  268. // This may be a request timeout error or a request cancelled error.
  269. // Check it before moving further
  270. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  271. ierr := ierrors.Wrap(err, 0)
  272. ierr.Unexpected = ierr.Unexpected || config.ReportDownloadingErrors
  273. sendErr(ctx, "download", ierr)
  274. if imagedata.FallbackImage == nil {
  275. panic(ierr)
  276. }
  277. // We didn't panic, so the error is not reported.
  278. // Report it now
  279. if ierr.Unexpected {
  280. errorreport.Report(ierr, r)
  281. }
  282. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  283. if config.FallbackImageHTTPCode > 0 {
  284. statusCode = config.FallbackImageHTTPCode
  285. } else {
  286. statusCode = ierr.StatusCode
  287. }
  288. originData = imagedata.FallbackImage
  289. }
  290. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  291. if config.ETagEnabled && statusCode == http.StatusOK {
  292. imgDataMatch := etagHandler.SetActualImageData(originData)
  293. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  294. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  295. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers)
  296. return
  297. }
  298. }
  299. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  300. // Skip processing svg with unknown or the same destination imageType
  301. // if it's not forced by AlwaysRasterizeSvg option
  302. // Also skip processing if the format is in SkipProcessingFormats
  303. shouldSkipProcessing := (originData.Type == po.Format || po.Format == imagetype.Unknown) &&
  304. (slices.Contains(po.SkipProcessingFormats, originData.Type) ||
  305. originData.Type == imagetype.SVG && !config.AlwaysRasterizeSvg)
  306. if shouldSkipProcessing {
  307. if originData.Type == imagetype.SVG && config.SanitizeSvg {
  308. sanitized, svgErr := svg.Sanitize(originData)
  309. checkErr(ctx, "svg_processing", svgErr)
  310. // Since we'll replace origin data, it's better to close it to return
  311. // it's buffer to the pool
  312. originData.Close()
  313. originData = sanitized
  314. }
  315. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  316. return
  317. }
  318. if !vips.SupportsLoad(originData.Type) {
  319. sendErrAndPanic(ctx, "processing", ierrors.New(
  320. 422,
  321. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  322. "Invalid URL",
  323. ))
  324. }
  325. // At this point we can't allow requested format to be SVG as we can't save SVGs
  326. if po.Format == imagetype.SVG {
  327. sendErrAndPanic(ctx, "processing", ierrors.New(
  328. 422, "Resulting image format is not supported: svg", "Invalid URL",
  329. ))
  330. }
  331. // We're going to rasterize SVG. Since librsvg lacks the support of some SVG
  332. // features, we're going to replace them to minimize rendering error
  333. if originData.Type == imagetype.SVG && config.SvgFixUnsupported {
  334. fixed, changed, svgErr := svg.FixUnsupported(originData)
  335. checkErr(ctx, "svg_processing", svgErr)
  336. if changed {
  337. // Since we'll replace origin data, it's better to close it to return
  338. // it's buffer to the pool
  339. originData.Close()
  340. originData = fixed
  341. }
  342. }
  343. resultData, err := func() (*imagedata.ImageData, error) {
  344. defer metrics.StartProcessingSegment(ctx)()
  345. return processing.ProcessImage(ctx, originData, po)
  346. }()
  347. checkErr(ctx, "processing", err)
  348. defer resultData.Close()
  349. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  350. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  351. }