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

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