processing_options.go 20 KB

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