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

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