Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

channel.go 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  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) (chname string, status alwaysOnChannelStatus) {
  477. channel.stateMutex.RLock()
  478. defer channel.stateMutex.RUnlock()
  479. chname = channel.name
  480. data := channel.members[client]
  481. status.Modes = data.modes.String()
  482. status.JoinTime = data.joinTime
  483. return
  484. }
  485. // overwrite any existing channel-user modes with the stored ones
  486. func (channel *Channel) setMemberStatus(client *Client, status alwaysOnChannelStatus) {
  487. newModes := modes.NewModeSet()
  488. for _, mode := range status.Modes {
  489. newModes.SetMode(modes.Mode(mode), true)
  490. }
  491. channel.stateMutex.Lock()
  492. defer channel.stateMutex.Unlock()
  493. if mData, ok := channel.members[client]; ok {
  494. mData.modes.Clear()
  495. for _, mode := range status.Modes {
  496. mData.modes.SetMode(modes.Mode(mode), true)
  497. }
  498. mData.joinTime = status.JoinTime
  499. }
  500. }
  501. func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
  502. channel.stateMutex.RLock()
  503. founder := channel.registeredFounder
  504. clientData, clientOK := channel.members[client]
  505. targetData, targetOK := channel.members[target]
  506. channel.stateMutex.RUnlock()
  507. if founder != "" {
  508. if founder == client.Account() {
  509. return true // #950: founder can take any privileged action without actually having +q
  510. } else if founder == target.Account() {
  511. return false // conversely, only the founder can kick the founder
  512. }
  513. }
  514. return clientOK && targetOK &&
  515. channelUserModeHasPrivsOver(
  516. clientData.modes.HighestChannelUserMode(),
  517. targetData.modes.HighestChannelUserMode(),
  518. )
  519. }
  520. func (channel *Channel) hasClient(client *Client) bool {
  521. channel.stateMutex.RLock()
  522. _, present := channel.members[client]
  523. channel.stateMutex.RUnlock()
  524. return present
  525. }
  526. // <mode> <mode params>
  527. func (channel *Channel) modeStrings(client *Client) (result []string) {
  528. hasPrivs := client.HasRoleCapabs("sajoin")
  529. channel.stateMutex.RLock()
  530. defer channel.stateMutex.RUnlock()
  531. isMember := hasPrivs || channel.members.Has(client)
  532. showKey := isMember && (channel.key != "")
  533. showUserLimit := channel.userLimit > 0
  534. showForward := channel.forward != ""
  535. var mods strings.Builder
  536. mods.WriteRune('+')
  537. // flags with args
  538. if showKey {
  539. mods.WriteRune(rune(modes.Key))
  540. }
  541. if showUserLimit {
  542. mods.WriteRune(rune(modes.UserLimit))
  543. }
  544. if showForward {
  545. mods.WriteRune(rune(modes.Forward))
  546. }
  547. for _, m := range channel.flags.AllModes() {
  548. mods.WriteRune(rune(m))
  549. }
  550. result = []string{mods.String()}
  551. // args for flags with args: The order must match above to keep
  552. // positional arguments in place.
  553. if showKey {
  554. result = append(result, channel.key)
  555. }
  556. if showUserLimit {
  557. result = append(result, strconv.Itoa(channel.userLimit))
  558. }
  559. if showForward {
  560. result = append(result, channel.forward)
  561. }
  562. return
  563. }
  564. func (channel *Channel) IsEmpty() bool {
  565. channel.stateMutex.RLock()
  566. defer channel.stateMutex.RUnlock()
  567. return len(channel.members) == 0
  568. }
  569. // figure out where history is being stored: persistent, ephemeral, or neither
  570. // target is only needed if we're doing persistent history
  571. func (channel *Channel) historyStatus(config *Config) (status HistoryStatus, target string, restrictions HistoryCutoff) {
  572. if !config.History.Enabled {
  573. return HistoryDisabled, "", HistoryCutoffNone
  574. }
  575. channel.stateMutex.RLock()
  576. target = channel.nameCasefolded
  577. settings := channel.settings
  578. registered := channel.registeredFounder != ""
  579. channel.stateMutex.RUnlock()
  580. restrictions = settings.QueryCutoff
  581. if restrictions == HistoryCutoffDefault {
  582. restrictions = config.History.Restrictions.queryCutoff
  583. }
  584. return channelHistoryStatus(config, registered, settings.History), target, restrictions
  585. }
  586. func (channel *Channel) joinTimeCutoff(client *Client) (present bool, cutoff time.Time) {
  587. account := client.Account()
  588. channel.stateMutex.RLock()
  589. defer channel.stateMutex.RUnlock()
  590. if data, ok := channel.members[client]; ok {
  591. present = true
  592. // report a cutoff of zero, i.e., no restriction, if the user is privileged
  593. if !((account != "" && account == channel.registeredFounder) || data.modes.HasMode(modes.ChannelFounder) || data.modes.HasMode(modes.ChannelAdmin) || data.modes.HasMode(modes.ChannelOperator)) {
  594. cutoff = time.Unix(0, data.joinTime)
  595. }
  596. }
  597. return
  598. }
  599. func channelHistoryStatus(config *Config, registered bool, storedStatus HistoryStatus) (result HistoryStatus) {
  600. if !config.History.Enabled {
  601. return HistoryDisabled
  602. }
  603. // ephemeral history: either the channel owner explicitly set the ephemeral preference,
  604. // or persistent history is disabled for unregistered channels
  605. if registered {
  606. return historyEnabled(config.History.Persistent.RegisteredChannels, storedStatus)
  607. } else {
  608. if config.History.Persistent.UnregisteredChannels {
  609. return HistoryPersistent
  610. } else {
  611. return HistoryEphemeral
  612. }
  613. }
  614. }
  615. func (channel *Channel) AddHistoryItem(item history.Item, account string) (err error) {
  616. if !itemIsStorable(&item, channel.server.Config()) {
  617. return
  618. }
  619. status, target, _ := channel.historyStatus(channel.server.Config())
  620. if status == HistoryPersistent {
  621. err = channel.server.historyDB.AddChannelItem(target, item, account)
  622. } else if status == HistoryEphemeral {
  623. channel.history.Add(item)
  624. }
  625. return
  626. }
  627. // Join joins the given client to this channel (if they can be joined).
  628. func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) (joinErr error, forward string) {
  629. details := client.Details()
  630. isBot := client.HasMode(modes.Bot)
  631. channel.stateMutex.RLock()
  632. chname := channel.name
  633. chcfname := channel.nameCasefolded
  634. founder := channel.registeredFounder
  635. createdAt := channel.createdTime
  636. chkey := channel.key
  637. limit := channel.userLimit
  638. chcount := len(channel.members)
  639. _, alreadyJoined := channel.members[client]
  640. persistentMode := channel.accountToUMode[details.account]
  641. forward = channel.forward
  642. channel.stateMutex.RUnlock()
  643. if alreadyJoined {
  644. // no message needs to be sent
  645. return nil, ""
  646. }
  647. // 0. SAJOIN always succeeds
  648. // 1. the founder can always join (even if they disabled auto +q on join)
  649. // 2. anyone who automatically receives halfop or higher can always join
  650. // 3. people invited with INVITE can join
  651. hasPrivs := isSajoin || (founder != "" && founder == details.account) ||
  652. (persistentMode != 0 && persistentMode != modes.Voice) ||
  653. client.CheckInvited(chcfname, createdAt)
  654. if !hasPrivs {
  655. if limit != 0 && chcount >= limit {
  656. return errLimitExceeded, forward
  657. }
  658. if chkey != "" && !utils.SecretTokensMatch(chkey, key) {
  659. return errWrongChannelKey, forward
  660. }
  661. // #1901: +h and up exempt from all restrictions, but +v additionally exempts from +i:
  662. if channel.flags.HasMode(modes.InviteOnly) && persistentMode == 0 &&
  663. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  664. return errInviteOnly, forward
  665. }
  666. if channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
  667. !channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) &&
  668. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  669. // do not forward people who are banned:
  670. return errBanned, ""
  671. }
  672. if details.account == "" &&
  673. (channel.flags.HasMode(modes.RegisteredOnly) || channel.server.Defcon() <= 2) &&
  674. !channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
  675. return errRegisteredOnly, forward
  676. }
  677. }
  678. if joinErr := client.addChannel(channel, rb == nil); joinErr != nil {
  679. return joinErr, ""
  680. }
  681. client.server.logger.Debug("channels", fmt.Sprintf("%s joined channel %s", details.nick, chname))
  682. givenMode := func() (givenMode modes.Mode) {
  683. channel.joinPartMutex.Lock()
  684. defer channel.joinPartMutex.Unlock()
  685. func() {
  686. channel.stateMutex.Lock()
  687. defer channel.stateMutex.Unlock()
  688. channel.members.Add(client)
  689. firstJoin := len(channel.members) == 1
  690. newChannel := firstJoin && channel.registeredFounder == ""
  691. if newChannel {
  692. givenMode = modes.ChannelOperator
  693. } else {
  694. givenMode = persistentMode
  695. }
  696. if givenMode != 0 {
  697. channel.members[client].modes.SetMode(givenMode, true)
  698. }
  699. }()
  700. channel.regenerateMembersCache()
  701. return
  702. }()
  703. var message utils.SplitMessage
  704. respectAuditorium := givenMode == modes.Mode(0) && channel.flags.HasMode(modes.Auditorium)
  705. message = utils.MakeMessage("")
  706. // no history item for fake persistent joins
  707. if rb != nil && !respectAuditorium {
  708. histItem := history.Item{
  709. Type: history.Join,
  710. Nick: details.nickMask,
  711. AccountName: details.accountName,
  712. Message: message,
  713. IsBot: isBot,
  714. }
  715. histItem.Params[0] = details.realname
  716. channel.AddHistoryItem(histItem, details.account)
  717. }
  718. if rb == nil {
  719. return nil, ""
  720. }
  721. var modestr string
  722. if givenMode != 0 {
  723. modestr = fmt.Sprintf("+%v", givenMode)
  724. }
  725. // cache the most common case (JOIN without extended-join)
  726. var cache MessageCache
  727. cache.Initialize(channel.server, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
  728. isAway, awayMessage := client.Away()
  729. for _, member := range channel.Members() {
  730. if respectAuditorium {
  731. channel.stateMutex.RLock()
  732. memberData, ok := channel.members[member]
  733. channel.stateMutex.RUnlock()
  734. if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  735. continue
  736. }
  737. }
  738. for _, session := range member.Sessions() {
  739. if session == rb.session {
  740. continue
  741. } else if client == session.client {
  742. channel.playJoinForSession(session)
  743. continue
  744. }
  745. if session.capabilities.Has(caps.ExtendedJoin) {
  746. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
  747. } else {
  748. cache.Send(session)
  749. }
  750. if givenMode != 0 {
  751. session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
  752. }
  753. if isAway && session.capabilities.Has(caps.AwayNotify) {
  754. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.accountName, isBot, nil, "AWAY", awayMessage)
  755. }
  756. }
  757. }
  758. if rb.session.capabilities.Has(caps.ExtendedJoin) {
  759. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
  760. } else {
  761. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
  762. }
  763. if rb.session.capabilities.Has(caps.ReadMarker) {
  764. rb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
  765. }
  766. if rb.session.client == client {
  767. // don't send topic and names for a SAJOIN of a different client
  768. channel.SendTopic(client, rb, false)
  769. if !rb.session.capabilities.Has(caps.NoImplicitNames) {
  770. channel.Names(client, rb)
  771. }
  772. } else {
  773. // ensure that SAJOIN sends a MODE line to the originating client, if applicable
  774. if givenMode != 0 {
  775. rb.Add(nil, client.server.name, "MODE", chname, modestr, details.nick)
  776. }
  777. }
  778. // TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
  779. rb.Flush(true)
  780. channel.autoReplayHistory(client, rb, message.Msgid)
  781. return nil, ""
  782. }
  783. func (channel *Channel) autoReplayHistory(client *Client, rb *ResponseBuffer, skipMsgid string) {
  784. // autoreplay any messages as necessary
  785. var items []history.Item
  786. hasAutoreplayTimestamps := false
  787. var start, end time.Time
  788. if rb.session.zncPlaybackTimes.ValidFor(channel.NameCasefolded()) {
  789. hasAutoreplayTimestamps = true
  790. start, end = rb.session.zncPlaybackTimes.start, rb.session.zncPlaybackTimes.end
  791. } else if !rb.session.autoreplayMissedSince.IsZero() {
  792. // we already checked for history caps in `playReattachMessages`
  793. hasAutoreplayTimestamps = true
  794. start = time.Now().UTC()
  795. end = rb.session.autoreplayMissedSince
  796. }
  797. if hasAutoreplayTimestamps {
  798. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  799. if seq != nil {
  800. zncMax := channel.server.Config().History.ZNCMax
  801. items, _ = seq.Between(history.Selector{Time: start}, history.Selector{Time: end}, zncMax)
  802. }
  803. } else if !rb.session.HasHistoryCaps() {
  804. var replayLimit int
  805. customReplayLimit := client.AccountSettings().AutoreplayLines
  806. if customReplayLimit != nil {
  807. replayLimit = *customReplayLimit
  808. maxLimit := channel.server.Config().History.ChathistoryMax
  809. if maxLimit < replayLimit {
  810. replayLimit = maxLimit
  811. }
  812. } else {
  813. replayLimit = channel.server.Config().History.AutoreplayOnJoin
  814. }
  815. if 0 < replayLimit {
  816. _, seq, _ := channel.server.GetHistorySequence(channel, client, "")
  817. if seq != nil {
  818. items, _ = seq.Between(history.Selector{}, history.Selector{}, replayLimit)
  819. }
  820. }
  821. }
  822. // remove the client's own JOIN line from the replay
  823. numItems := len(items)
  824. for i := len(items) - 1; 0 <= i; i-- {
  825. if items[i].Message.Msgid == skipMsgid {
  826. // zero'ed items will not be replayed because their `Type` field is not recognized
  827. items[i] = history.Item{}
  828. numItems--
  829. break
  830. }
  831. }
  832. if 0 < numItems {
  833. channel.replayHistoryItems(rb, items, false)
  834. rb.Flush(true)
  835. }
  836. }
  837. // plays channel join messages (the JOIN line, topic, and names) to a session.
  838. // this is used when attaching a new session to an existing client that already has
  839. // channels, and also when one session of a client initiates a JOIN and the other
  840. // sessions need to receive the state change
  841. func (channel *Channel) playJoinForSession(session *Session) {
  842. client := session.client
  843. sessionRb := NewResponseBuffer(session)
  844. details := client.Details()
  845. chname := channel.Name()
  846. if session.capabilities.Has(caps.ExtendedJoin) {
  847. sessionRb.Add(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
  848. } else {
  849. sessionRb.Add(nil, details.nickMask, "JOIN", chname)
  850. }
  851. if session.capabilities.Has(caps.ReadMarker) {
  852. chcfname := channel.NameCasefolded()
  853. sessionRb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
  854. }
  855. channel.SendTopic(client, sessionRb, false)
  856. if !session.capabilities.Has(caps.NoImplicitNames) {
  857. channel.Names(client, sessionRb)
  858. }
  859. sessionRb.Send(false)
  860. }
  861. // Part parts the given client from this channel, with the given message.
  862. func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
  863. channel.stateMutex.RLock()
  864. chname := channel.name
  865. clientData, ok := channel.members[client]
  866. channel.stateMutex.RUnlock()
  867. if !ok {
  868. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), chname, client.t("You're not on that channel"))
  869. return
  870. }
  871. channel.Quit(client)
  872. splitMessage := utils.MakeMessage(message)
  873. details := client.Details()
  874. isBot := client.HasMode(modes.Bot)
  875. params := make([]string, 1, 2)
  876. params[0] = chname
  877. if message != "" {
  878. params = append(params, message)
  879. }
  880. respectAuditorium := channel.flags.HasMode(modes.Auditorium) &&
  881. clientData.modes.HighestChannelUserMode() == modes.Mode(0)
  882. var cache MessageCache
  883. cache.Initialize(channel.server, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  884. for _, member := range channel.Members() {
  885. if respectAuditorium {
  886. channel.stateMutex.RLock()
  887. memberData, ok := channel.members[member]
  888. channel.stateMutex.RUnlock()
  889. if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
  890. continue
  891. }
  892. }
  893. for _, session := range member.Sessions() {
  894. cache.Send(session)
  895. }
  896. }
  897. rb.AddFromClient(splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  898. for _, session := range client.Sessions() {
  899. if session != rb.session {
  900. session.sendFromClientInternal(false, splitMessage.Time, splitMessage.Msgid, details.nickMask, details.accountName, isBot, nil, "PART", params...)
  901. }
  902. }
  903. if !respectAuditorium {
  904. channel.AddHistoryItem(history.Item{
  905. Type: history.Part,
  906. Nick: details.nickMask,
  907. AccountName: details.accountName,
  908. Message: splitMessage,
  909. IsBot: isBot,
  910. }, details.account)
  911. }
  912. client.server.logger.Debug("channels", fmt.Sprintf("%s left channel %s", details.nick, chname))
  913. }
  914. func (channel *Channel) replayHistoryItems(rb *ResponseBuffer, items []history.Item, chathistoryCommand bool) {
  915. // send an empty batch if necessary, as per the CHATHISTORY spec
  916. chname := channel.Name()
  917. client := rb.target
  918. eventPlayback := rb.session.capabilities.Has(caps.EventPlayback)
  919. extendedJoin := rb.session.capabilities.Has(caps.ExtendedJoin)
  920. var playJoinsAsPrivmsg bool
  921. if !eventPlayback {
  922. if chathistoryCommand {
  923. playJoinsAsPrivmsg = true
  924. } else {
  925. switch client.AccountSettings().ReplayJoins {
  926. case ReplayJoinsCommandsOnly:
  927. playJoinsAsPrivmsg = false
  928. case ReplayJoinsAlways:
  929. playJoinsAsPrivmsg = true
  930. }
  931. }
  932. }
  933. batchID := rb.StartNestedBatch("chathistory", chname)
  934. defer rb.EndNestedBatch(batchID)
  935. for _, item := range items {
  936. nick := NUHToNick(item.Nick)
  937. switch item.Type {
  938. case history.Privmsg:
  939. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "PRIVMSG", chname, item.Message)
  940. case history.Notice:
  941. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "NOTICE", chname, item.Message)
  942. case history.Tagmsg:
  943. if eventPlayback {
  944. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, item.Tags, "TAGMSG", chname, item.Message)
  945. } else if chathistoryCommand {
  946. // #1676, we have to send something here or else it breaks pagination
  947. 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))
  948. }
  949. case history.Join:
  950. if eventPlayback {
  951. if extendedJoin {
  952. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "JOIN", chname, item.AccountName, item.Params[0])
  953. } else {
  954. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "JOIN", chname)
  955. }
  956. } else {
  957. if !playJoinsAsPrivmsg {
  958. continue // #474
  959. }
  960. var message string
  961. if item.AccountName == "*" {
  962. message = fmt.Sprintf(client.t("%s joined the channel"), nick)
  963. } else {
  964. message = fmt.Sprintf(client.t("%[1]s [account: %[2]s] joined the channel"), nick, item.AccountName)
  965. }
  966. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  967. }
  968. case history.Part:
  969. if eventPlayback {
  970. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "PART", chname, item.Message.Message)
  971. } else {
  972. if !playJoinsAsPrivmsg {
  973. continue // #474
  974. }
  975. message := fmt.Sprintf(client.t("%[1]s left the channel (%[2]s)"), nick, item.Message.Message)
  976. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  977. }
  978. case history.Kick:
  979. if eventPlayback {
  980. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "KICK", chname, item.Params[0], item.Message.Message)
  981. } else {
  982. message := fmt.Sprintf(client.t("%[1]s kicked %[2]s (%[3]s)"), nick, item.Params[0], item.Message.Message)
  983. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  984. }
  985. case history.Quit:
  986. if eventPlayback {
  987. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "QUIT", item.Message.Message)
  988. } else {
  989. if !playJoinsAsPrivmsg {
  990. continue // #474
  991. }
  992. message := fmt.Sprintf(client.t("%[1]s quit (%[2]s)"), nick, item.Message.Message)
  993. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  994. }
  995. case history.Nick:
  996. if eventPlayback {
  997. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "NICK", item.Params[0])
  998. } else {
  999. message := fmt.Sprintf(client.t("%[1]s changed nick to %[2]s"), nick, item.Params[0])
  1000. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1001. }
  1002. case history.Topic:
  1003. if eventPlayback {
  1004. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "TOPIC", chname, item.Message.Message)
  1005. } else {
  1006. message := fmt.Sprintf(client.t("%[1]s set the channel topic to: %[2]s"), nick, item.Message.Message)
  1007. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1008. }
  1009. case history.Mode:
  1010. params := make([]string, len(item.Message.Split)+1)
  1011. params[0] = chname
  1012. for i, pair := range item.Message.Split {
  1013. params[i+1] = pair.Message
  1014. }
  1015. if eventPlayback {
  1016. rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "MODE", params...)
  1017. } else {
  1018. message := fmt.Sprintf(client.t("%[1]s set channel modes: %[2]s"), nick, strings.Join(params[1:], " "))
  1019. rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", chname, message)
  1020. }
  1021. }
  1022. }
  1023. }
  1024. // SendTopic sends the channel topic to the given client.
  1025. // `sendNoTopic` controls whether RPL_NOTOPIC is sent when the topic is unset
  1026. func (channel *Channel) SendTopic(client *Client, rb *ResponseBuffer, sendNoTopic bool) {
  1027. channel.stateMutex.RLock()
  1028. name := channel.name
  1029. topic := channel.topic
  1030. topicSetBy := channel.topicSetBy
  1031. topicSetTime := channel.topicSetTime
  1032. _, hasClient := channel.members[client]
  1033. channel.stateMutex.RUnlock()
  1034. if !hasClient {
  1035. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.name, client.t("You're not on that channel"))
  1036. return
  1037. }
  1038. if topic == "" {
  1039. if sendNoTopic {
  1040. rb.Add(nil, client.server.name, RPL_NOTOPIC, client.nick, name, client.t("No topic is set"))
  1041. }
  1042. return
  1043. }
  1044. rb.Add(nil, client.server.name, RPL_TOPIC, client.nick, name, topic)
  1045. rb.Add(nil, client.server.name, RPL_TOPICTIME, client.nick, name, topicSetBy, strconv.FormatInt(topicSetTime.Unix(), 10))
  1046. }
  1047. // SetTopic sets the topic of this channel, if the client is allowed to do so.
  1048. func (channel *Channel) SetTopic(client *Client, topic string, rb *ResponseBuffer) {
  1049. if !channel.hasClient(client) {
  1050. rb.Add(nil, client.server.name, ERR_NOTONCHANNEL, client.Nick(), channel.Name(), client.t("You're not on that channel"))
  1051. return
  1052. }
  1053. if channel.flags.HasMode(modes.OpOnlyTopic) && !(channel.ClientIsAtLeast(client, modes.Halfop) || client.HasRoleCapabs("samode")) {
  1054. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You're not a channel operator"))
  1055. return
  1056. }
  1057. topic = ircmsg.TruncateUTF8Safe(topic, client.server.Config().Limits.TopicLen)
  1058. channel.stateMutex.Lock()
  1059. chname := channel.name
  1060. channel.topic = topic
  1061. channel.topicSetBy = client.nickMaskString
  1062. channel.topicSetTime = time.Now().UTC()
  1063. channel.stateMutex.Unlock()
  1064. details := client.Details()
  1065. isBot := client.HasMode(modes.Bot)
  1066. message := utils.MakeMessage(topic)
  1067. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "TOPIC", chname, topic)
  1068. for _, member := range channel.Members() {
  1069. for _, session := range member.Sessions() {
  1070. if session != rb.session {
  1071. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "TOPIC", chname, topic)
  1072. }
  1073. }
  1074. }
  1075. channel.AddHistoryItem(history.Item{
  1076. Type: history.Topic,
  1077. Nick: details.nickMask,
  1078. AccountName: details.accountName,
  1079. Message: message,
  1080. IsBot: isBot,
  1081. }, details.account)
  1082. channel.MarkDirty(IncludeTopic)
  1083. }
  1084. // 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.
  1085. func (channel *Channel) CanSpeak(client *Client) (bool, modes.Mode) {
  1086. channel.stateMutex.RLock()
  1087. memberData, hasClient := channel.members[client]
  1088. channel.stateMutex.RUnlock()
  1089. highestMode := func() modes.Mode {
  1090. if !hasClient {
  1091. return modes.Mode(0)
  1092. }
  1093. return memberData.modes.HighestChannelUserMode()
  1094. }
  1095. if !hasClient && channel.flags.HasMode(modes.NoOutside) {
  1096. // TODO: enforce regular +b bans on -n channels?
  1097. return false, modes.NoOutside
  1098. }
  1099. if channel.isMuted(client) && highestMode() == modes.Mode(0) {
  1100. return false, modes.BanMask
  1101. }
  1102. if channel.flags.HasMode(modes.Moderated) && highestMode() == modes.Mode(0) {
  1103. return false, modes.Moderated
  1104. }
  1105. if channel.flags.HasMode(modes.RegisteredOnlySpeak) && client.Account() == "" &&
  1106. highestMode() == modes.Mode(0) {
  1107. return false, modes.RegisteredOnlySpeak
  1108. }
  1109. return true, modes.Mode('?')
  1110. }
  1111. func (channel *Channel) isMuted(client *Client) bool {
  1112. muteRe := channel.lists[modes.BanMask].MuteRegexp()
  1113. if muteRe == nil {
  1114. return false
  1115. }
  1116. nuh := client.NickMaskCasefolded()
  1117. return muteRe.MatchString(nuh) && !channel.lists[modes.ExceptMask].MatchMute(nuh)
  1118. }
  1119. func (channel *Channel) relayNickMuted(relayNick string) bool {
  1120. relayNUH := fmt.Sprintf("%s!*@*", relayNick)
  1121. return channel.lists[modes.BanMask].MatchMute(relayNUH) &&
  1122. !channel.lists[modes.ExceptMask].MatchMute(relayNUH)
  1123. }
  1124. func msgCommandToHistType(command string) (history.ItemType, error) {
  1125. switch command {
  1126. case "PRIVMSG":
  1127. return history.Privmsg, nil
  1128. case "NOTICE":
  1129. return history.Notice, nil
  1130. case "TAGMSG":
  1131. return history.Tagmsg, nil
  1132. default:
  1133. return history.ItemType(0), errInvalidParams
  1134. }
  1135. }
  1136. func (channel *Channel) SendSplitMessage(command string, minPrefixMode modes.Mode, clientOnlyTags map[string]string, client *Client, message utils.SplitMessage, rb *ResponseBuffer) {
  1137. histType, err := msgCommandToHistType(command)
  1138. if err != nil {
  1139. return
  1140. }
  1141. if canSpeak, mode := channel.CanSpeak(client); !canSpeak {
  1142. if histType != history.Notice {
  1143. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), mode))
  1144. }
  1145. return
  1146. }
  1147. isCTCP := message.IsRestrictedCTCPMessage()
  1148. if isCTCP && channel.flags.HasMode(modes.NoCTCP) {
  1149. if histType != history.Notice {
  1150. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, client.Nick(), channel.Name(), fmt.Sprintf(client.t("Cannot send to channel (+%s)"), "C"))
  1151. }
  1152. return
  1153. }
  1154. details := client.Details()
  1155. isBot := client.HasMode(modes.Bot)
  1156. chname := channel.Name()
  1157. if !client.server.Config().Server.Compatibility.allowTruncation {
  1158. if !validateSplitMessageLen(histType, details.nickMask, chname, message) {
  1159. rb.Add(nil, client.server.name, ERR_INPUTTOOLONG, details.nick, client.t("Line too long to be relayed without truncation"))
  1160. return
  1161. }
  1162. }
  1163. // STATUSMSG targets are prefixed with the supplied min-prefix, e.g., @#channel
  1164. if minPrefixMode != modes.Mode(0) {
  1165. chname = fmt.Sprintf("%s%s", modes.ChannelModePrefixes[minPrefixMode], chname)
  1166. }
  1167. if channel.flags.HasMode(modes.OpModerated) {
  1168. channel.stateMutex.RLock()
  1169. cuData, ok := channel.members[client]
  1170. channel.stateMutex.RUnlock()
  1171. if !ok || cuData.modes.HighestChannelUserMode() == modes.Mode(0) {
  1172. // max(statusmsg_minmode, halfop)
  1173. if minPrefixMode == modes.Mode(0) || minPrefixMode == modes.Voice {
  1174. minPrefixMode = modes.Halfop
  1175. }
  1176. }
  1177. }
  1178. // send echo-message
  1179. rb.addEchoMessage(clientOnlyTags, details.nickMask, details.accountName, command, chname, message)
  1180. var cache MessageCache
  1181. cache.InitializeSplitMessage(channel.server, details.nickMask, details.accountName, isBot, clientOnlyTags, command, chname, message)
  1182. for _, member := range channel.Members() {
  1183. if minPrefixMode != modes.Mode(0) && !channel.ClientIsAtLeast(member, minPrefixMode) {
  1184. // STATUSMSG or OpModerated
  1185. continue
  1186. }
  1187. for _, session := range member.Sessions() {
  1188. if session == rb.session {
  1189. continue // we already sent echo-message, if applicable
  1190. }
  1191. if isCTCP && session.isTor {
  1192. continue // #753
  1193. }
  1194. cache.Send(session)
  1195. }
  1196. }
  1197. // #959: don't save STATUSMSG (or OpModerated)
  1198. if minPrefixMode == modes.Mode(0) {
  1199. channel.AddHistoryItem(history.Item{
  1200. Type: histType,
  1201. Message: message,
  1202. Nick: details.nickMask,
  1203. AccountName: details.accountName,
  1204. Tags: clientOnlyTags,
  1205. IsBot: isBot,
  1206. }, details.account)
  1207. }
  1208. }
  1209. func (channel *Channel) applyModeToMember(client *Client, change modes.ModeChange, rb *ResponseBuffer) (applied bool, result modes.ModeChange) {
  1210. target := channel.server.clients.Get(change.Arg)
  1211. if target == nil {
  1212. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(change.Arg), client.t("No such nick"))
  1213. return
  1214. }
  1215. change.Arg = target.Nick()
  1216. channel.stateMutex.Lock()
  1217. memberData, exists := channel.members[target]
  1218. if exists {
  1219. if memberData.modes.SetMode(change.Mode, change.Op == modes.Add) {
  1220. applied = true
  1221. result = change
  1222. }
  1223. }
  1224. channel.stateMutex.Unlock()
  1225. if !exists {
  1226. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1227. }
  1228. if applied {
  1229. target.markDirty(IncludeChannels)
  1230. }
  1231. return
  1232. }
  1233. // ShowMaskList shows the given list to the client.
  1234. func (channel *Channel) ShowMaskList(client *Client, mode modes.Mode, rb *ResponseBuffer) {
  1235. // choose appropriate modes
  1236. var rpllist, rplendoflist string
  1237. if mode == modes.BanMask {
  1238. rpllist = RPL_BANLIST
  1239. rplendoflist = RPL_ENDOFBANLIST
  1240. } else if mode == modes.ExceptMask {
  1241. rpllist = RPL_EXCEPTLIST
  1242. rplendoflist = RPL_ENDOFEXCEPTLIST
  1243. } else if mode == modes.InviteMask {
  1244. rpllist = RPL_INVITELIST
  1245. rplendoflist = RPL_ENDOFINVITELIST
  1246. }
  1247. nick := client.Nick()
  1248. chname := channel.Name()
  1249. for mask, info := range channel.lists[mode].Masks() {
  1250. rb.Add(nil, client.server.name, rpllist, nick, chname, mask, info.CreatorNickmask, strconv.FormatInt(info.TimeCreated.Unix(), 10))
  1251. }
  1252. rb.Add(nil, client.server.name, rplendoflist, nick, chname, client.t("End of list"))
  1253. }
  1254. // Quit removes the given client from the channel
  1255. func (channel *Channel) Quit(client *Client) {
  1256. channelEmpty := func() bool {
  1257. channel.joinPartMutex.Lock()
  1258. defer channel.joinPartMutex.Unlock()
  1259. channel.stateMutex.Lock()
  1260. channel.members.Remove(client)
  1261. channelEmpty := len(channel.members) == 0
  1262. channel.stateMutex.Unlock()
  1263. channel.regenerateMembersCache()
  1264. return channelEmpty
  1265. }()
  1266. if channelEmpty {
  1267. client.server.channels.Cleanup(channel)
  1268. }
  1269. client.removeChannel(channel)
  1270. }
  1271. func (channel *Channel) Kick(client *Client, target *Client, comment string, rb *ResponseBuffer, hasPrivs bool) {
  1272. if !hasPrivs {
  1273. if !channel.ClientHasPrivsOver(client, target) {
  1274. rb.Add(nil, client.server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), channel.Name(), client.t("You don't have enough channel privileges"))
  1275. return
  1276. }
  1277. }
  1278. if !channel.hasClient(target) {
  1279. rb.Add(nil, client.server.name, ERR_USERNOTINCHANNEL, client.Nick(), channel.Name(), client.t("They aren't on that channel"))
  1280. return
  1281. }
  1282. comment = ircmsg.TruncateUTF8Safe(comment, channel.server.Config().Limits.KickLen)
  1283. message := utils.MakeMessage(comment)
  1284. details := client.Details()
  1285. isBot := client.HasMode(modes.Bot)
  1286. targetNick := target.Nick()
  1287. chname := channel.Name()
  1288. for _, member := range channel.Members() {
  1289. for _, session := range member.Sessions() {
  1290. if session != rb.session {
  1291. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "KICK", chname, targetNick, comment)
  1292. }
  1293. }
  1294. }
  1295. rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "KICK", chname, targetNick, comment)
  1296. histItem := history.Item{
  1297. Type: history.Kick,
  1298. Nick: details.nickMask,
  1299. AccountName: details.accountName,
  1300. Message: message,
  1301. IsBot: isBot,
  1302. }
  1303. histItem.Params[0] = targetNick
  1304. channel.AddHistoryItem(histItem, details.account)
  1305. channel.Quit(target)
  1306. }
  1307. // handle a purge: kick everyone off the channel, clean up all the pointers between
  1308. // *Channel and *Client
  1309. func (channel *Channel) Purge(source string) {
  1310. if source == "" {
  1311. source = channel.server.name
  1312. }
  1313. channel.stateMutex.Lock()
  1314. chname := channel.name
  1315. members := channel.membersCache
  1316. channel.membersCache = nil
  1317. channel.memberDataCache = nil
  1318. channel.members = make(MemberSet)
  1319. // TODO try to prevent Purge racing against (pending) Join?
  1320. channel.stateMutex.Unlock()
  1321. now := time.Now().UTC()
  1322. for _, member := range members {
  1323. tnick := member.Nick()
  1324. msgid := utils.GenerateSecretToken()
  1325. for _, session := range member.Sessions() {
  1326. 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"))
  1327. }
  1328. member.removeChannel(channel)
  1329. }
  1330. }
  1331. // Invite invites the given client to the channel, if the inviter can do so.
  1332. func (channel *Channel) Invite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1333. channel.stateMutex.RLock()
  1334. chname := channel.name
  1335. chcfname := channel.nameCasefolded
  1336. createdAt := channel.createdTime
  1337. _, inviterPresent := channel.members[inviter]
  1338. _, inviteePresent := channel.members[invitee]
  1339. channel.stateMutex.RUnlock()
  1340. if !inviterPresent {
  1341. rb.Add(nil, inviter.server.name, ERR_NOTONCHANNEL, inviter.Nick(), chname, inviter.t("You're not on that channel"))
  1342. return
  1343. }
  1344. inviteOnly := channel.flags.HasMode(modes.InviteOnly)
  1345. hasPrivs := channel.ClientIsAtLeast(inviter, modes.ChannelOperator)
  1346. if inviteOnly && !hasPrivs {
  1347. rb.Add(nil, inviter.server.name, ERR_CHANOPRIVSNEEDED, inviter.Nick(), chname, inviter.t("You're not a channel operator"))
  1348. return
  1349. }
  1350. if inviteePresent {
  1351. rb.Add(nil, inviter.server.name, ERR_USERONCHANNEL, inviter.Nick(), invitee.Nick(), chname, inviter.t("User is already on that channel"))
  1352. return
  1353. }
  1354. // #1876: INVITE should override all join restrictions, including +b and +l,
  1355. // not just +i. so we need to record it on a per-client basis iff the inviter
  1356. // is privileged:
  1357. if hasPrivs {
  1358. invitee.Invite(chcfname, createdAt)
  1359. }
  1360. details := inviter.Details()
  1361. isBot := inviter.HasMode(modes.Bot)
  1362. tDetails := invitee.Details()
  1363. tnick := invitee.Nick()
  1364. message := utils.MakeMessage(chname)
  1365. item := history.Item{
  1366. Type: history.Invite,
  1367. Message: message,
  1368. }
  1369. for _, member := range channel.Members() {
  1370. if member == inviter || member == invitee || !channel.ClientIsAtLeast(member, modes.Halfop) {
  1371. continue
  1372. }
  1373. for _, session := range member.Sessions() {
  1374. if session.capabilities.Has(caps.InviteNotify) {
  1375. session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "INVITE", tnick, chname)
  1376. }
  1377. }
  1378. }
  1379. rb.Add(nil, inviter.server.name, RPL_INVITING, details.nick, tnick, chname)
  1380. for _, iSession := range invitee.Sessions() {
  1381. iSession.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "INVITE", tnick, chname)
  1382. }
  1383. if away, awayMessage := invitee.Away(); away {
  1384. rb.Add(nil, inviter.server.name, RPL_AWAY, details.nick, tnick, awayMessage)
  1385. }
  1386. inviter.addHistoryItem(invitee, item, &details, &tDetails, channel.server.Config())
  1387. }
  1388. // Uninvite rescinds a channel invitation, if the inviter can do so.
  1389. func (channel *Channel) Uninvite(invitee *Client, inviter *Client, rb *ResponseBuffer) {
  1390. if !channel.flags.HasMode(modes.InviteOnly) {
  1391. rb.Add(nil, channel.server.name, "FAIL", "UNINVITE", "NOT_INVITE_ONLY", channel.Name(), inviter.t("Channel is not invite-only"))
  1392. return
  1393. }
  1394. if !channel.ClientIsAtLeast(inviter, modes.ChannelOperator) {
  1395. rb.Add(nil, channel.server.name, "FAIL", "UNINVITE", "PRIVS_NEEDED", channel.Name(), inviter.t("You're not a channel operator"))
  1396. return
  1397. }
  1398. invitee.Uninvite(channel.NameCasefolded())
  1399. rb.Add(nil, channel.server.name, "UNINVITE", invitee.Nick(), channel.Name())
  1400. }
  1401. // returns who the client can "see" in the channel, respecting the auditorium mode
  1402. func (channel *Channel) auditoriumFriends(client *Client) (friends []*Client) {
  1403. channel.stateMutex.RLock()
  1404. defer channel.stateMutex.RUnlock()
  1405. clientData, found := channel.members[client]
  1406. if !found {
  1407. return // non-members have no friends
  1408. }
  1409. if !channel.flags.HasMode(modes.Auditorium) {
  1410. return channel.membersCache // default behavior for members
  1411. }
  1412. if clientData.modes.HighestChannelUserMode() != modes.Mode(0) {
  1413. return channel.membersCache // +v and up can see everyone in the auditorium
  1414. }
  1415. // without +v, your friends are those with +v and up
  1416. for member, memberData := range channel.members {
  1417. if memberData.modes.HighestChannelUserMode() != modes.Mode(0) {
  1418. friends = append(friends, member)
  1419. }
  1420. }
  1421. return
  1422. }
  1423. // data for RPL_LIST
  1424. func (channel *Channel) listData() (memberCount int, name, topic string) {
  1425. channel.stateMutex.RLock()
  1426. defer channel.stateMutex.RUnlock()
  1427. return len(channel.members), channel.name, channel.topic
  1428. }