processing_options.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. package options
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "slices"
  8. "strconv"
  9. "strings"
  10. "time"
  11. log "github.com/sirupsen/logrus"
  12. "github.com/imgproxy/imgproxy/v3/config"
  13. "github.com/imgproxy/imgproxy/v3/ierrors"
  14. "github.com/imgproxy/imgproxy/v3/imagetype"
  15. "github.com/imgproxy/imgproxy/v3/imath"
  16. "github.com/imgproxy/imgproxy/v3/security"
  17. "github.com/imgproxy/imgproxy/v3/structdiff"
  18. "github.com/imgproxy/imgproxy/v3/vips"
  19. )
  20. const maxClientHintDPR = 8
  21. var errExpiredURL = errors.New("Expired URL")
  22. type ExtendOptions struct {
  23. Enabled bool
  24. Gravity GravityOptions
  25. }
  26. type CropOptions struct {
  27. Width float64
  28. Height float64
  29. Gravity GravityOptions
  30. }
  31. type PaddingOptions struct {
  32. Enabled bool
  33. Top int
  34. Right int
  35. Bottom int
  36. Left int
  37. }
  38. type TrimOptions struct {
  39. Enabled bool
  40. Threshold float64
  41. Smart bool
  42. Color vips.Color
  43. EqualHor bool
  44. EqualVer bool
  45. }
  46. type WatermarkOptions struct {
  47. Enabled bool
  48. Opacity float64
  49. Position GravityOptions
  50. Scale float64
  51. }
  52. func (wo WatermarkOptions) ShouldReplicate() bool {
  53. return wo.Position.Type == GravityReplicate
  54. }
  55. type ProcessingOptions struct {
  56. ResizingType ResizeType
  57. Width int
  58. Height int
  59. MinWidth int
  60. MinHeight int
  61. ZoomWidth float64
  62. ZoomHeight float64
  63. Dpr float64
  64. Gravity GravityOptions
  65. Enlarge bool
  66. Extend ExtendOptions
  67. ExtendAspectRatio ExtendOptions
  68. Crop CropOptions
  69. Padding PaddingOptions
  70. Trim TrimOptions
  71. Rotate int
  72. Format imagetype.Type
  73. Quality int
  74. FormatQuality map[imagetype.Type]int
  75. MaxBytes int
  76. Flatten bool
  77. Background vips.Color
  78. Blur float32
  79. Sharpen float32
  80. Pixelate int
  81. StripMetadata bool
  82. KeepCopyright bool
  83. StripColorProfile bool
  84. AutoRotate bool
  85. EnforceThumbnail bool
  86. SkipProcessingFormats []imagetype.Type
  87. CacheBuster string
  88. Expires *time.Time
  89. Watermark WatermarkOptions
  90. PreferWebP bool
  91. EnforceWebP bool
  92. PreferAvif bool
  93. EnforceAvif bool
  94. Filename string
  95. ReturnAttachment bool
  96. Raw bool
  97. UsedPresets []string
  98. SecurityOptions security.Options
  99. defaultQuality int
  100. }
  101. func NewProcessingOptions() *ProcessingOptions {
  102. po := ProcessingOptions{
  103. ResizingType: ResizeFit,
  104. Width: 0,
  105. Height: 0,
  106. ZoomWidth: 1,
  107. ZoomHeight: 1,
  108. Gravity: GravityOptions{Type: GravityCenter},
  109. Enlarge: false,
  110. Extend: ExtendOptions{Enabled: false, Gravity: GravityOptions{Type: GravityCenter}},
  111. ExtendAspectRatio: ExtendOptions{Enabled: false, Gravity: GravityOptions{Type: GravityCenter}},
  112. Padding: PaddingOptions{Enabled: false},
  113. Trim: TrimOptions{Enabled: false, Threshold: 10, Smart: true},
  114. Rotate: 0,
  115. Quality: 0,
  116. MaxBytes: 0,
  117. Format: imagetype.Unknown,
  118. Background: vips.Color{R: 255, G: 255, B: 255},
  119. Blur: 0,
  120. Sharpen: 0,
  121. Dpr: 1,
  122. Watermark: WatermarkOptions{Opacity: 1, Position: GravityOptions{Type: GravityCenter}},
  123. StripMetadata: config.StripMetadata,
  124. KeepCopyright: config.KeepCopyright,
  125. StripColorProfile: config.StripColorProfile,
  126. AutoRotate: config.AutoRotate,
  127. EnforceThumbnail: config.EnforceThumbnail,
  128. ReturnAttachment: config.ReturnAttachment,
  129. SkipProcessingFormats: append([]imagetype.Type(nil), config.SkipProcessingFormats...),
  130. UsedPresets: make([]string, 0, len(config.Presets)),
  131. SecurityOptions: security.DefaultOptions(),
  132. // Basically, we need this to update ETag when `IMGPROXY_QUALITY` is changed
  133. defaultQuality: config.Quality,
  134. }
  135. po.FormatQuality = make(map[imagetype.Type]int, len(config.FormatQuality))
  136. for k, v := range config.FormatQuality {
  137. po.FormatQuality[k] = v
  138. }
  139. return &po
  140. }
  141. func (po *ProcessingOptions) GetQuality() int {
  142. q := po.Quality
  143. if q == 0 {
  144. q = po.FormatQuality[po.Format]
  145. }
  146. if q == 0 {
  147. q = po.defaultQuality
  148. }
  149. return q
  150. }
  151. func (po *ProcessingOptions) Diff() structdiff.Entries {
  152. return structdiff.Diff(NewProcessingOptions(), po)
  153. }
  154. func (po *ProcessingOptions) String() string {
  155. return po.Diff().String()
  156. }
  157. func (po *ProcessingOptions) MarshalJSON() ([]byte, error) {
  158. return po.Diff().MarshalJSON()
  159. }
  160. func parseDimension(d *int, name, arg string) error {
  161. if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
  162. *d = v
  163. } else {
  164. return fmt.Errorf("Invalid %s: %s", name, arg)
  165. }
  166. return nil
  167. }
  168. func parseBoolOption(str string) bool {
  169. b, err := strconv.ParseBool(str)
  170. if err != nil {
  171. log.Warningf("`%s` is not a valid boolean value. Treated as false", str)
  172. }
  173. return b
  174. }
  175. func isGravityOffcetValid(gravity GravityType, offset float64) bool {
  176. return gravity != GravityFocusPoint || (offset >= 0 && offset <= 1)
  177. }
  178. func parseGravity(g *GravityOptions, name string, args []string, allowedTypes []GravityType) error {
  179. nArgs := len(args)
  180. if t, ok := gravityTypes[args[0]]; ok && slices.Contains(allowedTypes, t) {
  181. g.Type = t
  182. } else {
  183. return fmt.Errorf("Invalid %s: %s", name, args[0])
  184. }
  185. switch g.Type {
  186. case GravitySmart:
  187. if nArgs > 1 {
  188. return fmt.Errorf("Invalid %s arguments: %v", name, args)
  189. }
  190. g.X, g.Y = 0.0, 0.0
  191. case GravityFocusPoint:
  192. if nArgs != 3 {
  193. return fmt.Errorf("Invalid %s arguments: %v", name, args)
  194. }
  195. fallthrough
  196. default:
  197. if nArgs > 3 {
  198. return fmt.Errorf("Invalid %s arguments: %v", name, args)
  199. }
  200. if nArgs > 1 {
  201. if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
  202. g.X = x
  203. } else {
  204. return fmt.Errorf("Invalid %s X: %s", name, args[1])
  205. }
  206. }
  207. if nArgs > 2 {
  208. if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
  209. g.Y = y
  210. } else {
  211. return fmt.Errorf("Invalid %s Y: %s", name, args[2])
  212. }
  213. }
  214. }
  215. return nil
  216. }
  217. func parseExtend(opts *ExtendOptions, name string, args []string) error {
  218. if len(args) > 4 {
  219. return fmt.Errorf("Invalid %s arguments: %v", name, args)
  220. }
  221. opts.Enabled = parseBoolOption(args[0])
  222. if len(args) > 1 {
  223. if err := parseGravity(&opts.Gravity, name+" gravity", args[1:], extendGravityTypes); err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. func applyWidthOption(po *ProcessingOptions, args []string) error {
  230. if len(args) > 1 {
  231. return fmt.Errorf("Invalid width arguments: %v", args)
  232. }
  233. return parseDimension(&po.Width, "width", args[0])
  234. }
  235. func applyHeightOption(po *ProcessingOptions, args []string) error {
  236. if len(args) > 1 {
  237. return fmt.Errorf("Invalid height arguments: %v", args)
  238. }
  239. return parseDimension(&po.Height, "height", args[0])
  240. }
  241. func applyMinWidthOption(po *ProcessingOptions, args []string) error {
  242. if len(args) > 1 {
  243. return fmt.Errorf("Invalid min width arguments: %v", args)
  244. }
  245. return parseDimension(&po.MinWidth, "min width", args[0])
  246. }
  247. func applyMinHeightOption(po *ProcessingOptions, args []string) error {
  248. if len(args) > 1 {
  249. return fmt.Errorf("Invalid min height arguments: %v", args)
  250. }
  251. return parseDimension(&po.MinHeight, " min height", args[0])
  252. }
  253. func applyEnlargeOption(po *ProcessingOptions, args []string) error {
  254. if len(args) > 1 {
  255. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  256. }
  257. po.Enlarge = parseBoolOption(args[0])
  258. return nil
  259. }
  260. func applyExtendOption(po *ProcessingOptions, args []string) error {
  261. return parseExtend(&po.Extend, "extend", args)
  262. }
  263. func applyExtendAspectRatioOption(po *ProcessingOptions, args []string) error {
  264. return parseExtend(&po.ExtendAspectRatio, "extend_aspect_ratio", args)
  265. }
  266. func applySizeOption(po *ProcessingOptions, args []string) (err error) {
  267. if len(args) > 7 {
  268. return fmt.Errorf("Invalid size arguments: %v", args)
  269. }
  270. if len(args) >= 1 && len(args[0]) > 0 {
  271. if err = applyWidthOption(po, args[0:1]); err != nil {
  272. return
  273. }
  274. }
  275. if len(args) >= 2 && len(args[1]) > 0 {
  276. if err = applyHeightOption(po, args[1:2]); err != nil {
  277. return
  278. }
  279. }
  280. if len(args) >= 3 && len(args[2]) > 0 {
  281. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  282. return
  283. }
  284. }
  285. if len(args) >= 4 && len(args[3]) > 0 {
  286. if err = applyExtendOption(po, args[3:]); err != nil {
  287. return
  288. }
  289. }
  290. return nil
  291. }
  292. func applyResizingTypeOption(po *ProcessingOptions, args []string) error {
  293. if len(args) > 1 {
  294. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  295. }
  296. if r, ok := resizeTypes[args[0]]; ok {
  297. po.ResizingType = r
  298. } else {
  299. return fmt.Errorf("Invalid resize type: %s", args[0])
  300. }
  301. return nil
  302. }
  303. func applyResizeOption(po *ProcessingOptions, args []string) error {
  304. if len(args) > 8 {
  305. return fmt.Errorf("Invalid resize arguments: %v", args)
  306. }
  307. if len(args[0]) > 0 {
  308. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  309. return err
  310. }
  311. }
  312. if len(args) > 1 {
  313. if err := applySizeOption(po, args[1:]); err != nil {
  314. return err
  315. }
  316. }
  317. return nil
  318. }
  319. func applyZoomOption(po *ProcessingOptions, args []string) error {
  320. nArgs := len(args)
  321. if nArgs > 2 {
  322. return fmt.Errorf("Invalid zoom arguments: %v", args)
  323. }
  324. if z, err := strconv.ParseFloat(args[0], 64); err == nil && z > 0 {
  325. po.ZoomWidth = z
  326. po.ZoomHeight = z
  327. } else {
  328. return fmt.Errorf("Invalid zoom value: %s", args[0])
  329. }
  330. if nArgs > 1 {
  331. if z, err := strconv.ParseFloat(args[1], 64); err == nil && z > 0 {
  332. po.ZoomHeight = z
  333. } else {
  334. return fmt.Errorf("Invalid zoom value: %s", args[0])
  335. }
  336. }
  337. return nil
  338. }
  339. func applyDprOption(po *ProcessingOptions, args []string) error {
  340. if len(args) > 1 {
  341. return fmt.Errorf("Invalid dpr arguments: %v", args)
  342. }
  343. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  344. po.Dpr = d
  345. } else {
  346. return fmt.Errorf("Invalid dpr: %s", args[0])
  347. }
  348. return nil
  349. }
  350. func applyGravityOption(po *ProcessingOptions, args []string) error {
  351. if err := parseGravity(&po.Gravity, "gravity", args, cropGravityTypes); err != nil {
  352. return err
  353. }
  354. return nil
  355. }
  356. func applyCropOption(po *ProcessingOptions, args []string) error {
  357. if w, err := strconv.ParseFloat(args[0], 64); err == nil && w >= 0 {
  358. po.Crop.Width = w
  359. } else {
  360. return fmt.Errorf("Invalid crop width: %s", args[0])
  361. }
  362. if len(args) > 1 {
  363. if h, err := strconv.ParseFloat(args[1], 64); err == nil && h >= 0 {
  364. po.Crop.Height = h
  365. } else {
  366. return fmt.Errorf("Invalid crop height: %s", args[1])
  367. }
  368. }
  369. if len(args) > 2 {
  370. if err := parseGravity(&po.Crop.Gravity, "crop gravity", args[2:], cropGravityTypes); err != nil {
  371. return err
  372. }
  373. }
  374. return nil
  375. }
  376. func applyPaddingOption(po *ProcessingOptions, args []string) error {
  377. nArgs := len(args)
  378. if nArgs < 1 || nArgs > 4 {
  379. return fmt.Errorf("Invalid padding arguments: %v", args)
  380. }
  381. po.Padding.Enabled = true
  382. if nArgs > 0 && len(args[0]) > 0 {
  383. if err := parseDimension(&po.Padding.Top, "padding top (+all)", args[0]); err != nil {
  384. return err
  385. }
  386. po.Padding.Right = po.Padding.Top
  387. po.Padding.Bottom = po.Padding.Top
  388. po.Padding.Left = po.Padding.Top
  389. }
  390. if nArgs > 1 && len(args[1]) > 0 {
  391. if err := parseDimension(&po.Padding.Right, "padding right (+left)", args[1]); err != nil {
  392. return err
  393. }
  394. po.Padding.Left = po.Padding.Right
  395. }
  396. if nArgs > 2 && len(args[2]) > 0 {
  397. if err := parseDimension(&po.Padding.Bottom, "padding bottom", args[2]); err != nil {
  398. return err
  399. }
  400. }
  401. if nArgs > 3 && len(args[3]) > 0 {
  402. if err := parseDimension(&po.Padding.Left, "padding left", args[3]); err != nil {
  403. return err
  404. }
  405. }
  406. if po.Padding.Top == 0 && po.Padding.Right == 0 && po.Padding.Bottom == 0 && po.Padding.Left == 0 {
  407. po.Padding.Enabled = false
  408. }
  409. return nil
  410. }
  411. func applyTrimOption(po *ProcessingOptions, args []string) error {
  412. nArgs := len(args)
  413. if nArgs > 4 {
  414. return fmt.Errorf("Invalid trim arguments: %v", args)
  415. }
  416. if t, err := strconv.ParseFloat(args[0], 64); err == nil && t >= 0 {
  417. po.Trim.Enabled = true
  418. po.Trim.Threshold = t
  419. } else {
  420. return fmt.Errorf("Invalid trim threshold: %s", args[0])
  421. }
  422. if nArgs > 1 && len(args[1]) > 0 {
  423. if c, err := vips.ColorFromHex(args[1]); err == nil {
  424. po.Trim.Color = c
  425. po.Trim.Smart = false
  426. } else {
  427. return fmt.Errorf("Invalid trim color: %s", args[1])
  428. }
  429. }
  430. if nArgs > 2 && len(args[2]) > 0 {
  431. po.Trim.EqualHor = parseBoolOption(args[2])
  432. }
  433. if nArgs > 3 && len(args[3]) > 0 {
  434. po.Trim.EqualVer = parseBoolOption(args[3])
  435. }
  436. return nil
  437. }
  438. func applyRotateOption(po *ProcessingOptions, args []string) error {
  439. if len(args) > 1 {
  440. return fmt.Errorf("Invalid rotate arguments: %v", args)
  441. }
  442. if r, err := strconv.Atoi(args[0]); err == nil && r%90 == 0 {
  443. po.Rotate = r
  444. } else {
  445. return fmt.Errorf("Invalid rotation angle: %s", args[0])
  446. }
  447. return nil
  448. }
  449. func applyQualityOption(po *ProcessingOptions, args []string) error {
  450. if len(args) > 1 {
  451. return fmt.Errorf("Invalid quality arguments: %v", args)
  452. }
  453. if q, err := strconv.Atoi(args[0]); err == nil && q >= 0 && q <= 100 {
  454. po.Quality = q
  455. } else {
  456. return fmt.Errorf("Invalid quality: %s", args[0])
  457. }
  458. return nil
  459. }
  460. func applyFormatQualityOption(po *ProcessingOptions, args []string) error {
  461. argsLen := len(args)
  462. if len(args)%2 != 0 {
  463. return fmt.Errorf("Missing quality for: %s", args[argsLen-1])
  464. }
  465. for i := 0; i < argsLen; i += 2 {
  466. f, ok := imagetype.Types[args[i]]
  467. if !ok {
  468. return fmt.Errorf("Invalid image format: %s", args[i])
  469. }
  470. if q, err := strconv.Atoi(args[i+1]); err == nil && q >= 0 && q <= 100 {
  471. po.FormatQuality[f] = q
  472. } else {
  473. return fmt.Errorf("Invalid quality for %s: %s", args[i], args[i+1])
  474. }
  475. }
  476. return nil
  477. }
  478. func applyMaxBytesOption(po *ProcessingOptions, args []string) error {
  479. if len(args) > 1 {
  480. return fmt.Errorf("Invalid max_bytes arguments: %v", args)
  481. }
  482. if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
  483. po.MaxBytes = max
  484. } else {
  485. return fmt.Errorf("Invalid max_bytes: %s", args[0])
  486. }
  487. return nil
  488. }
  489. func applyBackgroundOption(po *ProcessingOptions, args []string) error {
  490. switch len(args) {
  491. case 1:
  492. if len(args[0]) == 0 {
  493. po.Flatten = false
  494. } else if c, err := vips.ColorFromHex(args[0]); err == nil {
  495. po.Flatten = true
  496. po.Background = c
  497. } else {
  498. return fmt.Errorf("Invalid background argument: %s", err)
  499. }
  500. case 3:
  501. po.Flatten = true
  502. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  503. po.Background.R = uint8(r)
  504. } else {
  505. return fmt.Errorf("Invalid background red channel: %s", args[0])
  506. }
  507. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  508. po.Background.G = uint8(g)
  509. } else {
  510. return fmt.Errorf("Invalid background green channel: %s", args[1])
  511. }
  512. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  513. po.Background.B = uint8(b)
  514. } else {
  515. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  516. }
  517. default:
  518. return fmt.Errorf("Invalid background arguments: %v", args)
  519. }
  520. return nil
  521. }
  522. func applyBlurOption(po *ProcessingOptions, args []string) error {
  523. if len(args) > 1 {
  524. return fmt.Errorf("Invalid blur arguments: %v", args)
  525. }
  526. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  527. po.Blur = float32(b)
  528. } else {
  529. return fmt.Errorf("Invalid blur: %s", args[0])
  530. }
  531. return nil
  532. }
  533. func applySharpenOption(po *ProcessingOptions, args []string) error {
  534. if len(args) > 1 {
  535. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  536. }
  537. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  538. po.Sharpen = float32(s)
  539. } else {
  540. return fmt.Errorf("Invalid sharpen: %s", args[0])
  541. }
  542. return nil
  543. }
  544. func applyPixelateOption(po *ProcessingOptions, args []string) error {
  545. if len(args) > 1 {
  546. return fmt.Errorf("Invalid pixelate arguments: %v", args)
  547. }
  548. if p, err := strconv.Atoi(args[0]); err == nil && p >= 0 {
  549. po.Pixelate = p
  550. } else {
  551. return fmt.Errorf("Invalid pixelate: %s", args[0])
  552. }
  553. return nil
  554. }
  555. func applyPresetOption(po *ProcessingOptions, args []string, usedPresets ...string) error {
  556. for _, preset := range args {
  557. if p, ok := presets[preset]; ok {
  558. if slices.Contains(usedPresets, preset) {
  559. log.Warningf("Recursive preset usage is detected: %s", preset)
  560. continue
  561. }
  562. po.UsedPresets = append(po.UsedPresets, preset)
  563. if err := applyURLOptions(po, p, append(usedPresets, preset)...); err != nil {
  564. return err
  565. }
  566. } else {
  567. return fmt.Errorf("Unknown preset: %s", preset)
  568. }
  569. }
  570. return nil
  571. }
  572. func applyWatermarkOption(po *ProcessingOptions, args []string) error {
  573. if len(args) > 7 {
  574. return fmt.Errorf("Invalid watermark arguments: %v", args)
  575. }
  576. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  577. po.Watermark.Enabled = o > 0
  578. po.Watermark.Opacity = o
  579. } else {
  580. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  581. }
  582. if len(args) > 1 && len(args[1]) > 0 {
  583. if g, ok := gravityTypes[args[1]]; ok && slices.Contains(watermarkGravityTypes, g) {
  584. po.Watermark.Position.Type = g
  585. } else {
  586. return fmt.Errorf("Invalid watermark position: %s", args[1])
  587. }
  588. }
  589. if len(args) > 2 && len(args[2]) > 0 {
  590. if x, err := strconv.ParseFloat(args[2], 64); err == nil {
  591. po.Watermark.Position.X = x
  592. } else {
  593. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  594. }
  595. }
  596. if len(args) > 3 && len(args[3]) > 0 {
  597. if y, err := strconv.ParseFloat(args[3], 64); err == nil {
  598. po.Watermark.Position.Y = y
  599. } else {
  600. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  601. }
  602. }
  603. if len(args) > 4 && len(args[4]) > 0 {
  604. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  605. po.Watermark.Scale = s
  606. } else {
  607. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  608. }
  609. }
  610. return nil
  611. }
  612. func applyFormatOption(po *ProcessingOptions, args []string) error {
  613. if len(args) > 1 {
  614. return fmt.Errorf("Invalid format arguments: %v", args)
  615. }
  616. if f, ok := imagetype.Types[args[0]]; ok {
  617. po.Format = f
  618. } else {
  619. return fmt.Errorf("Invalid image format: %s", args[0])
  620. }
  621. return nil
  622. }
  623. func applyCacheBusterOption(po *ProcessingOptions, args []string) error {
  624. if len(args) > 1 {
  625. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  626. }
  627. po.CacheBuster = args[0]
  628. return nil
  629. }
  630. func applySkipProcessingFormatsOption(po *ProcessingOptions, args []string) error {
  631. for _, format := range args {
  632. if f, ok := imagetype.Types[format]; ok {
  633. po.SkipProcessingFormats = append(po.SkipProcessingFormats, f)
  634. } else {
  635. return fmt.Errorf("Invalid image format in skip processing: %s", format)
  636. }
  637. }
  638. return nil
  639. }
  640. func applyRawOption(po *ProcessingOptions, args []string) error {
  641. if len(args) > 1 {
  642. return fmt.Errorf("Invalid return_attachment arguments: %v", args)
  643. }
  644. po.Raw = parseBoolOption(args[0])
  645. return nil
  646. }
  647. func applyFilenameOption(po *ProcessingOptions, args []string) error {
  648. if len(args) > 2 {
  649. return fmt.Errorf("Invalid filename arguments: %v", args)
  650. }
  651. po.Filename = args[0]
  652. if len(args) > 1 && parseBoolOption(args[1]) {
  653. decoded, err := base64.RawURLEncoding.DecodeString(po.Filename)
  654. if err != nil {
  655. return fmt.Errorf("Invalid filename encoding: %s", err)
  656. }
  657. po.Filename = string(decoded)
  658. }
  659. return nil
  660. }
  661. func applyExpiresOption(po *ProcessingOptions, args []string) error {
  662. if len(args) > 1 {
  663. return fmt.Errorf("Invalid expires arguments: %v", args)
  664. }
  665. timestamp, err := strconv.ParseInt(args[0], 10, 64)
  666. if err != nil {
  667. return fmt.Errorf("Invalid expires argument: %v", args[0])
  668. }
  669. if timestamp > 0 && timestamp < time.Now().Unix() {
  670. return errExpiredURL
  671. }
  672. expires := time.Unix(timestamp, 0)
  673. po.Expires = &expires
  674. return nil
  675. }
  676. func applyStripMetadataOption(po *ProcessingOptions, args []string) error {
  677. if len(args) > 1 {
  678. return fmt.Errorf("Invalid strip metadata arguments: %v", args)
  679. }
  680. po.StripMetadata = parseBoolOption(args[0])
  681. return nil
  682. }
  683. func applyKeepCopyrightOption(po *ProcessingOptions, args []string) error {
  684. if len(args) > 1 {
  685. return fmt.Errorf("Invalid keep copyright arguments: %v", args)
  686. }
  687. po.KeepCopyright = parseBoolOption(args[0])
  688. return nil
  689. }
  690. func applyStripColorProfileOption(po *ProcessingOptions, args []string) error {
  691. if len(args) > 1 {
  692. return fmt.Errorf("Invalid strip color profile arguments: %v", args)
  693. }
  694. po.StripColorProfile = parseBoolOption(args[0])
  695. return nil
  696. }
  697. func applyAutoRotateOption(po *ProcessingOptions, args []string) error {
  698. if len(args) > 1 {
  699. return fmt.Errorf("Invalid auto rotate arguments: %v", args)
  700. }
  701. po.AutoRotate = parseBoolOption(args[0])
  702. return nil
  703. }
  704. func applyEnforceThumbnailOption(po *ProcessingOptions, args []string) error {
  705. if len(args) > 1 {
  706. return fmt.Errorf("Invalid enforce thumbnail arguments: %v", args)
  707. }
  708. po.EnforceThumbnail = parseBoolOption(args[0])
  709. return nil
  710. }
  711. func applyReturnAttachmentOption(po *ProcessingOptions, args []string) error {
  712. if len(args) > 1 {
  713. return fmt.Errorf("Invalid return_attachment arguments: %v", args)
  714. }
  715. po.ReturnAttachment = parseBoolOption(args[0])
  716. return nil
  717. }
  718. func applyMaxSrcResolutionOption(po *ProcessingOptions, args []string) error {
  719. if err := security.IsSecurityOptionsAllowed(); err != nil {
  720. return err
  721. }
  722. if len(args) > 1 {
  723. return fmt.Errorf("Invalid max_src_resolution arguments: %v", args)
  724. }
  725. if x, err := strconv.ParseFloat(args[0], 64); err == nil && x > 0 {
  726. po.SecurityOptions.MaxSrcResolution = int(x * 1000000)
  727. } else {
  728. return fmt.Errorf("Invalid max_src_resolution: %s", args[0])
  729. }
  730. return nil
  731. }
  732. func applyMaxSrcFileSizeOption(po *ProcessingOptions, args []string) error {
  733. if err := security.IsSecurityOptionsAllowed(); err != nil {
  734. return err
  735. }
  736. if len(args) > 1 {
  737. return fmt.Errorf("Invalid max_src_file_size arguments: %v", args)
  738. }
  739. if x, err := strconv.Atoi(args[0]); err == nil {
  740. po.SecurityOptions.MaxSrcFileSize = x
  741. } else {
  742. return fmt.Errorf("Invalid max_src_file_size: %s", args[0])
  743. }
  744. return nil
  745. }
  746. func applyMaxAnimationFramesOption(po *ProcessingOptions, args []string) error {
  747. if err := security.IsSecurityOptionsAllowed(); err != nil {
  748. return err
  749. }
  750. if len(args) > 1 {
  751. return fmt.Errorf("Invalid max_animation_frames arguments: %v", args)
  752. }
  753. if x, err := strconv.Atoi(args[0]); err == nil && x > 0 {
  754. po.SecurityOptions.MaxAnimationFrames = x
  755. } else {
  756. return fmt.Errorf("Invalid max_animation_frames: %s", args[0])
  757. }
  758. return nil
  759. }
  760. func applyMaxAnimationFrameResolutionOption(po *ProcessingOptions, args []string) error {
  761. if err := security.IsSecurityOptionsAllowed(); err != nil {
  762. return err
  763. }
  764. if len(args) > 1 {
  765. return fmt.Errorf("Invalid max_animation_frame_resolution arguments: %v", args)
  766. }
  767. if x, err := strconv.ParseFloat(args[0], 64); err == nil {
  768. po.SecurityOptions.MaxAnimationFrameResolution = int(x * 1000000)
  769. } else {
  770. return fmt.Errorf("Invalid max_animation_frame_resolution: %s", args[0])
  771. }
  772. return nil
  773. }
  774. func applyURLOption(po *ProcessingOptions, name string, args []string, usedPresets ...string) error {
  775. switch name {
  776. case "resize", "rs":
  777. return applyResizeOption(po, args)
  778. case "size", "s":
  779. return applySizeOption(po, args)
  780. case "resizing_type", "rt":
  781. return applyResizingTypeOption(po, args)
  782. case "width", "w":
  783. return applyWidthOption(po, args)
  784. case "height", "h":
  785. return applyHeightOption(po, args)
  786. case "min-width", "mw":
  787. return applyMinWidthOption(po, args)
  788. case "min-height", "mh":
  789. return applyMinHeightOption(po, args)
  790. case "zoom", "z":
  791. return applyZoomOption(po, args)
  792. case "dpr":
  793. return applyDprOption(po, args)
  794. case "enlarge", "el":
  795. return applyEnlargeOption(po, args)
  796. case "extend", "ex":
  797. return applyExtendOption(po, args)
  798. case "extend_aspect_ratio", "extend_ar", "exar":
  799. return applyExtendAspectRatioOption(po, args)
  800. case "gravity", "g":
  801. return applyGravityOption(po, args)
  802. case "crop", "c":
  803. return applyCropOption(po, args)
  804. case "trim", "t":
  805. return applyTrimOption(po, args)
  806. case "padding", "pd":
  807. return applyPaddingOption(po, args)
  808. case "auto_rotate", "ar":
  809. return applyAutoRotateOption(po, args)
  810. case "rotate", "rot":
  811. return applyRotateOption(po, args)
  812. case "background", "bg":
  813. return applyBackgroundOption(po, args)
  814. case "blur", "bl":
  815. return applyBlurOption(po, args)
  816. case "sharpen", "sh":
  817. return applySharpenOption(po, args)
  818. case "pixelate", "pix":
  819. return applyPixelateOption(po, args)
  820. case "watermark", "wm":
  821. return applyWatermarkOption(po, args)
  822. case "strip_metadata", "sm":
  823. return applyStripMetadataOption(po, args)
  824. case "keep_copyright", "kcr":
  825. return applyKeepCopyrightOption(po, args)
  826. case "strip_color_profile", "scp":
  827. return applyStripColorProfileOption(po, args)
  828. case "enforce_thumbnail", "eth":
  829. return applyEnforceThumbnailOption(po, args)
  830. // Saving options
  831. case "quality", "q":
  832. return applyQualityOption(po, args)
  833. case "format_quality", "fq":
  834. return applyFormatQualityOption(po, args)
  835. case "max_bytes", "mb":
  836. return applyMaxBytesOption(po, args)
  837. case "format", "f", "ext":
  838. return applyFormatOption(po, args)
  839. // Handling options
  840. case "skip_processing", "skp":
  841. return applySkipProcessingFormatsOption(po, args)
  842. case "raw":
  843. return applyRawOption(po, args)
  844. case "cachebuster", "cb":
  845. return applyCacheBusterOption(po, args)
  846. case "expires", "exp":
  847. return applyExpiresOption(po, args)
  848. case "filename", "fn":
  849. return applyFilenameOption(po, args)
  850. case "return_attachment", "att":
  851. return applyReturnAttachmentOption(po, args)
  852. // Presets
  853. case "preset", "pr":
  854. return applyPresetOption(po, args, usedPresets...)
  855. // Security
  856. case "max_src_resolution", "msr":
  857. return applyMaxSrcResolutionOption(po, args)
  858. case "max_src_file_size", "msfs":
  859. return applyMaxSrcFileSizeOption(po, args)
  860. case "max_animation_frames", "maf":
  861. return applyMaxAnimationFramesOption(po, args)
  862. case "max_animation_frame_resolution", "mafr":
  863. return applyMaxAnimationFrameResolutionOption(po, args)
  864. }
  865. return fmt.Errorf("Unknown processing option: %s", name)
  866. }
  867. func applyURLOptions(po *ProcessingOptions, options urlOptions, usedPresets ...string) error {
  868. for _, opt := range options {
  869. if err := applyURLOption(po, opt.Name, opt.Args, usedPresets...); err != nil {
  870. return err
  871. }
  872. }
  873. return nil
  874. }
  875. func defaultProcessingOptions(headers http.Header) (*ProcessingOptions, error) {
  876. po := NewProcessingOptions()
  877. headerAccept := headers.Get("Accept")
  878. if strings.Contains(headerAccept, "image/webp") {
  879. po.PreferWebP = config.EnableWebpDetection || config.EnforceWebp
  880. po.EnforceWebP = config.EnforceWebp
  881. }
  882. if strings.Contains(headerAccept, "image/avif") {
  883. po.PreferAvif = config.EnableAvifDetection || config.EnforceAvif
  884. po.EnforceAvif = config.EnforceAvif
  885. }
  886. if config.EnableClientHints {
  887. headerDPR := headers.Get("Sec-CH-DPR")
  888. if len(headerDPR) == 0 {
  889. headerDPR = headers.Get("DPR")
  890. }
  891. if len(headerDPR) > 0 {
  892. if dpr, err := strconv.ParseFloat(headerDPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  893. po.Dpr = dpr
  894. }
  895. }
  896. headerWidth := headers.Get("Sec-CH-Width")
  897. if len(headerWidth) == 0 {
  898. headerWidth = headers.Get("Width")
  899. }
  900. if len(headerWidth) > 0 {
  901. if w, err := strconv.Atoi(headerWidth); err == nil {
  902. po.Width = imath.Shrink(w, po.Dpr)
  903. }
  904. }
  905. }
  906. if _, ok := presets["default"]; ok {
  907. if err := applyPresetOption(po, []string{"default"}); err != nil {
  908. return po, err
  909. }
  910. }
  911. return po, nil
  912. }
  913. func parsePathOptions(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  914. if _, ok := resizeTypes[parts[0]]; ok {
  915. return nil, "", ierrors.New(
  916. 404,
  917. "It looks like you're using the deprecated basic URL format",
  918. "Invalid URL",
  919. )
  920. }
  921. po, err := defaultProcessingOptions(headers)
  922. if err != nil {
  923. return nil, "", err
  924. }
  925. options, urlParts := parseURLOptions(parts)
  926. if err = applyURLOptions(po, options); err != nil {
  927. return nil, "", err
  928. }
  929. url, extension, err := DecodeURL(urlParts)
  930. if err != nil {
  931. return nil, "", err
  932. }
  933. if !po.Raw && len(extension) > 0 {
  934. if err = applyFormatOption(po, []string{extension}); err != nil {
  935. return nil, "", err
  936. }
  937. }
  938. return po, url, nil
  939. }
  940. func parsePathPresets(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  941. po, err := defaultProcessingOptions(headers)
  942. if err != nil {
  943. return nil, "", err
  944. }
  945. presets := strings.Split(parts[0], config.ArgumentsSeparator)
  946. urlParts := parts[1:]
  947. if err = applyPresetOption(po, presets); err != nil {
  948. return nil, "", err
  949. }
  950. url, extension, err := DecodeURL(urlParts)
  951. if err != nil {
  952. return nil, "", err
  953. }
  954. if !po.Raw && len(extension) > 0 {
  955. if err = applyFormatOption(po, []string{extension}); err != nil {
  956. return nil, "", err
  957. }
  958. }
  959. return po, url, nil
  960. }
  961. func ParsePath(path string, headers http.Header) (*ProcessingOptions, string, error) {
  962. if path == "" || path == "/" {
  963. return nil, "", ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL")
  964. }
  965. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  966. var (
  967. imageURL string
  968. po *ProcessingOptions
  969. err error
  970. )
  971. if config.OnlyPresets {
  972. po, imageURL, err = parsePathPresets(parts, headers)
  973. } else {
  974. po, imageURL, err = parsePathOptions(parts, headers)
  975. }
  976. if err != nil {
  977. return nil, "", ierrors.New(404, err.Error(), "Invalid URL")
  978. }
  979. return po, imageURL, nil
  980. }