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

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