processing_options.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. package main
  2. /*
  3. #cgo LDFLAGS: -s -w
  4. #include "vips.h"
  5. */
  6. import "C"
  7. import (
  8. "context"
  9. "encoding/base64"
  10. "errors"
  11. "fmt"
  12. "net/http"
  13. "net/url"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. )
  18. type urlOptions map[string][]string
  19. type imageType int
  20. const (
  21. imageTypeUnknown = imageType(C.UNKNOWN)
  22. imageTypeJPEG = imageType(C.JPEG)
  23. imageTypePNG = imageType(C.PNG)
  24. imageTypeWEBP = imageType(C.WEBP)
  25. imageTypeGIF = imageType(C.GIF)
  26. imageTypeICO = imageType(C.ICO)
  27. imageTypeSVG = imageType(C.SVG)
  28. )
  29. type processingHeaders struct {
  30. Accept string
  31. Width string
  32. ViewportWidth string
  33. DPR string
  34. }
  35. var imageTypes = map[string]imageType{
  36. "jpeg": imageTypeJPEG,
  37. "jpg": imageTypeJPEG,
  38. "png": imageTypePNG,
  39. "webp": imageTypeWEBP,
  40. "gif": imageTypeGIF,
  41. "ico": imageTypeICO,
  42. "svg": imageTypeSVG,
  43. }
  44. type gravityType int
  45. const (
  46. gravityCenter gravityType = iota
  47. gravityNorth
  48. gravityEast
  49. gravitySouth
  50. gravityWest
  51. gravityNorthWest
  52. gravityNorthEast
  53. gravitySouthWest
  54. gravitySouthEast
  55. gravitySmart
  56. gravityFocusPoint
  57. )
  58. var gravityTypes = map[string]gravityType{
  59. "ce": gravityCenter,
  60. "no": gravityNorth,
  61. "ea": gravityEast,
  62. "so": gravitySouth,
  63. "we": gravityWest,
  64. "nowe": gravityNorthWest,
  65. "noea": gravityNorthEast,
  66. "sowe": gravitySouthWest,
  67. "soea": gravitySouthEast,
  68. "sm": gravitySmart,
  69. "fp": gravityFocusPoint,
  70. }
  71. type gravityOptions struct {
  72. Type gravityType
  73. X, Y float64
  74. }
  75. type resizeType int
  76. const (
  77. resizeFit resizeType = iota
  78. resizeFill
  79. resizeCrop
  80. )
  81. var resizeTypes = map[string]resizeType{
  82. "fit": resizeFit,
  83. "fill": resizeFill,
  84. "crop": resizeCrop,
  85. }
  86. type rgbColor struct{ R, G, B uint8 }
  87. var hexColorRegex = regexp.MustCompile("^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
  88. const (
  89. hexColorLongFormat = "%02x%02x%02x"
  90. hexColorShortFormat = "%1x%1x%1x"
  91. )
  92. type watermarkOptions struct {
  93. Enabled bool
  94. Opacity float64
  95. Replicate bool
  96. Gravity gravityType
  97. OffsetX int
  98. OffsetY int
  99. Scale float64
  100. }
  101. type processingOptions struct {
  102. Resize resizeType
  103. Width int
  104. Height int
  105. Dpr float64
  106. Gravity gravityOptions
  107. Enlarge bool
  108. Expand bool
  109. Format imageType
  110. Quality int
  111. Flatten bool
  112. Background rgbColor
  113. Blur float32
  114. Sharpen float32
  115. CacheBuster string
  116. Watermark watermarkOptions
  117. UsedPresets []string
  118. }
  119. type applyOptionFunc func(po *processingOptions, args []string) error
  120. const (
  121. imageURLCtxKey = ctxKey("imageUrl")
  122. processingOptionsCtxKey = ctxKey("processingOptions")
  123. urlTokenPlain = "plain"
  124. maxClientHintDPR = 8
  125. msgForbidden = "Forbidden"
  126. msgInvalidURL = "Invalid URL"
  127. )
  128. var (
  129. errInvalidImageURL = errors.New("Invalid image url")
  130. errInvalidURLEncoding = errors.New("Invalid url encoding")
  131. errResultingImageFormatIsNotSupported = errors.New("Resulting image format is not supported")
  132. errInvalidPath = newError(404, "Invalid path", msgInvalidURL)
  133. )
  134. func (it imageType) String() string {
  135. for k, v := range imageTypes {
  136. if v == it {
  137. return k
  138. }
  139. }
  140. return ""
  141. }
  142. func (gt gravityType) String() string {
  143. for k, v := range gravityTypes {
  144. if v == gt {
  145. return k
  146. }
  147. }
  148. return ""
  149. }
  150. func (rt resizeType) String() string {
  151. for k, v := range resizeTypes {
  152. if v == rt {
  153. return k
  154. }
  155. }
  156. return ""
  157. }
  158. func (po *processingOptions) isPresetUsed(name string) bool {
  159. for _, usedName := range po.UsedPresets {
  160. if usedName == name {
  161. return true
  162. }
  163. }
  164. return false
  165. }
  166. func (po *processingOptions) presetUsed(name string) {
  167. po.UsedPresets = append(po.UsedPresets, name)
  168. }
  169. func colorFromHex(hexcolor string) (rgbColor, error) {
  170. c := rgbColor{}
  171. if !hexColorRegex.MatchString(hexcolor) {
  172. return c, fmt.Errorf("Invalid hex color: %s", hexcolor)
  173. }
  174. if len(hexcolor) == 3 {
  175. fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
  176. c.R *= 17
  177. c.G *= 17
  178. c.B *= 17
  179. } else {
  180. fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
  181. }
  182. return c, nil
  183. }
  184. func decodeBase64URL(parts []string) (string, string, error) {
  185. var format string
  186. urlParts := strings.Split(strings.Join(parts, ""), ".")
  187. if len(urlParts) > 2 {
  188. return "", "", errInvalidURLEncoding
  189. }
  190. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  191. format = urlParts[1]
  192. }
  193. imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
  194. if err != nil {
  195. return "", "", errInvalidURLEncoding
  196. }
  197. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, string(imageURL))
  198. if _, err := url.ParseRequestURI(fullURL); err != nil {
  199. return "", "", errInvalidImageURL
  200. }
  201. return fullURL, format, nil
  202. }
  203. func decodePlainURL(parts []string) (string, string, error) {
  204. var format string
  205. urlParts := strings.Split(strings.Join(parts, "/"), "@")
  206. if len(urlParts) > 2 {
  207. return "", "", errInvalidURLEncoding
  208. }
  209. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  210. format = urlParts[1]
  211. }
  212. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, urlParts[0])
  213. if _, err := url.ParseRequestURI(fullURL); err == nil {
  214. return fullURL, format, nil
  215. }
  216. if unescaped, err := url.PathUnescape(urlParts[0]); err == nil {
  217. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, unescaped)
  218. if _, err := url.ParseRequestURI(fullURL); err == nil {
  219. return fullURL, format, nil
  220. }
  221. }
  222. return "", "", errInvalidImageURL
  223. }
  224. func decodeURL(parts []string) (string, string, error) {
  225. if len(parts) == 0 {
  226. return "", "", errInvalidURLEncoding
  227. }
  228. if parts[0] == urlTokenPlain && len(parts) > 1 {
  229. return decodePlainURL(parts[1:])
  230. }
  231. return decodeBase64URL(parts)
  232. }
  233. func applyWidthOption(po *processingOptions, args []string) error {
  234. if len(args) > 1 {
  235. return fmt.Errorf("Invalid width arguments: %v", args)
  236. }
  237. if w, err := strconv.Atoi(args[0]); err == nil && w >= 0 {
  238. po.Width = w
  239. } else {
  240. return fmt.Errorf("Invalid width: %s", args[0])
  241. }
  242. return nil
  243. }
  244. func applyHeightOption(po *processingOptions, args []string) error {
  245. if len(args) > 1 {
  246. return fmt.Errorf("Invalid height arguments: %v", args)
  247. }
  248. if h, err := strconv.Atoi(args[0]); err == nil && po.Height >= 0 {
  249. po.Height = h
  250. } else {
  251. return fmt.Errorf("Invalid height: %s", args[0])
  252. }
  253. return nil
  254. }
  255. func applyEnlargeOption(po *processingOptions, args []string) error {
  256. if len(args) > 1 {
  257. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  258. }
  259. po.Enlarge = args[0] != "0"
  260. return nil
  261. }
  262. func applyExtendOption(po *processingOptions, args []string) error {
  263. if len(args) > 1 {
  264. return fmt.Errorf("Invalid expand arguments: %v", args)
  265. }
  266. po.Expand = args[0] != "0"
  267. return nil
  268. }
  269. func applySizeOption(po *processingOptions, args []string) (err error) {
  270. if len(args) > 4 {
  271. return fmt.Errorf("Invalid size arguments: %v", args)
  272. }
  273. if len(args) >= 1 && len(args[0]) > 0 {
  274. if err = applyWidthOption(po, args[0:1]); err != nil {
  275. return
  276. }
  277. }
  278. if len(args) >= 2 && len(args[1]) > 0 {
  279. if err = applyHeightOption(po, args[1:2]); err != nil {
  280. return
  281. }
  282. }
  283. if len(args) >= 3 && len(args[2]) > 0 {
  284. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  285. return
  286. }
  287. }
  288. if len(args) == 4 && len(args[3]) > 0 {
  289. if err = applyExtendOption(po, args[3:4]); err != nil {
  290. return
  291. }
  292. }
  293. return nil
  294. }
  295. func applyResizingTypeOption(po *processingOptions, args []string) error {
  296. if len(args) > 1 {
  297. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  298. }
  299. if r, ok := resizeTypes[args[0]]; ok {
  300. po.Resize = r
  301. } else {
  302. return fmt.Errorf("Invalid resize type: %s", args[0])
  303. }
  304. return nil
  305. }
  306. func applyResizeOption(po *processingOptions, args []string) error {
  307. if len(args) > 5 {
  308. return fmt.Errorf("Invalid resize arguments: %v", args)
  309. }
  310. if len(args[0]) > 0 {
  311. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  312. return err
  313. }
  314. }
  315. if len(args) > 1 {
  316. if err := applySizeOption(po, args[1:]); err != nil {
  317. return err
  318. }
  319. }
  320. return nil
  321. }
  322. func applyDprOption(po *processingOptions, args []string) error {
  323. if len(args) > 1 {
  324. return fmt.Errorf("Invalid dpr arguments: %v", args)
  325. }
  326. if d, err := strconv.ParseFloat(args[0], 64); err == nil || (d > 0 && d != 1) {
  327. po.Dpr = d
  328. } else {
  329. return fmt.Errorf("Invalid dpr: %s", args[0])
  330. }
  331. return nil
  332. }
  333. func applyGravityOption(po *processingOptions, args []string) error {
  334. if g, ok := gravityTypes[args[0]]; ok {
  335. po.Gravity.Type = g
  336. } else {
  337. return fmt.Errorf("Invalid gravity: %s", args[0])
  338. }
  339. if po.Gravity.Type == gravityFocusPoint {
  340. if len(args) != 3 {
  341. return fmt.Errorf("Invalid gravity arguments: %v", args)
  342. }
  343. if x, err := strconv.ParseFloat(args[1], 64); err == nil && x >= 0 && x <= 1 {
  344. po.Gravity.X = x
  345. } else {
  346. return fmt.Errorf("Invalid gravity X: %s", args[1])
  347. }
  348. if y, err := strconv.ParseFloat(args[2], 64); err == nil && y >= 0 && y <= 1 {
  349. po.Gravity.Y = y
  350. } else {
  351. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  352. }
  353. } else if len(args) > 1 {
  354. return fmt.Errorf("Invalid gravity arguments: %v", args)
  355. }
  356. return nil
  357. }
  358. func applyQualityOption(po *processingOptions, args []string) error {
  359. if len(args) > 1 {
  360. return fmt.Errorf("Invalid quality arguments: %v", args)
  361. }
  362. if q, err := strconv.Atoi(args[0]); err == nil && q > 0 && q <= 100 {
  363. po.Quality = q
  364. } else {
  365. return fmt.Errorf("Invalid quality: %s", args[0])
  366. }
  367. return nil
  368. }
  369. func applyBackgroundOption(po *processingOptions, args []string) error {
  370. switch len(args) {
  371. case 1:
  372. if len(args[0]) == 0 {
  373. po.Flatten = false
  374. } else if c, err := colorFromHex(args[0]); err == nil {
  375. po.Flatten = true
  376. po.Background = c
  377. } else {
  378. return fmt.Errorf("Invalid background argument: %s", err)
  379. }
  380. case 3:
  381. po.Flatten = true
  382. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r >= 0 && r <= 255 {
  383. po.Background.R = uint8(r)
  384. } else {
  385. return fmt.Errorf("Invalid background red channel: %s", args[0])
  386. }
  387. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g >= 0 && g <= 255 {
  388. po.Background.G = uint8(g)
  389. } else {
  390. return fmt.Errorf("Invalid background green channel: %s", args[1])
  391. }
  392. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b >= 0 && b <= 255 {
  393. po.Background.B = uint8(b)
  394. } else {
  395. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  396. }
  397. default:
  398. return fmt.Errorf("Invalid background arguments: %v", args)
  399. }
  400. return nil
  401. }
  402. func applyBlurOption(po *processingOptions, args []string) error {
  403. if len(args) > 1 {
  404. return fmt.Errorf("Invalid blur arguments: %v", args)
  405. }
  406. if b, err := strconv.ParseFloat(args[0], 32); err == nil || b >= 0 {
  407. po.Blur = float32(b)
  408. } else {
  409. return fmt.Errorf("Invalid blur: %s", args[0])
  410. }
  411. return nil
  412. }
  413. func applySharpenOption(po *processingOptions, args []string) error {
  414. if len(args) > 1 {
  415. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  416. }
  417. if s, err := strconv.ParseFloat(args[0], 32); err == nil || s >= 0 {
  418. po.Sharpen = float32(s)
  419. } else {
  420. return fmt.Errorf("Invalid sharpen: %s", args[0])
  421. }
  422. return nil
  423. }
  424. func applyPresetOption(po *processingOptions, args []string) error {
  425. for _, preset := range args {
  426. if p, ok := conf.Presets[preset]; ok {
  427. if po.isPresetUsed(preset) {
  428. return fmt.Errorf("Recursive preset usage is detected: %s", preset)
  429. }
  430. po.presetUsed(preset)
  431. if err := applyProcessingOptions(po, p); err != nil {
  432. return err
  433. }
  434. } else {
  435. return fmt.Errorf("Unknown asset: %s", preset)
  436. }
  437. }
  438. return nil
  439. }
  440. func applyWatermarkOption(po *processingOptions, args []string) error {
  441. if len(args) > 7 {
  442. return fmt.Errorf("Invalid watermark arguments: %v", args)
  443. }
  444. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  445. po.Watermark.Enabled = o > 0
  446. po.Watermark.Opacity = o
  447. } else {
  448. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  449. }
  450. if len(args) > 1 && len(args[1]) > 0 {
  451. if args[1] == "re" {
  452. po.Watermark.Replicate = true
  453. } else if g, ok := gravityTypes[args[1]]; ok && g != gravityFocusPoint && g != gravitySmart {
  454. po.Watermark.Gravity = g
  455. } else {
  456. return fmt.Errorf("Invalid watermark position: %s", args[1])
  457. }
  458. }
  459. if len(args) > 2 && len(args[2]) > 0 {
  460. if x, err := strconv.Atoi(args[2]); err == nil {
  461. po.Watermark.OffsetX = x
  462. } else {
  463. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  464. }
  465. }
  466. if len(args) > 3 && len(args[3]) > 0 {
  467. if y, err := strconv.Atoi(args[3]); err == nil {
  468. po.Watermark.OffsetY = y
  469. } else {
  470. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  471. }
  472. }
  473. if len(args) > 4 && len(args[4]) > 0 {
  474. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  475. po.Watermark.Scale = s
  476. } else {
  477. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  478. }
  479. }
  480. return nil
  481. }
  482. func applyFormatOption(po *processingOptions, args []string) error {
  483. if len(args) > 1 {
  484. return fmt.Errorf("Invalid format arguments: %v", args)
  485. }
  486. if conf.EnforceWebp && po.Format == imageTypeWEBP {
  487. // Webp is enforced and already set as format
  488. return nil
  489. }
  490. if f, ok := imageTypes[args[0]]; ok {
  491. po.Format = f
  492. } else {
  493. return fmt.Errorf("Invalid image format: %s", args[0])
  494. }
  495. if !vipsTypeSupportSave[po.Format] {
  496. return errResultingImageFormatIsNotSupported
  497. }
  498. return nil
  499. }
  500. func applyCacheBusterOption(po *processingOptions, args []string) error {
  501. if len(args) > 1 {
  502. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  503. }
  504. po.CacheBuster = args[0]
  505. return nil
  506. }
  507. func applyProcessingOption(po *processingOptions, name string, args []string) error {
  508. switch name {
  509. case "format", "f", "ext":
  510. if err := applyFormatOption(po, args); err != nil {
  511. return err
  512. }
  513. case "resize", "rs":
  514. if err := applyResizeOption(po, args); err != nil {
  515. return err
  516. }
  517. case "resizing_type", "rt":
  518. if err := applyResizingTypeOption(po, args); err != nil {
  519. return err
  520. }
  521. case "size", "s":
  522. if err := applySizeOption(po, args); err != nil {
  523. return err
  524. }
  525. case "width", "w":
  526. if err := applyWidthOption(po, args); err != nil {
  527. return err
  528. }
  529. case "height", "h":
  530. if err := applyHeightOption(po, args); err != nil {
  531. return err
  532. }
  533. case "enlarge", "el":
  534. if err := applyEnlargeOption(po, args); err != nil {
  535. return err
  536. }
  537. case "extend", "ex":
  538. if err := applyExtendOption(po, args); err != nil {
  539. return err
  540. }
  541. case "dpr":
  542. if err := applyDprOption(po, args); err != nil {
  543. return err
  544. }
  545. case "gravity", "g":
  546. if err := applyGravityOption(po, args); err != nil {
  547. return err
  548. }
  549. case "quality", "q":
  550. if err := applyQualityOption(po, args); err != nil {
  551. return err
  552. }
  553. case "background", "bg":
  554. if err := applyBackgroundOption(po, args); err != nil {
  555. return err
  556. }
  557. case "blur", "bl":
  558. if err := applyBlurOption(po, args); err != nil {
  559. return err
  560. }
  561. case "sharpen", "sh":
  562. if err := applySharpenOption(po, args); err != nil {
  563. return err
  564. }
  565. case "watermark", "wm":
  566. if err := applyWatermarkOption(po, args); err != nil {
  567. return err
  568. }
  569. case "preset", "pr":
  570. if err := applyPresetOption(po, args); err != nil {
  571. return err
  572. }
  573. case "cachebuster", "cb":
  574. if err := applyCacheBusterOption(po, args); err != nil {
  575. return err
  576. }
  577. default:
  578. return fmt.Errorf("Unknown processing option: %s", name)
  579. }
  580. return nil
  581. }
  582. func applyProcessingOptions(po *processingOptions, options urlOptions) error {
  583. for name, args := range options {
  584. if err := applyProcessingOption(po, name, args); err != nil {
  585. return err
  586. }
  587. }
  588. return nil
  589. }
  590. func parseURLOptions(opts []string) (urlOptions, []string) {
  591. parsed := make(urlOptions)
  592. urlStart := len(opts) + 1
  593. for i, opt := range opts {
  594. args := strings.Split(opt, ":")
  595. if len(args) == 1 {
  596. urlStart = i
  597. break
  598. }
  599. parsed[args[0]] = args[1:]
  600. }
  601. var rest []string
  602. if urlStart < len(opts) {
  603. rest = opts[urlStart:]
  604. } else {
  605. rest = []string{}
  606. }
  607. return parsed, rest
  608. }
  609. func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, error) {
  610. var err error
  611. po := processingOptions{
  612. Resize: resizeFit,
  613. Width: 0,
  614. Height: 0,
  615. Gravity: gravityOptions{Type: gravityCenter},
  616. Enlarge: false,
  617. Quality: conf.Quality,
  618. Format: imageTypeUnknown,
  619. Background: rgbColor{255, 255, 255},
  620. Blur: 0,
  621. Sharpen: 0,
  622. Dpr: 1,
  623. Watermark: watermarkOptions{Opacity: 1, Replicate: false, Gravity: gravityCenter},
  624. UsedPresets: make([]string, 0, len(conf.Presets)),
  625. }
  626. if (conf.EnableWebpDetection || conf.EnforceWebp) && strings.Contains(headers.Accept, "image/webp") {
  627. po.Format = imageTypeWEBP
  628. }
  629. if conf.EnableClientHints && len(headers.ViewportWidth) > 0 {
  630. if vw, err := strconv.Atoi(headers.ViewportWidth); err == nil {
  631. po.Width = vw
  632. }
  633. }
  634. if conf.EnableClientHints && len(headers.Width) > 0 {
  635. if w, err := strconv.Atoi(headers.Width); err == nil {
  636. po.Width = w
  637. }
  638. }
  639. if conf.EnableClientHints && len(headers.DPR) > 0 {
  640. if dpr, err := strconv.ParseFloat(headers.DPR, 64); err == nil || (dpr > 0 && dpr <= maxClientHintDPR) {
  641. po.Dpr = dpr
  642. }
  643. }
  644. if _, ok := conf.Presets["default"]; ok {
  645. err = applyPresetOption(&po, []string{"default"})
  646. }
  647. return &po, err
  648. }
  649. func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  650. po, err := defaultProcessingOptions(headers)
  651. if err != nil {
  652. return "", po, err
  653. }
  654. options, urlParts := parseURLOptions(parts)
  655. if err := applyProcessingOptions(po, options); err != nil {
  656. return "", po, err
  657. }
  658. url, extension, err := decodeURL(urlParts)
  659. if err != nil {
  660. return "", po, err
  661. }
  662. if len(extension) > 0 {
  663. if err := applyFormatOption(po, []string{extension}); err != nil {
  664. return "", po, err
  665. }
  666. }
  667. return url, po, nil
  668. }
  669. func parsePathBasic(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  670. var err error
  671. if len(parts) < 6 {
  672. return "", nil, errInvalidPath
  673. }
  674. po, err := defaultProcessingOptions(headers)
  675. if err != nil {
  676. return "", po, err
  677. }
  678. po.Resize = resizeTypes[parts[0]]
  679. if err = applyWidthOption(po, parts[1:2]); err != nil {
  680. return "", po, err
  681. }
  682. if err = applyHeightOption(po, parts[2:3]); err != nil {
  683. return "", po, err
  684. }
  685. if err = applyGravityOption(po, strings.Split(parts[3], ":")); err != nil {
  686. return "", po, err
  687. }
  688. if err = applyEnlargeOption(po, parts[4:5]); err != nil {
  689. return "", po, err
  690. }
  691. url, extension, err := decodeURL(parts[5:])
  692. if err != nil {
  693. return "", po, err
  694. }
  695. if len(extension) > 0 {
  696. if err := applyFormatOption(po, []string{extension}); err != nil {
  697. return "", po, err
  698. }
  699. }
  700. return url, po, nil
  701. }
  702. func parsePath(ctx context.Context, r *http.Request) (context.Context, error) {
  703. path := r.URL.Path
  704. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  705. if len(parts) < 3 {
  706. return ctx, errInvalidPath
  707. }
  708. if !conf.AllowInsecure {
  709. if err := validatePath(parts[0], strings.TrimPrefix(path, fmt.Sprintf("/%s", parts[0]))); err != nil {
  710. return ctx, newError(403, err.Error(), msgForbidden)
  711. }
  712. }
  713. headers := &processingHeaders{
  714. Accept: r.Header.Get("Accept"),
  715. Width: r.Header.Get("Width"),
  716. ViewportWidth: r.Header.Get("Viewport-Width"),
  717. DPR: r.Header.Get("DPR"),
  718. }
  719. var imageURL string
  720. var po *processingOptions
  721. var err error
  722. if _, ok := resizeTypes[parts[1]]; ok {
  723. imageURL, po, err = parsePathBasic(parts[1:], headers)
  724. } else {
  725. imageURL, po, err = parsePathAdvanced(parts[1:], headers)
  726. }
  727. if err != nil {
  728. return ctx, newError(404, err.Error(), msgInvalidURL)
  729. }
  730. ctx = context.WithValue(ctx, imageURLCtxKey, imageURL)
  731. ctx = context.WithValue(ctx, processingOptionsCtxKey, po)
  732. return ctx, nil
  733. }
  734. func getImageURL(ctx context.Context) string {
  735. return ctx.Value(imageURLCtxKey).(string)
  736. }
  737. func getProcessingOptions(ctx context.Context) *processingOptions {
  738. return ctx.Value(processingOptionsCtxKey).(*processingOptions)
  739. }