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

channel.go 46KB

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