actions.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "heckel.io/ntfy/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.InStringList(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.InStringList(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.InStringList([]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. // view, "Look ma, commas and \"quotes\" too", url=https://..; action=broadcast, ...
  80. //
  81. // It works by advancing the position ("pos") through the input string ("input").
  82. //
  83. // The parser is heavily inspired by https://go.dev/src/text/template/parse/lex.go (which
  84. // is described by Rob Pike in this video: https://www.youtube.com/watch?v=HxaD_trXwRE),
  85. // though it does not use state functions at all.
  86. //
  87. // Other resources:
  88. // https://adampresley.github.io/2015/04/12/writing-a-lexer-and-parser-in-go-part-1.html
  89. // https://github.com/adampresley/sample-ini-parser/blob/master/services/lexer/lexer/Lexer.go
  90. // https://github.com/benbjohnson/sql-parser/blob/master/scanner.go
  91. // https://blog.gopheracademy.com/advent-2014/parsers-lexers/
  92. func parseActionsFromSimple(s string) ([]*action, error) {
  93. if !utf8.ValidString(s) {
  94. return nil, errors.New("invalid utf-8 string")
  95. }
  96. parser := &actionParser{
  97. pos: 0,
  98. input: s,
  99. }
  100. return parser.Parse()
  101. }
  102. // Parse loops trough parseAction() until the end of the string is reached
  103. func (p *actionParser) Parse() ([]*action, error) {
  104. actions := make([]*action, 0)
  105. for !p.eof() {
  106. a, err := p.parseAction()
  107. if err != nil {
  108. return nil, err
  109. }
  110. actions = append(actions, a)
  111. }
  112. return actions, nil
  113. }
  114. // parseAction parses the individual sections of an action using parseSection into key/value pairs,
  115. // and then uses populateAction to interpret the keys/values. The function terminates
  116. // when EOF or ";" is reached.
  117. func (p *actionParser) parseAction() (*action, error) {
  118. a := newAction()
  119. section := 0
  120. for {
  121. key, value, last, err := p.parseSection()
  122. if err != nil {
  123. return nil, err
  124. }
  125. if err := populateAction(a, section, key, value); err != nil {
  126. return nil, err
  127. }
  128. p.slurpSpaces()
  129. if last {
  130. return a, nil
  131. }
  132. section++
  133. }
  134. }
  135. // populateAction is the "business logic" of the parser. It applies the key/value
  136. // pair to the action instance.
  137. func populateAction(newAction *action, section int, key, value string) error {
  138. // Auto-expand keys based on their index
  139. if key == "" && section == 0 {
  140. key = "action"
  141. } else if key == "" && section == 1 {
  142. key = "label"
  143. } else if key == "" && section == 2 && util.InStringList(actionsWithURL, newAction.Action) {
  144. key = "url"
  145. }
  146. // Validate
  147. if key == "" {
  148. return fmt.Errorf("term '%s' unknown", value)
  149. }
  150. // Populate
  151. if strings.HasPrefix(key, "headers.") {
  152. newAction.Headers[strings.TrimPrefix(key, "headers.")] = value
  153. } else if strings.HasPrefix(key, "extras.") {
  154. newAction.Extras[strings.TrimPrefix(key, "extras.")] = value
  155. } else {
  156. switch strings.ToLower(key) {
  157. case "action":
  158. newAction.Action = value
  159. case "label":
  160. newAction.Label = value
  161. case "clear":
  162. lvalue := strings.ToLower(value)
  163. if !util.InStringList([]string{"true", "yes", "1", "false", "no", "0"}, lvalue) {
  164. return fmt.Errorf("parameter 'clear' cannot be '%s', only boolean values are allowed (true/yes/1/false/no/0)", value)
  165. }
  166. newAction.Clear = lvalue == "true" || lvalue == "yes" || lvalue == "1"
  167. case "url":
  168. newAction.URL = value
  169. case "method":
  170. newAction.Method = value
  171. case "body":
  172. newAction.Body = value
  173. case "intent":
  174. newAction.Intent = value
  175. default:
  176. return fmt.Errorf("key '%s' unknown", key)
  177. }
  178. }
  179. return nil
  180. }
  181. // parseSection parses a section ("key=value") and returns a key/value pair. It terminates
  182. // when EOF or "," is reached.
  183. func (p *actionParser) parseSection() (key string, value string, last bool, err error) {
  184. p.slurpSpaces()
  185. key = p.parseKey()
  186. r, w := p.peek()
  187. if isSectionEnd(r) {
  188. p.pos += w
  189. last = isLastSection(r)
  190. return
  191. } else if r == '"' || r == '\'' {
  192. value, last, err = p.parseQuotedValue(r)
  193. return
  194. }
  195. value, last = p.parseValue()
  196. return
  197. }
  198. // parseKey uses a regex to determine whether the current position is a key definition ("key =")
  199. // and returns the key if it is, or an empty string otherwise.
  200. func (p *actionParser) parseKey() string {
  201. matches := actionsKeyRegex.FindStringSubmatch(p.input[p.pos:])
  202. if len(matches) == 2 {
  203. p.pos += len(matches[0])
  204. return matches[1]
  205. }
  206. return ""
  207. }
  208. // parseValue reads the input until EOF, "," or ";" and returns the value string. Unlike parseQuotedValue,
  209. // this function does not support "," or ";" in the value itself, and spaces in the beginning and end of the
  210. // string are trimmed.
  211. func (p *actionParser) parseValue() (value string, last bool) {
  212. start := p.pos
  213. for {
  214. r, w := p.peek()
  215. if isSectionEnd(r) {
  216. last = isLastSection(r)
  217. value = strings.TrimSpace(p.input[start:p.pos])
  218. p.pos += w
  219. return
  220. }
  221. p.pos += w
  222. }
  223. }
  224. // parseQuotedValue reads the input until it finds an unescaped end quote character ("), and then
  225. // advances the position beyond the section end. It supports quoting strings using backslash (\).
  226. func (p *actionParser) parseQuotedValue(quote rune) (value string, last bool, err error) {
  227. p.pos++
  228. start := p.pos
  229. var prev rune
  230. for {
  231. r, w := p.peek()
  232. if r == actionEOF {
  233. err = fmt.Errorf("unexpected end of input, quote started at position %d", start)
  234. return
  235. } else if r == quote && prev != '\\' {
  236. value = strings.ReplaceAll(p.input[start:p.pos], "\\"+string(quote), string(quote)) // \" -> "
  237. p.pos += w
  238. // Advance until section end (after "," or ";")
  239. p.slurpSpaces()
  240. r, w := p.peek()
  241. last = isLastSection(r)
  242. if !isSectionEnd(r) {
  243. err = fmt.Errorf("unexpected character '%c' at position %d", r, p.pos)
  244. return
  245. }
  246. p.pos += w
  247. return
  248. }
  249. prev = r
  250. p.pos += w
  251. }
  252. }
  253. // slurpSpaces reads all space characters and advances the position
  254. func (p *actionParser) slurpSpaces() {
  255. for {
  256. r, w := p.peek()
  257. if r == actionEOF || !isSpace(r) {
  258. return
  259. }
  260. p.pos += w
  261. }
  262. }
  263. // peek returns the next run and its width
  264. func (p *actionParser) peek() (rune, int) {
  265. if p.eof() {
  266. return actionEOF, 0
  267. }
  268. return utf8.DecodeRuneInString(p.input[p.pos:])
  269. }
  270. // eof returns true if the end of the input has been reached
  271. func (p *actionParser) eof() bool {
  272. return p.pos >= len(p.input)
  273. }
  274. func isSpace(r rune) bool {
  275. return r == ' ' || r == '\t' || r == '\r' || r == '\n'
  276. }
  277. func isSectionEnd(r rune) bool {
  278. return r == actionEOF || r == ';' || r == ','
  279. }
  280. func isLastSection(r rune) bool {
  281. return r == actionEOF || r == ';'
  282. }