processing_options.go 21 KB

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