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 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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. for {
  191. // TODO(#357) check the error value of this and implement timed backoff
  192. channel.performWrite(0)
  193. channel.writebackLock.Unlock()
  194. channel.stateMutex.RLock()
  195. isDirty := channel.dirtyBits != 0
  196. isEmpty := len(channel.members) == 0
  197. channel.stateMutex.RUnlock()
  198. if !isDirty {
  199. if isEmpty {
  200. channel.server.channels.Cleanup(channel)
  201. }
  202. return // nothing to do
  203. } // else: isDirty, so we need to write again
  204. if !channel.writebackLock.TryLock() {
  205. return
  206. }
  207. }
  208. }
  209. // Store writes part (or all) of the channel's data back to the database,
  210. // blocking until the write is complete. This is the equivalent of
  211. // Socket.BlockingWrite.
  212. func (channel *Channel) Store(dirtyBits uint) (err error) {
  213. defer func() {
  214. channel.stateMutex.Lock()
  215. isDirty := channel.dirtyBits != 0
  216. isEmpty := len(channel.members) == 0
  217. channel.stateMutex.Unlock()
  218. if isDirty {
  219. channel.wakeWriter()
  220. } else if isEmpty {
  221. channel.server.channels.Cleanup(channel)
  222. }
  223. }()
  224. channel.writebackLock.Lock()
  225. defer channel.writebackLock.Unlock()
  226. return channel.performWrite(dirtyBits)
  227. }
  228. // do an individual write; equivalent of Socket.send()
  229. func (channel *Channel) performWrite(additionalDirtyBits uint) (err error) {
  230. channel.stateMutex.Lock()
  231. dirtyBits := channel.dirtyBits | additionalDirtyBits
  232. channel.dirtyBits = 0
  233. isRegistered := channel.registeredFounder != ""
  234. channel.stateMutex.Unlock()
  235. if !isRegistered || dirtyBits == 0 {
  236. return
  237. }
  238. var success bool
  239. info := channel.ExportRegistration()
  240. if b, err := info.Serialize(); err == nil {
  241. if err := channel.server.dstore.Set(datastore.TableChannels, info.UUID, b, time.Time{}); err == nil {
  242. success = true
  243. } else {
  244. channel.server.logger.Error("internal", "couldn't persist channel", info.Name, err.Error())
  245. }
  246. } else {
  247. channel.server.logger.Error("internal", "couldn't serialize channel", info.Name, err.Error())
  248. }
  249. if !success {
  250. channel.stateMutex.Lock()
  251. channel.dirtyBits = channel.dirtyBits | dirtyBits
  252. channel.stateMutex.Unlock()
  253. }
  254. return
  255. }
  256. // SetRegistered registers the channel, returning an error if it was already registered.
  257. func (channel *Channel) SetRegistered(founder string) error {
  258. channel.stateMutex.Lock()
  259. defer channel.stateMutex.Unlock()
  260. if channel.registeredFounder != "" {
  261. return errChannelAlreadyRegistered
  262. }
  263. channel.registeredFounder = founder
  264. channel.registeredTime = time.Now().UTC()
  265. channel.accountToUMode[founder] = modes.ChannelFounder
  266. return nil
  267. }
  268. // SetUnregistered deletes the channel's registration information.
  269. func (channel *Channel) SetUnregistered(expectedFounder string) {
  270. uuid := utils.GenerateUUIDv4()
  271. channel.stateMutex.Lock()
  272. defer channel.stateMutex.Unlock()
  273. if channel.registeredFounder != expectedFounder {
  274. return
  275. }
  276. channel.registeredFounder = ""
  277. var zeroTime time.Time
  278. channel.registeredTime = zeroTime
  279. channel.accountToUMode = make(map[string]modes.Mode)
  280. // reset the UUID so that any re-registration will persist under
  281. // a separate key:
  282. channel.uuid = uuid
  283. }
  284. // implements `CHANSERV CLEAR #chan ACCESS` (resets bans, invites, excepts, and amodes)
  285. func (channel *Channel) resetAccess() {
  286. defer channel.MarkDirty(IncludeLists)
  287. channel.stateMutex.Lock()
  288. defer channel.stateMutex.Unlock()
  289. channel.initializeLists()
  290. if channel.registeredFounder != "" {
  291. channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
  292. }
  293. }
  294. // IsRegistered returns whether the channel is registered.
  295. func (channel *Channel) IsRegistered() bool {
  296. channel.stateMutex.RLock()
  297. defer channel.stateMutex.RUnlock()
  298. return channel.registeredFounder != ""
  299. }
  300. type channelTransferStatus uint
  301. const (
  302. channelTransferComplete channelTransferStatus = iota
  303. channelTransferPending
  304. channelTransferCancelled
  305. channelTransferFailed
  306. )
  307. // Transfer transfers ownership of a registered channel to a different account
  308. func (channel *Channel) Transfer(client *Client, target string, hasPrivs bool) (status channelTransferStatus, err error) {
  309. status = channelTransferFailed
  310. defer func() {
  311. if status == channelTransferComplete && err == nil {
  312. channel.Store(IncludeAllAttrs)
  313. }
  314. }()
  315. cftarget, err := CasefoldName(target)
  316. if err != nil {
  317. err = errAccountDoesNotExist
  318. return
  319. }
  320. channel.stateMutex.Lock()
  321. defer channel.stateMutex.Unlock()
  322. if channel.registeredFounder == "" {
  323. err = errChannelNotOwnedByAccount
  324. return
  325. }
  326. if hasPrivs {
  327. channel.transferOwnership(cftarget)
  328. return channelTransferComplete, nil
  329. } else {
  330. if channel.registeredFounder == cftarget {
  331. // transferring back to yourself cancels a pending transfer
  332. channel.transferPendingTo = ""
  333. return channelTransferCancelled, nil
  334. } else {
  335. channel.transferPendingTo = cftarget
  336. return channelTransferPending, nil
  337. }
  338. }
  339. }
  340. func (channel *Channel) transferOwnership(newOwner string) {
  341. delete(channel.accountToUMode, channel.registeredFounder)
  342. channel.registeredFounder = newOwner
  343. channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
  344. channel.transferPendingTo = ""
  345. }
  346. // AcceptTransfer implements `CS TRANSFER #chan ACCEPT`
  347. func (channel *Channel) AcceptTransfer(client *Client) (err error) {
  348. defer func() {
  349. if err == nil {
  350. channel.Store(IncludeAllAttrs)
  351. }
  352. }()
  353. account := client.Account()
  354. if account == "" {
  355. return errAccountNotLoggedIn
  356. }
  357. channel.stateMutex.Lock()
  358. defer channel.stateMutex.Unlock()
  359. if account != channel.transferPendingTo {
  360. return errChannelTransferNotOffered
  361. }
  362. channel.transferOwnership(account)
  363. return nil
  364. }
  365. func (channel *Channel) regenerateMembersCache() {
  366. channel.stateMutex.RLock()
  367. membersCache := make([]*Client, len(channel.members))
  368. dataCache := make([]*memberData, len(channel.members))
  369. i := 0
  370. for client, info := range channel.members {
  371. membersCache[i] = client
  372. dataCache[i] = info
  373. i++
  374. }
  375. channel.stateMutex.RUnlock()
  376. channel.stateMutex.Lock()
  377. channel.membersCache = membersCache
  378. channel.memberDataCache = dataCache
  379. channel.stateMutex.Unlock()
  380. }
  381. // Names sends the list of users joined to the channel to the given client.
  382. func (channel *Channel) Names(client *Client, rb *ResponseBuffer) {
  383. channel.stateMutex.RLock()
  384. clientData, isJoined := channel.members[client]
  385. chname := channel.name
  386. membersCache, memberDataCache := channel.membersCache, channel.memberDataCache
  387. channel.stateMutex.RUnlock()
  388. isOper := client.HasRoleCapabs("sajoin")
  389. respectAuditorium := channel.flags.HasMode(modes.Auditorium) && !isOper &&
  390. (!isJoined || clientData.modes.HighestChannelUserMode() == modes.Mode(0))
  391. isMultiPrefix := rb.session.capabilities.Has(caps.MultiPrefix)
  392. isUserhostInNames := rb.session.capabilities.Has(caps.UserhostInNames)
  393. maxNamLen := 480 - len(client.server.name) - len(client.Nick()) - len(chname)
  394. var tl utils.TokenLineBuilder
  395. tl.Initialize(maxNamLen, " ")
  396. if isJoined || !channel.flags.HasMode(modes.Secret) || isOper {
  397. for i, target := range membersCache {
  398. if !isJoined && target.HasMode(modes.Invisible) && !isOper {
  399. continue
  400. }
  401. var nick string
  402. if isUserhostInNames {
  403. nick = target.NickMaskString()
  404. } else {
  405. nick = target.Nick()
  406. }
  407. memberData := memberDataCache[i]
  408. if respectAuditorium && memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  409. continue
  410. }
  411. tl.AddParts(memberData.modes.Prefixes(isMultiPrefix), nick)
  412. }
  413. }
  414. for _, line := range tl.Lines() {
  415. rb.Add(nil, client.server.name, RPL_NAMREPLY, client.nick, "=", chname, line)
  416. }
  417. rb.Add(nil, client.server.name, RPL_ENDOFNAMES, client.nick, chname, client.t("End of NAMES list"))
  418. }
  419. // does `clientMode` give you privileges to grant/remove `targetMode` to/from people,
  420. // or to kick them?
  421. func channelUserModeHasPrivsOver(clientMode modes.Mode, targetMode modes.Mode) bool {
  422. switch clientMode {
  423. case modes.ChannelFounder:
  424. return true
  425. case modes.ChannelAdmin, modes.ChannelOperator:
  426. // admins cannot kick other admins, operators *can* kick other operators
  427. return targetMode != modes.ChannelFounder && targetMode != modes.ChannelAdmin
  428. case modes.Halfop:
  429. // halfops cannot kick other halfops
  430. return targetMode == modes.Voice || targetMode == modes.Mode(0)
  431. default:
  432. // voice and unprivileged cannot kick anyone
  433. return false
  434. }
  435. }
  436. // ClientIsAtLeast returns whether the client has at least the given channel privilege.
  437. func (channel *Channel) ClientIsAtLeast(client *Client, permission modes.Mode) bool {
  438. channel.stateMutex.RLock()
  439. memberData, present := channel.members[client]
  440. founder := channel.registeredFounder
  441. channel.stateMutex.RUnlock()
  442. if founder != "" && founder == client.Account() {
  443. return true
  444. }
  445. if !present {
  446. return false
  447. }
  448. for _, mode := range modes.ChannelUserModes {
  449. if memberData.modes.HasMode(mode) {
  450. return true
  451. }
  452. if mode == permission {
  453. break
  454. }
  455. }
  456. return false
  457. }
  458. func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) string {
  459. channel.stateMutex.RLock()
  460. defer channel.stateMutex.RUnlock()
  461. memberData, present := channel.members[client]
  462. if !present {
  463. return ""
  464. } else {
  465. return memberData.modes.Prefixes(isMultiPrefix)
  466. }
  467. }
  468. func (channel *Channel) ClientStatus(client *Client) (present bool, joinTimeSecs int64, cModes modes.Modes) {
  469. channel.stateMutex.RLock()
  470. defer channel.stateMutex.RUnlock()
  471. memberData, present := channel.members[client]
  472. return present, time.Unix(0, memberData.joinTime).Unix(), memberData.modes.AllModes()
  473. }
  474. // helper for persisting channel-user modes for always-on clients;
  475. // return the channel name and all channel-user modes for a client
  476. func (channel *Channel) alwaysOnStatus(client *Client) (ok bool, chname string, status alwaysOnChannelStatus) {
  477. channel.stateMutex.RLock()
  478. defer channel.stateMutex.RUnlock()
  479. chname = channel.name
  480. data, ok := channel.members[client]
  481. if !ok {
  482. return
  483. }
  484. status.Modes = data.modes.String()
  485. status.JoinTime = data.joinTime
  486. return
  487. }
  488. // overwrite any existing channel-user modes with the stored ones
  489. func (channel *Channel) setMemberStatus(client *Client, status alwaysOnChannelStatus) {
  490. newModes := modes.NewModeSet()
  491. for _, mode := range status.Modes {
  492. newModes.SetMode(modes.Mode(mode), true)
  493. }
  494. channel.stateMutex.Lock()
  495. defer channel.stateMutex.Unlock()
  496. if mData, ok := channel.members[client]; ok {
  497. mData.modes.Clear()
  498. for _, mode := range status.Modes {
  499. mData.modes.SetMode(modes.Mode(mode), true)
  500. }
  501. mData.joinTime = status.JoinTime
  502. }
  503. }
  504. func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
  505. channel.stateMutex.RLock()
  506. founder := channel.registeredFounder
  507. clientData, clientOK := channel.members[client]
  508. targetData, targetOK := channel.members[target]
  509. channel.stateMutex.RUnlock()
  510. if founder != "" {
  511. if founder == client.Account() {
  512. return true // #950: founder can take any privileged action without actually having +q
  513. } else if founder == target.Account() {
  514. return false // conversely, only the founder can kick the founder
  515. }
  516. }
  517. return clientOK && targetOK &&
  518. channelUserModeHasPrivsOver(
  519. clientData.modes.HighestChannelUserMode(),
  520. targetData.modes.HighestChannelUserMode(),
  521. )
  522. }
  523. func (channel *Channel) hasClient(client *Client) bool {
  524. channel.stateMutex.RLock()
  525. _, present := channel.members[client]
  526. channel.stateMutex.RUnlock()
  527. return present
  528. }
  529. // <mode> <mode params>
  530. func (channel *Channel) modeStrings(client *Client) (result []string) {
  531. hasPrivs := client.HasRoleCapabs("sajoin")
  532. channel.stateMutex.RLock()
  533. defer channel.stateMutex.RUnlock()
  534. isMember := hasPrivs || channel.members.Has(client)
  535. showKey := isMember && (channel.key != "")
  536. showUserLimit := channel.userLimit > 0
  537. showForward := channel.forward != ""
  538. var mods strings.Builder
  539. mods.WriteRune('+')
  540. // flags with args
  541. if showKey {
  542. mods.WriteRune(rune(modes.Key))
  543. }
  544. if showUserLimit {
  545. mods.WriteRune(rune(modes.UserLimit))
  546. }
  547. if showForward {
  548. mods.WriteRune(rune(modes.Forward))
  549. }
  550. for _, m := range channel.flags.AllModes() {
  551. mods.WriteRune(rune(m))
  552. }
  553. result = []string{mods.String()}
  554. // args for flags with args: The order must match above to keep
  555. // positional arguments in place.
  556. if showKey {
  557. result = append(result, channel.key)
  558. }
  559. if showUserLimit {
  560. result = append(result, strconv.Itoa(channel.userLimit))
  561. }
  562. if showForward {
  563. result = append(result, channel.forward)
  564. }
  565. return
  566. }
  567. func (channel *Channel) IsEmpty() bool {
  568. channel.stateMutex.RLock()
  569. defer channel.stateMutex.RUnlock()
  570. return len(channel.members) == 0
  571. }
  572. // figure out where history is being stored: persistent, ephemeral, or neither
  573. // target is only needed if we're doing persistent history
  574. func (channel *Channel) historyStatus(config *Config) (status HistoryStatus, target string, restrictions HistoryCutoff) {
  575. if !config.History.Enabled {
  576. return HistoryDisabled, "", HistoryCutoffNone
  577. }
  578. channel.stateMutex.RLock()
  579. target = channel.nameCasefolded
  580. settings := channel.settings
  581. registered := channel.registeredFounder != ""
  582. channel.stateMutex.RUnlock()
  583. restrictions = settings.QueryCutoff
  584. if restrictions == HistoryCutoffDefault {
  585. restrictions = config.History.Restrictions.queryCutoff
  586. }
  587. return channelHistoryStatus(config, registered, settings.History), target, restrictions
  588. }
  589. func (channel *Channel) joinTimeCutoff(client *Client) (present bool, cutoff time.Time) {
  590. account := client.Account()
  591. channel.stateMutex.RLock()
  592. defer channel.stateMutex.RUnlock()
  593. if data, ok := channel.members[client]; ok {
  594. present = true
  595. // report a cutoff of zero, i.e., no restriction, if the user is privileged
  596. if !((account != "" && account == channel.registeredFounder) || data.modes.HasMode(modes.ChannelFounder) || data.modes.HasMode(modes.ChannelAdmin) || data.modes.HasMode(modes.ChannelOperator)) {
  597. cutoff = time.Unix(0, data.joinTime)
  598. }
  599. }
  600. return
  601. }
  602. func channelHistoryStatus(config *Config, registered bool, storedStatus HistoryStatus) (result HistoryStatus) {
  603. if !config.History.Enabled {
  604. return HistoryDisabled
  605. }
  606. // ephemeral history: either the channel owner explicitly set the ephemeral preference,
  607. // or persistent history is disabled for unregistered channels
  608. if registered {
  609. return historyEnabled(config.History.Persistent.RegisteredChannels, storedStatus)
  610. } else {
  611. if config.History.Persistent.UnregisteredChannels {
  612. return HistoryPersistent
  613. } else {
  614. return HistoryEphemeral
  615. }
  616. }
  617. }
  618. func (channel *Channel) AddHistoryItem(item history.Item, account string) (err error) {
  619. if !itemIsStorable(&item, channel.server.Config()) {
  620. return
  621. }
  622. status, target, _ := channel.historyStatus(channel.server.Config())
  623. if status == HistoryPersistent {
  624. err = channel.server.historyDB.AddChannelItem(target, item, account)
  625. } else if status == HistoryEphemeral {
  626. channel.history.Add(item)
  627. }
  628. return
  629. }
  630. // Join joins the given client to this channel (if they can be joined).
  631. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) (joinErr error, forward string) {
  632. details := client.Details()
  633. isBot := client.HasMode(modes.Bot)
  634. channel.stateMutex.RLock()
  635. chname := channel.name
  636. chcfname := channel.nameCasefolded
  637. founder := channel.registeredFounder
  638. createdAt := channel.createdTime
  639. chkey := channel.key
  640. limit := channel.userLimit
  641. chcount := len(channel.members)
  642. _, alreadyJoined := channel.members[client]
  643. persistentMode := channel.accountToUMode[details.account]
  644. forward = channel.forward
  645. channel.stateMutex.RUnlock()
  646. if alreadyJoined {
  647. // no message needs to be sent
  648. return nil, ""
  649. }
  650. // 0. SAJOIN always succeeds
  651. // 1. the founder can always join (even if they disabled auto +q on join)
  652. // 2. anyone who automatically receives halfop or higher can always join
  653. // 3. people invited with INVITE can join
  654. hasPrivs := isSajoin || (founder != "" && founder == details.account) ||
  655. (persistentMode != 0 && persistentMode != modes.Voice) ||
  656. client.CheckInvited(chcfname, createdAt)
  657. if !hasPrivs {
  658. if limit != 0 && chcount >= limit {
  659. return errLimitExceeded, forward
  660. }
  661. if chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  662. return errWrongChannelKey, forward
  663. }
  664. // #1901: +h and up exempt from all restrictions, but +v additionally exempts from +i:
  665. if channel.flags.HasMode(modes.InviteOnly) && persistentMode == 0 &&
  666. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  667. return errInviteOnly, forward
  668. }
  669. if channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  670. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) &&
  671. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  672. // do not forward people who are banned:
  673. return errBanned, ""
  674. }
  675. if details.account == "" &&
  676. (channel.flags.HasMode(modes.RegisteredOnly) || channel.server.Defcon() <= 2) &&
  677. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  678. return errRegisteredOnly, forward
  679. }
  680. }
  681. if joinErr := client.addChannel(channel, rb == nil); joinErr != nil {
  682. return joinErr, ""
  683. }
  684. client.server.logger.Debug("channels", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  685. givenMode := func() (givenMode modes.Mode) {
  686. channel.joinPartMutex.Lock()
  687. defer channel.joinPartMutex.Unlock()
  688. func() {
  689. channel.stateMutex.Lock()
  690. defer channel.stateMutex.Unlock()
  691. channel.members.Add(client)
  692. firstJoin := len(channel.members) == 1
  693. newChannel := firstJoin && channel.registeredFounder == ""
  694. if newChannel {
  695. givenMode = modes.ChannelOperator
  696. } else {
  697. givenMode = persistentMode
  698. }
  699. if givenMode != 0 {
  700. channel.members[client].modes.SetMode(givenMode, true)
  701. }
  702. }()
  703. channel.regenerateMembersCache()
  704. return
  705. }()
  706. var message utils.SplitMessage
  707. respectAuditorium := givenMode == modes.Mode(0) && channel.flags.HasMode(modes.Auditorium)
  708. message = utils.MakeMessage("")
  709. // no history item for fake persistent joins
  710. if rb != nil && !respectAuditorium {
  711. histItem := history.Item{
  712. Type: history.Join,
  713. Nick: details.nickMask,
  714. AccountName: details.accountName,
  715. Message: message,
  716. IsBot: isBot,
  717. }
  718. histItem.Params[0] = details.realname
  719. channel.AddHistoryItem(histItem, details.account)
  720. }
  721. if rb == nil {
  722. return nil, ""
  723. }
  724. var modestr string
  725. if givenMode != 0 {
  726. modestr = fmt.Sprintf("+%v", givenMode)
  727. }
  728. // cache the most common case (JOIN without extended-join)
  729. var cache MessageCache
  730. cache.Initialize(channel.server, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
  731. isAway, awayMessage := client.Away()
  732. for _, member := range channel.Members() {
  733. if respectAuditorium {
  734. channel.stateMutex.RLock()
  735. memberData, ok := channel.members[member]
  736. channel.stateMutex.RUnlock()
  737. if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  738. continue
  739. }
  740. }
  741. for _, session := range member.Sessions() {
  742. if session == rb.session {
  743. continue
  744. } else if client == session.client {
  745. channel.playJoinForSession(session)
  746. continue
  747. }
  748. if session.capabilities.Has(caps.ExtendedJoin) {
  749. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
  750. } else {
  751. cache.Send(session)
  752. }
  753. if givenMode != 0 {
  754. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  755. }
  756. if isAway && session.capabilities.Has(caps.AwayNotify) {
  757. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.accountName, isBot, nil, "AWAY", awayMessage)
  758. }
  759. }
  760. }
  761. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  762. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
  763. } else {
  764. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
  765. }
  766. if rb.session.capabilities.Has(caps.ReadMarker) {
  767. rb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
  768. }
  769. if rb.session.client == client {
  770. // don't send topic and names for a SAJOIN of a different client
  771. channel.SendTopic(client, rb, false)
  772. if !rb.session.capabilities.Has(caps.NoImplicitNames) {
  773. channel.Names(client, rb)
  774. }
  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. if !session.capabilities.Has(caps.NoImplicitNames) {
  860. channel.Names(client, sessionRb)
  861. }
  862. sessionRb.Send(false)
  863. }
  864. // Part parts the given client from this channel, with the given message.
  865. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  866. channel.stateMutex.RLock()
  867. chname := channel.name
  868. clientData, ok := channel.members[client]
  869. channel.stateMutex.RUnlock()
  870. if !ok {
  871. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  872. return
  873. }
  874. channel.Quit(client)
  875. splitMessage := utils.MakeMessage(message)
  876. details := client.Details()
  877. isBot := client.HasMode(modes.Bot)
  878. params := make([]string, 1, 2)
  879. params[0] = chname
  880. if message != "" {
  881. params = append(params, message)
  882. }
  883. respectAuditorium := channel.flags.HasMode(modes.Auditorium) &&
  884. clientData.modes.HighestChannelUserMode() == modes.Mode(0)
  885. var cache MessageCache
  886. cache.Initialize(channel.server, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  887. for _, member := range channel.Members() {
  888. if respectAuditorium {
  889. channel.stateMutex.RLock()
  890. memberData, ok := channel.members[member]
  891. channel.stateMutex.RUnlock()
  892. if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  893. continue
  894. }
  895. }
  896. for _, session := range member.Sessions() {
  897. cache.Send(session)
  898. }
  899. }
  900. rb.AddFromClient(splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  901. for _, session := range client.Sessions() {
  902. if session != rb.session {
  903. session.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  904. }
  905. }
  906. if !respectAuditorium {
  907. channel.AddHistoryItem(history.Item{
  908. Type: history.Part,
  909. Nick: details.nickMask,
  910. AccountName: details.accountName,
  911. Message: splitMessage,
  912. IsBot: isBot,
  913. }, details.account)
  914. }
  915. client.server.logger.Debug("channels", fmt.Sprintf("%s left channel %s", details.nick, chname))
  916. }
  917. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item, chathistoryCommand bool) {
  918. // send an empty batch if necessary, as per the CHATHISTORY spec
  919. chname := channel.Name()
  920. client := rb.target
  921. eventPlayback := rb.session.capabilities.Has(caps.EventPlayback)
  922. extendedJoin := rb.session.capabilities.Has(caps.ExtendedJoin)
  923. var playJoinsAsPrivmsg bool
  924. if !eventPlayback {
  925. if chathistoryCommand {
  926. playJoinsAsPrivmsg = true
  927. } else {
  928. switch client.AccountSettings().ReplayJoins {
  929. case ReplayJoinsCommandsOnly:
  930. playJoinsAsPrivmsg = false
  931. case ReplayJoinsAlways:
  932. playJoinsAsPrivmsg = true
  933. }
  934. }
  935. }
  936. batchID := rb.StartNestedBatch("chathistory", chname)
  937. defer rb.EndNestedBatch(batchID)
  938. for _, item := range items {
  939. nick := NUHToNick(item.Nick)
  940. switch item.Type {
  941. case history.Privmsg:
  942. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "PRIVMSG", chname, item.Message)
  943. case history.Notice:
  944. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "NOTICE", chname, item.Message)
  945. case history.Tagmsg:
  946. if eventPlayback {
  947. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "TAGMSG", chname, item.Message)
  948. } else if chathistoryCommand {
  949. // #1676, we have to send something here or else it breaks pagination
  950. 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))
  951. }
  952. case history.Join:
  953. if eventPlayback {
  954. if extendedJoin {
  955. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "JOIN", chname, item.AccountName, item.Params[0])
  956. } else {
  957. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "JOIN", chname)
  958. }
  959. } else {
  960. if !playJoinsAsPrivmsg {
  961. continue // #474
  962. }
  963. var message string
  964. if item.AccountName == "*" {
  965. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  966. } else {
  967. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  968. }
  969. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  970. }
  971. case history.Part:
  972. if eventPlayback {
  973. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "PART", chname, item.Message.Message)
  974. } else {
  975. if !playJoinsAsPrivmsg {
  976. continue // #474
  977. }
  978. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  979. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  980. }
  981. case history.Kick:
  982. if eventPlayback {
  983. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "KICK", chname, item.Params[0], item.Message.Message)
  984. } else {
  985. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Params[0], item.Message.Message)
  986. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  987. }
  988. case history.Quit:
  989. if eventPlayback {
  990. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "QUIT", item.Message.Message)
  991. } else {
  992. if !playJoinsAsPrivmsg {
  993. continue // #474
  994. }
  995. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  996. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  997. }
  998. case history.Nick:
  999. if eventPlayback {
  1000. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "NICK", item.Params[0])
  1001. } else {
  1002. message := fmt.Sprintf(client.t("%[1]s changed nick to %[2]s"), nick, item.Params[0])
  1003. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1004. }
  1005. case history.Topic:
  1006. if eventPlayback {
  1007. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "TOPIC", chname, item.Message.Message)
  1008. } else {
  1009. message := fmt.Sprintf(client.t("%[1]s set the channel topic to: %[2]s"), nick, item.Message.Message)
  1010. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1011. }
  1012. case history.Mode:
  1013. params := make([]string, len(item.Message.Split)+1)
  1014. params[0] = chname
  1015. for i, pair := range item.Message.Split {
  1016. params[i+1] = pair.Message
  1017. }
  1018. if eventPlayback {
  1019. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "MODE", params...)
  1020. } else {
  1021. message := fmt.Sprintf(client.t("%[1]s set channel modes: %[2]s"), nick, strings.Join(params[1:], " "))
  1022. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1023. }
  1024. }
  1025. }
  1026. }
  1027. // SendTopic sends the channel topic to the given client.
  1028. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  1029. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  1030. channel.stateMutex.RLock()
  1031. name := channel.name
  1032. topic := channel.topic
  1033. topicSetBy := channel.topicSetBy
  1034. topicSetTime := channel.topicSetTime
  1035. _, hasClient := channel.members[client]
  1036. channel.stateMutex.RUnlock()
  1037. if !hasClient {
  1038. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.name, client.t("You're not on that channel"))
  1039. return
  1040. }
  1041. if topic == "" {
  1042. if sendNoTopic {
  1043. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  1044. }
  1045. return
  1046. }
  1047. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  1048. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  1049. }
  1050. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  1051. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  1052. if !channel.hasClient(client) {
  1053. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  1054. return
  1055. }
  1056. if channel.flags.HasMode(modes.OpOnlyTopic) && !(channel.ClientIsAtLeast(client, modes.Halfop) || client.HasRoleCapabs("samode")) {
  1057. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  1058. return
  1059. }
  1060. topic = ircmsg.TruncateUTF8Safe(topic, client.server.Config().Limits.TopicLen)
  1061. channel.stateMutex.Lock()
  1062. chname := channel.name
  1063. channel.topic = topic
  1064. channel.topicSetBy = client.nickMaskString
  1065. channel.topicSetTime = time.Now().UTC()
  1066. channel.stateMutex.Unlock()
  1067. details := client.Details()
  1068. isBot := client.HasMode(modes.Bot)
  1069. message := utils.MakeMessage(topic)
  1070. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "TOPIC", chname, topic)
  1071. for _, member := range channel.Members() {
  1072. for _, session := range member.Sessions() {
  1073. if session != rb.session {
  1074. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "TOPIC", chname, topic)
  1075. }
  1076. }
  1077. }
  1078. channel.AddHistoryItem(history.Item{
  1079. Type: history.Topic,
  1080. Nick: details.nickMask,
  1081. AccountName: details.accountName,
  1082. Message: message,
  1083. IsBot: isBot,
  1084. }, details.account)
  1085. channel.MarkDirty(IncludeTopic)
  1086. }
  1087. // 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.
  1088. func (channel *Channel) CanSpeak(client *Client) (bool, modes.Mode) {
  1089. channel.stateMutex.RLock()
  1090. memberData, hasClient := channel.members[client]
  1091. channel.stateMutex.RUnlock()
  1092. highestMode := func() modes.Mode {
  1093. if !hasClient {
  1094. return modes.Mode(0)
  1095. }
  1096. return memberData.modes.HighestChannelUserMode()
  1097. }
  1098. if !hasClient && channel.flags.HasMode(modes.NoOutside) {
  1099. // TODO: enforce regular +b bans on -n channels?
  1100. return false, modes.NoOutside
  1101. }
  1102. if channel.isMuted(client) && highestMode() == modes.Mode(0) {
  1103. return false, modes.BanMask
  1104. }
  1105. if channel.flags.HasMode(modes.Moderated) && highestMode() == modes.Mode(0) {
  1106. return false, modes.Moderated
  1107. }
  1108. if channel.flags.HasMode(modes.RegisteredOnlySpeak) && client.Account() == "" &&
  1109. highestMode() == modes.Mode(0) {
  1110. return false, modes.RegisteredOnlySpeak
  1111. }
  1112. return true, modes.Mode('?')
  1113. }
  1114. func (channel *Channel) isMuted(client *Client) bool {
  1115. muteRe := channel.lists[modes.BanMask].MuteRegexp()
  1116. if muteRe == nil {
  1117. return false
  1118. }
  1119. nuh := client.NickMaskCasefolded()
  1120. return muteRe.MatchString(nuh) && !channel.lists[modes.ExceptMask].MatchMute(nuh)
  1121. }
  1122. func (channel *Channel) relayNickMuted(relayNick string) bool {
  1123. relayNUH := fmt.Sprintf("%s!*@*", relayNick)
  1124. return channel.lists[modes.BanMask].MatchMute(relayNUH) &&
  1125. !channel.lists[modes.ExceptMask].MatchMute(relayNUH)
  1126. }
  1127. func msgCommandToHistType(command string) (history.ItemType, error) {
  1128. switch command {
  1129. case "PRIVMSG":
  1130. return history.Privmsg, nil
  1131. case "NOTICE":
  1132. return history.Notice, nil
  1133. case "TAGMSG":
  1134. return history.Tagmsg, nil
  1135. default:
  1136. return history.ItemType(0), errInvalidParams
  1137. }
  1138. }
  1139. func (channel *Channel) SendSplitMessage(command string, minPrefixMode modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  1140. histType, err := msgCommandToHistType(command)
  1141. if err != nil {
  1142. return
  1143. }
  1144. if canSpeak, mode := channel.CanSpeak(client); !canSpeak {
  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)"), mode))
  1147. }
  1148. return
  1149. }
  1150. isCTCP := message.IsRestrictedCTCPMessage()
  1151. if isCTCP && channel.flags.HasMode(modes.NoCTCP) {
  1152. if histType != history.Notice {
  1153. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), "C"))
  1154. }
  1155. return
  1156. }
  1157. details := client.Details()
  1158. isBot := client.HasMode(modes.Bot)
  1159. chname := channel.Name()
  1160. if !client.server.Config().Server.Compatibility.allowTruncation {
  1161. if !validateSplitMessageLen(histType, details.nickMask, chname, message) {
  1162. rb.Add(nil, client.server.name, ERR_INPUTTOOLONG, details.nick, client.t("Line too long to be relayed without truncation"))
  1163. return
  1164. }
  1165. }
  1166. // STATUSMSG targets are prefixed with the supplied min-prefix, e.g., @#channel
  1167. if minPrefixMode != modes.Mode(0) {
  1168. chname = fmt.Sprintf("%s%s", modes.ChannelModePrefixes[minPrefixMode], chname)
  1169. }
  1170. if channel.flags.HasMode(modes.OpModerated) {
  1171. channel.stateMutex.RLock()
  1172. cuData, ok := channel.members[client]
  1173. channel.stateMutex.RUnlock()
  1174. if !ok || cuData.modes.HighestChannelUserMode() == modes.Mode(0) {
  1175. // max(statusmsg_minmode, halfop)
  1176. if minPrefixMode == modes.Mode(0) || minPrefixMode == modes.Voice {
  1177. minPrefixMode = modes.Halfop
  1178. }
  1179. }
  1180. }
  1181. // send echo-message
  1182. rb.addEchoMessage(clientOnlyTags, details.nickMask, details.accountName, command, chname, message)
  1183. var cache MessageCache
  1184. cache.InitializeSplitMessage(channel.server, details.nickMask, details.accountName, isBot, clientOnlyTags, command, chname, message)
  1185. for _, member := range channel.Members() {
  1186. if minPrefixMode != modes.Mode(0) && !channel.ClientIsAtLeast(member, minPrefixMode) {
  1187. // STATUSMSG or OpModerated
  1188. continue
  1189. }
  1190. for _, session := range member.Sessions() {
  1191. if session == rb.session {
  1192. continue // we already sent echo-message, if applicable
  1193. }
  1194. if isCTCP && session.isTor {
  1195. continue // #753
  1196. }
  1197. cache.Send(session)
  1198. }
  1199. }
  1200. // #959: don't save STATUSMSG (or OpModerated)
  1201. if minPrefixMode == modes.Mode(0) {
  1202. channel.AddHistoryItem(history.Item{
  1203. Type: histType,
  1204. Message: message,
  1205. Nick: details.nickMask,
  1206. AccountName: details.accountName,
  1207. Tags: clientOnlyTags,
  1208. IsBot: isBot,
  1209. }, details.account)
  1210. }
  1211. }
  1212. func (channel *Channel) applyModeToMember(client *Client, change modes.ModeChange, rb *ResponseBuffer) (applied bool, result modes.ModeChange) {
  1213. target := channel.server.clients.Get(change.Arg)
  1214. if target == nil {
  1215. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(change.Arg), client.t("No such nick"))
  1216. return
  1217. }
  1218. change.Arg = target.Nick()
  1219. channel.stateMutex.Lock()
  1220. memberData, exists := channel.members[target]
  1221. if exists {
  1222. if memberData.modes.SetMode(change.Mode, change.Op == modes.Add) {
  1223. applied = true
  1224. result = change
  1225. }
  1226. }
  1227. channel.stateMutex.Unlock()
  1228. if !exists {
  1229. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1230. }
  1231. if applied {
  1232. target.markDirty(IncludeChannels)
  1233. }
  1234. return
  1235. }
  1236. // ShowMaskList shows the given list to the client.
  1237. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  1238. // choose appropriate modes
  1239. var rpllist, rplendoflist string
  1240. if mode == modes.BanMask {
  1241. rpllist = RPL_BANLIST
  1242. rplendoflist = RPL_ENDOFBANLIST
  1243. } else if mode == modes.ExceptMask {
  1244. rpllist = RPL_EXCEPTLIST
  1245. rplendoflist = RPL_ENDOFEXCEPTLIST
  1246. } else if mode == modes.InviteMask {
  1247. rpllist = RPL_INVITELIST
  1248. rplendoflist = RPL_ENDOFINVITELIST
  1249. }
  1250. nick := client.Nick()
  1251. chname := channel.Name()
  1252. for mask, info := range channel.lists[mode].Masks() {
  1253. rb.Add(nil, client.server.name, rpllist, nick, chname, mask, info.CreatorNickmask, strconv.FormatInt(info.TimeCreated.Unix(), 10))
  1254. }
  1255. rb.Add(nil, client.server.name, rplendoflist, nick, chname, client.t("End of list"))
  1256. }
  1257. // Quit removes the given client from the channel
  1258. func (channel *Channel) Quit(client *Client) {
  1259. channelEmpty := func() bool {
  1260. channel.joinPartMutex.Lock()
  1261. defer channel.joinPartMutex.Unlock()
  1262. channel.stateMutex.Lock()
  1263. channel.members.Remove(client)
  1264. channelEmpty := len(channel.members) == 0
  1265. channel.stateMutex.Unlock()
  1266. channel.regenerateMembersCache()
  1267. return channelEmpty
  1268. }()
  1269. if channelEmpty {
  1270. client.server.channels.Cleanup(channel)
  1271. }
  1272. client.removeChannel(channel)
  1273. }
  1274. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer, hasPrivs bool) {
  1275. if !hasPrivs {
  1276. if !channel.ClientHasPrivsOver(client, target) {
  1277. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  1278. return
  1279. }
  1280. }
  1281. if !channel.hasClient(target) {
  1282. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1283. return
  1284. }
  1285. comment = ircmsg.TruncateUTF8Safe(comment, channel.server.Config().Limits.KickLen)
  1286. message := utils.MakeMessage(comment)
  1287. details := client.Details()
  1288. isBot := client.HasMode(modes.Bot)
  1289. targetNick := target.Nick()
  1290. chname := channel.Name()
  1291. for _, member := range channel.Members() {
  1292. for _, session := range member.Sessions() {
  1293. if session != rb.session {
  1294. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "KICK", chname, targetNick, comment)
  1295. }
  1296. }
  1297. }
  1298. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "KICK", chname, targetNick, comment)
  1299. histItem := history.Item{
  1300. Type: history.Kick,
  1301. Nick: details.nickMask,
  1302. AccountName: details.accountName,
  1303. Message: message,
  1304. IsBot: isBot,
  1305. }
  1306. histItem.Params[0] = targetNick
  1307. channel.AddHistoryItem(histItem, details.account)
  1308. channel.Quit(target)
  1309. }
  1310. // handle a purge: kick everyone off the channel, clean up all the pointers between
  1311. // *Channel and *Client
  1312. func (channel *Channel) Purge(source string) {
  1313. if source == "" {
  1314. source = channel.server.name
  1315. }
  1316. channel.stateMutex.Lock()
  1317. chname := channel.name
  1318. members := channel.membersCache
  1319. channel.membersCache = nil
  1320. channel.memberDataCache = nil
  1321. channel.members = make(MemberSet)
  1322. // TODO try to prevent Purge racing against (pending) Join?
  1323. channel.stateMutex.Unlock()
  1324. now := time.Now().UTC()
  1325. for _, member := range members {
  1326. tnick := member.Nick()
  1327. msgid := utils.GenerateSecretToken()
  1328. for _, session := range member.Sessions() {
  1329. 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"))
  1330. }
  1331. member.removeChannel(channel)
  1332. }
  1333. }
  1334. // Invite invites the given client to the channel, if the inviter can do so.
  1335. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1336. channel.stateMutex.RLock()
  1337. chname := channel.name
  1338. chcfname := channel.nameCasefolded
  1339. createdAt := channel.createdTime
  1340. _, inviterPresent := channel.members[inviter]
  1341. _, inviteePresent := channel.members[invitee]
  1342. channel.stateMutex.RUnlock()
  1343. if !inviterPresent {
  1344. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), chname, inviter.t("You're not on that channel"))
  1345. return
  1346. }
  1347. inviteOnly := channel.flags.HasMode(modes.InviteOnly)
  1348. hasPrivs := channel.ClientIsAtLeast(inviter, modes.ChannelOperator)
  1349. if inviteOnly && !hasPrivs {
  1350. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), chname, inviter.t("You're not a channel operator"))
  1351. return
  1352. }
  1353. if inviteePresent {
  1354. rb.Add(nil, inviter.server.name, ERR_USERONCHANNEL, inviter.Nick(), invitee.Nick(), chname, inviter.t("User is already on that channel"))
  1355. return
  1356. }
  1357. // #1876: INVITE should override all join restrictions, including +b and +l,
  1358. // not just +i. so we need to record it on a per-client basis iff the inviter
  1359. // is privileged:
  1360. if hasPrivs {
  1361. invitee.Invite(chcfname, createdAt)
  1362. }
  1363. details := inviter.Details()
  1364. isBot := inviter.HasMode(modes.Bot)
  1365. tDetails := invitee.Details()
  1366. tnick := invitee.Nick()
  1367. message := utils.MakeMessage(chname)
  1368. item := history.Item{
  1369. Type: history.Invite,
  1370. Message: message,
  1371. }
  1372. for _, member := range channel.Members() {
  1373. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1374. continue
  1375. }
  1376. for _, session := range member.Sessions() {
  1377. if session.capabilities.Has(caps.InviteNotify) {
  1378. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "INVITE", tnick, chname)
  1379. }
  1380. }
  1381. }
  1382. rb.Add(nil, inviter.server.name, RPL_INVITING, details.nick, tnick, chname)
  1383. for _, iSession := range invitee.Sessions() {
  1384. iSession.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "INVITE", tnick, chname)
  1385. }
  1386. if away, awayMessage := invitee.Away(); away {
  1387. rb.Add(nil, inviter.server.name, RPL_AWAY, details.nick, tnick, awayMessage)
  1388. }
  1389. inviter.addHistoryItem(invitee, item, &details, &tDetails, channel.server.Config())
  1390. }
  1391. // Uninvite rescinds a channel invitation, if the inviter can do so.
  1392. func (channel *Channel) Uninvite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1393. if !channel.flags.HasMode(modes.InviteOnly) {
  1394. rb.Add(nil, channel.server.name, "FAIL", "UNINVITE", "NOT_INVITE_ONLY", channel.Name(), inviter.t("Channel is not invite-only"))
  1395. return
  1396. }
  1397. if !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  1398. rb.Add(nil, channel.server.name, "FAIL", "UNINVITE", "PRIVS_NEEDED", channel.Name(), inviter.t("You're not a channel operator"))
  1399. return
  1400. }
  1401. invitee.Uninvite(channel.NameCasefolded())
  1402. rb.Add(nil, channel.server.name, "UNINVITE", invitee.Nick(), channel.Name())
  1403. }
  1404. // returns who the client can "see" in the channel, respecting the auditorium mode
  1405. func (channel *Channel) auditoriumFriends(client *Client) (friends []*Client) {
  1406. channel.stateMutex.RLock()
  1407. defer channel.stateMutex.RUnlock()
  1408. clientData, found := channel.members[client]
  1409. if !found {
  1410. return // non-members have no friends
  1411. }
  1412. if !channel.flags.HasMode(modes.Auditorium) {
  1413. return channel.membersCache // default behavior for members
  1414. }
  1415. if clientData.modes.HighestChannelUserMode() != modes.Mode(0) {
  1416. return channel.membersCache // +v and up can see everyone in the auditorium
  1417. }
  1418. // without +v, your friends are those with +v and up
  1419. for member, memberData := range channel.members {
  1420. if memberData.modes.HighestChannelUserMode() != modes.Mode(0) {
  1421. friends = append(friends, member)
  1422. }
  1423. }
  1424. return
  1425. }
  1426. // data for RPL_LIST
  1427. func (channel *Channel) listData() (memberCount int, name, topic string) {
  1428. channel.stateMutex.RLock()
  1429. defer channel.stateMutex.RUnlock()
  1430. return len(channel.members), channel.name, channel.topic
  1431. }