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

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