1
0

processing_options.go 28 KB

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