processing_options.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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. return parseGravity(&opts.Gravity, name+" gravity", args[1:], extendGravityTypes)
  224. }
  225. return nil
  226. }
  227. func applyWidthOption(po *ProcessingOptions, args []string) error {
  228. if len(args) > 1 {
  229. return fmt.Errorf("Invalid width arguments: %v", args)
  230. }
  231. return parseDimension(&po.Width, "width", args[0])
  232. }
  233. func applyHeightOption(po *ProcessingOptions, args []string) error {
  234. if len(args) > 1 {
  235. return fmt.Errorf("Invalid height arguments: %v", args)
  236. }
  237. return parseDimension(&po.Height, "height", args[0])
  238. }
  239. func applyMinWidthOption(po *ProcessingOptions, args []string) error {
  240. if len(args) > 1 {
  241. return fmt.Errorf("Invalid min width arguments: %v", args)
  242. }
  243. return parseDimension(&po.MinWidth, "min width", args[0])
  244. }
  245. func applyMinHeightOption(po *ProcessingOptions, args []string) error {
  246. if len(args) > 1 {
  247. return fmt.Errorf("Invalid min height arguments: %v", args)
  248. }
  249. return parseDimension(&po.MinHeight, " min height", args[0])
  250. }
  251. func applyEnlargeOption(po *ProcessingOptions, args []string) error {
  252. if len(args) > 1 {
  253. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  254. }
  255. po.Enlarge = parseBoolOption(args[0])
  256. return nil
  257. }
  258. func applyExtendOption(po *ProcessingOptions, args []string) error {
  259. return parseExtend(&po.Extend, "extend", args)
  260. }
  261. func applyExtendAspectRatioOption(po *ProcessingOptions, args []string) error {
  262. return parseExtend(&po.ExtendAspectRatio, "extend_aspect_ratio", args)
  263. }
  264. func applySizeOption(po *ProcessingOptions, args []string) (err error) {
  265. if len(args) > 7 {
  266. return fmt.Errorf("Invalid size arguments: %v", args)
  267. }
  268. if len(args) >= 1 && len(args[0]) > 0 {
  269. if err = applyWidthOption(po, args[0:1]); err != nil {
  270. return
  271. }
  272. }
  273. if len(args) >= 2 && len(args[1]) > 0 {
  274. if err = applyHeightOption(po, args[1:2]); err != nil {
  275. return
  276. }
  277. }
  278. if len(args) >= 3 && len(args[2]) > 0 {
  279. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  280. return
  281. }
  282. }
  283. if len(args) >= 4 && len(args[3]) > 0 {
  284. if err = applyExtendOption(po, args[3:]); err != nil {
  285. return
  286. }
  287. }
  288. return nil
  289. }
  290. func applyResizingTypeOption(po *ProcessingOptions, args []string) error {
  291. if len(args) > 1 {
  292. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  293. }
  294. if r, ok := resizeTypes[args[0]]; ok {
  295. po.ResizingType = r
  296. } else {
  297. return fmt.Errorf("Invalid resize type: %s", args[0])
  298. }
  299. return nil
  300. }
  301. func applyResizeOption(po *ProcessingOptions, args []string) error {
  302. if len(args) > 8 {
  303. return fmt.Errorf("Invalid resize arguments: %v", args)
  304. }
  305. if len(args[0]) > 0 {
  306. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  307. return err
  308. }
  309. }
  310. if len(args) > 1 {
  311. if err := applySizeOption(po, args[1:]); err != nil {
  312. return err
  313. }
  314. }
  315. return nil
  316. }
  317. func applyZoomOption(po *ProcessingOptions, args []string) error {
  318. nArgs := len(args)
  319. if nArgs > 2 {
  320. return fmt.Errorf("Invalid zoom arguments: %v", args)
  321. }
  322. if z, err := strconv.ParseFloat(args[0], 64); err == nil && z > 0 {
  323. po.ZoomWidth = z
  324. po.ZoomHeight = z
  325. } else {
  326. return fmt.Errorf("Invalid zoom value: %s", args[0])
  327. }
  328. if nArgs > 1 {
  329. if z, err := strconv.ParseFloat(args[1], 64); err == nil && z > 0 {
  330. po.ZoomHeight = z
  331. } else {
  332. return fmt.Errorf("Invalid zoom value: %s", args[0])
  333. }
  334. }
  335. return nil
  336. }
  337. func applyDprOption(po *ProcessingOptions, args []string) error {
  338. if len(args) > 1 {
  339. return fmt.Errorf("Invalid dpr arguments: %v", args)
  340. }
  341. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  342. po.Dpr = d
  343. } else {
  344. return fmt.Errorf("Invalid dpr: %s", args[0])
  345. }
  346. return nil
  347. }
  348. func applyGravityOption(po *ProcessingOptions, args []string) error {
  349. return parseGravity(&po.Gravity, "gravity", args, cropGravityTypes)
  350. }
  351. func applyCropOption(po *ProcessingOptions, args []string) error {
  352. if w, err := strconv.ParseFloat(args[0], 64); err == nil && w >= 0 {
  353. po.Crop.Width = w
  354. } else {
  355. return fmt.Errorf("Invalid crop width: %s", args[0])
  356. }
  357. if len(args) > 1 {
  358. if h, err := strconv.ParseFloat(args[1], 64); err == nil && h >= 0 {
  359. po.Crop.Height = h
  360. } else {
  361. return fmt.Errorf("Invalid crop height: %s", args[1])
  362. }
  363. }
  364. if len(args) > 2 {
  365. return parseGravity(&po.Crop.Gravity, "crop gravity", args[2:], cropGravityTypes)
  366. }
  367. return nil
  368. }
  369. func applyPaddingOption(po *ProcessingOptions, args []string) error {
  370. nArgs := len(args)
  371. if nArgs < 1 || nArgs > 4 {
  372. return fmt.Errorf("Invalid padding arguments: %v", args)
  373. }
  374. po.Padding.Enabled = true
  375. if nArgs > 0 && len(args[0]) > 0 {
  376. if err := parseDimension(&po.Padding.Top, "padding top (+all)", args[0]); err != nil {
  377. return err
  378. }
  379. po.Padding.Right = po.Padding.Top
  380. po.Padding.Bottom = po.Padding.Top
  381. po.Padding.Left = po.Padding.Top
  382. }
  383. if nArgs > 1 && len(args[1]) > 0 {
  384. if err := parseDimension(&po.Padding.Right, "padding right (+left)", args[1]); err != nil {
  385. return err
  386. }
  387. po.Padding.Left = po.Padding.Right
  388. }
  389. if nArgs > 2 && len(args[2]) > 0 {
  390. if err := parseDimension(&po.Padding.Bottom, "padding bottom", args[2]); err != nil {
  391. return err
  392. }
  393. }
  394. if nArgs > 3 && len(args[3]) > 0 {
  395. if err := parseDimension(&po.Padding.Left, "padding left", args[3]); err != nil {
  396. return err
  397. }
  398. }
  399. if po.Padding.Top == 0 && po.Padding.Right == 0 && po.Padding.Bottom == 0 && po.Padding.Left == 0 {
  400. po.Padding.Enabled = false
  401. }
  402. return nil
  403. }
  404. func applyTrimOption(po *ProcessingOptions, args []string) error {
  405. nArgs := len(args)
  406. if nArgs > 4 {
  407. return fmt.Errorf("Invalid trim arguments: %v", args)
  408. }
  409. if t, err := strconv.ParseFloat(args[0], 64); err == nil && t >= 0 {
  410. po.Trim.Enabled = true
  411. po.Trim.Threshold = t
  412. } else {
  413. return fmt.Errorf("Invalid trim threshold: %s", args[0])
  414. }
  415. if nArgs > 1 && len(args[1]) > 0 {
  416. if c, err := vips.ColorFromHex(args[1]); err == nil {
  417. po.Trim.Color = c
  418. po.Trim.Smart = false
  419. } else {
  420. return fmt.Errorf("Invalid trim color: %s", args[1])
  421. }
  422. }
  423. if nArgs > 2 && len(args[2]) > 0 {
  424. po.Trim.EqualHor = parseBoolOption(args[2])
  425. }
  426. if nArgs > 3 && len(args[3]) > 0 {
  427. po.Trim.EqualVer = parseBoolOption(args[3])
  428. }
  429. return nil
  430. }
  431. func applyRotateOption(po *ProcessingOptions, args []string) error {
  432. if len(args) > 1 {
  433. return fmt.Errorf("Invalid rotate arguments: %v", args)
  434. }
  435. if r, err := strconv.Atoi(args[0]); err == nil && r%90 == 0 {
  436. po.Rotate = r
  437. } else {
  438. return fmt.Errorf("Invalid rotation angle: %s", args[0])
  439. }
  440. return nil
  441. }
  442. func applyQualityOption(po *ProcessingOptions, args []string) error {
  443. if len(args) > 1 {
  444. return fmt.Errorf("Invalid quality arguments: %v", args)
  445. }
  446. if q, err := strconv.Atoi(args[0]); err == nil && q >= 0 && q <= 100 {
  447. po.Quality = q
  448. } else {
  449. return fmt.Errorf("Invalid quality: %s", args[0])
  450. }
  451. return nil
  452. }
  453. func applyFormatQualityOption(po *ProcessingOptions, args []string) error {
  454. argsLen := len(args)
  455. if len(args)%2 != 0 {
  456. return fmt.Errorf("Missing quality for: %s", args[argsLen-1])
  457. }
  458. for i := 0; i < argsLen; i += 2 {
  459. f, ok := imagetype.Types[args[i]]
  460. if !ok {
  461. return fmt.Errorf("Invalid image format: %s", args[i])
  462. }
  463. if q, err := strconv.Atoi(args[i+1]); err == nil && q >= 0 && q <= 100 {
  464. po.FormatQuality[f] = q
  465. } else {
  466. return fmt.Errorf("Invalid quality for %s: %s", args[i], args[i+1])
  467. }
  468. }
  469. return nil
  470. }
  471. func applyMaxBytesOption(po *ProcessingOptions, args []string) error {
  472. if len(args) > 1 {
  473. return fmt.Errorf("Invalid max_bytes arguments: %v", args)
  474. }
  475. if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
  476. po.MaxBytes = max
  477. } else {
  478. return fmt.Errorf("Invalid max_bytes: %s", args[0])
  479. }
  480. return nil
  481. }
  482. func applyBackgroundOption(po *ProcessingOptions, args []string) error {
  483. switch len(args) {
  484. case 1:
  485. if len(args[0]) == 0 {
  486. po.Flatten = false
  487. } else if c, err := vips.ColorFromHex(args[0]); err == nil {
  488. po.Flatten = true
  489. po.Background = c
  490. } else {
  491. return fmt.Errorf("Invalid background argument: %s", err)
  492. }
  493. case 3:
  494. po.Flatten = true
  495. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  496. po.Background.R = uint8(r)
  497. } else {
  498. return fmt.Errorf("Invalid background red channel: %s", args[0])
  499. }
  500. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  501. po.Background.G = uint8(g)
  502. } else {
  503. return fmt.Errorf("Invalid background green channel: %s", args[1])
  504. }
  505. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  506. po.Background.B = uint8(b)
  507. } else {
  508. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  509. }
  510. default:
  511. return fmt.Errorf("Invalid background arguments: %v", args)
  512. }
  513. return nil
  514. }
  515. func applyBlurOption(po *ProcessingOptions, args []string) error {
  516. if len(args) > 1 {
  517. return fmt.Errorf("Invalid blur arguments: %v", args)
  518. }
  519. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  520. po.Blur = float32(b)
  521. } else {
  522. return fmt.Errorf("Invalid blur: %s", args[0])
  523. }
  524. return nil
  525. }
  526. func applySharpenOption(po *ProcessingOptions, args []string) error {
  527. if len(args) > 1 {
  528. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  529. }
  530. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  531. po.Sharpen = float32(s)
  532. } else {
  533. return fmt.Errorf("Invalid sharpen: %s", args[0])
  534. }
  535. return nil
  536. }
  537. func applyPixelateOption(po *ProcessingOptions, args []string) error {
  538. if len(args) > 1 {
  539. return fmt.Errorf("Invalid pixelate arguments: %v", args)
  540. }
  541. if p, err := strconv.Atoi(args[0]); err == nil && p >= 0 {
  542. po.Pixelate = p
  543. } else {
  544. return fmt.Errorf("Invalid pixelate: %s", args[0])
  545. }
  546. return nil
  547. }
  548. func applyPresetOption(po *ProcessingOptions, args []string, usedPresets ...string) error {
  549. for _, preset := range args {
  550. if p, ok := presets[preset]; ok {
  551. if slices.Contains(usedPresets, preset) {
  552. log.Warningf("Recursive preset usage is detected: %s", preset)
  553. continue
  554. }
  555. po.UsedPresets = append(po.UsedPresets, preset)
  556. if err := applyURLOptions(po, p, append(usedPresets, preset)...); err != nil {
  557. return err
  558. }
  559. } else {
  560. return fmt.Errorf("Unknown preset: %s", preset)
  561. }
  562. }
  563. return nil
  564. }
  565. func applyWatermarkOption(po *ProcessingOptions, args []string) error {
  566. if len(args) > 7 {
  567. return fmt.Errorf("Invalid watermark arguments: %v", args)
  568. }
  569. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  570. po.Watermark.Enabled = o > 0
  571. po.Watermark.Opacity = o
  572. } else {
  573. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  574. }
  575. if len(args) > 1 && len(args[1]) > 0 {
  576. if g, ok := gravityTypes[args[1]]; ok && slices.Contains(watermarkGravityTypes, g) {
  577. po.Watermark.Position.Type = g
  578. } else {
  579. return fmt.Errorf("Invalid watermark position: %s", args[1])
  580. }
  581. }
  582. if len(args) > 2 && len(args[2]) > 0 {
  583. if x, err := strconv.ParseFloat(args[2], 64); err == nil {
  584. po.Watermark.Position.X = x
  585. } else {
  586. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  587. }
  588. }
  589. if len(args) > 3 && len(args[3]) > 0 {
  590. if y, err := strconv.ParseFloat(args[3], 64); err == nil {
  591. po.Watermark.Position.Y = y
  592. } else {
  593. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  594. }
  595. }
  596. if len(args) > 4 && len(args[4]) > 0 {
  597. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  598. po.Watermark.Scale = s
  599. } else {
  600. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  601. }
  602. }
  603. return nil
  604. }
  605. func applyFormatOption(po *ProcessingOptions, args []string) error {
  606. if len(args) > 1 {
  607. return fmt.Errorf("Invalid format arguments: %v", args)
  608. }
  609. if f, ok := imagetype.Types[args[0]]; ok {
  610. po.Format = f
  611. } else {
  612. return fmt.Errorf("Invalid image format: %s", args[0])
  613. }
  614. return nil
  615. }
  616. func applyCacheBusterOption(po *ProcessingOptions, args []string) error {
  617. if len(args) > 1 {
  618. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  619. }
  620. po.CacheBuster = args[0]
  621. return nil
  622. }
  623. func applySkipProcessingFormatsOption(po *ProcessingOptions, args []string) error {
  624. for _, format := range args {
  625. if f, ok := imagetype.Types[format]; ok {
  626. po.SkipProcessingFormats = append(po.SkipProcessingFormats, f)
  627. } else {
  628. return fmt.Errorf("Invalid image format in skip processing: %s", format)
  629. }
  630. }
  631. return nil
  632. }
  633. func applyRawOption(po *ProcessingOptions, args []string) error {
  634. if len(args) > 1 {
  635. return fmt.Errorf("Invalid return_attachment arguments: %v", args)
  636. }
  637. po.Raw = parseBoolOption(args[0])
  638. return nil
  639. }
  640. func applyFilenameOption(po *ProcessingOptions, args []string) error {
  641. if len(args) > 2 {
  642. return fmt.Errorf("Invalid filename arguments: %v", args)
  643. }
  644. po.Filename = args[0]
  645. if len(args) > 1 && parseBoolOption(args[1]) {
  646. decoded, err := base64.RawURLEncoding.DecodeString(po.Filename)
  647. if err != nil {
  648. return fmt.Errorf("Invalid filename encoding: %s", err)
  649. }
  650. po.Filename = string(decoded)
  651. }
  652. return nil
  653. }
  654. func applyExpiresOption(po *ProcessingOptions, args []string) error {
  655. if len(args) > 1 {
  656. return fmt.Errorf("Invalid expires arguments: %v", args)
  657. }
  658. timestamp, err := strconv.ParseInt(args[0], 10, 64)
  659. if err != nil {
  660. return fmt.Errorf("Invalid expires argument: %v", args[0])
  661. }
  662. if timestamp > 0 && timestamp < time.Now().Unix() {
  663. return errExpiredURL
  664. }
  665. expires := time.Unix(timestamp, 0)
  666. po.Expires = &expires
  667. return nil
  668. }
  669. func applyStripMetadataOption(po *ProcessingOptions, args []string) error {
  670. if len(args) > 1 {
  671. return fmt.Errorf("Invalid strip metadata arguments: %v", args)
  672. }
  673. po.StripMetadata = parseBoolOption(args[0])
  674. return nil
  675. }
  676. func applyKeepCopyrightOption(po *ProcessingOptions, args []string) error {
  677. if len(args) > 1 {
  678. return fmt.Errorf("Invalid keep copyright arguments: %v", args)
  679. }
  680. po.KeepCopyright = parseBoolOption(args[0])
  681. return nil
  682. }
  683. func applyStripColorProfileOption(po *ProcessingOptions, args []string) error {
  684. if len(args) > 1 {
  685. return fmt.Errorf("Invalid strip color profile arguments: %v", args)
  686. }
  687. po.StripColorProfile = parseBoolOption(args[0])
  688. return nil
  689. }
  690. func applyAutoRotateOption(po *ProcessingOptions, args []string) error {
  691. if len(args) > 1 {
  692. return fmt.Errorf("Invalid auto rotate arguments: %v", args)
  693. }
  694. po.AutoRotate = parseBoolOption(args[0])
  695. return nil
  696. }
  697. func applyEnforceThumbnailOption(po *ProcessingOptions, args []string) error {
  698. if len(args) > 1 {
  699. return fmt.Errorf("Invalid enforce thumbnail arguments: %v", args)
  700. }
  701. po.EnforceThumbnail = parseBoolOption(args[0])
  702. return nil
  703. }
  704. func applyReturnAttachmentOption(po *ProcessingOptions, args []string) error {
  705. if len(args) > 1 {
  706. return fmt.Errorf("Invalid return_attachment arguments: %v", args)
  707. }
  708. po.ReturnAttachment = parseBoolOption(args[0])
  709. return nil
  710. }
  711. func applyMaxSrcResolutionOption(po *ProcessingOptions, args []string) error {
  712. if err := security.IsSecurityOptionsAllowed(); err != nil {
  713. return err
  714. }
  715. if len(args) > 1 {
  716. return fmt.Errorf("Invalid max_src_resolution arguments: %v", args)
  717. }
  718. if x, err := strconv.ParseFloat(args[0], 64); err == nil && x > 0 {
  719. po.SecurityOptions.MaxSrcResolution = int(x * 1000000)
  720. } else {
  721. return fmt.Errorf("Invalid max_src_resolution: %s", args[0])
  722. }
  723. return nil
  724. }
  725. func applyMaxSrcFileSizeOption(po *ProcessingOptions, args []string) error {
  726. if err := security.IsSecurityOptionsAllowed(); err != nil {
  727. return err
  728. }
  729. if len(args) > 1 {
  730. return fmt.Errorf("Invalid max_src_file_size arguments: %v", args)
  731. }
  732. if x, err := strconv.Atoi(args[0]); err == nil {
  733. po.SecurityOptions.MaxSrcFileSize = x
  734. } else {
  735. return fmt.Errorf("Invalid max_src_file_size: %s", args[0])
  736. }
  737. return nil
  738. }
  739. func applyMaxAnimationFramesOption(po *ProcessingOptions, args []string) error {
  740. if err := security.IsSecurityOptionsAllowed(); err != nil {
  741. return err
  742. }
  743. if len(args) > 1 {
  744. return fmt.Errorf("Invalid max_animation_frames arguments: %v", args)
  745. }
  746. if x, err := strconv.Atoi(args[0]); err == nil && x > 0 {
  747. po.SecurityOptions.MaxAnimationFrames = x
  748. } else {
  749. return fmt.Errorf("Invalid max_animation_frames: %s", args[0])
  750. }
  751. return nil
  752. }
  753. func applyMaxAnimationFrameResolutionOption(po *ProcessingOptions, args []string) error {
  754. if err := security.IsSecurityOptionsAllowed(); err != nil {
  755. return err
  756. }
  757. if len(args) > 1 {
  758. return fmt.Errorf("Invalid max_animation_frame_resolution arguments: %v", args)
  759. }
  760. if x, err := strconv.ParseFloat(args[0], 64); err == nil {
  761. po.SecurityOptions.MaxAnimationFrameResolution = int(x * 1000000)
  762. } else {
  763. return fmt.Errorf("Invalid max_animation_frame_resolution: %s", args[0])
  764. }
  765. return nil
  766. }
  767. func applyURLOption(po *ProcessingOptions, name string, args []string, usedPresets ...string) error {
  768. switch name {
  769. case "resize", "rs":
  770. return applyResizeOption(po, args)
  771. case "size", "s":
  772. return applySizeOption(po, args)
  773. case "resizing_type", "rt":
  774. return applyResizingTypeOption(po, args)
  775. case "width", "w":
  776. return applyWidthOption(po, args)
  777. case "height", "h":
  778. return applyHeightOption(po, args)
  779. case "min-width", "mw":
  780. return applyMinWidthOption(po, args)
  781. case "min-height", "mh":
  782. return applyMinHeightOption(po, args)
  783. case "zoom", "z":
  784. return applyZoomOption(po, args)
  785. case "dpr":
  786. return applyDprOption(po, args)
  787. case "enlarge", "el":
  788. return applyEnlargeOption(po, args)
  789. case "extend", "ex":
  790. return applyExtendOption(po, args)
  791. case "extend_aspect_ratio", "extend_ar", "exar":
  792. return applyExtendAspectRatioOption(po, args)
  793. case "gravity", "g":
  794. return applyGravityOption(po, args)
  795. case "crop", "c":
  796. return applyCropOption(po, args)
  797. case "trim", "t":
  798. return applyTrimOption(po, args)
  799. case "padding", "pd":
  800. return applyPaddingOption(po, args)
  801. case "auto_rotate", "ar":
  802. return applyAutoRotateOption(po, args)
  803. case "rotate", "rot":
  804. return applyRotateOption(po, args)
  805. case "background", "bg":
  806. return applyBackgroundOption(po, args)
  807. case "blur", "bl":
  808. return applyBlurOption(po, args)
  809. case "sharpen", "sh":
  810. return applySharpenOption(po, args)
  811. case "pixelate", "pix":
  812. return applyPixelateOption(po, args)
  813. case "watermark", "wm":
  814. return applyWatermarkOption(po, args)
  815. case "strip_metadata", "sm":
  816. return applyStripMetadataOption(po, args)
  817. case "keep_copyright", "kcr":
  818. return applyKeepCopyrightOption(po, args)
  819. case "strip_color_profile", "scp":
  820. return applyStripColorProfileOption(po, args)
  821. case "enforce_thumbnail", "eth":
  822. return applyEnforceThumbnailOption(po, args)
  823. // Saving options
  824. case "quality", "q":
  825. return applyQualityOption(po, args)
  826. case "format_quality", "fq":
  827. return applyFormatQualityOption(po, args)
  828. case "max_bytes", "mb":
  829. return applyMaxBytesOption(po, args)
  830. case "format", "f", "ext":
  831. return applyFormatOption(po, args)
  832. // Handling options
  833. case "skip_processing", "skp":
  834. return applySkipProcessingFormatsOption(po, args)
  835. case "raw":
  836. return applyRawOption(po, args)
  837. case "cachebuster", "cb":
  838. return applyCacheBusterOption(po, args)
  839. case "expires", "exp":
  840. return applyExpiresOption(po, args)
  841. case "filename", "fn":
  842. return applyFilenameOption(po, args)
  843. case "return_attachment", "att":
  844. return applyReturnAttachmentOption(po, args)
  845. // Presets
  846. case "preset", "pr":
  847. return applyPresetOption(po, args, usedPresets...)
  848. // Security
  849. case "max_src_resolution", "msr":
  850. return applyMaxSrcResolutionOption(po, args)
  851. case "max_src_file_size", "msfs":
  852. return applyMaxSrcFileSizeOption(po, args)
  853. case "max_animation_frames", "maf":
  854. return applyMaxAnimationFramesOption(po, args)
  855. case "max_animation_frame_resolution", "mafr":
  856. return applyMaxAnimationFrameResolutionOption(po, args)
  857. }
  858. return fmt.Errorf("Unknown processing option: %s", name)
  859. }
  860. func applyURLOptions(po *ProcessingOptions, options urlOptions, usedPresets ...string) error {
  861. for _, opt := range options {
  862. if err := applyURLOption(po, opt.Name, opt.Args, usedPresets...); err != nil {
  863. return err
  864. }
  865. }
  866. return nil
  867. }
  868. func defaultProcessingOptions(headers http.Header) (*ProcessingOptions, error) {
  869. po := NewProcessingOptions()
  870. headerAccept := headers.Get("Accept")
  871. if strings.Contains(headerAccept, "image/webp") {
  872. po.PreferWebP = config.EnableWebpDetection || config.EnforceWebp
  873. po.EnforceWebP = config.EnforceWebp
  874. }
  875. if strings.Contains(headerAccept, "image/avif") {
  876. po.PreferAvif = config.EnableAvifDetection || config.EnforceAvif
  877. po.EnforceAvif = config.EnforceAvif
  878. }
  879. if config.EnableClientHints {
  880. headerDPR := headers.Get("Sec-CH-DPR")
  881. if len(headerDPR) == 0 {
  882. headerDPR = headers.Get("DPR")
  883. }
  884. if len(headerDPR) > 0 {
  885. if dpr, err := strconv.ParseFloat(headerDPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  886. po.Dpr = dpr
  887. }
  888. }
  889. headerWidth := headers.Get("Sec-CH-Width")
  890. if len(headerWidth) == 0 {
  891. headerWidth = headers.Get("Width")
  892. }
  893. if len(headerWidth) > 0 {
  894. if w, err := strconv.Atoi(headerWidth); err == nil {
  895. po.Width = imath.Shrink(w, po.Dpr)
  896. }
  897. }
  898. }
  899. if _, ok := presets["default"]; ok {
  900. if err := applyPresetOption(po, []string{"default"}); err != nil {
  901. return po, err
  902. }
  903. }
  904. return po, nil
  905. }
  906. func parsePathOptions(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  907. if _, ok := resizeTypes[parts[0]]; ok {
  908. return nil, "", ierrors.New(
  909. 404,
  910. "It looks like you're using the deprecated basic URL format",
  911. "Invalid URL",
  912. )
  913. }
  914. po, err := defaultProcessingOptions(headers)
  915. if err != nil {
  916. return nil, "", err
  917. }
  918. options, urlParts := parseURLOptions(parts)
  919. if err = applyURLOptions(po, options); err != nil {
  920. return nil, "", err
  921. }
  922. url, extension, err := DecodeURL(urlParts)
  923. if err != nil {
  924. return nil, "", err
  925. }
  926. if !po.Raw && len(extension) > 0 {
  927. if err = applyFormatOption(po, []string{extension}); err != nil {
  928. return nil, "", err
  929. }
  930. }
  931. return po, url, nil
  932. }
  933. func parsePathPresets(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  934. po, err := defaultProcessingOptions(headers)
  935. if err != nil {
  936. return nil, "", err
  937. }
  938. presets := strings.Split(parts[0], config.ArgumentsSeparator)
  939. urlParts := parts[1:]
  940. if err = applyPresetOption(po, presets); err != nil {
  941. return nil, "", err
  942. }
  943. url, extension, err := DecodeURL(urlParts)
  944. if err != nil {
  945. return nil, "", err
  946. }
  947. if !po.Raw && len(extension) > 0 {
  948. if err = applyFormatOption(po, []string{extension}); err != nil {
  949. return nil, "", err
  950. }
  951. }
  952. return po, url, nil
  953. }
  954. func ParsePath(path string, headers http.Header) (*ProcessingOptions, string, error) {
  955. if path == "" || path == "/" {
  956. return nil, "", ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL")
  957. }
  958. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  959. var (
  960. imageURL string
  961. po *ProcessingOptions
  962. err error
  963. )
  964. if config.OnlyPresets {
  965. po, imageURL, err = parsePathPresets(parts, headers)
  966. } else {
  967. po, imageURL, err = parsePathOptions(parts, headers)
  968. }
  969. if err != nil {
  970. return nil, "", ierrors.New(404, err.Error(), "Invalid URL")
  971. }
  972. return po, imageURL, nil
  973. }