ircd/irc/client.go

649 lines
18 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 (
"errors"
2012-04-18 05:11:35 +00:00
"fmt"
"log"
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"
2012-12-12 07:12:35 +00:00
"time"
2017-05-28 18:43:09 +00:00
"github.com/DanielOaks/girc-go/ircfmt"
"github.com/DanielOaks/girc-go/ircmsg"
2017-06-14 18:00:53 +00:00
ident "github.com/oragono/go-ident"
"github.com/oragono/oragono/irc/sno"
2012-04-07 18:44:59 +00:00
)
const (
2016-07-02 09:12:00 +00:00
IDLE_TIMEOUT = time.Minute + time.Second*30 // how long before a client is considered idle
QUIT_TIMEOUT = time.Minute // how long after idle before a client is kicked
IdentTimeoutSeconds = 5
)
var (
TIMEOUT_STATED_SECONDS = strconv.Itoa(int((IDLE_TIMEOUT + QUIT_TIMEOUT).Seconds()))
ErrNickAlreadySet = errors.New("Nickname is already set")
)
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 *ClientAccount
atime time.Time
authorized bool
awayMessage string
capabilities CapabilitySet
capState CapState
2016-10-16 03:54:09 +00:00
capVersion CapVersion
certfp string
channels ChannelSet
class *OperClass
ctime time.Time
2017-04-18 12:26:01 +00:00
destroyMutex sync.Mutex
exitedSnomaskSent bool
2017-03-24 02:23:21 +00:00
flags map[Mode]bool
hasQuit bool
2016-10-16 11:28:59 +00:00
hops int
hostname string
idleTimer *time.Timer
2017-04-18 12:26:01 +00:00
isDestroyed bool
isQuitting bool
2016-10-16 10:14:56 +00:00
monitoring map[string]bool
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
operName string
quitMessageSent bool
2017-04-18 12:26:01 +00:00
quitMutex sync.Mutex
quitTimer *time.Timer
rawHostname string
realname string
registered bool
saslInProgress bool
saslMechanism string
saslValue string
server *Server
socket *Socket
2017-04-18 12:26:01 +00:00
timerMutex sync.Mutex
username string
2017-04-18 12:26:01 +00:00
vhost string
whoisLine string
}
2016-10-16 10:14:56 +00:00
// NewClient returns a client with all the appropriate info setup.
2016-06-28 15:09:07 +00:00
func NewClient(server *Server, conn net.Conn, isTLS bool) *Client {
2014-02-14 02:59:45 +00:00
now := time.Now()
2017-03-13 22:12:39 +00:00
socket := NewSocket(conn, server.MaxSendQBytes)
go socket.RunSocketWriter()
2012-12-09 20:51:50 +00:00
client := &Client{
atime: now,
authorized: server.password == nil,
capabilities: make(CapabilitySet),
2016-10-16 03:54:09 +00:00
capState: CapNone,
capVersion: Cap301,
channels: make(ChannelSet),
ctime: now,
2017-03-24 02:23:21 +00:00
flags: make(map[Mode]bool),
2016-10-16 10:14:56 +00:00
monitoring: make(map[string]bool),
server: server,
socket: &socket,
account: &NoAccount,
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
}
2016-06-28 15:09:07 +00:00
if isTLS {
client.flags[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, _ = client.socket.CertFP()
2016-06-28 15:09:07 +00:00
}
if server.checkIdent {
_, 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("*** Looking up your username")
2016-07-02 09:12:00 +00: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("*** Found your username")
client.username = username
// we don't need to updateNickMask here since nickMask is not used for anything yet
} else {
client.Notice("*** Got a malformed username, ignoring")
}
} else {
client.Notice("*** Could not find your username")
}
}
client.Touch()
2014-02-24 06:21:39 +00:00
go client.run()
2012-12-13 07:27:17 +00:00
2012-04-08 06:32:08 +00:00
return client
2012-04-07 18:44:59 +00:00
}
// IP returns the IP address of this client.
func (client *Client) IP() net.IP {
return net.ParseIP(IPString(client.socket.conn.RemoteAddr()))
}
2014-02-24 06:21:39 +00:00
//
// command goroutine
//
func (client *Client) maxlens() (int, int) {
maxlenTags := 512
maxlenRest := 512
if client.capabilities[MessageTags] {
maxlenTags = 4096
}
if client.capabilities[MaxLine] {
if client.server.limits.LineLen.Tags > maxlenTags {
maxlenTags = client.server.limits.LineLen.Tags
}
maxlenRest = client.server.limits.LineLen.Rest
}
return maxlenTags, maxlenRest
}
2014-02-24 06:21:39 +00:00
func (client *Client) run() {
var err error
var isExiting bool
var line string
var msg ircmsg.IrcMessage
// Set the hostname for this client
client.rawHostname = AddrLookupHostname(client.socket.conn.RemoteAddr())
for {
line, err = client.socket.Read()
if err != nil {
client.Quit("connection closed")
break
}
maxlenTags, maxlenRest := client.maxlens()
2016-11-29 08:38:04 +00:00
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("received malformed line")
break
2014-02-24 06:21:39 +00: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, "Unknown command")
} else {
client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", "No command given")
}
continue
}
isExiting = cmd.Run(client.server, client, msg)
2016-06-22 12:04:13 +00:00
if isExiting || client.isQuitting {
break
}
2014-02-24 06:21:39 +00:00
}
// ensure client connection gets closed
client.destroy()
}
//
// 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 21:25:21 +00:00
func (client *Client) Active() {
client.atime = time.Now()
2014-02-18 21:25:21 +00:00
}
// Touch marks the client as alive (as it it has a connection to us and we
// can receive messages from it), and resets when we'll send the client a
// keepalive PING.
2014-02-18 21:25:21 +00:00
func (client *Client) Touch() {
2017-04-18 12:26:01 +00:00
client.timerMutex.Lock()
defer client.timerMutex.Unlock()
2014-02-09 20:13:09 +00:00
if client.quitTimer != nil {
client.quitTimer.Stop()
}
2014-02-09 20:13:09 +00:00
if client.idleTimer == nil {
client.idleTimer = time.AfterFunc(IDLE_TIMEOUT, client.connectionIdle)
2014-02-09 20:13:09 +00:00
} else {
client.idleTimer.Reset(IDLE_TIMEOUT)
}
}
// connectionIdle is run when the client has not sent us any data for a while,
// sends the client a PING and starts the quit timeout.
func (client *Client) connectionIdle() {
2017-04-18 12:26:01 +00:00
client.timerMutex.Lock()
defer client.timerMutex.Unlock()
client.Send(nil, "", "PING", client.nick)
2014-02-09 20:13:09 +00:00
if client.quitTimer == nil {
client.quitTimer = time.AfterFunc(QUIT_TIMEOUT, client.connectionTimeout)
2014-02-09 20:13:09 +00:00
} else {
client.quitTimer.Reset(QUIT_TIMEOUT)
}
}
// connectionTimeout runs after connectionIdle has been run, if we do not receive a
// ping or any other activity back from the client. When this happens we assume the
// connection has died and remove the client from the network.
func (client *Client) connectionTimeout() {
client.Quit(fmt.Sprintf("Ping timeout: %s seconds", TIMEOUT_STATED_SECONDS))
client.isQuitting = true
}
//
// server goroutine
//
2016-10-16 10:35:50 +00:00
// Register sets the client details as appropriate when entering the network.
2014-02-18 21:25:21 +00:00
func (client *Client) Register() {
if client.registered {
return
}
client.registered = true
2014-02-18 21:25:21 +00:00
client.Touch()
2016-10-16 10:14:56 +00:00
2016-10-16 10:35:50 +00:00
client.updateNickMask()
2016-10-16 10:14:56 +00:00
client.alertMonitors()
2012-12-13 07:27:17 +00:00
}
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 {
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 {
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 {
return client.username != "" && client.username != "*"
}
2016-10-23 01:13:08 +00:00
// HasCapabs returns true if client has the given (role) capabilities.
func (client *Client) HasCapabs(capabs ...string) bool {
if client.class == nil {
return false
}
for _, capab := range capabs {
if !client.class.Capabilities[capab] {
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) {
2016-09-07 11:50:42 +00:00
str = "+"
2017-04-16 01:31:33 +00:00
for flag := range client.flags {
2014-02-17 21:22:35 +00:00
str += flag.String()
2014-02-09 18:07:40 +00:00
}
2014-02-09 16:53:06 +00:00
return
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(Capabilities ...Capability) ClientSet {
2014-02-18 23:28:20 +00:00
friends := make(ClientSet)
// make sure that I have the right caps
hasCaps := true
for _, Cap := range Capabilities {
if !client.capabilities[Cap] {
hasCaps = false
break
}
}
if hasCaps {
friends.Add(client)
}
2014-02-18 23:28:20 +00:00
for channel := range client.channels {
2017-01-10 16:09:08 +00:00
channel.membersMutex.RLock()
2014-02-18 23:28:20 +00:00
for member := range channel.members {
// make sure they have all the required caps
for _, Cap := range Capabilities {
if !member.capabilities[Cap] {
continue
}
}
2014-02-18 23:28:20 +00:00
friends.Add(member)
}
2017-03-24 11:54:06 +00:00
channel.membersMutex.RUnlock()
}
2014-02-18 23:28:20 +00:00
return friends
}
2016-10-16 10:35:50 +00:00
// updateNick updates the casefolded nickname.
func (client *Client) updateNick() {
casefoldedName, err := CasefoldName(client.nick)
if err != nil {
2016-10-16 10:35:50 +00:00
log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nick))
debug.PrintStack()
}
client.nickCasefolded = casefoldedName
2016-10-16 10:35:50 +00:00
}
// updateNickMask updates the casefolded nickname and nickmask.
func (client *Client) updateNickMask() {
client.updateNick()
if len(client.vhost) > 0 {
client.hostname = client.vhost
} else {
client.hostname = client.rawHostname
}
client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
nickMaskCasefolded, err := Casefold(client.nickMaskString)
if err != nil {
2016-10-16 10:35:50 +00:00
log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nickMaskString))
debug.PrintStack()
}
client.nickMaskCasefolded = nickMaskCasefolded
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.
func (client *Client) AllNickmasks() []string {
var masks []string
var mask string
var err error
if len(client.vhost) > 0 {
mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.vhost))
if err == nil {
masks = append(masks, mask)
}
}
mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.rawHostname))
if err == nil {
masks = append(masks, mask)
}
mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, IPString(client.socket.conn.RemoteAddr())))
if err == nil && mask2 != mask {
masks = append(masks, mask2)
}
return masks
}
2016-10-23 01:48:57 +00:00
// SetNickname sets the very first nickname for the client.
func (client *Client) SetNickname(nickname string) error {
if client.HasNick() {
client.server.logger.Error("nick", fmt.Sprintf("%s nickname already set, something is wrong with server consistency", client.nickMaskString))
return ErrNickAlreadySet
}
err := client.server.clients.Add(client, nickname)
if err == nil {
client.nick = nickname
client.updateNick()
}
return err
2014-02-18 23:36:58 +00:00
}
2016-10-23 01:48:57 +00:00
// ChangeNickname changes the existing nickname of the client.
func (client *Client) ChangeNickname(nickname string) error {
2016-06-19 05:37:29 +00:00
origNickMask := client.nickMaskString
2016-11-16 02:02:22 +00:00
err := client.server.clients.Replace(client.nick, nickname, client)
if err == nil {
client.server.logger.Debug("nick", fmt.Sprintf("%s changed nickname to %s", client.nick, nickname))
2017-06-10 23:07:44 +00:00
client.server.snomasks.Send(sno.LocalNicks, fmt.Sprintf(ircfmt.Unescape("$%s$r changed nickname to %s"), client.nick, nickname))
2016-11-16 02:02:22 +00:00
client.server.whoWas.Append(client)
client.nick = nickname
client.updateNickMask()
2016-11-16 02:02:22 +00:00
for friend := range client.Friends() {
friend.Send(nil, origNickMask, "NICK", nickname)
}
2014-02-22 19:40:32 +00:00
}
2016-11-16 02:02:22 +00:00
return err
2014-02-22 19:40:32 +00:00
}
2017-04-16 01:31:33 +00:00
// Quit sends the given quit message to the client (but does not destroy them).
func (client *Client) Quit(message string) {
2017-04-18 12:26:01 +00:00
client.quitMutex.Lock()
defer client.quitMutex.Unlock()
if !client.quitMessageSent {
quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
quitLine, _ := quitMsg.Line()
errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
errorLine, _ := errorMsg.Line()
2017-04-18 12:26:01 +00:00
client.socket.SetFinalData(quitLine + errorLine)
client.quitMessageSent = true
}
}
2016-10-23 01:48:57 +00:00
// destroy gets rid of a client, removes them from server lists etc.
func (client *Client) destroy() {
2017-04-18 12:26:01 +00:00
client.destroyMutex.Lock()
defer client.destroyMutex.Unlock()
if client.isDestroyed {
2014-02-18 21:25:21 +00:00
return
}
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")
client.isDestroyed = true
client.server.whoWas.Append(client)
2014-02-18 23:28:20 +00:00
friends := client.Friends()
friends.Remove(client)
// remove from connection limits
ipaddr := client.IP()
// this check shouldn't be required but eh
if ipaddr != nil {
client.server.connectionLimitsMutex.Lock()
client.server.connectionLimits.RemoveClient(ipaddr)
client.server.connectionLimitsMutex.Unlock()
}
// remove from opers list
_, exists := client.server.currentOpers[client]
if exists {
delete(client.server.currentOpers, client)
}
2016-10-16 10:14:56 +00:00
// alert monitors
for _, mClient := range client.server.monitoring[client.nickCasefolded] {
mClient.Send(nil, client.server.name, RPL_MONOFFLINE, mClient.nick, client.nick)
}
// remove my monitors
client.clearMonitorList()
// clean up channels
client.server.channelJoinPartMutex.Lock()
for channel := range client.channels {
channel.Quit(client, &friends)
}
client.server.channelJoinPartMutex.Unlock()
// clean up server
client.server.clients.Remove(client)
// clean up self
if client.idleTimer != nil {
client.idleTimer.Stop()
}
if client.quitTimer != nil {
client.quitTimer.Stop()
}
client.socket.Close()
// send quit messages to friends
for friend := range friends {
//TODO(dan): store quit message in user, if exists use that instead here
friend.Send(nil, client.nickMaskString, "QUIT", "Exited")
}
if !client.exitedSnomaskSent {
client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.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.
2017-01-14 09:52:47 +00:00
func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
if client.capabilities[MaxLine] {
2017-01-17 22:05:31 +00:00
client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
} else {
for _, str := range message.For512 {
2017-01-17 22:05:31 +00:00
client.SendFromClient(msgid, from, tags, command, target, str)
}
}
}
2016-09-12 01:25:31 +00:00
// SendFromClient sends an IRC line coming from a specific client.
// Adds account-tag to the line as well.
2017-01-14 11:48:57 +00:00
func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
2016-09-12 01:25:31 +00:00
// attach account-tag
if client.capabilities[AccountTag] && from.account != &NoAccount {
if tags == nil {
tags = ircmsg.MakeTags("account", from.account.Name)
} else {
(*tags)["account"] = ircmsg.MakeTagValue(from.account.Name)
}
}
2017-01-14 09:52:47 +00:00
// attach message-id
if len(msgid) > 0 && client.capabilities[MessageIDs] {
if tags == nil {
tags = ircmsg.MakeTags("draft/msgid", msgid)
} else {
(*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
}
}
2016-09-12 01:25:31 +00:00
2017-01-14 11:48:57 +00:00
return client.Send(tags, from.nickMaskString, command, params...)
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 silly clients like to treat trailing as separate 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,
}
)
// Send sends an IRC line to the client.
func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
2016-08-13 12:04:21 +00:00
// attach server-time
if client.capabilities[ServerTime] {
t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
2016-08-13 12:04:21 +00:00
if tags == nil {
tags = ircmsg.MakeTags("time", t)
2016-08-13 12:04:21 +00:00
} else {
(*tags)["time"] = ircmsg.MakeTagValue(t)
2016-08-13 12:04:21 +00:00
}
}
// force trailing, if message requires it
var usedTrailingHack bool
if commandsThatMustUseTrailing[strings.ToUpper(command)] && len(params) > 0 {
lastParam := params[len(params)-1]
// to force trailing, we ensure the final param contains a space
if !strings.Contains(lastParam, " ") {
params[len(params)-1] = lastParam + " "
usedTrailingHack = true
}
}
2016-08-13 12:04:21 +00:00
// send out the message
message := ircmsg.MakeMessage(tags, prefix, command, params...)
maxlenTags, maxlenRest := client.maxlens()
line, err := message.LineMaxLen(maxlenTags, maxlenRest)
if err != nil {
// try not to fail quietly - especially useful when running tests, as a note to dig deeper
2016-11-01 13:56:21 +00:00
// log.Println("Error assembling message:")
// spew.Dump(message)
// debug.PrintStack()
message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
line, _ := message.Line()
client.socket.Write(line)
return err
}
// is we used the trailing hack, we need to strip the final space we appended earlier
if usedTrailingHack {
line = line[:len(line)-3] + "\r\n"
}
client.server.logger.Debug("useroutput", client.nick, " ->", strings.TrimRight(line, "\r\n"))
client.socket.Write(line)
return nil
}
// Notice sends the client a notice from the server.
func (client *Client) Notice(text string) {
limit := 400
if client.capabilities[MaxLine] {
limit = client.server.limits.LineLen.Rest - 110
}
lines := wordWrap(text, limit)
for _, line := range lines {
client.Send(nil, client.server.name, "NOTICE", client.nick, line)
}
}