1
0

processing_options.go 27 KB

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