processing_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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/security"
  28. "github.com/imgproxy/imgproxy/v3/server"
  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(rw http.ResponseWriter, originData imagedata.ImageData) error {
  104. if !config.EnableDebugHeaders {
  105. return nil
  106. }
  107. size, err := originData.Size()
  108. if err != nil {
  109. return ierrors.Wrap(
  110. err, 0,
  111. ierrors.WithCategory(categoryImageDataSize),
  112. ierrors.WithShouldReport(true),
  113. )
  114. }
  115. rw.Header().Set(httpheaders.XOriginContentLength, strconv.Itoa(size))
  116. return nil
  117. }
  118. func writeDebugHeaders(rw http.ResponseWriter, result *processing.Result) {
  119. if !config.EnableDebugHeaders || result == nil {
  120. return
  121. }
  122. rw.Header().Set(httpheaders.XOriginWidth, strconv.Itoa(result.OriginWidth))
  123. rw.Header().Set(httpheaders.XOriginHeight, strconv.Itoa(result.OriginHeight))
  124. rw.Header().Set(httpheaders.XResultWidth, strconv.Itoa(result.ResultWidth))
  125. rw.Header().Set(httpheaders.XResultHeight, strconv.Itoa(result.ResultHeight))
  126. }
  127. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData imagedata.ImageData, po *options.ProcessingOptions, originURL string, originHeaders http.Header) error {
  128. // We read the size of the image data here, so we can set Content-Length header.
  129. // This indireclty ensures that the image data is fully read from the source, no
  130. // errors happened.
  131. resultSize, err := resultData.Size()
  132. if err != nil {
  133. return ierrors.Wrap(
  134. err, 0,
  135. ierrors.WithCategory(categoryImageDataSize),
  136. ierrors.WithShouldReport(true),
  137. )
  138. }
  139. contentDisposition := httpheaders.ContentDispositionValue(
  140. originURL,
  141. po.Filename,
  142. resultData.Format().Ext(),
  143. "",
  144. po.ReturnAttachment,
  145. )
  146. rw.Header().Set(httpheaders.ContentType, resultData.Format().Mime())
  147. rw.Header().Set(httpheaders.ContentDisposition, contentDisposition)
  148. setCacheControl(rw, po.Expires, originHeaders)
  149. setLastModified(rw, originHeaders)
  150. setVary(rw)
  151. setCanonical(rw, originURL)
  152. rw.Header().Set(httpheaders.ContentSecurityPolicy, "script-src 'none'")
  153. rw.Header().Set(httpheaders.ContentLength, strconv.Itoa(resultSize))
  154. rw.WriteHeader(statusCode)
  155. _, err = io.Copy(rw, resultData.Reader())
  156. var ierr *ierrors.Error
  157. if err != nil {
  158. ierr = newResponseWriteError(err)
  159. if config.ReportIOErrors {
  160. sendErr(r.Context(), categoryIO, ierr)
  161. errorreport.Report(ierr, r)
  162. }
  163. }
  164. server.LogResponse(
  165. reqID, r, statusCode, ierr,
  166. log.Fields{
  167. "image_url": originURL,
  168. "processing_options": po,
  169. },
  170. )
  171. return nil
  172. }
  173. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders http.Header) {
  174. setCacheControl(rw, po.Expires, originHeaders)
  175. setVary(rw)
  176. rw.WriteHeader(304)
  177. server.LogResponse(
  178. reqID, r, 304, nil,
  179. log.Fields{
  180. "image_url": originURL,
  181. "processing_options": po,
  182. },
  183. )
  184. }
  185. func sendErr(ctx context.Context, errType string, err error) {
  186. send := true
  187. if ierr, ok := err.(*ierrors.Error); ok {
  188. switch ierr.StatusCode() {
  189. case http.StatusServiceUnavailable:
  190. errType = "timeout"
  191. case 499:
  192. // Don't need to send a "request cancelled" error
  193. send = false
  194. }
  195. }
  196. if send {
  197. metrics.SendError(ctx, errType, err)
  198. }
  199. }
  200. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) error {
  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. return ierrors.Wrap(
  218. newInvalidURLErrorf(http.StatusNotFound, "Invalid path: %s", path), 0,
  219. ierrors.WithCategory(categoryPathParsing),
  220. )
  221. }
  222. path = fixPath(path)
  223. if err := security.VerifySignature(signature, path); err != nil {
  224. return ierrors.Wrap(err, 0, ierrors.WithCategory(categorySecurity))
  225. }
  226. po, imageURL, err := options.ParsePath(path, r.Header)
  227. if err != nil {
  228. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryPathParsing))
  229. }
  230. var imageOrigin any
  231. if u, uerr := url.Parse(imageURL); uerr == nil {
  232. imageOrigin = u.Scheme + "://" + u.Host
  233. }
  234. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  235. errorreport.SetMetadata(r, "Source Image Origin", imageOrigin)
  236. errorreport.SetMetadata(r, "Processing Options", po)
  237. metricsMeta := metrics.Meta{
  238. metrics.MetaSourceImageURL: imageURL,
  239. metrics.MetaSourceImageOrigin: imageOrigin,
  240. metrics.MetaProcessingOptions: po.Diff().Flatten(),
  241. }
  242. metrics.SetMetadata(ctx, metricsMeta)
  243. err = security.VerifySourceURL(imageURL)
  244. if err != nil {
  245. return ierrors.Wrap(err, 0, ierrors.WithCategory(categorySecurity))
  246. }
  247. if po.Raw {
  248. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  249. return nil
  250. }
  251. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  252. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  253. return ierrors.Wrap(newInvalidURLErrorf(
  254. http.StatusUnprocessableEntity,
  255. "Resulting image format is not supported: %s", po.Format,
  256. ), 0, ierrors.WithCategory(categoryPathParsing))
  257. }
  258. imgRequestHeader := make(http.Header)
  259. var etagHandler etag.Handler
  260. if config.ETagEnabled {
  261. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  262. if etagHandler.SetActualProcessingOptions(po) {
  263. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  264. imgRequestHeader.Set("If-None-Match", imgEtag)
  265. }
  266. }
  267. }
  268. if config.LastModifiedEnabled {
  269. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  270. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  271. }
  272. }
  273. if queueSem != nil {
  274. acquired := queueSem.TryAcquire(1)
  275. if !acquired {
  276. panic(newTooManyRequestsError())
  277. }
  278. defer queueSem.Release(1)
  279. }
  280. // The heavy part starts here, so we need to restrict worker number
  281. err = processingSem.Acquire(ctx, 1)
  282. if err != nil {
  283. metrics.StartQueueSegment(ctx)()
  284. // We don't actually need to check timeout here,
  285. // but it's an easy way to check if this is an actual timeout
  286. // or the request was canceled
  287. if terr := server.CheckTimeout(ctx); terr != nil {
  288. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  289. }
  290. if err != nil {
  291. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryQueue))
  292. }
  293. }
  294. defer processingSem.Release(1)
  295. metrics.StartQueueSegment(ctx)()
  296. stats.IncImagesInProgress()
  297. defer stats.DecImagesInProgress()
  298. statusCode := http.StatusOK
  299. originData, originHeaders, err := func() (imagedata.ImageData, http.Header, error) {
  300. downloadFinished := metrics.StartDownloadingSegment(ctx, metrics.Meta{
  301. metrics.MetaSourceImageURL: metricsMeta[metrics.MetaSourceImageURL],
  302. metrics.MetaSourceImageOrigin: metricsMeta[metrics.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)
  335. if config.ReportDownloadingErrors {
  336. ierr = ierrors.Wrap(ierr, 0, ierrors.WithShouldReport(true))
  337. }
  338. if ierr != nil {
  339. metrics.SendError(ctx, categoryDownload, err)
  340. }
  341. if imagedata.FallbackImage == nil {
  342. return ierr
  343. }
  344. // Fallback image was present, however, we did not report it
  345. if ierr.ShouldReport() {
  346. errorreport.Report(ierr, r)
  347. }
  348. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  349. if config.FallbackImageHTTPCode > 0 {
  350. statusCode = config.FallbackImageHTTPCode
  351. } else {
  352. statusCode = ierr.StatusCode()
  353. }
  354. originData = imagedata.FallbackImage
  355. originHeaders = imagedata.FallbackImageHeaders.Clone()
  356. if config.FallbackImageTTL > 0 {
  357. originHeaders.Set("Fallback-Image", "1")
  358. }
  359. }
  360. if terr := server.CheckTimeout(ctx); terr != nil {
  361. return ierrors.Wrap(terr, 0, ierrors.WithCategory(categoryTimeout))
  362. }
  363. if config.ETagEnabled && statusCode == http.StatusOK {
  364. imgDataMatch, terr := etagHandler.SetActualImageData(originData, originHeaders)
  365. if terr == nil {
  366. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  367. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  368. respondWithNotModified(reqID, r, rw, po, imageURL, originHeaders)
  369. return nil
  370. }
  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 metrics.StartProcessingSegment(ctx, metrics.Meta{
  384. metrics.MetaProcessingOptions: metricsMeta[metrics.MetaProcessingOptions],
  385. })()
  386. return processing.ProcessImage(ctx, originData, po)
  387. }()
  388. // Let's close resulting image data only if it differs from the source image data
  389. if result != nil && result.OutData != nil && result.OutData != originData {
  390. defer result.OutData.Close()
  391. }
  392. if err != nil {
  393. // First, check if the processing error wasn't caused by an image data error
  394. if originData.Error() != nil {
  395. return ierrors.Wrap(originData.Error(), 0, ierrors.WithCategory(categoryDownload))
  396. }
  397. // If it wasn't, than it was a processing error
  398. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryProcessing))
  399. }
  400. if err := server.CheckTimeout(ctx); err != nil {
  401. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryTimeout))
  402. }
  403. writeDebugHeaders(rw, result)
  404. if err := writeOriginContentLengthDebugHeader(rw, originData); err != nil {
  405. return err
  406. }
  407. respondWithImage(reqID, r, rw, statusCode, result.OutData, po, imageURL, originHeaders)
  408. return nil
  409. }