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.

channel.go 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "bytes"
  8. "fmt"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "sync"
  13. "github.com/oragono/oragono/irc/caps"
  14. "github.com/oragono/oragono/irc/history"
  15. "github.com/oragono/oragono/irc/modes"
  16. "github.com/oragono/oragono/irc/utils"
  17. )
  18. // Channel represents a channel that clients can join.
  19. type Channel struct {
  20. flags modes.ModeSet
  21. lists map[modes.Mode]*UserMaskSet
  22. key string
  23. members MemberSet
  24. membersCache []*Client // allow iteration over channel members without holding the lock
  25. name string
  26. nameCasefolded string
  27. server *Server
  28. createdTime time.Time
  29. registeredFounder string
  30. registeredTime time.Time
  31. topic string
  32. topicSetBy string
  33. topicSetTime time.Time
  34. userLimit int
  35. accountToUMode map[string]modes.Mode
  36. history history.Buffer
  37. stateMutex sync.RWMutex // tier 1
  38. writerSemaphore utils.Semaphore // tier 1.5
  39. joinPartMutex sync.Mutex // tier 3
  40. ensureLoaded utils.Once // manages loading stored registration info from the database
  41. dirtyBits uint
  42. }
  43. // NewChannel creates a new channel from a `Server` and a `name`
  44. // string, which must be unique on the server.
  45. func NewChannel(s *Server, name string, registered bool) *Channel {
  46. casefoldedName, err := CasefoldChannel(name)
  47. if err != nil {
  48. s.logger.Error("internal", "Bad channel name", name, err.Error())
  49. return nil
  50. }
  51. channel := &Channel{
  52. createdTime: time.Now(), // may be overwritten by applyRegInfo
  53. lists: map[modes.Mode]*UserMaskSet{
  54. modes.BanMask: NewUserMaskSet(),
  55. modes.ExceptMask: NewUserMaskSet(),
  56. modes.InviteMask: NewUserMaskSet(),
  57. },
  58. members: make(MemberSet),
  59. name: name,
  60. nameCasefolded: casefoldedName,
  61. server: s,
  62. accountToUMode: make(map[string]modes.Mode),
  63. }
  64. config := s.Config()
  65. channel.writerSemaphore.Initialize(1)
  66. channel.history.Initialize(config.History.ChannelLength)
  67. if !registered {
  68. for _, mode := range config.Channels.defaultModes {
  69. channel.flags.SetMode(mode, true)
  70. }
  71. // no loading to do, so "mark" the load operation as "done":
  72. channel.ensureLoaded.Do(func() {})
  73. } // else: modes will be loaded before first join
  74. return channel
  75. }
  76. // EnsureLoaded blocks until the channel's registration info has been loaded
  77. // from the database.
  78. func (channel *Channel) EnsureLoaded() {
  79. channel.ensureLoaded.Do(func() {
  80. nmc := channel.NameCasefolded()
  81. info, err := channel.server.channelRegistry.LoadChannel(nmc)
  82. if err == nil {
  83. channel.applyRegInfo(info)
  84. } else {
  85. channel.server.logger.Error("internal", "couldn't load channel", nmc, err.Error())
  86. }
  87. })
  88. }
  89. func (channel *Channel) IsLoaded() bool {
  90. return channel.ensureLoaded.Done()
  91. }
  92. // read in channel state that was persisted in the DB
  93. func (channel *Channel) applyRegInfo(chanReg RegisteredChannel) {
  94. channel.stateMutex.Lock()
  95. defer channel.stateMutex.Unlock()
  96. channel.registeredFounder = chanReg.Founder
  97. channel.registeredTime = chanReg.RegisteredAt
  98. channel.topic = chanReg.Topic
  99. channel.topicSetBy = chanReg.TopicSetBy
  100. channel.topicSetTime = chanReg.TopicSetTime
  101. channel.name = chanReg.Name
  102. channel.createdTime = chanReg.RegisteredAt
  103. channel.key = chanReg.Key
  104. for _, mode := range chanReg.Modes {
  105. channel.flags.SetMode(mode, true)
  106. }
  107. for _, mask := range chanReg.Banlist {
  108. channel.lists[modes.BanMask].Add(mask)
  109. }
  110. for _, mask := range chanReg.Exceptlist {
  111. channel.lists[modes.ExceptMask].Add(mask)
  112. }
  113. for _, mask := range chanReg.Invitelist {
  114. channel.lists[modes.InviteMask].Add(mask)
  115. }
  116. for account, mode := range chanReg.AccountToUMode {
  117. channel.accountToUMode[account] = mode
  118. }
  119. }
  120. // obtain a consistent snapshot of the channel state that can be persisted to the DB
  121. func (channel *Channel) ExportRegistration(includeFlags uint) (info RegisteredChannel) {
  122. channel.stateMutex.RLock()
  123. defer channel.stateMutex.RUnlock()
  124. info.Name = channel.name
  125. info.NameCasefolded = channel.nameCasefolded
  126. info.Founder = channel.registeredFounder
  127. info.RegisteredAt = channel.registeredTime
  128. if includeFlags&IncludeTopic != 0 {
  129. info.Topic = channel.topic
  130. info.TopicSetBy = channel.topicSetBy
  131. info.TopicSetTime = channel.topicSetTime
  132. }
  133. if includeFlags&IncludeModes != 0 {
  134. info.Key = channel.key
  135. info.Modes = channel.flags.AllModes()
  136. }
  137. if includeFlags&IncludeLists != 0 {
  138. for mask := range channel.lists[modes.BanMask].masks {
  139. info.Banlist = append(info.Banlist, mask)
  140. }
  141. for mask := range channel.lists[modes.ExceptMask].masks {
  142. info.Exceptlist = append(info.Exceptlist, mask)
  143. }
  144. for mask := range channel.lists[modes.InviteMask].masks {
  145. info.Invitelist = append(info.Invitelist, mask)
  146. }
  147. info.AccountToUMode = make(map[string]modes.Mode)
  148. for account, mode := range channel.accountToUMode {
  149. info.AccountToUMode[account] = mode
  150. }
  151. }
  152. return
  153. }
  154. // begin: asynchronous database writeback implementation, modeled on irc/socket.go
  155. // MarkDirty marks part (or all) of a channel's data as needing to be written back
  156. // to the database, then starts a writer goroutine if necessary.
  157. // This is the equivalent of Socket.Write().
  158. func (channel *Channel) MarkDirty(dirtyBits uint) {
  159. channel.stateMutex.Lock()
  160. isRegistered := channel.registeredFounder != ""
  161. channel.dirtyBits = channel.dirtyBits | dirtyBits
  162. channel.stateMutex.Unlock()
  163. if !isRegistered {
  164. return
  165. }
  166. channel.wakeWriter()
  167. }
  168. // IsClean returns whether a channel can be safely removed from the server.
  169. // To avoid the obvious TOCTOU race condition, it must be called while holding
  170. // ChannelManager's lock (that way, no one can join and make the channel dirty again
  171. // between this method exiting and the actual deletion).
  172. func (channel *Channel) IsClean() bool {
  173. if !channel.writerSemaphore.TryAcquire() {
  174. // a database write (which may fail) is in progress, the channel cannot be cleaned up
  175. return false
  176. }
  177. defer channel.writerSemaphore.Release()
  178. channel.stateMutex.RLock()
  179. defer channel.stateMutex.RUnlock()
  180. // the channel must be empty, and either be unregistered or fully written to the DB
  181. return len(channel.members) == 0 && (channel.registeredFounder == "" || channel.dirtyBits == 0)
  182. }
  183. func (channel *Channel) wakeWriter() {
  184. if channel.writerSemaphore.TryAcquire() {
  185. go channel.writeLoop()
  186. }
  187. }
  188. // equivalent of Socket.send()
  189. func (channel *Channel) writeLoop() {
  190. for {
  191. // TODO(#357) check the error value of this and implement timed backoff
  192. channel.performWrite(0)
  193. channel.writerSemaphore.Release()
  194. channel.stateMutex.RLock()
  195. isDirty := channel.dirtyBits != 0
  196. isEmpty := len(channel.members) == 0
  197. channel.stateMutex.RUnlock()
  198. if !isDirty {
  199. if isEmpty {
  200. channel.server.channels.Cleanup(channel)
  201. }
  202. return // nothing to do
  203. } // else: isDirty, so we need to write again
  204. if !channel.writerSemaphore.TryAcquire() {
  205. return
  206. }
  207. }
  208. }
  209. // Store writes part (or all) of the channel's data back to the database,
  210. // blocking until the write is complete. This is the equivalent of
  211. // Socket.BlockingWrite.
  212. func (channel *Channel) Store(dirtyBits uint) (err error) {
  213. defer func() {
  214. channel.stateMutex.Lock()
  215. isDirty := channel.dirtyBits != 0
  216. isEmpty := len(channel.members) == 0
  217. channel.stateMutex.Unlock()
  218. if isDirty {
  219. channel.wakeWriter()
  220. } else if isEmpty {
  221. channel.server.channels.Cleanup(channel)
  222. }
  223. }()
  224. channel.writerSemaphore.Acquire()
  225. defer channel.writerSemaphore.Release()
  226. return channel.performWrite(dirtyBits)
  227. }
  228. // do an individual write; equivalent of Socket.send()
  229. func (channel *Channel) performWrite(additionalDirtyBits uint) (err error) {
  230. channel.stateMutex.Lock()
  231. dirtyBits := channel.dirtyBits | additionalDirtyBits
  232. channel.dirtyBits = 0
  233. isRegistered := channel.registeredFounder != ""
  234. channel.stateMutex.Unlock()
  235. if !isRegistered || dirtyBits == 0 {
  236. return
  237. }
  238. info := channel.ExportRegistration(dirtyBits)
  239. err = channel.server.channelRegistry.StoreChannel(info, dirtyBits)
  240. if err != nil {
  241. channel.stateMutex.Lock()
  242. channel.dirtyBits = channel.dirtyBits | dirtyBits
  243. channel.stateMutex.Unlock()
  244. }
  245. return
  246. }
  247. // SetRegistered registers the channel, returning an error if it was already registered.
  248. func (channel *Channel) SetRegistered(founder string) error {
  249. channel.stateMutex.Lock()
  250. defer channel.stateMutex.Unlock()
  251. if channel.registeredFounder != "" {
  252. return errChannelAlreadyRegistered
  253. }
  254. channel.registeredFounder = founder
  255. channel.registeredTime = time.Now()
  256. channel.accountToUMode[founder] = modes.ChannelFounder
  257. return nil
  258. }
  259. // SetUnregistered deletes the channel's registration information.
  260. func (channel *Channel) SetUnregistered(expectedFounder string) {
  261. channel.stateMutex.Lock()
  262. defer channel.stateMutex.Unlock()
  263. if channel.registeredFounder != expectedFounder {
  264. return
  265. }
  266. channel.registeredFounder = ""
  267. var zeroTime time.Time
  268. channel.registeredTime = zeroTime
  269. channel.accountToUMode = make(map[string]modes.Mode)
  270. }
  271. // IsRegistered returns whether the channel is registered.
  272. func (channel *Channel) IsRegistered() bool {
  273. channel.stateMutex.RLock()
  274. defer channel.stateMutex.RUnlock()
  275. return channel.registeredFounder != ""
  276. }
  277. func (channel *Channel) regenerateMembersCache() {
  278. channel.stateMutex.RLock()
  279. result := make([]*Client, len(channel.members))
  280. i := 0
  281. for client := range channel.members {
  282. result[i] = client
  283. i++
  284. }
  285. channel.stateMutex.RUnlock()
  286. channel.stateMutex.Lock()
  287. channel.membersCache = result
  288. channel.stateMutex.Unlock()
  289. }
  290. // Names sends the list of users joined to the channel to the given client.
  291. func (channel *Channel) Names(client *Client, rb *ResponseBuffer) {
  292. isJoined := channel.hasClient(client)
  293. isOper := client.HasMode(modes.Operator)
  294. isMultiPrefix := rb.session.capabilities.Has(caps.MultiPrefix)
  295. isUserhostInNames := rb.session.capabilities.Has(caps.UserhostInNames)
  296. maxNamLen := 480 - len(client.server.name) - len(client.Nick())
  297. var namesLines []string
  298. var buffer bytes.Buffer
  299. if isJoined || !channel.flags.HasMode(modes.Secret) || isOper {
  300. for _, target := range channel.Members() {
  301. var nick string
  302. if isUserhostInNames {
  303. nick = target.NickMaskString()
  304. } else {
  305. nick = target.Nick()
  306. }
  307. channel.stateMutex.RLock()
  308. modeSet := channel.members[target]
  309. channel.stateMutex.RUnlock()
  310. if modeSet == nil {
  311. continue
  312. }
  313. if !isJoined && target.flags.HasMode(modes.Invisible) && !isOper {
  314. continue
  315. }
  316. prefix := modeSet.Prefixes(isMultiPrefix)
  317. if buffer.Len()+len(nick)+len(prefix)+1 > maxNamLen {
  318. namesLines = append(namesLines, buffer.String())
  319. buffer.Reset()
  320. }
  321. if buffer.Len() > 0 {
  322. buffer.WriteString(" ")
  323. }
  324. buffer.WriteString(prefix)
  325. buffer.WriteString(nick)
  326. }
  327. if buffer.Len() > 0 {
  328. namesLines = append(namesLines, buffer.String())
  329. }
  330. }
  331. for _, line := range namesLines {
  332. if buffer.Len() > 0 {
  333. rb.Add(nil, client.server.name, RPL_NAMREPLY, client.nick, "=", channel.name, line)
  334. }
  335. }
  336. rb.Add(nil, client.server.name, RPL_ENDOFNAMES, client.nick, channel.name, client.t("End of NAMES list"))
  337. }
  338. // does `clientMode` give you privileges to grant/remove `targetMode` to/from people,
  339. // or to kick them?
  340. func channelUserModeHasPrivsOver(clientMode modes.Mode, targetMode modes.Mode) bool {
  341. switch clientMode {
  342. case modes.ChannelFounder:
  343. return true
  344. case modes.ChannelAdmin, modes.ChannelOperator:
  345. // admins cannot kick other admins, operators *can* kick other operators
  346. return targetMode != modes.ChannelFounder && targetMode != modes.ChannelAdmin
  347. case modes.Halfop:
  348. // halfops cannot kick other halfops
  349. return targetMode != modes.ChannelFounder && targetMode != modes.ChannelAdmin && targetMode != modes.Halfop
  350. default:
  351. // voice and unprivileged cannot kick anyone
  352. return false
  353. }
  354. }
  355. // ClientIsAtLeast returns whether the client has at least the given channel privilege.
  356. func (channel *Channel) ClientIsAtLeast(client *Client, permission modes.Mode) bool {
  357. channel.stateMutex.RLock()
  358. clientModes := channel.members[client]
  359. channel.stateMutex.RUnlock()
  360. for _, mode := range modes.ChannelUserModes {
  361. if clientModes.HasMode(mode) {
  362. return true
  363. }
  364. if mode == permission {
  365. break
  366. }
  367. }
  368. return false
  369. }
  370. func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) string {
  371. channel.stateMutex.RLock()
  372. defer channel.stateMutex.RUnlock()
  373. modes, present := channel.members[client]
  374. if !present {
  375. return ""
  376. } else {
  377. return modes.Prefixes(isMultiPrefix)
  378. }
  379. }
  380. func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
  381. channel.stateMutex.RLock()
  382. clientModes := channel.members[client]
  383. targetModes := channel.members[target]
  384. channel.stateMutex.RUnlock()
  385. return channelUserModeHasPrivsOver(clientModes.HighestChannelUserMode(), targetModes.HighestChannelUserMode())
  386. }
  387. func (channel *Channel) hasClient(client *Client) bool {
  388. channel.stateMutex.RLock()
  389. _, present := channel.members[client]
  390. channel.stateMutex.RUnlock()
  391. return present
  392. }
  393. // <mode> <mode params>
  394. func (channel *Channel) modeStrings(client *Client) (result []string) {
  395. isMember := client.HasMode(modes.Operator) || channel.hasClient(client)
  396. showKey := isMember && (channel.key != "")
  397. showUserLimit := channel.userLimit > 0
  398. mods := "+"
  399. // flags with args
  400. if showKey {
  401. mods += modes.Key.String()
  402. }
  403. if showUserLimit {
  404. mods += modes.UserLimit.String()
  405. }
  406. mods += channel.flags.String()
  407. channel.stateMutex.RLock()
  408. defer channel.stateMutex.RUnlock()
  409. result = []string{mods}
  410. // args for flags with args: The order must match above to keep
  411. // positional arguments in place.
  412. if showKey {
  413. result = append(result, channel.key)
  414. }
  415. if showUserLimit {
  416. result = append(result, strconv.Itoa(channel.userLimit))
  417. }
  418. return
  419. }
  420. func (channel *Channel) IsEmpty() bool {
  421. channel.stateMutex.RLock()
  422. defer channel.stateMutex.RUnlock()
  423. return len(channel.members) == 0
  424. }
  425. // Join joins the given client to this channel (if they can be joined).
  426. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) {
  427. details := client.Details()
  428. channel.stateMutex.RLock()
  429. chname := channel.name
  430. chcfname := channel.nameCasefolded
  431. founder := channel.registeredFounder
  432. chkey := channel.key
  433. limit := channel.userLimit
  434. chcount := len(channel.members)
  435. _, alreadyJoined := channel.members[client]
  436. persistentMode := channel.accountToUMode[details.account]
  437. channel.stateMutex.RUnlock()
  438. if alreadyJoined {
  439. // no message needs to be sent
  440. return
  441. }
  442. // the founder can always join (even if they disabled auto +q on join);
  443. // anyone who automatically receives halfop or higher can always join
  444. hasPrivs := isSajoin || (founder != "" && founder == details.account) || (persistentMode != 0 && persistentMode != modes.Voice)
  445. if !hasPrivs && limit != 0 && chcount >= limit {
  446. rb.Add(nil, client.server.name, ERR_CHANNELISFULL, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "l"))
  447. return
  448. }
  449. if !hasPrivs && chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  450. rb.Add(nil, client.server.name, ERR_BADCHANNELKEY, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "k"))
  451. return
  452. }
  453. isInvited := client.CheckInvited(chcfname) || channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded)
  454. if !hasPrivs && channel.flags.HasMode(modes.InviteOnly) && !isInvited {
  455. rb.Add(nil, client.server.name, ERR_INVITEONLYCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "i"))
  456. return
  457. }
  458. if !hasPrivs && channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  459. !isInvited &&
  460. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) {
  461. rb.Add(nil, client.server.name, ERR_BANNEDFROMCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "b"))
  462. return
  463. }
  464. client.server.logger.Debug("join", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  465. givenMode := func() (givenMode modes.Mode) {
  466. channel.joinPartMutex.Lock()
  467. defer channel.joinPartMutex.Unlock()
  468. func() {
  469. channel.stateMutex.Lock()
  470. defer channel.stateMutex.Unlock()
  471. channel.members.Add(client)
  472. firstJoin := len(channel.members) == 1
  473. newChannel := firstJoin && channel.registeredFounder == ""
  474. if newChannel {
  475. givenMode = modes.ChannelOperator
  476. } else {
  477. givenMode = persistentMode
  478. }
  479. if givenMode != 0 {
  480. channel.members[client].SetMode(givenMode, true)
  481. }
  482. }()
  483. channel.regenerateMembersCache()
  484. message := utils.SplitMessage{}
  485. message.Msgid = details.realname
  486. channel.history.Add(history.Item{
  487. Type: history.Join,
  488. Nick: details.nickMask,
  489. AccountName: details.accountName,
  490. Message: message,
  491. })
  492. return
  493. }()
  494. client.addChannel(channel)
  495. var modestr string
  496. if givenMode != 0 {
  497. modestr = fmt.Sprintf("+%v", givenMode)
  498. }
  499. for _, member := range channel.Members() {
  500. for _, session := range member.Sessions() {
  501. if session == rb.session {
  502. continue
  503. } else if client == session.client {
  504. channel.playJoinForSession(session)
  505. continue
  506. }
  507. if session.capabilities.Has(caps.ExtendedJoin) {
  508. session.Send(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  509. } else {
  510. session.Send(nil, details.nickMask, "JOIN", chname)
  511. }
  512. if givenMode != 0 {
  513. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  514. }
  515. }
  516. }
  517. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  518. rb.Add(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  519. } else {
  520. rb.Add(nil, details.nickMask, "JOIN", chname)
  521. }
  522. if rb.session.client == client {
  523. // don't send topic and names for a SAJOIN of a different client
  524. channel.SendTopic(client, rb, false)
  525. channel.Names(client, rb)
  526. }
  527. // TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
  528. rb.Flush(true)
  529. replayLimit := channel.server.Config().History.AutoreplayOnJoin
  530. if replayLimit > 0 {
  531. items := channel.history.Latest(replayLimit)
  532. channel.replayHistoryItems(rb, items)
  533. rb.Flush(true)
  534. }
  535. }
  536. // plays channel join messages (the JOIN line, topic, and names) to a session.
  537. // this is used when attaching a new session to an existing client that already has
  538. // channels, and also when one session of a client initiates a JOIN and the other
  539. // sessions need to receive the state change
  540. func (channel *Channel) playJoinForSession(session *Session) {
  541. client := session.client
  542. sessionRb := NewResponseBuffer(session)
  543. if session.capabilities.Has(caps.ExtendedJoin) {
  544. sessionRb.Add(nil, client.NickMaskString(), "JOIN", channel.Name(), client.AccountName(), client.Realname())
  545. } else {
  546. sessionRb.Add(nil, client.NickMaskString(), "JOIN", channel.Name())
  547. }
  548. channel.SendTopic(client, sessionRb, false)
  549. channel.Names(client, sessionRb)
  550. sessionRb.Send(false)
  551. }
  552. // Part parts the given client from this channel, with the given message.
  553. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  554. chname := channel.Name()
  555. if !channel.hasClient(client) {
  556. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  557. return
  558. }
  559. channel.Quit(client)
  560. details := client.Details()
  561. for _, member := range channel.Members() {
  562. member.Send(nil, details.nickMask, "PART", chname, message)
  563. }
  564. rb.Add(nil, details.nickMask, "PART", chname, message)
  565. for _, session := range client.Sessions() {
  566. if session != rb.session {
  567. session.Send(nil, details.nickMask, "PART", chname, message)
  568. }
  569. }
  570. channel.history.Add(history.Item{
  571. Type: history.Part,
  572. Nick: details.nickMask,
  573. AccountName: details.accountName,
  574. Message: utils.MakeSplitMessage(message, true),
  575. })
  576. client.server.logger.Debug("part", fmt.Sprintf("%s left channel %s", details.nick, chname))
  577. }
  578. // Resume is called after a successful global resume to:
  579. // 1. Replace the old client with the new in the channel's data structures
  580. // 2. Send JOIN and MODE lines to channel participants (including the new client)
  581. // 3. Replay missed message history to the client
  582. func (channel *Channel) Resume(newClient, oldClient *Client, timestamp time.Time) {
  583. now := time.Now()
  584. channel.resumeAndAnnounce(newClient, oldClient)
  585. if !timestamp.IsZero() {
  586. channel.replayHistoryForResume(newClient, timestamp, now)
  587. }
  588. }
  589. func (channel *Channel) resumeAndAnnounce(newClient, oldClient *Client) {
  590. var oldModeSet *modes.ModeSet
  591. func() {
  592. channel.joinPartMutex.Lock()
  593. defer channel.joinPartMutex.Unlock()
  594. defer channel.regenerateMembersCache()
  595. channel.stateMutex.Lock()
  596. defer channel.stateMutex.Unlock()
  597. newClient.channels[channel] = true
  598. oldModeSet = channel.members[oldClient]
  599. if oldModeSet == nil {
  600. oldModeSet = modes.NewModeSet()
  601. }
  602. channel.members.Remove(oldClient)
  603. channel.members[newClient] = oldModeSet
  604. }()
  605. // construct fake modestring if necessary
  606. oldModes := oldModeSet.String()
  607. if 0 < len(oldModes) {
  608. oldModes = "+" + oldModes
  609. }
  610. // send join for old clients
  611. nick := newClient.Nick()
  612. nickMask := newClient.NickMaskString()
  613. accountName := newClient.AccountName()
  614. realName := newClient.Realname()
  615. for _, member := range channel.Members() {
  616. for _, session := range member.Sessions() {
  617. if session.capabilities.Has(caps.Resume) {
  618. continue
  619. }
  620. if session.capabilities.Has(caps.ExtendedJoin) {
  621. session.Send(nil, nickMask, "JOIN", channel.name, accountName, realName)
  622. } else {
  623. session.Send(nil, nickMask, "JOIN", channel.name)
  624. }
  625. if 0 < len(oldModes) {
  626. session.Send(nil, channel.server.name, "MODE", channel.name, oldModes, nick)
  627. }
  628. }
  629. }
  630. rb := NewResponseBuffer(newClient.Sessions()[0])
  631. // use blocking i/o to synchronize with the later history replay
  632. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  633. rb.Add(nil, nickMask, "JOIN", channel.name, accountName, realName)
  634. } else {
  635. rb.Add(nil, nickMask, "JOIN", channel.name)
  636. }
  637. channel.SendTopic(newClient, rb, false)
  638. channel.Names(newClient, rb)
  639. if 0 < len(oldModes) {
  640. rb.Add(nil, newClient.server.name, "MODE", channel.name, oldModes, nick)
  641. }
  642. rb.Send(true)
  643. }
  644. func (channel *Channel) replayHistoryForResume(newClient *Client, after time.Time, before time.Time) {
  645. items, complete := channel.history.Between(after, before, false, 0)
  646. rb := NewResponseBuffer(newClient.Sessions()[0])
  647. channel.replayHistoryItems(rb, items)
  648. if !complete && !newClient.resumeDetails.HistoryIncomplete {
  649. // warn here if we didn't warn already
  650. rb.Add(nil, "HistServ", "NOTICE", channel.Name(), newClient.t("Some additional message history may have been lost"))
  651. }
  652. rb.Send(true)
  653. }
  654. func stripMaskFromNick(nickMask string) (nick string) {
  655. index := strings.Index(nickMask, "!")
  656. if index == -1 {
  657. return
  658. }
  659. return nickMask[0:index]
  660. }
  661. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item) {
  662. chname := channel.Name()
  663. client := rb.target
  664. serverTime := rb.session.capabilities.Has(caps.ServerTime)
  665. for _, item := range items {
  666. var tags map[string]string
  667. if serverTime {
  668. tags = map[string]string{"time": item.Time.Format(IRCv3TimestampFormat)}
  669. }
  670. // TODO(#437) support history.Tagmsg
  671. switch item.Type {
  672. case history.Privmsg:
  673. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, "PRIVMSG", chname, item.Message)
  674. case history.Notice:
  675. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, "NOTICE", chname, item.Message)
  676. case history.Join:
  677. nick := stripMaskFromNick(item.Nick)
  678. var message string
  679. if item.AccountName == "*" {
  680. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  681. } else {
  682. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  683. }
  684. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  685. case history.Part:
  686. nick := stripMaskFromNick(item.Nick)
  687. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  688. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  689. case history.Quit:
  690. nick := stripMaskFromNick(item.Nick)
  691. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  692. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  693. case history.Kick:
  694. nick := stripMaskFromNick(item.Nick)
  695. // XXX Msgid is the kick target
  696. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Message.Msgid, item.Message.Message)
  697. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  698. }
  699. }
  700. }
  701. // SendTopic sends the channel topic to the given client.
  702. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  703. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  704. channel.stateMutex.RLock()
  705. name := channel.name
  706. topic := channel.topic
  707. topicSetBy := channel.topicSetBy
  708. topicSetTime := channel.topicSetTime
  709. _, hasClient := channel.members[client]
  710. channel.stateMutex.RUnlock()
  711. if !hasClient {
  712. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.name, client.t("You're not on that channel"))
  713. return
  714. }
  715. if topic == "" {
  716. if sendNoTopic {
  717. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  718. }
  719. return
  720. }
  721. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  722. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  723. }
  724. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  725. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  726. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  727. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  728. return
  729. }
  730. if channel.flags.HasMode(modes.OpOnlyTopic) && !channel.ClientIsAtLeast(client, modes.ChannelOperator) {
  731. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  732. return
  733. }
  734. topicLimit := client.server.Limits().TopicLen
  735. if len(topic) > topicLimit {
  736. topic = topic[:topicLimit]
  737. }
  738. channel.stateMutex.Lock()
  739. channel.topic = topic
  740. channel.topicSetBy = client.nickMaskString
  741. channel.topicSetTime = time.Now()
  742. channel.stateMutex.Unlock()
  743. prefix := client.NickMaskString()
  744. for _, member := range channel.Members() {
  745. for _, session := range member.Sessions() {
  746. if session == rb.session {
  747. rb.Add(nil, prefix, "TOPIC", channel.name, topic)
  748. } else {
  749. session.Send(nil, prefix, "TOPIC", channel.name, topic)
  750. }
  751. }
  752. }
  753. channel.MarkDirty(IncludeTopic)
  754. }
  755. // CanSpeak returns true if the client can speak on this channel.
  756. func (channel *Channel) CanSpeak(client *Client) bool {
  757. channel.stateMutex.RLock()
  758. defer channel.stateMutex.RUnlock()
  759. _, hasClient := channel.members[client]
  760. if channel.flags.HasMode(modes.NoOutside) && !hasClient {
  761. return false
  762. }
  763. if channel.flags.HasMode(modes.Moderated) && !channel.ClientIsAtLeast(client, modes.Voice) {
  764. return false
  765. }
  766. if channel.flags.HasMode(modes.RegisteredOnly) && client.Account() == "" {
  767. return false
  768. }
  769. return true
  770. }
  771. func msgCommandToHistType(server *Server, command string) (history.ItemType, error) {
  772. switch command {
  773. case "PRIVMSG":
  774. return history.Privmsg, nil
  775. case "NOTICE":
  776. return history.Notice, nil
  777. case "TAGMSG":
  778. return history.Tagmsg, nil
  779. default:
  780. server.logger.Error("internal", "unrecognized messaging command", command)
  781. return history.ItemType(0), errInvalidParams
  782. }
  783. }
  784. func (channel *Channel) SendSplitMessage(command string, minPrefixMode modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  785. histType, err := msgCommandToHistType(channel.server, command)
  786. if err != nil {
  787. return
  788. }
  789. if !channel.CanSpeak(client) {
  790. if histType != history.Notice {
  791. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), client.t("Cannot send to channel"))
  792. }
  793. return
  794. }
  795. nickmask := client.NickMaskString()
  796. account := client.AccountName()
  797. chname := channel.Name()
  798. now := time.Now().UTC()
  799. // STATUSMSG targets are prefixed with the supplied min-prefix, e.g., @#channel
  800. if minPrefixMode != modes.Mode(0) {
  801. chname = fmt.Sprintf("%s%s", modes.ChannelModePrefixes[minPrefixMode], chname)
  802. }
  803. // send echo-message
  804. // TODO this should use `now` as the time for consistency
  805. if rb.session.capabilities.Has(caps.EchoMessage) {
  806. var tagsToUse map[string]string
  807. if rb.session.capabilities.Has(caps.MessageTags) {
  808. tagsToUse = clientOnlyTags
  809. }
  810. if histType == history.Tagmsg && rb.session.capabilities.Has(caps.MessageTags) {
  811. rb.AddFromClient(message.Msgid, nickmask, account, tagsToUse, command, chname)
  812. } else {
  813. rb.AddSplitMessageFromClient(nickmask, account, tagsToUse, command, chname, message)
  814. }
  815. }
  816. // send echo-message to other connected sessions
  817. for _, session := range client.Sessions() {
  818. if session == rb.session || !session.capabilities.SelfMessagesEnabled() {
  819. continue
  820. }
  821. var tagsToUse map[string]string
  822. if session.capabilities.Has(caps.MessageTags) {
  823. tagsToUse = clientOnlyTags
  824. }
  825. if histType == history.Tagmsg && session.capabilities.Has(caps.MessageTags) {
  826. session.sendFromClientInternal(false, now, message.Msgid, nickmask, account, tagsToUse, command, chname)
  827. } else {
  828. session.sendSplitMsgFromClientInternal(false, now, nickmask, account, tagsToUse, command, chname, message)
  829. }
  830. }
  831. for _, member := range channel.Members() {
  832. // echo-message is handled above, so skip sending the msg to the user themselves as well
  833. if member == client {
  834. continue
  835. }
  836. if minPrefixMode != modes.Mode(0) && !channel.ClientIsAtLeast(member, minPrefixMode) {
  837. // STATUSMSG
  838. continue
  839. }
  840. for _, session := range member.Sessions() {
  841. var tagsToUse map[string]string
  842. if session.capabilities.Has(caps.MessageTags) {
  843. tagsToUse = clientOnlyTags
  844. } else if histType == history.Tagmsg {
  845. continue
  846. }
  847. if histType == history.Tagmsg {
  848. session.sendFromClientInternal(false, now, message.Msgid, nickmask, account, tagsToUse, command, chname)
  849. } else {
  850. session.sendSplitMsgFromClientInternal(false, now, nickmask, account, tagsToUse, command, chname, message)
  851. }
  852. }
  853. }
  854. channel.history.Add(history.Item{
  855. Type: histType,
  856. Message: message,
  857. Nick: nickmask,
  858. AccountName: account,
  859. Time: now,
  860. })
  861. }
  862. func (channel *Channel) applyModeToMember(client *Client, mode modes.Mode, op modes.ModeOp, nick string, rb *ResponseBuffer) (result *modes.ModeChange) {
  863. casefoldedName, err := CasefoldName(nick)
  864. target := channel.server.clients.Get(casefoldedName)
  865. if err != nil || target == nil {
  866. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), nick, client.t("No such nick"))
  867. return nil
  868. }
  869. channel.stateMutex.Lock()
  870. modeset, exists := channel.members[target]
  871. if exists {
  872. if modeset.SetMode(mode, op == modes.Add) {
  873. result = &modes.ModeChange{
  874. Op: op,
  875. Mode: mode,
  876. Arg: nick,
  877. }
  878. }
  879. }
  880. channel.stateMutex.Unlock()
  881. if !exists {
  882. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  883. }
  884. return
  885. }
  886. // ShowMaskList shows the given list to the client.
  887. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  888. // choose appropriate modes
  889. var rpllist, rplendoflist string
  890. if mode == modes.BanMask {
  891. rpllist = RPL_BANLIST
  892. rplendoflist = RPL_ENDOFBANLIST
  893. } else if mode == modes.ExceptMask {
  894. rpllist = RPL_EXCEPTLIST
  895. rplendoflist = RPL_ENDOFEXCEPTLIST
  896. } else if mode == modes.InviteMask {
  897. rpllist = RPL_INVITELIST
  898. rplendoflist = RPL_ENDOFINVITELIST
  899. }
  900. nick := client.Nick()
  901. channel.stateMutex.RLock()
  902. // XXX don't acquire any new locks in this section, besides Socket.Write
  903. for mask := range channel.lists[mode].masks {
  904. rb.Add(nil, client.server.name, rpllist, nick, channel.name, mask)
  905. }
  906. channel.stateMutex.RUnlock()
  907. rb.Add(nil, client.server.name, rplendoflist, nick, channel.name, client.t("End of list"))
  908. }
  909. func (channel *Channel) applyModeMask(client *Client, mode modes.Mode, op modes.ModeOp, mask string, rb *ResponseBuffer) bool {
  910. list := channel.lists[mode]
  911. if list == nil {
  912. // This should never happen, but better safe than panicky.
  913. return false
  914. }
  915. if (op == modes.List) || (mask == "") {
  916. channel.ShowMaskList(client, mode, rb)
  917. return false
  918. }
  919. if !channel.ClientIsAtLeast(client, modes.ChannelOperator) {
  920. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  921. return false
  922. }
  923. if op == modes.Add {
  924. return list.Add(mask)
  925. }
  926. if op == modes.Remove {
  927. return list.Remove(mask)
  928. }
  929. return false
  930. }
  931. // Quit removes the given client from the channel
  932. func (channel *Channel) Quit(client *Client) {
  933. channelEmpty := func() bool {
  934. channel.joinPartMutex.Lock()
  935. defer channel.joinPartMutex.Unlock()
  936. channel.stateMutex.Lock()
  937. channel.members.Remove(client)
  938. channelEmpty := len(channel.members) == 0
  939. channel.stateMutex.Unlock()
  940. channel.regenerateMembersCache()
  941. return channelEmpty
  942. }()
  943. if channelEmpty {
  944. client.server.channels.Cleanup(channel)
  945. }
  946. client.removeChannel(channel)
  947. }
  948. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer) {
  949. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  950. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  951. return
  952. }
  953. if !channel.hasClient(target) {
  954. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  955. return
  956. }
  957. if !channel.ClientHasPrivsOver(client, target) {
  958. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  959. return
  960. }
  961. kicklimit := client.server.Limits().KickLen
  962. if len(comment) > kicklimit {
  963. comment = comment[:kicklimit]
  964. }
  965. clientMask := client.NickMaskString()
  966. targetNick := target.Nick()
  967. chname := channel.Name()
  968. for _, member := range channel.Members() {
  969. for _, session := range member.Sessions() {
  970. if session != rb.session {
  971. session.Send(nil, clientMask, "KICK", chname, targetNick, comment)
  972. }
  973. }
  974. }
  975. rb.Add(nil, clientMask, "KICK", chname, targetNick, comment)
  976. message := utils.SplitMessage{}
  977. message.Message = comment
  978. message.Msgid = targetNick // XXX abuse this field
  979. channel.history.Add(history.Item{
  980. Type: history.Kick,
  981. Nick: clientMask,
  982. AccountName: target.AccountName(),
  983. Message: message,
  984. })
  985. channel.Quit(target)
  986. }
  987. // Invite invites the given client to the channel, if the inviter can do so.
  988. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  989. chname := channel.Name()
  990. if channel.flags.HasMode(modes.InviteOnly) && !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  991. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), channel.Name(), inviter.t("You're not a channel operator"))
  992. return
  993. }
  994. if !channel.hasClient(inviter) {
  995. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), channel.Name(), inviter.t("You're not on that channel"))
  996. return
  997. }
  998. if channel.flags.HasMode(modes.InviteOnly) {
  999. invitee.Invite(channel.NameCasefolded())
  1000. }
  1001. for _, member := range channel.Members() {
  1002. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1003. continue
  1004. }
  1005. for _, session := range member.Sessions() {
  1006. if session.capabilities.Has(caps.InviteNotify) {
  1007. session.Send(nil, inviter.NickMaskString(), "INVITE", invitee.Nick(), chname)
  1008. }
  1009. }
  1010. }
  1011. cnick := inviter.Nick()
  1012. tnick := invitee.Nick()
  1013. rb.Add(nil, inviter.server.name, RPL_INVITING, cnick, tnick, chname)
  1014. invitee.Send(nil, inviter.NickMaskString(), "INVITE", tnick, chname)
  1015. if invitee.Away() {
  1016. rb.Add(nil, inviter.server.name, RPL_AWAY, cnick, tnick, invitee.AwayMessage())
  1017. }
  1018. }