您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

channel.go 41KB

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