processing_options.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. package main
  2. /*
  3. #cgo LDFLAGS: -s -w
  4. #include "image_types.h"
  5. */
  6. import "C"
  7. import (
  8. "encoding/base64"
  9. "errors"
  10. "fmt"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. )
  15. type urlOptions map[string][]string
  16. type imageType int
  17. const (
  18. imageTypeUnknown = C.UNKNOWN
  19. imageTypeJPEG = C.JPEG
  20. imageTypePNG = C.PNG
  21. imageTypeWEBP = C.WEBP
  22. imageTypeGIF = C.GIF
  23. )
  24. var imageTypes = map[string]imageType{
  25. "jpeg": imageTypeJPEG,
  26. "jpg": imageTypeJPEG,
  27. "png": imageTypePNG,
  28. "webp": imageTypeWEBP,
  29. "gif": imageTypeGIF,
  30. }
  31. type gravityType int
  32. const (
  33. gravityCenter gravityType = iota
  34. gravityNorth
  35. gravityEast
  36. gravitySouth
  37. gravityWest
  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. "sm": gravitySmart,
  48. "fp": gravityFocusPoint,
  49. }
  50. type gravity struct {
  51. Type gravityType
  52. X, Y float64
  53. }
  54. type resizeType int
  55. const (
  56. resizeFit resizeType = iota
  57. resizeFill
  58. resizeCrop
  59. )
  60. var resizeTypes = map[string]resizeType{
  61. "fit": resizeFit,
  62. "fill": resizeFill,
  63. "crop": resizeCrop,
  64. }
  65. type color struct{ R, G, B uint8 }
  66. type processingOptions struct {
  67. Resize resizeType
  68. Width int
  69. Height int
  70. Gravity gravity
  71. Enlarge bool
  72. Format imageType
  73. Flatten bool
  74. Background color
  75. Blur float32
  76. Sharpen float32
  77. }
  78. func (it imageType) String() string {
  79. for k, v := range imageTypes {
  80. if v == it {
  81. return k
  82. }
  83. }
  84. return ""
  85. }
  86. func (gt gravityType) String() string {
  87. for k, v := range gravityTypes {
  88. if v == gt {
  89. return k
  90. }
  91. }
  92. return ""
  93. }
  94. func (rt resizeType) String() string {
  95. for k, v := range resizeTypes {
  96. if v == rt {
  97. return k
  98. }
  99. }
  100. return ""
  101. }
  102. func decodeURL(parts []string) (string, string, error) {
  103. var extension string
  104. urlParts := strings.Split(strings.Join(parts, ""), ".")
  105. if len(urlParts) > 2 {
  106. return "", "", errors.New("Invalid url encoding")
  107. }
  108. if len(urlParts) == 2 {
  109. extension = urlParts[1]
  110. }
  111. url, err := base64.RawURLEncoding.DecodeString(urlParts[0])
  112. if err != nil {
  113. return "", "", errors.New("Invalid url encoding")
  114. }
  115. return string(url), extension, nil
  116. }
  117. func applyWidthOption(po *processingOptions, args []string) error {
  118. if len(args) > 1 {
  119. return fmt.Errorf("Invalid width arguments: %v", args)
  120. }
  121. if w, err := strconv.Atoi(args[0]); err == nil && w >= 0 {
  122. po.Width = w
  123. } else {
  124. return fmt.Errorf("Invalid width: %s", args[0])
  125. }
  126. return nil
  127. }
  128. func applyHeightOption(po *processingOptions, args []string) error {
  129. if len(args) > 1 {
  130. return fmt.Errorf("Invalid height arguments: %v", args)
  131. }
  132. if h, err := strconv.Atoi(args[0]); err == nil && po.Height >= 0 {
  133. po.Height = h
  134. } else {
  135. return fmt.Errorf("Invalid height: %s", args[0])
  136. }
  137. return nil
  138. }
  139. func applyEnlargeOption(po *processingOptions, args []string) error {
  140. if len(args) > 1 {
  141. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  142. }
  143. po.Enlarge = args[0] != "0"
  144. return nil
  145. }
  146. func applySizeOption(po *processingOptions, args []string) (err error) {
  147. if len(args) > 3 {
  148. return fmt.Errorf("Invalid size arguments: %v", args)
  149. }
  150. if len(args) >= 1 && len(args[0]) > 0 {
  151. if err = applyWidthOption(po, args[0:1]); err != nil {
  152. return
  153. }
  154. }
  155. if len(args) >= 2 && len(args[1]) > 0 {
  156. if err = applyHeightOption(po, args[1:2]); err != nil {
  157. return
  158. }
  159. }
  160. if len(args) == 3 && len(args[2]) > 0 {
  161. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  162. return
  163. }
  164. }
  165. return nil
  166. }
  167. func applyResizingTypeOption(po *processingOptions, args []string) error {
  168. if len(args) > 1 {
  169. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  170. }
  171. if r, ok := resizeTypes[args[0]]; ok {
  172. po.Resize = r
  173. } else {
  174. return fmt.Errorf("Invalid resize type: %s", args[0])
  175. }
  176. return nil
  177. }
  178. func applyResizeOption(po *processingOptions, args []string) error {
  179. if len(args) > 4 {
  180. return fmt.Errorf("Invalid resize arguments: %v", args)
  181. }
  182. if len(args[0]) > 0 {
  183. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  184. return err
  185. }
  186. }
  187. if len(args) > 1 {
  188. if err := applySizeOption(po, args[1:]); err != nil {
  189. return err
  190. }
  191. }
  192. return nil
  193. }
  194. func applyGravityOption(po *processingOptions, args []string) error {
  195. if g, ok := gravityTypes[args[0]]; ok {
  196. po.Gravity.Type = g
  197. } else {
  198. return fmt.Errorf("Invalid gravity: %s", args[0])
  199. }
  200. if po.Gravity.Type == gravityFocusPoint {
  201. if len(args) != 3 {
  202. return fmt.Errorf("Invalid gravity arguments: %v", args)
  203. }
  204. if x, err := strconv.ParseFloat(args[1], 64); err == nil && x >= 0 && x <= 1 {
  205. po.Gravity.X = x
  206. } else {
  207. return fmt.Errorf("Invalid gravity X: %s", args[1])
  208. }
  209. if y, err := strconv.ParseFloat(args[2], 64); err == nil && y >= 0 && y <= 1 {
  210. po.Gravity.Y = y
  211. } else {
  212. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  213. }
  214. } else if len(args) > 1 {
  215. return fmt.Errorf("Invalid gravity arguments: %v", args)
  216. }
  217. return nil
  218. }
  219. func applyBackgroundOption(po *processingOptions, args []string) error {
  220. if len(args) != 3 {
  221. return fmt.Errorf("Invalid background arguments: %v", args)
  222. }
  223. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r >= 0 && r <= 255 {
  224. po.Background.R = uint8(r)
  225. } else {
  226. return fmt.Errorf("Invalid background red channel: %s", args[1])
  227. }
  228. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g >= 0 && g <= 255 {
  229. po.Background.G = uint8(g)
  230. } else {
  231. return fmt.Errorf("Invalid background green channel: %s", args[1])
  232. }
  233. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b >= 0 && b <= 255 {
  234. po.Background.B = uint8(b)
  235. } else {
  236. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  237. }
  238. po.Flatten = true
  239. return nil
  240. }
  241. func applyBlurOption(po *processingOptions, args []string) error {
  242. if len(args) > 1 {
  243. return fmt.Errorf("Invalid blur arguments: %v", args)
  244. }
  245. if b, err := strconv.ParseFloat(args[0], 32); err == nil || b >= 0 {
  246. po.Blur = float32(b)
  247. } else {
  248. return fmt.Errorf("Invalid blur: %s", args[0])
  249. }
  250. return nil
  251. }
  252. func applySharpenOption(po *processingOptions, args []string) error {
  253. if len(args) > 1 {
  254. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  255. }
  256. if s, err := strconv.ParseFloat(args[0], 32); err == nil || s >= 0 {
  257. po.Sharpen = float32(s)
  258. } else {
  259. return fmt.Errorf("Invalid sharpen: %s", args[0])
  260. }
  261. return nil
  262. }
  263. func applyPresetOption(po *processingOptions, args []string) error {
  264. for _, preset := range args {
  265. if p, ok := conf.Presets[preset]; ok {
  266. if err := applyProcessingOptions(po, p); err != nil {
  267. return err
  268. }
  269. } else {
  270. return fmt.Errorf("Unknown asset: %s", preset)
  271. }
  272. }
  273. return nil
  274. }
  275. func applyFormatOption(po *processingOptions, args []string) error {
  276. if len(args) > 1 {
  277. return fmt.Errorf("Invalid format arguments: %v", args)
  278. }
  279. if conf.EnforceWebp && po.Format == imageTypeWEBP {
  280. // Webp is enforced and already set as format
  281. return nil
  282. }
  283. if f, ok := imageTypes[args[0]]; ok {
  284. po.Format = f
  285. } else {
  286. return fmt.Errorf("Invalid image format: %s", args[0])
  287. }
  288. if !vipsTypeSupportSave[po.Format] {
  289. return errors.New("Resulting image type not supported")
  290. }
  291. return nil
  292. }
  293. func applyProcessingOption(po *processingOptions, name string, args []string) error {
  294. switch name {
  295. case "format":
  296. if err := applyFormatOption(po, args); err != nil {
  297. return err
  298. }
  299. case "resize":
  300. if err := applyResizeOption(po, args); err != nil {
  301. return err
  302. }
  303. case "resizing_type":
  304. if err := applyResizingTypeOption(po, args); err != nil {
  305. return err
  306. }
  307. case "size":
  308. if err := applySizeOption(po, args); err != nil {
  309. return err
  310. }
  311. case "width":
  312. if err := applyWidthOption(po, args); err != nil {
  313. return err
  314. }
  315. case "height":
  316. if err := applyHeightOption(po, args); err != nil {
  317. return err
  318. }
  319. case "enlarge":
  320. if err := applyEnlargeOption(po, args); err != nil {
  321. return err
  322. }
  323. case "gravity":
  324. if err := applyGravityOption(po, args); err != nil {
  325. return err
  326. }
  327. case "background":
  328. if err := applyBackgroundOption(po, args); err != nil {
  329. return err
  330. }
  331. case "blur":
  332. if err := applyBlurOption(po, args); err != nil {
  333. return err
  334. }
  335. case "sharpen":
  336. if err := applySharpenOption(po, args); err != nil {
  337. return err
  338. }
  339. case "preset":
  340. if err := applyPresetOption(po, args); err != nil {
  341. return err
  342. }
  343. default:
  344. return fmt.Errorf("Unknown processing option: %s", name)
  345. }
  346. return nil
  347. }
  348. func applyProcessingOptions(po *processingOptions, options urlOptions) error {
  349. for name, args := range options {
  350. if err := applyProcessingOption(po, name, args); err != nil {
  351. return err
  352. }
  353. }
  354. return nil
  355. }
  356. func parseURLOptions(opts []string) (urlOptions, []string) {
  357. parsed := make(urlOptions)
  358. urlStart := len(opts) + 1
  359. for i, opt := range opts {
  360. args := strings.Split(opt, ":")
  361. if len(args) == 1 {
  362. urlStart = i
  363. break
  364. }
  365. parsed[args[0]] = args[1:]
  366. }
  367. var rest []string
  368. if urlStart < len(opts) {
  369. rest = opts[urlStart:]
  370. } else {
  371. rest = []string{}
  372. }
  373. return parsed, rest
  374. }
  375. func defaultProcessingOptions(acceptHeader string) (processingOptions, error) {
  376. var err error
  377. po := processingOptions{
  378. Resize: resizeFit,
  379. Width: 0,
  380. Height: 0,
  381. Gravity: gravity{Type: gravityCenter},
  382. Enlarge: false,
  383. Format: imageTypeJPEG,
  384. Blur: 0,
  385. Sharpen: 0,
  386. }
  387. if (conf.EnableWebpDetection || conf.EnforceWebp) && strings.Contains(acceptHeader, "image/webp") {
  388. po.Format = imageTypeWEBP
  389. }
  390. if _, ok := conf.Presets["default"]; ok {
  391. err = applyPresetOption(&po, []string{"default"})
  392. }
  393. return po, err
  394. }
  395. func parsePathAdvanced(parts []string, acceptHeader string) (string, processingOptions, error) {
  396. po, err := defaultProcessingOptions(acceptHeader)
  397. if err != nil {
  398. return "", po, err
  399. }
  400. options, urlParts := parseURLOptions(parts)
  401. if err := applyProcessingOptions(&po, options); err != nil {
  402. return "", po, err
  403. }
  404. url, extension, err := decodeURL(urlParts)
  405. if err != nil {
  406. return "", po, err
  407. }
  408. if len(extension) > 0 {
  409. if err := applyFormatOption(&po, []string{extension}); err != nil {
  410. return "", po, errors.New("Resulting image type not supported")
  411. }
  412. }
  413. return string(url), po, nil
  414. }
  415. func parsePathSimple(parts []string, acceptHeader string) (string, processingOptions, error) {
  416. var err error
  417. if len(parts) < 6 {
  418. return "", processingOptions{}, errors.New("Invalid path")
  419. }
  420. po, err := defaultProcessingOptions(acceptHeader)
  421. if err != nil {
  422. return "", po, err
  423. }
  424. po.Resize = resizeTypes[parts[0]]
  425. if err = applyWidthOption(&po, parts[1:2]); err != nil {
  426. return "", po, err
  427. }
  428. if err = applyHeightOption(&po, parts[2:3]); err != nil {
  429. return "", po, err
  430. }
  431. if err = applyGravityOption(&po, strings.Split(parts[3], ":")); err != nil {
  432. return "", po, err
  433. }
  434. if err = applyEnlargeOption(&po, parts[4:5]); err != nil {
  435. return "", po, err
  436. }
  437. url, extension, err := decodeURL(parts[5:])
  438. if err != nil {
  439. return "", po, err
  440. }
  441. if len(extension) > 0 {
  442. if err := applyFormatOption(&po, []string{extension}); err != nil {
  443. return "", po, errors.New("Resulting image type not supported")
  444. }
  445. }
  446. return string(url), po, nil
  447. }
  448. func parsePath(r *http.Request) (string, processingOptions, error) {
  449. path := r.URL.Path
  450. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  451. var acceptHeader string
  452. if h, ok := r.Header["Accept"]; ok {
  453. acceptHeader = h[0]
  454. }
  455. if len(parts) < 3 {
  456. return "", processingOptions{}, errors.New("Invalid path")
  457. }
  458. if !conf.AllowInsecure {
  459. if err := validatePath(parts[0], strings.TrimPrefix(path, fmt.Sprintf("/%s", parts[0]))); err != nil {
  460. return "", processingOptions{}, err
  461. }
  462. }
  463. if _, ok := resizeTypes[parts[1]]; ok {
  464. return parsePathSimple(parts[1:], acceptHeader)
  465. }
  466. return parsePathAdvanced(parts[1:], acceptHeader)
  467. }