Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

channel.go 52KB

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