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

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