1
0

processing_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/imgproxy/imgproxy/v3/config"
  11. "github.com/imgproxy/imgproxy/v3/cookies"
  12. "github.com/imgproxy/imgproxy/v3/errorreport"
  13. "github.com/imgproxy/imgproxy/v3/etag"
  14. "github.com/imgproxy/imgproxy/v3/ierrors"
  15. "github.com/imgproxy/imgproxy/v3/imagedata"
  16. "github.com/imgproxy/imgproxy/v3/imagetype"
  17. "github.com/imgproxy/imgproxy/v3/imath"
  18. "github.com/imgproxy/imgproxy/v3/metrics"
  19. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  20. "github.com/imgproxy/imgproxy/v3/options"
  21. "github.com/imgproxy/imgproxy/v3/processing"
  22. "github.com/imgproxy/imgproxy/v3/router"
  23. "github.com/imgproxy/imgproxy/v3/security"
  24. "github.com/imgproxy/imgproxy/v3/semaphore"
  25. "github.com/imgproxy/imgproxy/v3/svg"
  26. "github.com/imgproxy/imgproxy/v3/vips"
  27. )
  28. var (
  29. queueSem *semaphore.Semaphore
  30. processingSem *semaphore.Semaphore
  31. headerVaryValue string
  32. )
  33. func initProcessingHandler() {
  34. if config.RequestsQueueSize > 0 {
  35. queueSem = semaphore.New(config.RequestsQueueSize + config.Workers)
  36. }
  37. processingSem = semaphore.New(config.Workers)
  38. vary := make([]string, 0)
  39. if config.EnableWebpDetection || config.EnforceWebp || config.EnableAvifDetection || config.EnforceAvif {
  40. vary = append(vary, "Accept")
  41. }
  42. if config.EnableClientHints {
  43. vary = append(vary, "Sec-CH-DPR", "DPR", "Sec-CH-Width", "Width")
  44. }
  45. headerVaryValue = strings.Join(vary, ", ")
  46. }
  47. func setCacheControl(rw http.ResponseWriter, force *time.Time, originHeaders map[string]string) {
  48. ttl := -1
  49. if _, ok := originHeaders["Fallback-Image"]; ok && config.FallbackImageTTL > 0 {
  50. ttl = config.FallbackImageTTL
  51. }
  52. if force != nil && (ttl < 0 || force.Before(time.Now().Add(time.Duration(ttl)*time.Second))) {
  53. ttl = imath.Min(config.TTL, imath.Max(0, int(time.Until(*force).Seconds())))
  54. }
  55. if config.CacheControlPassthrough && ttl < 0 && originHeaders != nil {
  56. if val, ok := originHeaders["Cache-Control"]; ok && len(val) > 0 {
  57. rw.Header().Set("Cache-Control", val)
  58. return
  59. }
  60. if val, ok := originHeaders["Expires"]; ok && len(val) > 0 {
  61. if t, err := time.Parse(http.TimeFormat, val); err == nil {
  62. ttl = imath.Max(0, int(time.Until(t).Seconds()))
  63. }
  64. }
  65. }
  66. if ttl < 0 {
  67. ttl = config.TTL
  68. }
  69. if ttl > 0 {
  70. rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", ttl))
  71. } else {
  72. rw.Header().Set("Cache-Control", "no-cache")
  73. }
  74. }
  75. func setLastModified(rw http.ResponseWriter, originHeaders map[string]string) {
  76. if config.LastModifiedEnabled {
  77. if val, ok := originHeaders["Last-Modified"]; ok && len(val) != 0 {
  78. rw.Header().Set("Last-Modified", val)
  79. }
  80. }
  81. }
  82. func setVary(rw http.ResponseWriter) {
  83. if len(headerVaryValue) > 0 {
  84. rw.Header().Set("Vary", headerVaryValue)
  85. }
  86. }
  87. func setCanonical(rw http.ResponseWriter, originURL string) {
  88. if config.SetCanonicalHeader {
  89. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  90. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  91. rw.Header().Set("Link", linkHeader)
  92. }
  93. }
  94. }
  95. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData *imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData *imagedata.ImageData) {
  96. var contentDisposition string
  97. if len(po.Filename) > 0 {
  98. contentDisposition = resultData.Type.ContentDisposition(po.Filename, po.ReturnAttachment)
  99. } else {
  100. contentDisposition = resultData.Type.ContentDispositionFromURL(originURL, po.ReturnAttachment)
  101. }
  102. rw.Header().Set("Content-Type", resultData.Type.Mime())
  103. rw.Header().Set("Content-Disposition", contentDisposition)
  104. setCacheControl(rw, po.Expires, originData.Headers)
  105. setLastModified(rw, originData.Headers)
  106. setVary(rw)
  107. setCanonical(rw, originURL)
  108. if config.EnableDebugHeaders {
  109. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(len(originData.Data)))
  110. rw.Header().Set("X-Origin-Width", resultData.Headers["X-Origin-Width"])
  111. rw.Header().Set("X-Origin-Height", resultData.Headers["X-Origin-Height"])
  112. rw.Header().Set("X-Result-Width", resultData.Headers["X-Result-Width"])
  113. rw.Header().Set("X-Result-Height", resultData.Headers["X-Result-Height"])
  114. }
  115. rw.Header().Set("Content-Security-Policy", "script-src 'none'")
  116. rw.Header().Set("Content-Length", strconv.Itoa(len(resultData.Data)))
  117. rw.WriteHeader(statusCode)
  118. rw.Write(resultData.Data)
  119. router.LogResponse(
  120. reqID, r, statusCode, nil,
  121. log.Fields{
  122. "image_url": originURL,
  123. "processing_options": po,
  124. },
  125. )
  126. }
  127. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders map[string]string) {
  128. setCacheControl(rw, po.Expires, originHeaders)
  129. setVary(rw)
  130. rw.WriteHeader(304)
  131. router.LogResponse(
  132. reqID, r, 304, nil,
  133. log.Fields{
  134. "image_url": originURL,
  135. "processing_options": po,
  136. },
  137. )
  138. }
  139. func sendErr(ctx context.Context, errType string, err error) {
  140. send := true
  141. if ierr, ok := err.(*ierrors.Error); ok {
  142. switch ierr.StatusCode {
  143. case http.StatusServiceUnavailable:
  144. errType = "timeout"
  145. case 499:
  146. // Don't need to send a "request cancelled" error
  147. send = false
  148. }
  149. }
  150. if send {
  151. metrics.SendError(ctx, errType, err)
  152. }
  153. }
  154. func sendErrAndPanic(ctx context.Context, errType string, err error) {
  155. sendErr(ctx, errType, err)
  156. panic(err)
  157. }
  158. func checkErr(ctx context.Context, errType string, err error) {
  159. if err == nil {
  160. return
  161. }
  162. sendErrAndPanic(ctx, errType, err)
  163. }
  164. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  165. stats.IncRequestsInProgress()
  166. defer stats.DecRequestsInProgress()
  167. ctx := r.Context()
  168. if queueSem != nil {
  169. token, acquired := queueSem.TryAcquire()
  170. if !acquired {
  171. panic(ierrors.New(429, "Too many requests", "Too many requests"))
  172. }
  173. defer token.Release()
  174. }
  175. path := r.RequestURI
  176. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  177. path = path[:queryStart]
  178. }
  179. if len(config.PathPrefix) > 0 {
  180. path = strings.TrimPrefix(path, config.PathPrefix)
  181. }
  182. path = strings.TrimPrefix(path, "/")
  183. signature := ""
  184. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  185. signature = path[:signatureEnd]
  186. path = path[signatureEnd:]
  187. } else {
  188. sendErrAndPanic(ctx, "path_parsing", ierrors.New(
  189. 404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL",
  190. ))
  191. }
  192. path = fixPath(path)
  193. if err := security.VerifySignature(signature, path); err != nil {
  194. sendErrAndPanic(ctx, "security", ierrors.New(403, err.Error(), "Forbidden"))
  195. }
  196. po, imageURL, err := options.ParsePath(path, r.Header)
  197. checkErr(ctx, "path_parsing", err)
  198. errorreport.SetMetadata(r, "Source Image URL", imageURL)
  199. errorreport.SetMetadata(r, "Processing Options", po)
  200. err = security.VerifySourceURL(imageURL)
  201. checkErr(ctx, "security", err)
  202. if po.Raw {
  203. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  204. return
  205. }
  206. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  207. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  208. sendErrAndPanic(ctx, "path_parsing", ierrors.New(
  209. 422,
  210. fmt.Sprintf("Resulting image format is not supported: %s", po.Format),
  211. "Invalid URL",
  212. ))
  213. }
  214. imgRequestHeader := make(http.Header)
  215. var etagHandler etag.Handler
  216. if config.ETagEnabled {
  217. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  218. if etagHandler.SetActualProcessingOptions(po) {
  219. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  220. imgRequestHeader.Set("If-None-Match", imgEtag)
  221. }
  222. }
  223. }
  224. if config.LastModifiedEnabled {
  225. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  226. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  227. }
  228. }
  229. // The heavy part start here, so we need to restrict worker number
  230. var processingSemToken *semaphore.Token
  231. func() {
  232. defer metrics.StartQueueSegment(ctx)()
  233. var acquired bool
  234. processingSemToken, acquired = processingSem.Acquire(ctx)
  235. if !acquired {
  236. // We don't actually need to check timeout here,
  237. // but it's an easy way to check if this is an actual timeout
  238. // or the request was canceled
  239. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  240. }
  241. }()
  242. defer processingSemToken.Release()
  243. stats.IncImagesInProgress()
  244. defer stats.DecImagesInProgress()
  245. statusCode := http.StatusOK
  246. originData, err := func() (*imagedata.ImageData, error) {
  247. defer metrics.StartDownloadingSegment(ctx)()
  248. downloadOpts := imagedata.DownloadOptions{
  249. Header: imgRequestHeader,
  250. CookieJar: nil,
  251. }
  252. if config.CookiePassthrough {
  253. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  254. checkErr(ctx, "download", err)
  255. }
  256. return imagedata.Download(ctx, imageURL, "source image", downloadOpts, po.SecurityOptions)
  257. }()
  258. if err == nil {
  259. defer originData.Close()
  260. } else if nmErr, ok := err.(*imagedata.ErrorNotModified); ok {
  261. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  262. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  263. }
  264. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers)
  265. return
  266. } else {
  267. // This may be a request timeout error or a request cancelled error.
  268. // Check it before moving further
  269. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  270. ierr := ierrors.Wrap(err, 0)
  271. ierr.Unexpected = ierr.Unexpected || config.ReportDownloadingErrors
  272. sendErr(ctx, "download", ierr)
  273. if imagedata.FallbackImage == nil {
  274. panic(ierr)
  275. }
  276. // We didn't panic, so the error is not reported.
  277. // Report it now
  278. if ierr.Unexpected {
  279. errorreport.Report(ierr, r)
  280. }
  281. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  282. if config.FallbackImageHTTPCode > 0 {
  283. statusCode = config.FallbackImageHTTPCode
  284. } else {
  285. statusCode = ierr.StatusCode
  286. }
  287. originData = imagedata.FallbackImage
  288. }
  289. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  290. if config.ETagEnabled && statusCode == http.StatusOK {
  291. imgDataMatch := etagHandler.SetActualImageData(originData)
  292. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  293. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  294. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers)
  295. return
  296. }
  297. }
  298. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  299. if originData.Type == po.Format || po.Format == imagetype.Unknown {
  300. // Don't process SVG
  301. if originData.Type == imagetype.SVG {
  302. if config.SanitizeSvg {
  303. sanitized, svgErr := svg.Sanitize(originData)
  304. checkErr(ctx, "svg_processing", svgErr)
  305. // Since we'll replace origin data, it's better to close it to return
  306. // it's buffer to the pool
  307. originData.Close()
  308. originData = sanitized
  309. }
  310. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  311. return
  312. }
  313. if len(po.SkipProcessingFormats) > 0 {
  314. for _, f := range po.SkipProcessingFormats {
  315. if f == originData.Type {
  316. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  317. return
  318. }
  319. }
  320. }
  321. }
  322. if !vips.SupportsLoad(originData.Type) {
  323. sendErrAndPanic(ctx, "processing", ierrors.New(
  324. 422,
  325. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  326. "Invalid URL",
  327. ))
  328. }
  329. // At this point we can't allow requested format to be SVG as we can't save SVGs
  330. if po.Format == imagetype.SVG {
  331. sendErrAndPanic(ctx, "processing", ierrors.New(
  332. 422, "Resulting image format is not supported: svg", "Invalid URL",
  333. ))
  334. }
  335. // We're going to rasterize SVG. Since librsvg lacks the support of some SVG
  336. // features, we're going to replace them to minimize rendering error
  337. if originData.Type == imagetype.SVG && config.SvgFixUnsupported {
  338. fixed, changed, svgErr := svg.FixUnsupported(originData)
  339. checkErr(ctx, "svg_processing", svgErr)
  340. if changed {
  341. // Since we'll replace origin data, it's better to close it to return
  342. // it's buffer to the pool
  343. originData.Close()
  344. originData = fixed
  345. }
  346. }
  347. resultData, err := func() (*imagedata.ImageData, error) {
  348. defer metrics.StartProcessingSegment(ctx)()
  349. return processing.ProcessImage(ctx, originData, po)
  350. }()
  351. checkErr(ctx, "processing", err)
  352. defer resultData.Close()
  353. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  354. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  355. }