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

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