processing_handler.go 12 KB

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