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