processing_options.go 21 KB

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