You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

channel.go 53KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "fmt"
  8. "maps"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "sync"
  13. "github.com/ergochat/irc-go/ircmsg"
  14. "github.com/ergochat/ergo/irc/caps"
  15. "github.com/ergochat/ergo/irc/datastore"
  16. "github.com/ergochat/ergo/irc/history"
  17. "github.com/ergochat/ergo/irc/modes"
  18. "github.com/ergochat/ergo/irc/utils"
  19. )
  20. type ChannelSettings struct {
  21. History HistoryStatus
  22. QueryCutoff HistoryCutoff
  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. forward string
  30. members MemberSet
  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. writebackLock sync.Mutex // tier 1.5
  46. joinPartMutex sync.Mutex // tier 3
  47. dirtyBits uint
  48. settings ChannelSettings
  49. uuid utils.UUID
  50. // these caches are paired to allow iteration over channel members without holding the lock
  51. membersCache []*Client
  52. memberDataCache []*memberData
  53. }
  54. // NewChannel creates a new channel from a `Server` and a `name`
  55. // string, which must be unique on the server.
  56. func NewChannel(s *Server, name, casefoldedName string, registered bool, regInfo RegisteredChannel) *Channel {
  57. config := s.Config()
  58. channel := &Channel{
  59. createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo
  60. members: make(MemberSet),
  61. name: name,
  62. nameCasefolded: casefoldedName,
  63. server: s,
  64. }
  65. channel.initializeLists()
  66. channel.history.Initialize(0, 0)
  67. if registered {
  68. channel.applyRegInfo(regInfo)
  69. } else {
  70. channel.resizeHistory(config)
  71. for _, mode := range config.Channels.defaultModes {
  72. channel.flags.SetMode(mode, true)
  73. }
  74. channel.uuid = utils.GenerateUUIDv4()
  75. }
  76. return channel
  77. }
  78. func (channel *Channel) initializeLists() {
  79. channel.lists = map[modes.Mode]*UserMaskSet{
  80. modes.BanMask: NewUserMaskSet(),
  81. modes.ExceptMask: NewUserMaskSet(),
  82. modes.InviteMask: NewUserMaskSet(),
  83. }
  84. channel.accountToUMode = make(map[string]modes.Mode)
  85. }
  86. func (channel *Channel) resizeHistory(config *Config) {
  87. status, _, _ := channel.historyStatus(config)
  88. if status == HistoryEphemeral {
  89. channel.history.Resize(config.History.ChannelLength, time.Duration(config.History.AutoresizeWindow))
  90. } else {
  91. channel.history.Resize(0, 0)
  92. }
  93. }
  94. // read in channel state that was persisted in the DB
  95. func (channel *Channel) applyRegInfo(chanReg RegisteredChannel) {
  96. defer channel.resizeHistory(channel.server.Config())
  97. channel.stateMutex.Lock()
  98. defer channel.stateMutex.Unlock()
  99. channel.uuid = chanReg.UUID
  100. channel.registeredFounder = chanReg.Founder
  101. channel.registeredTime = chanReg.RegisteredAt
  102. channel.topic = chanReg.Topic
  103. channel.topicSetBy = chanReg.TopicSetBy
  104. channel.topicSetTime = chanReg.TopicSetTime
  105. channel.name = chanReg.Name
  106. channel.createdTime = chanReg.RegisteredAt
  107. channel.key = chanReg.Key
  108. channel.userLimit = chanReg.UserLimit
  109. channel.settings = chanReg.Settings
  110. channel.forward = chanReg.Forward
  111. for _, mode := range chanReg.Modes {
  112. channel.flags.SetMode(mode, true)
  113. }
  114. for account, mode := range chanReg.AccountToUMode {
  115. channel.accountToUMode[account] = mode
  116. }
  117. channel.lists[modes.BanMask].SetMasks(chanReg.Bans)
  118. channel.lists[modes.InviteMask].SetMasks(chanReg.Invites)
  119. channel.lists[modes.ExceptMask].SetMasks(chanReg.Excepts)
  120. }
  121. // obtain a consistent snapshot of the channel state that can be persisted to the DB
  122. func (channel *Channel) ExportRegistration() (info RegisteredChannel) {
  123. channel.stateMutex.RLock()
  124. defer channel.stateMutex.RUnlock()
  125. info.Name = channel.name
  126. info.UUID = channel.uuid
  127. info.Founder = channel.registeredFounder
  128. info.RegisteredAt = channel.registeredTime
  129. info.Topic = channel.topic
  130. info.TopicSetBy = channel.topicSetBy
  131. info.TopicSetTime = channel.topicSetTime
  132. info.Key = channel.key
  133. info.Forward = channel.forward
  134. info.Modes = channel.flags.AllModes()
  135. info.UserLimit = channel.userLimit
  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 = maps.Clone(channel.accountToUMode)
  140. info.Settings = channel.settings
  141. return
  142. }
  143. func (channel *Channel) exportSummary() (info RegisteredChannel) {
  144. channel.stateMutex.RLock()
  145. defer channel.stateMutex.RUnlock()
  146. info.Name = channel.name
  147. info.Founder = channel.registeredFounder
  148. info.RegisteredAt = channel.registeredTime
  149. return
  150. }
  151. // begin: asynchronous database writeback implementation, modeled on irc/socket.go
  152. // MarkDirty marks part (or all) of a channel's data as needing to be written back
  153. // to the database, then starts a writer goroutine if necessary.
  154. // This is the equivalent of Socket.Write().
  155. func (channel *Channel) MarkDirty(dirtyBits uint) {
  156. channel.stateMutex.Lock()
  157. isRegistered := channel.registeredFounder != ""
  158. channel.dirtyBits = channel.dirtyBits | dirtyBits
  159. channel.stateMutex.Unlock()
  160. if !isRegistered {
  161. return
  162. }
  163. channel.wakeWriter()
  164. }
  165. // IsClean returns whether a channel can be safely removed from the server.
  166. // To avoid the obvious TOCTOU race condition, it must be called while holding
  167. // ChannelManager's lock (that way, no one can join and make the channel dirty again
  168. // between this method exiting and the actual deletion).
  169. func (channel *Channel) IsClean() bool {
  170. if !channel.writebackLock.TryLock() {
  171. // a database write (which may fail) is in progress, the channel cannot be cleaned up
  172. return false
  173. }
  174. defer channel.writebackLock.Unlock()
  175. channel.stateMutex.RLock()
  176. defer channel.stateMutex.RUnlock()
  177. if len(channel.members) != 0 {
  178. return false
  179. }
  180. // see #1507 and #704 among others; registered channels should never be removed
  181. return channel.registeredFounder == ""
  182. }
  183. func (channel *Channel) wakeWriter() {
  184. if channel.writebackLock.TryLock() {
  185. go channel.writeLoop()
  186. }
  187. }
  188. // equivalent of Socket.send()
  189. func (channel *Channel) writeLoop() {
  190. defer channel.server.HandlePanic()
  191. for {
  192. // TODO(#357) check the error value of this and implement timed backoff
  193. channel.performWrite(0)
  194. channel.writebackLock.Unlock()
  195. channel.stateMutex.RLock()
  196. isDirty := channel.dirtyBits != 0
  197. isEmpty := len(channel.members) == 0
  198. channel.stateMutex.RUnlock()
  199. if !isDirty {
  200. if isEmpty {
  201. channel.server.channels.Cleanup(channel)
  202. }
  203. return // nothing to do
  204. } // else: isDirty, so we need to write again
  205. if !channel.writebackLock.TryLock() {
  206. return
  207. }
  208. }
  209. }
  210. // Store writes part (or all) of the channel's data back to the database,
  211. // blocking until the write is complete. This is the equivalent of
  212. // Socket.BlockingWrite.
  213. func (channel *Channel) Store(dirtyBits uint) (err error) {
  214. defer func() {
  215. channel.stateMutex.Lock()
  216. isDirty := channel.dirtyBits != 0
  217. isEmpty := len(channel.members) == 0
  218. channel.stateMutex.Unlock()
  219. if isDirty {
  220. channel.wakeWriter()
  221. } else if isEmpty {
  222. channel.server.channels.Cleanup(channel)
  223. }
  224. }()
  225. channel.writebackLock.Lock()
  226. defer channel.writebackLock.Unlock()
  227. return channel.performWrite(dirtyBits)
  228. }
  229. // do an individual write; equivalent of Socket.send()
  230. func (channel *Channel) performWrite(additionalDirtyBits uint) (err error) {
  231. channel.stateMutex.Lock()
  232. dirtyBits := channel.dirtyBits | additionalDirtyBits
  233. channel.dirtyBits = 0
  234. isRegistered := channel.registeredFounder != ""
  235. channel.stateMutex.Unlock()
  236. if !isRegistered || dirtyBits == 0 {
  237. return
  238. }
  239. var success bool
  240. info := channel.ExportRegistration()
  241. if b, err := info.Serialize(); err == nil {
  242. if err := channel.server.dstore.Set(datastore.TableChannels, info.UUID, b, time.Time{}); err == nil {
  243. success = true
  244. } else {
  245. channel.server.logger.Error("internal", "couldn't persist channel", info.Name, err.Error())
  246. }
  247. } else {
  248. channel.server.logger.Error("internal", "couldn't serialize channel", info.Name, err.Error())
  249. }
  250. if !success {
  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. uuid := utils.GenerateUUIDv4()
  272. channel.stateMutex.Lock()
  273. defer channel.stateMutex.Unlock()
  274. if channel.registeredFounder != expectedFounder {
  275. return
  276. }
  277. channel.registeredFounder = ""
  278. var zeroTime time.Time
  279. channel.registeredTime = zeroTime
  280. channel.accountToUMode = make(map[string]modes.Mode)
  281. // reset the UUID so that any re-registration will persist under
  282. // a separate key:
  283. channel.uuid = uuid
  284. }
  285. // implements `CHANSERV CLEAR #chan ACCESS` (resets bans, invites, excepts, and amodes)
  286. func (channel *Channel) resetAccess() {
  287. defer channel.MarkDirty(IncludeLists)
  288. channel.stateMutex.Lock()
  289. defer channel.stateMutex.Unlock()
  290. channel.initializeLists()
  291. if channel.registeredFounder != "" {
  292. channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
  293. }
  294. }
  295. // IsRegistered returns whether the channel is registered.
  296. func (channel *Channel) IsRegistered() bool {
  297. channel.stateMutex.RLock()
  298. defer channel.stateMutex.RUnlock()
  299. return channel.registeredFounder != ""
  300. }
  301. type channelTransferStatus uint
  302. const (
  303. channelTransferComplete channelTransferStatus = iota
  304. channelTransferPending
  305. channelTransferCancelled
  306. channelTransferFailed
  307. )
  308. // Transfer transfers ownership of a registered channel to a different account
  309. func (channel *Channel) Transfer(client *Client, target string, hasPrivs bool) (status channelTransferStatus, err error) {
  310. status = channelTransferFailed
  311. defer func() {
  312. if status == channelTransferComplete && err == nil {
  313. channel.Store(IncludeAllAttrs)
  314. }
  315. }()
  316. cftarget, err := CasefoldName(target)
  317. if err != nil {
  318. err = errAccountDoesNotExist
  319. return
  320. }
  321. channel.stateMutex.Lock()
  322. defer channel.stateMutex.Unlock()
  323. if channel.registeredFounder == "" {
  324. err = errChannelNotOwnedByAccount
  325. return
  326. }
  327. if hasPrivs {
  328. channel.transferOwnership(cftarget)
  329. return channelTransferComplete, nil
  330. } else {
  331. if channel.registeredFounder == cftarget {
  332. // transferring back to yourself cancels a pending transfer
  333. channel.transferPendingTo = ""
  334. return channelTransferCancelled, nil
  335. } else {
  336. channel.transferPendingTo = cftarget
  337. return channelTransferPending, nil
  338. }
  339. }
  340. }
  341. func (channel *Channel) transferOwnership(newOwner string) {
  342. delete(channel.accountToUMode, channel.registeredFounder)
  343. channel.registeredFounder = newOwner
  344. channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
  345. channel.transferPendingTo = ""
  346. }
  347. // AcceptTransfer implements `CS TRANSFER #chan ACCEPT`
  348. func (channel *Channel) AcceptTransfer(client *Client) (err error) {
  349. defer func() {
  350. if err == nil {
  351. channel.Store(IncludeAllAttrs)
  352. }
  353. }()
  354. account := client.Account()
  355. if account == "" {
  356. return errAccountNotLoggedIn
  357. }
  358. channel.stateMutex.Lock()
  359. defer channel.stateMutex.Unlock()
  360. if account != channel.transferPendingTo {
  361. return errChannelTransferNotOffered
  362. }
  363. channel.transferOwnership(account)
  364. return nil
  365. }
  366. func (channel *Channel) regenerateMembersCache() {
  367. channel.stateMutex.RLock()
  368. membersCache := make([]*Client, len(channel.members))
  369. dataCache := make([]*memberData, len(channel.members))
  370. i := 0
  371. for client, info := range channel.members {
  372. membersCache[i] = client
  373. dataCache[i] = info
  374. i++
  375. }
  376. channel.stateMutex.RUnlock()
  377. channel.stateMutex.Lock()
  378. channel.membersCache = membersCache
  379. channel.memberDataCache = dataCache
  380. channel.stateMutex.Unlock()
  381. }
  382. // Names sends the list of users joined to the channel to the given client.
  383. func (channel *Channel) Names(client *Client, rb *ResponseBuffer) {
  384. channel.stateMutex.RLock()
  385. clientData, isJoined := channel.members[client]
  386. chname := channel.name
  387. membersCache, memberDataCache := channel.membersCache, channel.memberDataCache
  388. channel.stateMutex.RUnlock()
  389. symbol := "=" // https://modern.ircdocs.horse/#rplnamreply-353
  390. if channel.flags.HasMode(modes.Secret) {
  391. symbol = "@"
  392. }
  393. isOper := client.HasRoleCapabs("sajoin")
  394. respectAuditorium := channel.flags.HasMode(modes.Auditorium) && !isOper &&
  395. (!isJoined || clientData.modes.HighestChannelUserMode() == modes.Mode(0))
  396. isMultiPrefix := rb.session.capabilities.Has(caps.MultiPrefix)
  397. isUserhostInNames := rb.session.capabilities.Has(caps.UserhostInNames)
  398. maxNamLen := 480 - len(client.server.name) - len(client.Nick()) - len(chname)
  399. var tl utils.TokenLineBuilder
  400. tl.Initialize(maxNamLen, " ")
  401. if isJoined || !channel.flags.HasMode(modes.Secret) || isOper {
  402. for i, target := range membersCache {
  403. if !isJoined && target.HasMode(modes.Invisible) && !isOper {
  404. continue
  405. }
  406. var nick string
  407. if isUserhostInNames {
  408. nick = target.NickMaskString()
  409. } else {
  410. nick = target.Nick()
  411. }
  412. memberData := memberDataCache[i]
  413. if respectAuditorium && memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  414. continue
  415. }
  416. tl.AddParts(memberData.modes.Prefixes(isMultiPrefix), nick)
  417. }
  418. }
  419. for _, line := range tl.Lines() {
  420. rb.Add(nil, client.server.name, RPL_NAMREPLY, client.nick, symbol, chname, line)
  421. }
  422. rb.Add(nil, client.server.name, RPL_ENDOFNAMES, client.nick, chname, client.t("End of NAMES list"))
  423. }
  424. // does `clientMode` give you privileges to grant/remove `targetMode` to/from people,
  425. // or to kick them?
  426. func channelUserModeHasPrivsOver(clientMode modes.Mode, targetMode modes.Mode) bool {
  427. switch clientMode {
  428. case modes.ChannelFounder:
  429. return true
  430. case modes.ChannelAdmin, modes.ChannelOperator:
  431. // admins cannot kick other admins, operators *can* kick other operators
  432. return targetMode != modes.ChannelFounder && targetMode != modes.ChannelAdmin
  433. case modes.Halfop:
  434. // halfops cannot kick other halfops
  435. return targetMode == modes.Voice || targetMode == modes.Mode(0)
  436. default:
  437. // voice and unprivileged cannot kick anyone
  438. return false
  439. }
  440. }
  441. // ClientIsAtLeast returns whether the client has at least the given channel privilege.
  442. func (channel *Channel) ClientIsAtLeast(client *Client, permission modes.Mode) bool {
  443. channel.stateMutex.RLock()
  444. memberData, present := channel.members[client]
  445. founder := channel.registeredFounder
  446. channel.stateMutex.RUnlock()
  447. if founder != "" && founder == client.Account() {
  448. return true
  449. }
  450. if !present {
  451. return false
  452. }
  453. for _, mode := range modes.ChannelUserModes {
  454. if memberData.modes.HasMode(mode) {
  455. return true
  456. }
  457. if mode == permission {
  458. break
  459. }
  460. }
  461. return false
  462. }
  463. func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) string {
  464. channel.stateMutex.RLock()
  465. defer channel.stateMutex.RUnlock()
  466. memberData, present := channel.members[client]
  467. if !present {
  468. return ""
  469. } else {
  470. return memberData.modes.Prefixes(isMultiPrefix)
  471. }
  472. }
  473. func (channel *Channel) ClientStatus(client *Client) (present bool, joinTimeSecs int64, cModes modes.Modes) {
  474. channel.stateMutex.RLock()
  475. defer channel.stateMutex.RUnlock()
  476. memberData, present := channel.members[client]
  477. return present, time.Unix(0, memberData.joinTime).Unix(), memberData.modes.AllModes()
  478. }
  479. // helper for persisting channel-user modes for always-on clients;
  480. // return the channel name and all channel-user modes for a client
  481. func (channel *Channel) alwaysOnStatus(client *Client) (ok bool, chname string, status alwaysOnChannelStatus) {
  482. channel.stateMutex.RLock()
  483. defer channel.stateMutex.RUnlock()
  484. chname = channel.name
  485. data, ok := channel.members[client]
  486. if !ok {
  487. return
  488. }
  489. status.Modes = data.modes.String()
  490. status.JoinTime = data.joinTime
  491. return
  492. }
  493. // overwrite any existing channel-user modes with the stored ones
  494. func (channel *Channel) setMemberStatus(client *Client, status alwaysOnChannelStatus) {
  495. newModes := modes.NewModeSet()
  496. for _, mode := range status.Modes {
  497. newModes.SetMode(modes.Mode(mode), true)
  498. }
  499. channel.stateMutex.Lock()
  500. defer channel.stateMutex.Unlock()
  501. if mData, ok := channel.members[client]; ok {
  502. mData.modes.Clear()
  503. for _, mode := range status.Modes {
  504. mData.modes.SetMode(modes.Mode(mode), true)
  505. }
  506. mData.joinTime = status.JoinTime
  507. }
  508. }
  509. func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
  510. channel.stateMutex.RLock()
  511. founder := channel.registeredFounder
  512. clientData, clientOK := channel.members[client]
  513. targetData, targetOK := channel.members[target]
  514. channel.stateMutex.RUnlock()
  515. if founder != "" {
  516. if founder == client.Account() {
  517. return true // #950: founder can take any privileged action without actually having +q
  518. } else if founder == target.Account() {
  519. return false // conversely, only the founder can kick the founder
  520. }
  521. }
  522. return clientOK && targetOK &&
  523. channelUserModeHasPrivsOver(
  524. clientData.modes.HighestChannelUserMode(),
  525. targetData.modes.HighestChannelUserMode(),
  526. )
  527. }
  528. func (channel *Channel) hasClient(client *Client) bool {
  529. channel.stateMutex.RLock()
  530. _, present := channel.members[client]
  531. channel.stateMutex.RUnlock()
  532. return present
  533. }
  534. // <mode> <mode params>
  535. func (channel *Channel) modeStrings(client *Client) (result []string) {
  536. hasPrivs := client.HasRoleCapabs("sajoin")
  537. channel.stateMutex.RLock()
  538. defer channel.stateMutex.RUnlock()
  539. isMember := hasPrivs || channel.members.Has(client)
  540. showKey := isMember && (channel.key != "")
  541. showUserLimit := channel.userLimit > 0
  542. showForward := channel.forward != ""
  543. var mods strings.Builder
  544. mods.WriteRune('+')
  545. // flags with args
  546. if showKey {
  547. mods.WriteRune(rune(modes.Key))
  548. }
  549. if showUserLimit {
  550. mods.WriteRune(rune(modes.UserLimit))
  551. }
  552. if showForward {
  553. mods.WriteRune(rune(modes.Forward))
  554. }
  555. for _, m := range channel.flags.AllModes() {
  556. mods.WriteRune(rune(m))
  557. }
  558. result = []string{mods.String()}
  559. // args for flags with args: The order must match above to keep
  560. // positional arguments in place.
  561. if showKey {
  562. result = append(result, channel.key)
  563. }
  564. if showUserLimit {
  565. result = append(result, strconv.Itoa(channel.userLimit))
  566. }
  567. if showForward {
  568. result = append(result, channel.forward)
  569. }
  570. return
  571. }
  572. func (channel *Channel) IsEmpty() bool {
  573. channel.stateMutex.RLock()
  574. defer channel.stateMutex.RUnlock()
  575. return len(channel.members) == 0
  576. }
  577. // figure out where history is being stored: persistent, ephemeral, or neither
  578. // target is only needed if we're doing persistent history
  579. func (channel *Channel) historyStatus(config *Config) (status HistoryStatus, target string, restrictions HistoryCutoff) {
  580. if !config.History.Enabled {
  581. return HistoryDisabled, "", HistoryCutoffNone
  582. }
  583. channel.stateMutex.RLock()
  584. target = channel.nameCasefolded
  585. settings := channel.settings
  586. registered := channel.registeredFounder != ""
  587. channel.stateMutex.RUnlock()
  588. restrictions = settings.QueryCutoff
  589. if restrictions == HistoryCutoffDefault {
  590. restrictions = config.History.Restrictions.queryCutoff
  591. }
  592. return channelHistoryStatus(config, registered, settings.History), target, restrictions
  593. }
  594. func (channel *Channel) joinTimeCutoff(client *Client) (present bool, cutoff time.Time) {
  595. account := client.Account()
  596. channel.stateMutex.RLock()
  597. defer channel.stateMutex.RUnlock()
  598. if data, ok := channel.members[client]; ok {
  599. present = true
  600. // report a cutoff of zero, i.e., no restriction, if the user is privileged
  601. if !((account != "" && account == channel.registeredFounder) || data.modes.HasMode(modes.ChannelFounder) || data.modes.HasMode(modes.ChannelAdmin) || data.modes.HasMode(modes.ChannelOperator)) {
  602. cutoff = time.Unix(0, data.joinTime)
  603. }
  604. }
  605. return
  606. }
  607. func channelHistoryStatus(config *Config, registered bool, storedStatus HistoryStatus) (result HistoryStatus) {
  608. if !config.History.Enabled {
  609. return HistoryDisabled
  610. }
  611. // ephemeral history: either the channel owner explicitly set the ephemeral preference,
  612. // or persistent history is disabled for unregistered channels
  613. if registered {
  614. return historyEnabled(config.History.Persistent.RegisteredChannels, storedStatus)
  615. } else {
  616. if config.History.Persistent.UnregisteredChannels {
  617. return HistoryPersistent
  618. } else {
  619. return HistoryEphemeral
  620. }
  621. }
  622. }
  623. func (channel *Channel) AddHistoryItem(item history.Item, account string) (err error) {
  624. if !itemIsStorable(&item, channel.server.Config()) {
  625. return
  626. }
  627. status, target, _ := channel.historyStatus(channel.server.Config())
  628. if status == HistoryPersistent {
  629. err = channel.server.historyDB.AddChannelItem(target, item, account)
  630. } else if status == HistoryEphemeral {
  631. channel.history.Add(item)
  632. }
  633. return
  634. }
  635. // Join joins the given client to this channel (if they can be joined).
  636. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) (joinErr error, forward string) {
  637. details := client.Details()
  638. isBot := client.HasMode(modes.Bot)
  639. channel.stateMutex.RLock()
  640. chname := channel.name
  641. chcfname := channel.nameCasefolded
  642. founder := channel.registeredFounder
  643. createdAt := channel.createdTime
  644. chkey := channel.key
  645. limit := channel.userLimit
  646. chcount := len(channel.members)
  647. _, alreadyJoined := channel.members[client]
  648. persistentMode := channel.accountToUMode[details.account]
  649. forward = channel.forward
  650. channel.stateMutex.RUnlock()
  651. if alreadyJoined {
  652. // no message needs to be sent
  653. return nil, ""
  654. }
  655. // 0. SAJOIN always succeeds
  656. // 1. the founder can always join (even if they disabled auto +q on join)
  657. // 2. anyone who automatically receives halfop or higher can always join
  658. // 3. people invited with INVITE can join
  659. hasPrivs := isSajoin || (founder != "" && founder == details.account) ||
  660. (persistentMode != 0 && persistentMode != modes.Voice) ||
  661. client.CheckInvited(chcfname, createdAt)
  662. if !hasPrivs {
  663. if limit != 0 && chcount >= limit {
  664. return errLimitExceeded, forward
  665. }
  666. if chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  667. return errWrongChannelKey, forward
  668. }
  669. // #1901: +h and up exempt from all restrictions, but +v additionally exempts from +i:
  670. if channel.flags.HasMode(modes.InviteOnly) && persistentMode == 0 &&
  671. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  672. return errInviteOnly, forward
  673. }
  674. if channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  675. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) &&
  676. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  677. // do not forward people who are banned:
  678. return errBanned, ""
  679. }
  680. if details.account == "" &&
  681. (channel.flags.HasMode(modes.RegisteredOnly) || channel.server.Defcon() <= 2) &&
  682. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  683. return errRegisteredOnly, forward
  684. }
  685. }
  686. if joinErr := client.addChannel(channel, rb == nil); joinErr != nil {
  687. return joinErr, ""
  688. }
  689. client.server.logger.Debug("channels", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  690. givenMode := func() (givenMode modes.Mode) {
  691. channel.joinPartMutex.Lock()
  692. defer channel.joinPartMutex.Unlock()
  693. func() {
  694. channel.stateMutex.Lock()
  695. defer channel.stateMutex.Unlock()
  696. channel.members.Add(client)
  697. firstJoin := len(channel.members) == 1
  698. newChannel := firstJoin && channel.registeredFounder == ""
  699. if newChannel {
  700. givenMode = modes.ChannelOperator
  701. } else {
  702. givenMode = persistentMode
  703. }
  704. if givenMode != 0 {
  705. channel.members[client].modes.SetMode(givenMode, true)
  706. }
  707. }()
  708. channel.regenerateMembersCache()
  709. return
  710. }()
  711. var message utils.SplitMessage
  712. respectAuditorium := givenMode == modes.Mode(0) && channel.flags.HasMode(modes.Auditorium)
  713. message = utils.MakeMessage("")
  714. // no history item for fake persistent joins
  715. if rb != nil && !respectAuditorium {
  716. histItem := history.Item{
  717. Type: history.Join,
  718. Nick: details.nickMask,
  719. AccountName: details.accountName,
  720. Message: message,
  721. IsBot: isBot,
  722. }
  723. histItem.Params[0] = details.realname
  724. channel.AddHistoryItem(histItem, details.account)
  725. }
  726. if rb == nil {
  727. return nil, ""
  728. }
  729. var modestr string
  730. if givenMode != 0 {
  731. modestr = fmt.Sprintf("+%v", givenMode)
  732. }
  733. // cache the most common case (JOIN without extended-join)
  734. var cache MessageCache
  735. cache.Initialize(channel.server, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
  736. isAway, awayMessage := client.Away()
  737. for _, member := range channel.Members() {
  738. if respectAuditorium {
  739. channel.stateMutex.RLock()
  740. memberData, ok := channel.members[member]
  741. channel.stateMutex.RUnlock()
  742. if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  743. continue
  744. }
  745. }
  746. for _, session := range member.Sessions() {
  747. if session == rb.session {
  748. continue
  749. } else if client == session.client {
  750. channel.playJoinForSession(session)
  751. continue
  752. }
  753. if session.capabilities.Has(caps.ExtendedJoin) {
  754. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
  755. } else {
  756. cache.Send(session)
  757. }
  758. if givenMode != 0 {
  759. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  760. }
  761. if isAway && session.capabilities.Has(caps.AwayNotify) {
  762. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.accountName, isBot, nil, "AWAY", awayMessage)
  763. }
  764. }
  765. }
  766. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  767. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
  768. } else {
  769. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
  770. }
  771. if rb.session.capabilities.Has(caps.ReadMarker) {
  772. rb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
  773. }
  774. if rb.session.client == client {
  775. // don't send topic and names for a SAJOIN of a different client
  776. channel.SendTopic(client, rb, false)
  777. if !rb.session.capabilities.Has(caps.NoImplicitNames) {
  778. channel.Names(client, rb)
  779. }
  780. } else {
  781. // ensure that SAJOIN sends a MODE line to the originating client, if applicable
  782. if givenMode != 0 {
  783. rb.Add(nil, client.server.name, "MODE", chname, modestr, details.nick)
  784. }
  785. }
  786. // TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
  787. rb.Flush(true)
  788. channel.autoReplayHistory(client, rb, message.Msgid)
  789. return nil, ""
  790. }
  791. func (channel *Channel) autoReplayHistory(client *Client, rb *ResponseBuffer, skipMsgid string) {
  792. // autoreplay any messages as necessary
  793. var items []history.Item
  794. hasAutoreplayTimestamps := false
  795. var start, end time.Time
  796. if rb.session.zncPlaybackTimes.ValidFor(channel.NameCasefolded()) {
  797. hasAutoreplayTimestamps = true
  798. start, end = rb.session.zncPlaybackTimes.start, rb.session.zncPlaybackTimes.end
  799. } else if !rb.session.autoreplayMissedSince.IsZero() {
  800. // we already checked for history caps in `playReattachMessages`
  801. hasAutoreplayTimestamps = true
  802. start = time.Now().UTC()
  803. end = rb.session.autoreplayMissedSince
  804. }
  805. if hasAutoreplayTimestamps {
  806. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  807. if seq != nil {
  808. zncMax := channel.server.Config().History.ZNCMax
  809. items, _ = seq.Between(history.Selector{Time: start}, history.Selector{Time: end}, zncMax)
  810. }
  811. } else if !rb.session.HasHistoryCaps() {
  812. var replayLimit int
  813. customReplayLimit := client.AccountSettings().AutoreplayLines
  814. if customReplayLimit != nil {
  815. replayLimit = *customReplayLimit
  816. maxLimit := channel.server.Config().History.ChathistoryMax
  817. if maxLimit < replayLimit {
  818. replayLimit = maxLimit
  819. }
  820. } else {
  821. replayLimit = channel.server.Config().History.AutoreplayOnJoin
  822. }
  823. if 0 < replayLimit {
  824. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  825. if seq != nil {
  826. items, _ = seq.Between(history.Selector{}, history.Selector{}, replayLimit)
  827. }
  828. }
  829. }
  830. // remove the client's own JOIN line from the replay
  831. numItems := len(items)
  832. for i := len(items) - 1; 0 <= i; i-- {
  833. if items[i].Message.Msgid == skipMsgid {
  834. // zero'ed items will not be replayed because their `Type` field is not recognized
  835. items[i] = history.Item{}
  836. numItems--
  837. break
  838. }
  839. }
  840. if 0 < numItems {
  841. channel.replayHistoryItems(rb, items, false)
  842. rb.Flush(true)
  843. }
  844. }
  845. // plays channel join messages (the JOIN line, topic, and names) to a session.
  846. // this is used when attaching a new session to an existing client that already has
  847. // channels, and also when one session of a client initiates a JOIN and the other
  848. // sessions need to receive the state change
  849. func (channel *Channel) playJoinForSession(session *Session) {
  850. client := session.client
  851. sessionRb := NewResponseBuffer(session)
  852. details := client.Details()
  853. chname := channel.Name()
  854. if session.capabilities.Has(caps.ExtendedJoin) {
  855. sessionRb.Add(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  856. } else {
  857. sessionRb.Add(nil, details.nickMask, "JOIN", chname)
  858. }
  859. if session.capabilities.Has(caps.ReadMarker) {
  860. chcfname := channel.NameCasefolded()
  861. sessionRb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
  862. }
  863. channel.SendTopic(client, sessionRb, false)
  864. if !session.capabilities.Has(caps.NoImplicitNames) {
  865. channel.Names(client, sessionRb)
  866. }
  867. sessionRb.Send(false)
  868. }
  869. // Part parts the given client from this channel, with the given message.
  870. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  871. channel.stateMutex.RLock()
  872. chname := channel.name
  873. clientData, ok := channel.members[client]
  874. channel.stateMutex.RUnlock()
  875. if !ok {
  876. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  877. return
  878. }
  879. channel.Quit(client)
  880. splitMessage := utils.MakeMessage(message)
  881. details := client.Details()
  882. isBot := client.HasMode(modes.Bot)
  883. params := make([]string, 1, 2)
  884. params[0] = chname
  885. if message != "" {
  886. params = append(params, message)
  887. }
  888. respectAuditorium := channel.flags.HasMode(modes.Auditorium) &&
  889. clientData.modes.HighestChannelUserMode() == modes.Mode(0)
  890. var cache MessageCache
  891. cache.Initialize(channel.server, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  892. for _, member := range channel.Members() {
  893. if respectAuditorium {
  894. channel.stateMutex.RLock()
  895. memberData, ok := channel.members[member]
  896. channel.stateMutex.RUnlock()
  897. if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  898. continue
  899. }
  900. }
  901. for _, session := range member.Sessions() {
  902. cache.Send(session)
  903. }
  904. }
  905. rb.AddFromClient(splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  906. for _, session := range client.Sessions() {
  907. if session != rb.session {
  908. session.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  909. }
  910. }
  911. if !respectAuditorium {
  912. channel.AddHistoryItem(history.Item{
  913. Type: history.Part,
  914. Nick: details.nickMask,
  915. AccountName: details.accountName,
  916. Message: splitMessage,
  917. IsBot: isBot,
  918. }, details.account)
  919. }
  920. client.server.logger.Debug("channels", fmt.Sprintf("%s left channel %s", details.nick, chname))
  921. }
  922. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item, chathistoryCommand bool) {
  923. // send an empty batch if necessary, as per the CHATHISTORY spec
  924. chname := channel.Name()
  925. client := rb.target
  926. eventPlayback := rb.session.capabilities.Has(caps.EventPlayback)
  927. extendedJoin := rb.session.capabilities.Has(caps.ExtendedJoin)
  928. var playJoinsAsPrivmsg bool
  929. if !eventPlayback {
  930. if chathistoryCommand {
  931. playJoinsAsPrivmsg = true
  932. } else {
  933. switch client.AccountSettings().ReplayJoins {
  934. case ReplayJoinsCommandsOnly:
  935. playJoinsAsPrivmsg = false
  936. case ReplayJoinsAlways:
  937. playJoinsAsPrivmsg = true
  938. }
  939. }
  940. }
  941. batchID := rb.StartNestedBatch("chathistory", chname)
  942. defer rb.EndNestedBatch(batchID)
  943. for _, item := range items {
  944. nick := NUHToNick(item.Nick)
  945. switch item.Type {
  946. case history.Privmsg:
  947. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "PRIVMSG", chname, item.Message)
  948. case history.Notice:
  949. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "NOTICE", chname, item.Message)
  950. case history.Tagmsg:
  951. if eventPlayback {
  952. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "TAGMSG", chname, item.Message)
  953. } else if chathistoryCommand {
  954. // #1676, we have to send something here or else it breaks pagination
  955. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, fmt.Sprintf(client.t("%s sent a TAGMSG"), nick))
  956. }
  957. case history.Join:
  958. if eventPlayback {
  959. if extendedJoin {
  960. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "JOIN", chname, item.AccountName, item.Params[0])
  961. } else {
  962. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "JOIN", chname)
  963. }
  964. } else {
  965. if !playJoinsAsPrivmsg {
  966. continue // #474
  967. }
  968. var message string
  969. if item.AccountName == "*" {
  970. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  971. } else {
  972. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  973. }
  974. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  975. }
  976. case history.Part:
  977. if eventPlayback {
  978. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "PART", chname, item.Message.Message)
  979. } else {
  980. if !playJoinsAsPrivmsg {
  981. continue // #474
  982. }
  983. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  984. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  985. }
  986. case history.Kick:
  987. if eventPlayback {
  988. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "KICK", chname, item.Params[0], item.Message.Message)
  989. } else {
  990. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Params[0], item.Message.Message)
  991. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  992. }
  993. case history.Quit:
  994. if eventPlayback {
  995. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "QUIT", item.Message.Message)
  996. } else {
  997. if !playJoinsAsPrivmsg {
  998. continue // #474
  999. }
  1000. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  1001. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1002. }
  1003. case history.Nick:
  1004. if eventPlayback {
  1005. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "NICK", item.Params[0])
  1006. } else {
  1007. message := fmt.Sprintf(client.t("%[1]s changed nick to %[2]s"), nick, item.Params[0])
  1008. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1009. }
  1010. case history.Topic:
  1011. if eventPlayback {
  1012. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "TOPIC", chname, item.Message.Message)
  1013. } else {
  1014. message := fmt.Sprintf(client.t("%[1]s set the channel topic to: %[2]s"), nick, item.Message.Message)
  1015. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1016. }
  1017. case history.Mode:
  1018. params := make([]string, len(item.Message.Split)+1)
  1019. params[0] = chname
  1020. for i, pair := range item.Message.Split {
  1021. params[i+1] = pair.Message
  1022. }
  1023. if eventPlayback {
  1024. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "MODE", params...)
  1025. } else {
  1026. message := fmt.Sprintf(client.t("%[1]s set channel modes: %[2]s"), nick, strings.Join(params[1:], " "))
  1027. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1028. }
  1029. }
  1030. }
  1031. }
  1032. // SendTopic sends the channel topic to the given client.
  1033. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  1034. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  1035. channel.stateMutex.RLock()
  1036. name := channel.name
  1037. topic := channel.topic
  1038. topicSetBy := channel.topicSetBy
  1039. topicSetTime := channel.topicSetTime
  1040. _, hasClient := channel.members[client]
  1041. channel.stateMutex.RUnlock()
  1042. if !hasClient {
  1043. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.name, client.t("You're not on that channel"))
  1044. return
  1045. }
  1046. if topic == "" {
  1047. if sendNoTopic {
  1048. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  1049. }
  1050. return
  1051. }
  1052. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  1053. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  1054. }
  1055. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  1056. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  1057. if !channel.hasClient(client) {
  1058. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  1059. return
  1060. }
  1061. if channel.flags.HasMode(modes.OpOnlyTopic) && !(channel.ClientIsAtLeast(client, modes.Halfop) || client.HasRoleCapabs("samode")) {
  1062. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  1063. return
  1064. }
  1065. topic = ircmsg.TruncateUTF8Safe(topic, client.server.Config().Limits.TopicLen)
  1066. channel.stateMutex.Lock()
  1067. chname := channel.name
  1068. channel.topic = topic
  1069. channel.topicSetBy = client.nickMaskString
  1070. channel.topicSetTime = time.Now().UTC()
  1071. channel.stateMutex.Unlock()
  1072. details := client.Details()
  1073. isBot := client.HasMode(modes.Bot)
  1074. message := utils.MakeMessage(topic)
  1075. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "TOPIC", chname, topic)
  1076. for _, member := range channel.Members() {
  1077. for _, session := range member.Sessions() {
  1078. if session != rb.session {
  1079. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "TOPIC", chname, topic)
  1080. }
  1081. }
  1082. }
  1083. channel.AddHistoryItem(history.Item{
  1084. Type: history.Topic,
  1085. Nick: details.nickMask,
  1086. AccountName: details.accountName,
  1087. Message: message,
  1088. IsBot: isBot,
  1089. }, details.account)
  1090. channel.MarkDirty(IncludeTopic)
  1091. }
  1092. // CanSpeak returns true if the client can speak on this channel, otherwise it returns false along with the channel mode preventing the client from speaking.
  1093. func (channel *Channel) CanSpeak(client *Client) (bool, modes.Mode) {
  1094. channel.stateMutex.RLock()
  1095. memberData, hasClient := channel.members[client]
  1096. channel.stateMutex.RUnlock()
  1097. highestMode := func() modes.Mode {
  1098. if !hasClient {
  1099. return modes.Mode(0)
  1100. }
  1101. return memberData.modes.HighestChannelUserMode()
  1102. }
  1103. if !hasClient && channel.flags.HasMode(modes.NoOutside) {
  1104. // TODO: enforce regular +b bans on -n channels?
  1105. return false, modes.NoOutside
  1106. }
  1107. if channel.isMuted(client) && highestMode() == modes.Mode(0) {
  1108. return false, modes.BanMask
  1109. }
  1110. if channel.flags.HasMode(modes.Moderated) && highestMode() == modes.Mode(0) {
  1111. return false, modes.Moderated
  1112. }
  1113. if channel.flags.HasMode(modes.RegisteredOnlySpeak) && client.Account() == "" &&
  1114. highestMode() == modes.Mode(0) {
  1115. return false, modes.RegisteredOnlySpeak
  1116. }
  1117. return true, modes.Mode('?')
  1118. }
  1119. func (channel *Channel) isMuted(client *Client) bool {
  1120. muteRe := channel.lists[modes.BanMask].MuteRegexp()
  1121. if muteRe == nil {
  1122. return false
  1123. }
  1124. nuh := client.NickMaskCasefolded()
  1125. return muteRe.MatchString(nuh) && !channel.lists[modes.ExceptMask].MatchMute(nuh)
  1126. }
  1127. func (channel *Channel) relayNickMuted(relayNick string) bool {
  1128. relayNUH := fmt.Sprintf("%s!*@*", relayNick)
  1129. return channel.lists[modes.BanMask].MatchMute(relayNUH) &&
  1130. !channel.lists[modes.ExceptMask].MatchMute(relayNUH)
  1131. }
  1132. func msgCommandToHistType(command string) (history.ItemType, error) {
  1133. switch command {
  1134. case "PRIVMSG":
  1135. return history.Privmsg, nil
  1136. case "NOTICE":
  1137. return history.Notice, nil
  1138. case "TAGMSG":
  1139. return history.Tagmsg, nil
  1140. default:
  1141. return history.ItemType(0), errInvalidParams
  1142. }
  1143. }
  1144. func (channel *Channel) SendSplitMessage(command string, minPrefixMode modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  1145. histType, err := msgCommandToHistType(command)
  1146. if err != nil {
  1147. return
  1148. }
  1149. if canSpeak, mode := channel.CanSpeak(client); !canSpeak {
  1150. if histType != history.Notice {
  1151. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), mode))
  1152. }
  1153. return
  1154. }
  1155. isCTCP := message.IsRestrictedCTCPMessage()
  1156. if isCTCP && channel.flags.HasMode(modes.NoCTCP) {
  1157. if histType != history.Notice {
  1158. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), "C"))
  1159. }
  1160. return
  1161. }
  1162. details := client.Details()
  1163. isBot := client.HasMode(modes.Bot)
  1164. chname := channel.Name()
  1165. if !client.server.Config().Server.Compatibility.allowTruncation {
  1166. if !validateSplitMessageLen(histType, details.nickMask, chname, message) {
  1167. rb.Add(nil, client.server.name, ERR_INPUTTOOLONG, details.nick, client.t("Line too long to be relayed without truncation"))
  1168. return
  1169. }
  1170. }
  1171. // STATUSMSG targets are prefixed with the supplied min-prefix, e.g., @#channel
  1172. if minPrefixMode != modes.Mode(0) {
  1173. chname = fmt.Sprintf("%s%s", modes.ChannelModePrefixes[minPrefixMode], chname)
  1174. }
  1175. if channel.flags.HasMode(modes.OpModerated) {
  1176. channel.stateMutex.RLock()
  1177. cuData, ok := channel.members[client]
  1178. channel.stateMutex.RUnlock()
  1179. if !ok || cuData.modes.HighestChannelUserMode() == modes.Mode(0) {
  1180. // max(statusmsg_minmode, halfop)
  1181. if minPrefixMode == modes.Mode(0) || minPrefixMode == modes.Voice {
  1182. minPrefixMode = modes.Halfop
  1183. }
  1184. }
  1185. }
  1186. // send echo-message
  1187. rb.addEchoMessage(clientOnlyTags, details.nickMask, details.accountName, command, chname, message)
  1188. var cache MessageCache
  1189. cache.InitializeSplitMessage(channel.server, details.nickMask, details.accountName, isBot, clientOnlyTags, command, chname, message)
  1190. for _, member := range channel.Members() {
  1191. if minPrefixMode != modes.Mode(0) && !channel.ClientIsAtLeast(member, minPrefixMode) {
  1192. // STATUSMSG or OpModerated
  1193. continue
  1194. }
  1195. for _, session := range member.Sessions() {
  1196. if session == rb.session {
  1197. continue // we already sent echo-message, if applicable
  1198. }
  1199. if isCTCP && session.isTor {
  1200. continue // #753
  1201. }
  1202. cache.Send(session)
  1203. }
  1204. }
  1205. // #959: don't save STATUSMSG (or OpModerated)
  1206. if minPrefixMode == modes.Mode(0) {
  1207. channel.AddHistoryItem(history.Item{
  1208. Type: histType,
  1209. Message: message,
  1210. Nick: details.nickMask,
  1211. AccountName: details.accountName,
  1212. Tags: clientOnlyTags,
  1213. IsBot: isBot,
  1214. }, details.account)
  1215. }
  1216. }
  1217. func (channel *Channel) applyModeToMember(client *Client, change modes.ModeChange, rb *ResponseBuffer) (applied bool, result modes.ModeChange) {
  1218. target := channel.server.clients.Get(change.Arg)
  1219. if target == nil {
  1220. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(change.Arg), client.t("No such nick"))
  1221. return
  1222. }
  1223. change.Arg = target.Nick()
  1224. channel.stateMutex.Lock()
  1225. memberData, exists := channel.members[target]
  1226. if exists {
  1227. if memberData.modes.SetMode(change.Mode, change.Op == modes.Add) {
  1228. applied = true
  1229. result = change
  1230. }
  1231. }
  1232. channel.stateMutex.Unlock()
  1233. if !exists {
  1234. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1235. }
  1236. if applied {
  1237. target.markDirty(IncludeChannels)
  1238. }
  1239. return
  1240. }
  1241. // ShowMaskList shows the given list to the client.
  1242. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  1243. // choose appropriate modes
  1244. var rpllist, rplendoflist string
  1245. if mode == modes.BanMask {
  1246. rpllist = RPL_BANLIST
  1247. rplendoflist = RPL_ENDOFBANLIST
  1248. } else if mode == modes.ExceptMask {
  1249. rpllist = RPL_EXCEPTLIST
  1250. rplendoflist = RPL_ENDOFEXCEPTLIST
  1251. } else if mode == modes.InviteMask {
  1252. rpllist = RPL_INVITELIST
  1253. rplendoflist = RPL_ENDOFINVITELIST
  1254. }
  1255. nick := client.Nick()
  1256. chname := channel.Name()
  1257. for mask, info := range channel.lists[mode].Masks() {
  1258. rb.Add(nil, client.server.name, rpllist, nick, chname, mask, info.CreatorNickmask, strconv.FormatInt(info.TimeCreated.Unix(), 10))
  1259. }
  1260. rb.Add(nil, client.server.name, rplendoflist, nick, chname, client.t("End of list"))
  1261. }
  1262. // Quit removes the given client from the channel
  1263. func (channel *Channel) Quit(client *Client) {
  1264. channelEmpty := func() bool {
  1265. channel.joinPartMutex.Lock()
  1266. defer channel.joinPartMutex.Unlock()
  1267. channel.stateMutex.Lock()
  1268. channel.members.Remove(client)
  1269. channelEmpty := len(channel.members) == 0
  1270. channel.stateMutex.Unlock()
  1271. channel.regenerateMembersCache()
  1272. return channelEmpty
  1273. }()
  1274. if channelEmpty {
  1275. client.server.channels.Cleanup(channel)
  1276. }
  1277. client.removeChannel(channel)
  1278. }
  1279. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer, hasPrivs bool) {
  1280. if !hasPrivs {
  1281. if !channel.ClientHasPrivsOver(client, target) {
  1282. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  1283. return
  1284. }
  1285. }
  1286. if !channel.hasClient(target) {
  1287. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1288. return
  1289. }
  1290. comment = ircmsg.TruncateUTF8Safe(comment, channel.server.Config().Limits.KickLen)
  1291. message := utils.MakeMessage(comment)
  1292. details := client.Details()
  1293. isBot := client.HasMode(modes.Bot)
  1294. targetNick := target.Nick()
  1295. chname := channel.Name()
  1296. for _, member := range channel.Members() {
  1297. for _, session := range member.Sessions() {
  1298. if session != rb.session {
  1299. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "KICK", chname, targetNick, comment)
  1300. }
  1301. }
  1302. }
  1303. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "KICK", chname, targetNick, comment)
  1304. histItem := history.Item{
  1305. Type: history.Kick,
  1306. Nick: details.nickMask,
  1307. AccountName: details.accountName,
  1308. Message: message,
  1309. IsBot: isBot,
  1310. }
  1311. histItem.Params[0] = targetNick
  1312. channel.AddHistoryItem(histItem, details.account)
  1313. channel.Quit(target)
  1314. }
  1315. // handle a purge: kick everyone off the channel, clean up all the pointers between
  1316. // *Channel and *Client
  1317. func (channel *Channel) Purge(source string) {
  1318. if source == "" {
  1319. source = channel.server.name
  1320. }
  1321. channel.stateMutex.Lock()
  1322. chname := channel.name
  1323. members := channel.membersCache
  1324. channel.membersCache = nil
  1325. channel.memberDataCache = nil
  1326. channel.members = make(MemberSet)
  1327. // TODO try to prevent Purge racing against (pending) Join?
  1328. channel.stateMutex.Unlock()
  1329. now := time.Now().UTC()
  1330. for _, member := range members {
  1331. tnick := member.Nick()
  1332. msgid := utils.GenerateSecretToken()
  1333. for _, session := range member.Sessions() {
  1334. session.sendFromClientInternal(false, now, msgid, source, "*", false, nil, "KICK", chname, tnick, member.t("This channel has been purged by the server administrators and cannot be used"))
  1335. }
  1336. member.removeChannel(channel)
  1337. }
  1338. }
  1339. // Invite invites the given client to the channel, if the inviter can do so.
  1340. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1341. channel.stateMutex.RLock()
  1342. chname := channel.name
  1343. chcfname := channel.nameCasefolded
  1344. createdAt := channel.createdTime
  1345. _, inviterPresent := channel.members[inviter]
  1346. _, inviteePresent := channel.members[invitee]
  1347. channel.stateMutex.RUnlock()
  1348. if !inviterPresent {
  1349. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), chname, inviter.t("You're not on that channel"))
  1350. return
  1351. }
  1352. inviteOnly := channel.flags.HasMode(modes.InviteOnly)
  1353. hasPrivs := channel.ClientIsAtLeast(inviter, modes.ChannelOperator)
  1354. if inviteOnly && !hasPrivs {
  1355. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), chname, inviter.t("You're not a channel operator"))
  1356. return
  1357. }
  1358. if inviteePresent {
  1359. rb.Add(nil, inviter.server.name, ERR_USERONCHANNEL, inviter.Nick(), invitee.Nick(), chname, inviter.t("User is already on that channel"))
  1360. return
  1361. }
  1362. // #1876: INVITE should override all join restrictions, including +b and +l,
  1363. // not just +i. so we need to record it on a per-client basis iff the inviter
  1364. // is privileged:
  1365. if hasPrivs {
  1366. invitee.Invite(chcfname, createdAt)
  1367. }
  1368. details := inviter.Details()
  1369. isBot := inviter.HasMode(modes.Bot)
  1370. tDetails := invitee.Details()
  1371. tnick := invitee.Nick()
  1372. message := utils.MakeMessage(chname)
  1373. item := history.Item{
  1374. Type: history.Invite,
  1375. Message: message,
  1376. }
  1377. for _, member := range channel.Members() {
  1378. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1379. continue
  1380. }
  1381. for _, session := range member.Sessions() {
  1382. if session.capabilities.Has(caps.InviteNotify) {
  1383. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "INVITE", tnick, chname)
  1384. }
  1385. }
  1386. }
  1387. rb.Add(nil, inviter.server.name, RPL_INVITING, details.nick, tnick, chname)
  1388. for _, iSession := range invitee.Sessions() {
  1389. iSession.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "INVITE", tnick, chname)
  1390. }
  1391. if away, awayMessage := invitee.Away(); away {
  1392. rb.Add(nil, inviter.server.name, RPL_AWAY, details.nick, tnick, awayMessage)
  1393. }
  1394. inviter.addHistoryItem(invitee, item, &details, &tDetails, channel.server.Config())
  1395. }
  1396. // Uninvite rescinds a channel invitation, if the inviter can do so.
  1397. func (channel *Channel) Uninvite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1398. if !channel.flags.HasMode(modes.InviteOnly) {
  1399. rb.Add(nil, channel.server.name, "FAIL", "UNINVITE", "NOT_INVITE_ONLY", channel.Name(), inviter.t("Channel is not invite-only"))
  1400. return
  1401. }
  1402. if !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  1403. rb.Add(nil, channel.server.name, "FAIL", "UNINVITE", "PRIVS_NEEDED", channel.Name(), inviter.t("You're not a channel operator"))
  1404. return
  1405. }
  1406. invitee.Uninvite(channel.NameCasefolded())
  1407. rb.Add(nil, channel.server.name, "UNINVITE", invitee.Nick(), channel.Name())
  1408. }
  1409. // returns who the client can "see" in the channel, respecting the auditorium mode
  1410. func (channel *Channel) auditoriumFriends(client *Client) (friends []*Client) {
  1411. channel.stateMutex.RLock()
  1412. defer channel.stateMutex.RUnlock()
  1413. clientData, found := channel.members[client]
  1414. if !found {
  1415. return // non-members have no friends
  1416. }
  1417. if !channel.flags.HasMode(modes.Auditorium) {
  1418. return channel.membersCache // default behavior for members
  1419. }
  1420. if clientData.modes.HighestChannelUserMode() != modes.Mode(0) {
  1421. return channel.membersCache // +v and up can see everyone in the auditorium
  1422. }
  1423. // without +v, your friends are those with +v and up
  1424. for member, memberData := range channel.members {
  1425. if memberData.modes.HighestChannelUserMode() != modes.Mode(0) {
  1426. friends = append(friends, member)
  1427. }
  1428. }
  1429. return
  1430. }
  1431. // returns whether the client is visible to unprivileged users in the channel
  1432. // (i.e., respecting auditorium mode). note that this assumes that the client
  1433. // is a member; if the client is not, it may return true anyway
  1434. func (channel *Channel) memberIsVisible(client *Client) bool {
  1435. // fast path, we assume they're a member so if this isn't an auditorium,
  1436. // they're visible:
  1437. if !channel.flags.HasMode(modes.Auditorium) {
  1438. return true
  1439. }
  1440. channel.stateMutex.RLock()
  1441. defer channel.stateMutex.RUnlock()
  1442. clientData, found := channel.members[client]
  1443. if !found {
  1444. return false
  1445. }
  1446. return clientData.modes.HighestChannelUserMode() != modes.Mode(0)
  1447. }
  1448. // data for RPL_LIST
  1449. func (channel *Channel) listData() (memberCount int, name, topic string) {
  1450. channel.stateMutex.RLock()
  1451. defer channel.stateMutex.RUnlock()
  1452. return len(channel.members), channel.name, channel.topic
  1453. }