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

channel.go 53KB

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