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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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 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. isMultiPrefix := rb.session.capabilities.Has(caps.MultiPrefix)
  293. isUserhostInNames := rb.session.capabilities.Has(caps.UserhostInNames)
  294. maxNamLen := 480 - len(client.server.name) - len(client.Nick())
  295. var namesLines []string
  296. var buffer bytes.Buffer
  297. for _, target := range channel.Members() {
  298. var nick string
  299. if isUserhostInNames {
  300. nick = target.NickMaskString()
  301. } else {
  302. nick = target.Nick()
  303. }
  304. channel.stateMutex.RLock()
  305. modes := channel.members[target]
  306. channel.stateMutex.RUnlock()
  307. if modes == nil {
  308. continue
  309. }
  310. prefix := modes.Prefixes(isMultiPrefix)
  311. if buffer.Len()+len(nick)+len(prefix)+1 > maxNamLen {
  312. namesLines = append(namesLines, buffer.String())
  313. buffer.Reset()
  314. }
  315. if buffer.Len() > 0 {
  316. buffer.WriteString(" ")
  317. }
  318. buffer.WriteString(prefix)
  319. buffer.WriteString(nick)
  320. }
  321. if buffer.Len() > 0 {
  322. namesLines = append(namesLines, buffer.String())
  323. }
  324. for _, line := range namesLines {
  325. if buffer.Len() > 0 {
  326. rb.Add(nil, client.server.name, RPL_NAMREPLY, client.nick, "=", channel.name, line)
  327. }
  328. }
  329. rb.Add(nil, client.server.name, RPL_ENDOFNAMES, client.nick, channel.name, client.t("End of NAMES list"))
  330. }
  331. func channelUserModeIsAtLeast(clientModes *modes.ModeSet, permission modes.Mode) bool {
  332. if clientModes == nil {
  333. return false
  334. }
  335. for _, mode := range modes.ChannelUserModes {
  336. if clientModes.HasMode(mode) {
  337. return true
  338. }
  339. if mode == permission {
  340. break
  341. }
  342. }
  343. return false
  344. }
  345. // ClientIsAtLeast returns whether the client has at least the given channel privilege.
  346. func (channel *Channel) ClientIsAtLeast(client *Client, permission modes.Mode) bool {
  347. channel.stateMutex.RLock()
  348. clientModes := channel.members[client]
  349. channel.stateMutex.RUnlock()
  350. return channelUserModeIsAtLeast(clientModes, permission)
  351. }
  352. func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) string {
  353. channel.stateMutex.RLock()
  354. defer channel.stateMutex.RUnlock()
  355. modes, present := channel.members[client]
  356. if !present {
  357. return ""
  358. } else {
  359. return modes.Prefixes(isMultiPrefix)
  360. }
  361. }
  362. func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
  363. channel.stateMutex.RLock()
  364. clientModes := channel.members[client]
  365. targetModes := channel.members[target]
  366. channel.stateMutex.RUnlock()
  367. if clientModes.HasMode(modes.ChannelFounder) {
  368. // founder can kick anyone
  369. return true
  370. } else if clientModes.HasMode(modes.ChannelAdmin) {
  371. // admins cannot kick other admins
  372. return !channelUserModeIsAtLeast(targetModes, modes.ChannelAdmin)
  373. } else if clientModes.HasMode(modes.ChannelOperator) {
  374. // operators *can* kick other operators
  375. return !channelUserModeIsAtLeast(targetModes, modes.ChannelAdmin)
  376. } else if clientModes.HasMode(modes.Halfop) {
  377. // halfops cannot kick other halfops
  378. return !channelUserModeIsAtLeast(targetModes, modes.Halfop)
  379. } else {
  380. // voice and unprivileged cannot kick anyone
  381. return false
  382. }
  383. }
  384. func (channel *Channel) hasClient(client *Client) bool {
  385. channel.stateMutex.RLock()
  386. defer channel.stateMutex.RUnlock()
  387. _, present := channel.members[client]
  388. return present
  389. }
  390. // <mode> <mode params>
  391. func (channel *Channel) modeStrings(client *Client) (result []string) {
  392. isMember := client.HasMode(modes.Operator) || channel.hasClient(client)
  393. showKey := isMember && (channel.key != "")
  394. showUserLimit := channel.userLimit > 0
  395. mods := "+"
  396. // flags with args
  397. if showKey {
  398. mods += modes.Key.String()
  399. }
  400. if showUserLimit {
  401. mods += modes.UserLimit.String()
  402. }
  403. mods += channel.flags.String()
  404. channel.stateMutex.RLock()
  405. defer channel.stateMutex.RUnlock()
  406. result = []string{mods}
  407. // args for flags with args: The order must match above to keep
  408. // positional arguments in place.
  409. if showKey {
  410. result = append(result, channel.key)
  411. }
  412. if showUserLimit {
  413. result = append(result, strconv.Itoa(channel.userLimit))
  414. }
  415. return
  416. }
  417. func (channel *Channel) IsEmpty() bool {
  418. channel.stateMutex.RLock()
  419. defer channel.stateMutex.RUnlock()
  420. return len(channel.members) == 0
  421. }
  422. // Join joins the given client to this channel (if they can be joined).
  423. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) {
  424. details := client.Details()
  425. channel.stateMutex.RLock()
  426. chname := channel.name
  427. chcfname := channel.nameCasefolded
  428. founder := channel.registeredFounder
  429. chkey := channel.key
  430. limit := channel.userLimit
  431. chcount := len(channel.members)
  432. _, alreadyJoined := channel.members[client]
  433. persistentMode := channel.accountToUMode[details.account]
  434. channel.stateMutex.RUnlock()
  435. if alreadyJoined {
  436. // no message needs to be sent
  437. return
  438. }
  439. // the founder can always join (even if they disabled auto +q on join);
  440. // anyone who automatically receives halfop or higher can always join
  441. hasPrivs := isSajoin || (founder != "" && founder == details.account) || (persistentMode != 0 && persistentMode != modes.Voice)
  442. if !hasPrivs && limit != 0 && chcount >= limit {
  443. rb.Add(nil, client.server.name, ERR_CHANNELISFULL, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "l"))
  444. return
  445. }
  446. if !hasPrivs && chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  447. rb.Add(nil, client.server.name, ERR_BADCHANNELKEY, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "k"))
  448. return
  449. }
  450. isInvited := client.CheckInvited(chcfname) || channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded)
  451. if !hasPrivs && channel.flags.HasMode(modes.InviteOnly) && !isInvited {
  452. rb.Add(nil, client.server.name, ERR_INVITEONLYCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "i"))
  453. return
  454. }
  455. if !hasPrivs && channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  456. !isInvited &&
  457. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) {
  458. rb.Add(nil, client.server.name, ERR_BANNEDFROMCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "b"))
  459. return
  460. }
  461. client.server.logger.Debug("join", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  462. givenMode := func() (givenMode modes.Mode) {
  463. channel.joinPartMutex.Lock()
  464. defer channel.joinPartMutex.Unlock()
  465. func() {
  466. channel.stateMutex.Lock()
  467. defer channel.stateMutex.Unlock()
  468. channel.members.Add(client)
  469. firstJoin := len(channel.members) == 1
  470. newChannel := firstJoin && channel.registeredFounder == ""
  471. if newChannel {
  472. givenMode = modes.ChannelOperator
  473. } else {
  474. givenMode = persistentMode
  475. }
  476. if givenMode != 0 {
  477. channel.members[client].SetMode(givenMode, true)
  478. }
  479. }()
  480. channel.regenerateMembersCache()
  481. message := utils.SplitMessage{}
  482. message.Msgid = details.realname
  483. channel.history.Add(history.Item{
  484. Type: history.Join,
  485. Nick: details.nickMask,
  486. AccountName: details.accountName,
  487. Message: message,
  488. })
  489. return
  490. }()
  491. client.addChannel(channel)
  492. var modestr string
  493. if givenMode != 0 {
  494. modestr = fmt.Sprintf("+%v", givenMode)
  495. }
  496. for _, member := range channel.Members() {
  497. for _, session := range member.Sessions() {
  498. if session == rb.session {
  499. continue
  500. } else if client == session.client {
  501. channel.playJoinForSession(session)
  502. continue
  503. }
  504. if session.capabilities.Has(caps.ExtendedJoin) {
  505. session.Send(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  506. } else {
  507. session.Send(nil, details.nickMask, "JOIN", chname)
  508. }
  509. if givenMode != 0 {
  510. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  511. }
  512. }
  513. }
  514. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  515. rb.Add(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  516. } else {
  517. rb.Add(nil, details.nickMask, "JOIN", chname)
  518. }
  519. if rb.session.client == client {
  520. // don't send topic and names for a SAJOIN of a different client
  521. channel.SendTopic(client, rb, false)
  522. channel.Names(client, rb)
  523. }
  524. // TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
  525. rb.Flush(true)
  526. replayLimit := channel.server.Config().History.AutoreplayOnJoin
  527. if replayLimit > 0 {
  528. items := channel.history.Latest(replayLimit)
  529. channel.replayHistoryItems(rb, items)
  530. rb.Flush(true)
  531. }
  532. }
  533. // plays channel join messages (the JOIN line, topic, and names) to a session.
  534. // this is used when attaching a new session to an existing client that already has
  535. // channels, and also when one session of a client initiates a JOIN and the other
  536. // sessions need to receive the state change
  537. func (channel *Channel) playJoinForSession(session *Session) {
  538. client := session.client
  539. sessionRb := NewResponseBuffer(session)
  540. if session.capabilities.Has(caps.ExtendedJoin) {
  541. sessionRb.Add(nil, client.NickMaskString(), "JOIN", channel.Name(), client.AccountName(), client.Realname())
  542. } else {
  543. sessionRb.Add(nil, client.NickMaskString(), "JOIN", channel.Name())
  544. }
  545. channel.SendTopic(client, sessionRb, false)
  546. channel.Names(client, sessionRb)
  547. sessionRb.Send(false)
  548. }
  549. // Part parts the given client from this channel, with the given message.
  550. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  551. chname := channel.Name()
  552. if !channel.hasClient(client) {
  553. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  554. return
  555. }
  556. channel.Quit(client)
  557. details := client.Details()
  558. for _, member := range channel.Members() {
  559. member.Send(nil, details.nickMask, "PART", chname, message)
  560. }
  561. rb.Add(nil, details.nickMask, "PART", chname, message)
  562. for _, session := range client.Sessions() {
  563. if session != rb.session {
  564. session.Send(nil, details.nickMask, "PART", chname, message)
  565. }
  566. }
  567. channel.history.Add(history.Item{
  568. Type: history.Part,
  569. Nick: details.nickMask,
  570. AccountName: details.accountName,
  571. Message: utils.MakeSplitMessage(message, true),
  572. })
  573. client.server.logger.Debug("part", fmt.Sprintf("%s left channel %s", details.nick, chname))
  574. }
  575. // Resume is called after a successful global resume to:
  576. // 1. Replace the old client with the new in the channel's data structures
  577. // 2. Send JOIN and MODE lines to channel participants (including the new client)
  578. // 3. Replay missed message history to the client
  579. func (channel *Channel) Resume(newClient, oldClient *Client, timestamp time.Time) {
  580. now := time.Now()
  581. channel.resumeAndAnnounce(newClient, oldClient)
  582. if !timestamp.IsZero() {
  583. channel.replayHistoryForResume(newClient, timestamp, now)
  584. }
  585. }
  586. func (channel *Channel) resumeAndAnnounce(newClient, oldClient *Client) {
  587. var oldModeSet *modes.ModeSet
  588. func() {
  589. channel.joinPartMutex.Lock()
  590. defer channel.joinPartMutex.Unlock()
  591. defer channel.regenerateMembersCache()
  592. channel.stateMutex.Lock()
  593. defer channel.stateMutex.Unlock()
  594. newClient.channels[channel] = true
  595. oldModeSet = channel.members[oldClient]
  596. if oldModeSet == nil {
  597. oldModeSet = modes.NewModeSet()
  598. }
  599. channel.members.Remove(oldClient)
  600. channel.members[newClient] = oldModeSet
  601. }()
  602. // construct fake modestring if necessary
  603. oldModes := oldModeSet.String()
  604. if 0 < len(oldModes) {
  605. oldModes = "+" + oldModes
  606. }
  607. // send join for old clients
  608. nick := newClient.Nick()
  609. nickMask := newClient.NickMaskString()
  610. accountName := newClient.AccountName()
  611. realName := newClient.Realname()
  612. for _, member := range channel.Members() {
  613. for _, session := range member.Sessions() {
  614. if session.capabilities.Has(caps.Resume) {
  615. continue
  616. }
  617. if session.capabilities.Has(caps.ExtendedJoin) {
  618. session.Send(nil, nickMask, "JOIN", channel.name, accountName, realName)
  619. } else {
  620. session.Send(nil, nickMask, "JOIN", channel.name)
  621. }
  622. if 0 < len(oldModes) {
  623. session.Send(nil, channel.server.name, "MODE", channel.name, oldModes, nick)
  624. }
  625. }
  626. }
  627. rb := NewResponseBuffer(newClient.Sessions()[0])
  628. // use blocking i/o to synchronize with the later history replay
  629. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  630. rb.Add(nil, nickMask, "JOIN", channel.name, accountName, realName)
  631. } else {
  632. rb.Add(nil, nickMask, "JOIN", channel.name)
  633. }
  634. channel.SendTopic(newClient, rb, false)
  635. channel.Names(newClient, rb)
  636. if 0 < len(oldModes) {
  637. rb.Add(nil, newClient.server.name, "MODE", channel.name, oldModes, nick)
  638. }
  639. rb.Send(true)
  640. }
  641. func (channel *Channel) replayHistoryForResume(newClient *Client, after time.Time, before time.Time) {
  642. items, complete := channel.history.Between(after, before, false, 0)
  643. rb := NewResponseBuffer(newClient.Sessions()[0])
  644. channel.replayHistoryItems(rb, items)
  645. if !complete && !newClient.resumeDetails.HistoryIncomplete {
  646. // warn here if we didn't warn already
  647. rb.Add(nil, "HistServ", "NOTICE", channel.Name(), newClient.t("Some additional message history may have been lost"))
  648. }
  649. rb.Send(true)
  650. }
  651. func stripMaskFromNick(nickMask string) (nick string) {
  652. index := strings.Index(nickMask, "!")
  653. if index == -1 {
  654. return
  655. }
  656. return nickMask[0:index]
  657. }
  658. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item) {
  659. chname := channel.Name()
  660. client := rb.target
  661. serverTime := rb.session.capabilities.Has(caps.ServerTime)
  662. for _, item := range items {
  663. var tags map[string]string
  664. if serverTime {
  665. tags = map[string]string{"time": item.Time.Format(IRCv3TimestampFormat)}
  666. }
  667. // TODO(#437) support history.Tagmsg
  668. switch item.Type {
  669. case history.Privmsg:
  670. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, "PRIVMSG", chname, item.Message)
  671. case history.Notice:
  672. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, "NOTICE", chname, item.Message)
  673. case history.Join:
  674. nick := stripMaskFromNick(item.Nick)
  675. var message string
  676. if item.AccountName == "*" {
  677. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  678. } else {
  679. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  680. }
  681. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  682. case history.Part:
  683. nick := stripMaskFromNick(item.Nick)
  684. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  685. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  686. case history.Quit:
  687. nick := stripMaskFromNick(item.Nick)
  688. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  689. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  690. case history.Kick:
  691. nick := stripMaskFromNick(item.Nick)
  692. // XXX Msgid is the kick target
  693. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Message.Msgid, item.Message.Message)
  694. rb.Add(tags, "HistServ", "PRIVMSG", chname, message)
  695. }
  696. }
  697. }
  698. // SendTopic sends the channel topic to the given client.
  699. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  700. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  701. channel.stateMutex.RLock()
  702. name := channel.name
  703. topic := channel.topic
  704. topicSetBy := channel.topicSetBy
  705. topicSetTime := channel.topicSetTime
  706. _, hasClient := channel.members[client]
  707. channel.stateMutex.RUnlock()
  708. if !hasClient {
  709. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.name, client.t("You're not on that channel"))
  710. return
  711. }
  712. if topic == "" {
  713. if sendNoTopic {
  714. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  715. }
  716. return
  717. }
  718. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  719. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  720. }
  721. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  722. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  723. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  724. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  725. return
  726. }
  727. if channel.flags.HasMode(modes.OpOnlyTopic) && !channel.ClientIsAtLeast(client, modes.ChannelOperator) {
  728. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  729. return
  730. }
  731. topicLimit := client.server.Limits().TopicLen
  732. if len(topic) > topicLimit {
  733. topic = topic[:topicLimit]
  734. }
  735. channel.stateMutex.Lock()
  736. channel.topic = topic
  737. channel.topicSetBy = client.nickMaskString
  738. channel.topicSetTime = time.Now()
  739. channel.stateMutex.Unlock()
  740. prefix := client.NickMaskString()
  741. for _, member := range channel.Members() {
  742. for _, session := range member.Sessions() {
  743. if session == rb.session {
  744. rb.Add(nil, prefix, "TOPIC", channel.name, topic)
  745. } else {
  746. session.Send(nil, prefix, "TOPIC", channel.name, topic)
  747. }
  748. }
  749. }
  750. channel.MarkDirty(IncludeTopic)
  751. }
  752. // CanSpeak returns true if the client can speak on this channel.
  753. func (channel *Channel) CanSpeak(client *Client) bool {
  754. channel.stateMutex.RLock()
  755. defer channel.stateMutex.RUnlock()
  756. _, hasClient := channel.members[client]
  757. if channel.flags.HasMode(modes.NoOutside) && !hasClient {
  758. return false
  759. }
  760. if channel.flags.HasMode(modes.Moderated) && !channel.ClientIsAtLeast(client, modes.Voice) {
  761. return false
  762. }
  763. if channel.flags.HasMode(modes.RegisteredOnly) && client.Account() == "" {
  764. return false
  765. }
  766. return true
  767. }
  768. func msgCommandToHistType(server *Server, command string) (history.ItemType, error) {
  769. switch command {
  770. case "PRIVMSG":
  771. return history.Privmsg, nil
  772. case "NOTICE":
  773. return history.Notice, nil
  774. case "TAGMSG":
  775. return history.Tagmsg, nil
  776. default:
  777. server.logger.Error("internal", "unrecognized messaging command", command)
  778. return history.ItemType(0), errInvalidParams
  779. }
  780. }
  781. func (channel *Channel) SendSplitMessage(command string, minPrefix *modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  782. histType, err := msgCommandToHistType(channel.server, command)
  783. if err != nil {
  784. return
  785. }
  786. if !channel.CanSpeak(client) {
  787. if histType != history.Notice {
  788. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), client.t("Cannot send to channel"))
  789. }
  790. return
  791. }
  792. nickmask := client.NickMaskString()
  793. account := client.AccountName()
  794. chname := channel.Name()
  795. now := time.Now().UTC()
  796. // for STATUSMSG
  797. var minPrefixMode modes.Mode
  798. if minPrefix != nil {
  799. minPrefixMode = *minPrefix
  800. }
  801. // send echo-message
  802. // TODO this should use `now` as the time for consistency
  803. if rb.session.capabilities.Has(caps.EchoMessage) {
  804. var tagsToUse map[string]string
  805. if rb.session.capabilities.Has(caps.MessageTags) {
  806. tagsToUse = clientOnlyTags
  807. }
  808. if histType == history.Tagmsg && rb.session.capabilities.Has(caps.MessageTags) {
  809. rb.AddFromClient(message.Msgid, nickmask, account, tagsToUse, command, chname)
  810. } else {
  811. rb.AddSplitMessageFromClient(nickmask, account, tagsToUse, command, chname, message)
  812. }
  813. }
  814. // send echo-message to other connected sessions
  815. for _, session := range client.Sessions() {
  816. if session == rb.session || !session.capabilities.SelfMessagesEnabled() {
  817. continue
  818. }
  819. var tagsToUse map[string]string
  820. if session.capabilities.Has(caps.MessageTags) {
  821. tagsToUse = clientOnlyTags
  822. }
  823. if histType == history.Tagmsg && session.capabilities.Has(caps.MessageTags) {
  824. session.sendFromClientInternal(false, now, message.Msgid, nickmask, account, tagsToUse, command, chname)
  825. } else {
  826. session.sendSplitMsgFromClientInternal(false, now, nickmask, account, tagsToUse, command, chname, message)
  827. }
  828. }
  829. for _, member := range channel.Members() {
  830. // echo-message is handled above, so skip sending the msg to the user themselves as well
  831. if member == client {
  832. continue
  833. }
  834. if minPrefix != nil && !channel.ClientIsAtLeast(member, minPrefixMode) {
  835. // STATUSMSG
  836. continue
  837. }
  838. for _, session := range member.Sessions() {
  839. var tagsToUse map[string]string
  840. if session.capabilities.Has(caps.MessageTags) {
  841. tagsToUse = clientOnlyTags
  842. } else if histType == history.Tagmsg {
  843. continue
  844. }
  845. if histType == history.Tagmsg {
  846. session.sendFromClientInternal(false, now, message.Msgid, nickmask, account, tagsToUse, command, chname)
  847. } else {
  848. session.sendSplitMsgFromClientInternal(false, now, nickmask, account, tagsToUse, command, chname, message)
  849. }
  850. }
  851. }
  852. channel.history.Add(history.Item{
  853. Type: histType,
  854. Message: message,
  855. Nick: nickmask,
  856. AccountName: account,
  857. Time: now,
  858. })
  859. }
  860. func (channel *Channel) applyModeToMember(client *Client, mode modes.Mode, op modes.ModeOp, nick string, rb *ResponseBuffer) (result *modes.ModeChange) {
  861. casefoldedName, err := CasefoldName(nick)
  862. target := channel.server.clients.Get(casefoldedName)
  863. if err != nil || target == nil {
  864. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), nick, client.t("No such nick"))
  865. return nil
  866. }
  867. channel.stateMutex.Lock()
  868. modeset, exists := channel.members[target]
  869. if exists {
  870. if modeset.SetMode(mode, op == modes.Add) {
  871. result = &modes.ModeChange{
  872. Op: op,
  873. Mode: mode,
  874. Arg: nick,
  875. }
  876. }
  877. }
  878. channel.stateMutex.Unlock()
  879. if !exists {
  880. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  881. }
  882. return
  883. }
  884. // ShowMaskList shows the given list to the client.
  885. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  886. // choose appropriate modes
  887. var rpllist, rplendoflist string
  888. if mode == modes.BanMask {
  889. rpllist = RPL_BANLIST
  890. rplendoflist = RPL_ENDOFBANLIST
  891. } else if mode == modes.ExceptMask {
  892. rpllist = RPL_EXCEPTLIST
  893. rplendoflist = RPL_ENDOFEXCEPTLIST
  894. } else if mode == modes.InviteMask {
  895. rpllist = RPL_INVITELIST
  896. rplendoflist = RPL_ENDOFINVITELIST
  897. }
  898. nick := client.Nick()
  899. channel.stateMutex.RLock()
  900. // XXX don't acquire any new locks in this section, besides Socket.Write
  901. for mask := range channel.lists[mode].masks {
  902. rb.Add(nil, client.server.name, rpllist, nick, channel.name, mask)
  903. }
  904. channel.stateMutex.RUnlock()
  905. rb.Add(nil, client.server.name, rplendoflist, nick, channel.name, client.t("End of list"))
  906. }
  907. func (channel *Channel) applyModeMask(client *Client, mode modes.Mode, op modes.ModeOp, mask string, rb *ResponseBuffer) bool {
  908. list := channel.lists[mode]
  909. if list == nil {
  910. // This should never happen, but better safe than panicky.
  911. return false
  912. }
  913. if (op == modes.List) || (mask == "") {
  914. channel.ShowMaskList(client, mode, rb)
  915. return false
  916. }
  917. if !channel.ClientIsAtLeast(client, modes.ChannelOperator) {
  918. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  919. return false
  920. }
  921. if op == modes.Add {
  922. return list.Add(mask)
  923. }
  924. if op == modes.Remove {
  925. return list.Remove(mask)
  926. }
  927. return false
  928. }
  929. // Quit removes the given client from the channel
  930. func (channel *Channel) Quit(client *Client) {
  931. channelEmpty := func() bool {
  932. channel.joinPartMutex.Lock()
  933. defer channel.joinPartMutex.Unlock()
  934. channel.stateMutex.Lock()
  935. channel.members.Remove(client)
  936. channelEmpty := len(channel.members) == 0
  937. channel.stateMutex.Unlock()
  938. channel.regenerateMembersCache()
  939. return channelEmpty
  940. }()
  941. if channelEmpty {
  942. client.server.channels.Cleanup(channel)
  943. }
  944. client.removeChannel(channel)
  945. }
  946. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer) {
  947. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  948. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  949. return
  950. }
  951. if !channel.hasClient(target) {
  952. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  953. return
  954. }
  955. if !channel.ClientHasPrivsOver(client, target) {
  956. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  957. return
  958. }
  959. kicklimit := client.server.Limits().KickLen
  960. if len(comment) > kicklimit {
  961. comment = comment[:kicklimit]
  962. }
  963. clientMask := client.NickMaskString()
  964. targetNick := target.Nick()
  965. chname := channel.Name()
  966. for _, member := range channel.Members() {
  967. for _, session := range member.Sessions() {
  968. if session != rb.session {
  969. session.Send(nil, clientMask, "KICK", chname, targetNick, comment)
  970. }
  971. }
  972. }
  973. rb.Add(nil, clientMask, "KICK", chname, targetNick, comment)
  974. message := utils.SplitMessage{}
  975. message.Message = comment
  976. message.Msgid = targetNick // XXX abuse this field
  977. channel.history.Add(history.Item{
  978. Type: history.Kick,
  979. Nick: clientMask,
  980. AccountName: target.AccountName(),
  981. Message: message,
  982. })
  983. channel.Quit(target)
  984. }
  985. // Invite invites the given client to the channel, if the inviter can do so.
  986. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  987. chname := channel.Name()
  988. if channel.flags.HasMode(modes.InviteOnly) && !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  989. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), channel.Name(), inviter.t("You're not a channel operator"))
  990. return
  991. }
  992. if !channel.hasClient(inviter) {
  993. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), channel.Name(), inviter.t("You're not on that channel"))
  994. return
  995. }
  996. if channel.flags.HasMode(modes.InviteOnly) {
  997. invitee.Invite(channel.NameCasefolded())
  998. }
  999. for _, member := range channel.Members() {
  1000. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1001. continue
  1002. }
  1003. for _, session := range member.Sessions() {
  1004. if session.capabilities.Has(caps.InviteNotify) {
  1005. session.Send(nil, inviter.NickMaskString(), "INVITE", invitee.Nick(), chname)
  1006. }
  1007. }
  1008. }
  1009. cnick := inviter.Nick()
  1010. tnick := invitee.Nick()
  1011. rb.Add(nil, inviter.server.name, RPL_INVITING, cnick, tnick, chname)
  1012. invitee.Send(nil, inviter.NickMaskString(), "INVITE", tnick, chname)
  1013. if invitee.HasMode(modes.Away) {
  1014. rb.Add(nil, inviter.server.name, RPL_AWAY, cnick, tnick, invitee.AwayMessage())
  1015. }
  1016. }