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.

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