ircd/server.go

354 lines
8.8 KiB
Go
Raw Normal View History

2014-11-22 13:21:30 +00:00
package ircd
import (
"code.dnix.de/conf"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
// "io"
"code.dnix.de/xlog"
"runtime"
)
const (
CHANLIMIT = 1024
CHANNELLEN = 200
TOPICLEN = 1024
)
var flagConfig string
var myinfo string = "%s %s/%s * *"
var isupport string = "ALIAS FRIEND UNFRIEND CASEMAPPING=rfc1459 CHANLIMIT=#:1024 CHANMODES=b,k,l,imnpst CHANNELLEN=200 CHANTYPES=# EXCEPTS=e KICKLEN MAXLIST=b:50,e:50 MODES=1 NETWORK=dnix.de NICKLEN=32 PREFIX=(aohv)&@%%+ SAFELIST STATUSMSG=&@%%+ TOPICLEN"
type ControlMsg struct {
Opcode int
Client *Client
}
type Server struct {
Config *conf.ConfigFile
Receive chan *Message
AddClient chan Client
DelClient chan Client
Host string
info string
software string
version string
created string
motd string
clients map[string]Client
channels map[string]*Channel
ports map[int]bool
configPath string
}
func init() {
}
// Create a new server instance.
func NewServer(configPath, software, version string) *Server {
srv := &Server{software: software, version: version, created: "yes"}
srv.Receive = make(chan *Message, 1024)
srv.AddClient = make(chan Client, 1024)
srv.DelClient = make(chan Client, 1024)
srv.Host = "dnix.de"
srv.clients = make(map[string]Client)
srv.channels = make(map[string]*Channel)
srv.info = ""
srv.motd = `foo bar baz.`
srv.configPath = configPath
srv.loadConfig()
loglevel, _ := srv.Config.GetInt("system", "loglevel")
xlog.Init(loglevel)
return srv
}
// Open the listening port and start the main server loop.
func (srv *Server) Run() {
xlog.Info("%s/%s", srv.software, srv.version)
srv.Host, _ = srv.Config.GetString("server", "host")
srv.info, _ = srv.Config.GetString("server", "info")
port, _ := srv.Config.GetInt("net", "port")
go srv.listen(port)
srv.loop()
}
func (srv *Server) loop() {
xlog.Debug("Entering server main loop.")
for {
time.Sleep(1 * time.Millisecond)
select {
case msg := <-srv.Receive:
srv.recvMsg(msg)
case cl := <-srv.AddClient:
if _, exists := srv.clients[cl.Name()]; exists {
xlog.Warning("Client registration failed: '%s'.", cl.Name())
go func() { cl.Register() <- false }()
continue
}
go func() { cl.Register() <- true }()
srv.clients[cl.Name()] = cl
xlog.Info("Client registered: '%s'.", cl.Name())
xlog.Info("Server has %d client(s).", len(srv.clients))
xlog.Debug("Goroutines running: %d.", runtime.NumGoroutine())
srv.clientLogon(cl)
srv.clientMotd(cl)
case cl := <-srv.DelClient:
delete(srv.clients, cl.Name())
xlog.Info("Client deleted: '%s'.", cl.Name())
xlog.Info("Server has %d client(s).", len(srv.clients))
xlog.Debug("Goroutines running: %d.", runtime.NumGoroutine())
default:
for name, ch := range srv.channels {
if len(ch.clients) == 0 {
ch.destroy <- true
delete(srv.channels, name)
xlog.Info("Channel destroyed: %s.", name)
}
}
}
}
}
func (srv *Server) listen(port int) {
if _, exists := srv.ports[port]; exists {
xlog.Warning("Port %i already opened.", port)
}
listen, err := net.Listen("tcp", ":"+strconv.Itoa(port))
if err != nil {
xlog.Fatal("Cannot listen on port %i (%s). Exiting.",
port, err.Error())
os.Exit(-1)
}
xlog.Info("Start listening on port %d.", port)
for {
time.Sleep(1e6)
conn, err := listen.Accept()
if err != nil {
// return err
}
NewRemoteClient(srv, conn)
}
}
func (srv *Server) loadConfig() {
conf, err := conf.ReadConfigFile(srv.configPath)
if err != nil {
xlog.Fatal("Can't read config file (%s).", err.Error())
os.Exit(-1)
}
srv.Config = conf
}
func (srv *Server) recvMsg(msg *Message) {
if AddrHost(msg.Dst) != "" {
// TODO send remote
return
}
if AddrHost(msg.Src) != "" {
// TODO from remote
return
}
if msg.Dst != "" {
srv.sendMsg(msg)
return
}
cmd := msg.Cmd
hook, exists := srvCommandHooks[cmd]
if !exists {
srv.sendCommand(msg.Src, ERR_UNKNOWNCOMMAND, cmd, "Unknown command.")
return
}
argc := len(msg.Args)
if argc < hook.MinArgs {
srv.sendCommand(msg.Src, ERR_NEEDMOREPARAMS, cmd,
"Not enough parameters.")
return
}
hook.HookFn(srv, msg)
}
func (srv *Server) sendMsg(msg *Message) {
// Splitting this into two functions is necessary to avoid an
// initialization loop in channel.go when broadcasting channel messages.
if strings.HasPrefix(msg.Dst, "#") {
srv.sendMsgToChannel(msg)
} else {
srv.sendMsgToClient(msg)
}
}
func (srv *Server) sendMsgToChannel(msg *Message) {
if _, exists := srv.channels[msg.Dst]; !exists {
if msg.Cmd != "JOIN" {
srv.sendCommand(msg.Src, ERR_NOSUCHCHANNEL, msg.Dst, "No such channel.")
return
}
srv.channels[msg.Dst] = NewChannel(srv, msg.Dst)
xlog.Info("Channel created: %s.", msg.Dst)
}
ch := srv.channels[msg.Dst]
ch.Receive(msg)
}
func (srv *Server) sendMsgToClient(msg *Message) {
if _, exists := srv.clients[msg.Dst]; !exists {
xlog.Error("Client '%s' does not exist.", msg.Dst)
return
}
cl := srv.clients[msg.Dst]
cl.Receive(msg)
}
func (srv *Server) sendRemote(msg *Message) {
}
func (srv *Server) sendCommand(dst, cmd, args, text string) {
srv.sendMsg(M(srv.Host, dst, dst, cmd, args, text))
}
func (srv *Server) sendClient(cl Client, cmd, args, text string) {
srv.sendMsg(M(srv.Host, cl.Name(), cl.Name(), cmd, args, text))
}
func (srv *Server) clientLogon(cl Client) {
srv.sendClient(cl, RPL_WELCOME, "", "Willkommen!")
srv.sendClient(cl, RPL_YOURHOST, "",
fmt.Sprintf("Your host is %s, running on %s/%s.",
srv.Host, srv.software, srv.version))
srv.sendClient(cl, RPL_CREATED, "",
"This server was created. Yes. Really.")
srv.sendClient(cl, RPL_MYINFO,
fmt.Sprintf(myinfo, srv.Host, srv.software, srv.version), "")
srv.sendClient(cl, RPL_ISUPPORT, isupport, "are supported by this server.")
}
func (srv *Server) clientMotd(cl Client) {
srv.sendClient(cl, RPL_MOTDSTART, "",
fmt.Sprintf("- %s Message of the day -", srv.Host))
for _, line := range strings.Split(srv.motd, "\n") {
srv.sendClient(cl, RPL_MOTD, "", fmt.Sprintf("- %s", line))
}
srv.sendClient(cl, RPL_ENDOFMOTD, "", "End of MOTD command.")
}
type SrvCommandHook struct {
HookFn func(srv *Server, msg *Message)
MinArgs int
NeedOper bool
NeedAuth bool
}
var srvCommandHooks = map[string]SrvCommandHook{
"OPER": {srvHandleCmdOper, 1, false, false},
"QUIT": {srvHandleCmdQuit, 0, false, false},
"MODE": {srvHandleCmdMode, 1, false, false},
"LIST": {srvHandleCmdList, 0, false, false},
"VERSION": {srvHandleCmdVersion, 0, false, false},
"STATS": {srvHandleCmdStats, 0, false, false},
"TIME": {srvHandleCmdTime, 0, false, false},
"ADMIN": {srvHandleCmdAdmin, 0, false, false},
"INFO": {srvHandleCmdInfo, 0, false, false},
"WHO": {srvHandleCmdWho, 0, false, false},
"WHOIS": {srvHandleCmdWhois, 0, false, false},
"WHOWAS": {srvHandleCmdWhowas, 0, false, false},
"KILL": {srvHandleCmdKill, 0, false, false},
"PING": {srvHandleCmdPing, 0, false, false},
"PONG": {srvHandleCmdPong, 0, false, false},
"ERROR": {srvHandleCmdError, 0, false, false},
"AWAY": {srvHandleCmdAway, 0, false, false},
"REHASH": {srvHandleCmdRehash, 0, false, false},
"RESTART": {srvHandleCmdRestart, 0, false, false},
"SUMMON": {srvHandleCmdSummon, 0, false, false},
"USERS": {srvHandleCmdUsers, 0, false, false},
"USERHOST": {srvHandleCmdUserhost, 0, false, false},
"ISON": {srvHandleCmdIson, 0, false, false},
}
func srvHandleCmdOper(srv *Server, msg *Message) {
}
func srvHandleCmdQuit(srv *Server, msg *Message) {
}
func srvHandleCmdMode(srv *Server, msg *Message) {
}
func srvHandleCmdList(srv *Server, msg *Message) {
}
func srvHandleCmdVersion(srv *Server, msg *Message) {
}
func srvHandleCmdStats(srv *Server, msg *Message) {
}
func srvHandleCmdTime(srv *Server, msg *Message) {
}
func srvHandleCmdAdmin(srv *Server, msg *Message) {
}
func srvHandleCmdInfo(srv *Server, msg *Message) {
}
func srvHandleCmdWho(srv *Server, msg *Message) {
}
func srvHandleCmdWhois(srv *Server, msg *Message) {
}
func srvHandleCmdWhowas(srv *Server, msg *Message) {
}
func srvHandleCmdKill(srv *Server, msg *Message) {
}
func srvHandleCmdPing(srv *Server, msg *Message) {
srv.sendCommand(msg.Src, "PONG", "", msg.Args[0])
}
func srvHandleCmdPong(srv *Server, msg *Message) {
}
func srvHandleCmdError(srv *Server, msg *Message) {
}
func srvHandleCmdAway(srv *Server, msg *Message) {
}
func srvHandleCmdRehash(srv *Server, msg *Message) {
srv.loadConfig()
srv.sendCommand(msg.Src, RPL_REHASHING, "", "Rehashing.")
xlog.Info("Rehashing.")
}
func srvHandleCmdRestart(srv *Server, msg *Message) {
}
func srvHandleCmdSummon(srv *Server, msg *Message) {
}
func srvHandleCmdUsers(srv *Server, msg *Message) {
}
func srvHandleCmdUserhost(srv *Server, msg *Message) {
}
func srvHandleCmdIson(srv *Server, msg *Message) {
}
// vim:ts=4:sts=4:sw=4:noet:tw=72