processing_options.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. structdiff "github.com/imgproxy/imgproxy/struct-diff"
  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 cropOptions struct {
  78. Width int
  79. Height int
  80. Gravity gravityOptions
  81. }
  82. type watermarkOptions struct {
  83. Enabled bool
  84. Opacity float64
  85. Replicate bool
  86. Gravity gravityType
  87. OffsetX int
  88. OffsetY int
  89. Scale float64
  90. }
  91. type processingOptions struct {
  92. ResizingType resizeType
  93. Width int
  94. Height int
  95. Dpr float64
  96. Gravity gravityOptions
  97. Enlarge bool
  98. Extend bool
  99. Crop cropOptions
  100. Format imageType
  101. Quality int
  102. MaxBytes int
  103. Flatten bool
  104. Background rgbColor
  105. Blur float32
  106. Sharpen float32
  107. CacheBuster string
  108. Watermark watermarkOptions
  109. PreferWebP bool
  110. EnforceWebP bool
  111. Filename string
  112. UsedPresets []string
  113. }
  114. const (
  115. imageURLCtxKey = ctxKey("imageUrl")
  116. processingOptionsCtxKey = ctxKey("processingOptions")
  117. urlTokenPlain = "plain"
  118. maxClientHintDPR = 8
  119. msgForbidden = "Forbidden"
  120. msgInvalidURL = "Invalid URL"
  121. )
  122. func (gt gravityType) String() string {
  123. for k, v := range gravityTypes {
  124. if v == gt {
  125. return k
  126. }
  127. }
  128. return ""
  129. }
  130. func (gt gravityType) MarshalJSON() ([]byte, error) {
  131. for k, v := range gravityTypes {
  132. if v == gt {
  133. return []byte(fmt.Sprintf("%q", k)), nil
  134. }
  135. }
  136. return []byte("null"), nil
  137. }
  138. func (rt resizeType) String() string {
  139. for k, v := range resizeTypes {
  140. if v == rt {
  141. return k
  142. }
  143. }
  144. return ""
  145. }
  146. func (rt resizeType) MarshalJSON() ([]byte, error) {
  147. for k, v := range resizeTypes {
  148. if v == rt {
  149. return []byte(fmt.Sprintf("%q", k)), nil
  150. }
  151. }
  152. return []byte("null"), nil
  153. }
  154. var (
  155. _newProcessingOptions processingOptions
  156. newProcessingOptionsOnce sync.Once
  157. )
  158. func newProcessingOptions() *processingOptions {
  159. newProcessingOptionsOnce.Do(func() {
  160. _newProcessingOptions = processingOptions{
  161. ResizingType: resizeFit,
  162. Width: 0,
  163. Height: 0,
  164. Gravity: gravityOptions{Type: gravityCenter},
  165. Enlarge: false,
  166. Quality: conf.Quality,
  167. MaxBytes: 0,
  168. Format: imageTypeUnknown,
  169. Background: rgbColor{255, 255, 255},
  170. Blur: 0,
  171. Sharpen: 0,
  172. Dpr: 1,
  173. Watermark: watermarkOptions{Opacity: 1, Replicate: false, Gravity: gravityCenter},
  174. }
  175. })
  176. po := _newProcessingOptions
  177. po.UsedPresets = make([]string, 0, len(conf.Presets))
  178. return &po
  179. }
  180. func (po *processingOptions) isPresetUsed(name string) bool {
  181. for _, usedName := range po.UsedPresets {
  182. if usedName == name {
  183. return true
  184. }
  185. }
  186. return false
  187. }
  188. func (po *processingOptions) presetUsed(name string) {
  189. po.UsedPresets = append(po.UsedPresets, name)
  190. }
  191. func (po *processingOptions) Diff() structdiff.Entries {
  192. return structdiff.Diff(newProcessingOptions(), po)
  193. }
  194. func (po *processingOptions) String() string {
  195. return po.Diff().String()
  196. }
  197. func (po *processingOptions) MarshalJSON() ([]byte, error) {
  198. return po.Diff().MarshalJSON()
  199. }
  200. func colorFromHex(hexcolor string) (rgbColor, error) {
  201. c := rgbColor{}
  202. if !hexColorRegex.MatchString(hexcolor) {
  203. return c, fmt.Errorf("Invalid hex color: %s", hexcolor)
  204. }
  205. if len(hexcolor) == 3 {
  206. fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
  207. c.R *= 17
  208. c.G *= 17
  209. c.B *= 17
  210. } else {
  211. fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
  212. }
  213. return c, nil
  214. }
  215. func decodeBase64URL(parts []string) (string, string, error) {
  216. var format string
  217. encoded := strings.Join(parts, "")
  218. urlParts := strings.Split(encoded, ".")
  219. if len(urlParts[0]) == 0 {
  220. return "", "", errors.New("Image URL is empty")
  221. }
  222. if len(urlParts) > 2 {
  223. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  224. }
  225. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  226. format = urlParts[1]
  227. }
  228. imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
  229. if err != nil {
  230. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  231. }
  232. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, string(imageURL))
  233. return fullURL, format, nil
  234. }
  235. func decodePlainURL(parts []string) (string, string, error) {
  236. var format string
  237. encoded := strings.Join(parts, "/")
  238. urlParts := strings.Split(encoded, "@")
  239. if len(urlParts[0]) == 0 {
  240. return "", "", errors.New("Image URL is empty")
  241. }
  242. if len(urlParts) > 2 {
  243. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  244. }
  245. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  246. format = urlParts[1]
  247. }
  248. unescaped, err := url.PathUnescape(urlParts[0])
  249. if err != nil {
  250. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  251. }
  252. fullURL := fmt.Sprintf("%s%s", conf.BaseURL, unescaped)
  253. return fullURL, format, nil
  254. }
  255. func decodeURL(parts []string) (string, string, error) {
  256. if len(parts) == 0 {
  257. return "", "", errors.New("Image URL is empty")
  258. }
  259. if parts[0] == urlTokenPlain && len(parts) > 1 {
  260. return decodePlainURL(parts[1:])
  261. }
  262. return decodeBase64URL(parts)
  263. }
  264. func parseDimension(d *int, name, arg string) error {
  265. if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
  266. *d = v
  267. } else {
  268. return fmt.Errorf("Invalid %s: %s", name, arg)
  269. }
  270. return nil
  271. }
  272. func parseBoolOption(str string) bool {
  273. b, err := strconv.ParseBool(str)
  274. if err != nil {
  275. logWarning("`%s` is not a valid boolean value. Treated as false", str)
  276. }
  277. return b
  278. }
  279. func isGravityOffcetValid(gravity gravityType, offset float64) bool {
  280. if gravity == gravityCenter {
  281. return true
  282. }
  283. return offset >= 0 && (gravity != gravityFocusPoint || offset <= 1)
  284. }
  285. func parseGravity(g *gravityOptions, args []string) error {
  286. nArgs := len(args)
  287. if nArgs > 3 {
  288. return fmt.Errorf("Invalid gravity arguments: %v", args)
  289. }
  290. if t, ok := gravityTypes[args[0]]; ok {
  291. g.Type = t
  292. } else {
  293. return fmt.Errorf("Invalid gravity: %s", args[0])
  294. }
  295. if g.Type == gravitySmart && nArgs > 1 {
  296. return fmt.Errorf("Invalid gravity arguments: %v", args)
  297. } else if g.Type == gravityFocusPoint && nArgs != 3 {
  298. return fmt.Errorf("Invalid gravity arguments: %v", args)
  299. }
  300. if nArgs > 1 {
  301. if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
  302. g.X = x
  303. } else {
  304. return fmt.Errorf("Invalid gravity X: %s", args[1])
  305. }
  306. }
  307. if nArgs > 2 {
  308. if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
  309. g.Y = y
  310. } else {
  311. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  312. }
  313. }
  314. return nil
  315. }
  316. func applyWidthOption(po *processingOptions, args []string) error {
  317. if len(args) > 1 {
  318. return fmt.Errorf("Invalid width arguments: %v", args)
  319. }
  320. return parseDimension(&po.Width, "width", args[0])
  321. }
  322. func applyHeightOption(po *processingOptions, args []string) error {
  323. if len(args) > 1 {
  324. return fmt.Errorf("Invalid height arguments: %v", args)
  325. }
  326. return parseDimension(&po.Height, "height", args[0])
  327. }
  328. func applyEnlargeOption(po *processingOptions, args []string) error {
  329. if len(args) > 1 {
  330. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  331. }
  332. po.Enlarge = parseBoolOption(args[0])
  333. return nil
  334. }
  335. func applyExtendOption(po *processingOptions, args []string) error {
  336. if len(args) > 1 {
  337. return fmt.Errorf("Invalid extend arguments: %v", args)
  338. }
  339. po.Extend = parseBoolOption(args[0])
  340. return nil
  341. }
  342. func applySizeOption(po *processingOptions, args []string) (err error) {
  343. if len(args) > 4 {
  344. return fmt.Errorf("Invalid size arguments: %v", args)
  345. }
  346. if len(args) >= 1 && len(args[0]) > 0 {
  347. if err = applyWidthOption(po, args[0:1]); err != nil {
  348. return
  349. }
  350. }
  351. if len(args) >= 2 && len(args[1]) > 0 {
  352. if err = applyHeightOption(po, args[1:2]); err != nil {
  353. return
  354. }
  355. }
  356. if len(args) >= 3 && len(args[2]) > 0 {
  357. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  358. return
  359. }
  360. }
  361. if len(args) == 4 && len(args[3]) > 0 {
  362. if err = applyExtendOption(po, args[3:4]); err != nil {
  363. return
  364. }
  365. }
  366. return nil
  367. }
  368. func applyResizingTypeOption(po *processingOptions, args []string) error {
  369. if len(args) > 1 {
  370. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  371. }
  372. if r, ok := resizeTypes[args[0]]; ok {
  373. po.ResizingType = r
  374. } else {
  375. return fmt.Errorf("Invalid resize type: %s", args[0])
  376. }
  377. return nil
  378. }
  379. func applyResizeOption(po *processingOptions, args []string) error {
  380. if len(args) > 5 {
  381. return fmt.Errorf("Invalid resize arguments: %v", args)
  382. }
  383. if len(args[0]) > 0 {
  384. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  385. return err
  386. }
  387. }
  388. if len(args) > 1 {
  389. if err := applySizeOption(po, args[1:]); err != nil {
  390. return err
  391. }
  392. }
  393. return nil
  394. }
  395. func applyDprOption(po *processingOptions, args []string) error {
  396. if len(args) > 1 {
  397. return fmt.Errorf("Invalid dpr arguments: %v", args)
  398. }
  399. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  400. po.Dpr = d
  401. } else {
  402. return fmt.Errorf("Invalid dpr: %s", args[0])
  403. }
  404. return nil
  405. }
  406. func applyGravityOption(po *processingOptions, args []string) error {
  407. return parseGravity(&po.Gravity, args)
  408. }
  409. func applyCropOption(po *processingOptions, args []string) error {
  410. if len(args) > 5 {
  411. return fmt.Errorf("Invalid crop arguments: %v", args)
  412. }
  413. if err := parseDimension(&po.Crop.Width, "crop width", args[0]); err != nil {
  414. return err
  415. }
  416. if len(args) > 1 {
  417. if err := parseDimension(&po.Crop.Height, "crop height", args[1]); err != nil {
  418. return err
  419. }
  420. }
  421. if len(args) > 2 {
  422. return parseGravity(&po.Crop.Gravity, args[2:])
  423. }
  424. return nil
  425. }
  426. func applyQualityOption(po *processingOptions, args []string) error {
  427. if len(args) > 1 {
  428. return fmt.Errorf("Invalid quality arguments: %v", args)
  429. }
  430. if q, err := strconv.Atoi(args[0]); err == nil && q > 0 && q <= 100 {
  431. po.Quality = q
  432. } else {
  433. return fmt.Errorf("Invalid quality: %s", args[0])
  434. }
  435. return nil
  436. }
  437. func applyMaxBytesOption(po *processingOptions, args []string) error {
  438. if len(args) > 1 {
  439. return fmt.Errorf("Invalid max_bytes arguments: %v", args)
  440. }
  441. if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
  442. po.MaxBytes = max
  443. } else {
  444. return fmt.Errorf("Invalid max_bytes: %s", args[0])
  445. }
  446. return nil
  447. }
  448. func applyBackgroundOption(po *processingOptions, args []string) error {
  449. switch len(args) {
  450. case 1:
  451. if len(args[0]) == 0 {
  452. po.Flatten = false
  453. } else if c, err := colorFromHex(args[0]); err == nil {
  454. po.Flatten = true
  455. po.Background = c
  456. } else {
  457. return fmt.Errorf("Invalid background argument: %s", err)
  458. }
  459. case 3:
  460. po.Flatten = true
  461. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  462. po.Background.R = uint8(r)
  463. } else {
  464. return fmt.Errorf("Invalid background red channel: %s", args[0])
  465. }
  466. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  467. po.Background.G = uint8(g)
  468. } else {
  469. return fmt.Errorf("Invalid background green channel: %s", args[1])
  470. }
  471. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  472. po.Background.B = uint8(b)
  473. } else {
  474. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  475. }
  476. default:
  477. return fmt.Errorf("Invalid background arguments: %v", args)
  478. }
  479. return nil
  480. }
  481. func applyBlurOption(po *processingOptions, args []string) error {
  482. if len(args) > 1 {
  483. return fmt.Errorf("Invalid blur arguments: %v", args)
  484. }
  485. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  486. po.Blur = float32(b)
  487. } else {
  488. return fmt.Errorf("Invalid blur: %s", args[0])
  489. }
  490. return nil
  491. }
  492. func applySharpenOption(po *processingOptions, args []string) error {
  493. if len(args) > 1 {
  494. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  495. }
  496. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  497. po.Sharpen = float32(s)
  498. } else {
  499. return fmt.Errorf("Invalid sharpen: %s", args[0])
  500. }
  501. return nil
  502. }
  503. func applyPresetOption(po *processingOptions, args []string) error {
  504. for _, preset := range args {
  505. if p, ok := conf.Presets[preset]; ok {
  506. if po.isPresetUsed(preset) {
  507. logWarning("Recursive preset usage is detected: %s", preset)
  508. continue
  509. }
  510. po.presetUsed(preset)
  511. if err := applyProcessingOptions(po, p); err != nil {
  512. return err
  513. }
  514. } else {
  515. return fmt.Errorf("Unknown preset: %s", preset)
  516. }
  517. }
  518. return nil
  519. }
  520. func applyWatermarkOption(po *processingOptions, args []string) error {
  521. if len(args) > 7 {
  522. return fmt.Errorf("Invalid watermark arguments: %v", args)
  523. }
  524. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  525. po.Watermark.Enabled = o > 0
  526. po.Watermark.Opacity = o
  527. } else {
  528. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  529. }
  530. if len(args) > 1 && len(args[1]) > 0 {
  531. if args[1] == "re" {
  532. po.Watermark.Replicate = true
  533. } else if g, ok := gravityTypes[args[1]]; ok && g != gravityFocusPoint && g != gravitySmart {
  534. po.Watermark.Gravity = g
  535. } else {
  536. return fmt.Errorf("Invalid watermark position: %s", args[1])
  537. }
  538. }
  539. if len(args) > 2 && len(args[2]) > 0 {
  540. if x, err := strconv.Atoi(args[2]); err == nil {
  541. po.Watermark.OffsetX = x
  542. } else {
  543. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  544. }
  545. }
  546. if len(args) > 3 && len(args[3]) > 0 {
  547. if y, err := strconv.Atoi(args[3]); err == nil {
  548. po.Watermark.OffsetY = y
  549. } else {
  550. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  551. }
  552. }
  553. if len(args) > 4 && len(args[4]) > 0 {
  554. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  555. po.Watermark.Scale = s
  556. } else {
  557. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  558. }
  559. }
  560. return nil
  561. }
  562. func applyFormatOption(po *processingOptions, args []string) error {
  563. if len(args) > 1 {
  564. return fmt.Errorf("Invalid format arguments: %v", args)
  565. }
  566. if f, ok := imageTypes[args[0]]; ok {
  567. po.Format = f
  568. } else {
  569. return fmt.Errorf("Invalid image format: %s", args[0])
  570. }
  571. if !imageTypeSaveSupport(po.Format) {
  572. return fmt.Errorf("Resulting image format is not supported: %s", po.Format)
  573. }
  574. return nil
  575. }
  576. func applyCacheBusterOption(po *processingOptions, args []string) error {
  577. if len(args) > 1 {
  578. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  579. }
  580. po.CacheBuster = args[0]
  581. return nil
  582. }
  583. func applyFilenameOption(po *processingOptions, args []string) error {
  584. if len(args) > 1 {
  585. return fmt.Errorf("Invalid filename arguments: %v", args)
  586. }
  587. po.Filename = args[0]
  588. return nil
  589. }
  590. func applyProcessingOption(po *processingOptions, name string, args []string) error {
  591. switch name {
  592. case "format", "f", "ext":
  593. return applyFormatOption(po, args)
  594. case "resize", "rs":
  595. return applyResizeOption(po, args)
  596. case "resizing_type", "rt":
  597. return applyResizingTypeOption(po, args)
  598. case "size", "s":
  599. return applySizeOption(po, args)
  600. case "width", "w":
  601. return applyWidthOption(po, args)
  602. case "height", "h":
  603. return applyHeightOption(po, args)
  604. case "enlarge", "el":
  605. return applyEnlargeOption(po, args)
  606. case "extend", "ex":
  607. return applyExtendOption(po, args)
  608. case "dpr":
  609. return applyDprOption(po, args)
  610. case "gravity", "g":
  611. return applyGravityOption(po, args)
  612. case "crop", "c":
  613. return applyCropOption(po, args)
  614. case "quality", "q":
  615. return applyQualityOption(po, args)
  616. case "max_bytes", "mb":
  617. return applyMaxBytesOption(po, args)
  618. case "background", "bg":
  619. return applyBackgroundOption(po, args)
  620. case "blur", "bl":
  621. return applyBlurOption(po, args)
  622. case "sharpen", "sh":
  623. return applySharpenOption(po, args)
  624. case "watermark", "wm":
  625. return applyWatermarkOption(po, args)
  626. case "preset", "pr":
  627. return applyPresetOption(po, args)
  628. case "cachebuster", "cb":
  629. return applyCacheBusterOption(po, args)
  630. case "filename", "fn":
  631. return applyFilenameOption(po, args)
  632. }
  633. return fmt.Errorf("Unknown processing option: %s", name)
  634. }
  635. func applyProcessingOptions(po *processingOptions, options urlOptions) error {
  636. for _, opt := range options {
  637. if err := applyProcessingOption(po, opt.Name, opt.Args); err != nil {
  638. return err
  639. }
  640. }
  641. return nil
  642. }
  643. func parseURLOptions(opts []string) (urlOptions, []string) {
  644. parsed := make(urlOptions, 0, len(opts))
  645. urlStart := len(opts) + 1
  646. for i, opt := range opts {
  647. args := strings.Split(opt, ":")
  648. if len(args) == 1 {
  649. urlStart = i
  650. break
  651. }
  652. parsed = append(parsed, urlOption{Name: args[0], Args: args[1:]})
  653. }
  654. var rest []string
  655. if urlStart < len(opts) {
  656. rest = opts[urlStart:]
  657. } else {
  658. rest = []string{}
  659. }
  660. return parsed, rest
  661. }
  662. func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, error) {
  663. po := newProcessingOptions()
  664. if strings.Contains(headers.Accept, "image/webp") {
  665. po.PreferWebP = conf.EnableWebpDetection || conf.EnforceWebp
  666. po.EnforceWebP = conf.EnforceWebp
  667. }
  668. if conf.EnableClientHints && len(headers.ViewportWidth) > 0 {
  669. if vw, err := strconv.Atoi(headers.ViewportWidth); err == nil {
  670. po.Width = vw
  671. }
  672. }
  673. if conf.EnableClientHints && len(headers.Width) > 0 {
  674. if w, err := strconv.Atoi(headers.Width); err == nil {
  675. po.Width = w
  676. }
  677. }
  678. if conf.EnableClientHints && len(headers.DPR) > 0 {
  679. if dpr, err := strconv.ParseFloat(headers.DPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  680. po.Dpr = dpr
  681. }
  682. }
  683. if _, ok := conf.Presets["default"]; ok {
  684. if err := applyPresetOption(po, []string{"default"}); err != nil {
  685. return po, err
  686. }
  687. }
  688. return po, nil
  689. }
  690. func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  691. po, err := defaultProcessingOptions(headers)
  692. if err != nil {
  693. return "", po, err
  694. }
  695. options, urlParts := parseURLOptions(parts)
  696. if err = applyProcessingOptions(po, options); err != nil {
  697. return "", po, err
  698. }
  699. url, extension, err := decodeURL(urlParts)
  700. if err != nil {
  701. return "", po, err
  702. }
  703. if len(extension) > 0 {
  704. if err = applyFormatOption(po, []string{extension}); err != nil {
  705. return "", po, err
  706. }
  707. }
  708. return url, po, nil
  709. }
  710. func parsePathPresets(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  711. po, err := defaultProcessingOptions(headers)
  712. if err != nil {
  713. return "", po, err
  714. }
  715. presets := strings.Split(parts[0], ":")
  716. urlParts := parts[1:]
  717. if err = applyPresetOption(po, presets); err != nil {
  718. return "", nil, err
  719. }
  720. url, extension, err := decodeURL(urlParts)
  721. if err != nil {
  722. return "", po, err
  723. }
  724. if len(extension) > 0 {
  725. if err = applyFormatOption(po, []string{extension}); err != nil {
  726. return "", po, err
  727. }
  728. }
  729. return url, po, nil
  730. }
  731. func parsePathBasic(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
  732. if len(parts) < 6 {
  733. return "", nil, fmt.Errorf("Invalid basic URL format arguments: %s", strings.Join(parts, "/"))
  734. }
  735. po, err := defaultProcessingOptions(headers)
  736. if err != nil {
  737. return "", po, err
  738. }
  739. po.ResizingType = resizeTypes[parts[0]]
  740. if err = applyWidthOption(po, parts[1:2]); err != nil {
  741. return "", po, err
  742. }
  743. if err = applyHeightOption(po, parts[2:3]); err != nil {
  744. return "", po, err
  745. }
  746. if err = applyGravityOption(po, strings.Split(parts[3], ":")); err != nil {
  747. return "", po, err
  748. }
  749. if err = applyEnlargeOption(po, parts[4:5]); err != nil {
  750. return "", po, err
  751. }
  752. url, extension, err := decodeURL(parts[5:])
  753. if err != nil {
  754. return "", po, err
  755. }
  756. if len(extension) > 0 {
  757. if err := applyFormatOption(po, []string{extension}); err != nil {
  758. return "", po, err
  759. }
  760. }
  761. return url, po, nil
  762. }
  763. func parsePath(ctx context.Context, r *http.Request) (context.Context, error) {
  764. path := r.URL.RawPath
  765. if len(path) == 0 {
  766. path = r.URL.Path
  767. }
  768. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  769. if len(parts) < 2 {
  770. return ctx, newError(404, fmt.Sprintf("Invalid path: %s", path), msgInvalidURL)
  771. }
  772. if !conf.AllowInsecure {
  773. if err := validatePath(parts[0], strings.TrimPrefix(path, fmt.Sprintf("/%s", parts[0]))); err != nil {
  774. return ctx, newError(403, err.Error(), msgForbidden)
  775. }
  776. }
  777. headers := &processingHeaders{
  778. Accept: r.Header.Get("Accept"),
  779. Width: r.Header.Get("Width"),
  780. ViewportWidth: r.Header.Get("Viewport-Width"),
  781. DPR: r.Header.Get("DPR"),
  782. }
  783. var imageURL string
  784. var po *processingOptions
  785. var err error
  786. if conf.OnlyPresets {
  787. imageURL, po, err = parsePathPresets(parts[1:], headers)
  788. } else if _, ok := resizeTypes[parts[1]]; ok {
  789. imageURL, po, err = parsePathBasic(parts[1:], headers)
  790. } else {
  791. imageURL, po, err = parsePathAdvanced(parts[1:], headers)
  792. }
  793. if err != nil {
  794. return ctx, newError(404, err.Error(), msgInvalidURL)
  795. }
  796. ctx = context.WithValue(ctx, imageURLCtxKey, imageURL)
  797. ctx = context.WithValue(ctx, processingOptionsCtxKey, po)
  798. return ctx, nil
  799. }
  800. func getImageURL(ctx context.Context) string {
  801. return ctx.Value(imageURLCtxKey).(string)
  802. }
  803. func getProcessingOptions(ctx context.Context) *processingOptions {
  804. return ctx.Value(processingOptionsCtxKey).(*processingOptions)
  805. }