Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

client.go 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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. "net"
  9. "runtime/debug"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/goshuirc/irc-go/ircfmt"
  16. "github.com/goshuirc/irc-go/ircmsg"
  17. ident "github.com/oragono/go-ident"
  18. "github.com/oragono/oragono/irc/caps"
  19. "github.com/oragono/oragono/irc/connection_limits"
  20. "github.com/oragono/oragono/irc/history"
  21. "github.com/oragono/oragono/irc/modes"
  22. "github.com/oragono/oragono/irc/sno"
  23. "github.com/oragono/oragono/irc/utils"
  24. )
  25. const (
  26. // IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
  27. IdentTimeoutSeconds = 1.5
  28. IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
  29. )
  30. // ResumeDetails is a place to stash data at various stages of
  31. // the resume process: when handling the RESUME command itself,
  32. // when completing the registration, and when rejoining channels.
  33. type ResumeDetails struct {
  34. PresentedToken string
  35. Timestamp time.Time
  36. HistoryIncomplete bool
  37. }
  38. // Client is an IRC client.
  39. type Client struct {
  40. account string
  41. accountName string // display name of the account: uncasefolded, '*' if not logged in
  42. accountSettings AccountSettings
  43. atime time.Time
  44. away bool
  45. awayMessage string
  46. brbTimer BrbTimer
  47. certfp string
  48. channels ChannelSet
  49. ctime time.Time
  50. destroyed bool
  51. exitedSnomaskSent bool
  52. flags modes.ModeSet
  53. hostname string
  54. invitedTo map[string]bool
  55. isSTSOnly bool
  56. isTor bool
  57. languages []string
  58. loginThrottle connection_limits.GenericThrottle
  59. nick string
  60. nickCasefolded string
  61. nickMaskCasefolded string
  62. nickMaskString string // cache for nickmask string since it's used with lots of replies
  63. nickTimer NickTimer
  64. oper *Oper
  65. preregNick string
  66. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  67. rawHostname string
  68. cloakedHostname string
  69. realname string
  70. realIP net.IP
  71. registered bool
  72. resumeID string
  73. saslInProgress bool
  74. saslMechanism string
  75. saslValue string
  76. sentPassCommand bool
  77. server *Server
  78. skeleton string
  79. sessions []*Session
  80. stateMutex sync.RWMutex // tier 1
  81. username string
  82. vhost string
  83. history history.Buffer
  84. }
  85. // Session is an individual client connection to the server (TCP connection
  86. // and associated per-connection data, such as capabilities). There is a
  87. // many-one relationship between sessions and clients.
  88. type Session struct {
  89. client *Client
  90. ctime time.Time
  91. atime time.Time
  92. socket *Socket
  93. realIP net.IP
  94. proxiedIP net.IP
  95. rawHostname string
  96. idletimer IdleTimer
  97. fakelag Fakelag
  98. destroyed uint32
  99. batchCounter uint32
  100. quitMessage string
  101. capabilities caps.Set
  102. maxlenRest uint32
  103. capState caps.State
  104. capVersion caps.Version
  105. registrationMessages int
  106. resumeID string
  107. resumeDetails *ResumeDetails
  108. zncPlaybackTimes *zncPlaybackTimes
  109. batch MultilineBatch
  110. }
  111. // MultilineBatch tracks the state of a client-to-server multiline batch.
  112. type MultilineBatch struct {
  113. label string // this is the first param to BATCH (the "reference tag")
  114. command string
  115. target string
  116. responseLabel string // this is the value of the labeled-response tag sent with BATCH
  117. message utils.SplitMessage
  118. tags map[string]string
  119. }
  120. // sets the session quit message, if there isn't one already
  121. func (sd *Session) SetQuitMessage(message string) (set bool) {
  122. if message == "" {
  123. message = "Connection closed"
  124. }
  125. if sd.quitMessage == "" {
  126. sd.quitMessage = message
  127. return true
  128. } else {
  129. return false
  130. }
  131. }
  132. // set the negotiated message length based on session capabilities
  133. func (session *Session) SetMaxlenRest() {
  134. maxlenRest := 512
  135. if session.capabilities.Has(caps.MaxLine) {
  136. maxlenRest = session.client.server.Config().Limits.LineLen.Rest
  137. }
  138. atomic.StoreUint32(&session.maxlenRest, uint32(maxlenRest))
  139. }
  140. // allow the negotiated message length limit to be read without locks; this is a convenience
  141. // so that Session.SendRawMessage doesn't have to acquire any Client locks
  142. func (session *Session) MaxlenRest() int {
  143. return int(atomic.LoadUint32(&session.maxlenRest))
  144. }
  145. // returns whether the session was actively destroyed (for example, by ping
  146. // timeout or NS GHOST).
  147. // avoids a race condition between asynchronous idle-timing-out of sessions,
  148. // and a condition that allows implicit BRB on connection errors (since
  149. // destroy()'s socket.Close() appears to socket.Read() as a connection error)
  150. func (session *Session) Destroyed() bool {
  151. return atomic.LoadUint32(&session.destroyed) == 1
  152. }
  153. // sets the timed-out flag
  154. func (session *Session) SetDestroyed() {
  155. atomic.StoreUint32(&session.destroyed, 1)
  156. }
  157. // returns whether the client supports a smart history replay cap,
  158. // and therefore autoreplay-on-join and similar should be suppressed
  159. func (session *Session) HasHistoryCaps() bool {
  160. // TODO the chathistory cap will go here as well
  161. return session.capabilities.Has(caps.ZNCPlayback)
  162. }
  163. // generates a batch ID. the uniqueness requirements for this are fairly weak:
  164. // any two batch IDs that are active concurrently (either through interleaving
  165. // or nesting) on an individual session connection need to be unique.
  166. // this allows ~4 billion such batches which should be fine.
  167. func (session *Session) generateBatchID() string {
  168. id := atomic.AddUint32(&session.batchCounter, 1)
  169. return strconv.Itoa(int(id))
  170. }
  171. // WhoWas is the subset of client details needed to answer a WHOWAS query
  172. type WhoWas struct {
  173. nick string
  174. nickCasefolded string
  175. username string
  176. hostname string
  177. realname string
  178. }
  179. // ClientDetails is a standard set of details about a client
  180. type ClientDetails struct {
  181. WhoWas
  182. nickMask string
  183. nickMaskCasefolded string
  184. account string
  185. accountName string
  186. }
  187. // RunClient sets up a new client and runs its goroutine.
  188. func (server *Server) RunClient(conn clientConn, proxyLine string) {
  189. var isBanned bool
  190. var banMsg string
  191. var realIP net.IP
  192. if conn.Config.Tor {
  193. realIP = utils.IPv4LoopbackAddress
  194. isBanned, banMsg = server.checkTorLimits()
  195. } else {
  196. realIP = utils.AddrToIP(conn.Conn.RemoteAddr())
  197. isBanned, banMsg = server.checkBans(realIP)
  198. }
  199. if isBanned {
  200. // this might not show up properly on some clients,
  201. // but our objective here is just to close the connection out before it has a load impact on us
  202. conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
  203. conn.Conn.Close()
  204. return
  205. }
  206. server.logger.Info("localconnect-ip", fmt.Sprintf("Client connecting from %v", realIP))
  207. now := time.Now().UTC()
  208. config := server.Config()
  209. fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
  210. // give them 1k of grace over the limit:
  211. socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
  212. client := &Client{
  213. atime: now,
  214. channels: make(ChannelSet),
  215. ctime: now,
  216. isSTSOnly: conn.Config.STSOnly,
  217. isTor: conn.Config.Tor,
  218. languages: server.Languages().Default(),
  219. loginThrottle: connection_limits.GenericThrottle{
  220. Duration: config.Accounts.LoginThrottling.Duration,
  221. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  222. },
  223. server: server,
  224. accountName: "*",
  225. nick: "*", // * is used until actual nick is given
  226. nickCasefolded: "*",
  227. nickMaskString: "*", // * is used until actual nick is given
  228. }
  229. client.history.Initialize(config.History.ClientLength, config.History.AutoresizeWindow)
  230. client.brbTimer.Initialize(client)
  231. session := &Session{
  232. client: client,
  233. socket: socket,
  234. capVersion: caps.Cap301,
  235. capState: caps.NoneState,
  236. ctime: now,
  237. atime: now,
  238. realIP: realIP,
  239. }
  240. session.SetMaxlenRest()
  241. client.sessions = []*Session{session}
  242. if conn.Config.TLSConfig != nil {
  243. client.SetMode(modes.TLS, true)
  244. // error is not useful to us here anyways so we can ignore it
  245. client.certfp, _ = socket.CertFP()
  246. }
  247. if conn.Config.Tor {
  248. client.SetMode(modes.TLS, true)
  249. // cover up details of the tor proxying infrastructure (not a user privacy concern,
  250. // but a hardening measure):
  251. session.proxiedIP = utils.IPv4LoopbackAddress
  252. client.proxiedIP = session.proxiedIP
  253. session.rawHostname = config.Server.TorListeners.Vhost
  254. client.rawHostname = session.rawHostname
  255. } else {
  256. remoteAddr := conn.Conn.RemoteAddr()
  257. if utils.AddrIsLocal(remoteAddr) {
  258. // treat local connections as secure (may be overridden later by WEBIRC)
  259. client.SetMode(modes.TLS, true)
  260. }
  261. if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
  262. client.doIdentLookup(conn.Conn)
  263. }
  264. }
  265. client.realIP = session.realIP
  266. server.stats.Add()
  267. client.run(session, proxyLine)
  268. }
  269. // resolve an IP to an IRC-ready hostname, using reverse DNS, forward-confirming if necessary,
  270. // and sending appropriate notices to the client
  271. func (client *Client) lookupHostname(session *Session, overwrite bool) {
  272. if client.isTor {
  273. return
  274. } // else: even if cloaking is enabled, look up the real hostname to show to operators
  275. config := client.server.Config()
  276. ip := session.realIP
  277. if session.proxiedIP != nil {
  278. ip = session.proxiedIP
  279. }
  280. ipString := ip.String()
  281. var hostname, candidate string
  282. if config.Server.lookupHostnames {
  283. session.Notice("*** Looking up your hostname...")
  284. names, err := net.LookupAddr(ipString)
  285. if err == nil && 0 < len(names) {
  286. candidate = strings.TrimSuffix(names[0], ".")
  287. }
  288. if utils.IsHostname(candidate) {
  289. if config.Server.ForwardConfirmHostnames {
  290. addrs, err := net.LookupHost(candidate)
  291. if err == nil {
  292. for _, addr := range addrs {
  293. if addr == ipString {
  294. hostname = candidate // successful forward confirmation
  295. break
  296. }
  297. }
  298. }
  299. } else {
  300. hostname = candidate
  301. }
  302. }
  303. }
  304. if hostname != "" {
  305. session.Notice("*** Found your hostname")
  306. } else {
  307. if config.Server.lookupHostnames {
  308. session.Notice("*** Couldn't look up your hostname")
  309. }
  310. hostname = utils.IPStringToHostname(ipString)
  311. }
  312. session.rawHostname = hostname
  313. cloakedHostname := config.Server.Cloaks.ComputeCloak(ip)
  314. client.stateMutex.Lock()
  315. defer client.stateMutex.Unlock()
  316. // update the hostname if this is a new connection or a resume, but not if it's a reattach
  317. if overwrite || client.rawHostname == "" {
  318. client.rawHostname = hostname
  319. client.cloakedHostname = cloakedHostname
  320. client.updateNickMaskNoMutex()
  321. }
  322. }
  323. func (client *Client) doIdentLookup(conn net.Conn) {
  324. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  325. if err != nil {
  326. client.server.logger.Error("internal", "bad server address", err.Error())
  327. return
  328. }
  329. serverPort, _ := strconv.Atoi(serverPortString)
  330. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  331. if err != nil {
  332. client.server.logger.Error("internal", "bad client address", err.Error())
  333. return
  334. }
  335. clientPort, _ := strconv.Atoi(clientPortString)
  336. client.Notice(client.t("*** Looking up your username"))
  337. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  338. if err == nil {
  339. err := client.SetNames(resp.Identifier, "", true)
  340. if err == nil {
  341. client.Notice(client.t("*** Found your username"))
  342. // we don't need to updateNickMask here since nickMask is not used for anything yet
  343. } else {
  344. client.Notice(client.t("*** Got a malformed username, ignoring"))
  345. }
  346. } else {
  347. client.Notice(client.t("*** Could not find your username"))
  348. }
  349. }
  350. type AuthOutcome uint
  351. const (
  352. authSuccess AuthOutcome = iota
  353. authFailPass
  354. authFailTorSaslRequired
  355. authFailSaslRequired
  356. )
  357. func (client *Client) isAuthorized(config *Config) AuthOutcome {
  358. saslSent := client.account != ""
  359. // PASS requirement
  360. if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
  361. return authFailPass
  362. }
  363. // Tor connections may be required to authenticate with SASL
  364. if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
  365. return authFailTorSaslRequired
  366. }
  367. // finally, enforce require-sasl
  368. if config.Accounts.RequireSasl.Enabled && !saslSent && !utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets) {
  369. return authFailSaslRequired
  370. }
  371. return authSuccess
  372. }
  373. func (session *Session) resetFakelag() {
  374. var flc FakelagConfig = session.client.server.Config().Fakelag
  375. flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
  376. session.fakelag.Initialize(flc)
  377. }
  378. // IP returns the IP address of this client.
  379. func (client *Client) IP() net.IP {
  380. client.stateMutex.RLock()
  381. defer client.stateMutex.RUnlock()
  382. if client.proxiedIP != nil {
  383. return client.proxiedIP
  384. }
  385. return client.realIP
  386. }
  387. // IPString returns the IP address of this client as a string.
  388. func (client *Client) IPString() string {
  389. ip := client.IP().String()
  390. if 0 < len(ip) && ip[0] == ':' {
  391. ip = "0" + ip
  392. }
  393. return ip
  394. }
  395. // t returns the translated version of the given string, based on the languages configured by the client.
  396. func (client *Client) t(originalString string) string {
  397. languageManager := client.server.Config().languageManager
  398. if !languageManager.Enabled() {
  399. return originalString
  400. }
  401. return languageManager.Translate(client.Languages(), originalString)
  402. }
  403. // main client goroutine: read lines and execute the corresponding commands
  404. // `proxyLine` is the PROXY-before-TLS line, if there was one
  405. func (client *Client) run(session *Session, proxyLine string) {
  406. defer func() {
  407. if r := recover(); r != nil {
  408. client.server.logger.Error("internal",
  409. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  410. if client.server.Config().Debug.recoverFromErrors {
  411. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  412. } else {
  413. panic(r)
  414. }
  415. }
  416. // ensure client connection gets closed
  417. client.destroy(session)
  418. }()
  419. session.idletimer.Initialize(session)
  420. session.resetFakelag()
  421. isReattach := client.Registered()
  422. if isReattach {
  423. if session.resumeDetails != nil {
  424. session.playResume()
  425. session.resumeDetails = nil
  426. client.brbTimer.Disable()
  427. client.SetAway(false, "") // clear BRB message if any
  428. } else {
  429. client.playReattachMessages(session)
  430. }
  431. } else {
  432. // don't reset the nick timer during a reattach
  433. client.nickTimer.Initialize(client)
  434. }
  435. firstLine := !isReattach
  436. for {
  437. maxlenRest := session.MaxlenRest()
  438. var line string
  439. var err error
  440. if proxyLine == "" {
  441. line, err = session.socket.Read()
  442. } else {
  443. line = proxyLine // pretend we're just now receiving the proxy-before-TLS line
  444. proxyLine = ""
  445. }
  446. if err != nil {
  447. quitMessage := "connection closed"
  448. if err == errReadQ {
  449. quitMessage = "readQ exceeded"
  450. }
  451. client.Quit(quitMessage, session)
  452. // since the client did not actually send us a QUIT,
  453. // give them a chance to resume if applicable:
  454. if !session.Destroyed() {
  455. client.brbTimer.Enable()
  456. }
  457. break
  458. }
  459. if client.server.logger.IsLoggingRawIO() {
  460. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  461. }
  462. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  463. if firstLine {
  464. firstLine = false
  465. if strings.HasPrefix(line, "PROXY") {
  466. err = handleProxyCommand(client.server, client, session, line)
  467. if err != nil {
  468. break
  469. } else {
  470. continue
  471. }
  472. }
  473. }
  474. if client.registered {
  475. session.fakelag.Touch()
  476. } else {
  477. // DoS hardening, #505
  478. session.registrationMessages++
  479. if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
  480. client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
  481. break
  482. }
  483. }
  484. msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
  485. if err == ircmsg.ErrorLineIsEmpty {
  486. continue
  487. } else if err == ircmsg.ErrorLineTooLong {
  488. session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
  489. continue
  490. } else if err != nil {
  491. client.Quit(client.t("Received malformed line"), session)
  492. break
  493. }
  494. // "Clients MUST NOT send messages other than PRIVMSG while a multiline batch is open."
  495. // in future we might want to whitelist some commands that are allowed here, like PONG
  496. if session.batch.label != "" && msg.Command != "BATCH" {
  497. _, batchTag := msg.GetTag("batch")
  498. if batchTag != session.batch.label {
  499. if msg.Command != "NOTICE" {
  500. session.Send(nil, client.server.name, "FAIL", "BATCH", "MULTILINE_INVALID", client.t("Incorrect batch tag sent"))
  501. }
  502. session.batch = MultilineBatch{}
  503. continue
  504. }
  505. }
  506. cmd, exists := Commands[msg.Command]
  507. if !exists {
  508. if len(msg.Command) > 0 {
  509. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
  510. } else {
  511. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
  512. }
  513. continue
  514. }
  515. isExiting := cmd.Run(client.server, client, session, msg)
  516. if isExiting {
  517. break
  518. } else if session.client != client {
  519. // bouncer reattach
  520. go session.client.run(session, "")
  521. break
  522. }
  523. }
  524. }
  525. func (client *Client) playReattachMessages(session *Session) {
  526. client.server.playRegistrationBurst(session)
  527. for _, channel := range session.client.Channels() {
  528. channel.playJoinForSession(session)
  529. // clients should receive autoreplay-on-join lines, if applicable;
  530. // if they negotiated znc.in/playback or chathistory, they will receive nothing,
  531. // because those caps disable autoreplay-on-join and they haven't sent the relevant
  532. // *playback PRIVMSG or CHATHISTORY command yet
  533. rb := NewResponseBuffer(session)
  534. channel.autoReplayHistory(client, rb, "")
  535. rb.Send(true)
  536. }
  537. }
  538. //
  539. // idle, quit, timers and timeouts
  540. //
  541. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  542. func (client *Client) Active(session *Session) {
  543. now := time.Now().UTC()
  544. client.stateMutex.Lock()
  545. defer client.stateMutex.Unlock()
  546. session.atime = now
  547. client.atime = now
  548. }
  549. // Ping sends the client a PING message.
  550. func (session *Session) Ping() {
  551. session.Send(nil, "", "PING", session.client.Nick())
  552. }
  553. // tryResume tries to resume if the client asked us to.
  554. func (session *Session) tryResume() (success bool) {
  555. var oldResumeID string
  556. defer func() {
  557. if success {
  558. // "On a successful request, the server [...] terminates the old client's connection"
  559. oldSession := session.client.GetSessionByResumeID(oldResumeID)
  560. if oldSession != nil {
  561. session.client.destroy(oldSession)
  562. }
  563. } else {
  564. session.resumeDetails = nil
  565. }
  566. }()
  567. client := session.client
  568. server := client.server
  569. config := server.Config()
  570. oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
  571. if oldClient == nil {
  572. session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
  573. return
  574. }
  575. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  576. if !resumeAllowed {
  577. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
  578. return
  579. }
  580. if oldClient.isTor != client.isTor {
  581. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
  582. return
  583. }
  584. err := server.clients.Resume(oldClient, session)
  585. if err != nil {
  586. session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
  587. return
  588. }
  589. success = true
  590. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
  591. return
  592. }
  593. // playResume is called from the session's fresh goroutine after a resume;
  594. // it sends notifications to friends, then plays the registration burst and replays
  595. // stored history to the session
  596. func (session *Session) playResume() {
  597. client := session.client
  598. server := client.server
  599. friends := make(ClientSet)
  600. oldestLostMessage := time.Now().UTC()
  601. // work out how much time, if any, is not covered by history buffers
  602. for _, channel := range client.Channels() {
  603. for _, member := range channel.Members() {
  604. friends.Add(member)
  605. lastDiscarded := channel.history.LastDiscarded()
  606. if lastDiscarded.Before(oldestLostMessage) {
  607. oldestLostMessage = lastDiscarded
  608. }
  609. }
  610. }
  611. privmsgMatcher := func(item history.Item) bool {
  612. return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
  613. }
  614. privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
  615. lastDiscarded := client.history.LastDiscarded()
  616. if lastDiscarded.Before(oldestLostMessage) {
  617. oldestLostMessage = lastDiscarded
  618. }
  619. for _, item := range privmsgHistory {
  620. sender := server.clients.Get(stripMaskFromNick(item.Nick))
  621. if sender != nil {
  622. friends.Add(sender)
  623. }
  624. }
  625. timestamp := session.resumeDetails.Timestamp
  626. gap := lastDiscarded.Sub(timestamp)
  627. session.resumeDetails.HistoryIncomplete = gap > 0 || timestamp.IsZero()
  628. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  629. details := client.Details()
  630. oldNickmask := details.nickMask
  631. client.lookupHostname(session, true)
  632. hostname := client.Hostname() // may be a vhost
  633. timestampString := timestamp.Format(IRCv3TimestampFormat)
  634. // send quit/resume messages to friends
  635. for friend := range friends {
  636. if friend == client {
  637. continue
  638. }
  639. for _, fSession := range friend.Sessions() {
  640. if fSession.capabilities.Has(caps.Resume) {
  641. if !session.resumeDetails.HistoryIncomplete {
  642. fSession.Send(nil, oldNickmask, "RESUMED", hostname, "ok")
  643. } else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  644. fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
  645. } else {
  646. fSession.Send(nil, oldNickmask, "RESUMED", hostname)
  647. }
  648. } else {
  649. if !session.resumeDetails.HistoryIncomplete {
  650. fSession.Send(nil, oldNickmask, "QUIT", friend.t("Client reconnected"))
  651. } else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  652. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of message history lost)"), gapSeconds))
  653. } else {
  654. fSession.Send(nil, oldNickmask, "QUIT", friend.t("Client reconnected (message history may have been lost)"))
  655. }
  656. }
  657. }
  658. }
  659. if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  660. session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", fmt.Sprintf(client.t("Resume may have lost up to %d seconds of history"), gapSeconds))
  661. } else {
  662. session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Resume may have lost some message history"))
  663. }
  664. session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
  665. server.playRegistrationBurst(session)
  666. for _, channel := range client.Channels() {
  667. channel.Resume(session, timestamp)
  668. }
  669. // replay direct PRIVSMG history
  670. if !timestamp.IsZero() {
  671. now := time.Now().UTC()
  672. items, complete := client.history.Between(timestamp, now, false, 0)
  673. rb := NewResponseBuffer(client.Sessions()[0])
  674. client.replayPrivmsgHistory(rb, items, complete)
  675. rb.Send(true)
  676. }
  677. session.resumeDetails = nil
  678. }
  679. func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
  680. var batchID string
  681. details := client.Details()
  682. nick := details.nick
  683. if 0 < len(items) {
  684. batchID = rb.StartNestedHistoryBatch(nick)
  685. }
  686. allowTags := rb.session.capabilities.Has(caps.MessageTags)
  687. for _, item := range items {
  688. var command string
  689. switch item.Type {
  690. case history.Privmsg:
  691. command = "PRIVMSG"
  692. case history.Notice:
  693. command = "NOTICE"
  694. case history.Tagmsg:
  695. if allowTags {
  696. command = "TAGMSG"
  697. } else {
  698. continue
  699. }
  700. default:
  701. continue
  702. }
  703. var tags map[string]string
  704. if allowTags {
  705. tags = item.Tags
  706. }
  707. if item.Params[0] == "" {
  708. // this message was sent *to* the client from another nick
  709. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
  710. } else {
  711. // this message was sent *from* the client to another nick; the target is item.Params[0]
  712. // substitute the client's current nickmask in case they changed nick
  713. rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
  714. }
  715. }
  716. rb.EndNestedBatch(batchID)
  717. if !complete {
  718. rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  719. }
  720. }
  721. // IdleTime returns how long this client's been idle.
  722. func (client *Client) IdleTime() time.Duration {
  723. client.stateMutex.RLock()
  724. defer client.stateMutex.RUnlock()
  725. return time.Since(client.atime)
  726. }
  727. // SignonTime returns this client's signon time as a unix timestamp.
  728. func (client *Client) SignonTime() int64 {
  729. return client.ctime.Unix()
  730. }
  731. // IdleSeconds returns the number of seconds this client's been idle.
  732. func (client *Client) IdleSeconds() uint64 {
  733. return uint64(client.IdleTime().Seconds())
  734. }
  735. // HasNick returns true if the client's nickname is set (used in registration).
  736. func (client *Client) HasNick() bool {
  737. client.stateMutex.RLock()
  738. defer client.stateMutex.RUnlock()
  739. return client.nick != "" && client.nick != "*"
  740. }
  741. // HasUsername returns true if the client's username is set (used in registration).
  742. func (client *Client) HasUsername() bool {
  743. client.stateMutex.RLock()
  744. defer client.stateMutex.RUnlock()
  745. return client.username != "" && client.username != "*"
  746. }
  747. // SetNames sets the client's ident and realname.
  748. func (client *Client) SetNames(username, realname string, fromIdent bool) error {
  749. limit := client.server.Config().Limits.IdentLen
  750. if !fromIdent {
  751. limit -= 1 // leave room for the prepended ~
  752. }
  753. if limit < len(username) {
  754. username = username[:limit]
  755. }
  756. if !isIdent(username) {
  757. return errInvalidUsername
  758. }
  759. if !fromIdent {
  760. username = "~" + username
  761. }
  762. client.stateMutex.Lock()
  763. defer client.stateMutex.Unlock()
  764. if client.username == "" {
  765. client.username = username
  766. }
  767. if client.realname == "" {
  768. client.realname = realname
  769. }
  770. return nil
  771. }
  772. // HasRoleCapabs returns true if client has the given (role) capabilities.
  773. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  774. oper := client.Oper()
  775. if oper == nil {
  776. return false
  777. }
  778. for _, capab := range capabs {
  779. if !oper.Class.Capabilities[capab] {
  780. return false
  781. }
  782. }
  783. return true
  784. }
  785. // ModeString returns the mode string for this client.
  786. func (client *Client) ModeString() (str string) {
  787. return "+" + client.flags.String()
  788. }
  789. // Friends refers to clients that share a channel with this client.
  790. func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
  791. result = make(map[*Session]bool)
  792. // look at the client's own sessions
  793. for _, session := range client.Sessions() {
  794. if session.capabilities.HasAll(capabs...) {
  795. result[session] = true
  796. }
  797. }
  798. for _, channel := range client.Channels() {
  799. for _, member := range channel.Members() {
  800. for _, session := range member.Sessions() {
  801. if session.capabilities.HasAll(capabs...) {
  802. result[session] = true
  803. }
  804. }
  805. }
  806. }
  807. return
  808. }
  809. func (client *Client) SetOper(oper *Oper) {
  810. client.stateMutex.Lock()
  811. defer client.stateMutex.Unlock()
  812. client.oper = oper
  813. // operators typically get a vhost, update the nickmask
  814. client.updateNickMaskNoMutex()
  815. }
  816. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  817. // this is annoying to do correctly
  818. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  819. username := client.Username()
  820. for fClient := range client.Friends(caps.ChgHost) {
  821. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  822. }
  823. }
  824. // choose the correct vhost to display
  825. func (client *Client) getVHostNoMutex() string {
  826. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  827. if client.vhost != "" {
  828. return client.vhost
  829. } else if client.oper != nil {
  830. return client.oper.Vhost
  831. } else {
  832. return ""
  833. }
  834. }
  835. // SetVHost updates the client's hostserv-based vhost
  836. func (client *Client) SetVHost(vhost string) (updated bool) {
  837. client.stateMutex.Lock()
  838. defer client.stateMutex.Unlock()
  839. updated = (client.vhost != vhost)
  840. client.vhost = vhost
  841. if updated {
  842. client.updateNickMaskNoMutex()
  843. }
  844. return
  845. }
  846. // updateNick updates `nick` and `nickCasefolded`.
  847. func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
  848. client.stateMutex.Lock()
  849. defer client.stateMutex.Unlock()
  850. client.nick = nick
  851. client.nickCasefolded = nickCasefolded
  852. client.skeleton = skeleton
  853. client.updateNickMaskNoMutex()
  854. }
  855. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  856. func (client *Client) updateNickMaskNoMutex() {
  857. client.hostname = client.getVHostNoMutex()
  858. if client.hostname == "" {
  859. client.hostname = client.cloakedHostname
  860. if client.hostname == "" {
  861. client.hostname = client.rawHostname
  862. }
  863. }
  864. if client.hostname == "" {
  865. return // pre-registration, don't bother generating the hostname
  866. }
  867. cfhostname := strings.ToLower(client.hostname)
  868. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  869. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
  870. }
  871. // AllNickmasks returns all the possible nickmasks for the client.
  872. func (client *Client) AllNickmasks() (masks []string) {
  873. client.stateMutex.RLock()
  874. nick := client.nickCasefolded
  875. username := client.username
  876. rawHostname := client.rawHostname
  877. cloakedHostname := client.cloakedHostname
  878. vhost := client.getVHostNoMutex()
  879. client.stateMutex.RUnlock()
  880. username = strings.ToLower(username)
  881. if len(vhost) > 0 {
  882. cfvhost := strings.ToLower(vhost)
  883. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  884. }
  885. var rawhostmask string
  886. cfrawhost := strings.ToLower(rawHostname)
  887. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  888. masks = append(masks, rawhostmask)
  889. if cloakedHostname != "" {
  890. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
  891. }
  892. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  893. if ipmask != rawhostmask {
  894. masks = append(masks, ipmask)
  895. }
  896. return
  897. }
  898. // LoggedIntoAccount returns true if this client is logged into an account.
  899. func (client *Client) LoggedIntoAccount() bool {
  900. return client.Account() != ""
  901. }
  902. // Quit sets the given quit message for the client.
  903. // (You must ensure separately that destroy() is called, e.g., by returning `true` from
  904. // the command handler or calling it yourself.)
  905. func (client *Client) Quit(message string, session *Session) {
  906. setFinalData := func(sess *Session) {
  907. message := sess.quitMessage
  908. var finalData []byte
  909. // #364: don't send QUIT lines to unregistered clients
  910. if client.registered {
  911. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  912. finalData, _ = quitMsg.LineBytesStrict(false, 512)
  913. }
  914. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  915. errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
  916. finalData = append(finalData, errorMsgBytes...)
  917. sess.socket.SetFinalData(finalData)
  918. }
  919. client.stateMutex.Lock()
  920. defer client.stateMutex.Unlock()
  921. var sessions []*Session
  922. if session != nil {
  923. sessions = []*Session{session}
  924. } else {
  925. sessions = client.sessions
  926. }
  927. for _, session := range sessions {
  928. if session.SetQuitMessage(message) {
  929. setFinalData(session)
  930. }
  931. }
  932. }
  933. // destroy gets rid of a client, removes them from server lists etc.
  934. // if `session` is nil, destroys the client unconditionally, removing all sessions;
  935. // otherwise, destroys one specific session, only destroying the client if it
  936. // has no more sessions.
  937. func (client *Client) destroy(session *Session) {
  938. var sessionsToDestroy []*Session
  939. client.stateMutex.Lock()
  940. details := client.detailsNoMutex()
  941. brbState := client.brbTimer.state
  942. brbAt := client.brbTimer.brbAt
  943. wasReattach := session != nil && session.client != client
  944. sessionRemoved := false
  945. var remainingSessions int
  946. if session == nil {
  947. sessionsToDestroy = client.sessions
  948. client.sessions = nil
  949. remainingSessions = 0
  950. } else {
  951. sessionRemoved, remainingSessions = client.removeSession(session)
  952. if sessionRemoved {
  953. sessionsToDestroy = []*Session{session}
  954. }
  955. }
  956. // should we destroy the whole client this time?
  957. // BRB is not respected if this is a destroy of the whole client (i.e., session == nil)
  958. brbEligible := session != nil && (brbState == BrbEnabled || brbState == BrbSticky)
  959. shouldDestroy := !client.destroyed && remainingSessions == 0 && !brbEligible
  960. if shouldDestroy {
  961. // if it's our job to destroy it, don't let anyone else try
  962. client.destroyed = true
  963. }
  964. exitedSnomaskSent := client.exitedSnomaskSent
  965. client.stateMutex.Unlock()
  966. // destroy all applicable sessions:
  967. var quitMessage string
  968. for _, session := range sessionsToDestroy {
  969. if session.client != client {
  970. // session has been attached to a new client; do not destroy it
  971. continue
  972. }
  973. session.idletimer.Stop()
  974. // send quit/error message to client if they haven't been sent already
  975. client.Quit("", session)
  976. quitMessage = session.quitMessage
  977. session.SetDestroyed()
  978. session.socket.Close()
  979. // remove from connection limits
  980. var source string
  981. if client.isTor {
  982. client.server.torLimiter.RemoveClient()
  983. source = "tor"
  984. } else {
  985. ip := session.realIP
  986. if session.proxiedIP != nil {
  987. ip = session.proxiedIP
  988. }
  989. client.server.connectionLimiter.RemoveClient(ip)
  990. source = ip.String()
  991. }
  992. client.server.logger.Info("localconnect-ip", fmt.Sprintf("disconnecting session of %s from %s", details.nick, source))
  993. }
  994. // do not destroy the client if it has either remaining sessions, or is BRB'ed
  995. if !shouldDestroy {
  996. return
  997. }
  998. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  999. // a lot of RAM, so limit concurrency to avoid thrashing
  1000. client.server.semaphores.ClientDestroy.Acquire()
  1001. defer client.server.semaphores.ClientDestroy.Release()
  1002. if !wasReattach {
  1003. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", details.nick))
  1004. }
  1005. registered := client.Registered()
  1006. if registered {
  1007. client.server.whoWas.Append(client.WhoWas())
  1008. }
  1009. client.server.resumeManager.Delete(client)
  1010. // alert monitors
  1011. if registered {
  1012. client.server.monitorManager.AlertAbout(client, false)
  1013. }
  1014. // clean up monitor state
  1015. client.server.monitorManager.RemoveAll(client)
  1016. splitQuitMessage := utils.MakeSplitMessage(quitMessage, true)
  1017. // clean up channels
  1018. // (note that if this is a reattach, client has no channels and therefore no friends)
  1019. friends := make(ClientSet)
  1020. for _, channel := range client.Channels() {
  1021. channel.Quit(client)
  1022. channel.history.Add(history.Item{
  1023. Type: history.Quit,
  1024. Nick: details.nickMask,
  1025. AccountName: details.accountName,
  1026. Message: splitQuitMessage,
  1027. })
  1028. for _, member := range channel.Members() {
  1029. friends.Add(member)
  1030. }
  1031. }
  1032. friends.Remove(client)
  1033. // clean up server
  1034. client.server.clients.Remove(client)
  1035. // clean up self
  1036. client.nickTimer.Stop()
  1037. client.brbTimer.Disable()
  1038. client.server.accounts.Logout(client)
  1039. client.server.stats.Remove(registered, client.HasMode(modes.Invisible),
  1040. client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator))
  1041. // this happens under failure to return from BRB
  1042. if quitMessage == "" {
  1043. if brbState == BrbDead && !brbAt.IsZero() {
  1044. awayMessage := client.AwayMessage()
  1045. if awayMessage == "" {
  1046. awayMessage = "Disconnected" // auto-BRB
  1047. }
  1048. quitMessage = fmt.Sprintf("%s [%s ago]", awayMessage, time.Since(brbAt).Truncate(time.Second).String())
  1049. }
  1050. }
  1051. if quitMessage == "" {
  1052. quitMessage = "Exited"
  1053. }
  1054. for friend := range friends {
  1055. friend.sendFromClientInternal(false, splitQuitMessage.Time, splitQuitMessage.Msgid, details.nickMask, details.accountName, nil, "QUIT", quitMessage)
  1056. }
  1057. if !exitedSnomaskSent && registered {
  1058. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), details.nick))
  1059. }
  1060. }
  1061. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  1062. // Adds account-tag to the line as well.
  1063. func (session *Session) sendSplitMsgFromClientInternal(blocking bool, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
  1064. if message.Is512() || session.capabilities.Has(caps.MaxLine) {
  1065. session.sendFromClientInternal(blocking, message.Time, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
  1066. } else {
  1067. if message.IsMultiline() && session.capabilities.Has(caps.Multiline) {
  1068. for _, msg := range session.composeMultilineBatch(nickmask, accountName, tags, command, target, message) {
  1069. session.SendRawMessage(msg, blocking)
  1070. }
  1071. } else {
  1072. for _, messagePair := range message.Wrapped {
  1073. session.sendFromClientInternal(blocking, message.Time, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
  1074. }
  1075. }
  1076. }
  1077. }
  1078. // Sends a line with `nickmask` as the prefix, adding `time` and `account` tags if supported
  1079. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  1080. for _, session := range client.Sessions() {
  1081. err_ := session.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, params...)
  1082. if err_ != nil {
  1083. err = err_
  1084. }
  1085. }
  1086. return
  1087. }
  1088. func (session *Session) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  1089. msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
  1090. // attach account-tag
  1091. if session.capabilities.Has(caps.AccountTag) && accountName != "*" {
  1092. msg.SetTag("account", accountName)
  1093. }
  1094. // attach message-id
  1095. if msgid != "" && session.capabilities.Has(caps.MessageTags) {
  1096. msg.SetTag("msgid", msgid)
  1097. }
  1098. // attach server-time
  1099. session.setTimeTag(&msg, serverTime)
  1100. return session.SendRawMessage(msg, blocking)
  1101. }
  1102. func (session *Session) composeMultilineBatch(fromNickMask, fromAccount string, tags map[string]string, command, target string, message utils.SplitMessage) (result []ircmsg.IrcMessage) {
  1103. batchID := session.generateBatchID()
  1104. batchStart := ircmsg.MakeMessage(tags, fromNickMask, "BATCH", "+"+batchID, caps.MultilineBatchType)
  1105. batchStart.SetTag("time", message.Time.Format(IRCv3TimestampFormat))
  1106. batchStart.SetTag("msgid", message.Msgid)
  1107. if session.capabilities.Has(caps.AccountTag) && fromAccount != "*" {
  1108. batchStart.SetTag("account", fromAccount)
  1109. }
  1110. result = append(result, batchStart)
  1111. for _, msg := range message.Wrapped {
  1112. message := ircmsg.MakeMessage(nil, fromNickMask, command, target, msg.Message)
  1113. message.SetTag("batch", batchID)
  1114. message.SetTag(caps.MultilineFmsgidTag, msg.Msgid)
  1115. if msg.Concat {
  1116. message.SetTag(caps.MultilineConcatTag, "")
  1117. }
  1118. result = append(result, message)
  1119. }
  1120. result = append(result, ircmsg.MakeMessage(nil, fromNickMask, "BATCH", "-"+batchID))
  1121. return
  1122. }
  1123. var (
  1124. // these are all the output commands that MUST have their last param be a trailing.
  1125. // this is needed because dumb clients like to treat trailing params separately from the
  1126. // other params in messages.
  1127. commandsThatMustUseTrailing = map[string]bool{
  1128. "PRIVMSG": true,
  1129. "NOTICE": true,
  1130. RPL_WHOISCHANNELS: true,
  1131. RPL_USERHOST: true,
  1132. }
  1133. )
  1134. // SendRawMessage sends a raw message to the client.
  1135. func (session *Session) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  1136. // use dumb hack to force the last param to be a trailing param if required
  1137. var usedTrailingHack bool
  1138. config := session.client.server.Config()
  1139. if config.Server.Compatibility.forceTrailing && commandsThatMustUseTrailing[message.Command] && len(message.Params) > 0 {
  1140. lastParam := message.Params[len(message.Params)-1]
  1141. // to force trailing, we ensure the final param contains a space
  1142. if strings.IndexByte(lastParam, ' ') == -1 {
  1143. message.Params[len(message.Params)-1] = lastParam + " "
  1144. usedTrailingHack = true
  1145. }
  1146. }
  1147. // assemble message
  1148. maxlenRest := session.MaxlenRest()
  1149. line, err := message.LineBytesStrict(false, maxlenRest)
  1150. if err != nil {
  1151. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  1152. session.client.server.logger.Error("internal", logline)
  1153. message = ircmsg.MakeMessage(nil, session.client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  1154. line, _ := message.LineBytesStrict(false, 0)
  1155. if blocking {
  1156. session.socket.BlockingWrite(line)
  1157. } else {
  1158. session.socket.Write(line)
  1159. }
  1160. return err
  1161. }
  1162. // if we used the trailing hack, we need to strip the final space we appended earlier on
  1163. if usedTrailingHack {
  1164. copy(line[len(line)-3:], "\r\n")
  1165. line = line[:len(line)-1]
  1166. }
  1167. if session.client.server.logger.IsLoggingRawIO() {
  1168. logline := string(line[:len(line)-2]) // strip "\r\n"
  1169. session.client.server.logger.Debug("useroutput", session.client.Nick(), " ->", logline)
  1170. }
  1171. if blocking {
  1172. return session.socket.BlockingWrite(line)
  1173. } else {
  1174. return session.socket.Write(line)
  1175. }
  1176. }
  1177. // Send sends an IRC line to the client.
  1178. func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1179. for _, session := range client.Sessions() {
  1180. err_ := session.Send(tags, prefix, command, params...)
  1181. if err_ != nil {
  1182. err = err_
  1183. }
  1184. }
  1185. return
  1186. }
  1187. func (session *Session) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1188. msg := ircmsg.MakeMessage(tags, prefix, command, params...)
  1189. session.setTimeTag(&msg, time.Time{})
  1190. return session.SendRawMessage(msg, false)
  1191. }
  1192. func (session *Session) setTimeTag(msg *ircmsg.IrcMessage, serverTime time.Time) {
  1193. if session.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
  1194. if serverTime.IsZero() {
  1195. serverTime = time.Now()
  1196. }
  1197. msg.SetTag("time", serverTime.UTC().Format(IRCv3TimestampFormat))
  1198. }
  1199. }
  1200. // Notice sends the client a notice from the server.
  1201. func (client *Client) Notice(text string) {
  1202. client.Send(nil, client.server.name, "NOTICE", client.Nick(), text)
  1203. }
  1204. func (session *Session) Notice(text string) {
  1205. session.Send(nil, session.client.server.name, "NOTICE", session.client.Nick(), text)
  1206. }
  1207. func (client *Client) addChannel(channel *Channel) {
  1208. client.stateMutex.Lock()
  1209. client.channels[channel] = true
  1210. client.stateMutex.Unlock()
  1211. }
  1212. func (client *Client) removeChannel(channel *Channel) {
  1213. client.stateMutex.Lock()
  1214. delete(client.channels, channel)
  1215. client.stateMutex.Unlock()
  1216. }
  1217. // Records that the client has been invited to join an invite-only channel
  1218. func (client *Client) Invite(casefoldedChannel string) {
  1219. client.stateMutex.Lock()
  1220. defer client.stateMutex.Unlock()
  1221. if client.invitedTo == nil {
  1222. client.invitedTo = make(map[string]bool)
  1223. }
  1224. client.invitedTo[casefoldedChannel] = true
  1225. }
  1226. // Checks that the client was invited to join a given channel
  1227. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  1228. client.stateMutex.Lock()
  1229. defer client.stateMutex.Unlock()
  1230. invited = client.invitedTo[casefoldedChannel]
  1231. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  1232. delete(client.invitedTo, casefoldedChannel)
  1233. return
  1234. }
  1235. // Implements auto-oper by certfp (scans for an auto-eligible operator block that matches
  1236. // the client's cert, then applies it).
  1237. func (client *Client) attemptAutoOper(session *Session) {
  1238. if client.certfp == "" || client.HasMode(modes.Operator) {
  1239. return
  1240. }
  1241. for _, oper := range client.server.Config().operators {
  1242. if oper.Auto && oper.Pass == nil && oper.Fingerprint != "" && oper.Fingerprint == client.certfp {
  1243. rb := NewResponseBuffer(session)
  1244. applyOper(client, oper, rb)
  1245. rb.Send(true)
  1246. return
  1247. }
  1248. }
  1249. }