processing_handler.go 14 KB

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