nmdc-ircfrontend/server.go
2016-05-07 17:51:07 +12:00

600 lines
15 KiB
Go

package main
/*
Copyright (C) 2016 The `nmdc-ircfrontend' author(s)
Copyright (C) 2013 Harry Jeffery
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import (
"bytes"
"fmt"
"io"
"libnmdc"
"log"
"net"
"strings"
"time"
)
type ClientState int
const (
CSUnregistered ClientState = iota
CSRegistered
CSJoined
)
type Server struct {
name string
motd string
clientConn net.Conn
clientState ClientState
upstreamLauncher libnmdc.HubConnectionOptions
upstreamCloser chan struct{}
upstream *libnmdc.HubConnection
verbose bool
autojoin bool
lastMessage string // FIXME racey
}
func NewServer(name string, upstream libnmdc.HubAddress, conn net.Conn) *Server {
self := libnmdc.NewUserInfo("")
self.ClientTag = APP_DESCRIPTION
return &Server{
name: name,
clientConn: conn,
clientState: CSUnregistered,
motd: "Connected to " + name + ". You /must/ join " + BLESSED_CHANNEL + " to continue.",
upstreamLauncher: libnmdc.HubConnectionOptions{
Address: upstream,
Self: *self,
},
upstreamCloser: make(chan struct{}, 1),
}
}
func (s *Server) verboseln(line string) {
if s.verbose {
log.Println(line)
}
}
func (s *Server) verbosef(fmt string, args ...interface{}) {
if s.verbose {
log.Printf(fmt, args...)
}
}
func (s *Server) RunWorker() {
// Send the connection handshake.
// Can't connect to the upstream server yet, until we've recieved a nick.
s.sendMOTD(s.motd)
for {
if s.clientConn == nil {
break // abandon thread
}
buf := make([]byte, CLIENT_READ_BUFFSIZE)
ln, err := s.clientConn.Read(buf)
if err != nil {
if err == io.EOF {
break // abandon thread
}
// If this was a /timeout/, send a KA and continue.
// But otherwise, it was a real error (e.g. unexpected disconnect)
s.verboseln(err.Error())
break // abandon
}
rawLines := buf[:ln]
rawLines = bytes.Replace(rawLines, []byte("\r\n"), []byte("\n"), -1)
rawLines = bytes.Replace(rawLines, []byte("\r"), []byte("\n"), -1)
lines := bytes.Split(rawLines, []byte("\n"))
for _, line := range lines {
if len(line) > 0 {
// Client sent a command
fields := strings.Fields(string(line))
if len(fields) < 1 {
return
}
if strings.HasPrefix(fields[0], ":") {
fields = fields[1:]
}
s.handleCommand(strings.ToUpper(fields[0]), fields[1:])
}
}
}
s.verboseln("Broken loop.")
// Cleanup upstream
if s.upstream != nil {
s.upstreamCloser <- struct{}{} // always safe to do this /once/
}
// Clean up ourselves
s.DisconnectClient() // if not already done
}
func (s *Server) upstreamWorker() {
var BLANK_NICK = "PtokaX" // "\xC2\xA0"
// Read loop
for {
select {
case <-s.upstreamCloser:
// Abandon the upstream connection
s.verboseln("Abandoning upstream connection...")
s.upstream.Disconnect()
return
case hubEvent := <-s.upstream.OnEvent:
switch hubEvent.EventType {
case libnmdc.EVENT_USER_JOINED:
s.reply(rplJoin, hubEvent.Nick, BLESSED_CHANNEL)
case libnmdc.EVENT_USER_PART:
s.reply(rplPart, hubEvent.Nick, BLESSED_CHANNEL, "Disconnected")
case libnmdc.EVENT_USER_UPDATED_INFO:
// description change - no relevance for IRC users
case libnmdc.EVENT_CONNECTION_STATE_CHANGED:
s.reply(rplMsg, BLANK_NICK, BLESSED_CHANNEL, "* Upstream: "+hubEvent.StateChange.Format())
case libnmdc.EVENT_HUBNAME_CHANGED:
s.sendChannelTopic(hubEvent.Nick)
case libnmdc.EVENT_PRIVATE:
s.reply(rplMsg, hubEvent.Nick, s.upstreamLauncher.Self.Nick, hubEvent.Message)
case libnmdc.EVENT_PUBLIC:
if hubEvent.Nick == s.upstreamLauncher.Self.Nick && hubEvent.Message == s.lastMessage {
s.lastMessage = "" // irc doesn't echo our own pubchat
} else {
s.reply(rplMsg, hubEvent.Nick, BLESSED_CHANNEL, hubEvent.Message)
}
case libnmdc.EVENT_SYSTEM_MESSAGE_FROM_CONN, libnmdc.EVENT_SYSTEM_MESSAGE_FROM_HUB:
// FIXME blank names work well in hexchat, but not in yaaic
s.reply(rplMsg, BLANK_NICK, BLESSED_CHANNEL, hubEvent.Message)
}
}
}
}
func (s *Server) handleCommand(command string, args []string) {
s.verbosef(" >>> '%s' %v", command, args)
switch command {
case "PING":
s.reply(rplPong)
case "PONG":
// do nothing
case "INFO":
s.reply(rplInfo, APP_DESCRIPTION)
case "VERSION":
s.reply(rplVersion, VERSION)
case "MOTD":
s.sendMOTD(s.motd)
case "CAP":
return
/*
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
if args[0] == "LS" {
s.writeClient("CAP * LS :nmdc-ircfrontend") // no special IRCv3 capabilities available
} else {
s.writeClient(fmt.Sprintf(":%s 410 * %s :Invalid CAP command", s.name, args[0]))
}
*/
case "PASS":
// RFC2812 registration. Stash the password for later
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
s.upstreamLauncher.NickPassword = args[0]
case "NICK":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
if s.upstreamLauncher.Self.Nick == "" {
// allow set, as part of the login phase
s.upstreamLauncher.Self.Nick = args[0]
} else {
s.reply(rplKill, "Can't change nicks on this server", "")
s.DisconnectClient()
}
case "USER":
// This command sets altname, realname, ... none of which we use
// It's the final step in a PASS/NICK/USER login handshake.
if s.clientState != CSUnregistered {
s.reply(rplKill, "You're already registered.", "")
s.DisconnectClient()
return
}
if s.upstreamLauncher.Self.Nick == "" {
s.reply(rplKill, "Your nickname is already being used", "")
s.DisconnectClient()
return
}
s.reply(rplWelcome)
s.clientState = CSRegistered
// TODO tell the client that they /must/ join #chat
if s.autojoin {
s.handleCommand("JOIN", []string{BLESSED_CHANNEL})
}
// Send a CTCP VERSION request to the client. If the IRC client can
// supply a client version string, we can replace our tag with it,
// but that's optional
default:
s.handleRegisteredCommand(command, args)
}
}
func (s *Server) handleRegisteredCommand(command string, args []string) {
if s.clientState == CSUnregistered {
s.reply(errNotReg)
return
}
switch command {
case "JOIN":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
switch args[0] {
case BLESSED_CHANNEL:
if s.clientState != CSJoined {
// Join for the first time
s.clientState = CSJoined
// Acknowledge
s.reply(rplJoin, s.upstreamLauncher.Self.Nick, BLESSED_CHANNEL)
// Send (initially just us) nicklist for the chat channel
s.sendNames()
// Spawn upstream connection
s.upstream = s.upstreamLauncher.Connect()
go s.upstreamWorker()
} else {
// They're already here, ignore
// Can happen if autojoin is enabled but the client already requested a login
}
case "0":
// Quitting all channels? Drop client
s.reply(rplKill, "Bye.", "")
s.DisconnectClient()
default:
s.reply(rplKill, "There is only '"+BLESSED_CHANNEL+"'.", "")
s.DisconnectClient()
}
case "PART":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
if args[0] == BLESSED_CHANNEL {
// You can check out any time you like, but you can never leave
s.reply(rplJoin, s.upstreamLauncher.Self.Nick, BLESSED_CHANNEL)
s.sendNames()
}
case "PRIVMSG", "NOTICE":
if len(args) < 2 {
s.reply(errMoreArgs)
return
}
if s.upstream == nil || s.upstream.State != libnmdc.CONNECTIONSTATE_CONNECTED {
s.reply(errCannotSend, args[0])
return
}
message := strings.Join(args[1:], " ")[1:] // strip leading colon
// IRC is case-insensitive case-preserving. We can respect that for the
// channel name, but not really for user nicks
if strings.ToLower(args[0]) == BLESSED_CHANNEL {
s.lastMessage = message
s.upstream.SayPublic(s.lastMessage)
} else if _, clientExists := s.upstream.Users[args[0]]; clientExists {
s.upstream.SayPrivate(args[0], message)
} else {
s.reply(errNoSuchNick, args[0])
}
case "QUIT":
s.DisconnectClient()
case "TOPIC":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
if strings.ToLower(args[0]) != BLESSED_CHANNEL {
s.reply(errNoSuchNick, args[0])
return
}
if len(args) == 1 {
s.sendChannelTopic(s.upstream.HubName) // Valid topic get
} else {
s.reply(errNoPriv) // Disallow topic set
}
case "LIST":
listItem := fmt.Sprintf("%s %d :%s", BLESSED_CHANNEL, len(s.upstream.Users), s.upstream.HubName)
s.reply(rplList, listItem)
s.reply(rplListEnd)
case "OPER":
if len(args) < 2 {
s.reply(errMoreArgs)
return
}
// Can't use this command.
s.reply(errPassword)
case "KILL", "KICK":
s.reply(errNoPriv)
return
case "WHO":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
// Ignore what we're "supposed" to do
s.sendNames()
/*
if args[0] == BLESSED_CHANNEL {
// always include ourselves
s.reply(rplWho, s.upstreamLauncher.Self.Nick, args[0])
for nick, _ := range s.upstream.Users {
if nick != s.upstreamLauncher.Self.Nick { // but don't repeat ourselves
s.reply(rplWho, nick, args[0])
}
}
} else {
// argument is a filter
for nick, _ := range s.upstream.Users {
if strings.Contains(nick, args[0]) {
s.reply(rplWho, nick, args[0])
}
}
}
s.reply(rplEndOfWho, args[0])
*/
case "MODE":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
if strings.ToLower(args[0]) != BLESSED_CHANNEL {
s.reply(errNoSuchNick, args[0])
return
}
if len(args) == 1 {
// No more args, they just want the mode
s.reply(rplChannelModeIs, args[0], BLESSED_CHANNEL_MODE, "")
} else {
// Setting modes is disallowed
s.reply(errNoPriv)
}
return
default:
s.reply(errUnknownCommand, command)
}
}
func (s *Server) DisconnectClient() {
if s.clientConn != nil {
s.clientConn.Close()
}
s.clientConn = nil
s.clientState = CSUnregistered
// Readloop will stop, which kills the upstream connection too
}
func (s *Server) sendNames() {
names := s.upstreamLauncher.Self.Nick
if s.upstream != nil {
for nick, _ := range s.upstream.Users {
names += " " + nick
}
}
s.reply(rplNames, BLESSED_CHANNEL, names)
s.reply(rplEndOfNames, BLESSED_CHANNEL)
}
func (s *Server) sendChannelTopic(topic string) {
if len(topic) > 0 {
s.reply(rplTopic, BLESSED_CHANNEL, s.upstream.HubName)
} else {
s.reply(rplNoTopic, BLESSED_CHANNEL)
}
}
func (s *Server) sendMOTD(motd string) {
s.reply(rplMOTDStart)
for len(motd) > 80 {
s.reply(rplMOTD, motd[:80])
motd = motd[80:]
}
if len(motd) > 0 {
s.reply(rplMOTD, motd)
}
s.reply(rplEndOfMOTD)
}
// Send a reply to a user with the code specified
func (s *Server) reply(code replyCode, args ...string) {
switch code {
case rplWelcome:
s.writeClient(fmt.Sprintf(":%s 001 %s :Welcome to %s", s.name, s.upstreamLauncher.Self.Nick, s.name))
case rplJoin:
s.writeClient(fmt.Sprintf(":%s JOIN %s", args[0], args[1]))
case rplPart:
s.writeClient(fmt.Sprintf(":%s PART %s %s", args[0], args[1], args[2]))
case rplTopic:
s.writeClient(fmt.Sprintf(":%s 332 %s %s :%s", s.name, s.upstreamLauncher.Self.Nick, args[0], args[1]))
case rplNoTopic:
s.writeClient(fmt.Sprintf(":%s 331 %s %s :No topic is set", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplNames:
s.writeClient(fmt.Sprintf(":%s 353 %s = %s :%s", s.name, s.upstreamLauncher.Self.Nick, args[0], args[1]))
case rplEndOfNames:
s.writeClient(fmt.Sprintf(":%s 366 %s %s :End of NAMES list", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplWho:
s.writeClient(fmt.Sprintf(":%s 352 %s %s %s %s %s %s H :0 %s", s.name, s.upstreamLauncher.Self.Nick, args[1], args[0], args[0], s.name, args[0], args[0]))
case rplEndOfWho:
s.writeClient(fmt.Sprintf(":%s 315 %s %s :End of WHO list", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplNickChange:
s.writeClient(fmt.Sprintf(":%s NICK %s", args[0], args[1]))
case rplKill:
s.writeClient(fmt.Sprintf(":%s KILL %s A %s", args[0], s.upstreamLauncher.Self.Nick, args[1]))
case rplMsg:
for _, itm := range strings.Split(args[2], "\n") {
s.writeClient(fmt.Sprintf(":%s PRIVMSG %s %s", args[0], args[1], itm))
}
case rplList:
s.writeClient(fmt.Sprintf(":%s 322 %s %s", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplListEnd:
s.writeClient(fmt.Sprintf(":%s 323 %s", s.name, s.upstreamLauncher.Self.Nick))
case rplOper:
s.writeClient(fmt.Sprintf(":%s 381 %s :You are now an operator", s.name, s.upstreamLauncher.Self.Nick))
case rplChannelModeIs:
s.writeClient(fmt.Sprintf(":%s 324 %s %s %s %s", s.name, s.upstreamLauncher.Self.Nick, args[0], args[1], args[2]))
case rplKick:
s.writeClient(fmt.Sprintf(":%s KICK %s %s %s", args[0], args[1], args[2], args[3]))
case rplInfo:
s.writeClient(fmt.Sprintf(":%s 371 %s :%s", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplVersion:
s.writeClient(fmt.Sprintf(":%s 351 %s %s", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplMOTDStart:
s.writeClient(fmt.Sprintf(":%s 375 %s :- Message of the day - ", s.name, s.upstreamLauncher.Self.Nick))
case rplMOTD:
s.writeClient(fmt.Sprintf(":%s 372 %s :- %s", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case rplEndOfMOTD:
s.writeClient(fmt.Sprintf(":%s 376 %s :- End of MOTD", s.name, s.upstreamLauncher.Self.Nick))
case rplPong:
s.writeClient(fmt.Sprintf(":%s PONG %s %s", s.name, s.upstreamLauncher.Self.Nick, s.name))
case errMoreArgs:
s.writeClient(fmt.Sprintf(":%s 461 %s :Not enough params", s.name, s.upstreamLauncher.Self.Nick))
case errNoNick:
s.writeClient(fmt.Sprintf(":%s 431 %s :No nickname given", s.name, s.upstreamLauncher.Self.Nick))
case errInvalidNick:
s.writeClient(fmt.Sprintf(":%s 432 %s %s :Erronenous nickname", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case errNickInUse:
s.writeClient(fmt.Sprintf(":%s 433 %s %s :Nick already in use", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case errAlreadyReg:
s.writeClient(fmt.Sprintf(":%s 462 :You need a valid nick first", s.name))
case errNoSuchNick:
s.writeClient(fmt.Sprintf(":%s 401 %s %s :No such nick/channel", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case errUnknownCommand:
s.writeClient(fmt.Sprintf(":%s 421 %s %s :Unknown command", s.name, s.upstreamLauncher.Self.Nick, args[0]))
case errNotReg:
s.writeClient(fmt.Sprintf(":%s 451 :- You have not registered", s.name))
case errPassword:
s.writeClient(fmt.Sprintf(":%s 464 %s :Error, password incorrect", s.name, s.upstreamLauncher.Self.Nick))
case errNoPriv:
s.writeClient(fmt.Sprintf(":%s 481 %s :Permission denied", s.name, s.upstreamLauncher.Self.Nick))
case errCannotSend:
s.writeClient(fmt.Sprintf(":%s 404 %s %s :Cannot send to channel", s.name, s.upstreamLauncher.Self.Nick, args[0]))
}
}
func (s *Server) writeClient(output string) {
if s.clientConn == nil {
return
}
s.verbosef(" <<< %s", output)
s.clientConn.SetWriteDeadline(time.Now().Add(time.Second * 30))
if _, err := fmt.Fprintf(s.clientConn, "%s\r\n", output); err != nil {
s.DisconnectClient()
return
}
}