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