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.

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