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.

channelreg.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "encoding/json"
  10. "github.com/oragono/oragono/irc/modes"
  11. "github.com/tidwall/buntdb"
  12. )
  13. // this is exclusively the *persistence* layer for channel registration;
  14. // channel creation/tracking/destruction is in channelmanager.go
  15. const (
  16. keyChannelExists = "channel.exists %s"
  17. keyChannelName = "channel.name %s" // stores the 'preferred name' of the channel, not casemapped
  18. keyChannelRegTime = "channel.registered.time %s"
  19. keyChannelFounder = "channel.founder %s"
  20. keyChannelTopic = "channel.topic %s"
  21. keyChannelTopicSetBy = "channel.topic.setby %s"
  22. keyChannelTopicSetTime = "channel.topic.settime %s"
  23. keyChannelBanlist = "channel.banlist %s"
  24. keyChannelExceptlist = "channel.exceptlist %s"
  25. keyChannelInvitelist = "channel.invitelist %s"
  26. keyChannelPassword = "channel.key %s"
  27. keyChannelModes = "channel.modes %s"
  28. keyChannelAccountToUMode = "channel.accounttoumode %s"
  29. keyChannelPurged = "channel.purged %s"
  30. )
  31. var (
  32. channelKeyStrings = []string{
  33. keyChannelExists,
  34. keyChannelName,
  35. keyChannelRegTime,
  36. keyChannelFounder,
  37. keyChannelTopic,
  38. keyChannelTopicSetBy,
  39. keyChannelTopicSetTime,
  40. keyChannelBanlist,
  41. keyChannelExceptlist,
  42. keyChannelInvitelist,
  43. keyChannelPassword,
  44. keyChannelModes,
  45. keyChannelAccountToUMode,
  46. }
  47. )
  48. // these are bit flags indicating what part of the channel status is "dirty"
  49. // and needs to be read from memory and written to the db
  50. const (
  51. IncludeInitial uint = 1 << iota
  52. IncludeTopic
  53. IncludeModes
  54. IncludeLists
  55. )
  56. // this is an OR of all possible flags
  57. const (
  58. IncludeAllChannelAttrs = ^uint(0)
  59. )
  60. // RegisteredChannel holds details about a given registered channel.
  61. type RegisteredChannel struct {
  62. // Name of the channel.
  63. Name string
  64. // Casefolded name of the channel.
  65. NameCasefolded string
  66. // RegisteredAt represents the time that the channel was registered.
  67. RegisteredAt time.Time
  68. // Founder indicates the founder of the channel.
  69. Founder string
  70. // Topic represents the channel topic.
  71. Topic string
  72. // TopicSetBy represents the host that set the topic.
  73. TopicSetBy string
  74. // TopicSetTime represents the time the topic was set.
  75. TopicSetTime time.Time
  76. // Modes represents the channel modes
  77. Modes []modes.Mode
  78. // Key represents the channel key / password
  79. Key string
  80. // AccountToUMode maps user accounts to their persistent channel modes (e.g., +q, +h)
  81. AccountToUMode map[string]modes.Mode
  82. // Bans represents the bans set on the channel.
  83. Bans map[string]MaskInfo
  84. // Excepts represents the exceptions set on the channel.
  85. Excepts map[string]MaskInfo
  86. // Invites represents the invite exceptions set on the channel.
  87. Invites map[string]MaskInfo
  88. }
  89. type ChannelPurgeRecord struct {
  90. Oper string
  91. PurgedAt time.Time
  92. Reason string
  93. }
  94. // ChannelRegistry manages registered channels.
  95. type ChannelRegistry struct {
  96. server *Server
  97. }
  98. // NewChannelRegistry returns a new ChannelRegistry.
  99. func (reg *ChannelRegistry) Initialize(server *Server) {
  100. reg.server = server
  101. }
  102. // AllChannels returns the uncasefolded names of all registered channels.
  103. func (reg *ChannelRegistry) AllChannels() (result []string) {
  104. prefix := fmt.Sprintf(keyChannelName, "")
  105. reg.server.store.View(func(tx *buntdb.Tx) error {
  106. return tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  107. if !strings.HasPrefix(key, prefix) {
  108. return false
  109. }
  110. result = append(result, value)
  111. return true
  112. })
  113. })
  114. return
  115. }
  116. // PurgedChannels returns the set of all casefolded channel names that have been purged
  117. func (reg *ChannelRegistry) PurgedChannels() (result map[string]empty) {
  118. result = make(map[string]empty)
  119. prefix := fmt.Sprintf(keyChannelPurged, "")
  120. reg.server.store.View(func(tx *buntdb.Tx) error {
  121. return tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  122. if !strings.HasPrefix(key, prefix) {
  123. return false
  124. }
  125. channel := strings.TrimPrefix(key, prefix)
  126. result[channel] = empty{}
  127. return true
  128. })
  129. })
  130. return
  131. }
  132. // StoreChannel obtains a consistent view of a channel, then persists it to the store.
  133. func (reg *ChannelRegistry) StoreChannel(info RegisteredChannel, includeFlags uint) (err error) {
  134. if !reg.server.ChannelRegistrationEnabled() {
  135. return
  136. }
  137. if info.Founder == "" {
  138. // sanity check, don't try to store an unregistered channel
  139. return
  140. }
  141. reg.server.store.Update(func(tx *buntdb.Tx) error {
  142. reg.saveChannel(tx, info, includeFlags)
  143. return nil
  144. })
  145. return nil
  146. }
  147. // LoadChannel loads a channel from the store.
  148. func (reg *ChannelRegistry) LoadChannel(nameCasefolded string) (info RegisteredChannel, err error) {
  149. if !reg.server.ChannelRegistrationEnabled() {
  150. err = errFeatureDisabled
  151. return
  152. }
  153. channelKey := nameCasefolded
  154. // nice to have: do all JSON (de)serialization outside of the buntdb transaction
  155. err = reg.server.store.View(func(tx *buntdb.Tx) error {
  156. _, dberr := tx.Get(fmt.Sprintf(keyChannelExists, channelKey))
  157. if dberr == buntdb.ErrNotFound {
  158. // chan does not already exist, return
  159. return errNoSuchChannel
  160. }
  161. // channel exists, load it
  162. name, _ := tx.Get(fmt.Sprintf(keyChannelName, channelKey))
  163. regTime, _ := tx.Get(fmt.Sprintf(keyChannelRegTime, channelKey))
  164. regTimeInt, _ := strconv.ParseInt(regTime, 10, 64)
  165. founder, _ := tx.Get(fmt.Sprintf(keyChannelFounder, channelKey))
  166. topic, _ := tx.Get(fmt.Sprintf(keyChannelTopic, channelKey))
  167. topicSetBy, _ := tx.Get(fmt.Sprintf(keyChannelTopicSetBy, channelKey))
  168. topicSetTime, _ := tx.Get(fmt.Sprintf(keyChannelTopicSetTime, channelKey))
  169. topicSetTimeInt, _ := strconv.ParseInt(topicSetTime, 10, 64)
  170. password, _ := tx.Get(fmt.Sprintf(keyChannelPassword, channelKey))
  171. modeString, _ := tx.Get(fmt.Sprintf(keyChannelModes, channelKey))
  172. banlistString, _ := tx.Get(fmt.Sprintf(keyChannelBanlist, channelKey))
  173. exceptlistString, _ := tx.Get(fmt.Sprintf(keyChannelExceptlist, channelKey))
  174. invitelistString, _ := tx.Get(fmt.Sprintf(keyChannelInvitelist, channelKey))
  175. accountToUModeString, _ := tx.Get(fmt.Sprintf(keyChannelAccountToUMode, channelKey))
  176. modeSlice := make([]modes.Mode, len(modeString))
  177. for i, mode := range modeString {
  178. modeSlice[i] = modes.Mode(mode)
  179. }
  180. var banlist map[string]MaskInfo
  181. _ = json.Unmarshal([]byte(banlistString), &banlist)
  182. var exceptlist map[string]MaskInfo
  183. _ = json.Unmarshal([]byte(exceptlistString), &exceptlist)
  184. var invitelist map[string]MaskInfo
  185. _ = json.Unmarshal([]byte(invitelistString), &invitelist)
  186. accountToUMode := make(map[string]modes.Mode)
  187. _ = json.Unmarshal([]byte(accountToUModeString), &accountToUMode)
  188. info = RegisteredChannel{
  189. Name: name,
  190. RegisteredAt: time.Unix(regTimeInt, 0).UTC(),
  191. Founder: founder,
  192. Topic: topic,
  193. TopicSetBy: topicSetBy,
  194. TopicSetTime: time.Unix(topicSetTimeInt, 0).UTC(),
  195. Key: password,
  196. Modes: modeSlice,
  197. Bans: banlist,
  198. Excepts: exceptlist,
  199. Invites: invitelist,
  200. AccountToUMode: accountToUMode,
  201. }
  202. return nil
  203. })
  204. return
  205. }
  206. // Delete deletes a channel corresponding to `info`. If no such channel
  207. // is present in the database, no error is returned.
  208. func (reg *ChannelRegistry) Delete(info RegisteredChannel) (err error) {
  209. if !reg.server.ChannelRegistrationEnabled() {
  210. return
  211. }
  212. reg.server.store.Update(func(tx *buntdb.Tx) error {
  213. reg.deleteChannel(tx, info.NameCasefolded, info)
  214. return nil
  215. })
  216. return nil
  217. }
  218. // delete a channel, unless it was overwritten by another registration of the same channel
  219. func (reg *ChannelRegistry) deleteChannel(tx *buntdb.Tx, key string, info RegisteredChannel) {
  220. _, err := tx.Get(fmt.Sprintf(keyChannelExists, key))
  221. if err == nil {
  222. regTime, _ := tx.Get(fmt.Sprintf(keyChannelRegTime, key))
  223. regTimeInt, _ := strconv.ParseInt(regTime, 10, 64)
  224. registeredAt := time.Unix(regTimeInt, 0)
  225. founder, _ := tx.Get(fmt.Sprintf(keyChannelFounder, key))
  226. // to see if we're deleting the right channel, confirm the founder and the registration time
  227. if founder == info.Founder && registeredAt.Unix() == info.RegisteredAt.Unix() {
  228. for _, keyFmt := range channelKeyStrings {
  229. tx.Delete(fmt.Sprintf(keyFmt, key))
  230. }
  231. // remove this channel from the client's list of registered channels
  232. channelsKey := fmt.Sprintf(keyAccountChannels, info.Founder)
  233. channelsStr, err := tx.Get(channelsKey)
  234. if err == buntdb.ErrNotFound {
  235. return
  236. }
  237. registeredChannels := unmarshalRegisteredChannels(channelsStr)
  238. var nowRegisteredChannels []string
  239. for _, channel := range registeredChannels {
  240. if channel != key {
  241. nowRegisteredChannels = append(nowRegisteredChannels, channel)
  242. }
  243. }
  244. tx.Set(channelsKey, strings.Join(nowRegisteredChannels, ","), nil)
  245. }
  246. }
  247. }
  248. func (reg *ChannelRegistry) updateAccountToChannelMapping(tx *buntdb.Tx, channelInfo RegisteredChannel) {
  249. channelKey := channelInfo.NameCasefolded
  250. chanFounderKey := fmt.Sprintf(keyChannelFounder, channelKey)
  251. founder, existsErr := tx.Get(chanFounderKey)
  252. if existsErr == buntdb.ErrNotFound || founder != channelInfo.Founder {
  253. // add to new founder's list
  254. accountChannelsKey := fmt.Sprintf(keyAccountChannels, channelInfo.Founder)
  255. alreadyChannels, _ := tx.Get(accountChannelsKey)
  256. newChannels := channelKey // this is the casefolded channel name
  257. if alreadyChannels != "" {
  258. newChannels = fmt.Sprintf("%s,%s", alreadyChannels, newChannels)
  259. }
  260. tx.Set(accountChannelsKey, newChannels, nil)
  261. }
  262. if existsErr == nil && founder != channelInfo.Founder {
  263. // remove from old founder's list
  264. accountChannelsKey := fmt.Sprintf(keyAccountChannels, founder)
  265. alreadyChannelsRaw, _ := tx.Get(accountChannelsKey)
  266. var newChannels []string
  267. if alreadyChannelsRaw != "" {
  268. for _, chname := range strings.Split(alreadyChannelsRaw, ",") {
  269. if chname != channelInfo.NameCasefolded {
  270. newChannels = append(newChannels, chname)
  271. }
  272. }
  273. }
  274. tx.Set(accountChannelsKey, strings.Join(newChannels, ","), nil)
  275. }
  276. }
  277. // saveChannel saves a channel to the store.
  278. func (reg *ChannelRegistry) saveChannel(tx *buntdb.Tx, channelInfo RegisteredChannel, includeFlags uint) {
  279. channelKey := channelInfo.NameCasefolded
  280. // maintain the mapping of account -> registered channels
  281. reg.updateAccountToChannelMapping(tx, channelInfo)
  282. if includeFlags&IncludeInitial != 0 {
  283. tx.Set(fmt.Sprintf(keyChannelExists, channelKey), "1", nil)
  284. tx.Set(fmt.Sprintf(keyChannelName, channelKey), channelInfo.Name, nil)
  285. tx.Set(fmt.Sprintf(keyChannelRegTime, channelKey), strconv.FormatInt(channelInfo.RegisteredAt.Unix(), 10), nil)
  286. tx.Set(fmt.Sprintf(keyChannelFounder, channelKey), channelInfo.Founder, nil)
  287. }
  288. if includeFlags&IncludeTopic != 0 {
  289. tx.Set(fmt.Sprintf(keyChannelTopic, channelKey), channelInfo.Topic, nil)
  290. tx.Set(fmt.Sprintf(keyChannelTopicSetTime, channelKey), strconv.FormatInt(channelInfo.TopicSetTime.Unix(), 10), nil)
  291. tx.Set(fmt.Sprintf(keyChannelTopicSetBy, channelKey), channelInfo.TopicSetBy, nil)
  292. }
  293. if includeFlags&IncludeModes != 0 {
  294. tx.Set(fmt.Sprintf(keyChannelPassword, channelKey), channelInfo.Key, nil)
  295. modeStrings := make([]string, len(channelInfo.Modes))
  296. for i, mode := range channelInfo.Modes {
  297. modeStrings[i] = string(mode)
  298. }
  299. tx.Set(fmt.Sprintf(keyChannelModes, channelKey), strings.Join(modeStrings, ""), nil)
  300. }
  301. if includeFlags&IncludeLists != 0 {
  302. banlistString, _ := json.Marshal(channelInfo.Bans)
  303. tx.Set(fmt.Sprintf(keyChannelBanlist, channelKey), string(banlistString), nil)
  304. exceptlistString, _ := json.Marshal(channelInfo.Excepts)
  305. tx.Set(fmt.Sprintf(keyChannelExceptlist, channelKey), string(exceptlistString), nil)
  306. invitelistString, _ := json.Marshal(channelInfo.Invites)
  307. tx.Set(fmt.Sprintf(keyChannelInvitelist, channelKey), string(invitelistString), nil)
  308. accountToUModeString, _ := json.Marshal(channelInfo.AccountToUMode)
  309. tx.Set(fmt.Sprintf(keyChannelAccountToUMode, channelKey), string(accountToUModeString), nil)
  310. }
  311. }
  312. // PurgeChannel records a channel purge.
  313. func (reg *ChannelRegistry) PurgeChannel(chname string, record ChannelPurgeRecord) (err error) {
  314. serialized, err := json.Marshal(record)
  315. if err != nil {
  316. return err
  317. }
  318. serializedStr := string(serialized)
  319. key := fmt.Sprintf(keyChannelPurged, chname)
  320. return reg.server.store.Update(func(tx *buntdb.Tx) error {
  321. tx.Set(key, serializedStr, nil)
  322. return nil
  323. })
  324. }
  325. // LoadPurgeRecord retrieves information about whether and how a channel was purged.
  326. func (reg *ChannelRegistry) LoadPurgeRecord(chname string) (record ChannelPurgeRecord, err error) {
  327. var rawRecord string
  328. key := fmt.Sprintf(keyChannelPurged, chname)
  329. reg.server.store.View(func(tx *buntdb.Tx) error {
  330. rawRecord, _ = tx.Get(key)
  331. return nil
  332. })
  333. if rawRecord == "" {
  334. err = errNoSuchChannel
  335. return
  336. }
  337. err = json.Unmarshal([]byte(rawRecord), &record)
  338. if err != nil {
  339. reg.server.logger.Error("internal", "corrupt purge record", chname, err.Error())
  340. err = errNoSuchChannel
  341. return
  342. }
  343. return
  344. }
  345. // UnpurgeChannel deletes the record of a channel purge.
  346. func (reg *ChannelRegistry) UnpurgeChannel(chname string) (err error) {
  347. key := fmt.Sprintf(keyChannelPurged, chname)
  348. return reg.server.store.Update(func(tx *buntdb.Tx) error {
  349. tx.Delete(key)
  350. return nil
  351. })
  352. }