processing_handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  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/httpheaders"
  19. "github.com/imgproxy/imgproxy/v3/ierrors"
  20. "github.com/imgproxy/imgproxy/v3/imagedata"
  21. "github.com/imgproxy/imgproxy/v3/imagefetcher"
  22. "github.com/imgproxy/imgproxy/v3/imagetype"
  23. "github.com/imgproxy/imgproxy/v3/metrics"
  24. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  25. "github.com/imgproxy/imgproxy/v3/options"
  26. "github.com/imgproxy/imgproxy/v3/processing"
  27. "github.com/imgproxy/imgproxy/v3/router"
  28. "github.com/imgproxy/imgproxy/v3/security"
  29. "github.com/imgproxy/imgproxy/v3/svg"
  30. "github.com/imgproxy/imgproxy/v3/vips"
  31. )
  32. var (
  33. queueSem *semaphore.Weighted
  34. processingSem *semaphore.Weighted
  35. headerVaryValue string
  36. )
  37. func initProcessingHandler() {
  38. if config.RequestsQueueSize > 0 {
  39. queueSem = semaphore.NewWeighted(int64(config.RequestsQueueSize + config.Workers))
  40. }
  41. processingSem = semaphore.NewWeighted(int64(config.Workers))
  42. vary := make([]string, 0)
  43. if config.AutoWebp ||
  44. config.EnforceWebp ||
  45. config.AutoAvif ||
  46. config.EnforceAvif ||
  47. config.AutoJxl ||
  48. config.EnforceJxl {
  49. vary = append(vary, "Accept")
  50. }
  51. if config.EnableClientHints {
  52. vary = append(vary, "Sec-CH-DPR", "DPR", "Sec-CH-Width", "Width")
  53. }
  54. headerVaryValue = strings.Join(vary, ", ")
  55. }
  56. func setCacheControl(rw http.ResponseWriter, force *time.Time, originHeaders http.Header) {
  57. ttl := -1
  58. if _, ok := originHeaders["Fallback-Image"]; ok && config.FallbackImageTTL > 0 {
  59. ttl = config.FallbackImageTTL
  60. }
  61. if force != nil && (ttl < 0 || force.Before(time.Now().Add(time.Duration(ttl)*time.Second))) {
  62. ttl = min(config.TTL, max(0, int(time.Until(*force).Seconds())))
  63. }
  64. if config.CacheControlPassthrough && ttl < 0 && originHeaders != nil {
  65. if val := originHeaders.Get(httpheaders.CacheControl); len(val) > 0 {
  66. rw.Header().Set(httpheaders.CacheControl, val)
  67. return
  68. }
  69. if val := originHeaders.Get(httpheaders.Expires); len(val) > 0 {
  70. if t, err := time.Parse(http.TimeFormat, val); err == nil {
  71. ttl = max(0, int(time.Until(t).Seconds()))
  72. }
  73. }
  74. }
  75. if ttl < 0 {
  76. ttl = config.TTL
  77. }
  78. if ttl > 0 {
  79. rw.Header().Set(httpheaders.CacheControl, fmt.Sprintf("max-age=%d, public", ttl))
  80. } else {
  81. rw.Header().Set(httpheaders.CacheControl, "no-cache")
  82. }
  83. }
  84. func setLastModified(rw http.ResponseWriter, originHeaders http.Header) {
  85. if config.LastModifiedEnabled {
  86. if val := originHeaders.Get(httpheaders.LastModified); len(val) != 0 {
  87. rw.Header().Set(httpheaders.LastModified, val)
  88. }
  89. }
  90. }
  91. func setVary(rw http.ResponseWriter) {
  92. if len(headerVaryValue) > 0 {
  93. rw.Header().Set(httpheaders.Vary, headerVaryValue)
  94. }
  95. }
  96. func setCanonical(rw http.ResponseWriter, originURL string) {
  97. if config.SetCanonicalHeader {
  98. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  99. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  100. rw.Header().Set("Link", linkHeader)
  101. }
  102. }
  103. }
  104. func writeOriginContentLengthDebugHeader(ctx context.Context, rw http.ResponseWriter, originData imagedata.ImageData) {
  105. if !config.EnableDebugHeaders {
  106. return
  107. }
  108. size, err := originData.Size()
  109. if err != nil {
  110. checkErr(ctx, "image_data_size", err)
  111. }
  112. rw.Header().Set(httpheaders.XOriginContentLength, strconv.Itoa(size))
  113. }
  114. func writeDebugHeaders(rw http.ResponseWriter, result *processing.Result) {
  115. if !config.EnableDebugHeaders || result == nil {
  116. return
  117. }
  118. rw.Header().Set(httpheaders.XOriginWidth, strconv.Itoa(result.OriginWidth))
  119. rw.Header().Set(httpheaders.XOriginHeight, strconv.Itoa(result.OriginHeight))
  120. rw.Header().Set(httpheaders.XResultWidth, strconv.Itoa(result.ResultWidth))
  121. rw.Header().Set(httpheaders.XResultHeight, strconv.Itoa(result.ResultHeight))
  122. }
  123. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData imagedata.ImageData, originHeaders http.Header) {
  124. // We read the size of the image data here, so we can set Content-Length header.
  125. // This indireclty ensures that the image data is fully read from the source, no
  126. // errors happened.
  127. resultSize, err := resultData.Size()
  128. if err != nil {
  129. checkErr(r.Context(), "image_data_size", err)
  130. }
  131. contentDisposition := httpheaders.ContentDispositionValue(
  132. originURL,
  133. po.Filename,
  134. resultData.Format().Ext(),
  135. "",
  136. po.ReturnAttachment,
  137. )
  138. rw.Header().Set(httpheaders.ContentType, resultData.Format().Mime())
  139. rw.Header().Set(httpheaders.ContentDisposition, contentDisposition)
  140. setCacheControl(rw, po.Expires, originHeaders)
  141. setLastModified(rw, originHeaders)
  142. setVary(rw)
  143. setCanonical(rw, originURL)
  144. rw.Header().Set(httpheaders.ContentSecurityPolicy, "script-src 'none'")
  145. rw.Header().Set(httpheaders.ContentLength, strconv.Itoa(resultSize))
  146. rw.WriteHeader(statusCode)
  147. _, err = io.Copy(rw, resultData.Reader())
  148. var ierr *ierrors.Error
  149. if err != nil {
  150. ierr = newResponseWriteError(err)
  151. if config.ReportIOErrors {
  152. sendErr(r.Context(), "IO", ierr)
  153. errorreport.Report(ierr, r)
  154. }
  155. }
  156. router.LogResponse(
  157. reqID, r, statusCode, ierr,
  158. log.Fields{
  159. "image_url": originURL,
  160. "processing_options": po,
  161. },
  162. )
  163. }
  164. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders http.Header) {
  165. setCacheControl(rw, po.Expires, originHeaders)
  166. setVary(rw)
  167. rw.WriteHeader(304)
  168. router.LogResponse(
  169. reqID, r, 304, nil,
  170. log.Fields{
  171. "image_url": originURL,
  172. "processing_options": po,
  173. },
  174. )
  175. }
  176. func sendErr(ctx context.Context, errType string, err error) {
  177. send := true
  178. if ierr, ok := err.(*ierrors.Error); ok {
  179. switch ierr.StatusCode() {
  180. case http.StatusServiceUnavailable:
  181. errType = "timeout"
  182. case 499:
  183. // Don't need to send a "request cancelled" error
  184. send = false
  185. }
  186. }
  187. if send {
  188. metrics.SendError(ctx, errType, err)
  189. }
  190. }
  191. func sendErrAndPanic(ctx context.Context, errType string, err error) {
  192. sendErr(ctx, errType, err)
  193. panic(err)
  194. }
  195. func checkErr(ctx context.Context, errType string, err error) {
  196. if err == nil {
  197. return
  198. }
  199. sendErrAndPanic(ctx, errType, err)
  200. }
  201. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  202. stats.IncRequestsInProgress()
  203. defer stats.DecRequestsInProgress()
  204. ctx := r.Context()
  205. path := r.RequestURI
  206. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  207. path = path[:queryStart]
  208. }
  209. if len(config.PathPrefix) > 0 {
  210. path = strings.TrimPrefix(path, config.PathPrefix)
  211. }
  212. path = strings.TrimPrefix(path, "/")
  213. signature := ""
  214. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  215. signature = path[:signatureEnd]
  216. path = path[signatureEnd:]
  217. } else {
  218. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  219. http.StatusNotFound, "Invalid path: %s", path),
  220. )
  221. }
  222. path = fixPath(path)
  223. if err := security.VerifySignature(signature, path); err != nil {
  224. sendErrAndPanic(ctx, "security", err)
  225. }
  226. po, imageURL, err := options.ParsePath(path, r.Header)
  227. checkErr(ctx, "path_parsing", err)
  228. var imageOrigin any
  229. if u, uerr := url.Parse(imageURL); uerr == nil {
  230. imageOrigin = u.Scheme + "://" + u.Host
  231. }
  232. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  233. errorreport.SetMetadata(r, "Source Image Origin", imageOrigin)
  234. errorreport.SetMetadata(r, "Processing Options", po)
  235. metricsMeta := metrics.Meta{
  236. metrics.MetaSourceImageURL: imageURL,
  237. metrics.MetaSourceImageOrigin: imageOrigin,
  238. metrics.MetaProcessingOptions: po.Diff().Flatten(),
  239. }
  240. metrics.SetMetadata(ctx, metricsMeta)
  241. err = security.VerifySourceURL(imageURL)
  242. checkErr(ctx, "security", err)
  243. if po.Raw {
  244. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  245. return
  246. }
  247. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  248. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  249. sendErrAndPanic(ctx, "path_parsing", newInvalidURLErrorf(
  250. http.StatusUnprocessableEntity,
  251. "Resulting image format is not supported: %s", po.Format,
  252. ))
  253. }
  254. imgRequestHeader := make(http.Header)
  255. var etagHandler etag.Handler
  256. if config.ETagEnabled {
  257. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  258. if etagHandler.SetActualProcessingOptions(po) {
  259. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  260. imgRequestHeader.Set("If-None-Match", imgEtag)
  261. }
  262. }
  263. }
  264. if config.LastModifiedEnabled {
  265. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  266. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  267. }
  268. }
  269. if queueSem != nil {
  270. acquired := queueSem.TryAcquire(1)
  271. if !acquired {
  272. panic(newTooManyRequestsError())
  273. }
  274. defer queueSem.Release(1)
  275. }
  276. // The heavy part starts here, so we need to restrict worker number
  277. func() {
  278. defer metrics.StartQueueSegment(ctx)()
  279. err = processingSem.Acquire(ctx, 1)
  280. if err != nil {
  281. // We don't actually need to check timeout here,
  282. // but it's an easy way to check if this is an actual timeout
  283. // or the request was canceled
  284. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  285. // We should never reach this line as err could be only ctx.Err()
  286. // and we've already checked for it. But beter safe than sorry
  287. sendErrAndPanic(ctx, "queue", err)
  288. }
  289. }()
  290. defer processingSem.Release(1)
  291. stats.IncImagesInProgress()
  292. defer stats.DecImagesInProgress()
  293. statusCode := http.StatusOK
  294. originData, originHeaders, err := func() (imagedata.ImageData, http.Header, error) {
  295. downloadFinished := metrics.StartDownloadingSegment(ctx, metrics.Meta{
  296. metrics.MetaSourceImageURL: metricsMeta[metrics.MetaSourceImageURL],
  297. metrics.MetaSourceImageOrigin: metricsMeta[metrics.MetaSourceImageOrigin],
  298. })
  299. downloadOpts := imagedata.DownloadOptions{
  300. Header: imgRequestHeader,
  301. CookieJar: nil,
  302. MaxSrcFileSize: po.SecurityOptions.MaxSrcFileSize,
  303. DownloadFinished: downloadFinished,
  304. }
  305. if config.CookiePassthrough {
  306. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  307. checkErr(ctx, "download", err)
  308. }
  309. return imagedata.DownloadAsync(ctx, imageURL, "source image", downloadOpts)
  310. }()
  311. var nmErr imagefetcher.NotModifiedError
  312. switch {
  313. case err == nil:
  314. defer originData.Close()
  315. case errors.As(err, &nmErr):
  316. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  317. rw.Header().Set(httpheaders.Etag, etagHandler.GenerateExpectedETag())
  318. }
  319. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers())
  320. return
  321. default:
  322. // This may be a request timeout error or a request cancelled error.
  323. // Check it before moving further
  324. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  325. ierr := ierrors.Wrap(err, 0)
  326. if config.ReportDownloadingErrors {
  327. ierr = ierrors.Wrap(ierr, 0, ierrors.WithShouldReport(true))
  328. }
  329. sendErr(ctx, "download", ierr)
  330. if imagedata.FallbackImage == nil {
  331. panic(ierr)
  332. }
  333. // We didn't panic, so the error is not reported.
  334. // Report it now
  335. if ierr.ShouldReport() {
  336. errorreport.Report(ierr, r)
  337. }
  338. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  339. if config.FallbackImageHTTPCode > 0 {
  340. statusCode = config.FallbackImageHTTPCode
  341. } else {
  342. statusCode = ierr.StatusCode()
  343. }
  344. originData = imagedata.FallbackImage
  345. originHeaders = imagedata.FallbackImageHeaders.Clone()
  346. if config.FallbackImageTTL > 0 {
  347. originHeaders.Set("Fallback-Image", "1")
  348. }
  349. }
  350. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  351. if config.ETagEnabled && statusCode == http.StatusOK {
  352. imgDataMatch, terr := etagHandler.SetActualImageData(originData, originHeaders)
  353. if terr == nil {
  354. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  355. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  356. respondWithNotModified(reqID, r, rw, po, imageURL, originHeaders)
  357. return
  358. }
  359. }
  360. }
  361. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  362. if !vips.SupportsLoad(originData.Format()) {
  363. sendErrAndPanic(ctx, "processing", newInvalidURLErrorf(
  364. http.StatusUnprocessableEntity,
  365. "Source image format is not supported: %s", originData.Format(),
  366. ))
  367. }
  368. result, err := func() (*processing.Result, error) {
  369. defer metrics.StartProcessingSegment(ctx, metrics.Meta{
  370. metrics.MetaProcessingOptions: metricsMeta[metrics.MetaProcessingOptions],
  371. })()
  372. return processing.ProcessImage(ctx, originData, po)
  373. }()
  374. // Let's close resulting image data only if it differs from the source image data
  375. if result != nil && result.OutData != nil && result.OutData != originData {
  376. defer result.OutData.Close()
  377. }
  378. if err != nil {
  379. // svg_processing is an exception. We use As here because Is does not work with types.
  380. var e svg.SanitizeError
  381. if errors.As(err, &e) {
  382. checkErr(ctx, "svg_processing", e)
  383. }
  384. // First, check if the processing error wasn't caused by an image data error
  385. checkErr(ctx, "download", originData.Error())
  386. // If it wasn't, than it was a processing error
  387. sendErrAndPanic(ctx, "processing", err)
  388. }
  389. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  390. writeDebugHeaders(rw, result)
  391. writeOriginContentLengthDebugHeader(ctx, rw, originData)
  392. respondWithImage(reqID, r, rw, statusCode, result.OutData, po, imageURL, originData, originHeaders)
  393. }