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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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. type ChannelSettings struct {
  19. History HistoryStatus
  20. }
  21. // Channel represents a channel that clients can join.
  22. type Channel struct {
  23. flags modes.ModeSet
  24. lists map[modes.Mode]*UserMaskSet
  25. key string
  26. members MemberSet
  27. membersCache []*Client // allow iteration over channel members without holding the lock
  28. name string
  29. nameCasefolded string
  30. server *Server
  31. createdTime time.Time
  32. registeredFounder string
  33. registeredTime time.Time
  34. transferPendingTo string
  35. topic string
  36. topicSetBy string
  37. topicSetTime time.Time
  38. userLimit int
  39. accountToUMode map[string]modes.Mode
  40. history history.Buffer
  41. stateMutex sync.RWMutex // tier 1
  42. writerSemaphore utils.Semaphore // tier 1.5
  43. joinPartMutex sync.Mutex // tier 3
  44. ensureLoaded utils.Once // manages loading stored registration info from the database
  45. dirtyBits uint
  46. settings ChannelSettings
  47. }
  48. // NewChannel creates a new channel from a `Server` and a `name`
  49. // string, which must be unique on the server.
  50. func NewChannel(s *Server, name, casefoldedName string, registered bool) *Channel {
  51. config := s.Config()
  52. channel := &Channel{
  53. createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo
  54. members: make(MemberSet),
  55. name: name,
  56. nameCasefolded: casefoldedName,
  57. server: s,
  58. }
  59. channel.initializeLists()
  60. channel.writerSemaphore.Initialize(1)
  61. channel.history.Initialize(0, 0)
  62. if !registered {
  63. channel.resizeHistory(config)
  64. for _, mode := range config.Channels.defaultModes {
  65. channel.flags.SetMode(mode, true)
  66. }
  67. // no loading to do, so "mark" the load operation as "done":
  68. channel.ensureLoaded.Do(func() {})
  69. } // else: modes will be loaded before first join
  70. return channel
  71. }
  72. func (channel *Channel) initializeLists() {
  73. channel.lists = map[modes.Mode]*UserMaskSet{
  74. modes.BanMask: NewUserMaskSet(),
  75. modes.ExceptMask: NewUserMaskSet(),
  76. modes.InviteMask: NewUserMaskSet(),
  77. }
  78. channel.accountToUMode = make(map[string]modes.Mode)
  79. }
  80. // EnsureLoaded blocks until the channel's registration info has been loaded
  81. // from the database.
  82. func (channel *Channel) EnsureLoaded() {
  83. channel.ensureLoaded.Do(func() {
  84. nmc := channel.NameCasefolded()
  85. info, err := channel.server.channelRegistry.LoadChannel(nmc)
  86. if err == nil {
  87. channel.applyRegInfo(info)
  88. } else {
  89. channel.server.logger.Error("internal", "couldn't load channel", nmc, err.Error())
  90. }
  91. })
  92. }
  93. func (channel *Channel) IsLoaded() bool {
  94. return channel.ensureLoaded.Done()
  95. }
  96. func (channel *Channel) resizeHistory(config *Config) {
  97. status, _ := channel.historyStatus(config)
  98. if status == HistoryEphemeral {
  99. channel.history.Resize(config.History.ChannelLength, config.History.AutoresizeWindow)
  100. } else {
  101. channel.history.Resize(0, 0)
  102. }
  103. }
  104. // read in channel state that was persisted in the DB
  105. func (channel *Channel) applyRegInfo(chanReg RegisteredChannel) {
  106. defer channel.resizeHistory(channel.server.Config())
  107. channel.stateMutex.Lock()
  108. defer channel.stateMutex.Unlock()
  109. channel.registeredFounder = chanReg.Founder
  110. channel.registeredTime = chanReg.RegisteredAt
  111. channel.topic = chanReg.Topic
  112. channel.topicSetBy = chanReg.TopicSetBy
  113. channel.topicSetTime = chanReg.TopicSetTime
  114. channel.name = chanReg.Name
  115. channel.createdTime = chanReg.RegisteredAt
  116. channel.key = chanReg.Key
  117. channel.userLimit = chanReg.UserLimit
  118. channel.settings = chanReg.Settings
  119. for _, mode := range chanReg.Modes {
  120. channel.flags.SetMode(mode, true)
  121. }
  122. for account, mode := range chanReg.AccountToUMode {
  123. channel.accountToUMode[account] = mode
  124. }
  125. channel.lists[modes.BanMask].SetMasks(chanReg.Bans)
  126. channel.lists[modes.InviteMask].SetMasks(chanReg.Invites)
  127. channel.lists[modes.ExceptMask].SetMasks(chanReg.Excepts)
  128. }
  129. // obtain a consistent snapshot of the channel state that can be persisted to the DB
  130. func (channel *Channel) ExportRegistration(includeFlags uint) (info RegisteredChannel) {
  131. channel.stateMutex.RLock()
  132. defer channel.stateMutex.RUnlock()
  133. info.Name = channel.name
  134. info.NameCasefolded = channel.nameCasefolded
  135. info.Founder = channel.registeredFounder
  136. info.RegisteredAt = channel.registeredTime
  137. if includeFlags&IncludeTopic != 0 {
  138. info.Topic = channel.topic
  139. info.TopicSetBy = channel.topicSetBy
  140. info.TopicSetTime = channel.topicSetTime
  141. }
  142. if includeFlags&IncludeModes != 0 {
  143. info.Key = channel.key
  144. info.Modes = channel.flags.AllModes()
  145. info.UserLimit = channel.userLimit
  146. }
  147. if includeFlags&IncludeLists != 0 {
  148. info.Bans = channel.lists[modes.BanMask].Masks()
  149. info.Invites = channel.lists[modes.InviteMask].Masks()
  150. info.Excepts = channel.lists[modes.ExceptMask].Masks()
  151. info.AccountToUMode = make(map[string]modes.Mode)
  152. for account, mode := range channel.accountToUMode {
  153. info.AccountToUMode[account] = mode
  154. }
  155. }
  156. if includeFlags&IncludeSettings != 0 {
  157. info.Settings = channel.settings
  158. }
  159. return
  160. }
  161. // begin: asynchronous database writeback implementation, modeled on irc/socket.go
  162. // MarkDirty marks part (or all) of a channel's data as needing to be written back
  163. // to the database, then starts a writer goroutine if necessary.
  164. // This is the equivalent of Socket.Write().
  165. func (channel *Channel) MarkDirty(dirtyBits uint) {
  166. channel.stateMutex.Lock()
  167. isRegistered := channel.registeredFounder != ""
  168. channel.dirtyBits = channel.dirtyBits | dirtyBits
  169. channel.stateMutex.Unlock()
  170. if !isRegistered {
  171. return
  172. }
  173. channel.wakeWriter()
  174. }
  175. // IsClean returns whether a channel can be safely removed from the server.
  176. // To avoid the obvious TOCTOU race condition, it must be called while holding
  177. // ChannelManager's lock (that way, no one can join and make the channel dirty again
  178. // between this method exiting and the actual deletion).
  179. func (channel *Channel) IsClean() bool {
  180. config := channel.server.Config()
  181. if !channel.writerSemaphore.TryAcquire() {
  182. // a database write (which may fail) is in progress, the channel cannot be cleaned up
  183. return false
  184. }
  185. defer channel.writerSemaphore.Release()
  186. channel.stateMutex.RLock()
  187. defer channel.stateMutex.RUnlock()
  188. if len(channel.members) != 0 {
  189. return false
  190. }
  191. if channel.registeredFounder == "" {
  192. return true
  193. }
  194. // a registered channel must be fully written to the DB,
  195. // and not set to ephemeral history (#704)
  196. return channel.dirtyBits == 0 &&
  197. channelHistoryStatus(config, true, channel.settings.History) != HistoryEphemeral
  198. }
  199. func (channel *Channel) wakeWriter() {
  200. if channel.writerSemaphore.TryAcquire() {
  201. go channel.writeLoop()
  202. }
  203. }
  204. // equivalent of Socket.send()
  205. func (channel *Channel) writeLoop() {
  206. for {
  207. // TODO(#357) check the error value of this and implement timed backoff
  208. channel.performWrite(0)
  209. channel.writerSemaphore.Release()
  210. channel.stateMutex.RLock()
  211. isDirty := channel.dirtyBits != 0
  212. isEmpty := len(channel.members) == 0
  213. channel.stateMutex.RUnlock()
  214. if !isDirty {
  215. if isEmpty {
  216. channel.server.channels.Cleanup(channel)
  217. }
  218. return // nothing to do
  219. } // else: isDirty, so we need to write again
  220. if !channel.writerSemaphore.TryAcquire() {
  221. return
  222. }
  223. }
  224. }
  225. // Store writes part (or all) of the channel's data back to the database,
  226. // blocking until the write is complete. This is the equivalent of
  227. // Socket.BlockingWrite.
  228. func (channel *Channel) Store(dirtyBits uint) (err error) {
  229. defer func() {
  230. channel.stateMutex.Lock()
  231. isDirty := channel.dirtyBits != 0
  232. isEmpty := len(channel.members) == 0
  233. channel.stateMutex.Unlock()
  234. if isDirty {
  235. channel.wakeWriter()
  236. } else if isEmpty {
  237. channel.server.channels.Cleanup(channel)
  238. }
  239. }()
  240. channel.writerSemaphore.Acquire()
  241. defer channel.writerSemaphore.Release()
  242. return channel.performWrite(dirtyBits)
  243. }
  244. // do an individual write; equivalent of Socket.send()
  245. func (channel *Channel) performWrite(additionalDirtyBits uint) (err error) {
  246. channel.stateMutex.Lock()
  247. dirtyBits := channel.dirtyBits | additionalDirtyBits
  248. channel.dirtyBits = 0
  249. isRegistered := channel.registeredFounder != ""
  250. channel.stateMutex.Unlock()
  251. if !isRegistered || dirtyBits == 0 {
  252. return
  253. }
  254. info := channel.ExportRegistration(dirtyBits)
  255. err = channel.server.channelRegistry.StoreChannel(info, dirtyBits)
  256. if err != nil {
  257. channel.stateMutex.Lock()
  258. channel.dirtyBits = channel.dirtyBits | dirtyBits
  259. channel.stateMutex.Unlock()
  260. }
  261. return
  262. }
  263. // SetRegistered registers the channel, returning an error if it was already registered.
  264. func (channel *Channel) SetRegistered(founder string) error {
  265. channel.stateMutex.Lock()
  266. defer channel.stateMutex.Unlock()
  267. if channel.registeredFounder != "" {
  268. return errChannelAlreadyRegistered
  269. }
  270. channel.registeredFounder = founder
  271. channel.registeredTime = time.Now().UTC()
  272. channel.accountToUMode[founder] = modes.ChannelFounder
  273. return nil
  274. }
  275. // SetUnregistered deletes the channel's registration information.
  276. func (channel *Channel) SetUnregistered(expectedFounder string) {
  277. channel.stateMutex.Lock()
  278. defer channel.stateMutex.Unlock()
  279. if channel.registeredFounder != expectedFounder {
  280. return
  281. }
  282. channel.registeredFounder = ""
  283. var zeroTime time.Time
  284. channel.registeredTime = zeroTime
  285. channel.accountToUMode = make(map[string]modes.Mode)
  286. }
  287. // implements `CHANSERV CLEAR #chan ACCESS` (resets bans, invites, excepts, and amodes)
  288. func (channel *Channel) resetAccess() {
  289. defer channel.MarkDirty(IncludeLists)
  290. channel.stateMutex.Lock()
  291. defer channel.stateMutex.Unlock()
  292. channel.initializeLists()
  293. if channel.registeredFounder != "" {
  294. channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
  295. }
  296. }
  297. // IsRegistered returns whether the channel is registered.
  298. func (channel *Channel) IsRegistered() bool {
  299. channel.stateMutex.RLock()
  300. defer channel.stateMutex.RUnlock()
  301. return channel.registeredFounder != ""
  302. }
  303. type channelTransferStatus uint
  304. const (
  305. channelTransferComplete channelTransferStatus = iota
  306. channelTransferPending
  307. channelTransferCancelled
  308. channelTransferFailed
  309. )
  310. // Transfer transfers ownership of a registered channel to a different account
  311. func (channel *Channel) Transfer(client *Client, target string, hasPrivs bool) (status channelTransferStatus, err error) {
  312. status = channelTransferFailed
  313. defer func() {
  314. if status == channelTransferComplete && err == nil {
  315. channel.Store(IncludeAllAttrs)
  316. }
  317. }()
  318. cftarget, err := CasefoldName(target)
  319. if err != nil {
  320. err = errAccountDoesNotExist
  321. return
  322. }
  323. channel.stateMutex.Lock()
  324. defer channel.stateMutex.Unlock()
  325. if channel.registeredFounder == "" {
  326. err = errChannelNotOwnedByAccount
  327. return
  328. }
  329. if hasPrivs {
  330. channel.transferOwnership(cftarget)
  331. return channelTransferComplete, nil
  332. } else {
  333. if channel.registeredFounder == cftarget {
  334. // transferring back to yourself cancels a pending transfer
  335. channel.transferPendingTo = ""
  336. return channelTransferCancelled, nil
  337. } else {
  338. channel.transferPendingTo = cftarget
  339. return channelTransferPending, nil
  340. }
  341. }
  342. }
  343. func (channel *Channel) transferOwnership(newOwner string) {
  344. delete(channel.accountToUMode, channel.registeredFounder)
  345. channel.registeredFounder = newOwner
  346. channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
  347. channel.transferPendingTo = ""
  348. }
  349. // AcceptTransfer implements `CS TRANSFER #chan ACCEPT`
  350. func (channel *Channel) AcceptTransfer(client *Client) (err error) {
  351. defer func() {
  352. if err == nil {
  353. channel.Store(IncludeAllAttrs)
  354. }
  355. }()
  356. account := client.Account()
  357. if account == "" {
  358. return errAccountNotLoggedIn
  359. }
  360. channel.stateMutex.Lock()
  361. defer channel.stateMutex.Unlock()
  362. if account != channel.transferPendingTo {
  363. return errChannelTransferNotOffered
  364. }
  365. channel.transferOwnership(account)
  366. return nil
  367. }
  368. func (channel *Channel) regenerateMembersCache() {
  369. channel.stateMutex.RLock()
  370. result := make([]*Client, len(channel.members))
  371. i := 0
  372. for client := range channel.members {
  373. result[i] = client
  374. i++
  375. }
  376. channel.stateMutex.RUnlock()
  377. channel.stateMutex.Lock()
  378. channel.membersCache = result
  379. channel.stateMutex.Unlock()
  380. }
  381. // Names sends the list of users joined to the channel to the given client.
  382. func (channel *Channel) Names(client *Client, rb *ResponseBuffer) {
  383. isJoined := channel.hasClient(client)
  384. isOper := client.HasMode(modes.Operator)
  385. isMultiPrefix := rb.session.capabilities.Has(caps.MultiPrefix)
  386. isUserhostInNames := rb.session.capabilities.Has(caps.UserhostInNames)
  387. maxNamLen := 480 - len(client.server.name) - len(client.Nick())
  388. var namesLines []string
  389. var buffer bytes.Buffer
  390. if isJoined || !channel.flags.HasMode(modes.Secret) || isOper {
  391. for _, target := range channel.Members() {
  392. var nick string
  393. if isUserhostInNames {
  394. nick = target.NickMaskString()
  395. } else {
  396. nick = target.Nick()
  397. }
  398. channel.stateMutex.RLock()
  399. modeSet := channel.members[target]
  400. channel.stateMutex.RUnlock()
  401. if modeSet == nil {
  402. continue
  403. }
  404. if !isJoined && target.HasMode(modes.Invisible) && !isOper {
  405. continue
  406. }
  407. prefix := modeSet.Prefixes(isMultiPrefix)
  408. if buffer.Len()+len(nick)+len(prefix)+1 > maxNamLen {
  409. namesLines = append(namesLines, buffer.String())
  410. buffer.Reset()
  411. }
  412. if buffer.Len() > 0 {
  413. buffer.WriteString(" ")
  414. }
  415. buffer.WriteString(prefix)
  416. buffer.WriteString(nick)
  417. }
  418. if buffer.Len() > 0 {
  419. namesLines = append(namesLines, buffer.String())
  420. }
  421. }
  422. for _, line := range namesLines {
  423. if buffer.Len() > 0 {
  424. rb.Add(nil, client.server.name, RPL_NAMREPLY, client.nick, "=", channel.name, line)
  425. }
  426. }
  427. rb.Add(nil, client.server.name, RPL_ENDOFNAMES, client.nick, channel.name, client.t("End of NAMES list"))
  428. }
  429. // does `clientMode` give you privileges to grant/remove `targetMode` to/from people,
  430. // or to kick them?
  431. func channelUserModeHasPrivsOver(clientMode modes.Mode, targetMode modes.Mode) bool {
  432. switch clientMode {
  433. case modes.ChannelFounder:
  434. return true
  435. case modes.ChannelAdmin, modes.ChannelOperator:
  436. // admins cannot kick other admins, operators *can* kick other operators
  437. return targetMode != modes.ChannelFounder && targetMode != modes.ChannelAdmin
  438. case modes.Halfop:
  439. // halfops cannot kick other halfops
  440. return targetMode == modes.Voice || targetMode == modes.Mode(0)
  441. default:
  442. // voice and unprivileged cannot kick anyone
  443. return false
  444. }
  445. }
  446. // ClientIsAtLeast returns whether the client has at least the given channel privilege.
  447. func (channel *Channel) ClientIsAtLeast(client *Client, permission modes.Mode) bool {
  448. channel.stateMutex.RLock()
  449. clientModes := channel.members[client]
  450. founder := channel.registeredFounder
  451. channel.stateMutex.RUnlock()
  452. if founder != "" && founder == client.Account() {
  453. return true
  454. }
  455. for _, mode := range modes.ChannelUserModes {
  456. if clientModes.HasMode(mode) {
  457. return true
  458. }
  459. if mode == permission {
  460. break
  461. }
  462. }
  463. return false
  464. }
  465. func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) string {
  466. channel.stateMutex.RLock()
  467. defer channel.stateMutex.RUnlock()
  468. modes, present := channel.members[client]
  469. if !present {
  470. return ""
  471. } else {
  472. return modes.Prefixes(isMultiPrefix)
  473. }
  474. }
  475. func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
  476. channel.stateMutex.RLock()
  477. founder := channel.registeredFounder
  478. clientModes := channel.members[client]
  479. targetModes := channel.members[target]
  480. channel.stateMutex.RUnlock()
  481. if founder != "" && founder == client.Account() {
  482. // #950: founder can kick or whatever without actually having the +q mode
  483. return true
  484. }
  485. return channelUserModeHasPrivsOver(clientModes.HighestChannelUserMode(), targetModes.HighestChannelUserMode())
  486. }
  487. func (channel *Channel) hasClient(client *Client) bool {
  488. channel.stateMutex.RLock()
  489. _, present := channel.members[client]
  490. channel.stateMutex.RUnlock()
  491. return present
  492. }
  493. // <mode> <mode params>
  494. func (channel *Channel) modeStrings(client *Client) (result []string) {
  495. isMember := client.HasMode(modes.Operator) || channel.hasClient(client)
  496. showKey := isMember && (channel.key != "")
  497. showUserLimit := channel.userLimit > 0
  498. mods := "+"
  499. // flags with args
  500. if showKey {
  501. mods += modes.Key.String()
  502. }
  503. if showUserLimit {
  504. mods += modes.UserLimit.String()
  505. }
  506. mods += channel.flags.String()
  507. channel.stateMutex.RLock()
  508. defer channel.stateMutex.RUnlock()
  509. result = []string{mods}
  510. // args for flags with args: The order must match above to keep
  511. // positional arguments in place.
  512. if showKey {
  513. result = append(result, channel.key)
  514. }
  515. if showUserLimit {
  516. result = append(result, strconv.Itoa(channel.userLimit))
  517. }
  518. return
  519. }
  520. func (channel *Channel) IsEmpty() bool {
  521. channel.stateMutex.RLock()
  522. defer channel.stateMutex.RUnlock()
  523. return len(channel.members) == 0
  524. }
  525. // figure out where history is being stored: persistent, ephemeral, or neither
  526. // target is only needed if we're doing persistent history
  527. func (channel *Channel) historyStatus(config *Config) (status HistoryStatus, target string) {
  528. if !config.History.Enabled {
  529. return HistoryDisabled, ""
  530. }
  531. channel.stateMutex.RLock()
  532. target = channel.nameCasefolded
  533. historyStatus := channel.settings.History
  534. registered := channel.registeredFounder != ""
  535. channel.stateMutex.RUnlock()
  536. return channelHistoryStatus(config, registered, historyStatus), target
  537. }
  538. func channelHistoryStatus(config *Config, registered bool, storedStatus HistoryStatus) (result HistoryStatus) {
  539. if !config.History.Enabled {
  540. return HistoryDisabled
  541. }
  542. // ephemeral history: either the channel owner explicitly set the ephemeral preference,
  543. // or persistent history is disabled for unregistered channels
  544. if registered {
  545. return historyEnabled(config.History.Persistent.RegisteredChannels, storedStatus)
  546. } else {
  547. if config.History.Persistent.UnregisteredChannels {
  548. return HistoryPersistent
  549. } else {
  550. return HistoryEphemeral
  551. }
  552. }
  553. }
  554. func (channel *Channel) AddHistoryItem(item history.Item, account string) (err error) {
  555. if !item.IsStorable() {
  556. return
  557. }
  558. status, target := channel.historyStatus(channel.server.Config())
  559. if status == HistoryPersistent {
  560. err = channel.server.historyDB.AddChannelItem(target, item, account)
  561. } else if status == HistoryEphemeral {
  562. channel.history.Add(item)
  563. }
  564. return
  565. }
  566. // Join joins the given client to this channel (if they can be joined).
  567. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) {
  568. details := client.Details()
  569. channel.stateMutex.RLock()
  570. chname := channel.name
  571. chcfname := channel.nameCasefolded
  572. founder := channel.registeredFounder
  573. chkey := channel.key
  574. limit := channel.userLimit
  575. chcount := len(channel.members)
  576. _, alreadyJoined := channel.members[client]
  577. persistentMode := channel.accountToUMode[details.account]
  578. channel.stateMutex.RUnlock()
  579. if alreadyJoined {
  580. // no message needs to be sent
  581. return
  582. }
  583. // the founder can always join (even if they disabled auto +q on join);
  584. // anyone who automatically receives halfop or higher can always join
  585. hasPrivs := isSajoin || (founder != "" && founder == details.account) || (persistentMode != 0 && persistentMode != modes.Voice)
  586. if !hasPrivs && limit != 0 && chcount >= limit {
  587. rb.Add(nil, client.server.name, ERR_CHANNELISFULL, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "l"))
  588. return
  589. }
  590. if !hasPrivs && chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  591. rb.Add(nil, client.server.name, ERR_BADCHANNELKEY, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "k"))
  592. return
  593. }
  594. isInvited := client.CheckInvited(chcfname) || channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded)
  595. if !hasPrivs && channel.flags.HasMode(modes.InviteOnly) && !isInvited {
  596. rb.Add(nil, client.server.name, ERR_INVITEONLYCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "i"))
  597. return
  598. }
  599. if !hasPrivs && channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  600. !isInvited &&
  601. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) {
  602. rb.Add(nil, client.server.name, ERR_BANNEDFROMCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "b"))
  603. return
  604. }
  605. if !hasPrivs && channel.flags.HasMode(modes.RegisteredOnly) && details.account == "" && !isInvited {
  606. rb.Add(nil, client.server.name, ERR_NEEDREGGEDNICK, details.nick, chname, client.t("You must be registered to join that channel"))
  607. return
  608. }
  609. client.server.logger.Debug("join", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  610. givenMode := func() (givenMode modes.Mode) {
  611. channel.joinPartMutex.Lock()
  612. defer channel.joinPartMutex.Unlock()
  613. func() {
  614. channel.stateMutex.Lock()
  615. defer channel.stateMutex.Unlock()
  616. channel.members.Add(client)
  617. firstJoin := len(channel.members) == 1
  618. newChannel := firstJoin && channel.registeredFounder == ""
  619. if newChannel {
  620. givenMode = modes.ChannelOperator
  621. } else {
  622. givenMode = persistentMode
  623. }
  624. if givenMode != 0 {
  625. channel.members[client].SetMode(givenMode, true)
  626. }
  627. }()
  628. channel.regenerateMembersCache()
  629. return
  630. }()
  631. var message utils.SplitMessage
  632. // no history item for fake persistent joins
  633. if rb != nil {
  634. message = utils.MakeMessage("")
  635. histItem := history.Item{
  636. Type: history.Join,
  637. Nick: details.nickMask,
  638. AccountName: details.accountName,
  639. Message: message,
  640. }
  641. histItem.Params[0] = details.realname
  642. channel.AddHistoryItem(histItem, details.account)
  643. }
  644. client.addChannel(channel, rb == nil)
  645. if rb == nil {
  646. return
  647. }
  648. var modestr string
  649. if givenMode != 0 {
  650. modestr = fmt.Sprintf("+%v", givenMode)
  651. }
  652. for _, member := range channel.Members() {
  653. for _, session := range member.Sessions() {
  654. if session == rb.session {
  655. continue
  656. } else if client == session.client {
  657. channel.playJoinForSession(session)
  658. continue
  659. }
  660. if session.capabilities.Has(caps.ExtendedJoin) {
  661. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname, details.accountName, details.realname)
  662. } else {
  663. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname)
  664. }
  665. if givenMode != 0 {
  666. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  667. }
  668. }
  669. }
  670. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  671. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname, details.accountName, details.realname)
  672. } else {
  673. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname)
  674. }
  675. if rb.session.client == client {
  676. // don't send topic and names for a SAJOIN of a different client
  677. channel.SendTopic(client, rb, false)
  678. channel.Names(client, rb)
  679. }
  680. // TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
  681. rb.Flush(true)
  682. channel.autoReplayHistory(client, rb, message.Msgid)
  683. }
  684. func (channel *Channel) autoReplayHistory(client *Client, rb *ResponseBuffer, skipMsgid string) {
  685. // autoreplay any messages as necessary
  686. var items []history.Item
  687. var start, end time.Time
  688. if rb.session.zncPlaybackTimes.ValidFor(channel.NameCasefolded()) {
  689. start, end = rb.session.zncPlaybackTimes.start, rb.session.zncPlaybackTimes.end
  690. } else if !rb.session.autoreplayMissedSince.IsZero() {
  691. // we already checked for history caps in `playReattachMessages`
  692. start = time.Now().UTC()
  693. end = rb.session.autoreplayMissedSince
  694. }
  695. if !start.IsZero() || !end.IsZero() {
  696. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  697. if seq != nil {
  698. zncMax := channel.server.Config().History.ZNCMax
  699. items, _, _ = seq.Between(history.Selector{Time: start}, history.Selector{Time: end}, zncMax)
  700. }
  701. } else if !rb.session.HasHistoryCaps() {
  702. var replayLimit int
  703. customReplayLimit := client.AccountSettings().AutoreplayLines
  704. if customReplayLimit != nil {
  705. replayLimit = *customReplayLimit
  706. maxLimit := channel.server.Config().History.ChathistoryMax
  707. if maxLimit < replayLimit {
  708. replayLimit = maxLimit
  709. }
  710. } else {
  711. replayLimit = channel.server.Config().History.AutoreplayOnJoin
  712. }
  713. if 0 < replayLimit {
  714. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  715. if seq != nil {
  716. items, _, _ = seq.Between(history.Selector{}, history.Selector{}, replayLimit)
  717. }
  718. }
  719. }
  720. // remove the client's own JOIN line from the replay
  721. numItems := len(items)
  722. for i := len(items) - 1; 0 <= i; i-- {
  723. if items[i].Message.Msgid == skipMsgid {
  724. // zero'ed items will not be replayed because their `Type` field is not recognized
  725. items[i] = history.Item{}
  726. numItems--
  727. break
  728. }
  729. }
  730. if 0 < numItems {
  731. channel.replayHistoryItems(rb, items, true)
  732. rb.Flush(true)
  733. }
  734. }
  735. // plays channel join messages (the JOIN line, topic, and names) to a session.
  736. // this is used when attaching a new session to an existing client that already has
  737. // channels, and also when one session of a client initiates a JOIN and the other
  738. // sessions need to receive the state change
  739. func (channel *Channel) playJoinForSession(session *Session) {
  740. client := session.client
  741. sessionRb := NewResponseBuffer(session)
  742. details := client.Details()
  743. if session.capabilities.Has(caps.ExtendedJoin) {
  744. sessionRb.Add(nil, details.nickMask, "JOIN", channel.Name(), details.accountName, details.realname)
  745. } else {
  746. sessionRb.Add(nil, details.nickMask, "JOIN", channel.Name())
  747. }
  748. channel.SendTopic(client, sessionRb, false)
  749. channel.Names(client, sessionRb)
  750. sessionRb.Send(false)
  751. }
  752. // Part parts the given client from this channel, with the given message.
  753. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  754. chname := channel.Name()
  755. if !channel.hasClient(client) {
  756. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  757. return
  758. }
  759. channel.Quit(client)
  760. splitMessage := utils.MakeMessage(message)
  761. details := client.Details()
  762. params := make([]string, 1, 2)
  763. params[0] = chname
  764. if message != "" {
  765. params = append(params, message)
  766. }
  767. for _, member := range channel.Members() {
  768. member.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, nil, "PART", params...)
  769. }
  770. rb.AddFromClient(splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, nil, "PART", params...)
  771. for _, session := range client.Sessions() {
  772. if session != rb.session {
  773. session.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, nil, "PART", params...)
  774. }
  775. }
  776. channel.AddHistoryItem(history.Item{
  777. Type: history.Part,
  778. Nick: details.nickMask,
  779. AccountName: details.accountName,
  780. Message: splitMessage,
  781. }, details.account)
  782. client.server.logger.Debug("part", fmt.Sprintf("%s left channel %s", details.nick, chname))
  783. }
  784. // Resume is called after a successful global resume to:
  785. // 1. Replace the old client with the new in the channel's data structures
  786. // 2. Send JOIN and MODE lines to channel participants (including the new client)
  787. // 3. Replay missed message history to the client
  788. func (channel *Channel) Resume(session *Session, timestamp time.Time) {
  789. channel.resumeAndAnnounce(session)
  790. if !timestamp.IsZero() {
  791. channel.replayHistoryForResume(session, timestamp, time.Time{})
  792. }
  793. }
  794. func (channel *Channel) resumeAndAnnounce(session *Session) {
  795. channel.stateMutex.RLock()
  796. modeSet := channel.members[session.client]
  797. channel.stateMutex.RUnlock()
  798. if modeSet == nil {
  799. return
  800. }
  801. oldModes := modeSet.String()
  802. if 0 < len(oldModes) {
  803. oldModes = "+" + oldModes
  804. }
  805. // send join for old clients
  806. chname := channel.Name()
  807. details := session.client.Details()
  808. for _, member := range channel.Members() {
  809. for _, session := range member.Sessions() {
  810. if session.capabilities.Has(caps.Resume) {
  811. continue
  812. }
  813. if session.capabilities.Has(caps.ExtendedJoin) {
  814. session.Send(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  815. } else {
  816. session.Send(nil, details.nickMask, "JOIN", chname)
  817. }
  818. if 0 < len(oldModes) {
  819. session.Send(nil, channel.server.name, "MODE", chname, oldModes, details.nick)
  820. }
  821. }
  822. }
  823. rb := NewResponseBuffer(session)
  824. // use blocking i/o to synchronize with the later history replay
  825. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  826. rb.Add(nil, details.nickMask, "JOIN", channel.name, details.accountName, details.realname)
  827. } else {
  828. rb.Add(nil, details.nickMask, "JOIN", channel.name)
  829. }
  830. channel.SendTopic(session.client, rb, false)
  831. channel.Names(session.client, rb)
  832. rb.Send(true)
  833. }
  834. func (channel *Channel) replayHistoryForResume(session *Session, after time.Time, before time.Time) {
  835. var items []history.Item
  836. var complete bool
  837. afterS, beforeS := history.Selector{Time: after}, history.Selector{Time: before}
  838. _, seq, _ := channel.server.GetHistorySequence(channel, session.client, "")
  839. if seq != nil {
  840. items, complete, _ = seq.Between(afterS, beforeS, channel.server.Config().History.ZNCMax)
  841. }
  842. rb := NewResponseBuffer(session)
  843. if len(items) != 0 {
  844. channel.replayHistoryItems(rb, items, false)
  845. }
  846. if !complete && !session.resumeDetails.HistoryIncomplete {
  847. // warn here if we didn't warn already
  848. rb.Add(nil, histServMask, "NOTICE", channel.Name(), session.client.t("Some additional message history may have been lost"))
  849. }
  850. rb.Send(true)
  851. }
  852. func stripMaskFromNick(nickMask string) (nick string) {
  853. index := strings.Index(nickMask, "!")
  854. if index == -1 {
  855. return nickMask
  856. }
  857. return nickMask[0:index]
  858. }
  859. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item, autoreplay bool) {
  860. // send an empty batch if necessary, as per the CHATHISTORY spec
  861. chname := channel.Name()
  862. client := rb.target
  863. eventPlayback := rb.session.capabilities.Has(caps.EventPlayback)
  864. extendedJoin := rb.session.capabilities.Has(caps.ExtendedJoin)
  865. var playJoinsAsPrivmsg bool
  866. if !eventPlayback {
  867. switch client.AccountSettings().ReplayJoins {
  868. case ReplayJoinsCommandsOnly:
  869. playJoinsAsPrivmsg = !autoreplay
  870. case ReplayJoinsAlways:
  871. playJoinsAsPrivmsg = true
  872. case ReplayJoinsNever:
  873. playJoinsAsPrivmsg = false
  874. }
  875. }
  876. batchID := rb.StartNestedHistoryBatch(chname)
  877. defer rb.EndNestedBatch(batchID)
  878. for _, item := range items {
  879. nick := stripMaskFromNick(item.Nick)
  880. switch item.Type {
  881. case history.Privmsg:
  882. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.Tags, "PRIVMSG", chname, item.Message)
  883. case history.Notice:
  884. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.Tags, "NOTICE", chname, item.Message)
  885. case history.Tagmsg:
  886. if rb.session.capabilities.Has(caps.MessageTags) {
  887. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.Tags, "TAGMSG", chname, item.Message)
  888. }
  889. case history.Join:
  890. if eventPlayback {
  891. if extendedJoin {
  892. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "JOIN", chname, item.AccountName, item.Params[0])
  893. } else {
  894. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "JOIN", chname)
  895. }
  896. } else {
  897. if !playJoinsAsPrivmsg {
  898. continue // #474
  899. }
  900. var message string
  901. if item.AccountName == "*" {
  902. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  903. } else {
  904. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  905. }
  906. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  907. }
  908. case history.Part:
  909. if eventPlayback {
  910. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "PART", chname, item.Message.Message)
  911. } else {
  912. if !playJoinsAsPrivmsg {
  913. continue // #474
  914. }
  915. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  916. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  917. }
  918. case history.Kick:
  919. if eventPlayback {
  920. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "KICK", chname, item.Params[0], item.Message.Message)
  921. } else {
  922. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Params[0], item.Message.Message)
  923. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  924. }
  925. case history.Quit:
  926. if eventPlayback {
  927. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "QUIT", item.Message.Message)
  928. } else {
  929. if !playJoinsAsPrivmsg {
  930. continue // #474
  931. }
  932. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  933. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  934. }
  935. case history.Nick:
  936. if eventPlayback {
  937. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "NICK", item.Params[0])
  938. } else {
  939. message := fmt.Sprintf(client.t("%[1]s changed nick to %[2]s"), nick, item.Params[0])
  940. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  941. }
  942. case history.Topic:
  943. if eventPlayback {
  944. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "TOPIC", chname, item.Message.Message)
  945. } else {
  946. message := fmt.Sprintf(client.t("%[1]s set the channel topic to: %[2]s"), nick, item.Message.Message)
  947. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  948. }
  949. case history.Mode:
  950. params := make([]string, len(item.Message.Split)+1)
  951. params[0] = chname
  952. for i, pair := range item.Message.Split {
  953. params[i+1] = pair.Message
  954. }
  955. if eventPlayback {
  956. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "MODE", params...)
  957. } else {
  958. message := fmt.Sprintf(client.t("%[1]s set channel modes: %[2]s"), nick, strings.Join(params[1:], " "))
  959. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  960. }
  961. }
  962. }
  963. }
  964. // SendTopic sends the channel topic to the given client.
  965. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  966. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  967. channel.stateMutex.RLock()
  968. name := channel.name
  969. topic := channel.topic
  970. topicSetBy := channel.topicSetBy
  971. topicSetTime := channel.topicSetTime
  972. _, hasClient := channel.members[client]
  973. channel.stateMutex.RUnlock()
  974. if !hasClient {
  975. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.name, client.t("You're not on that channel"))
  976. return
  977. }
  978. if topic == "" {
  979. if sendNoTopic {
  980. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  981. }
  982. return
  983. }
  984. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  985. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  986. }
  987. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  988. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  989. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  990. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  991. return
  992. }
  993. if channel.flags.HasMode(modes.OpOnlyTopic) && !channel.ClientIsAtLeast(client, modes.ChannelOperator) {
  994. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  995. return
  996. }
  997. topicLimit := client.server.Config().Limits.TopicLen
  998. if len(topic) > topicLimit {
  999. topic = topic[:topicLimit]
  1000. }
  1001. channel.stateMutex.Lock()
  1002. chname := channel.name
  1003. channel.topic = topic
  1004. channel.topicSetBy = client.nickMaskString
  1005. channel.topicSetTime = time.Now().UTC()
  1006. channel.stateMutex.Unlock()
  1007. details := client.Details()
  1008. message := utils.MakeMessage(topic)
  1009. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, nil, "TOPIC", chname, topic)
  1010. for _, member := range channel.Members() {
  1011. for _, session := range member.Sessions() {
  1012. if session != rb.session {
  1013. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, nil, "TOPIC", chname, topic)
  1014. }
  1015. }
  1016. }
  1017. channel.AddHistoryItem(history.Item{
  1018. Type: history.Topic,
  1019. Nick: details.nickMask,
  1020. AccountName: details.accountName,
  1021. Message: message,
  1022. }, details.account)
  1023. channel.MarkDirty(IncludeTopic)
  1024. }
  1025. // CanSpeak returns true if the client can speak on this channel.
  1026. func (channel *Channel) CanSpeak(client *Client) bool {
  1027. channel.stateMutex.RLock()
  1028. defer channel.stateMutex.RUnlock()
  1029. _, hasClient := channel.members[client]
  1030. if channel.flags.HasMode(modes.NoOutside) && !hasClient {
  1031. return false
  1032. }
  1033. if channel.flags.HasMode(modes.Moderated) && !channel.ClientIsAtLeast(client, modes.Voice) {
  1034. return false
  1035. }
  1036. if channel.flags.HasMode(modes.RegisteredOnly) && client.Account() == "" {
  1037. return false
  1038. }
  1039. return true
  1040. }
  1041. func msgCommandToHistType(command string) (history.ItemType, error) {
  1042. switch command {
  1043. case "PRIVMSG":
  1044. return history.Privmsg, nil
  1045. case "NOTICE":
  1046. return history.Notice, nil
  1047. case "TAGMSG":
  1048. return history.Tagmsg, nil
  1049. default:
  1050. return history.ItemType(0), errInvalidParams
  1051. }
  1052. }
  1053. func (channel *Channel) SendSplitMessage(command string, minPrefixMode modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  1054. histType, err := msgCommandToHistType(command)
  1055. if err != nil {
  1056. return
  1057. }
  1058. if !channel.CanSpeak(client) {
  1059. if histType != history.Notice {
  1060. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), client.t("Cannot send to channel"))
  1061. }
  1062. return
  1063. }
  1064. isCTCP := message.IsRestrictedCTCPMessage()
  1065. if isCTCP && channel.flags.HasMode(modes.NoCTCP) {
  1066. if histType != history.Notice {
  1067. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), "C"))
  1068. }
  1069. return
  1070. }
  1071. details := client.Details()
  1072. chname := channel.Name()
  1073. // STATUSMSG targets are prefixed with the supplied min-prefix, e.g., @#channel
  1074. if minPrefixMode != modes.Mode(0) {
  1075. chname = fmt.Sprintf("%s%s", modes.ChannelModePrefixes[minPrefixMode], chname)
  1076. }
  1077. // send echo-message
  1078. if rb.session.capabilities.Has(caps.EchoMessage) {
  1079. var tagsToUse map[string]string
  1080. if rb.session.capabilities.Has(caps.MessageTags) {
  1081. tagsToUse = clientOnlyTags
  1082. }
  1083. if histType == history.Tagmsg && rb.session.capabilities.Has(caps.MessageTags) {
  1084. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, tagsToUse, command, chname)
  1085. } else {
  1086. rb.AddSplitMessageFromClient(details.nickMask, details.accountName, tagsToUse, command, chname, message)
  1087. }
  1088. }
  1089. // send echo-message to other connected sessions
  1090. for _, session := range client.Sessions() {
  1091. if session == rb.session {
  1092. continue
  1093. }
  1094. var tagsToUse map[string]string
  1095. if session.capabilities.Has(caps.MessageTags) {
  1096. tagsToUse = clientOnlyTags
  1097. }
  1098. if histType == history.Tagmsg && session.capabilities.Has(caps.MessageTags) {
  1099. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, tagsToUse, command, chname)
  1100. } else if histType != history.Tagmsg {
  1101. session.sendSplitMsgFromClientInternal(false, details.nickMask, details.accountName, tagsToUse, command, chname, message)
  1102. }
  1103. }
  1104. for _, member := range channel.Members() {
  1105. // echo-message is handled above, so skip sending the msg to the user themselves as well
  1106. if member == client {
  1107. continue
  1108. }
  1109. if minPrefixMode != modes.Mode(0) && !channel.ClientIsAtLeast(member, minPrefixMode) {
  1110. // STATUSMSG
  1111. continue
  1112. }
  1113. for _, session := range member.Sessions() {
  1114. if isCTCP && session.isTor {
  1115. continue // #753
  1116. }
  1117. var tagsToUse map[string]string
  1118. if session.capabilities.Has(caps.MessageTags) {
  1119. tagsToUse = clientOnlyTags
  1120. } else if histType == history.Tagmsg {
  1121. continue
  1122. }
  1123. if histType == history.Tagmsg {
  1124. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, tagsToUse, command, chname)
  1125. } else {
  1126. session.sendSplitMsgFromClientInternal(false, details.nickMask, details.accountName, tagsToUse, command, chname, message)
  1127. }
  1128. }
  1129. }
  1130. // #959: don't save STATUSMSG
  1131. if minPrefixMode == modes.Mode(0) {
  1132. channel.AddHistoryItem(history.Item{
  1133. Type: histType,
  1134. Message: message,
  1135. Nick: details.nickMask,
  1136. AccountName: details.accountName,
  1137. Tags: clientOnlyTags,
  1138. }, details.account)
  1139. }
  1140. }
  1141. func (channel *Channel) applyModeToMember(client *Client, change modes.ModeChange, rb *ResponseBuffer) (applied bool, result modes.ModeChange) {
  1142. target := channel.server.clients.Get(change.Arg)
  1143. if target == nil {
  1144. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(change.Arg), client.t("No such nick"))
  1145. return
  1146. }
  1147. change.Arg = target.Nick()
  1148. channel.stateMutex.Lock()
  1149. modeset, exists := channel.members[target]
  1150. if exists {
  1151. if modeset.SetMode(change.Mode, change.Op == modes.Add) {
  1152. applied = true
  1153. result = change
  1154. }
  1155. }
  1156. channel.stateMutex.Unlock()
  1157. if !exists {
  1158. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1159. }
  1160. return
  1161. }
  1162. // ShowMaskList shows the given list to the client.
  1163. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  1164. // choose appropriate modes
  1165. var rpllist, rplendoflist string
  1166. if mode == modes.BanMask {
  1167. rpllist = RPL_BANLIST
  1168. rplendoflist = RPL_ENDOFBANLIST
  1169. } else if mode == modes.ExceptMask {
  1170. rpllist = RPL_EXCEPTLIST
  1171. rplendoflist = RPL_ENDOFEXCEPTLIST
  1172. } else if mode == modes.InviteMask {
  1173. rpllist = RPL_INVITELIST
  1174. rplendoflist = RPL_ENDOFINVITELIST
  1175. }
  1176. nick := client.Nick()
  1177. chname := channel.Name()
  1178. for mask, info := range channel.lists[mode].Masks() {
  1179. rb.Add(nil, client.server.name, rpllist, nick, chname, mask, info.CreatorNickmask, strconv.FormatInt(info.TimeCreated.Unix(), 10))
  1180. }
  1181. rb.Add(nil, client.server.name, rplendoflist, nick, chname, client.t("End of list"))
  1182. }
  1183. // Quit removes the given client from the channel
  1184. func (channel *Channel) Quit(client *Client) {
  1185. channelEmpty := func() bool {
  1186. channel.joinPartMutex.Lock()
  1187. defer channel.joinPartMutex.Unlock()
  1188. channel.stateMutex.Lock()
  1189. channel.members.Remove(client)
  1190. channelEmpty := len(channel.members) == 0
  1191. channel.stateMutex.Unlock()
  1192. channel.regenerateMembersCache()
  1193. return channelEmpty
  1194. }()
  1195. if channelEmpty {
  1196. client.server.channels.Cleanup(channel)
  1197. }
  1198. client.removeChannel(channel)
  1199. }
  1200. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer, hasPrivs bool) {
  1201. if !hasPrivs {
  1202. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  1203. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  1204. return
  1205. }
  1206. if !channel.ClientHasPrivsOver(client, target) {
  1207. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  1208. return
  1209. }
  1210. }
  1211. if !channel.hasClient(target) {
  1212. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1213. return
  1214. }
  1215. kicklimit := channel.server.Config().Limits.KickLen
  1216. if len(comment) > kicklimit {
  1217. comment = comment[:kicklimit]
  1218. }
  1219. message := utils.MakeMessage(comment)
  1220. details := client.Details()
  1221. targetNick := target.Nick()
  1222. chname := channel.Name()
  1223. for _, member := range channel.Members() {
  1224. for _, session := range member.Sessions() {
  1225. if session != rb.session {
  1226. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, nil, "KICK", chname, targetNick, comment)
  1227. }
  1228. }
  1229. }
  1230. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, nil, "KICK", chname, targetNick, comment)
  1231. histItem := history.Item{
  1232. Type: history.Kick,
  1233. Nick: details.nickMask,
  1234. AccountName: details.accountName,
  1235. Message: message,
  1236. }
  1237. histItem.Params[0] = targetNick
  1238. channel.AddHistoryItem(histItem, details.account)
  1239. channel.Quit(target)
  1240. }
  1241. // Invite invites the given client to the channel, if the inviter can do so.
  1242. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1243. chname := channel.Name()
  1244. if channel.flags.HasMode(modes.InviteOnly) && !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  1245. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), chname, inviter.t("You're not a channel operator"))
  1246. return
  1247. }
  1248. if !channel.hasClient(inviter) {
  1249. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), chname, inviter.t("You're not on that channel"))
  1250. return
  1251. }
  1252. if channel.hasClient(invitee) {
  1253. rb.Add(nil, inviter.server.name, ERR_USERONCHANNEL, inviter.Nick(), invitee.Nick(), chname, inviter.t("User is already on that channel"))
  1254. return
  1255. }
  1256. if channel.flags.HasMode(modes.InviteOnly) {
  1257. invitee.Invite(channel.NameCasefolded())
  1258. }
  1259. for _, member := range channel.Members() {
  1260. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1261. continue
  1262. }
  1263. for _, session := range member.Sessions() {
  1264. if session.capabilities.Has(caps.InviteNotify) {
  1265. session.Send(nil, inviter.NickMaskString(), "INVITE", invitee.Nick(), chname)
  1266. }
  1267. }
  1268. }
  1269. cnick := inviter.Nick()
  1270. tnick := invitee.Nick()
  1271. rb.Add(nil, inviter.server.name, RPL_INVITING, cnick, tnick, chname)
  1272. invitee.Send(nil, inviter.NickMaskString(), "INVITE", tnick, chname)
  1273. if invitee.Away() {
  1274. rb.Add(nil, inviter.server.name, RPL_AWAY, cnick, tnick, invitee.AwayMessage())
  1275. }
  1276. }