processing_options.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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 (po *processingOptions) isPresetUsed(name string) bool {
  136. for _, usedName := range po.UsedPresets {
  137. if usedName == name {
  138. return true
  139. }
  140. }
  141. return false
  142. }
  143. func (po *processingOptions) presetUsed(name string) {
  144. po.UsedPresets = append(po.UsedPresets, name)
  145. }
  146. func colorFromHex(hexcolor string) (rgbColor, error) {
  147. c := rgbColor{}
  148. if !hexColorRegex.MatchString(hexcolor) {
  149. return c, fmt.Errorf("Invalid hex color: %s", hexcolor)
  150. }
  151. if len(hexcolor) == 3 {
  152. fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
  153. c.R *= 17
  154. c.G *= 17
  155. c.B *= 17
  156. } else {
  157. fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
  158. }
  159. return c, nil
  160. }
  161. func decodeBase64URL(parts []string) (string, string, error) {
  162. var format string
  163. encoded := strings.Join(parts, "")
  164. urlParts := strings.Split(encoded, ".")
  165. if len(urlParts[0]) == 0 {
  166. return "", "", errors.New("Image URL is empty")
  167. }
  168. if len(urlParts) > 2 {
  169. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  170. }
  171. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  172. format = urlParts[1]
  173. }
  174. imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
  175. if err != nil {
  176. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  177. }
  178. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, string(imageURL))
  179. if _, err := url.ParseRequestURI(fullURL); err != nil {
  180. return "", "", fmt.Errorf("Invalid image url: %s", fullURL)
  181. }
  182. return fullURL, format, nil
  183. }
  184. func decodePlainURL(parts []string) (string, string, error) {
  185. var format string
  186. encoded := strings.Join(parts, "/")
  187. urlParts := strings.Split(encoded, "@")
  188. if len(urlParts[0]) == 0 {
  189. return "", "", errors.New("Image URL is empty")
  190. }
  191. if len(urlParts) > 2 {
  192. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  193. }
  194. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  195. format = urlParts[1]
  196. }
  197. unescaped, err := url.PathUnescape(urlParts[0])
  198. if err != nil {
  199. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  200. }
  201. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, unescaped)
  202. if _, err := url.ParseRequestURI(fullURL); err != nil {
  203. return "", "", fmt.Errorf("Invalid image url: %s", fullURL)
  204. }
  205. return fullURL, format, nil
  206. }
  207. func decodeURL(parts []string) (string, string, error) {
  208. if len(parts) == 0 {
  209. return "", "", errors.New("Image URL is empty")
  210. }
  211. if parts[0] == urlTokenPlain && len(parts) > 1 {
  212. return decodePlainURL(parts[1:])
  213. }
  214. return decodeBase64URL(parts)
  215. }
  216. func parseDimension(d *int, name, arg string) error {
  217. if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
  218. *d = v
  219. } else {
  220. return fmt.Errorf("Invalid %s: %s", name, arg)
  221. }
  222. return nil
  223. }
  224. func isGravityOffcetValid(gravity gravityType, offset float64) bool {
  225. if gravity == gravityCenter {
  226. return true
  227. }
  228. return offset >= 0 && (gravity != gravityFocusPoint || offset <= 1)
  229. }
  230. func parseGravity(g *gravityOptions, args []string) error {
  231. nArgs := len(args)
  232. if nArgs > 3 {
  233. return fmt.Errorf("Invalid gravity arguments: %v", args)
  234. }
  235. if t, ok := gravityTypes[args[0]]; ok {
  236. g.Type = t
  237. } else {
  238. return fmt.Errorf("Invalid gravity: %s", args[0])
  239. }
  240. if g.Type == gravitySmart && nArgs > 1 {
  241. return fmt.Errorf("Invalid gravity arguments: %v", args)
  242. } else if g.Type == gravityFocusPoint && nArgs != 3 {
  243. return fmt.Errorf("Invalid gravity arguments: %v", args)
  244. }
  245. if nArgs > 1 {
  246. if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
  247. g.X = x
  248. } else {
  249. return fmt.Errorf("Invalid gravity X: %s", args[1])
  250. }
  251. }
  252. if nArgs > 2 {
  253. if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
  254. g.Y = y
  255. } else {
  256. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  257. }
  258. }
  259. return nil
  260. }
  261. func applyWidthOption(po *processingOptions, args []string) error {
  262. if len(args) > 1 {
  263. return fmt.Errorf("Invalid width arguments: %v", args)
  264. }
  265. return parseDimension(&po.Width, "width", args[0])
  266. }
  267. func applyHeightOption(po *processingOptions, args []string) error {
  268. if len(args) > 1 {
  269. return fmt.Errorf("Invalid height arguments: %v", args)
  270. }
  271. return parseDimension(&po.Height, "height", args[0])
  272. }
  273. func applyEnlargeOption(po *processingOptions, args []string) error {
  274. if len(args) > 1 {
  275. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  276. }
  277. po.Enlarge = args[0] != "0"
  278. return nil
  279. }
  280. func applyExtendOption(po *processingOptions, args []string) error {
  281. if len(args) > 1 {
  282. return fmt.Errorf("Invalid extend arguments: %v", args)
  283. }
  284. po.Extend = args[0] != "0"
  285. return nil
  286. }
  287. func applySizeOption(po *processingOptions, args []string) (err error) {
  288. if len(args) > 4 {
  289. return fmt.Errorf("Invalid size arguments: %v", args)
  290. }
  291. if len(args) >= 1 && len(args[0]) > 0 {
  292. if err = applyWidthOption(po, args[0:1]); err != nil {
  293. return
  294. }
  295. }
  296. if len(args) >= 2 && len(args[1]) > 0 {
  297. if err = applyHeightOption(po, args[1:2]); err != nil {
  298. return
  299. }
  300. }
  301. if len(args) >= 3 && len(args[2]) > 0 {
  302. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  303. return
  304. }
  305. }
  306. if len(args) == 4 && len(args[3]) > 0 {
  307. if err = applyExtendOption(po, args[3:4]); err != nil {
  308. return
  309. }
  310. }
  311. return nil
  312. }
  313. func applyResizingTypeOption(po *processingOptions, args []string) error {
  314. if len(args) > 1 {
  315. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  316. }
  317. if r, ok := resizeTypes[args[0]]; ok {
  318. po.Resize = r
  319. } else {
  320. return fmt.Errorf("Invalid resize type: %s", args[0])
  321. }
  322. return nil
  323. }
  324. func applyResizeOption(po *processingOptions, args []string) error {
  325. if len(args) > 5 {
  326. return fmt.Errorf("Invalid resize arguments: %v", args)
  327. }
  328. if len(args[0]) > 0 {
  329. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  330. return err
  331. }
  332. }
  333. if len(args) > 1 {
  334. if err := applySizeOption(po, args[1:]); err != nil {
  335. return err
  336. }
  337. }
  338. return nil
  339. }
  340. func applyDprOption(po *processingOptions, args []string) error {
  341. if len(args) > 1 {
  342. return fmt.Errorf("Invalid dpr arguments: %v", args)
  343. }
  344. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  345. po.Dpr = d
  346. } else {
  347. return fmt.Errorf("Invalid dpr: %s", args[0])
  348. }
  349. return nil
  350. }
  351. func applyGravityOption(po *processingOptions, args []string) error {
  352. return parseGravity(&po.Gravity, args)
  353. }
  354. func applyCropOption(po *processingOptions, args []string) error {
  355. if len(args) > 5 {
  356. return fmt.Errorf("Invalid crop arguments: %v", args)
  357. }
  358. if err := parseDimension(&po.Crop.Width, "crop width", args[0]); err != nil {
  359. return err
  360. }
  361. if len(args) > 1 {
  362. if err := parseDimension(&po.Crop.Height, "crop height", args[1]); err != nil {
  363. return err
  364. }
  365. }
  366. if len(args) > 2 {
  367. return parseGravity(&po.Crop.Gravity, args[2:])
  368. }
  369. return nil
  370. }
  371. func applyQualityOption(po *processingOptions, args []string) error {
  372. if len(args) > 1 {
  373. return fmt.Errorf("Invalid quality arguments: %v", args)
  374. }
  375. if q, err := strconv.Atoi(args[0]); err == nil && q > 0 && q <= 100 {
  376. po.Quality = q
  377. } else {
  378. return fmt.Errorf("Invalid quality: %s", args[0])
  379. }
  380. return nil
  381. }
  382. func applyBackgroundOption(po *processingOptions, args []string) error {
  383. switch len(args) {
  384. case 1:
  385. if len(args[0]) == 0 {
  386. po.Flatten = false
  387. } else if c, err := colorFromHex(args[0]); err == nil {
  388. po.Flatten = true
  389. po.Background = c
  390. } else {
  391. return fmt.Errorf("Invalid background argument: %s", err)
  392. }
  393. case 3:
  394. po.Flatten = true
  395. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  396. po.Background.R = uint8(r)
  397. } else {
  398. return fmt.Errorf("Invalid background red channel: %s", args[0])
  399. }
  400. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  401. po.Background.G = uint8(g)
  402. } else {
  403. return fmt.Errorf("Invalid background green channel: %s", args[1])
  404. }
  405. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  406. po.Background.B = uint8(b)
  407. } else {
  408. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  409. }
  410. default:
  411. return fmt.Errorf("Invalid background arguments: %v", args)
  412. }
  413. return nil
  414. }
  415. func applyBlurOption(po *processingOptions, args []string) error {
  416. if len(args) > 1 {
  417. return fmt.Errorf("Invalid blur arguments: %v", args)
  418. }
  419. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  420. po.Blur = float32(b)
  421. } else {
  422. return fmt.Errorf("Invalid blur: %s", args[0])
  423. }
  424. return nil
  425. }
  426. func applySharpenOption(po *processingOptions, args []string) error {
  427. if len(args) > 1 {
  428. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  429. }
  430. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  431. po.Sharpen = float32(s)
  432. } else {
  433. return fmt.Errorf("Invalid sharpen: %s", args[0])
  434. }
  435. return nil
  436. }
  437. func applyPresetOption(po *processingOptions, args []string) error {
  438. for _, preset := range args {
  439. if p, ok := conf.Presets[preset]; ok {
  440. if po.isPresetUsed(preset) {
  441. logWarning("Recursive preset usage is detected: %s", preset)
  442. continue
  443. }
  444. po.presetUsed(preset)
  445. if err := applyProcessingOptions(po, p); err != nil {
  446. return err
  447. }
  448. } else {
  449. return fmt.Errorf("Unknown preset: %s", preset)
  450. }
  451. }
  452. return nil
  453. }
  454. func applyWatermarkOption(po *processingOptions, args []string) error {
  455. if len(args) > 7 {
  456. return fmt.Errorf("Invalid watermark arguments: %v", args)
  457. }
  458. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  459. po.Watermark.Enabled = o > 0
  460. po.Watermark.Opacity = o
  461. } else {
  462. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  463. }
  464. if len(args) > 1 && len(args[1]) > 0 {
  465. if args[1] == "re" {
  466. po.Watermark.Replicate = true
  467. } else if g, ok := gravityTypes[args[1]]; ok && g != gravityFocusPoint && g != gravitySmart {
  468. po.Watermark.Gravity = g
  469. } else {
  470. return fmt.Errorf("Invalid watermark position: %s", args[1])
  471. }
  472. }
  473. if len(args) > 2 && len(args[2]) > 0 {
  474. if x, err := strconv.Atoi(args[2]); err == nil {
  475. po.Watermark.OffsetX = x
  476. } else {
  477. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  478. }
  479. }
  480. if len(args) > 3 && len(args[3]) > 0 {
  481. if y, err := strconv.Atoi(args[3]); err == nil {
  482. po.Watermark.OffsetY = y
  483. } else {
  484. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  485. }
  486. }
  487. if len(args) > 4 && len(args[4]) > 0 {
  488. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  489. po.Watermark.Scale = s
  490. } else {
  491. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  492. }
  493. }
  494. return nil
  495. }
  496. func applyFormatOption(po *processingOptions, args []string) error {
  497. if len(args) > 1 {
  498. return fmt.Errorf("Invalid format arguments: %v", args)
  499. }
  500. if f, ok := imageTypes[args[0]]; ok {
  501. po.Format = f
  502. } else {
  503. return fmt.Errorf("Invalid image format: %s", args[0])
  504. }
  505. if !vipsTypeSupportSave[po.Format] {
  506. return fmt.Errorf("Resulting image format is not supported: %s", po.Format)
  507. }
  508. return nil
  509. }
  510. func applyCacheBusterOption(po *processingOptions, args []string) error {
  511. if len(args) > 1 {
  512. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  513. }
  514. po.CacheBuster = args[0]
  515. return nil
  516. }
  517. func applyFilenameOption(po *processingOptions, args []string) error {
  518. if len(args) > 1 {
  519. return fmt.Errorf("Invalid filename arguments: %v", args)
  520. }
  521. po.Filename = args[0]
  522. return nil
  523. }
  524. func applyProcessingOption(po *processingOptions, name string, args []string) error {
  525. switch name {
  526. case "format", "f", "ext":
  527. return applyFormatOption(po, args)
  528. case "resize", "rs":
  529. return applyResizeOption(po, args)
  530. case "resizing_type", "rt":
  531. return applyResizingTypeOption(po, args)
  532. case "size", "s":
  533. return applySizeOption(po, args)
  534. case "width", "w":
  535. return applyWidthOption(po, args)
  536. case "height", "h":
  537. return applyHeightOption(po, args)
  538. case "enlarge", "el":
  539. return applyEnlargeOption(po, args)
  540. case "extend", "ex":
  541. return applyExtendOption(po, args)
  542. case "dpr":
  543. return applyDprOption(po, args)
  544. case "gravity", "g":
  545. return applyGravityOption(po, args)
  546. case "crop", "c":
  547. return applyCropOption(po, args)
  548. case "quality", "q":
  549. return applyQualityOption(po, args)
  550. case "background", "bg":
  551. return applyBackgroundOption(po, args)
  552. case "blur", "bl":
  553. return applyBlurOption(po, args)
  554. case "sharpen", "sh":
  555. return applySharpenOption(po, args)
  556. case "watermark", "wm":
  557. return applyWatermarkOption(po, args)
  558. case "preset", "pr":
  559. return applyPresetOption(po, args)
  560. case "cachebuster", "cb":
  561. return applyCacheBusterOption(po, args)
  562. case "filename", "fn":
  563. return applyFilenameOption(po, args)
  564. }
  565. return fmt.Errorf("Unknown processing option: %s", name)
  566. }
  567. func applyProcessingOptions(po *processingOptions, options urlOptions) error {
  568. for _, opt := range options {
  569. if err := applyProcessingOption(po, opt.Name, opt.Args); err != nil {
  570. return err
  571. }
  572. }
  573. return nil
  574. }
  575. func parseURLOptions(opts []string) (urlOptions, []string) {
  576. parsed := make(urlOptions, 0, len(opts))
  577. urlStart := len(opts) + 1
  578. for i, opt := range opts {
  579. args := strings.Split(opt, ":")
  580. if len(args) == 1 {
  581. urlStart = i
  582. break
  583. }
  584. parsed = append(parsed, urlOption{Name: args[0], Args: args[1:]})
  585. }
  586. var rest []string
  587. if urlStart < len(opts) {
  588. rest = opts[urlStart:]
  589. } else {
  590. rest = []string{}
  591. }
  592. return parsed, rest
  593. }
  594. func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, error) {
  595. var err error
  596. po := processingOptions{
  597. Resize: resizeFit,
  598. Width: 0,
  599. Height: 0,
  600. Gravity: gravityOptions{Type: gravityCenter},
  601. Enlarge: false,
  602. Quality: conf.Quality,
  603. Format: imageTypeUnknown,
  604. Background: rgbColor{255, 255, 255},
  605. Blur: 0,
  606. Sharpen: 0,
  607. Dpr: 1,
  608. Watermark: watermarkOptions{Opacity: 1, Replicate: false, Gravity: gravityCenter},
  609. UsedPresets: make([]string, 0, len(conf.Presets)),
  610. }
  611. if strings.Contains(headers.Accept, "image/webp") {
  612. po.PreferWebP = conf.EnableWebpDetection || conf.EnforceWebp
  613. po.EnforceWebP = conf.EnforceWebp
  614. }
  615. if conf.EnableClientHints && len(headers.ViewportWidth) > 0 {
  616. if vw, err := strconv.Atoi(headers.ViewportWidth); err == nil {
  617. po.Width = vw
  618. }
  619. }
  620. if conf.EnableClientHints && len(headers.Width) > 0 {
  621. if w, err := strconv.Atoi(headers.Width); err == nil {
  622. po.Width = w
  623. }
  624. }
  625. if conf.EnableClientHints && len(headers.DPR) > 0 {
  626. if dpr, err := strconv.ParseFloat(headers.DPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  627. po.Dpr = dpr
  628. }
  629. }
  630. if _, ok := conf.Presets["default"]; ok {
  631. err = applyPresetOption(&po, []string{"default"})
  632. }
  633. return &po, err
  634. }
  635. func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  636. po, err := defaultProcessingOptions(headers)
  637. if err != nil {
  638. return "", po, err
  639. }
  640. options, urlParts := parseURLOptions(parts)
  641. if err := applyProcessingOptions(po, options); err != nil {
  642. return "", po, err
  643. }
  644. url, extension, err := decodeURL(urlParts)
  645. if err != nil {
  646. return "", po, err
  647. }
  648. if len(extension) > 0 {
  649. if err := applyFormatOption(po, []string{extension}); err != nil {
  650. return "", po, err
  651. }
  652. }
  653. return url, po, nil
  654. }
  655. func parsePathPresets(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  656. po, err := defaultProcessingOptions(headers)
  657. if err != nil {
  658. return "", po, err
  659. }
  660. presets := strings.Split(parts[0], ":")
  661. urlParts := parts[1:]
  662. if err := applyPresetOption(po, presets); err != nil {
  663. return "", nil, err
  664. }
  665. url, extension, err := decodeURL(urlParts)
  666. if err != nil {
  667. return "", po, err
  668. }
  669. if len(extension) > 0 {
  670. if err := applyFormatOption(po, []string{extension}); err != nil {
  671. return "", po, err
  672. }
  673. }
  674. return url, po, nil
  675. }
  676. func parsePathBasic(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  677. var err 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. }