3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-12-01 16:39:26 +01:00
ergo/irc/client.go

938 lines
26 KiB
Go
Raw Normal View History

// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2014-2015 Edmund Huber
2017-03-27 14:15:02 +02:00
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
2012-04-07 20:44:59 +02:00
package irc
import (
2012-04-18 07:11:35 +02:00
"fmt"
"log"
2012-04-07 20:44:59 +02:00
"net"
2016-10-16 12:35:50 +02:00
"runtime/debug"
"strconv"
"strings"
2017-04-18 14:26:01 +02:00
"sync"
2017-10-23 01:50:16 +02:00
"sync/atomic"
2012-12-12 08:12:35 +01:00
"time"
2017-06-15 18:14:19 +02:00
"github.com/goshuirc/irc-go/ircfmt"
"github.com/goshuirc/irc-go/ircmsg"
2017-06-14 20:00:53 +02:00
ident "github.com/oragono/go-ident"
"github.com/oragono/oragono/irc/caps"
"github.com/oragono/oragono/irc/modes"
2017-06-14 20:00:53 +02:00
"github.com/oragono/oragono/irc/sno"
"github.com/oragono/oragono/irc/utils"
2012-04-07 20:44:59 +02:00
)
const (
// IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
IdentTimeoutSeconds = 1.5
)
var (
2018-02-03 13:03:36 +01:00
LoopbackIP = net.ParseIP("127.0.0.1")
)
2016-10-23 03:48:57 +02:00
// Client is an IRC client.
2012-04-07 20:44:59 +02:00
type Client struct {
account string
accountName string
atime time.Time
authorized bool
awayMessage string
capabilities *caps.Set
2018-02-03 12:15:07 +01:00
capState caps.State
capVersion caps.Version
certfp string
channels ChannelSet
ctime time.Time
exitedSnomaskSent bool
2018-03-22 16:04:21 +01:00
fakelag *Fakelag
2018-04-23 00:47:10 +02:00
flags *modes.ModeSet
hasQuit bool
2016-10-16 13:28:59 +02:00
hops int
hostname string
2017-10-15 18:24:28 +02:00
idletimer *IdleTimer
2017-04-18 14:26:01 +02:00
isDestroyed bool
isQuitting bool
languages []string
2017-10-23 01:50:16 +02:00
maxlenTags uint32
maxlenRest uint32
nick string
nickCasefolded string
nickMaskCasefolded string
2017-04-18 14:26:01 +02:00
nickMaskString string // cache for nickmask string since it's used with lots of replies
nickTimer *NickTimer
2018-04-19 08:48:19 +02:00
oper *Oper
2018-02-27 03:44:03 +01:00
preregNick string
2018-02-01 21:53:49 +01:00
proxiedIP net.IP // actual remote IP if using the PROXY protocol
quitMessage string
2017-04-18 14:26:01 +02:00
rawHostname string
realname string
registered bool
resumeDetails *ResumeDetails
saslInProgress bool
saslMechanism string
saslValue string
server *Server
socket *Socket
2017-11-22 10:41:11 +01:00
stateMutex sync.RWMutex // tier 1
username string
2017-04-18 14:26:01 +02:00
vhost string
}
2016-10-16 12:14:56 +02:00
// NewClient returns a client with all the appropriate info setup.
2016-06-28 17:09:07 +02:00
func NewClient(server *Server, conn net.Conn, isTLS bool) *Client {
2014-02-14 03:59:45 +01:00
now := time.Now()
2018-03-18 02:32:12 +01:00
limits := server.Limits()
fullLineLenLimit := limits.LineLen.Tags + limits.LineLen.Rest
socket := NewSocket(conn, fullLineLenLimit*2, server.MaxSendQBytes())
2012-12-09 21:51:50 +01:00
client := &Client{
atime: now,
authorized: server.Password() == nil,
capabilities: caps.NewSet(),
2018-02-03 12:15:07 +01:00
capState: caps.NoneState,
capVersion: caps.Cap301,
channels: make(ChannelSet),
ctime: now,
2018-04-23 00:47:10 +02:00
flags: modes.NewModeSet(),
server: server,
socket: socket,
nick: "*", // * is used until actual nick is given
nickCasefolded: "*",
nickMaskString: "*", // * is used until actual nick is given
2012-12-09 21:51:50 +01:00
}
client.languages = server.languages.Default()
client.recomputeMaxlens()
2016-06-28 17:09:07 +02:00
if isTLS {
2018-04-23 00:47:10 +02:00
client.SetMode(modes.TLS, true)
2016-09-07 13:32:58 +02:00
// error is not useful to us here anyways so we can ignore it
client.certfp, _ = client.socket.CertFP()
2016-06-28 17:09:07 +02:00
}
2018-02-01 21:53:49 +01:00
if server.checkIdent && !utils.AddrIsUnix(conn.RemoteAddr()) {
_, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
serverPort, _ := strconv.Atoi(serverPortString)
if err != nil {
log.Fatal(err)
}
clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
clientPort, _ := strconv.Atoi(clientPortString)
if err != nil {
log.Fatal(err)
}
client.Notice(client.t("*** Looking up your username"))
2016-07-02 11:12:00 +02:00
resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
if err == nil {
username := resp.Identifier
_, err := CasefoldName(username) // ensure it's a valid username
if err == nil {
client.Notice(client.t("*** Found your username"))
client.username = username
// we don't need to updateNickMask here since nickMask is not used for anything yet
} else {
client.Notice(client.t("*** Got a malformed username, ignoring"))
}
} else {
client.Notice(client.t("*** Could not find your username"))
}
}
2014-02-24 07:21:39 +01:00
go client.run()
2012-12-13 08:27:17 +01:00
2012-04-08 08:32:08 +02:00
return client
2012-04-07 20:44:59 +02:00
}
2018-03-22 16:04:21 +01:00
func (client *Client) resetFakelag() {
fakelag := func() *Fakelag {
if client.HasRoleCapabs("nofakelag") {
return nil
}
flc := client.server.FakelagConfig()
if !flc.Enabled {
return nil
}
return NewFakelag(flc.Window, flc.BurstLimit, flc.MessagesPerWindow, flc.Cooldown)
2018-03-22 16:04:21 +01:00
}()
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
client.fakelag = fakelag
}
// IP returns the IP address of this client.
func (client *Client) IP() net.IP {
2018-02-01 21:53:49 +01:00
if client.proxiedIP != nil {
return client.proxiedIP
}
2018-02-01 21:53:49 +01:00
if ip := utils.AddrToIP(client.socket.conn.RemoteAddr()); ip != nil {
return ip
}
// unix domain socket that hasn't issued PROXY/WEBIRC yet. YOLO
return LoopbackIP
}
// 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 07:21:39 +01:00
//
// command goroutine
//
2017-10-23 01:50:16 +02:00
func (client *Client) recomputeMaxlens() (int, int) {
maxlenTags := 512
maxlenRest := 512
if client.capabilities.Has(caps.MessageTags) {
maxlenTags = 4096
}
if client.capabilities.Has(caps.MaxLine) {
limits := client.server.Limits()
if limits.LineLen.Tags > maxlenTags {
maxlenTags = limits.LineLen.Tags
}
maxlenRest = limits.LineLen.Rest
}
2017-10-23 01:50:16 +02:00
atomic.StoreUint32(&client.maxlenTags, uint32(maxlenTags))
atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
return maxlenTags, maxlenRest
}
2017-10-23 01:50:16 +02:00
// allow these negotiated length limits to be read without locks; this is a convenience
// so that Client.Send doesn't have to acquire any Client locks
func (client *Client) maxlens() (int, int) {
return int(atomic.LoadUint32(&client.maxlenTags)), int(atomic.LoadUint32(&client.maxlenRest))
}
2014-02-24 07:21:39 +01:00
func (client *Client) run() {
var err error
var isExiting bool
var line string
var msg ircmsg.IrcMessage
2017-10-24 00:38:32 +02:00
defer func() {
2017-10-26 11:15:55 +02:00
if r := recover(); r != nil {
client.server.logger.Error("internal",
fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
if client.server.RecoverFromErrors() {
client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
} else {
panic(r)
2017-10-26 10:19:01 +02:00
}
2017-10-24 00:38:32 +02:00
}
// ensure client connection gets closed
2018-01-21 02:59:52 +01:00
client.destroy(false)
2017-10-24 00:38:32 +02:00
}()
2017-10-15 18:24:28 +02:00
client.idletimer = NewIdleTimer(client)
client.idletimer.Start()
client.nickTimer = NewNickTimer(client)
2018-03-22 16:04:21 +01:00
client.resetFakelag()
// Set the hostname for this client
// (may be overridden by a later PROXY command from stunnel)
client.rawHostname = utils.AddrLookupHostname(client.socket.conn.RemoteAddr())
for {
2017-10-23 01:50:16 +02:00
maxlenTags, maxlenRest := client.recomputeMaxlens()
line, err = client.socket.Read()
if err != nil {
2018-03-18 02:32:12 +01:00
quitMessage := "connection closed"
if err == errReadQ {
quitMessage = "readQ exceeded"
}
client.Quit(quitMessage)
break
}
client.server.logger.Debug("userinput ", client.nick, "<- ", line)
msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
if err == ircmsg.ErrorLineIsEmpty {
continue
} else if err != nil {
client.Quit(client.t("Received malformed line"))
break
2014-02-24 07:21:39 +01:00
}
cmd, exists := Commands[msg.Command]
if !exists {
if len(msg.Command) > 0 {
client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, client.t("Unknown command"))
} else {
client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", client.t("No command given"))
}
continue
}
isExiting = cmd.Run(client.server, client, msg)
2016-06-22 14:04:13 +02:00
if isExiting || client.isQuitting {
break
}
2014-02-24 07:21:39 +01:00
}
}
//
// 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).
2014-02-18 22:25:21 +01:00
func (client *Client) Active() {
2017-12-03 02:05:06 +01:00
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
client.atime = time.Now()
2014-02-18 22:25:21 +01:00
}
// Touch marks the client as alive (as it it has a connection to us and we
2017-10-15 18:24:28 +02:00
// can receive messages from it).
2014-02-18 22:25:21 +01:00
func (client *Client) Touch() {
2017-10-15 18:24:28 +02:00
client.idletimer.Touch()
2014-02-09 21:13:09 +01:00
}
2017-10-15 18:24:28 +02:00
// Ping sends the client a PING message.
func (client *Client) Ping() {
client.Send(nil, "", "PING", client.nick)
}
2016-10-16 12:35:50 +02:00
// Register sets the client details as appropriate when entering the network.
2014-02-18 22:25:21 +01:00
func (client *Client) Register() {
2017-10-15 18:24:28 +02:00
client.stateMutex.Lock()
alreadyRegistered := client.registered
client.registered = true
client.stateMutex.Unlock()
if alreadyRegistered {
return
}
2016-10-16 12:14:56 +02:00
// apply resume details if we're able to.
client.TryResume()
// finish registration
client.updateNickMask("")
client.server.monitorManager.AlertAbout(client, true)
2012-12-13 08:27:17 +01:00
}
// TryResume tries to resume if the client asked us to.
func (client *Client) TryResume() {
if client.resumeDetails == nil {
return
}
server := client.server
// just grab these mutexes for safety. later we can work out whether we can grab+release them earlier
server.clients.Lock()
defer server.clients.Unlock()
server.channels.Lock()
defer server.channels.Unlock()
oldnick := client.resumeDetails.OldNick
timestamp := client.resumeDetails.Timestamp
var timestampString string
if timestamp != nil {
2018-01-21 03:23:47 +01:00
timestampString = timestamp.UTC().Format("2006-01-02T15:04:05.999Z")
}
2018-01-21 03:23:47 +01:00
// can't use server.clients.Get since we hold server.clients' tier 1 mutex
casefoldedName, err := CasefoldName(oldnick)
if err != nil {
client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
2018-01-21 03:23:47 +01:00
return
}
oldClient := server.clients.byNick[casefoldedName]
if oldClient == nil {
client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
return
}
oldAccountName := oldClient.Account()
newAccountName := client.Account()
if oldAccountName == "" || newAccountName == "" || oldAccountName != newAccountName {
client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must be logged into the same account"))
return
}
if !oldClient.HasMode(modes.TLS) || !client.HasMode(modes.TLS) {
client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
return
}
// unmark the new client's nick as being occupied
server.clients.removeInternal(client)
// send RESUMED to the reconnecting client
if timestamp == nil {
client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
} else {
client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
}
// send QUIT/RESUMED to friends
for friend := range oldClient.Friends() {
if friend.capabilities.Has(caps.Resume) {
if timestamp == nil {
friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
} else {
friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
}
} else {
friend.Send(nil, oldClient.NickMaskString(), "QUIT", friend.t("Client reconnected"))
}
}
// apply old client's details to new client
client.nick = oldClient.nick
client.updateNickMaskNoMutex()
2018-04-24 09:11:11 +02:00
rejoinChannel := func(channel *Channel) {
channel.joinPartMutex.Lock()
defer channel.joinPartMutex.Unlock()
2018-04-24 09:11:11 +02:00
channel.stateMutex.Lock()
client.channels[channel] = true
2018-01-21 04:13:20 +01:00
client.resumeDetails.SendFakeJoinsFor = append(client.resumeDetails.SendFakeJoinsFor, channel.name)
oldModeSet := channel.members[oldClient]
channel.members.Remove(oldClient)
channel.members[client] = oldModeSet
2018-04-24 09:11:11 +02:00
channel.stateMutex.Unlock()
channel.regenerateMembersCache()
// construct fake modestring if necessary
oldModes := oldModeSet.String()
var params []string
if 0 < len(oldModes) {
params = []string{channel.name, "+" + oldModes}
2018-02-03 13:03:36 +01:00
for range oldModes {
params = append(params, client.nick)
}
}
// send join for old clients
for member := range channel.members {
if member.capabilities.Has(caps.Resume) {
continue
}
if member.capabilities.Has(caps.ExtendedJoin) {
member.Send(nil, client.nickMaskString, "JOIN", channel.name, client.AccountName(), client.realname)
} else {
member.Send(nil, client.nickMaskString, "JOIN", channel.name)
}
// send fake modestring if necessary
if 0 < len(oldModes) {
member.Send(nil, server.name, "MODE", params...)
}
}
2018-04-24 09:11:11 +02:00
}
2018-04-24 09:11:11 +02:00
for channel := range oldClient.channels {
rejoinChannel(channel)
}
server.clients.byNick[oldnick] = client
oldClient.destroy(true)
}
2016-10-23 03:48:57 +02:00
// IdleTime returns how long this client's been idle.
2014-02-18 00:25:32 +01:00
func (client *Client) IdleTime() time.Duration {
2017-12-03 02:05:06 +01:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
2014-02-18 00:25:32 +01:00
return time.Since(client.atime)
}
2016-10-23 03:48:57 +02:00
// SignonTime returns this client's signon time as a unix timestamp.
2014-02-18 04:56:06 +01:00
func (client *Client) SignonTime() int64 {
return client.ctime.Unix()
}
2016-10-23 03:48:57 +02:00
// IdleSeconds returns the number of seconds this client's been idle.
2014-02-18 04:08:57 +01:00
func (client *Client) IdleSeconds() uint64 {
return uint64(client.IdleTime().Seconds())
}
2016-10-23 03:48:57 +02:00
// HasNick returns true if the client's nickname is set (used in registration).
func (client *Client) HasNick() bool {
2017-11-22 10:41:11 +01:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.nick != "" && client.nick != "*"
}
2017-04-16 03:31:33 +02:00
// HasUsername returns true if the client's username is set (used in registration).
func (client *Client) HasUsername() bool {
2017-11-22 10:41:11 +01:00
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.username != "" && client.username != "*"
}
// HasRoleCapabs returns true if client has the given (role) capabilities.
func (client *Client) HasRoleCapabs(capabs ...string) bool {
2018-04-19 08:48:19 +02:00
oper := client.Oper()
if oper == nil {
2016-10-23 03:13:08 +02:00
return false
}
for _, capab := range capabs {
2018-04-19 08:48:19 +02:00
if !oper.Class.Capabilities[capab] {
2016-10-23 03:13:08 +02:00
return false
}
}
return true
}
2017-04-16 03:31:33 +02:00
// ModeString returns the mode string for this client.
func (client *Client) ModeString() (str string) {
2018-04-23 00:47:10 +02:00
return "+" + client.flags.String()
2012-04-18 05:24:26 +02:00
}
2012-04-18 06:13:12 +02:00
// Friends refers to clients that share a channel with this client.
func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
2014-02-19 00:28:20 +01:00
friends := make(ClientSet)
// make sure that I have the right caps
hasCaps := true
for _, capab := range capabs {
if !client.capabilities.Has(capab) {
hasCaps = false
break
}
}
if hasCaps {
friends.Add(client)
}
2017-10-23 01:50:16 +02:00
for _, channel := range client.Channels() {
for _, member := range channel.Members() {
// make sure they have all the required caps
hasCaps = true
for _, capab := range capabs {
if !member.capabilities.Has(capab) {
hasCaps = false
break
}
}
if hasCaps {
friends.Add(member)
}
2014-02-19 00:28:20 +01:00
}
}
2014-02-19 00:28:20 +01:00
return friends
}
2018-04-19 08:48:19 +02: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("", client, oldNickMask, nil, "CHGHOST", username, vhost)
}
}
// 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 string) {
casefoldedName, err := CasefoldName(nick)
if err != nil {
2018-04-23 08:38:35 +02:00
client.server.logger.Error("internal", "nick couldn't be casefolded", nick, err.Error())
return
}
client.stateMutex.Lock()
client.nick = nick
client.nickCasefolded = casefoldedName
client.stateMutex.Unlock()
2016-10-16 12:35:50 +02:00
}
// updateNickMask updates the casefolded nickname and nickmask.
func (client *Client) updateNickMask(nick string) {
// on "", just regenerate the nickmask etc.
// otherwise, update the actual nick
if nick != "" {
client.updateNick(nick)
}
client.stateMutex.Lock()
2017-11-22 10:41:11 +01:00
defer client.stateMutex.Unlock()
client.updateNickMaskNoMutex()
}
2018-04-19 08:48:19 +02:00
// updateNickMask updates the casefolded nickname and nickmask, not acquiring any mutexes.
func (client *Client) updateNickMaskNoMutex() {
2018-04-19 08:48:19 +02:00
client.hostname = client.getVHostNoMutex()
if client.hostname == "" {
client.hostname = client.rawHostname
}
nickMaskString := fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
nickMaskCasefolded, err := Casefold(nickMaskString)
if err != nil {
2018-04-23 08:38:35 +02:00
client.server.logger.Error("internal", "nickmask couldn't be casefolded", nickMaskString, err.Error())
return
}
client.nickMaskString = nickMaskString
client.nickMaskCasefolded = nickMaskCasefolded
2016-06-19 07:37:29 +02:00
}
2017-01-11 13:38:16 +01:00
// AllNickmasks returns all the possible nickmasks for the client.
func (client *Client) AllNickmasks() []string {
var masks []string
var mask string
var err error
2018-04-19 08:48:19 +02:00
client.stateMutex.RLock()
nick := client.nick
username := client.username
rawHostname := client.rawHostname
vhost := client.getVHostNoMutex()
client.stateMutex.RUnlock()
if len(vhost) > 0 {
mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, vhost))
2017-01-11 13:38:16 +01:00
if err == nil {
masks = append(masks, mask)
}
}
2018-04-19 08:48:19 +02:00
mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, rawHostname))
2017-01-11 13:38:16 +01:00
if err == nil {
masks = append(masks, mask)
}
2018-04-19 08:48:19 +02:00
mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", nick, username, client.IPString()))
2017-01-11 13:38:16 +01:00
if err == nil && mask2 != mask {
masks = append(masks, mask2)
}
return masks
}
// LoggedIntoAccount returns true if this client is logged into an account.
func (client *Client) LoggedIntoAccount() bool {
return client.Account() != ""
}
2017-10-05 15:39:57 +02:00
// RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
2018-02-05 15:21:08 +01:00
func (client *Client) RplISupport(rb *ResponseBuffer) {
translatedISupport := client.t("are supported by this server")
2018-04-20 20:13:25 +02:00
nick := client.Nick()
for _, cachedTokenLine := range client.server.ISupport().CachedReply {
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 15:39:57 +02:00
}
}
// Quit sets the given quit message for the client and tells the client to quit out.
func (client *Client) Quit(message string) {
2017-10-11 02:49:29 +02:00
client.stateMutex.Lock()
2017-10-15 18:24:28 +02:00
alreadyQuit := client.isQuitting
2017-10-11 02:49:29 +02:00
if !alreadyQuit {
2017-10-15 18:24:28 +02:00
client.isQuitting = true
client.quitMessage = message
}
2017-10-11 02:49:29 +02:00
client.stateMutex.Unlock()
if alreadyQuit {
return
}
quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
quitLine, _ := quitMsg.Line()
errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
errorLine, _ := errorMsg.Line()
client.socket.SetFinalData(quitLine + errorLine)
}
2016-10-23 03:48:57 +02:00
// destroy gets rid of a client, removes them from server lists etc.
func (client *Client) destroy(beingResumed bool) {
2017-10-11 18:48:06 +02:00
// allow destroy() to execute at most once
if !beingResumed {
client.stateMutex.Lock()
}
isDestroyed := client.isDestroyed
client.isDestroyed = true
if !beingResumed {
client.stateMutex.Unlock()
}
if isDestroyed {
return
2014-02-18 22:25:21 +01:00
}
2018-04-25 02:34:28 +02: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()
if beingResumed {
client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
} else {
client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
}
// send quit/error message to client if they haven't been sent already
client.Quit("Connection closed")
if !beingResumed {
2018-05-04 06:24:54 +02:00
client.server.whoWas.Append(client.WhoWas())
}
// remove from connection limits
ipaddr := client.IP()
// this check shouldn't be required but eh
if ipaddr != nil {
client.server.connectionLimiter.RemoveClient(ipaddr)
}
2016-10-16 12:14:56 +02:00
// alert monitors
client.server.monitorManager.AlertAbout(client, false)
// clean up monitor state
client.server.monitorManager.RemoveAll(client)
2016-10-16 12:14:56 +02:00
// clean up channels
2018-04-25 02:23:01 +02:00
friends := make(ClientSet)
2017-10-30 10:21:47 +01:00
for _, channel := range client.Channels() {
if !beingResumed {
channel.Quit(client)
}
2017-10-23 01:50:16 +02:00
for _, member := range channel.Members() {
friends.Add(member)
}
}
2018-04-25 02:23:01 +02:00
friends.Remove(client)
// clean up server
if !beingResumed {
client.server.clients.Remove(client)
}
// clean up self
client.idletimer.Stop()
client.nickTimer.Stop()
client.server.accounts.Logout(client)
client.socket.Close()
// send quit messages to friends
if !beingResumed {
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)
}
for friend := range friends {
if client.quitMessage == "" {
client.quitMessage = "Exited"
}
friend.Send(nil, client.nickMaskString, "QUIT", client.quitMessage)
}
}
if !client.exitedSnomaskSent {
if beingResumed {
client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
} else {
client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
}
}
}
2014-02-18 22:25:21 +01:00
// SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
// Adds account-tag to the line as well.
2017-01-14 10:52:47 +01:00
func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
if client.capabilities.Has(caps.MaxLine) {
2017-01-17 23:05:31 +01:00
client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
} else {
for _, str := range message.For512 {
2017-01-17 23:05:31 +01:00
client.SendFromClient(msgid, from, tags, command, target, str)
}
}
}
2016-09-12 03:25:31 +02:00
// SendFromClient sends an IRC line coming from a specific client.
// Adds account-tag to the line as well.
2017-01-14 12:48:57 +01:00
func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
2018-04-19 08:48:19 +02:00
return client.sendFromClientInternal(msgid, from, from.NickMaskString(), tags, command, params...)
}
// XXX this is a hack where we allow overriding the client's nickmask
// this is to support CHGHOST, which requires that we send the *original* nickmask with the response
func (client *Client) sendFromClientInternal(msgid string, from *Client, nickmask string, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
2016-09-12 03:25:31 +02:00
// attach account-tag
2018-02-11 12:31:23 +01:00
if client.capabilities.Has(caps.AccountTag) && from.LoggedIntoAccount() {
2016-09-12 03:25:31 +02:00
if tags == nil {
tags = ircmsg.MakeTags("account", from.AccountName())
2016-09-12 03:25:31 +02:00
} else {
(*tags)["account"] = ircmsg.MakeTagValue(from.AccountName())
2016-09-12 03:25:31 +02:00
}
}
2017-01-14 10:52:47 +01:00
// attach message-id
if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
2017-01-14 10:52:47 +01:00
if tags == nil {
tags = ircmsg.MakeTags("draft/msgid", msgid)
} else {
(*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
}
}
2016-09-12 03:25:31 +02:00
2018-04-19 08:48:19 +02:00
return client.Send(tags, nickmask, command, params...)
2016-09-12 03:25:31 +02: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 06:50:23 +01:00
RPL_USERHOST: true,
}
)
// SendRawMessage sends a raw message to the client.
func (client *Client) SendRawMessage(message ircmsg.IrcMessage) error {
// use dumb hack to force the last param to be a trailing param if required
var usedTrailingHack bool
if commandsThatMustUseTrailing[strings.ToUpper(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.Contains(lastParam, " ") {
message.Params[len(message.Params)-1] = lastParam + " "
usedTrailingHack = true
}
}
// assemble message
maxlenTags, maxlenRest := client.maxlens()
2018-04-26 21:32:32 +02:00
line, err := message.LineMaxLenBytes(maxlenTags, maxlenRest)
if err != nil {
logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
client.server.logger.Error("internal", logline)
message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
2018-04-26 21:32:32 +02:00
line, _ := message.LineBytes()
client.socket.Write(line)
return err
}
2018-04-15 18:28:25 +02:00
// if we used the trailing hack, we need to strip the final space we appended earlier on
if usedTrailingHack {
2018-04-26 21:32:32 +02:00
copy(line[len(line)-3:], []byte{'\r', '\n'})
line = line[:len(line)-1]
2018-04-15 18:28:25 +02:00
}
2018-04-26 21:32:32 +02:00
if client.server.logger.IsLoggingRawIO() {
logline := string(line[:len(line)-2]) // strip "\r\n"
client.server.logger.Debug("useroutput", client.nick, " ->", logline)
}
client.socket.Write(line)
return nil
}
// Send sends an IRC line to the client.
func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
// attach server-time
if client.capabilities.Has(caps.ServerTime) {
t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
if tags == nil {
tags = ircmsg.MakeTags("time", t)
} else {
(*tags)["time"] = ircmsg.MakeTagValue(t)
}
}
// send out the message
message := ircmsg.MakeMessage(tags, prefix, command, params...)
client.SendRawMessage(message)
return nil
}
// Notice sends the client a notice from the server.
func (client *Client) Notice(text string) {
limit := 400
if client.capabilities.Has(caps.MaxLine) {
limit = client.server.Limits().LineLen.Rest - 110
}
lines := wordWrap(text, limit)
2018-02-03 10:00:27 +01:00
// force blank lines to be sent if we receive them
if len(lines) == 0 {
lines = []string{""}
}
for _, line := range lines {
client.Send(nil, client.server.name, "NOTICE", client.nick, line)
}
}
2017-10-23 01:50:16 +02: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()
}