ircd/irc/client.go

1274 lines
38 KiB
Go
Raw Normal View History

// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2014-2015 Edmund Huber
2017-03-27 12:15:02 +00:00
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
2012-04-07 18:44:59 +00:00
package irc
import (
2012-04-18 05:11:35 +00:00
"fmt"
2012-04-07 18:44:59 +00:00
"net"
2016-10-16 10:35:50 +00:00
"runtime/debug"
"strconv"
"strings"
2017-04-18 12:26:01 +00:00
"sync"
2017-10-22 23:50:16 +00:00
"sync/atomic"
2012-12-12 07:12:35 +00:00
"time"
2017-06-15 16:14:19 +00:00
"github.com/goshuirc/irc-go/ircfmt"
"github.com/goshuirc/irc-go/ircmsg"
2017-06-14 18:00:53 +00:00
ident "github.com/oragono/go-ident"
"github.com/oragono/oragono/irc/caps"
2019-01-01 21:45:37 +00:00
"github.com/oragono/oragono/irc/connection_limits"
"github.com/oragono/oragono/irc/history"
"github.com/oragono/oragono/irc/modes"
2017-06-14 18:00:53 +00:00
"github.com/oragono/oragono/irc/sno"
"github.com/oragono/oragono/irc/utils"
2012-04-07 18:44:59 +00:00
)
const (
// IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
IdentTimeoutSeconds = 1.5
IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
)
// ResumeDetails is a place to stash data at various stages of
// the resume process: when handling the RESUME command itself,
// when completing the registration, and when rejoining channels.
type ResumeDetails struct {
PresentedToken string
Timestamp time.Time
HistoryIncomplete bool
}
2016-10-23 01:48:57 +00:00
// Client is an IRC client.
2012-04-07 18:44:59 +00:00
type Client struct {
account string
accountName string // display name of the account: uncasefolded, '*' if not logged in
2019-05-19 08:27:44 +00:00
accountSettings AccountSettings
atime time.Time
2019-04-28 19:10:03 +00:00
away bool
awayMessage string
2019-05-22 01:40:25 +00:00
brbTimer BrbTimer
certfp string
channels ChannelSet
ctime time.Time
2019-05-27 09:52:40 +00:00
destroyed bool
exitedSnomaskSent bool
2019-03-11 23:24:45 +00:00
flags modes.ModeSet
hostname string
2018-12-23 18:25:02 +00:00
invitedTo map[string]bool
2019-02-26 02:50:43 +00:00
isTor bool
languages []string
2019-01-01 21:45:37 +00:00
loginThrottle connection_limits.GenericThrottle
nick string
nickCasefolded string
nickMaskCasefolded string
2017-04-18 12:26:01 +00:00
nickMaskString string // cache for nickmask string since it's used with lots of replies
nickTimer NickTimer
2018-04-19 06:48:19 +00:00
oper *Oper
2018-02-27 02:44:03 +00:00
preregNick string
2018-02-01 20:53:49 +00:00
proxiedIP net.IP // actual remote IP if using the PROXY protocol
2017-04-18 12:26:01 +00:00
rawHostname string
2019-05-12 06:17:57 +00:00
cloakedHostname string
realname string
2019-02-05 05:19:03 +00:00
realIP net.IP
registered bool
resumeID string
saslInProgress bool
saslMechanism string
saslValue string
2019-02-05 05:19:03 +00:00
sentPassCommand bool
server *Server
skeleton string
sessions []*Session
2017-11-22 09:41:11 +00:00
stateMutex sync.RWMutex // tier 1
username string
2017-04-18 12:26:01 +00:00
vhost string
2019-05-22 01:40:25 +00:00
history history.Buffer
}
// Session is an individual client connection to the server (TCP connection
// and associated per-connection data, such as capabilities). There is a
// many-one relationship between sessions and clients.
type Session struct {
client *Client
ctime time.Time
atime time.Time
socket *Socket
realIP net.IP
proxiedIP net.IP
rawHostname string
idletimer IdleTimer
fakelag Fakelag
2019-05-27 08:18:07 +00:00
destroyed uint32
quitMessage string
capabilities caps.Set
maxlenRest uint32
capState caps.State
capVersion caps.Version
2019-05-22 01:40:25 +00:00
registrationMessages int
resumeID string
resumeDetails *ResumeDetails
2019-05-20 23:08:57 +00:00
zncPlaybackTimes *zncPlaybackTimes
}
// sets the session quit message, if there isn't one already
func (sd *Session) SetQuitMessage(message string) (set bool) {
if message == "" {
message = "Connection closed"
}
if sd.quitMessage == "" {
sd.quitMessage = message
return true
} else {
return false
}
}
// set the negotiated message length based on session capabilities
func (session *Session) SetMaxlenRest() {
maxlenRest := 512
if session.capabilities.Has(caps.MaxLine) {
maxlenRest = session.client.server.Config().Limits.LineLen.Rest
}
atomic.StoreUint32(&session.maxlenRest, uint32(maxlenRest))
}
// allow the negotiated message length limit to be read without locks; this is a convenience
// so that Session.SendRawMessage doesn't have to acquire any Client locks
func (session *Session) MaxlenRest() int {
return int(atomic.LoadUint32(&session.maxlenRest))
}
2019-05-27 08:18:07 +00:00
// returns whether the session was actively destroyed (for example, by ping
// timeout or NS GHOST).
// avoids a race condition between asynchronous idle-timing-out of sessions,
// and a condition that allows implicit BRB on connection errors (since
// destroy()'s socket.Close() appears to socket.Read() as a connection error)
func (session *Session) Destroyed() bool {
return atomic.LoadUint32(&session.destroyed) == 1
}
// sets the timed-out flag
func (session *Session) SetDestroyed() {
atomic.StoreUint32(&session.destroyed, 1)
}
// WhoWas is the subset of client details needed to answer a WHOWAS query
type WhoWas struct {
nick string
nickCasefolded string
username string
hostname string
realname string
}
// ClientDetails is a standard set of details about a client
type ClientDetails struct {
WhoWas
nickMask string
nickMaskCasefolded string
account string
accountName string
}
// RunClient sets up a new client and runs its goroutine.
func (server *Server) RunClient(conn clientConn) {
var isBanned bool
var banMsg string
var realIP net.IP
if conn.IsTor {
realIP = utils.IPv4LoopbackAddress
isBanned, banMsg = server.checkTorLimits()
} else {
realIP = utils.AddrToIP(conn.Conn.RemoteAddr())
isBanned, banMsg = server.checkBans(realIP)
}
if isBanned {
// this might not show up properly on some clients,
// but our objective here is just to close the connection out before it has a load impact on us
conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
conn.Conn.Close()
return
}
server.logger.Info("localconnect-ip", fmt.Sprintf("Client connecting from %v", realIP))
now := time.Now().UTC()
config := server.Config()
fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
// give them 1k of grace over the limit:
socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
2012-12-09 20:51:50 +00:00
client := &Client{
atime: now,
channels: make(ChannelSet),
ctime: now,
isTor: conn.IsTor,
languages: server.Languages().Default(),
2019-01-01 21:45:37 +00:00
loginThrottle: connection_limits.GenericThrottle{
Duration: config.Accounts.LoginThrottling.Duration,
Limit: config.Accounts.LoginThrottling.MaxAttempts,
},
server: server,
accountName: "*",
nick: "*", // * is used until actual nick is given
nickCasefolded: "*",
nickMaskString: "*", // * is used until actual nick is given
2012-12-09 20:51:50 +00:00
}
2019-05-22 01:40:25 +00:00
client.history.Initialize(config.History.ClientLength)
client.brbTimer.Initialize(client)
session := &Session{
client: client,
socket: socket,
capVersion: caps.Cap301,
capState: caps.NoneState,
ctime: now,
atime: now,
realIP: realIP,
}
session.SetMaxlenRest()
client.sessions = []*Session{session}
2016-09-07 11:32:58 +00:00
2019-02-26 02:50:43 +00:00
if conn.IsTLS {
client.SetMode(modes.TLS, true)
2016-09-07 11:32:58 +00:00
// error is not useful to us here anyways so we can ignore it
client.certfp, _ = socket.CertFP()
2016-06-28 15:09:07 +00:00
}
2019-02-26 02:50:43 +00:00
if conn.IsTor {
client.SetMode(modes.TLS, true)
// cover up details of the tor proxying infrastructure (not a user privacy concern,
// but a hardening measure):
session.proxiedIP = utils.IPv4LoopbackAddress
session.rawHostname = config.Server.TorListeners.Vhost
2019-02-26 02:50:43 +00:00
} else {
// set the hostname for this client (may be overridden later by PROXY or WEBIRC)
session.rawHostname = utils.LookupHostname(session.realIP.String())
2019-05-12 06:17:57 +00:00
client.cloakedHostname = config.Server.Cloaks.ComputeCloak(session.realIP)
remoteAddr := conn.Conn.RemoteAddr()
if utils.AddrIsLocal(remoteAddr) {
// treat local connections as secure (may be overridden later by WEBIRC)
client.SetMode(modes.TLS, true)
}
2019-02-26 02:50:43 +00:00
if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
client.doIdentLookup(conn.Conn)
}
2019-02-26 02:50:43 +00:00
}
client.realIP = session.realIP
client.rawHostname = session.rawHostname
client.proxiedIP = session.proxiedIP
2019-02-26 02:50:43 +00:00
client.run(session)
2019-02-26 02:50:43 +00:00
}
func (client *Client) doIdentLookup(conn net.Conn) {
_, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
if err != nil {
client.server.logger.Error("internal", "bad server address", err.Error())
return
}
serverPort, _ := strconv.Atoi(serverPortString)
clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
client.server.logger.Error("internal", "bad client address", err.Error())
return
}
clientPort, _ := strconv.Atoi(clientPortString)
2019-02-26 02:50:43 +00:00
client.Notice(client.t("*** Looking up your username"))
resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
if err == nil {
err := client.SetNames(resp.Identifier, "", true)
if err == nil {
2019-02-26 02:50:43 +00:00
client.Notice(client.t("*** Found your username"))
// we don't need to updateNickMask here since nickMask is not used for anything yet
} else {
2019-02-26 02:50:43 +00:00
client.Notice(client.t("*** Got a malformed username, ignoring"))
}
2019-02-26 02:50:43 +00:00
} else {
client.Notice(client.t("*** Could not find your username"))
}
2012-04-07 18:44:59 +00:00
}
2019-05-23 00:25:57 +00:00
type AuthOutcome uint
const (
authSuccess AuthOutcome = iota
authFailPass
authFailTorSaslRequired
authFailSaslRequired
)
func (client *Client) isAuthorized(config *Config) AuthOutcome {
2019-02-05 05:19:03 +00:00
saslSent := client.account != ""
2019-02-26 02:50:43 +00:00
// PASS requirement
2019-02-26 03:56:08 +00:00
if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
2019-05-23 00:25:57 +00:00
return authFailPass
2019-02-05 05:19:03 +00:00
}
2019-02-26 02:50:43 +00:00
// Tor connections may be required to authenticate with SASL
2019-02-26 03:56:08 +00:00
if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
2019-05-23 00:25:57 +00:00
return authFailTorSaslRequired
2019-02-26 02:50:43 +00:00
}
// finally, enforce require-sasl
2019-05-23 00:25:57 +00:00
if config.Accounts.RequireSasl.Enabled && !saslSent && !utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets) {
return authFailSaslRequired
}
return authSuccess
2019-02-05 05:19:03 +00:00
}
func (session *Session) resetFakelag() {
var flc FakelagConfig = session.client.server.Config().Fakelag
flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
session.fakelag.Initialize(flc)
2018-03-22 15:04:21 +00:00
}
// IP returns the IP address of this client.
func (client *Client) IP() net.IP {
2019-02-05 05:19:03 +00:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
2018-02-01 20:53:49 +00:00
if client.proxiedIP != nil {
return client.proxiedIP
}
2019-02-05 05:19:03 +00:00
return client.realIP
}
// IPString returns the IP address of this client as a string.
func (client *Client) IPString() string {
ip := client.IP().String()
if 0 < len(ip) && ip[0] == ':' {
ip = "0" + ip
}
return ip
}
2014-02-24 06:21:39 +00:00
//
// command goroutine
//
func (client *Client) run(session *Session) {
2017-10-23 22:38:32 +00:00
defer func() {
2017-10-26 09:15:55 +00:00
if r := recover(); r != nil {
client.server.logger.Error("internal",
fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
2019-05-22 23:07:12 +00:00
if client.server.Config().Debug.recoverFromErrors {
2017-10-26 09:15:55 +00:00
client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
} else {
panic(r)
2017-10-26 08:19:01 +00:00
}
2017-10-23 22:38:32 +00:00
}
// ensure client connection gets closed
2019-05-22 01:40:25 +00:00
client.destroy(session)
2017-10-23 22:38:32 +00:00
}()
session.idletimer.Initialize(session)
session.resetFakelag()
2017-10-15 16:24:28 +00:00
isReattach := client.Registered()
2019-05-08 22:14:49 +00:00
if isReattach {
2019-05-22 01:40:25 +00:00
if session.resumeDetails != nil {
session.playResume()
session.resumeDetails = nil
client.brbTimer.Disable()
} else {
client.playReattachMessages(session)
}
2019-05-08 22:14:49 +00:00
} else {
// don't reset the nick timer during a reattach
client.nickTimer.Initialize(client)
}
2018-03-22 15:04:21 +00:00
2019-05-27 08:18:07 +00:00
firstLine := !isReattach
for {
maxlenRest := session.MaxlenRest()
2017-10-22 23:50:16 +00:00
line, err := session.socket.Read()
if err != nil {
2018-03-18 01:32:12 +00:00
quitMessage := "connection closed"
if err == errReadQ {
quitMessage = "readQ exceeded"
}
client.Quit(quitMessage, session)
2019-05-22 01:40:25 +00:00
// since the client did not actually send us a QUIT,
2019-05-27 08:18:07 +00:00
// give them a chance to resume if applicable:
if !session.Destroyed() {
client.brbTimer.Enable()
}
break
}
if client.server.logger.IsLoggingRawIO() {
client.server.logger.Debug("userinput", client.nick, "<- ", line)
}
// special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
2019-05-27 08:18:07 +00:00
if firstLine {
firstLine = false
if strings.HasPrefix(line, "PROXY") {
err = handleProxyCommand(client.server, client, session, line)
if err != nil {
break
} else {
continue
}
}
}
if client.registered {
session.fakelag.Touch()
} else {
// DoS hardening, #505
session.registrationMessages++
if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
break
}
}
msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
if err == ircmsg.ErrorLineIsEmpty {
continue
} else if err == ircmsg.ErrorLineTooLong {
session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
continue
} else if err != nil {
client.Quit(client.t("Received malformed line"), session)
break
2014-02-24 06:21:39 +00:00
}
cmd, exists := Commands[msg.Command]
if !exists {
if len(msg.Command) > 0 {
session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
} else {
session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
}
continue
}
isExiting := cmd.Run(client.server, client, session, msg)
if isExiting {
break
} else if session.client != client {
// bouncer reattach
go session.client.run(session)
break
}
2014-02-24 06:21:39 +00:00
}
}
2019-05-08 22:14:49 +00:00
func (client *Client) playReattachMessages(session *Session) {
client.server.playRegistrationBurst(session)
for _, channel := range session.client.Channels() {
channel.playJoinForSession(session)
}
}
//
// idle, quit, timers and timeouts
//
// Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
func (client *Client) Active(session *Session) {
now := time.Now().UTC()
2017-12-03 01:05:06 +00:00
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
session.atime = now
client.atime = now
2014-02-18 21:25:21 +00:00
}
2017-10-15 16:24:28 +00:00
// Ping sends the client a PING message.
func (session *Session) Ping() {
session.Send(nil, "", "PING", session.client.Nick())
}
// tryResume tries to resume if the client asked us to.
2019-05-22 01:40:25 +00:00
func (session *Session) tryResume() (success bool) {
var oldResumeID string
defer func() {
2019-05-22 01:40:25 +00:00
if success {
// "On a successful request, the server [...] terminates the old client's connection"
oldSession := session.client.GetSessionByResumeID(oldResumeID)
if oldSession != nil {
session.client.destroy(oldSession)
}
} else {
session.resumeDetails = nil
}
}()
2019-05-22 01:40:25 +00:00
client := session.client
server := client.server
config := server.Config()
2019-05-22 01:40:25 +00:00
oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
if oldClient == nil {
2019-05-22 01:40:25 +00:00
session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
2018-01-21 02:23:47 +00:00
return
}
resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
if !resumeAllowed {
2019-05-22 01:40:25 +00:00
session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
return
}
2019-02-26 21:39:10 +00:00
if oldClient.isTor != client.isTor {
2019-05-22 01:40:25 +00:00
session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
return
}
2019-05-22 01:40:25 +00:00
err := server.clients.Resume(oldClient, session)
if err != nil {
2019-05-22 01:40:25 +00:00
session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
return
}
success = true
2019-05-22 01:40:25 +00:00
client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
2019-05-22 01:40:25 +00:00
return
}
2019-05-22 01:40:25 +00:00
// playResume is called from the session's fresh goroutine after a resume;
// it sends notifications to friends, then plays the registration burst and replays
// stored history to the session
func (session *Session) playResume() {
client := session.client
server := client.server
friends := make(ClientSet)
oldestLostMessage := time.Now().UTC()
// work out how much time, if any, is not covered by history buffers
2019-05-22 01:40:25 +00:00
for _, channel := range client.Channels() {
for _, member := range channel.Members() {
friends.Add(member)
lastDiscarded := channel.history.LastDiscarded()
if lastDiscarded.Before(oldestLostMessage) {
oldestLostMessage = lastDiscarded
}
}
}
2018-12-28 18:45:55 +00:00
privmsgMatcher := func(item history.Item) bool {
2019-05-07 03:17:57 +00:00
return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
2018-12-28 18:45:55 +00:00
}
2019-05-22 01:40:25 +00:00
privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
lastDiscarded := client.history.LastDiscarded()
if lastDiscarded.Before(oldestLostMessage) {
oldestLostMessage = lastDiscarded
}
2018-12-28 18:45:55 +00:00
for _, item := range privmsgHistory {
2019-05-07 03:17:57 +00:00
sender := server.clients.Get(stripMaskFromNick(item.Nick))
2018-12-28 18:45:55 +00:00
if sender != nil {
friends.Add(sender)
}
}
2019-05-22 01:40:25 +00:00
timestamp := session.resumeDetails.Timestamp
if timestamp.IsZero() {
timestamp = session.client.ctime
}
gap := lastDiscarded.Sub(timestamp)
2019-05-22 01:40:25 +00:00
session.resumeDetails.HistoryIncomplete = gap > 0
gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
2019-05-22 01:40:25 +00:00
details := client.Details()
oldNickmask := details.nickMask
client.SetRawHostname(session.rawHostname)
hostname := client.Hostname() // may be a vhost
timestampString := session.resumeDetails.Timestamp.Format(IRCv3TimestampFormat)
// send quit/resume messages to friends
for friend := range friends {
2019-05-22 01:40:25 +00:00
if friend == client {
continue
}
for _, fSession := range friend.Sessions() {
if fSession.capabilities.Has(caps.Resume) {
if session.resumeDetails.HistoryIncomplete {
2019-05-22 01:40:25 +00:00
fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
} else {
fSession.Send(nil, oldNickmask, "RESUMED", hostname)
}
} else {
2019-05-22 01:40:25 +00:00
if session.resumeDetails.HistoryIncomplete {
fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of history lost)"), gapSeconds))
} else {
2019-05-22 01:40:25 +00:00
fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
}
}
}
}
2019-05-22 01:40:25 +00:00
if session.resumeDetails.HistoryIncomplete {
2019-05-22 19:08:02 +00:00
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))
}
2019-05-22 19:08:02 +00:00
session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
2018-04-24 07:11:11 +00:00
2019-05-22 01:40:25 +00:00
server.playRegistrationBurst(session)
2019-05-22 01:40:25 +00:00
for _, channel := range client.Channels() {
channel.Resume(session, timestamp)
}
// replay direct PRIVSMG history
2019-05-22 01:40:25 +00:00
if !timestamp.IsZero() {
now := time.Now().UTC()
2019-05-22 01:40:25 +00:00
items, complete := client.history.Between(timestamp, now, false, 0)
rb := NewResponseBuffer(client.Sessions()[0])
client.replayPrivmsgHistory(rb, items, complete)
rb.Send(true)
2018-04-24 07:11:11 +00:00
}
2019-05-22 01:40:25 +00:00
session.resumeDetails = nil
}
func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
2019-05-07 03:17:57 +00:00
var batchID string
2019-05-19 06:14:36 +00:00
details := client.Details()
nick := details.nick
2019-05-07 03:17:57 +00:00
if 0 < len(items) {
batchID = rb.StartNestedHistoryBatch(nick)
}
allowTags := rb.session.capabilities.Has(caps.MessageTags)
for _, item := range items {
var command string
switch item.Type {
case history.Privmsg:
command = "PRIVMSG"
case history.Notice:
command = "NOTICE"
2019-05-07 03:17:57 +00:00
case history.Tagmsg:
if allowTags {
command = "TAGMSG"
} else {
continue
}
default:
continue
}
var tags map[string]string
2019-05-07 03:17:57 +00:00
if allowTags {
tags = item.Tags
}
2019-05-19 06:14:36 +00:00
if item.Params[0] == "" {
// this message was sent *to* the client from another nick
rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
} else {
// this message was sent *from* the client to another nick; the target is item.Params[0]
// substitute the client's current nickmask in case they changed nick
rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
}
}
2019-05-07 03:17:57 +00:00
rb.EndNestedBatch(batchID)
if !complete {
rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
}
}
2016-10-23 01:48:57 +00:00
// IdleTime returns how long this client's been idle.
2014-02-17 23:25:32 +00:00
func (client *Client) IdleTime() time.Duration {
2017-12-03 01:05:06 +00:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
2014-02-17 23:25:32 +00:00
return time.Since(client.atime)
}
2016-10-23 01:48:57 +00:00
// SignonTime returns this client's signon time as a unix timestamp.
2014-02-18 03:56:06 +00:00
func (client *Client) SignonTime() int64 {
return client.ctime.Unix()
}
2016-10-23 01:48:57 +00:00
// IdleSeconds returns the number of seconds this client's been idle.
2014-02-18 03:08:57 +00:00
func (client *Client) IdleSeconds() uint64 {
return uint64(client.IdleTime().Seconds())
}
2016-10-23 01:48:57 +00:00
// HasNick returns true if the client's nickname is set (used in registration).
func (client *Client) HasNick() bool {
2017-11-22 09:41:11 +00:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.nick != "" && client.nick != "*"
}
2017-04-16 01:31:33 +00:00
// HasUsername returns true if the client's username is set (used in registration).
func (client *Client) HasUsername() bool {
2017-11-22 09:41:11 +00:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.username != "" && client.username != "*"
}
2019-02-03 08:49:42 +00:00
// SetNames sets the client's ident and realname.
2019-02-05 07:40:49 +00:00
func (client *Client) SetNames(username, realname string, fromIdent bool) error {
limit := client.server.Config().Limits.IdentLen
if !fromIdent {
limit -= 1 // leave room for the prepended ~
}
2019-02-05 08:04:52 +00:00
if limit < len(username) {
2019-02-05 07:40:49 +00:00
username = username[:limit]
}
2019-02-03 08:49:42 +00:00
if !isIdent(username) {
return errInvalidUsername
}
2019-02-05 07:40:49 +00:00
if !fromIdent {
username = "~" + username
}
2019-02-03 08:49:42 +00:00
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
if client.username == "" {
2019-02-05 07:40:49 +00:00
client.username = username
}
if client.realname == "" {
client.realname = realname
}
return nil
}
// HasRoleCapabs returns true if client has the given (role) capabilities.
func (client *Client) HasRoleCapabs(capabs ...string) bool {
2018-04-19 06:48:19 +00:00
oper := client.Oper()
if oper == nil {
2016-10-23 01:13:08 +00:00
return false
}
for _, capab := range capabs {
2018-04-19 06:48:19 +00:00
if !oper.Class.Capabilities[capab] {
2016-10-23 01:13:08 +00:00
return false
}
}
return true
}
2017-04-16 01:31:33 +00:00
// ModeString returns the mode string for this client.
func (client *Client) ModeString() (str string) {
2018-04-22 22:47:10 +00:00
return "+" + client.flags.String()
2012-04-18 03:24:26 +00:00
}
2012-04-18 04:13:12 +00:00
// Friends refers to clients that share a channel with this client.
func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
result = make(map[*Session]bool)
// look at the client's own sessions
for _, session := range client.Sessions() {
if session.capabilities.HasAll(capabs...) {
result[session] = true
}
}
2017-10-22 23:50:16 +00:00
for _, channel := range client.Channels() {
for _, member := range channel.Members() {
for _, session := range member.Sessions() {
if session.capabilities.HasAll(capabs...) {
result[session] = true
}
}
2014-02-18 23:28:20 +00:00
}
}
return
}
func (client *Client) SetOper(oper *Oper) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
client.oper = oper
// operators typically get a vhost, update the nickmask
client.updateNickMaskNoMutex()
}
2018-04-19 06:48:19 +00:00
// XXX: CHGHOST requires prefix nickmask to have original hostname,
// this is annoying to do correctly
func (client *Client) sendChghost(oldNickMask string, vhost string) {
username := client.Username()
for fClient := range client.Friends(caps.ChgHost) {
fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
2018-04-19 06:48:19 +00:00
}
}
// choose the correct vhost to display
func (client *Client) getVHostNoMutex() string {
// hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
if client.vhost != "" {
return client.vhost
} else if client.oper != nil {
return client.oper.Vhost
} else {
return ""
}
}
// SetVHost updates the client's hostserv-based vhost
func (client *Client) SetVHost(vhost string) (updated bool) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
updated = (client.vhost != vhost)
client.vhost = vhost
if updated {
client.updateNickMaskNoMutex()
}
return
}
// updateNick updates `nick` and `nickCasefolded`.
func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
client.nick = nick
client.nickCasefolded = nickCasefolded
client.skeleton = skeleton
client.updateNickMaskNoMutex()
2016-10-16 10:35:50 +00:00
}
// updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
func (client *Client) updateNickMaskNoMutex() {
2018-04-19 06:48:19 +00:00
client.hostname = client.getVHostNoMutex()
if client.hostname == "" {
2019-05-12 06:17:57 +00:00
client.hostname = client.cloakedHostname
if client.hostname == "" {
client.hostname = client.rawHostname
}
}
cfhostname, err := Casefold(client.hostname)
if err != nil {
client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
cfhostname = client.hostname // YOLO
}
client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
2019-02-05 07:40:49 +00:00
client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
2016-06-19 05:37:29 +00:00
}
2017-01-11 12:38:16 +00:00
// AllNickmasks returns all the possible nickmasks for the client.
2019-01-29 04:03:30 +00:00
func (client *Client) AllNickmasks() (masks []string) {
2018-04-19 06:48:19 +00:00
client.stateMutex.RLock()
2019-01-29 04:03:30 +00:00
nick := client.nickCasefolded
2019-02-05 07:40:49 +00:00
username := client.username
2018-04-19 06:48:19 +00:00
rawHostname := client.rawHostname
2019-05-12 06:17:57 +00:00
cloakedHostname := client.cloakedHostname
2018-04-19 06:48:19 +00:00
vhost := client.getVHostNoMutex()
client.stateMutex.RUnlock()
2019-02-05 08:04:52 +00:00
username = strings.ToLower(username)
2018-04-19 06:48:19 +00:00
if len(vhost) > 0 {
2019-01-29 04:03:30 +00:00
cfvhost, err := Casefold(vhost)
2017-01-11 12:38:16 +00:00
if err == nil {
2019-01-29 04:03:30 +00:00
masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
2017-01-11 12:38:16 +00:00
}
}
2019-01-29 04:03:30 +00:00
var rawhostmask string
cfrawhost, err := Casefold(rawHostname)
2017-01-11 12:38:16 +00:00
if err == nil {
2019-01-29 04:03:30 +00:00
rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
masks = append(masks, rawhostmask)
2017-01-11 12:38:16 +00:00
}
2019-05-12 06:17:57 +00:00
if cloakedHostname != "" {
masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
}
2017-01-11 12:38:16 +00:00
2019-01-29 04:03:30 +00:00
ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
if ipmask != rawhostmask {
masks = append(masks, ipmask)
2017-01-11 12:38:16 +00:00
}
2019-01-29 04:03:30 +00:00
return
2017-01-11 12:38:16 +00:00
}
// LoggedIntoAccount returns true if this client is logged into an account.
func (client *Client) LoggedIntoAccount() bool {
return client.Account() != ""
}
2017-10-05 13:39:57 +00:00
// RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
2018-02-05 14:21:08 +00:00
func (client *Client) RplISupport(rb *ResponseBuffer) {
translatedISupport := client.t("are supported by this server")
2018-04-20 18:13:25 +00:00
nick := client.Nick()
config := client.server.Config()
for _, cachedTokenLine := range config.Server.isupport.CachedReply {
2018-04-20 18:13:25 +00:00
length := len(cachedTokenLine) + 2
tokenline := make([]string, length)
tokenline[0] = nick
copy(tokenline[1:], cachedTokenLine)
tokenline[length-1] = translatedISupport
rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
2017-10-05 13:39:57 +00:00
}
}
2019-02-10 18:57:32 +00:00
// Quit sets the given quit message for the client.
// (You must ensure separately that destroy() is called, e.g., by returning `true` from
// the command handler or calling it yourself.)
func (client *Client) Quit(message string, session *Session) {
setFinalData := func(sess *Session) {
message := sess.quitMessage
var finalData []byte
// #364: don't send QUIT lines to unregistered clients
if client.registered {
quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
finalData, _ = quitMsg.LineBytesStrict(false, 512)
}
2017-10-11 00:49:29 +00:00
errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
finalData = append(finalData, errorMsgBytes...)
2017-10-11 00:49:29 +00:00
sess.socket.SetFinalData(finalData)
2019-02-10 18:57:32 +00:00
}
2017-10-11 00:49:29 +00:00
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
var sessions []*Session
if session != nil {
sessions = []*Session{session}
} else {
sessions = client.sessions
}
2017-10-11 00:49:29 +00:00
for _, session := range sessions {
if session.SetQuitMessage(message) {
setFinalData(session)
}
}
}
2016-10-23 01:48:57 +00:00
// destroy gets rid of a client, removes them from server lists etc.
// if `session` is nil, destroys the client unconditionally, removing all sessions;
// otherwise, destroys one specific session, only destroying the client if it
// has no more sessions.
2019-05-22 01:40:25 +00:00
func (client *Client) destroy(session *Session) {
var sessionsToDestroy []*Session
client.stateMutex.Lock()
2019-05-08 22:14:49 +00:00
details := client.detailsNoMutex()
2019-05-22 01:40:25 +00:00
brbState := client.brbTimer.state
2019-05-27 08:18:07 +00:00
brbAt := client.brbTimer.brbAt
2019-05-08 22:14:49 +00:00
wasReattach := session != nil && session.client != client
sessionRemoved := false
var remainingSessions int
if session == nil {
sessionsToDestroy = client.sessions
client.sessions = nil
remainingSessions = 0
} else {
sessionRemoved, remainingSessions = client.removeSession(session)
if sessionRemoved {
sessionsToDestroy = []*Session{session}
}
}
2019-05-27 09:52:40 +00:00
// should we destroy the whole client this time?
shouldDestroy := !client.destroyed && remainingSessions == 0 && (brbState != BrbEnabled && brbState != BrbSticky)
if shouldDestroy {
// if it's our job to destroy it, don't let anyone else try
client.destroyed = true
}
client.stateMutex.Unlock()
2019-05-08 22:14:49 +00:00
// destroy all applicable sessions:
var quitMessage string
for _, session := range sessionsToDestroy {
if session.client != client {
// session has been attached to a new client; do not destroy it
continue
}
session.idletimer.Stop()
// send quit/error message to client if they haven't been sent already
client.Quit("", session)
2019-05-08 22:14:49 +00:00
quitMessage = session.quitMessage
2019-05-27 08:18:07 +00:00
session.SetDestroyed()
2019-05-08 22:14:49 +00:00
session.socket.Close()
// remove from connection limits
var source string
if client.isTor {
client.server.torLimiter.RemoveClient()
source = "tor"
} else {
ip := session.realIP
if session.proxiedIP != nil {
ip = session.proxiedIP
}
client.server.connectionLimiter.RemoveClient(ip)
source = ip.String()
}
client.server.logger.Info("localconnect-ip", fmt.Sprintf("disconnecting session of %s from %s", details.nick, source))
}
2019-05-22 01:40:25 +00:00
// do not destroy the client if it has either remaining sessions, or is BRB'ed
2019-05-27 09:52:40 +00:00
if !shouldDestroy {
return
2014-02-18 21:25:21 +00:00
}
2018-04-25 00:34:28 +00:00
// see #235: deduplicating the list of PART recipients uses (comparatively speaking)
// a lot of RAM, so limit concurrency to avoid thrashing
client.server.semaphores.ClientDestroy.Acquire()
defer client.server.semaphores.ClientDestroy.Release()
2019-05-22 01:40:25 +00:00
if !wasReattach {
2019-05-07 03:17:57 +00:00
client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", details.nick))
}
2019-05-08 22:14:49 +00:00
registered := client.Registered()
2019-05-22 01:40:25 +00:00
if registered {
2018-05-04 04:24:54 +00:00
client.server.whoWas.Append(client.WhoWas())
}
client.server.resumeManager.Delete(client)
2016-10-16 10:14:56 +00:00
// alert monitors
2019-05-08 22:14:49 +00:00
if registered {
client.server.monitorManager.AlertAbout(client, false)
}
// clean up monitor state
client.server.monitorManager.RemoveAll(client)
2016-10-16 10:14:56 +00:00
2019-05-07 03:17:57 +00:00
splitQuitMessage := utils.MakeSplitMessage(quitMessage, true)
// clean up channels
2019-05-08 22:14:49 +00:00
// (note that if this is a reattach, client has no channels and therefore no friends)
2018-04-25 00:23:01 +00:00
friends := make(ClientSet)
2017-10-30 09:21:47 +00:00
for _, channel := range client.Channels() {
2019-05-22 01:40:25 +00:00
channel.Quit(client)
channel.history.Add(history.Item{
Type: history.Quit,
Nick: details.nickMask,
AccountName: details.accountName,
Message: splitQuitMessage,
})
2017-10-22 23:50:16 +00:00
for _, member := range channel.Members() {
friends.Add(member)
}
}
2018-04-25 00:23:01 +00:00
friends.Remove(client)
// clean up server
2019-05-22 01:40:25 +00:00
client.server.clients.Remove(client)
// clean up self
client.nickTimer.Stop()
2019-05-22 01:40:25 +00:00
client.brbTimer.Disable()
client.server.accounts.Logout(client)
// send quit messages to friends
2019-05-22 01:40:25 +00:00
if registered {
client.server.stats.ChangeTotal(-1)
}
if client.HasMode(modes.Invisible) {
client.server.stats.ChangeInvisible(-1)
}
if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
client.server.stats.ChangeOperators(-1)
}
2019-05-27 08:18:07 +00:00
// this happens under failure to return from BRB
if quitMessage == "" {
if !brbAt.IsZero() {
awayMessage := client.AwayMessage()
if awayMessage != "" {
quitMessage = fmt.Sprintf("%s [%s ago]", awayMessage, time.Since(brbAt).Truncate(time.Second).String())
}
}
2019-05-27 08:18:07 +00:00
}
if quitMessage == "" {
quitMessage = "Exited"
}
for friend := range friends {
2019-05-22 01:40:25 +00:00
friend.sendFromClientInternal(false, splitQuitMessage.Time, splitQuitMessage.Msgid, details.nickMask, details.accountName, nil, "QUIT", quitMessage)
}
2019-05-22 01:40:25 +00:00
if !client.exitedSnomaskSent && registered {
client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), details.nick))
}
}
2014-02-18 21:25:21 +00:00
// SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
// Adds account-tag to the line as well.
2019-05-13 04:39:59 +00:00
func (session *Session) sendSplitMsgFromClientInternal(blocking bool, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
if session.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
2019-05-13 04:39:59 +00:00
session.sendFromClientInternal(blocking, message.Time, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
} else {
for _, messagePair := range message.Wrapped {
2019-05-13 04:39:59 +00:00
session.sendFromClientInternal(blocking, message.Time, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
}
}
}
2019-05-07 03:17:57 +00:00
// Sends a line with `nickmask` as the prefix, adding `time` and `account` tags if supported
func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
for _, session := range client.Sessions() {
err_ := session.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, params...)
if err_ != nil {
err = err_
}
}
return
}
func (session *Session) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
2016-09-12 01:25:31 +00:00
// attach account-tag
if session.capabilities.Has(caps.AccountTag) && accountName != "*" {
msg.SetTag("account", accountName)
2016-09-12 01:25:31 +00:00
}
2017-01-14 09:52:47 +00:00
// attach message-id
if msgid != "" && session.capabilities.Has(caps.MessageTags) {
2019-05-15 05:30:21 +00:00
msg.SetTag("msgid", msgid)
}
// attach server-time
if session.capabilities.Has(caps.ServerTime) {
2019-05-07 03:17:57 +00:00
if serverTime.IsZero() {
serverTime = time.Now().UTC()
}
msg.SetTag("time", serverTime.Format(IRCv3TimestampFormat))
2017-01-14 09:52:47 +00:00
}
2016-09-12 01:25:31 +00:00
return session.SendRawMessage(msg, blocking)
2016-09-12 01:25:31 +00:00
}
var (
// these are all the output commands that MUST have their last param be a trailing.
// this is needed because dumb clients like to treat trailing params separately from the
// other params in messages.
commandsThatMustUseTrailing = map[string]bool{
"PRIVMSG": true,
"NOTICE": true,
RPL_WHOISCHANNELS: true,
2017-03-06 05:50:23 +00:00
RPL_USERHOST: true,
}
)
// SendRawMessage sends a raw message to the client.
func (session *Session) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
// use dumb hack to force the last param to be a trailing param if required
var usedTrailingHack bool
2019-05-09 18:18:30 +00:00
config := session.client.server.Config()
if config.Server.Compatibility.forceTrailing && commandsThatMustUseTrailing[message.Command] && len(message.Params) > 0 {
lastParam := message.Params[len(message.Params)-1]
// to force trailing, we ensure the final param contains a space
if strings.IndexByte(lastParam, ' ') == -1 {
message.Params[len(message.Params)-1] = lastParam + " "
usedTrailingHack = true
}
}
// assemble message
maxlenRest := session.MaxlenRest()
line, err := message.LineBytesStrict(false, maxlenRest)
if err != nil {
logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
session.client.server.logger.Error("internal", logline)
message = ircmsg.MakeMessage(nil, session.client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
line, _ := message.LineBytesStrict(false, 0)
if blocking {
session.socket.BlockingWrite(line)
} else {
session.socket.Write(line)
}
return err
}
2018-04-15 16:28:25 +00:00
// if we used the trailing hack, we need to strip the final space we appended earlier on
if usedTrailingHack {
copy(line[len(line)-3:], "\r\n")
2018-04-26 19:32:32 +00:00
line = line[:len(line)-1]
2018-04-15 16:28:25 +00:00
}
if session.client.server.logger.IsLoggingRawIO() {
2018-04-26 19:32:32 +00:00
logline := string(line[:len(line)-2]) // strip "\r\n"
session.client.server.logger.Debug("useroutput", session.client.Nick(), " ->", logline)
2018-04-26 19:32:32 +00:00
}
if blocking {
return session.socket.BlockingWrite(line)
} else {
return session.socket.Write(line)
}
}
// Send sends an IRC line to the client.
func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
for _, session := range client.Sessions() {
err_ := session.Send(tags, prefix, command, params...)
if err_ != nil {
err = err_
}
}
return
}
func (session *Session) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
msg := ircmsg.MakeMessage(tags, prefix, command, params...)
if session.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
msg.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
}
return session.SendRawMessage(msg, false)
}
// Notice sends the client a notice from the server.
func (client *Client) Notice(text string) {
client.Send(nil, client.server.name, "NOTICE", client.Nick(), text)
}
2017-10-22 23:50:16 +00:00
func (client *Client) addChannel(channel *Channel) {
client.stateMutex.Lock()
client.channels[channel] = true
client.stateMutex.Unlock()
}
func (client *Client) removeChannel(channel *Channel) {
client.stateMutex.Lock()
delete(client.channels, channel)
client.stateMutex.Unlock()
}
2018-12-23 18:25:02 +00:00
// Records that the client has been invited to join an invite-only channel
func (client *Client) Invite(casefoldedChannel string) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
if client.invitedTo == nil {
client.invitedTo = make(map[string]bool)
}
client.invitedTo[casefoldedChannel] = true
}
// Checks that the client was invited to join a given channel
func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
invited = client.invitedTo[casefoldedChannel]
// joining an invited channel "uses up" your invite, so you can't rejoin on kick
delete(client.invitedTo, casefoldedChannel)
return
}