1
0

processing_options.go 20 KB

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