actions.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "heckel.io/ntfy/v2/util"
  7. "regexp"
  8. "strings"
  9. "unicode/utf8"
  10. )
  11. const (
  12. actionIDLength = 10
  13. actionEOF = rune(0)
  14. actionsMax = 3
  15. )
  16. const (
  17. actionView = "view"
  18. actionBroadcast = "broadcast"
  19. actionHTTP = "http"
  20. )
  21. var (
  22. actionsAll = []string{actionView, actionBroadcast, actionHTTP}
  23. actionsWithURL = []string{actionView, actionHTTP}
  24. actionsKeyRegex = regexp.MustCompile(`^([-.\w]+)\s*=\s*`)
  25. )
  26. type actionParser struct {
  27. input string
  28. pos int
  29. }
  30. // parseActions parses the actions string as described in https://ntfy.sh/docs/publish/#action-buttons.
  31. // It supports both a JSON representation (if the string begins with "[", see parseActionsFromJSON),
  32. // and the "simple" format, which is more human-readable, but harder to parse (see parseActionsFromSimple).
  33. func parseActions(s string) (actions []*action, err error) {
  34. // Parse JSON or simple format
  35. s = strings.TrimSpace(s)
  36. if strings.HasPrefix(s, "[") {
  37. actions, err = parseActionsFromJSON(s)
  38. } else {
  39. actions, err = parseActionsFromSimple(s)
  40. }
  41. if err != nil {
  42. return nil, err
  43. }
  44. // Add ID field, ensure correct uppercase/lowercase
  45. for i := range actions {
  46. actions[i].ID = util.RandomString(actionIDLength)
  47. actions[i].Action = strings.ToLower(actions[i].Action)
  48. actions[i].Method = strings.ToUpper(actions[i].Method)
  49. }
  50. // Validate
  51. if len(actions) > actionsMax {
  52. return nil, fmt.Errorf("only %d actions allowed", actionsMax)
  53. }
  54. for _, action := range actions {
  55. if !util.Contains(actionsAll, action.Action) {
  56. return nil, fmt.Errorf("parameter 'action' cannot be '%s', valid values are 'view', 'broadcast' and 'http'", action.Action)
  57. } else if action.Label == "" {
  58. return nil, fmt.Errorf("parameter 'label' is required")
  59. } else if util.Contains(actionsWithURL, action.Action) && action.URL == "" {
  60. return nil, fmt.Errorf("parameter 'url' is required for action '%s'", action.Action)
  61. } else if action.Action == actionHTTP && util.Contains([]string{"GET", "HEAD"}, action.Method) && action.Body != "" {
  62. return nil, fmt.Errorf("parameter 'body' cannot be set if method is %s", action.Method)
  63. }
  64. }
  65. return actions, nil
  66. }
  67. // parseActionsFromJSON converts a JSON array into an array of actions
  68. func parseActionsFromJSON(s string) ([]*action, error) {
  69. actions := make([]*action, 0)
  70. if err := json.Unmarshal([]byte(s), &actions); err != nil {
  71. return nil, fmt.Errorf("JSON error: %w", err)
  72. }
  73. return actions, nil
  74. }
  75. // parseActionsFromSimple parses the "simple" actions string (as described in
  76. // https://ntfy.sh/docs/publish/#action-buttons), into an array of actions.
  77. //
  78. // It can parse an actions string like this:
  79. //
  80. // view, "Look ma, commas and \"quotes\" too", url=https://..; action=broadcast, ...
  81. //
  82. // It works by advancing the position ("pos") through the input string ("input").
  83. //
  84. // The parser is heavily inspired by https://go.dev/src/text/template/parse/lex.go (which
  85. // is described by Rob Pike in this video: https://www.youtube.com/watch?v=HxaD_trXwRE),
  86. // though it does not use state functions at all.
  87. //
  88. // Other resources:
  89. //
  90. // https://adampresley.github.io/2015/04/12/writing-a-lexer-and-parser-in-go-part-1.html
  91. // https://github.com/adampresley/sample-ini-parser/blob/master/services/lexer/lexer/Lexer.go
  92. // https://github.com/benbjohnson/sql-parser/blob/master/scanner.go
  93. // https://blog.gopheracademy.com/advent-2014/parsers-lexers/
  94. func parseActionsFromSimple(s string) ([]*action, error) {
  95. if !utf8.ValidString(s) {
  96. return nil, errors.New("invalid utf-8 string")
  97. }
  98. parser := &actionParser{
  99. pos: 0,
  100. input: s,
  101. }
  102. return parser.Parse()
  103. }
  104. // Parse loops trough parseAction() until the end of the string is reached
  105. func (p *actionParser) Parse() ([]*action, error) {
  106. actions := make([]*action, 0)
  107. for !p.eof() {
  108. a, err := p.parseAction()
  109. if err != nil {
  110. return nil, err
  111. }
  112. actions = append(actions, a)
  113. }
  114. return actions, nil
  115. }
  116. // parseAction parses the individual sections of an action using parseSection into key/value pairs,
  117. // and then uses populateAction to interpret the keys/values. The function terminates
  118. // when EOF or ";" is reached.
  119. func (p *actionParser) parseAction() (*action, error) {
  120. a := newAction()
  121. section := 0
  122. for {
  123. key, value, last, err := p.parseSection()
  124. if err != nil {
  125. return nil, err
  126. }
  127. if err := populateAction(a, section, key, value); err != nil {
  128. return nil, err
  129. }
  130. p.slurpSpaces()
  131. if last {
  132. return a, nil
  133. }
  134. section++
  135. }
  136. }
  137. // populateAction is the "business logic" of the parser. It applies the key/value
  138. // pair to the action instance.
  139. func populateAction(newAction *action, section int, key, value string) error {
  140. // Auto-expand keys based on their index
  141. if key == "" && section == 0 {
  142. key = "action"
  143. } else if key == "" && section == 1 {
  144. key = "label"
  145. } else if key == "" && section == 2 && util.Contains(actionsWithURL, newAction.Action) {
  146. key = "url"
  147. }
  148. // Validate
  149. if key == "" {
  150. return fmt.Errorf("term '%s' unknown", value)
  151. }
  152. // Populate
  153. if strings.HasPrefix(key, "headers.") {
  154. newAction.Headers[strings.TrimPrefix(key, "headers.")] = value
  155. } else if strings.HasPrefix(key, "extras.") {
  156. newAction.Extras[strings.TrimPrefix(key, "extras.")] = value
  157. } else {
  158. switch strings.ToLower(key) {
  159. case "action":
  160. newAction.Action = value
  161. case "label":
  162. newAction.Label = value
  163. case "clear":
  164. lvalue := strings.ToLower(value)
  165. if !util.Contains([]string{"true", "yes", "1", "false", "no", "0"}, lvalue) {
  166. return fmt.Errorf("parameter 'clear' cannot be '%s', only boolean values are allowed (true/yes/1/false/no/0)", value)
  167. }
  168. newAction.Clear = lvalue == "true" || lvalue == "yes" || lvalue == "1"
  169. case "url":
  170. newAction.URL = value
  171. case "method":
  172. newAction.Method = value
  173. case "body":
  174. newAction.Body = value
  175. case "intent":
  176. newAction.Intent = value
  177. default:
  178. return fmt.Errorf("key '%s' unknown", key)
  179. }
  180. }
  181. return nil
  182. }
  183. // parseSection parses a section ("key=value") and returns a key/value pair. It terminates
  184. // when EOF or "," is reached.
  185. func (p *actionParser) parseSection() (key string, value string, last bool, err error) {
  186. p.slurpSpaces()
  187. key = p.parseKey()
  188. r, w := p.peek()
  189. if isSectionEnd(r) {
  190. p.pos += w
  191. last = isLastSection(r)
  192. return
  193. } else if r == '"' || r == '\'' {
  194. value, last, err = p.parseQuotedValue(r)
  195. return
  196. }
  197. value, last = p.parseValue()
  198. return
  199. }
  200. // parseKey uses a regex to determine whether the current position is a key definition ("key =")
  201. // and returns the key if it is, or an empty string otherwise.
  202. func (p *actionParser) parseKey() string {
  203. matches := actionsKeyRegex.FindStringSubmatch(p.input[p.pos:])
  204. if len(matches) == 2 {
  205. p.pos += len(matches[0])
  206. return matches[1]
  207. }
  208. return ""
  209. }
  210. // parseValue reads the input until EOF, "," or ";" and returns the value string. Unlike parseQuotedValue,
  211. // this function does not support "," or ";" in the value itself, and spaces in the beginning and end of the
  212. // string are trimmed.
  213. func (p *actionParser) parseValue() (value string, last bool) {
  214. start := p.pos
  215. for {
  216. r, w := p.peek()
  217. if isSectionEnd(r) {
  218. last = isLastSection(r)
  219. value = strings.TrimSpace(p.input[start:p.pos])
  220. p.pos += w
  221. return
  222. }
  223. p.pos += w
  224. }
  225. }
  226. // parseQuotedValue reads the input until it finds an unescaped end quote character ("), and then
  227. // advances the position beyond the section end. It supports quoting strings using backslash (\).
  228. func (p *actionParser) parseQuotedValue(quote rune) (value string, last bool, err error) {
  229. p.pos++
  230. start := p.pos
  231. var prev rune
  232. for {
  233. r, w := p.peek()
  234. if r == actionEOF {
  235. err = fmt.Errorf("unexpected end of input, quote started at position %d", start)
  236. return
  237. } else if r == quote && prev != '\\' {
  238. value = strings.ReplaceAll(p.input[start:p.pos], "\\"+string(quote), string(quote)) // \" -> "
  239. p.pos += w
  240. // Advance until section end (after "," or ";")
  241. p.slurpSpaces()
  242. r, w := p.peek()
  243. last = isLastSection(r)
  244. if !isSectionEnd(r) {
  245. err = fmt.Errorf("unexpected character '%c' at position %d", r, p.pos)
  246. return
  247. }
  248. p.pos += w
  249. return
  250. }
  251. prev = r
  252. p.pos += w
  253. }
  254. }
  255. // slurpSpaces reads all space characters and advances the position
  256. func (p *actionParser) slurpSpaces() {
  257. for {
  258. r, w := p.peek()
  259. if r == actionEOF || !isSpace(r) {
  260. return
  261. }
  262. p.pos += w
  263. }
  264. }
  265. // peek returns the next run and its width
  266. func (p *actionParser) peek() (rune, int) {
  267. if p.eof() {
  268. return actionEOF, 0
  269. }
  270. return utf8.DecodeRuneInString(p.input[p.pos:])
  271. }
  272. // eof returns true if the end of the input has been reached
  273. func (p *actionParser) eof() bool {
  274. return p.pos >= len(p.input)
  275. }
  276. func isSpace(r rune) bool {
  277. return r == ' ' || r == '\t' || r == '\r' || r == '\n'
  278. }
  279. func isSectionEnd(r rune) bool {
  280. return r == actionEOF || r == ';' || r == ','
  281. }
  282. func isLastSection(r rune) bool {
  283. return r == actionEOF || r == ';'
  284. }