processing_options.go 20 KB

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