You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

channel.go 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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. clientModes := channel.members[client]
  477. targetModes := channel.members[target]
  478. channel.stateMutex.RUnlock()
  479. return channelUserModeHasPrivsOver(clientModes.HighestChannelUserMode(), targetModes.HighestChannelUserMode())
  480. }
  481. func (channel *Channel) hasClient(client *Client) bool {
  482. channel.stateMutex.RLock()
  483. _, present := channel.members[client]
  484. channel.stateMutex.RUnlock()
  485. return present
  486. }
  487. // <mode> <mode params>
  488. func (channel *Channel) modeStrings(client *Client) (result []string) {
  489. isMember := client.HasMode(modes.Operator) || channel.hasClient(client)
  490. showKey := isMember && (channel.key != "")
  491. showUserLimit := channel.userLimit > 0
  492. mods := "+"
  493. // flags with args
  494. if showKey {
  495. mods += modes.Key.String()
  496. }
  497. if showUserLimit {
  498. mods += modes.UserLimit.String()
  499. }
  500. mods += channel.flags.String()
  501. channel.stateMutex.RLock()
  502. defer channel.stateMutex.RUnlock()
  503. result = []string{mods}
  504. // args for flags with args: The order must match above to keep
  505. // positional arguments in place.
  506. if showKey {
  507. result = append(result, channel.key)
  508. }
  509. if showUserLimit {
  510. result = append(result, strconv.Itoa(channel.userLimit))
  511. }
  512. return
  513. }
  514. func (channel *Channel) IsEmpty() bool {
  515. channel.stateMutex.RLock()
  516. defer channel.stateMutex.RUnlock()
  517. return len(channel.members) == 0
  518. }
  519. // figure out where history is being stored: persistent, ephemeral, or neither
  520. // target is only needed if we're doing persistent history
  521. func (channel *Channel) historyStatus(config *Config) (status HistoryStatus, target string) {
  522. if !config.History.Enabled {
  523. return HistoryDisabled, ""
  524. }
  525. channel.stateMutex.RLock()
  526. target = channel.nameCasefolded
  527. historyStatus := channel.settings.History
  528. registered := channel.registeredFounder != ""
  529. channel.stateMutex.RUnlock()
  530. return channelHistoryStatus(config, registered, historyStatus), target
  531. }
  532. func channelHistoryStatus(config *Config, registered bool, storedStatus HistoryStatus) (result HistoryStatus) {
  533. if !config.History.Enabled {
  534. return HistoryDisabled
  535. }
  536. // ephemeral history: either the channel owner explicitly set the ephemeral preference,
  537. // or persistent history is disabled for unregistered channels
  538. if registered {
  539. return historyEnabled(config.History.Persistent.RegisteredChannels, storedStatus)
  540. } else {
  541. if config.History.Persistent.UnregisteredChannels {
  542. return HistoryPersistent
  543. } else {
  544. return HistoryEphemeral
  545. }
  546. }
  547. }
  548. func (channel *Channel) AddHistoryItem(item history.Item) (err error) {
  549. if !item.IsStorable() {
  550. return
  551. }
  552. status, target := channel.historyStatus(channel.server.Config())
  553. if status == HistoryPersistent {
  554. err = channel.server.historyDB.AddChannelItem(target, item)
  555. } else if status == HistoryEphemeral {
  556. channel.history.Add(item)
  557. }
  558. return
  559. }
  560. // Join joins the given client to this channel (if they can be joined).
  561. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) {
  562. details := client.Details()
  563. channel.stateMutex.RLock()
  564. chname := channel.name
  565. chcfname := channel.nameCasefolded
  566. founder := channel.registeredFounder
  567. chkey := channel.key
  568. limit := channel.userLimit
  569. chcount := len(channel.members)
  570. _, alreadyJoined := channel.members[client]
  571. persistentMode := channel.accountToUMode[details.account]
  572. channel.stateMutex.RUnlock()
  573. if alreadyJoined {
  574. // no message needs to be sent
  575. return
  576. }
  577. // the founder can always join (even if they disabled auto +q on join);
  578. // anyone who automatically receives halfop or higher can always join
  579. hasPrivs := isSajoin || (founder != "" && founder == details.account) || (persistentMode != 0 && persistentMode != modes.Voice)
  580. if !hasPrivs && limit != 0 && chcount >= limit {
  581. rb.Add(nil, client.server.name, ERR_CHANNELISFULL, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "l"))
  582. return
  583. }
  584. if !hasPrivs && chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  585. rb.Add(nil, client.server.name, ERR_BADCHANNELKEY, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "k"))
  586. return
  587. }
  588. isInvited := client.CheckInvited(chcfname) || channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded)
  589. if !hasPrivs && channel.flags.HasMode(modes.InviteOnly) && !isInvited {
  590. rb.Add(nil, client.server.name, ERR_INVITEONLYCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "i"))
  591. return
  592. }
  593. if !hasPrivs && channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  594. !isInvited &&
  595. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) {
  596. rb.Add(nil, client.server.name, ERR_BANNEDFROMCHAN, details.nick, chname, fmt.Sprintf(client.t("Cannot join channel (+%s)"), "b"))
  597. return
  598. }
  599. if !hasPrivs && channel.flags.HasMode(modes.RegisteredOnly) && details.account == "" && !isInvited {
  600. rb.Add(nil, client.server.name, ERR_BANNEDFROMCHAN, details.nick, chname, client.t("You must be registered to join that channel"))
  601. return
  602. }
  603. client.server.logger.Debug("join", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  604. givenMode := func() (givenMode modes.Mode) {
  605. channel.joinPartMutex.Lock()
  606. defer channel.joinPartMutex.Unlock()
  607. func() {
  608. channel.stateMutex.Lock()
  609. defer channel.stateMutex.Unlock()
  610. channel.members.Add(client)
  611. firstJoin := len(channel.members) == 1
  612. newChannel := firstJoin && channel.registeredFounder == ""
  613. if newChannel {
  614. givenMode = modes.ChannelOperator
  615. } else {
  616. givenMode = persistentMode
  617. }
  618. if givenMode != 0 {
  619. channel.members[client].SetMode(givenMode, true)
  620. }
  621. }()
  622. channel.regenerateMembersCache()
  623. return
  624. }()
  625. var message utils.SplitMessage
  626. // no history item for fake persistent joins
  627. if rb != nil {
  628. message = utils.MakeMessage("")
  629. histItem := history.Item{
  630. Type: history.Join,
  631. Nick: details.nickMask,
  632. AccountName: details.accountName,
  633. Message: message,
  634. }
  635. histItem.Params[0] = details.realname
  636. channel.AddHistoryItem(histItem)
  637. }
  638. client.addChannel(channel, rb == nil)
  639. if rb == nil {
  640. return
  641. }
  642. var modestr string
  643. if givenMode != 0 {
  644. modestr = fmt.Sprintf("+%v", givenMode)
  645. }
  646. for _, member := range channel.Members() {
  647. for _, session := range member.Sessions() {
  648. if session == rb.session {
  649. continue
  650. } else if client == session.client {
  651. channel.playJoinForSession(session)
  652. continue
  653. }
  654. if session.capabilities.Has(caps.ExtendedJoin) {
  655. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname, details.accountName, details.realname)
  656. } else {
  657. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname)
  658. }
  659. if givenMode != 0 {
  660. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  661. }
  662. }
  663. }
  664. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  665. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname, details.accountName, details.realname)
  666. } else {
  667. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, nil, "JOIN", chname)
  668. }
  669. if rb.session.client == client {
  670. // don't send topic and names for a SAJOIN of a different client
  671. channel.SendTopic(client, rb, false)
  672. channel.Names(client, rb)
  673. }
  674. // TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
  675. rb.Flush(true)
  676. channel.autoReplayHistory(client, rb, message.Msgid)
  677. }
  678. func (channel *Channel) autoReplayHistory(client *Client, rb *ResponseBuffer, skipMsgid string) {
  679. // autoreplay any messages as necessary
  680. var items []history.Item
  681. var start, end time.Time
  682. if rb.session.zncPlaybackTimes.ValidFor(channel.NameCasefolded()) {
  683. start, end = rb.session.zncPlaybackTimes.start, rb.session.zncPlaybackTimes.end
  684. } else if !rb.session.autoreplayMissedSince.IsZero() {
  685. // we already checked for history caps in `playReattachMessages`
  686. start = time.Now().UTC()
  687. end = rb.session.autoreplayMissedSince
  688. }
  689. if !start.IsZero() || !end.IsZero() {
  690. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  691. if seq != nil {
  692. zncMax := channel.server.Config().History.ZNCMax
  693. items, _, _ = seq.Between(history.Selector{Time: start}, history.Selector{Time: end}, zncMax)
  694. }
  695. } else if !rb.session.HasHistoryCaps() {
  696. var replayLimit int
  697. customReplayLimit := client.AccountSettings().AutoreplayLines
  698. if customReplayLimit != nil {
  699. replayLimit = *customReplayLimit
  700. maxLimit := channel.server.Config().History.ChathistoryMax
  701. if maxLimit < replayLimit {
  702. replayLimit = maxLimit
  703. }
  704. } else {
  705. replayLimit = channel.server.Config().History.AutoreplayOnJoin
  706. }
  707. if 0 < replayLimit {
  708. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  709. if seq != nil {
  710. items, _, _ = seq.Between(history.Selector{}, history.Selector{}, replayLimit)
  711. }
  712. }
  713. }
  714. // remove the client's own JOIN line from the replay
  715. numItems := len(items)
  716. for i := len(items) - 1; 0 <= i; i-- {
  717. if items[i].Message.Msgid == skipMsgid {
  718. // zero'ed items will not be replayed because their `Type` field is not recognized
  719. items[i] = history.Item{}
  720. numItems--
  721. break
  722. }
  723. }
  724. if 0 < numItems {
  725. channel.replayHistoryItems(rb, items, true)
  726. rb.Flush(true)
  727. }
  728. }
  729. // plays channel join messages (the JOIN line, topic, and names) to a session.
  730. // this is used when attaching a new session to an existing client that already has
  731. // channels, and also when one session of a client initiates a JOIN and the other
  732. // sessions need to receive the state change
  733. func (channel *Channel) playJoinForSession(session *Session) {
  734. client := session.client
  735. sessionRb := NewResponseBuffer(session)
  736. details := client.Details()
  737. if session.capabilities.Has(caps.ExtendedJoin) {
  738. sessionRb.Add(nil, details.nickMask, "JOIN", channel.Name(), details.accountName, details.realname)
  739. } else {
  740. sessionRb.Add(nil, details.nickMask, "JOIN", channel.Name())
  741. }
  742. channel.SendTopic(client, sessionRb, false)
  743. channel.Names(client, sessionRb)
  744. sessionRb.Send(false)
  745. }
  746. // Part parts the given client from this channel, with the given message.
  747. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  748. chname := channel.Name()
  749. if !channel.hasClient(client) {
  750. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  751. return
  752. }
  753. channel.Quit(client)
  754. splitMessage := utils.MakeMessage(message)
  755. details := client.Details()
  756. params := make([]string, 1, 2)
  757. params[0] = chname
  758. if message != "" {
  759. params = append(params, message)
  760. }
  761. for _, member := range channel.Members() {
  762. member.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, nil, "PART", params...)
  763. }
  764. rb.AddFromClient(splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, nil, "PART", params...)
  765. for _, session := range client.Sessions() {
  766. if session != rb.session {
  767. session.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, nil, "PART", params...)
  768. }
  769. }
  770. channel.AddHistoryItem(history.Item{
  771. Type: history.Part,
  772. Nick: details.nickMask,
  773. AccountName: details.accountName,
  774. Message: splitMessage,
  775. })
  776. client.server.logger.Debug("part", fmt.Sprintf("%s left channel %s", details.nick, chname))
  777. }
  778. // Resume is called after a successful global resume to:
  779. // 1. Replace the old client with the new in the channel's data structures
  780. // 2. Send JOIN and MODE lines to channel participants (including the new client)
  781. // 3. Replay missed message history to the client
  782. func (channel *Channel) Resume(session *Session, timestamp time.Time) {
  783. channel.resumeAndAnnounce(session)
  784. if !timestamp.IsZero() {
  785. channel.replayHistoryForResume(session, timestamp, time.Time{})
  786. }
  787. }
  788. func (channel *Channel) resumeAndAnnounce(session *Session) {
  789. channel.stateMutex.RLock()
  790. modeSet := channel.members[session.client]
  791. channel.stateMutex.RUnlock()
  792. if modeSet == nil {
  793. return
  794. }
  795. oldModes := modeSet.String()
  796. if 0 < len(oldModes) {
  797. oldModes = "+" + oldModes
  798. }
  799. // send join for old clients
  800. chname := channel.Name()
  801. details := session.client.Details()
  802. for _, member := range channel.Members() {
  803. for _, session := range member.Sessions() {
  804. if session.capabilities.Has(caps.Resume) {
  805. continue
  806. }
  807. if session.capabilities.Has(caps.ExtendedJoin) {
  808. session.Send(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  809. } else {
  810. session.Send(nil, details.nickMask, "JOIN", chname)
  811. }
  812. if 0 < len(oldModes) {
  813. session.Send(nil, channel.server.name, "MODE", chname, oldModes, details.nick)
  814. }
  815. }
  816. }
  817. rb := NewResponseBuffer(session)
  818. // use blocking i/o to synchronize with the later history replay
  819. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  820. rb.Add(nil, details.nickMask, "JOIN", channel.name, details.accountName, details.realname)
  821. } else {
  822. rb.Add(nil, details.nickMask, "JOIN", channel.name)
  823. }
  824. channel.SendTopic(session.client, rb, false)
  825. channel.Names(session.client, rb)
  826. rb.Send(true)
  827. }
  828. func (channel *Channel) replayHistoryForResume(session *Session, after time.Time, before time.Time) {
  829. var items []history.Item
  830. var complete bool
  831. afterS, beforeS := history.Selector{Time: after}, history.Selector{Time: before}
  832. _, seq, _ := channel.server.GetHistorySequence(channel, session.client, "")
  833. if seq != nil {
  834. items, complete, _ = seq.Between(afterS, beforeS, channel.server.Config().History.ZNCMax)
  835. }
  836. rb := NewResponseBuffer(session)
  837. if len(items) != 0 {
  838. channel.replayHistoryItems(rb, items, false)
  839. }
  840. if !complete && !session.resumeDetails.HistoryIncomplete {
  841. // warn here if we didn't warn already
  842. rb.Add(nil, histServMask, "NOTICE", channel.Name(), session.client.t("Some additional message history may have been lost"))
  843. }
  844. rb.Send(true)
  845. }
  846. func stripMaskFromNick(nickMask string) (nick string) {
  847. index := strings.Index(nickMask, "!")
  848. if index == -1 {
  849. return nickMask
  850. }
  851. return nickMask[0:index]
  852. }
  853. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item, autoreplay bool) {
  854. // send an empty batch if necessary, as per the CHATHISTORY spec
  855. chname := channel.Name()
  856. client := rb.target
  857. eventPlayback := rb.session.capabilities.Has(caps.EventPlayback)
  858. extendedJoin := rb.session.capabilities.Has(caps.ExtendedJoin)
  859. var playJoinsAsPrivmsg bool
  860. if !eventPlayback {
  861. switch client.AccountSettings().ReplayJoins {
  862. case ReplayJoinsCommandsOnly:
  863. playJoinsAsPrivmsg = !autoreplay
  864. case ReplayJoinsAlways:
  865. playJoinsAsPrivmsg = true
  866. case ReplayJoinsNever:
  867. playJoinsAsPrivmsg = false
  868. }
  869. }
  870. batchID := rb.StartNestedHistoryBatch(chname)
  871. defer rb.EndNestedBatch(batchID)
  872. for _, item := range items {
  873. nick := stripMaskFromNick(item.Nick)
  874. switch item.Type {
  875. case history.Privmsg:
  876. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.Tags, "PRIVMSG", chname, item.Message)
  877. case history.Notice:
  878. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.Tags, "NOTICE", chname, item.Message)
  879. case history.Tagmsg:
  880. if rb.session.capabilities.Has(caps.MessageTags) {
  881. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.Tags, "TAGMSG", chname, item.Message)
  882. }
  883. case history.Join:
  884. if eventPlayback {
  885. if extendedJoin {
  886. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "JOIN", chname, item.AccountName, item.Params[0])
  887. } else {
  888. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "JOIN", chname)
  889. }
  890. } else {
  891. if !playJoinsAsPrivmsg {
  892. continue // #474
  893. }
  894. var message string
  895. if item.AccountName == "*" {
  896. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  897. } else {
  898. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  899. }
  900. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  901. }
  902. case history.Part:
  903. if eventPlayback {
  904. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "PART", chname, item.Message.Message)
  905. } else {
  906. if !playJoinsAsPrivmsg {
  907. continue // #474
  908. }
  909. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  910. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  911. }
  912. case history.Kick:
  913. if eventPlayback {
  914. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "KICK", chname, item.Params[0], item.Message.Message)
  915. } else {
  916. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Params[0], item.Message.Message)
  917. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  918. }
  919. case history.Quit:
  920. if eventPlayback {
  921. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "QUIT", item.Message.Message)
  922. } else {
  923. if !playJoinsAsPrivmsg {
  924. continue // #474
  925. }
  926. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  927. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  928. }
  929. case history.Nick:
  930. if eventPlayback {
  931. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, nil, "NICK", item.Params[0])
  932. } else {
  933. message := fmt.Sprintf(client.t("%[1]s changed nick to %[2]s"), nick, item.Params[0])
  934. rb.AddFromClient(item.Message.Time, utils.MungeSecretToken(item.Message.Msgid), histServMask, "*", nil, "PRIVMSG", chname, message)
  935. }
  936. }
  937. }
  938. }
  939. // SendTopic sends the channel topic to the given client.
  940. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  941. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  942. channel.stateMutex.RLock()
  943. name := channel.name
  944. topic := channel.topic
  945. topicSetBy := channel.topicSetBy
  946. topicSetTime := channel.topicSetTime
  947. _, hasClient := channel.members[client]
  948. channel.stateMutex.RUnlock()
  949. if !hasClient {
  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 topic == "" {
  954. if sendNoTopic {
  955. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  956. }
  957. return
  958. }
  959. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  960. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  961. }
  962. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  963. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  964. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  965. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  966. return
  967. }
  968. if channel.flags.HasMode(modes.OpOnlyTopic) && !channel.ClientIsAtLeast(client, modes.ChannelOperator) {
  969. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  970. return
  971. }
  972. topicLimit := client.server.Config().Limits.TopicLen
  973. if len(topic) > topicLimit {
  974. topic = topic[:topicLimit]
  975. }
  976. channel.stateMutex.Lock()
  977. channel.topic = topic
  978. channel.topicSetBy = client.nickMaskString
  979. channel.topicSetTime = time.Now().UTC()
  980. channel.stateMutex.Unlock()
  981. prefix := client.NickMaskString()
  982. for _, member := range channel.Members() {
  983. for _, session := range member.Sessions() {
  984. if session == rb.session {
  985. rb.Add(nil, prefix, "TOPIC", channel.name, topic)
  986. } else {
  987. session.Send(nil, prefix, "TOPIC", channel.name, topic)
  988. }
  989. }
  990. }
  991. channel.MarkDirty(IncludeTopic)
  992. }
  993. // CanSpeak returns true if the client can speak on this channel.
  994. func (channel *Channel) CanSpeak(client *Client) bool {
  995. channel.stateMutex.RLock()
  996. defer channel.stateMutex.RUnlock()
  997. _, hasClient := channel.members[client]
  998. if channel.flags.HasMode(modes.NoOutside) && !hasClient {
  999. return false
  1000. }
  1001. if channel.flags.HasMode(modes.Moderated) && !channel.ClientIsAtLeast(client, modes.Voice) {
  1002. return false
  1003. }
  1004. if channel.flags.HasMode(modes.RegisteredOnly) && client.Account() == "" {
  1005. return false
  1006. }
  1007. return true
  1008. }
  1009. func msgCommandToHistType(command string) (history.ItemType, error) {
  1010. switch command {
  1011. case "PRIVMSG":
  1012. return history.Privmsg, nil
  1013. case "NOTICE":
  1014. return history.Notice, nil
  1015. case "TAGMSG":
  1016. return history.Tagmsg, nil
  1017. default:
  1018. return history.ItemType(0), errInvalidParams
  1019. }
  1020. }
  1021. func (channel *Channel) SendSplitMessage(command string, minPrefixMode modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  1022. histType, err := msgCommandToHistType(command)
  1023. if err != nil {
  1024. return
  1025. }
  1026. if !channel.CanSpeak(client) {
  1027. if histType != history.Notice {
  1028. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), client.t("Cannot send to channel"))
  1029. }
  1030. return
  1031. }
  1032. isCTCP := message.IsRestrictedCTCPMessage()
  1033. if isCTCP && channel.flags.HasMode(modes.NoCTCP) {
  1034. if histType != history.Notice {
  1035. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), "C"))
  1036. }
  1037. return
  1038. }
  1039. nickmask := client.NickMaskString()
  1040. account := client.AccountName()
  1041. chname := channel.Name()
  1042. // STATUSMSG targets are prefixed with the supplied min-prefix, e.g., @#channel
  1043. if minPrefixMode != modes.Mode(0) {
  1044. chname = fmt.Sprintf("%s%s", modes.ChannelModePrefixes[minPrefixMode], chname)
  1045. }
  1046. // send echo-message
  1047. if rb.session.capabilities.Has(caps.EchoMessage) {
  1048. var tagsToUse map[string]string
  1049. if rb.session.capabilities.Has(caps.MessageTags) {
  1050. tagsToUse = clientOnlyTags
  1051. }
  1052. if histType == history.Tagmsg && rb.session.capabilities.Has(caps.MessageTags) {
  1053. rb.AddFromClient(message.Time, message.Msgid, nickmask, account, tagsToUse, command, chname)
  1054. } else {
  1055. rb.AddSplitMessageFromClient(nickmask, account, tagsToUse, command, chname, message)
  1056. }
  1057. }
  1058. // send echo-message to other connected sessions
  1059. for _, session := range client.Sessions() {
  1060. if session == rb.session {
  1061. continue
  1062. }
  1063. var tagsToUse map[string]string
  1064. if session.capabilities.Has(caps.MessageTags) {
  1065. tagsToUse = clientOnlyTags
  1066. }
  1067. if histType == history.Tagmsg && session.capabilities.Has(caps.MessageTags) {
  1068. session.sendFromClientInternal(false, message.Time, message.Msgid, nickmask, account, tagsToUse, command, chname)
  1069. } else if histType != history.Tagmsg {
  1070. session.sendSplitMsgFromClientInternal(false, nickmask, account, tagsToUse, command, chname, message)
  1071. }
  1072. }
  1073. for _, member := range channel.Members() {
  1074. // echo-message is handled above, so skip sending the msg to the user themselves as well
  1075. if member == client {
  1076. continue
  1077. }
  1078. if minPrefixMode != modes.Mode(0) && !channel.ClientIsAtLeast(member, minPrefixMode) {
  1079. // STATUSMSG
  1080. continue
  1081. }
  1082. for _, session := range member.Sessions() {
  1083. if isCTCP && session.isTor {
  1084. continue // #753
  1085. }
  1086. var tagsToUse map[string]string
  1087. if session.capabilities.Has(caps.MessageTags) {
  1088. tagsToUse = clientOnlyTags
  1089. } else if histType == history.Tagmsg {
  1090. continue
  1091. }
  1092. if histType == history.Tagmsg {
  1093. session.sendFromClientInternal(false, message.Time, message.Msgid, nickmask, account, tagsToUse, command, chname)
  1094. } else {
  1095. session.sendSplitMsgFromClientInternal(false, nickmask, account, tagsToUse, command, chname, message)
  1096. }
  1097. }
  1098. }
  1099. channel.AddHistoryItem(history.Item{
  1100. Type: histType,
  1101. Message: message,
  1102. Nick: nickmask,
  1103. AccountName: account,
  1104. Tags: clientOnlyTags,
  1105. })
  1106. }
  1107. func (channel *Channel) applyModeToMember(client *Client, change modes.ModeChange, rb *ResponseBuffer) (applied bool, result modes.ModeChange) {
  1108. target := channel.server.clients.Get(change.Arg)
  1109. if target == nil {
  1110. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(change.Arg), client.t("No such nick"))
  1111. return
  1112. }
  1113. change.Arg = target.Nick()
  1114. channel.stateMutex.Lock()
  1115. modeset, exists := channel.members[target]
  1116. if exists {
  1117. if modeset.SetMode(change.Mode, change.Op == modes.Add) {
  1118. applied = true
  1119. result = change
  1120. }
  1121. }
  1122. channel.stateMutex.Unlock()
  1123. if !exists {
  1124. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1125. }
  1126. return
  1127. }
  1128. // ShowMaskList shows the given list to the client.
  1129. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  1130. // choose appropriate modes
  1131. var rpllist, rplendoflist string
  1132. if mode == modes.BanMask {
  1133. rpllist = RPL_BANLIST
  1134. rplendoflist = RPL_ENDOFBANLIST
  1135. } else if mode == modes.ExceptMask {
  1136. rpllist = RPL_EXCEPTLIST
  1137. rplendoflist = RPL_ENDOFEXCEPTLIST
  1138. } else if mode == modes.InviteMask {
  1139. rpllist = RPL_INVITELIST
  1140. rplendoflist = RPL_ENDOFINVITELIST
  1141. }
  1142. nick := client.Nick()
  1143. chname := channel.Name()
  1144. for mask, info := range channel.lists[mode].Masks() {
  1145. rb.Add(nil, client.server.name, rpllist, nick, chname, mask, info.CreatorNickmask, strconv.FormatInt(info.TimeCreated.Unix(), 10))
  1146. }
  1147. rb.Add(nil, client.server.name, rplendoflist, nick, chname, client.t("End of list"))
  1148. }
  1149. // Quit removes the given client from the channel
  1150. func (channel *Channel) Quit(client *Client) {
  1151. channelEmpty := func() bool {
  1152. channel.joinPartMutex.Lock()
  1153. defer channel.joinPartMutex.Unlock()
  1154. channel.stateMutex.Lock()
  1155. channel.members.Remove(client)
  1156. channelEmpty := len(channel.members) == 0
  1157. channel.stateMutex.Unlock()
  1158. channel.regenerateMembersCache()
  1159. return channelEmpty
  1160. }()
  1161. if channelEmpty {
  1162. client.server.channels.Cleanup(channel)
  1163. }
  1164. client.removeChannel(channel)
  1165. }
  1166. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer, hasPrivs bool) {
  1167. if !hasPrivs {
  1168. if !(client.HasMode(modes.Operator) || channel.hasClient(client)) {
  1169. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  1170. return
  1171. }
  1172. if !channel.ClientHasPrivsOver(client, target) {
  1173. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  1174. return
  1175. }
  1176. }
  1177. if !channel.hasClient(target) {
  1178. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1179. return
  1180. }
  1181. kicklimit := channel.server.Config().Limits.KickLen
  1182. if len(comment) > kicklimit {
  1183. comment = comment[:kicklimit]
  1184. }
  1185. message := utils.MakeMessage(comment)
  1186. clientMask := client.NickMaskString()
  1187. clientAccount := client.AccountName()
  1188. targetNick := target.Nick()
  1189. chname := channel.Name()
  1190. for _, member := range channel.Members() {
  1191. for _, session := range member.Sessions() {
  1192. if session != rb.session {
  1193. session.sendFromClientInternal(false, message.Time, message.Msgid, clientMask, clientAccount, nil, "KICK", chname, targetNick, comment)
  1194. }
  1195. }
  1196. }
  1197. rb.Add(nil, clientMask, "KICK", chname, targetNick, comment)
  1198. histItem := history.Item{
  1199. Type: history.Kick,
  1200. Nick: clientMask,
  1201. AccountName: target.AccountName(),
  1202. Message: message,
  1203. }
  1204. histItem.Params[0] = targetNick
  1205. channel.AddHistoryItem(histItem)
  1206. channel.Quit(target)
  1207. }
  1208. // Invite invites the given client to the channel, if the inviter can do so.
  1209. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1210. chname := channel.Name()
  1211. if channel.flags.HasMode(modes.InviteOnly) && !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  1212. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), chname, inviter.t("You're not a channel operator"))
  1213. return
  1214. }
  1215. if !channel.hasClient(inviter) {
  1216. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), chname, inviter.t("You're not on that channel"))
  1217. return
  1218. }
  1219. if channel.hasClient(invitee) {
  1220. rb.Add(nil, inviter.server.name, ERR_USERONCHANNEL, inviter.Nick(), invitee.Nick(), chname, inviter.t("User is already on that channel"))
  1221. return
  1222. }
  1223. if channel.flags.HasMode(modes.InviteOnly) {
  1224. invitee.Invite(channel.NameCasefolded())
  1225. }
  1226. for _, member := range channel.Members() {
  1227. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1228. continue
  1229. }
  1230. for _, session := range member.Sessions() {
  1231. if session.capabilities.Has(caps.InviteNotify) {
  1232. session.Send(nil, inviter.NickMaskString(), "INVITE", invitee.Nick(), chname)
  1233. }
  1234. }
  1235. }
  1236. cnick := inviter.Nick()
  1237. tnick := invitee.Nick()
  1238. rb.Add(nil, inviter.server.name, RPL_INVITING, cnick, tnick, chname)
  1239. invitee.Send(nil, inviter.NickMaskString(), "INVITE", tnick, chname)
  1240. if invitee.Away() {
  1241. rb.Add(nil, inviter.server.name, RPL_AWAY, cnick, tnick, invitee.AwayMessage())
  1242. }
  1243. }