processing_options.go 25 KB

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