processing_handler.go 11 KB

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