processing_handler.go 10 KB

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