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 14KB

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