actions.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. default:
  174. return fmt.Errorf("key '%s' unknown", key)
  175. }
  176. }
  177. return nil
  178. }
  179. // parseSection parses a section ("key=value") and returns a key/value pair. It terminates
  180. // when EOF or "," is reached.
  181. func (p *actionParser) parseSection() (key string, value string, last bool, err error) {
  182. p.slurpSpaces()
  183. key = p.parseKey()
  184. r, w := p.peek()
  185. if isSectionEnd(r) {
  186. p.pos += w
  187. last = isLastSection(r)
  188. return
  189. } else if r == '"' || r == '\'' {
  190. value, last, err = p.parseQuotedValue(r)
  191. return
  192. }
  193. value, last = p.parseValue()
  194. return
  195. }
  196. // parseKey uses a regex to determine whether the current position is a key definition ("key =")
  197. // and returns the key if it is, or an empty string otherwise.
  198. func (p *actionParser) parseKey() string {
  199. matches := actionsKeyRegex.FindStringSubmatch(p.input[p.pos:])
  200. if len(matches) == 2 {
  201. p.pos += len(matches[0])
  202. return matches[1]
  203. }
  204. return ""
  205. }
  206. // parseValue reads the input until EOF, "," or ";" and returns the value string. Unlike parseQuotedValue,
  207. // this function does not support "," or ";" in the value itself, and spaces in the beginning and end of the
  208. // string are trimmed.
  209. func (p *actionParser) parseValue() (value string, last bool) {
  210. start := p.pos
  211. for {
  212. r, w := p.peek()
  213. if isSectionEnd(r) {
  214. last = isLastSection(r)
  215. value = strings.TrimSpace(p.input[start:p.pos])
  216. p.pos += w
  217. return
  218. }
  219. p.pos += w
  220. }
  221. }
  222. // parseQuotedValue reads the input until it finds an unescaped end quote character ("), and then
  223. // advances the position beyond the section end. It supports quoting strings using backslash (\).
  224. func (p *actionParser) parseQuotedValue(quote rune) (value string, last bool, err error) {
  225. p.pos++
  226. start := p.pos
  227. var prev rune
  228. for {
  229. r, w := p.peek()
  230. if r == actionEOF {
  231. err = fmt.Errorf("unexpected end of input, quote started at position %d", start)
  232. return
  233. } else if r == quote && prev != '\\' {
  234. value = strings.ReplaceAll(p.input[start:p.pos], "\\"+string(quote), string(quote)) // \" -> "
  235. p.pos += w
  236. // Advance until section end (after "," or ";")
  237. p.slurpSpaces()
  238. r, w := p.peek()
  239. last = isLastSection(r)
  240. if !isSectionEnd(r) {
  241. err = fmt.Errorf("unexpected character '%c' at position %d", r, p.pos)
  242. return
  243. }
  244. p.pos += w
  245. return
  246. }
  247. prev = r
  248. p.pos += w
  249. }
  250. }
  251. // slurpSpaces reads all space characters and advances the position
  252. func (p *actionParser) slurpSpaces() {
  253. for {
  254. r, w := p.peek()
  255. if r == actionEOF || !isSpace(r) {
  256. return
  257. }
  258. p.pos += w
  259. }
  260. }
  261. // peek returns the next run and its width
  262. func (p *actionParser) peek() (rune, int) {
  263. if p.eof() {
  264. return actionEOF, 0
  265. }
  266. return utf8.DecodeRuneInString(p.input[p.pos:])
  267. }
  268. // eof returns true if the end of the input has been reached
  269. func (p *actionParser) eof() bool {
  270. return p.pos >= len(p.input)
  271. }
  272. func isSpace(r rune) bool {
  273. return r == ' ' || r == '\t' || r == '\r' || r == '\n'
  274. }
  275. func isSectionEnd(r rune) bool {
  276. return r == actionEOF || r == ';' || r == ','
  277. }
  278. func isLastSection(r rune) bool {
  279. return r == actionEOF || r == ';'
  280. }