actions.go 8.6 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("action '%s' unknown", 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, 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 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. } else if a == nil {
  110. return actions, 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. fmt.Printf("--> key=%s, value=%s, last=%t, err=%#v\n", key, value, last, err)
  125. if err != nil {
  126. return nil, err
  127. }
  128. if err := populateAction(a, section, key, value); err != nil {
  129. return nil, err
  130. }
  131. p.slurpSpaces()
  132. if last {
  133. return a, nil
  134. }
  135. section++
  136. }
  137. }
  138. // populateAction is the "business logic" of the parser. It applies the key/value
  139. // pair to the action instance.
  140. func populateAction(newAction *action, section int, key, value string) error {
  141. // Auto-expand keys based on their index
  142. if key == "" && section == 0 {
  143. key = "action"
  144. } else if key == "" && section == 1 {
  145. key = "label"
  146. } else if key == "" && section == 2 && util.InStringList(actionsWithURL, newAction.Action) {
  147. key = "url"
  148. }
  149. // Validate
  150. if key == "" {
  151. return fmt.Errorf("term '%s' unknown", value)
  152. }
  153. // Populate
  154. if strings.HasPrefix(key, "headers.") {
  155. newAction.Headers[strings.TrimPrefix(key, "headers.")] = value
  156. } else if strings.HasPrefix(key, "extras.") {
  157. newAction.Extras[strings.TrimPrefix(key, "extras.")] = value
  158. } else {
  159. switch strings.ToLower(key) {
  160. case "action":
  161. newAction.Action = value
  162. case "label":
  163. newAction.Label = value
  164. case "clear":
  165. lvalue := strings.ToLower(value)
  166. if !util.InStringList([]string{"true", "yes", "1", "false", "no", "0"}, lvalue) {
  167. return fmt.Errorf("'clear=%s' not allowed", value)
  168. }
  169. newAction.Clear = lvalue == "true" || lvalue == "yes" || lvalue == "1"
  170. case "url":
  171. newAction.URL = value
  172. case "method":
  173. newAction.Method = value
  174. case "body":
  175. newAction.Body = value
  176. default:
  177. return fmt.Errorf("key '%s' unknown", key)
  178. }
  179. }
  180. return nil
  181. }
  182. // parseSection parses a section ("key=value") and returns a key/value pair. It terminates
  183. // when EOF or "," is reached.
  184. func (p *actionParser) parseSection() (key string, value string, last bool, err error) {
  185. p.slurpSpaces()
  186. key = p.parseKey()
  187. r, w := p.peek()
  188. if isSectionEnd(r) {
  189. p.pos += w
  190. last = isLastSection(r)
  191. return
  192. } else if r == '"' || r == '\'' {
  193. value, last, err = p.parseQuotedValue(r)
  194. return
  195. }
  196. value, last = p.parseValue()
  197. return
  198. }
  199. // parseKey uses a regex to determine whether the current position is a key definition ("key =")
  200. // and returns the key if it is, or an empty string otherwise.
  201. func (p *actionParser) parseKey() string {
  202. matches := actionsKeyRegex.FindStringSubmatch(p.input[p.pos:])
  203. if len(matches) == 2 {
  204. p.pos += len(matches[0])
  205. return matches[1]
  206. }
  207. return ""
  208. }
  209. // parseValue reads the input until EOF, "," or ";" and returns the value string. Unlike parseQuotedValue,
  210. // this function does not support "," or ";" in the value itself.
  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 = 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 = p.input[start:p.pos]
  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. }