processing_options.go 26 KB

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