processing_options.go 25 KB

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