Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

channelreg.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. NameCasefolded: nameCasefolded,
  205. RegisteredAt: time.Unix(regTimeInt, 0).UTC(),
  206. Founder: founder,
  207. Topic: topic,
  208. TopicSetBy: topicSetBy,
  209. TopicSetTime: time.Unix(topicSetTimeInt, 0).UTC(),
  210. Key: password,
  211. Modes: modeSlice,
  212. Bans: banlist,
  213. Excepts: exceptlist,
  214. Invites: invitelist,
  215. AccountToUMode: accountToUMode,
  216. UserLimit: int(userLimit),
  217. Settings: settings,
  218. }
  219. return nil
  220. })
  221. return
  222. }
  223. // Delete deletes a channel corresponding to `info`. If no such channel
  224. // is present in the database, no error is returned.
  225. func (reg *ChannelRegistry) Delete(info RegisteredChannel) (err error) {
  226. if !reg.server.ChannelRegistrationEnabled() {
  227. return
  228. }
  229. reg.server.store.Update(func(tx *buntdb.Tx) error {
  230. reg.deleteChannel(tx, info.NameCasefolded, info)
  231. return nil
  232. })
  233. return nil
  234. }
  235. // delete a channel, unless it was overwritten by another registration of the same channel
  236. func (reg *ChannelRegistry) deleteChannel(tx *buntdb.Tx, key string, info RegisteredChannel) {
  237. _, err := tx.Get(fmt.Sprintf(keyChannelExists, key))
  238. if err == nil {
  239. regTime, _ := tx.Get(fmt.Sprintf(keyChannelRegTime, key))
  240. regTimeInt, _ := strconv.ParseInt(regTime, 10, 64)
  241. registeredAt := time.Unix(regTimeInt, 0).UTC()
  242. founder, _ := tx.Get(fmt.Sprintf(keyChannelFounder, key))
  243. // to see if we're deleting the right channel, confirm the founder and the registration time
  244. if founder == info.Founder && registeredAt.Unix() == info.RegisteredAt.Unix() {
  245. for _, keyFmt := range channelKeyStrings {
  246. tx.Delete(fmt.Sprintf(keyFmt, key))
  247. }
  248. // remove this channel from the client's list of registered channels
  249. channelsKey := fmt.Sprintf(keyAccountChannels, info.Founder)
  250. channelsStr, err := tx.Get(channelsKey)
  251. if err == buntdb.ErrNotFound {
  252. return
  253. }
  254. registeredChannels := unmarshalRegisteredChannels(channelsStr)
  255. var nowRegisteredChannels []string
  256. for _, channel := range registeredChannels {
  257. if channel != key {
  258. nowRegisteredChannels = append(nowRegisteredChannels, channel)
  259. }
  260. }
  261. tx.Set(channelsKey, strings.Join(nowRegisteredChannels, ","), nil)
  262. }
  263. }
  264. }
  265. func (reg *ChannelRegistry) updateAccountToChannelMapping(tx *buntdb.Tx, channelInfo RegisteredChannel) {
  266. channelKey := channelInfo.NameCasefolded
  267. chanFounderKey := fmt.Sprintf(keyChannelFounder, channelKey)
  268. founder, existsErr := tx.Get(chanFounderKey)
  269. if existsErr == buntdb.ErrNotFound || founder != channelInfo.Founder {
  270. // add to new founder's list
  271. accountChannelsKey := fmt.Sprintf(keyAccountChannels, channelInfo.Founder)
  272. alreadyChannels, _ := tx.Get(accountChannelsKey)
  273. newChannels := channelKey // this is the casefolded channel name
  274. if alreadyChannels != "" {
  275. newChannels = fmt.Sprintf("%s,%s", alreadyChannels, newChannels)
  276. }
  277. tx.Set(accountChannelsKey, newChannels, nil)
  278. }
  279. if existsErr == nil && founder != channelInfo.Founder {
  280. // remove from old founder's list
  281. accountChannelsKey := fmt.Sprintf(keyAccountChannels, founder)
  282. alreadyChannelsRaw, _ := tx.Get(accountChannelsKey)
  283. var newChannels []string
  284. if alreadyChannelsRaw != "" {
  285. for _, chname := range strings.Split(alreadyChannelsRaw, ",") {
  286. if chname != channelInfo.NameCasefolded {
  287. newChannels = append(newChannels, chname)
  288. }
  289. }
  290. }
  291. tx.Set(accountChannelsKey, strings.Join(newChannels, ","), nil)
  292. }
  293. }
  294. // saveChannel saves a channel to the store.
  295. func (reg *ChannelRegistry) saveChannel(tx *buntdb.Tx, channelInfo RegisteredChannel, includeFlags uint) {
  296. channelKey := channelInfo.NameCasefolded
  297. // maintain the mapping of account -> registered channels
  298. reg.updateAccountToChannelMapping(tx, channelInfo)
  299. if includeFlags&IncludeInitial != 0 {
  300. tx.Set(fmt.Sprintf(keyChannelExists, channelKey), "1", nil)
  301. tx.Set(fmt.Sprintf(keyChannelName, channelKey), channelInfo.Name, nil)
  302. tx.Set(fmt.Sprintf(keyChannelRegTime, channelKey), strconv.FormatInt(channelInfo.RegisteredAt.Unix(), 10), nil)
  303. tx.Set(fmt.Sprintf(keyChannelFounder, channelKey), channelInfo.Founder, nil)
  304. }
  305. if includeFlags&IncludeTopic != 0 {
  306. tx.Set(fmt.Sprintf(keyChannelTopic, channelKey), channelInfo.Topic, nil)
  307. tx.Set(fmt.Sprintf(keyChannelTopicSetTime, channelKey), strconv.FormatInt(channelInfo.TopicSetTime.Unix(), 10), nil)
  308. tx.Set(fmt.Sprintf(keyChannelTopicSetBy, channelKey), channelInfo.TopicSetBy, nil)
  309. }
  310. if includeFlags&IncludeModes != 0 {
  311. tx.Set(fmt.Sprintf(keyChannelPassword, channelKey), channelInfo.Key, nil)
  312. modeStrings := make([]string, len(channelInfo.Modes))
  313. for i, mode := range channelInfo.Modes {
  314. modeStrings[i] = string(mode)
  315. }
  316. tx.Set(fmt.Sprintf(keyChannelModes, channelKey), strings.Join(modeStrings, ""), nil)
  317. tx.Set(fmt.Sprintf(keyChannelUserLimit, channelKey), strconv.Itoa(channelInfo.UserLimit), nil)
  318. }
  319. if includeFlags&IncludeLists != 0 {
  320. banlistString, _ := json.Marshal(channelInfo.Bans)
  321. tx.Set(fmt.Sprintf(keyChannelBanlist, channelKey), string(banlistString), nil)
  322. exceptlistString, _ := json.Marshal(channelInfo.Excepts)
  323. tx.Set(fmt.Sprintf(keyChannelExceptlist, channelKey), string(exceptlistString), nil)
  324. invitelistString, _ := json.Marshal(channelInfo.Invites)
  325. tx.Set(fmt.Sprintf(keyChannelInvitelist, channelKey), string(invitelistString), nil)
  326. accountToUModeString, _ := json.Marshal(channelInfo.AccountToUMode)
  327. tx.Set(fmt.Sprintf(keyChannelAccountToUMode, channelKey), string(accountToUModeString), nil)
  328. }
  329. if includeFlags&IncludeSettings != 0 {
  330. settingsString, _ := json.Marshal(channelInfo.Settings)
  331. tx.Set(fmt.Sprintf(keyChannelSettings, channelKey), string(settingsString), nil)
  332. }
  333. }
  334. // PurgeChannel records a channel purge.
  335. func (reg *ChannelRegistry) PurgeChannel(chname string, record ChannelPurgeRecord) (err error) {
  336. serialized, err := json.Marshal(record)
  337. if err != nil {
  338. return err
  339. }
  340. serializedStr := string(serialized)
  341. key := fmt.Sprintf(keyChannelPurged, chname)
  342. return reg.server.store.Update(func(tx *buntdb.Tx) error {
  343. tx.Set(key, serializedStr, nil)
  344. return nil
  345. })
  346. }
  347. // LoadPurgeRecord retrieves information about whether and how a channel was purged.
  348. func (reg *ChannelRegistry) LoadPurgeRecord(chname string) (record ChannelPurgeRecord, err error) {
  349. var rawRecord string
  350. key := fmt.Sprintf(keyChannelPurged, chname)
  351. reg.server.store.View(func(tx *buntdb.Tx) error {
  352. rawRecord, _ = tx.Get(key)
  353. return nil
  354. })
  355. if rawRecord == "" {
  356. err = errNoSuchChannel
  357. return
  358. }
  359. err = json.Unmarshal([]byte(rawRecord), &record)
  360. if err != nil {
  361. reg.server.logger.Error("internal", "corrupt purge record", chname, err.Error())
  362. err = errNoSuchChannel
  363. return
  364. }
  365. return
  366. }
  367. // UnpurgeChannel deletes the record of a channel purge.
  368. func (reg *ChannelRegistry) UnpurgeChannel(chname string) (err error) {
  369. key := fmt.Sprintf(keyChannelPurged, chname)
  370. return reg.server.store.Update(func(tx *buntdb.Tx) error {
  371. tx.Delete(key)
  372. return nil
  373. })
  374. }