processing_handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/url"
  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/handlers/stream"
  18. "github.com/imgproxy/imgproxy/v3/headerwriter"
  19. "github.com/imgproxy/imgproxy/v3/httpheaders"
  20. "github.com/imgproxy/imgproxy/v3/ierrors"
  21. "github.com/imgproxy/imgproxy/v3/imagedata"
  22. "github.com/imgproxy/imgproxy/v3/imagefetcher"
  23. "github.com/imgproxy/imgproxy/v3/imagetype"
  24. "github.com/imgproxy/imgproxy/v3/monitoring"
  25. "github.com/imgproxy/imgproxy/v3/monitoring/stats"
  26. "github.com/imgproxy/imgproxy/v3/options"
  27. "github.com/imgproxy/imgproxy/v3/processing"
  28. "github.com/imgproxy/imgproxy/v3/security"
  29. "github.com/imgproxy/imgproxy/v3/server"
  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(rw http.ResponseWriter, originData imagedata.ImageData) error {
  105. if !config.EnableDebugHeaders {
  106. return nil
  107. }
  108. size, err := originData.Size()
  109. if err != nil {
  110. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryImageDataSize))
  111. }
  112. rw.Header().Set(httpheaders.XOriginContentLength, strconv.Itoa(size))
  113. return nil
  114. }
  115. func writeDebugHeaders(rw http.ResponseWriter, result *processing.Result) {
  116. if !config.EnableDebugHeaders || result == nil {
  117. return
  118. }
  119. rw.Header().Set(httpheaders.XOriginWidth, strconv.Itoa(result.OriginWidth))
  120. rw.Header().Set(httpheaders.XOriginHeight, strconv.Itoa(result.OriginHeight))
  121. rw.Header().Set(httpheaders.XResultWidth, strconv.Itoa(result.ResultWidth))
  122. rw.Header().Set(httpheaders.XResultHeight, strconv.Itoa(result.ResultHeight))
  123. }
  124. 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) error {
  125. // We read the size of the image data here, so we can set Content-Length header.
  126. // This indireclty ensures that the image data is fully read from the source, no
  127. // errors happened.
  128. resultSize, err := resultData.Size()
  129. if err != nil {
  130. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryImageDataSize))
  131. }
  132. contentDisposition := httpheaders.ContentDispositionValue(
  133. originURL,
  134. po.Filename,
  135. resultData.Format().Ext(),
  136. "",
  137. po.ReturnAttachment,
  138. )
  139. rw.Header().Set(httpheaders.ContentType, resultData.Format().Mime())
  140. rw.Header().Set(httpheaders.ContentDisposition, contentDisposition)
  141. setCacheControl(rw, po.Expires, originHeaders)
  142. setLastModified(rw, originHeaders)
  143. setVary(rw)
  144. setCanonical(rw, originURL)
  145. rw.Header().Set(httpheaders.ContentSecurityPolicy, "script-src 'none'")
  146. rw.Header().Set(httpheaders.ContentLength, strconv.Itoa(resultSize))
  147. rw.WriteHeader(statusCode)
  148. _, err = io.Copy(rw, resultData.Reader())
  149. var ierr *ierrors.Error
  150. if err != nil {
  151. ierr = newResponseWriteError(err)
  152. if config.ReportIOErrors {
  153. return ierrors.Wrap(ierr, 0, ierrors.WithCategory(categoryIO), ierrors.WithShouldReport(true))
  154. }
  155. }
  156. server.LogResponse(
  157. reqID, r, statusCode, ierr,
  158. log.Fields{
  159. "image_url": originURL,
  160. "processing_options": po,
  161. },
  162. )
  163. return nil
  164. }
  165. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders http.Header) {
  166. setCacheControl(rw, po.Expires, originHeaders)
  167. setVary(rw)
  168. rw.WriteHeader(304)
  169. server.LogResponse(
  170. reqID, r, 304, nil,
  171. log.Fields{
  172. "image_url": originURL,
  173. "processing_options": po,
  174. },
  175. )
  176. }
  177. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) error {
  178. stats.IncRequestsInProgress()
  179. defer stats.DecRequestsInProgress()
  180. ctx := r.Context()
  181. path := r.RequestURI
  182. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  183. path = path[:queryStart]
  184. }
  185. if len(config.PathPrefix) > 0 {
  186. path = strings.TrimPrefix(path, config.PathPrefix)
  187. }
  188. path = strings.TrimPrefix(path, "/")
  189. signature := ""
  190. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  191. signature = path[:signatureEnd]
  192. path = path[signatureEnd:]
  193. } else {
  194. return ierrors.Wrap(
  195. newInvalidURLErrorf(http.StatusNotFound, "Invalid path: %s", path), 0,
  196. ierrors.WithCategory(categoryPathParsing),
  197. )
  198. }
  199. path = fixPath(path)
  200. if err := security.VerifySignature(signature, path); err != nil {
  201. return ierrors.Wrap(err, 0, ierrors.WithCategory(categorySecurity))
  202. }
  203. po, imageURL, err := options.ParsePath(path, r.Header)
  204. if err != nil {
  205. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryPathParsing))
  206. }
  207. var imageOrigin any
  208. if u, uerr := url.Parse(imageURL); uerr == nil {
  209. imageOrigin = u.Scheme + "://" + u.Host
  210. }
  211. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  212. errorreport.SetMetadata(r, "Source Image Origin", imageOrigin)
  213. errorreport.SetMetadata(r, "Processing Options", po)
  214. monitoringMeta := monitoring.Meta{
  215. monitoring.MetaSourceImageURL: imageURL,
  216. monitoring.MetaSourceImageOrigin: imageOrigin,
  217. monitoring.MetaProcessingOptions: po.Diff().Flatten(),
  218. }
  219. monitoring.SetMetadata(ctx, monitoringMeta)
  220. err = security.VerifySourceURL(imageURL)
  221. if err != nil {
  222. return ierrors.Wrap(err, 0, ierrors.WithCategory(categorySecurity))
  223. }
  224. if po.Raw {
  225. // NOTE: This is temporary, there would be no categoryConfig once we
  226. // finish with refactoring.
  227. // TODO: Move this up
  228. cfg, cerr := stream.NewDefaultConfig().LoadFromEnv()
  229. if cerr != nil {
  230. return ierrors.Wrap(cerr, 0, ierrors.WithCategory(categoryConfig))
  231. }
  232. hwc, cerr := headerwriter.NewDefaultConfig().LoadFromEnv()
  233. if cerr != nil {
  234. return ierrors.Wrap(cerr, 0, ierrors.WithCategory(categoryConfig))
  235. }
  236. hw, cerr := headerwriter.New(hwc)
  237. if cerr != nil {
  238. return ierrors.Wrap(cerr, 0, ierrors.WithCategory(categoryConfig))
  239. }
  240. handler, cerr := stream.New(cfg, hw, imagedata.Fetcher)
  241. if cerr != nil {
  242. return ierrors.Wrap(cerr, 0, ierrors.WithCategory(categoryConfig))
  243. }
  244. return handler.Execute(ctx, r, imageURL, reqID, po, rw)
  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. return ierrors.Wrap(newInvalidURLErrorf(
  249. http.StatusUnprocessableEntity,
  250. "Resulting image format is not supported: %s", po.Format,
  251. ), 0, ierrors.WithCategory(categoryPathParsing))
  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. err = func() error {
  277. defer monitoring.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. if terr := server.CheckTimeout(ctx); terr != nil {
  284. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  285. }
  286. // We should never reach this line as err could be only ctx.Err()
  287. // and we've already checked for it. But beter safe than sorry
  288. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryQueue))
  289. }
  290. return nil
  291. }()
  292. if err != nil {
  293. return err
  294. }
  295. defer processingSem.Release(1)
  296. stats.IncImagesInProgress()
  297. defer stats.DecImagesInProgress()
  298. statusCode := http.StatusOK
  299. originData, originHeaders, err := func() (imagedata.ImageData, http.Header, error) {
  300. downloadFinished := monitoring.StartDownloadingSegment(ctx, monitoringMeta.Filter(
  301. monitoring.MetaSourceImageURL,
  302. monitoring.MetaSourceImageOrigin,
  303. ))
  304. downloadOpts := imagedata.DownloadOptions{
  305. Header: imgRequestHeader,
  306. CookieJar: nil,
  307. MaxSrcFileSize: po.SecurityOptions.MaxSrcFileSize,
  308. DownloadFinished: downloadFinished,
  309. }
  310. if config.CookiePassthrough {
  311. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  312. if err != nil {
  313. return nil, nil, ierrors.Wrap(err, 0, ierrors.WithCategory(categoryDownload))
  314. }
  315. }
  316. return imagedata.DownloadAsync(ctx, imageURL, "source image", downloadOpts)
  317. }()
  318. var nmErr imagefetcher.NotModifiedError
  319. switch {
  320. case err == nil:
  321. defer originData.Close()
  322. case errors.As(err, &nmErr):
  323. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  324. rw.Header().Set(httpheaders.Etag, etagHandler.GenerateExpectedETag())
  325. }
  326. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers())
  327. return nil
  328. default:
  329. // This may be a request timeout error or a request cancelled error.
  330. // Check it before moving further
  331. if terr := server.CheckTimeout(ctx); terr != nil {
  332. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  333. }
  334. ierr := ierrors.Wrap(err, 0, ierrors.WithCategory(categoryDownload))
  335. if config.ReportDownloadingErrors {
  336. ierr = ierrors.Wrap(ierr, 0, ierrors.WithShouldReport(true))
  337. }
  338. if imagedata.FallbackImage == nil {
  339. return ierr
  340. }
  341. // Just send error
  342. monitoring.SendError(ctx, categoryDownload, ierr)
  343. // We didn't return, so we have to report error
  344. if ierr.ShouldReport() {
  345. errorreport.Report(ierr, r)
  346. }
  347. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  348. if config.FallbackImageHTTPCode > 0 {
  349. statusCode = config.FallbackImageHTTPCode
  350. } else {
  351. statusCode = ierr.StatusCode()
  352. }
  353. originData = imagedata.FallbackImage
  354. originHeaders = imagedata.FallbackImageHeaders.Clone()
  355. if config.FallbackImageTTL > 0 {
  356. originHeaders.Set("Fallback-Image", "1")
  357. }
  358. }
  359. if terr := server.CheckTimeout(ctx); terr != nil {
  360. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  361. }
  362. if config.ETagEnabled && statusCode == http.StatusOK {
  363. imgDataMatch, eerr := etagHandler.SetActualImageData(originData, originHeaders)
  364. if eerr != nil && config.ReportIOErrors {
  365. return ierrors.Wrap(eerr, 0, ierrors.WithCategory(categoryIO))
  366. }
  367. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  368. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  369. respondWithNotModified(reqID, r, rw, po, imageURL, originHeaders)
  370. return nil
  371. }
  372. }
  373. if terr := server.CheckTimeout(ctx); terr != nil {
  374. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  375. }
  376. if !vips.SupportsLoad(originData.Format()) {
  377. return ierrors.Wrap(newInvalidURLErrorf(
  378. http.StatusUnprocessableEntity,
  379. "Source image format is not supported: %s", originData.Format(),
  380. ), 0, ierrors.WithCategory(categoryProcessing))
  381. }
  382. result, err := func() (*processing.Result, error) {
  383. defer monitoring.StartProcessingSegment(ctx, monitoringMeta.Filter(monitoring.MetaProcessingOptions))()
  384. return processing.ProcessImage(ctx, originData, po)
  385. }()
  386. // Let's close resulting image data only if it differs from the source image data
  387. if result != nil && result.OutData != nil && result.OutData != originData {
  388. defer result.OutData.Close()
  389. }
  390. // First, check if the processing error wasn't caused by an image data error
  391. if derr := originData.Error(); derr != nil {
  392. return ierrors.Wrap(derr, 0, ierrors.WithCategory(categoryDownload))
  393. }
  394. // If it wasn't, than it was a processing error
  395. if err != nil {
  396. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryProcessing))
  397. }
  398. if terr := server.CheckTimeout(ctx); terr != nil {
  399. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  400. }
  401. writeDebugHeaders(rw, result)
  402. err = writeOriginContentLengthDebugHeader(rw, originData)
  403. if err != nil {
  404. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryImageDataSize))
  405. }
  406. err = respondWithImage(reqID, r, rw, statusCode, result.OutData, po, imageURL, originData, originHeaders)
  407. if err != nil {
  408. return err
  409. }
  410. return nil
  411. }