processing_handler.go 11 KB

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