Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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