Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

channel.go 52KB

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