processing_handler.go 13 KB

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