processing_options.go 27 KB

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