nmdc-ircfrontend/server.go

893 lines
24 KiB
Go
Raw Normal View History

2013-08-24 06:48:28 +00:00
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/>.
*/
2013-08-24 06:48:28 +00:00
import (
"bytes"
2013-08-24 06:48:28 +00:00
"fmt"
"io"
"log"
2013-08-24 06:48:28 +00:00
"net"
"regexp"
2013-08-24 06:48:28 +00:00
"strings"
"sync"
2016-05-03 07:57:02 +00:00
"time"
"code.ivysaur.me/libnmdc"
2013-08-24 06:48:28 +00:00
)
type ClientState int
const (
CSUnregistered ClientState = iota
CSRegistered
CSJoined
)
2016-05-03 06:25:27 +00:00
type Server struct {
name string
motd string
hubSecNick string
2016-05-05 07:11:40 +00:00
clientConn net.Conn
clientState ClientState
ClientStateLock sync.Mutex
2016-05-05 07:11:40 +00:00
2016-05-03 07:25:37 +00:00
upstreamLauncher libnmdc.HubConnectionOptions
upstreamCloser chan struct{}
2016-05-03 07:57:02 +00:00
upstream *libnmdc.HubConnection
verbose bool
autojoin bool
recievedFirstServerMessage bool
recievedCtcpVersion bool
nickChangeAttempt int
2016-05-03 06:25:27 +00:00
}
2013-08-24 06:48:28 +00:00
2016-05-05 07:11:40 +00:00
func NewServer(name string, upstream libnmdc.HubAddress, conn net.Conn) *Server {
2016-05-03 07:57:02 +00:00
self := libnmdc.NewUserInfo("")
self.ClientTag = APP_NAME
self.ClientVersion = APP_VERSION
2016-05-03 07:57:02 +00:00
2016-05-05 07:11:40 +00:00
return &Server{
name: name,
clientConn: conn,
clientState: CSUnregistered,
motd: "Connected to " + name + ". You /must/ join " + BLESSED_CHANNEL + " to continue.",
2016-05-03 07:25:37 +00:00
upstreamLauncher: libnmdc.HubConnectionOptions{
Address: upstream,
Self: *self,
SkipAutoReconnect: true,
2016-05-03 07:25:37 +00:00
},
upstreamCloser: make(chan struct{}, 1),
}
2013-08-24 06:48:28 +00:00
}
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...)
}
}
2016-05-05 07:11:40 +00:00
func (s *Server) RunWorker() {
2013-08-24 06:48:28 +00:00
// Send the connection handshake.
2016-05-03 07:25:37 +00:00
// Can't connect to the upstream server yet, until we've recieved a nick.
s.sendMOTD(s.motd)
2016-05-03 07:25:37 +00:00
for {
if s.clientConn == nil {
break // abandon thread
}
buf := make([]byte, CLIENT_READ_BUFFSIZE)
s.clientConn.SetReadDeadline(time.Now().Add(CLIENT_KEEPALIVE_EVERY * time.Second))
2016-05-05 07:11:40 +00:00
ln, err := s.clientConn.Read(buf)
2016-05-03 07:57:02 +00:00
if err != nil {
if err == io.EOF {
break // abandon thread
}
// If this was a /timeout/, send a KA and continue.
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
s.writeClient("PING :" + s.name)
continue
}
// But otherwise, it was a real error (e.g. unexpected disconnect)
s.verboseln(err.Error())
break // abandon
2016-05-03 07:57:02 +00:00
}
2016-05-03 07:57:02 +00:00
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) < 2 {
2016-05-03 07:57:02 +00:00
return
}
2016-05-03 07:25:37 +00:00
2016-05-03 07:57:02 +00:00
if strings.HasPrefix(fields[0], ":") {
fields = fields[1:]
2016-05-03 07:25:37 +00:00
}
2016-05-03 07:57:02 +00:00
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) postGeneralMessageInRoom(msg string) {
2016-05-03 07:57:02 +00:00
var sendAs = ""
// Some clients can't handle blank nicks very well
if s.upstreamLauncher.Self.ClientTag == "mIRC" || s.upstreamLauncher.Self.ClientTag == "Atomic" {
sendAs = s.hubSecNick + "!" + s.hubSecNick + "@" + s.hubSecNick
}
// Detect pseudo-system message for potential CTCP ACTION conversion
words := strings.Split(msg, " ")
firstWord := words[0]
remainder := strings.Join(words[1:], " ")
if firstWord == "*" {
firstWord = words[1]
remainder = strings.Join(words[2:], " ")
}
if s.upstream.UserExists(firstWord) {
// it's a /me in disguise - convert back to a CTCP ACTION
// If it's **our own** action, skip it
if firstWord != s.clientNick() {
s.reply(
rplMsg, firstWord+"!"+firstWord+"@"+firstWord, BLESSED_CHANNEL,
"\x01ACTION "+remainder+"\x01",
)
}
} else {
// genuine system message
s.reply(rplMsg, sendAs, BLESSED_CHANNEL, msg)
}
}
var rx_colorControlCode *regexp.Regexp = regexp.MustCompilePOSIX("\x03[0-9]+(,[0-9]+)?")
var rx_formattingControlCode *regexp.Regexp = regexp.MustCompile("(\x02|\x1D|\x1F|\x16|\x0F)")
func reformatOutgoingMessageBody(body string) string {
// Strip color codes
noColors := rx_colorControlCode.ReplaceAllString(body, "")
// Strip formatting codes
return rx_formattingControlCode.ReplaceAllString(noColors, "")
}
func reformatIncomingMessageBody(body string) string {
// "Greentext" filter
// TODO markdown filters
if len(body) > 0 && body[0] == '>' {
return "\x033" + strings.Replace(body, "implying", "\x02implying\x02", -1)
} else {
return body
}
}
func (s *Server) upstreamWorker() {
2016-05-03 07:25:37 +00:00
// Read loop
for {
select {
2016-05-05 07:11:40 +00:00
case <-s.upstreamCloser:
// Abandon the upstream connection
s.verboseln("Abandoning upstream connection...")
s.upstream.Disconnect()
2016-05-03 07:25:37 +00:00
return
2013-09-08 15:24:17 +00:00
2016-05-03 07:25:37 +00:00
case hubEvent := <-s.upstream.OnEvent:
switch hubEvent.EventType {
case libnmdc.EVENT_USER_JOINED:
2016-05-05 07:11:40 +00:00
s.reply(rplJoin, hubEvent.Nick, BLESSED_CHANNEL)
// If we want to JOIN with the full power of the supplied nick!user@host, then we'll need to actually remember the active client's USER parameters
2016-05-03 07:25:37 +00:00
case libnmdc.EVENT_USER_PART:
2016-05-05 07:11:40 +00:00
s.reply(rplPart, hubEvent.Nick, BLESSED_CHANNEL, "Disconnected")
2016-05-03 07:25:37 +00:00
case libnmdc.EVENT_USER_UPDATED_INFO:
// description change - no relevance for IRC users
case libnmdc.EVENT_CONNECTION_STATE_CHANGED:
s.postGeneralMessageInRoom("* Upstream: " + hubEvent.StateChange.String())
if hubEvent.StateChange == libnmdc.CONNECTIONSTATE_CONNECTED {
s.sendNames() // delay doing this until now
}
if hubEvent.StateChange == libnmdc.CONNECTIONSTATE_DISCONNECTED {
if s.nickChangeAttempt > 0 {
// If this was a nick change, reconnect /immediately/
s.upstream = nil
s.clientState = CSRegistered
s.maybeStartUpstream() // launches new goroutine
} else {
// Abandon thread. Don't try to autoreconnect at our level, the remote client can be responsible for that
s.DisconnectClient()
}
return
}
2016-05-03 07:25:37 +00:00
case libnmdc.EVENT_HUBNAME_CHANGED:
s.sendChannelTopic(hubEvent.Nick)
2016-05-03 07:25:37 +00:00
case libnmdc.EVENT_PRIVATE:
s.reply(rplMsg, hubEvent.Nick+"!"+hubEvent.Nick+"@"+hubEvent.Nick, s.clientNick(), reformatIncomingMessageBody(hubEvent.Message))
2016-05-03 07:25:37 +00:00
case libnmdc.EVENT_PUBLIC:
if hubEvent.Nick == s.clientNick() {
// irc doesn't echo our own pubchat
} else {
// nick!username@userhost, but for us all three of those are always identical
s.reply(rplMsg, hubEvent.Nick+"!"+hubEvent.Nick+"@"+hubEvent.Nick, BLESSED_CHANNEL, reformatIncomingMessageBody(hubEvent.Message))
}
if !s.recievedFirstServerMessage {
s.hubSecNick = hubEvent.Nick // Replace with the hub's real Hub-Security nick, although we shouldn't need it again
}
2016-05-03 07:25:37 +00:00
case libnmdc.EVENT_SYSTEM_MESSAGE_FROM_CONN, libnmdc.EVENT_SYSTEM_MESSAGE_FROM_HUB:
s.postGeneralMessageInRoom(hubEvent.Message)
2016-05-03 07:25:37 +00:00
}
}
}
2013-09-08 15:24:17 +00:00
}
2013-08-24 06:48:28 +00:00
2016-05-03 07:25:37 +00:00
func (s *Server) handleCommand(command string, args []string) {
2013-08-24 06:48:28 +00:00
s.verbosef(" >>> '%s' %v", command, args)
2013-09-08 15:24:17 +00:00
switch command {
2013-10-21 12:34:12 +00:00
case "PING":
s.reply(rplPong, strings.Join(args, " "))
case "PONG":
// do nothing
2013-09-08 15:24:17 +00:00
case "INFO":
s.reply(rplInfo, APP_NAME+" v"+APP_VERSION)
2013-09-08 15:24:17 +00:00
case "VERSION":
s.reply(rplVersion, APP_VERSION)
2016-05-03 07:25:37 +00:00
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]))
}
*/
2016-05-03 07:25:37 +00:00
case "PASS":
// RFC2812 registration. Stash the password for later
2016-05-03 07:25:37 +00:00
if len(args) < 1 {
2016-05-05 07:11:40 +00:00
s.reply(errMoreArgs)
2016-05-03 07:25:37 +00:00
return
}
s.upstreamLauncher.NickPassword = args[0]
2013-09-08 15:24:17 +00:00
case "NICK":
2016-05-03 07:25:37 +00:00
if len(args) < 1 {
2016-05-05 07:11:40 +00:00
s.reply(errMoreArgs)
2016-05-03 07:25:37 +00:00
return
}
// mIRC puts a colon in first place when changing nick, hexchat doesn't
suppliedNick := args[0]
if len(suppliedNick) >= 2 && suppliedNick[0] == ':' {
suppliedNick = suppliedNick[1:]
}
if s.clientNick() == "" {
2016-05-03 07:25:37 +00:00
// allow set, as part of the login phase
s.upstreamLauncher.Self.Nick = suppliedNick
} else if suppliedNick == s.clientNick() {
// Ignore
// Required for compatibility with Lite IRC, which sends USER/NICK in the wrong order
2016-05-03 07:25:37 +00:00
} else {
s.ClientStateLock.Lock()
defer s.ClientStateLock.Unlock()
if s.upstream == nil {
// Not yet connected, should be safe to change nick
s.upstreamLauncher.Self.Nick = suppliedNick
} else {
// Need to disconnect/reconnect the upstream
s.writeClient(fmt.Sprintf(":%s!%s@%s NICK %s", s.clientNick(), s.clientNick(), s.clientNick(), suppliedNick)) // notify client about what they've done
s.upstreamLauncher.Self.Nick = suppliedNick
s.nickChangeAttempt++
s.upstream.Disconnect()
}
//s.reply(rplKill, "Can't change nicks on this server.")
//s.DisconnectClient()
2016-05-03 07:25:37 +00:00
}
2013-08-24 06:48:28 +00:00
2013-09-08 15:24:17 +00:00
case "USER":
2016-05-03 07:57:02 +00:00
// 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.")
2016-05-05 07:11:40 +00:00
s.DisconnectClient()
2016-05-03 07:57:02 +00:00
return
2016-05-03 06:25:27 +00:00
}
if s.clientNick() == "" {
// Whatever, treat it as a NICK call (non-strict client handshake) and take the username field to be the intended nick
// This will allow Lite IRC's bad handshake to log in (as long as the username and the nickname are the same)
s.upstreamLauncher.Self.Nick = args[0]
}
// Use the client's {real name} field as an NMDC {description}
if len(args) >= 4 && len(args[3]) > 0 && args[3][0] == ':' {
realName := strings.Join(args[3:], " ")[1:]
s.upstreamLauncher.Self.Description = realName
2016-05-03 07:57:02 +00:00
}
2016-05-03 06:25:27 +00:00
2016-05-05 07:11:40 +00:00
s.reply(rplWelcome)
s.clientState = CSRegistered
// Send CTCP VERSION request immediately
s.reply(rplMsg, s.hubSecNick+"!"+s.hubSecNick+"@"+s.hubSecNick, BLESSED_CHANNEL, "\x01VERSION\x01")
if s.autojoin {
s.handleCommand("JOIN", []string{BLESSED_CHANNEL})
}
2016-05-03 07:57:02 +00:00
default:
s.handleRegisteredCommand(command, args)
}
}
func (s *Server) handleRegisteredCommand(command string, args []string) {
if s.clientState == CSUnregistered {
s.reply(errNotReg)
return
}
switch command {
case "LIST":
if s.upstream == nil {
s.reply(rplList, fmt.Sprintf("%s %d :%s", BLESSED_CHANNEL, 1, "-"))
} else {
s.reply(rplList, fmt.Sprintf("%s %d :%s", BLESSED_CHANNEL, s.upstream.UserCount(), s.upstream.HubName))
}
s.reply(rplListEnd)
case "PRIVMSG", "NOTICE":
if len(args) < 2 {
2016-05-05 07:11:40 +00:00
s.reply(errMoreArgs)
2013-08-24 06:48:28 +00:00
return
}
message := strings.Join(args[1:], " ")[1:] // strip leading colon
if strings.HasPrefix(message, "\x01VERSION ") {
// Not a real message - a reply to our internal request. Change the user's tag to match the actual client software
// This /can/ actually be done regardless of whether we're truely connected yet, since the request is triggered
// by an incoming PM which means even though we might not be in CONNECTIONSTATE_CONNECTED, it's probably far-enough
// that an extra upstream $MyINFO won't hurt
versionString := message[9:]
versionString = versionString[:len(versionString)-1]
s.SetClientSoftwareVersion(versionString)
return
}
if s.upstream == nil || s.upstream.State != libnmdc.CONNECTIONSTATE_CONNECTED {
s.reply(errCannotSend, args[0])
return
}
if strings.HasPrefix(message, "\x01ACTION ") {
message = "/me " + message[8:]
message = message[:len(message)-1] // trailing \x01
}
// 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.upstream.SayPublic(reformatOutgoingMessageBody(message))
} else if s.upstream.UserExists(args[0]) {
s.upstream.SayPrivate(args[0], reformatOutgoingMessageBody(message))
} else {
s.reply(errNoSuchNick, args[0])
}
case "JOIN":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
switch args[0] {
case BLESSED_CHANNEL:
// Give it a few seconds - it's better to hear the CTCP VERSION
// response first. Once we get that, it'll connect instantly
go func() {
<-time.After(WAIT_FOR_VERSION * time.Second)
s.ClientStateLock.Lock()
defer s.ClientStateLock.Unlock()
s.maybeStartUpstream()
}()
case "0":
// Quitting all channels? Drop client
s.reply(rplKill, "Bye.")
s.DisconnectClient()
default:
s.reply(rplKill, "There is only '"+BLESSED_CHANNEL+"'.")
2016-05-05 07:11:40 +00:00
s.DisconnectClient()
2013-08-24 06:48:28 +00:00
}
default:
s.handleJoinedCommand(command, args)
}
}
func (s *Server) maybeStartUpstream() {
if s.clientState != CSJoined {
// Join for the first time
s.clientState = CSJoined
// Acknowledge
s.reply(rplJoin, s.clientNick(), BLESSED_CHANNEL)
// 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
}
}
func (s *Server) SetClientSoftwareVersion(ver string) {
// "HexChat 2.12.1 [x64] / Microsoft Windows 10 Pro (x64) [Intel(R) Core(TM) i5-2500 CPU @ 3.30GHz (3.60GHz)]"
// "AndroIRC - Android IRC Client (5.2 - Build 6830152) - http://www.androirc.com"
// "AndChat 1.4.3.2 http://www.andchat.net"
// "liteIRC for Android 1.1.8"
// ":Relay:1.0:Android"
// "mIRC v7.45"
// A bit long and unwieldy.
// Heuristic: keep the first word, and the the first word containing digits
tag := APP_NAME
version := APP_VERSION
words := strings.Split(ver, " ")
for _, word := range words[1:] {
if strings.ContainsAny(word, "0123456789") {
tag = words[0]
version = strings.Replace(word, "(", "", -1) // AndroIRC
break
}
}
// Strip leading v from mIRC
if len(version) >= 2 && (version[0] == 'v' || version[0] == 'V') && strings.ContainsAny(string(version[1]), "0123456789") {
version = version[1:]
}
s.verbosef("Replacing client tag with '%s' version '%s'", tag, version)
s.upstreamLauncher.Self.ClientTag = tag
s.upstreamLauncher.Self.ClientVersion = version
s.recievedCtcpVersion = true
s.ClientStateLock.Lock()
defer s.ClientStateLock.Unlock()
if s.upstream != nil {
s.upstream.Hco.Self.ClientTag = tag
s.upstream.Hco.Self.ClientVersion = version
s.upstream.SayInfo()
} else {
// Connected for the first time (order was CTCP VERSION --> JOIN)
s.maybeStartUpstream()
}
}
func (s *Server) handleJoinedCommand(command string, args []string) {
if s.clientState != CSJoined {
s.reply(errNotReg)
return
}
switch command {
2013-09-08 15:24:17 +00:00
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.clientNick(), BLESSED_CHANNEL)
s.sendNames()
}
2013-08-24 06:48:28 +00:00
2013-09-08 15:24:17 +00:00
case "QUIT":
2016-05-05 07:11:40 +00:00
s.DisconnectClient()
2013-08-24 06:48:28 +00:00
2013-09-08 15:24:17 +00:00
case "TOPIC":
2013-08-24 06:48:28 +00:00
if len(args) < 1 {
2016-05-05 07:11:40 +00:00
s.reply(errMoreArgs)
2013-08-24 06:48:28 +00:00
return
}
if strings.ToLower(args[0]) != BLESSED_CHANNEL {
2016-05-05 07:11:40 +00:00
s.reply(errNoSuchNick, args[0])
2013-08-24 06:48:28 +00:00
return
}
if len(args) == 1 {
s.sendChannelTopic(s.upstream.HubName) // Valid topic get
} else {
s.reply(errNoPriv) // Disallow topic set
2013-08-24 06:48:28 +00:00
}
case "PROTOCTL":
// we advertised support for NAMESX, if this happens the client accepted it
s.sendNames()
2013-08-24 06:48:28 +00:00
2013-09-08 15:24:17 +00:00
case "OPER":
2013-08-24 06:48:28 +00:00
if len(args) < 2 {
2016-05-05 07:11:40 +00:00
s.reply(errMoreArgs)
2013-08-24 06:48:28 +00:00
return
}
2016-05-03 07:57:02 +00:00
// Can't use this command.
2016-05-05 07:11:40 +00:00
s.reply(errPassword)
2013-08-24 06:48:28 +00:00
case "KILL", "KICK":
2016-05-05 07:11:40 +00:00
s.reply(errNoPriv)
2016-05-03 06:25:27 +00:00
return
2013-08-31 17:44:25 +00:00
case "WHO":
if len(args) < 1 {
s.reply(errMoreArgs)
2013-08-29 20:10:28 +00:00
return
}
// s.sendWho(args[0])
// s.sendNames() // fixes hexchat, but andchat always sends WHO /immediately/ after NAMES end, causing an infinite loop
2013-08-29 20:10:28 +00:00
2013-09-08 15:24:17 +00:00
case "MODE":
if len(args) < 1 {
2016-05-05 07:11:40 +00:00
s.reply(errMoreArgs)
return
}
if strings.ToLower(args[0]) != BLESSED_CHANNEL {
2016-05-05 07:11:40 +00:00
s.reply(errNoSuchNick, args[0])
return
}
if len(args) == 1 {
2016-05-03 07:57:02 +00:00
// No more args, they just want the mode
s.sendChannelMode()
} else {
// Setting modes is disallowed
2016-05-05 07:11:40 +00:00
s.reply(errNoPriv)
}
return
case "WHOIS":
if len(args) < 1 {
s.reply(errMoreArgs)
return
}
// WHOIS [target] nick[,nick2[,nick...]]
nicklist := args[0] // Assume WHOIS ${nick} only,
if len(args) >= 2 {
nicklist = args[1] // It was WHOIS ${target} ${nick} instead
}
for _, targetnick := range strings.Split(nicklist, ",") {
// tell the client something about it
// The protocol does ostensibly support wildcard WHOIS, but we don't (yet)
s.upstream.Users(func(u *map[string]libnmdc.UserInfo) error {
for nick, nickinfo := range *u {
if nick == targetnick {
s.reply(rplWhoisUser, nick, nickinfo.Description+" <"+nickinfo.ClientTag+" V:"+nickinfo.ClientVersion+">")
if nickinfo.IsOperator {
s.reply(rplWhoisOperator, nick)
}
}
}
return nil
})
s.reply(rplEndOfWhois)
}
2013-08-24 06:48:28 +00:00
default:
2016-05-05 07:11:40 +00:00
s.reply(errUnknownCommand, command)
}
}
func (s *Server) DisconnectClient() {
if s.clientConn != nil {
s.clientConn.Close()
}
2016-05-05 07:11:40 +00:00
s.clientConn = nil
s.clientState = CSUnregistered
// Readloop will stop, which kills the upstream connection too
2016-05-05 07:11:40 +00:00
}
func (s *Server) sendNames() {
nameList := make([]string, 0)
if s.upstream != nil {
s.upstream.Users(func(u *map[string]libnmdc.UserInfo) error {
for nick, nickinfo := range *u {
if nickinfo.IsOperator {
nameList = append(nameList, "@"+nick)
} else {
nameList = append(nameList, nick)
}
}
return nil
})
}
s.reply(rplNames, BLESSED_CHANNEL, strings.Join(nameList, " "))
s.reply(rplEndOfNames, BLESSED_CHANNEL)
}
func (s *Server) sendChannelMode() {
s.reply(rplChannelModeIs, BLESSED_CHANNEL, BLESSED_CHANNEL_MODE, "")
}
func (s *Server) sendWho(arg string) {
if arg == BLESSED_CHANNEL {
// always include ourselves
s.reply(rplWho, s.clientNick(), arg)
s.upstream.Users(func(u *map[string]libnmdc.UserInfo) error {
for nick, _ := range *u {
if nick != s.clientNick() { // but don't repeat ourselves
s.reply(rplWho, nick, arg)
}
}
return nil
})
} else {
// argument is a filter
s.upstream.Users(func(u *map[string]libnmdc.UserInfo) error {
for nick, _ := range *u {
if strings.Contains(nick, arg) {
s.reply(rplWho, nick, arg)
}
}
return nil
})
}
s.reply(rplEndOfWho, arg)
}
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) {
2016-05-05 07:11:40 +00:00
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)
}
func (s *Server) clientNick() string {
return s.upstreamLauncher.Self.Nick
}
2016-05-05 07:11:40 +00:00
// 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.clientNick(), s.name))
s.writeClient(fmt.Sprintf(":%s 005 %s NAMESX CHANTYPES=# :are supported by this server", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
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.clientNick(), args[0], args[1]))
2016-05-05 07:11:40 +00:00
case rplNoTopic:
s.writeClient(fmt.Sprintf(":%s 331 %s %s :No topic is set", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case rplNames:
s.writeClient(fmt.Sprintf(":%s 353 %s = %s :%s", s.name, s.clientNick(), args[0], args[1]))
2016-05-05 07:11:40 +00:00
case rplEndOfNames:
s.writeClient(fmt.Sprintf(":%s 366 %s %s :End of NAMES list", s.name, s.clientNick(), args[0]))
case rplWho:
s.writeClient(fmt.Sprintf(":%s 352 %s %s %s %s %s %s H :0 %s", s.name, s.clientNick(), 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.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case rplNickChange:
s.writeClient(fmt.Sprintf(":%s NICK %s", args[0], args[1]))
2016-05-05 07:11:40 +00:00
case rplKill:
s.writeClient(fmt.Sprintf(":%s KILL %s %s", s.name, s.clientNick(), args[0]))
// s.writeClient(fmt.Sprintf(":%s KILL %s A %s", args[0], s.clientNick(), args[1]))
2016-05-05 07:11:40 +00:00
case rplMsg:
for _, itm := range strings.Split(args[2], "\n") {
s.writeClient(fmt.Sprintf(":%s PRIVMSG %s :%s", args[0], args[1], itm))
2016-05-05 07:11:40 +00:00
}
2016-05-05 07:11:40 +00:00
case rplList:
s.writeClient(fmt.Sprintf(":%s 322 %s %s", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case rplListEnd:
s.writeClient(fmt.Sprintf(":%s 323 %s", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case rplOper:
s.writeClient(fmt.Sprintf(":%s 381 %s :You are now an operator", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case rplChannelModeIs:
s.writeClient(fmt.Sprintf(":%s 324 %s %s %s %s", s.name, s.clientNick(), args[0], args[1], args[2]))
2016-05-05 07:11:40 +00:00
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.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case rplVersion:
s.writeClient(fmt.Sprintf(":%s 351 %s %s", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case rplMOTDStart:
s.writeClient(fmt.Sprintf(":%s 375 %s :- Message of the day - ", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case rplMOTD:
s.writeClient(fmt.Sprintf(":%s 372 %s :- %s", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case rplEndOfMOTD:
s.writeClient(fmt.Sprintf(":%s 376 %s :- End of MOTD", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case rplPong:
s.writeClient(fmt.Sprintf(":%s PONG %s %s", s.name, s.clientNick(), args[0]))
case rplWhoisUser:
s.writeClient(fmt.Sprintf(":%s 311 %s %s %s %s * :%s", s.name, args[0], args[0], args[0], s.name, args[1])) // caller should supply nick,description
case rplWhoisOperator:
s.writeClient(fmt.Sprintf(":%s 313 %s :is an IRC operator", s.name, args[0]))
case rplEndOfWhois:
s.writeClient(fmt.Sprintf(":%s 318 :End of WHOIS list", s.name))
2016-05-05 07:11:40 +00:00
case errMoreArgs:
s.writeClient(fmt.Sprintf(":%s 461 %s :Not enough params", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case errNoNick:
s.writeClient(fmt.Sprintf(":%s 431 %s :No nickname given", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case errInvalidNick:
s.writeClient(fmt.Sprintf(":%s 432 %s %s :Erronenous nickname", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case errNickInUse:
s.writeClient(fmt.Sprintf(":%s 433 %s %s :Nick already in use", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
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.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case errUnknownCommand:
s.writeClient(fmt.Sprintf(":%s 421 %s %s :Unknown command", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
case errNotReg:
s.writeClient(fmt.Sprintf(":%s 451 :- You have not registered", s.name))
2016-05-05 07:11:40 +00:00
case errPassword:
s.writeClient(fmt.Sprintf(":%s 464 %s :Error, password incorrect", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case errNoPriv:
s.writeClient(fmt.Sprintf(":%s 481 %s :Permission denied", s.name, s.clientNick()))
2016-05-05 07:11:40 +00:00
case errCannotSend:
s.writeClient(fmt.Sprintf(":%s 404 %s %s :Cannot send to channel", s.name, s.clientNick(), args[0]))
2016-05-05 07:11:40 +00:00
}
}
func (s *Server) writeClient(output string) {
if s.clientConn == nil {
return
}
s.verbosef(" <<< %s", output)
2016-05-05 07:11:40 +00:00
s.clientConn.SetWriteDeadline(time.Now().Add(time.Second * 30))
if _, err := fmt.Fprintf(s.clientConn, "%s\r\n", output); err != nil {
s.DisconnectClient()
return
2013-08-24 06:48:28 +00:00
}
}