processing_options.go 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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. "github.com/imgproxy/imgproxy/v2/structdiff"
  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 extendOptions struct {
  78. Enabled bool
  79. Gravity gravityOptions
  80. }
  81. type cropOptions struct {
  82. Width int
  83. Height int
  84. Gravity gravityOptions
  85. }
  86. type paddingOptions struct {
  87. Enabled bool
  88. Top int
  89. Right int
  90. Bottom int
  91. Left int
  92. }
  93. type trimOptions struct {
  94. Enabled bool
  95. Threshold float64
  96. Smart bool
  97. Color rgbColor
  98. EqualHor bool
  99. EqualVer bool
  100. }
  101. type watermarkOptions struct {
  102. Enabled bool
  103. Opacity float64
  104. Replicate bool
  105. Gravity gravityOptions
  106. Scale float64
  107. }
  108. type processingOptions struct {
  109. ResizingType resizeType
  110. Width int
  111. Height int
  112. Dpr float64
  113. Gravity gravityOptions
  114. Enlarge bool
  115. Extend extendOptions
  116. Crop cropOptions
  117. Padding paddingOptions
  118. Trim trimOptions
  119. Format imageType
  120. Quality int
  121. MaxBytes int
  122. Flatten bool
  123. Background rgbColor
  124. Blur float32
  125. Sharpen float32
  126. StripMetadata bool
  127. CacheBuster string
  128. Watermark watermarkOptions
  129. PreferWebP bool
  130. EnforceWebP bool
  131. Filename string
  132. UsedPresets []string
  133. }
  134. const (
  135. imageURLCtxKey = ctxKey("imageUrl")
  136. processingOptionsCtxKey = ctxKey("processingOptions")
  137. urlTokenPlain = "plain"
  138. maxClientHintDPR = 8
  139. msgForbidden = "Forbidden"
  140. msgInvalidURL = "Invalid URL"
  141. msgInvalidSource = "Invalid Source"
  142. )
  143. func (gt gravityType) String() string {
  144. for k, v := range gravityTypes {
  145. if v == gt {
  146. return k
  147. }
  148. }
  149. return ""
  150. }
  151. func (gt gravityType) MarshalJSON() ([]byte, error) {
  152. for k, v := range gravityTypes {
  153. if v == gt {
  154. return []byte(fmt.Sprintf("%q", k)), nil
  155. }
  156. }
  157. return []byte("null"), nil
  158. }
  159. func (rt resizeType) String() string {
  160. for k, v := range resizeTypes {
  161. if v == rt {
  162. return k
  163. }
  164. }
  165. return ""
  166. }
  167. func (rt resizeType) MarshalJSON() ([]byte, error) {
  168. for k, v := range resizeTypes {
  169. if v == rt {
  170. return []byte(fmt.Sprintf("%q", k)), nil
  171. }
  172. }
  173. return []byte("null"), nil
  174. }
  175. var (
  176. _newProcessingOptions processingOptions
  177. newProcessingOptionsOnce sync.Once
  178. )
  179. func newProcessingOptions() *processingOptions {
  180. newProcessingOptionsOnce.Do(func() {
  181. _newProcessingOptions = processingOptions{
  182. ResizingType: resizeFit,
  183. Width: 0,
  184. Height: 0,
  185. Gravity: gravityOptions{Type: gravityCenter},
  186. Enlarge: false,
  187. Extend: extendOptions{Enabled: false, Gravity: gravityOptions{Type: gravityCenter}},
  188. Padding: paddingOptions{Enabled: false},
  189. Trim: trimOptions{Enabled: false, Threshold: 10, Smart: true},
  190. Quality: conf.Quality,
  191. MaxBytes: 0,
  192. Format: imageTypeUnknown,
  193. Background: rgbColor{255, 255, 255},
  194. Blur: 0,
  195. Sharpen: 0,
  196. Dpr: 1,
  197. Watermark: watermarkOptions{Opacity: 1, Replicate: false, Gravity: gravityOptions{Type: gravityCenter}},
  198. StripMetadata: conf.StripMetadata,
  199. }
  200. })
  201. po := _newProcessingOptions
  202. po.UsedPresets = make([]string, 0, len(conf.Presets))
  203. return &po
  204. }
  205. func (po *processingOptions) isPresetUsed(name string) bool {
  206. for _, usedName := range po.UsedPresets {
  207. if usedName == name {
  208. return true
  209. }
  210. }
  211. return false
  212. }
  213. func (po *processingOptions) presetUsed(name string) {
  214. po.UsedPresets = append(po.UsedPresets, name)
  215. }
  216. func (po *processingOptions) Diff() structdiff.Entries {
  217. return structdiff.Diff(newProcessingOptions(), po)
  218. }
  219. func (po *processingOptions) String() string {
  220. return po.Diff().String()
  221. }
  222. func (po *processingOptions) MarshalJSON() ([]byte, error) {
  223. return po.Diff().MarshalJSON()
  224. }
  225. func colorFromHex(hexcolor string) (rgbColor, error) {
  226. c := rgbColor{}
  227. if !hexColorRegex.MatchString(hexcolor) {
  228. return c, fmt.Errorf("Invalid hex color: %s", hexcolor)
  229. }
  230. if len(hexcolor) == 3 {
  231. fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
  232. c.R *= 17
  233. c.G *= 17
  234. c.B *= 17
  235. } else {
  236. fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
  237. }
  238. return c, nil
  239. }
  240. func decodeBase64URL(parts []string) (string, string, error) {
  241. var format string
  242. encoded := strings.Join(parts, "")
  243. urlParts := strings.Split(encoded, ".")
  244. if len(urlParts[0]) == 0 {
  245. return "", "", errors.New("Image URL is empty")
  246. }
  247. if len(urlParts) > 2 {
  248. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  249. }
  250. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  251. format = urlParts[1]
  252. }
  253. imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
  254. if err != nil {
  255. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  256. }
  257. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, string(imageURL))
  258. return fullURL, format, nil
  259. }
  260. func decodePlainURL(parts []string) (string, string, error) {
  261. var format string
  262. encoded := strings.Join(parts, "/")
  263. urlParts := strings.Split(encoded, "@")
  264. if len(urlParts[0]) == 0 {
  265. return "", "", errors.New("Image URL is empty")
  266. }
  267. if len(urlParts) > 2 {
  268. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  269. }
  270. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  271. format = urlParts[1]
  272. }
  273. unescaped, err := url.PathUnescape(urlParts[0])
  274. if err != nil {
  275. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  276. }
  277. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, unescaped)
  278. return fullURL, format, nil
  279. }
  280. func decodeURL(parts []string) (string, string, error) {
  281. if len(parts) == 0 {
  282. return "", "", errors.New("Image URL is empty")
  283. }
  284. if parts[0] == urlTokenPlain && len(parts) > 1 {
  285. return decodePlainURL(parts[1:])
  286. }
  287. return decodeBase64URL(parts)
  288. }
  289. func parseDimension(d *int, name, arg string) error {
  290. if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
  291. *d = v
  292. } else {
  293. return fmt.Errorf("Invalid %s: %s", name, arg)
  294. }
  295. return nil
  296. }
  297. func parseBoolOption(str string) bool {
  298. b, err := strconv.ParseBool(str)
  299. if err != nil {
  300. logWarning("`%s` is not a valid boolean value. Treated as false", str)
  301. }
  302. return b
  303. }
  304. func isGravityOffcetValid(gravity gravityType, offset float64) bool {
  305. if gravity == gravityCenter {
  306. return true
  307. }
  308. return offset >= 0 && (gravity != gravityFocusPoint || offset <= 1)
  309. }
  310. func parseGravity(g *gravityOptions, args []string) error {
  311. nArgs := len(args)
  312. if nArgs > 3 {
  313. return fmt.Errorf("Invalid gravity arguments: %v", args)
  314. }
  315. if t, ok := gravityTypes[args[0]]; ok {
  316. g.Type = t
  317. } else {
  318. return fmt.Errorf("Invalid gravity: %s", args[0])
  319. }
  320. if g.Type == gravitySmart && nArgs > 1 {
  321. return fmt.Errorf("Invalid gravity arguments: %v", args)
  322. } else if g.Type == gravityFocusPoint && nArgs != 3 {
  323. return fmt.Errorf("Invalid gravity arguments: %v", args)
  324. }
  325. if nArgs > 1 {
  326. if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
  327. g.X = x
  328. } else {
  329. return fmt.Errorf("Invalid gravity X: %s", args[1])
  330. }
  331. }
  332. if nArgs > 2 {
  333. if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
  334. g.Y = y
  335. } else {
  336. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  337. }
  338. }
  339. return nil
  340. }
  341. func applyWidthOption(po *processingOptions, args []string) error {
  342. if len(args) > 1 {
  343. return fmt.Errorf("Invalid width arguments: %v", args)
  344. }
  345. return parseDimension(&po.Width, "width", args[0])
  346. }
  347. func applyHeightOption(po *processingOptions, args []string) error {
  348. if len(args) > 1 {
  349. return fmt.Errorf("Invalid height arguments: %v", args)
  350. }
  351. return parseDimension(&po.Height, "height", args[0])
  352. }
  353. func applyEnlargeOption(po *processingOptions, args []string) error {
  354. if len(args) > 1 {
  355. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  356. }
  357. po.Enlarge = parseBoolOption(args[0])
  358. return nil
  359. }
  360. func applyExtendOption(po *processingOptions, args []string) error {
  361. if len(args) > 4 {
  362. return fmt.Errorf("Invalid extend arguments: %v", args)
  363. }
  364. po.Extend.Enabled = parseBoolOption(args[0])
  365. if len(args) > 1 {
  366. if err := parseGravity(&po.Extend.Gravity, args[1:]); err != nil {
  367. return err
  368. }
  369. if po.Extend.Gravity.Type == gravitySmart {
  370. return errors.New("extend doesn't support smart gravity")
  371. }
  372. }
  373. return nil
  374. }
  375. func applySizeOption(po *processingOptions, args []string) (err error) {
  376. if len(args) > 7 {
  377. return fmt.Errorf("Invalid size arguments: %v", args)
  378. }
  379. if len(args) >= 1 && len(args[0]) > 0 {
  380. if err = applyWidthOption(po, args[0:1]); err != nil {
  381. return
  382. }
  383. }
  384. if len(args) >= 2 && len(args[1]) > 0 {
  385. if err = applyHeightOption(po, args[1:2]); err != nil {
  386. return
  387. }
  388. }
  389. if len(args) >= 3 && len(args[2]) > 0 {
  390. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  391. return
  392. }
  393. }
  394. if len(args) >= 4 && len(args[3]) > 0 {
  395. if err = applyExtendOption(po, args[3:]); err != nil {
  396. return
  397. }
  398. }
  399. return nil
  400. }
  401. func applyResizingTypeOption(po *processingOptions, args []string) error {
  402. if len(args) > 1 {
  403. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  404. }
  405. if r, ok := resizeTypes[args[0]]; ok {
  406. po.ResizingType = r
  407. } else {
  408. return fmt.Errorf("Invalid resize type: %s", args[0])
  409. }
  410. return nil
  411. }
  412. func applyResizeOption(po *processingOptions, args []string) error {
  413. if len(args) > 8 {
  414. return fmt.Errorf("Invalid resize arguments: %v", args)
  415. }
  416. if len(args[0]) > 0 {
  417. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  418. return err
  419. }
  420. }
  421. if len(args) > 1 {
  422. if err := applySizeOption(po, args[1:]); err != nil {
  423. return err
  424. }
  425. }
  426. return nil
  427. }
  428. func applyDprOption(po *processingOptions, args []string) error {
  429. if len(args) > 1 {
  430. return fmt.Errorf("Invalid dpr arguments: %v", args)
  431. }
  432. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  433. po.Dpr = d
  434. } else {
  435. return fmt.Errorf("Invalid dpr: %s", args[0])
  436. }
  437. return nil
  438. }
  439. func applyGravityOption(po *processingOptions, args []string) error {
  440. return parseGravity(&po.Gravity, args)
  441. }
  442. func applyCropOption(po *processingOptions, args []string) error {
  443. if len(args) > 5 {
  444. return fmt.Errorf("Invalid crop arguments: %v", args)
  445. }
  446. if err := parseDimension(&po.Crop.Width, "crop width", args[0]); err != nil {
  447. return err
  448. }
  449. if len(args) > 1 {
  450. if err := parseDimension(&po.Crop.Height, "crop height", args[1]); err != nil {
  451. return err
  452. }
  453. }
  454. if len(args) > 2 {
  455. return parseGravity(&po.Crop.Gravity, args[2:])
  456. }
  457. return nil
  458. }
  459. func applyPaddingOption(po *processingOptions, args []string) error {
  460. nArgs := len(args)
  461. if nArgs < 1 || nArgs > 4 {
  462. return fmt.Errorf("Invalid padding arguments: %v", args)
  463. }
  464. po.Padding.Enabled = true
  465. if nArgs > 0 && len(args[0]) > 0 {
  466. if err := parseDimension(&po.Padding.Top, "padding top (+all)", args[0]); err != nil {
  467. return err
  468. }
  469. po.Padding.Right = po.Padding.Top
  470. po.Padding.Bottom = po.Padding.Top
  471. po.Padding.Left = po.Padding.Top
  472. }
  473. if nArgs > 1 && len(args[1]) > 0 {
  474. if err := parseDimension(&po.Padding.Right, "padding right (+left)", args[1]); err != nil {
  475. return err
  476. }
  477. po.Padding.Left = po.Padding.Right
  478. }
  479. if nArgs > 2 && len(args[2]) > 0 {
  480. if err := parseDimension(&po.Padding.Bottom, "padding bottom", args[2]); err != nil {
  481. return err
  482. }
  483. }
  484. if nArgs > 3 && len(args[3]) > 0 {
  485. if err := parseDimension(&po.Padding.Left, "padding left", args[3]); err != nil {
  486. return err
  487. }
  488. }
  489. if po.Padding.Top == 0 && po.Padding.Right == 0 && po.Padding.Bottom == 0 && po.Padding.Left == 0 {
  490. po.Padding.Enabled = false
  491. }
  492. return nil
  493. }
  494. func applyTrimOption(po *processingOptions, args []string) error {
  495. nArgs := len(args)
  496. if nArgs > 4 {
  497. return fmt.Errorf("Invalid trim arguments: %v", args)
  498. }
  499. if t, err := strconv.ParseFloat(args[0], 64); err == nil && t >= 0 {
  500. po.Trim.Enabled = true
  501. po.Trim.Threshold = t
  502. } else {
  503. return fmt.Errorf("Invalid trim threshold: %s", args[0])
  504. }
  505. if nArgs > 1 && len(args[1]) > 0 {
  506. if c, err := colorFromHex(args[1]); err == nil {
  507. po.Trim.Color = c
  508. po.Trim.Smart = false
  509. } else {
  510. return fmt.Errorf("Invalid trim color: %s", args[1])
  511. }
  512. }
  513. if nArgs > 2 && len(args[2]) > 0 {
  514. po.Trim.EqualHor = parseBoolOption(args[2])
  515. }
  516. if nArgs > 3 && len(args[3]) > 0 {
  517. po.Trim.EqualVer = parseBoolOption(args[3])
  518. }
  519. return nil
  520. }
  521. func applyQualityOption(po *processingOptions, args []string) error {
  522. if len(args) > 1 {
  523. return fmt.Errorf("Invalid quality arguments: %v", args)
  524. }
  525. if q, err := strconv.Atoi(args[0]); err == nil && q > 0 && q <= 100 {
  526. po.Quality = q
  527. } else {
  528. return fmt.Errorf("Invalid quality: %s", args[0])
  529. }
  530. return nil
  531. }
  532. func applyMaxBytesOption(po *processingOptions, args []string) error {
  533. if len(args) > 1 {
  534. return fmt.Errorf("Invalid max_bytes arguments: %v", args)
  535. }
  536. if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
  537. po.MaxBytes = max
  538. } else {
  539. return fmt.Errorf("Invalid max_bytes: %s", args[0])
  540. }
  541. return nil
  542. }
  543. func applyBackgroundOption(po *processingOptions, args []string) error {
  544. switch len(args) {
  545. case 1:
  546. if len(args[0]) == 0 {
  547. po.Flatten = false
  548. } else if c, err := colorFromHex(args[0]); err == nil {
  549. po.Flatten = true
  550. po.Background = c
  551. } else {
  552. return fmt.Errorf("Invalid background argument: %s", err)
  553. }
  554. case 3:
  555. po.Flatten = true
  556. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  557. po.Background.R = uint8(r)
  558. } else {
  559. return fmt.Errorf("Invalid background red channel: %s", args[0])
  560. }
  561. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  562. po.Background.G = uint8(g)
  563. } else {
  564. return fmt.Errorf("Invalid background green channel: %s", args[1])
  565. }
  566. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  567. po.Background.B = uint8(b)
  568. } else {
  569. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  570. }
  571. default:
  572. return fmt.Errorf("Invalid background arguments: %v", args)
  573. }
  574. return nil
  575. }
  576. func applyBlurOption(po *processingOptions, args []string) error {
  577. if len(args) > 1 {
  578. return fmt.Errorf("Invalid blur arguments: %v", args)
  579. }
  580. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  581. po.Blur = float32(b)
  582. } else {
  583. return fmt.Errorf("Invalid blur: %s", args[0])
  584. }
  585. return nil
  586. }
  587. func applySharpenOption(po *processingOptions, args []string) error {
  588. if len(args) > 1 {
  589. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  590. }
  591. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  592. po.Sharpen = float32(s)
  593. } else {
  594. return fmt.Errorf("Invalid sharpen: %s", args[0])
  595. }
  596. return nil
  597. }
  598. func applyPresetOption(po *processingOptions, args []string) error {
  599. for _, preset := range args {
  600. if p, ok := conf.Presets[preset]; ok {
  601. if po.isPresetUsed(preset) {
  602. logWarning("Recursive preset usage is detected: %s", preset)
  603. continue
  604. }
  605. po.presetUsed(preset)
  606. if err := applyProcessingOptions(po, p); err != nil {
  607. return err
  608. }
  609. } else {
  610. return fmt.Errorf("Unknown preset: %s", preset)
  611. }
  612. }
  613. return nil
  614. }
  615. func applyWatermarkOption(po *processingOptions, args []string) error {
  616. if len(args) > 7 {
  617. return fmt.Errorf("Invalid watermark arguments: %v", args)
  618. }
  619. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  620. po.Watermark.Enabled = o > 0
  621. po.Watermark.Opacity = o
  622. } else {
  623. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  624. }
  625. if len(args) > 1 && len(args[1]) > 0 {
  626. if args[1] == "re" {
  627. po.Watermark.Replicate = true
  628. } else if g, ok := gravityTypes[args[1]]; ok && g != gravityFocusPoint && g != gravitySmart {
  629. po.Watermark.Gravity.Type = g
  630. } else {
  631. return fmt.Errorf("Invalid watermark position: %s", args[1])
  632. }
  633. }
  634. if len(args) > 2 && len(args[2]) > 0 {
  635. if x, err := strconv.Atoi(args[2]); err == nil {
  636. po.Watermark.Gravity.X = float64(x)
  637. } else {
  638. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  639. }
  640. }
  641. if len(args) > 3 && len(args[3]) > 0 {
  642. if y, err := strconv.Atoi(args[3]); err == nil {
  643. po.Watermark.Gravity.Y = float64(y)
  644. } else {
  645. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  646. }
  647. }
  648. if len(args) > 4 && len(args[4]) > 0 {
  649. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  650. po.Watermark.Scale = s
  651. } else {
  652. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  653. }
  654. }
  655. return nil
  656. }
  657. func applyFormatOption(po *processingOptions, args []string) error {
  658. if len(args) > 1 {
  659. return fmt.Errorf("Invalid format arguments: %v", args)
  660. }
  661. if f, ok := imageTypes[args[0]]; ok {
  662. po.Format = f
  663. } else {
  664. return fmt.Errorf("Invalid image format: %s", args[0])
  665. }
  666. if !imageTypeSaveSupport(po.Format) {
  667. return fmt.Errorf("Resulting image format is not supported: %s", po.Format)
  668. }
  669. return nil
  670. }
  671. func applyCacheBusterOption(po *processingOptions, args []string) error {
  672. if len(args) > 1 {
  673. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  674. }
  675. po.CacheBuster = args[0]
  676. return nil
  677. }
  678. func applyFilenameOption(po *processingOptions, args []string) error {
  679. if len(args) > 1 {
  680. return fmt.Errorf("Invalid filename arguments: %v", args)
  681. }
  682. po.Filename = args[0]
  683. return nil
  684. }
  685. func applyStripMetadataOption(po *processingOptions, args []string) error {
  686. if len(args) > 1 {
  687. return fmt.Errorf("Invalid strip metadata arguments: %v", args)
  688. }
  689. po.StripMetadata = parseBoolOption(args[0])
  690. return nil
  691. }
  692. func applyProcessingOption(po *processingOptions, name string, args []string) error {
  693. switch name {
  694. case "format", "f", "ext":
  695. return applyFormatOption(po, args)
  696. case "resize", "rs":
  697. return applyResizeOption(po, args)
  698. case "resizing_type", "rt":
  699. return applyResizingTypeOption(po, args)
  700. case "size", "s":
  701. return applySizeOption(po, args)
  702. case "width", "w":
  703. return applyWidthOption(po, args)
  704. case "height", "h":
  705. return applyHeightOption(po, args)
  706. case "enlarge", "el":
  707. return applyEnlargeOption(po, args)
  708. case "extend", "ex":
  709. return applyExtendOption(po, args)
  710. case "dpr":
  711. return applyDprOption(po, args)
  712. case "gravity", "g":
  713. return applyGravityOption(po, args)
  714. case "crop", "c":
  715. return applyCropOption(po, args)
  716. case "trim", "t":
  717. return applyTrimOption(po, args)
  718. case "padding", "pd":
  719. return applyPaddingOption(po, args)
  720. case "quality", "q":
  721. return applyQualityOption(po, args)
  722. case "max_bytes", "mb":
  723. return applyMaxBytesOption(po, args)
  724. case "background", "bg":
  725. return applyBackgroundOption(po, args)
  726. case "blur", "bl":
  727. return applyBlurOption(po, args)
  728. case "sharpen", "sh":
  729. return applySharpenOption(po, args)
  730. case "watermark", "wm":
  731. return applyWatermarkOption(po, args)
  732. case "preset", "pr":
  733. return applyPresetOption(po, args)
  734. case "cachebuster", "cb":
  735. return applyCacheBusterOption(po, args)
  736. case "strip_metadata", "sm":
  737. return applyStripMetadataOption(po, args)
  738. case "filename", "fn":
  739. return applyFilenameOption(po, args)
  740. }
  741. return fmt.Errorf("Unknown processing option: %s", name)
  742. }
  743. func applyProcessingOptions(po *processingOptions, options urlOptions) error {
  744. for _, opt := range options {
  745. if err := applyProcessingOption(po, opt.Name, opt.Args); err != nil {
  746. return err
  747. }
  748. }
  749. return nil
  750. }
  751. func isAllowedSource(imageURL string) bool {
  752. if len(conf.AllowedSources) == 0 {
  753. return true
  754. }
  755. for _, val := range conf.AllowedSources {
  756. if strings.HasPrefix(imageURL, string(val)) {
  757. return true
  758. }
  759. }
  760. return false
  761. }
  762. func parseURLOptions(opts []string) (urlOptions, []string) {
  763. parsed := make(urlOptions, 0, len(opts))
  764. urlStart := len(opts) + 1
  765. for i, opt := range opts {
  766. args := strings.Split(opt, ":")
  767. if len(args) == 1 {
  768. urlStart = i
  769. break
  770. }
  771. parsed = append(parsed, urlOption{Name: args[0], Args: args[1:]})
  772. }
  773. var rest []string
  774. if urlStart < len(opts) {
  775. rest = opts[urlStart:]
  776. } else {
  777. rest = []string{}
  778. }
  779. return parsed, rest
  780. }
  781. func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, error) {
  782. po := newProcessingOptions()
  783. if strings.Contains(headers.Accept, "image/webp") {
  784. po.PreferWebP = conf.EnableWebpDetection || conf.EnforceWebp
  785. po.EnforceWebP = conf.EnforceWebp
  786. }
  787. if conf.EnableClientHints && len(headers.ViewportWidth) > 0 {
  788. if vw, err := strconv.Atoi(headers.ViewportWidth); err == nil {
  789. po.Width = vw
  790. }
  791. }
  792. if conf.EnableClientHints && len(headers.Width) > 0 {
  793. if w, err := strconv.Atoi(headers.Width); err == nil {
  794. po.Width = w
  795. }
  796. }
  797. if conf.EnableClientHints && len(headers.DPR) > 0 {
  798. if dpr, err := strconv.ParseFloat(headers.DPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  799. po.Dpr = dpr
  800. }
  801. }
  802. if _, ok := conf.Presets["default"]; ok {
  803. if err := applyPresetOption(po, []string{"default"}); err != nil {
  804. return po, err
  805. }
  806. }
  807. return po, nil
  808. }
  809. func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  810. po, err := defaultProcessingOptions(headers)
  811. if err != nil {
  812. return "", po, err
  813. }
  814. options, urlParts := parseURLOptions(parts)
  815. if err = applyProcessingOptions(po, options); err != nil {
  816. return "", po, err
  817. }
  818. url, extension, err := decodeURL(urlParts)
  819. if err != nil {
  820. return "", po, err
  821. }
  822. if len(extension) > 0 {
  823. if err = applyFormatOption(po, []string{extension}); err != nil {
  824. return "", po, err
  825. }
  826. }
  827. return url, po, nil
  828. }
  829. func parsePathPresets(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  830. po, err := defaultProcessingOptions(headers)
  831. if err != nil {
  832. return "", po, err
  833. }
  834. presets := strings.Split(parts[0], ":")
  835. urlParts := parts[1:]
  836. if err = applyPresetOption(po, presets); err != nil {
  837. return "", nil, err
  838. }
  839. url, extension, err := decodeURL(urlParts)
  840. if err != nil {
  841. return "", po, err
  842. }
  843. if len(extension) > 0 {
  844. if err = applyFormatOption(po, []string{extension}); err != nil {
  845. return "", po, err
  846. }
  847. }
  848. return url, po, nil
  849. }
  850. func parsePathBasic(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  851. if len(parts) < 6 {
  852. return "", nil, fmt.Errorf("Invalid basic URL format arguments: %s", strings.Join(parts, "/"))
  853. }
  854. po, err := defaultProcessingOptions(headers)
  855. if err != nil {
  856. return "", po, err
  857. }
  858. po.ResizingType = resizeTypes[parts[0]]
  859. if err = applyWidthOption(po, parts[1:2]); err != nil {
  860. return "", po, err
  861. }
  862. if err = applyHeightOption(po, parts[2:3]); err != nil {
  863. return "", po, err
  864. }
  865. if err = applyGravityOption(po, strings.Split(parts[3], ":")); err != nil {
  866. return "", po, err
  867. }
  868. if err = applyEnlargeOption(po, parts[4:5]); err != nil {
  869. return "", po, err
  870. }
  871. url, extension, err := decodeURL(parts[5:])
  872. if err != nil {
  873. return "", po, err
  874. }
  875. if len(extension) > 0 {
  876. if err := applyFormatOption(po, []string{extension}); err != nil {
  877. return "", po, err
  878. }
  879. }
  880. return url, po, nil
  881. }
  882. func parsePath(ctx context.Context, r *http.Request) (context.Context, error) {
  883. var err error
  884. path := trimAfter(r.RequestURI, '?')
  885. if len(conf.PathPrefix) > 0 {
  886. path = strings.TrimPrefix(path, conf.PathPrefix)
  887. }
  888. path = strings.TrimPrefix(path, "/")
  889. parts := strings.Split(path, "/")
  890. if len(parts) < 2 {
  891. return ctx, newError(404, fmt.Sprintf("Invalid path: %s", path), msgInvalidURL)
  892. }
  893. if !conf.AllowInsecure {
  894. if err = validatePath(parts[0], strings.TrimPrefix(path, parts[0])); err != nil {
  895. return ctx, newError(403, err.Error(), msgForbidden)
  896. }
  897. }
  898. headers := &processingHeaders{
  899. Accept: r.Header.Get("Accept"),
  900. Width: r.Header.Get("Width"),
  901. ViewportWidth: r.Header.Get("Viewport-Width"),
  902. DPR: r.Header.Get("DPR"),
  903. }
  904. var imageURL string
  905. var po *processingOptions
  906. if conf.OnlyPresets {
  907. imageURL, po, err = parsePathPresets(parts[1:], headers)
  908. } else if _, ok := resizeTypes[parts[1]]; ok {
  909. imageURL, po, err = parsePathBasic(parts[1:], headers)
  910. } else {
  911. imageURL, po, err = parsePathAdvanced(parts[1:], headers)
  912. }
  913. if err != nil {
  914. return ctx, newError(404, err.Error(), msgInvalidURL)
  915. }
  916. if !isAllowedSource(imageURL) {
  917. return ctx, newError(404, "Invalid source", msgInvalidSource)
  918. }
  919. ctx = context.WithValue(ctx, imageURLCtxKey, imageURL)
  920. ctx = context.WithValue(ctx, processingOptionsCtxKey, po)
  921. return ctx, nil
  922. }
  923. func getImageURL(ctx context.Context) string {
  924. str, _ := ctx.Value(imageURLCtxKey).(string)
  925. return str
  926. }
  927. func getProcessingOptions(ctx context.Context) *processingOptions {
  928. return ctx.Value(processingOptionsCtxKey).(*processingOptions)
  929. }