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.6KB

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