You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

znc.go 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. // Copyright (c) 2019 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/oragono/oragono/irc/history"
  10. )
  11. const (
  12. // #829, also see "Case 2" in the "three cases" below:
  13. zncPlaybackCommandExpiration = time.Second * 30
  14. )
  15. type zncCommandHandler func(client *Client, command string, params []string, rb *ResponseBuffer)
  16. var zncHandlers = map[string]zncCommandHandler{
  17. "*playback": zncPlaybackHandler,
  18. }
  19. func zncPrivmsgHandler(client *Client, command string, privmsg string, rb *ResponseBuffer) {
  20. zncModuleHandler(client, command, strings.Fields(privmsg), rb)
  21. }
  22. func zncModuleHandler(client *Client, command string, params []string, rb *ResponseBuffer) {
  23. command = strings.ToLower(command)
  24. if subHandler, ok := zncHandlers[command]; ok {
  25. subHandler(client, command, params, rb)
  26. } else {
  27. nick := rb.target.Nick()
  28. rb.Add(nil, client.server.name, "NOTICE", nick, fmt.Sprintf(client.t("Oragono does not emulate the ZNC module %s"), command))
  29. rb.Add(nil, "*status!znc@znc.in", "NOTICE", nick, fmt.Sprintf(client.t("No such module [%s]"), command))
  30. }
  31. }
  32. // "number of seconds (floating point for millisecond precision) elapsed since January 1, 1970"
  33. func zncWireTimeToTime(str string) (result time.Time) {
  34. var secondsPortion, fracPortion string
  35. dot := strings.IndexByte(str, '.')
  36. if dot == -1 {
  37. secondsPortion = str
  38. } else {
  39. secondsPortion = str[:dot]
  40. fracPortion = str[dot:]
  41. }
  42. seconds, _ := strconv.ParseInt(secondsPortion, 10, 64)
  43. fraction, _ := strconv.ParseFloat(fracPortion, 64)
  44. return time.Unix(seconds, int64(fraction*1000000000)).UTC()
  45. }
  46. func timeToZncWireTime(t time.Time) (result string) {
  47. secs := t.Unix()
  48. nano := t.UnixNano() - (secs * 1000000000)
  49. return fmt.Sprintf("%d.%d", secs, nano)
  50. }
  51. type zncPlaybackTimes struct {
  52. start time.Time
  53. end time.Time
  54. targets StringSet // nil for "*" (everything), otherwise the channel names
  55. setAt time.Time
  56. }
  57. func (z *zncPlaybackTimes) ValidFor(target string) bool {
  58. if z == nil {
  59. return false
  60. }
  61. if time.Now().Sub(z.setAt) > zncPlaybackCommandExpiration {
  62. return false
  63. }
  64. if z.targets == nil {
  65. return true
  66. }
  67. return z.targets.Has(target)
  68. }
  69. // https://wiki.znc.in/Playback
  70. func zncPlaybackHandler(client *Client, command string, params []string, rb *ResponseBuffer) {
  71. if len(params) == 0 {
  72. return
  73. }
  74. switch strings.ToLower(params[0]) {
  75. case "play":
  76. zncPlaybackPlayHandler(client, command, params, rb)
  77. case "list":
  78. zncPlaybackListHandler(client, command, params, rb)
  79. default:
  80. return
  81. }
  82. }
  83. // PRIVMSG *playback :play <target> [lower_bound] [upper_bound]
  84. // e.g., PRIVMSG *playback :play * 1558374442
  85. func zncPlaybackPlayHandler(client *Client, command string, params []string, rb *ResponseBuffer) {
  86. if len(params) < 2 || len(params) > 4 {
  87. return
  88. }
  89. targetString := params[1]
  90. now := time.Now().UTC()
  91. var start, end time.Time
  92. switch len(params) {
  93. case 2:
  94. // #1205: this should have the same semantics as `LATEST *`
  95. case 3:
  96. // #831: this should have the same semantics as `LATEST timestamp=qux`,
  97. // or equivalently `BETWEEN timestamp=$now timestamp=qux`, as opposed to
  98. // `AFTER timestamp=qux` (this matters in the case where there are
  99. // more than znc-maxmessages available)
  100. start = now
  101. end = zncWireTimeToTime(params[2])
  102. case 4:
  103. start = zncWireTimeToTime(params[2])
  104. end = zncWireTimeToTime(params[3])
  105. }
  106. var targets StringSet
  107. var nickTargets []string
  108. // three cases:
  109. // 1. the user's PMs get played back immediately upon receiving this
  110. // 2. if this is a new connection (from the server's POV), save the information
  111. // and use it to process subsequent joins. (This is the Textual behavior:
  112. // first send the playback PRIVMSG, then send the JOIN lines.)
  113. // 3. if this is a reattach (from the server's POV), immediately play back
  114. // history for channels that the client is already joined to. In this scenario,
  115. // there are three total attempts to play the history:
  116. // 3.1. During the initial reattach (no-op because the *playback privmsg
  117. // hasn't been received yet, but they negotiated the znc.in/playback
  118. // cap so we know we're going to receive it later)
  119. // 3.2 Upon receiving the *playback privmsg, i.e., now: we should play
  120. // the relevant history lines
  121. // 3.3 When the client sends a subsequent redundant JOIN line for those
  122. // channels; redundant JOIN is a complete no-op so we won't replay twice
  123. playPrivmsgs := false
  124. if params[1] == "*" {
  125. playPrivmsgs = true // XXX nil `targets` means "every channel"
  126. } else {
  127. targets = make(StringSet)
  128. for _, targetName := range strings.Split(targetString, ",") {
  129. if targetName == "*self" {
  130. playPrivmsgs = true
  131. } else if strings.HasPrefix(targetName, "#") {
  132. if cfTarget, err := CasefoldChannel(targetName); err == nil {
  133. targets.Add(cfTarget)
  134. }
  135. } else {
  136. if cfNick, err := CasefoldName(targetName); err == nil {
  137. nickTargets = append(nickTargets, cfNick)
  138. }
  139. }
  140. }
  141. }
  142. if playPrivmsgs {
  143. zncPlayPrivmsgs(client, rb, "*", start, end)
  144. }
  145. rb.session.zncPlaybackTimes = &zncPlaybackTimes{
  146. start: start,
  147. end: end,
  148. targets: targets,
  149. setAt: time.Now().UTC(),
  150. }
  151. for _, channel := range client.Channels() {
  152. if targets == nil || targets.Has(channel.NameCasefolded()) {
  153. channel.autoReplayHistory(client, rb, "")
  154. rb.Flush(true)
  155. }
  156. }
  157. for _, cfNick := range nickTargets {
  158. zncPlayPrivmsgs(client, rb, cfNick, start, end)
  159. rb.Flush(true)
  160. }
  161. }
  162. func zncPlayPrivmsgs(client *Client, rb *ResponseBuffer, target string, after, before time.Time) {
  163. _, sequence, _ := client.server.GetHistorySequence(nil, client, target)
  164. if sequence == nil {
  165. return
  166. }
  167. zncMax := client.server.Config().History.ZNCMax
  168. items, _, err := sequence.Between(history.Selector{Time: after}, history.Selector{Time: before}, zncMax)
  169. if err == nil && len(items) != 0 {
  170. client.replayPrivmsgHistory(rb, items, "", true)
  171. }
  172. }
  173. // PRIVMSG *playback :list
  174. func zncPlaybackListHandler(client *Client, command string, params []string, rb *ResponseBuffer) {
  175. nick := client.Nick()
  176. for _, channel := range client.Channels() {
  177. _, sequence, err := client.server.GetHistorySequence(channel, client, "")
  178. if err != nil {
  179. client.server.logger.Error("internal", "couldn't get history sequence for ZNC list", err.Error())
  180. continue
  181. }
  182. items, _, err := sequence.Between(history.Selector{}, history.Selector{}, 1) // i.e., LATEST * 1
  183. if err != nil {
  184. client.server.logger.Error("internal", "couldn't query history for ZNC list", err.Error())
  185. } else if len(items) != 0 {
  186. stamp := timeToZncWireTime(items[0].Message.Time)
  187. rb.Add(nil, "*playback!znc@znc.in", "PRIVMSG", nick, fmt.Sprintf("%s 0 %s", channel.Name(), stamp))
  188. }
  189. }
  190. }