goircd/daemon.go

525 lines
14 KiB
Go
Raw Normal View History

2014-05-11 16:18:55 +00:00
/*
goircd -- minimalistic simple Internet Relay Chat (IRC) server
2015-05-09 15:27:06 +00:00
Copyright (C) 2014-2015 Sergey Matveev <stargrave@stargrave.org>
2014-05-11 16:18:55 +00:00
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2015-05-09 15:27:06 +00:00
2014-05-11 16:18:55 +00:00
package main
import (
"fmt"
2014-06-08 01:16:33 +00:00
"io/ioutil"
2014-05-11 16:18:55 +00:00
"log"
2014-06-09 14:03:11 +00:00
"net"
2014-05-11 16:18:55 +00:00
"regexp"
"sort"
"strings"
"time"
)
const (
2015-05-09 15:27:06 +00:00
// Max time deadline for client's unresponsiveness
PingTimeout = time.Second * 180
// Max idle client's time before PING are sent
PingThreshold = time.Second * 90
// Client's aliveness check period
AlivenessCheck = time.Second * 10
2014-05-11 16:18:55 +00:00
)
var (
2014-08-09 12:42:19 +00:00
RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
)
2014-05-11 16:18:55 +00:00
type Daemon struct {
2014-08-09 12:42:19 +00:00
Verbose bool
2014-08-14 10:31:34 +00:00
version string
hostname *string
motd *string
passwords *string
2015-10-06 07:59:49 +00:00
clients map[*Client]struct{}
2014-08-09 12:42:19 +00:00
clientAliveness map[*Client]*ClientAlivenessState
rooms map[string]*Room
roomSinks map[*Room]chan ClientEvent
lastAlivenessCheck time.Time
logSink chan<- LogEvent
stateSink chan<- StateEvent
2014-05-11 16:18:55 +00:00
}
func NewDaemon(version string, hostname, motd, passwords *string, logSink chan<- LogEvent, stateSink chan<- StateEvent) *Daemon {
2015-05-09 15:27:06 +00:00
daemon := Daemon{
2015-10-06 07:59:49 +00:00
version: version,
hostname: hostname,
motd: motd,
2015-05-09 15:27:06 +00:00
passwords: passwords,
}
2015-10-06 07:59:49 +00:00
daemon.clients = make(map[*Client]struct{})
2014-08-09 12:42:19 +00:00
daemon.clientAliveness = make(map[*Client]*ClientAlivenessState)
2014-05-11 16:18:55 +00:00
daemon.rooms = make(map[string]*Room)
2014-08-09 12:42:19 +00:00
daemon.roomSinks = make(map[*Room]chan ClientEvent)
daemon.logSink = logSink
daemon.stateSink = stateSink
2014-05-11 16:18:55 +00:00
return &daemon
}
func (daemon *Daemon) SendLusers(client *Client) {
lusers := 0
for client := range daemon.clients {
if client.registered {
lusers++
}
}
client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
2014-05-11 16:18:55 +00:00
}
func (daemon *Daemon) SendMotd(client *Client) {
if daemon.motd == nil || *daemon.motd == "" {
2014-06-08 01:16:33 +00:00
client.ReplyNicknamed("422", "MOTD File is missing")
return
}
2014-05-11 16:18:55 +00:00
motd, err := ioutil.ReadFile(*daemon.motd)
2014-06-08 01:16:33 +00:00
if err != nil {
log.Printf("Can not read motd file %s: %v", *daemon.motd, err)
2014-06-08 01:16:33 +00:00
client.ReplyNicknamed("422", "Error reading MOTD File")
return
}
client.ReplyNicknamed("375", "- "+*daemon.hostname+" Message of the day -")
2014-06-08 01:16:33 +00:00
for _, s := range strings.Split(strings.Trim(string(motd), "\n"), "\n") {
client.ReplyNicknamed("372", "- "+string(s))
2014-05-11 16:18:55 +00:00
}
2014-06-08 01:16:33 +00:00
client.ReplyNicknamed("376", "End of /MOTD command")
2014-05-11 16:18:55 +00:00
}
func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
for _, nickname := range nicknames {
nickname = strings.ToLower(nickname)
found := false
for c := range daemon.clients {
2014-06-08 00:28:55 +00:00
if strings.ToLower(c.nickname) != nickname {
2014-05-11 16:18:55 +00:00
continue
}
found = true
2014-06-09 14:03:11 +00:00
h := c.conn.RemoteAddr().String()
h, _, err := net.SplitHostPort(h)
if err != nil {
log.Printf("Can't parse RemoteAddr %q: %v", h, err)
h = "Unknown"
}
client.ReplyNicknamed("311", c.nickname, c.username, h, "*", c.realname)
client.ReplyNicknamed("312", c.nickname, *daemon.hostname, *daemon.hostname)
2014-11-14 20:26:32 +00:00
if c.away != nil {
client.ReplyNicknamed("301", c.nickname, *c.away)
}
2014-05-11 16:18:55 +00:00
subscriptions := []string{}
for _, room := range daemon.rooms {
for subscriber := range room.members {
if subscriber.nickname == nickname {
subscriptions = append(subscriptions, room.name)
}
}
}
sort.Strings(subscriptions)
client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
2014-05-11 16:18:55 +00:00
}
if !found {
2014-05-13 19:56:29 +00:00
client.ReplyNoNickChan(nickname)
2014-05-11 16:18:55 +00:00
}
}
}
func (daemon *Daemon) SendList(client *Client, cols []string) {
var rooms []string
if (len(cols) > 1) && (cols[1] != "") {
rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
} else {
rooms = []string{}
for room := range daemon.rooms {
rooms = append(rooms, room)
}
}
sort.Strings(rooms)
for _, room := range rooms {
r, found := daemon.rooms[room]
if found {
client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
}
}
client.ReplyNicknamed("323", "End of /LIST")
2014-05-11 16:18:55 +00:00
}
// Unregistered client workflow processor. Unregistered client:
// * is not PINGed
// * only QUIT, NICK and USER commands are processed
// * other commands are quietly ignored
// When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
switch command {
case "PASS":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("PASS")
return
}
client.password = cols[1]
2014-05-11 16:18:55 +00:00
case "NICK":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyParts("431", "No nickname given")
return
}
nickname := cols[1]
// Compatibility with some clients prepending colons to nickname
nickname = strings.TrimPrefix(nickname, ":")
2014-08-09 12:42:19 +00:00
for existingClient := range daemon.clients {
if existingClient.nickname == nickname {
client.ReplyParts("433", "*", nickname, "Nickname is already in use")
return
2014-05-11 16:18:55 +00:00
}
}
2014-08-09 12:42:19 +00:00
if !RENickname.MatchString(nickname) {
2014-05-11 16:18:55 +00:00
client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
return
2014-05-11 16:18:55 +00:00
}
client.nickname = nickname
case "USER":
if len(cols) == 1 {
client.ReplyNotEnoughParameters("USER")
return
}
args := strings.SplitN(cols[1], " ", 4)
if len(args) < 4 {
client.ReplyNotEnoughParameters("USER")
return
}
client.username = args[0]
client.realname = strings.TrimLeft(args[3], ":")
}
if client.nickname != "*" && client.username != "" {
if daemon.passwords != nil && *daemon.passwords != "" {
if client.password == "" {
client.ReplyParts("462", "You may not register")
client.conn.Close()
return
}
contents, err := ioutil.ReadFile(*daemon.passwords)
if err != nil {
log.Fatalf("Can no read passwords file %s: %s", *daemon.passwords, err)
return
}
for _, entry := range strings.Split(string(contents), "\n") {
if entry == "" {
continue
}
if lp := strings.Split(entry, ":"); lp[0] == client.nickname && lp[1] != client.password {
client.ReplyParts("462", "You may not register")
client.conn.Close()
return
}
}
}
2014-05-11 16:18:55 +00:00
client.registered = true
client.ReplyNicknamed("001", "Hi, welcome to IRC")
client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
2014-05-11 16:18:55 +00:00
client.ReplyNicknamed("003", "This server was created sometime")
client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
2014-05-11 16:18:55 +00:00
daemon.SendLusers(client)
daemon.SendMotd(client)
log.Println(client, "logged in")
2014-05-11 16:18:55 +00:00
}
}
// Register new room in Daemon. Create an object, events sink, save pointers
// to corresponding daemon's places and start room's processor goroutine.
2014-06-08 00:21:06 +00:00
func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
2014-08-09 12:42:19 +00:00
roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
roomNew.Verbose = daemon.Verbose
roomSink := make(chan ClientEvent)
daemon.rooms[name] = roomNew
daemon.roomSinks[roomNew] = roomSink
go roomNew.Processor(roomSink)
return roomNew, roomSink
2014-05-11 16:18:55 +00:00
}
func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
args := strings.Split(cmd, " ")
rooms := strings.Split(args[0], ",")
var keys []string
if len(args) > 1 {
keys = strings.Split(args[1], ",")
} else {
keys = []string{}
}
for n, room := range rooms {
if !RoomNameValid(room) {
2014-05-11 16:18:55 +00:00
client.ReplyNoChannel(room)
continue
}
var key string
if (n < len(keys)) && (keys[n] != "") {
key = keys[n]
} else {
key = ""
}
denied := false
joined := false
2014-08-09 12:42:19 +00:00
for roomExisting, roomSink := range daemon.roomSinks {
if room == roomExisting.name {
if (roomExisting.key != "") && (roomExisting.key != key) {
2014-05-11 16:18:55 +00:00
denied = true
} else {
2014-08-09 12:42:19 +00:00
roomSink <- ClientEvent{client, EventNew, ""}
2014-05-11 16:18:55 +00:00
joined = true
}
break
}
}
if denied {
client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
}
if denied || joined {
continue
}
2014-08-09 12:42:19 +00:00
roomNew, roomSink := daemon.RoomRegister(room)
log.Println("Room", roomNew, "created")
2014-05-11 16:18:55 +00:00
if key != "" {
2014-08-09 12:42:19 +00:00
roomNew.key = key
roomNew.StateSave()
2014-05-11 16:18:55 +00:00
}
2014-08-09 12:42:19 +00:00
roomSink <- ClientEvent{client, EventNew, ""}
2014-05-11 16:18:55 +00:00
}
}
2014-06-08 00:21:06 +00:00
func (daemon *Daemon) Processor(events <-chan ClientEvent) {
2015-10-06 07:59:49 +00:00
var now time.Time
2014-05-11 16:18:55 +00:00
for event := range events {
2015-10-06 07:59:49 +00:00
now = time.Now()
2014-08-09 11:37:10 +00:00
client := event.client
2014-05-11 16:18:55 +00:00
// Check for clients aliveness
2014-08-09 12:42:19 +00:00
if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
2014-05-11 16:18:55 +00:00
for c := range daemon.clients {
2014-08-09 12:42:19 +00:00
aliveness, alive := daemon.clientAliveness[c]
2014-08-09 11:37:10 +00:00
if !alive {
continue
}
2014-08-09 12:42:19 +00:00
if aliveness.timestamp.Add(PingTimeout).Before(now) {
2014-05-11 16:18:55 +00:00
log.Println(c, "ping timeout")
c.conn.Close()
continue
}
2014-08-09 12:42:19 +00:00
if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
2014-05-11 16:18:55 +00:00
if c.registered {
c.Msg("PING :" + *daemon.hostname)
2014-08-09 12:42:19 +00:00
aliveness.pingSent = true
2014-05-11 16:18:55 +00:00
} else {
log.Println(c, "ping timeout")
c.conn.Close()
}
}
}
2014-08-09 12:42:19 +00:00
daemon.lastAlivenessCheck = now
2014-05-11 16:18:55 +00:00
}
2014-08-09 12:42:19 +00:00
switch event.eventType {
case EventNew:
2015-10-06 07:59:49 +00:00
daemon.clients[client] = struct{}{}
2015-05-09 15:27:06 +00:00
daemon.clientAliveness[client] = &ClientAlivenessState{
2015-10-06 07:59:49 +00:00
pingSent: false,
2015-05-09 15:27:06 +00:00
timestamp: now,
}
2014-08-09 12:42:19 +00:00
case EventDel:
2014-05-11 16:18:55 +00:00
delete(daemon.clients, client)
2014-08-09 12:42:19 +00:00
delete(daemon.clientAliveness, client)
for _, roomSink := range daemon.roomSinks {
roomSink <- event
2014-05-11 16:18:55 +00:00
}
2014-08-09 12:42:19 +00:00
case EventMsg:
2014-05-11 16:18:55 +00:00
cols := strings.SplitN(event.text, " ", 2)
command := strings.ToUpper(cols[0])
2014-06-08 00:49:27 +00:00
if daemon.Verbose {
log.Println(client, "command", command)
}
2014-05-11 16:18:55 +00:00
if command == "QUIT" {
log.Println(client, "quit")
2014-05-11 16:18:55 +00:00
delete(daemon.clients, client)
2014-08-09 12:42:19 +00:00
delete(daemon.clientAliveness, client)
2014-05-11 16:18:55 +00:00
client.conn.Close()
continue
}
if !client.registered {
2014-08-09 11:37:10 +00:00
daemon.ClientRegister(client, command, cols)
2014-05-11 16:18:55 +00:00
continue
}
switch command {
case "AWAY":
2014-11-14 20:26:32 +00:00
if len(cols) == 1 {
client.away = nil
client.ReplyNicknamed("305", "You are no longer marked as being away")
continue
}
msg := strings.TrimLeft(cols[1], ":")
client.away = &msg
client.ReplyNicknamed("306", "You have been marked as being away")
2014-05-11 16:18:55 +00:00
case "JOIN":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("JOIN")
continue
}
2014-08-09 11:37:10 +00:00
daemon.HandlerJoin(client, cols[1])
2014-05-11 16:18:55 +00:00
case "LIST":
daemon.SendList(client, cols)
case "LUSERS":
daemon.SendLusers(client)
2014-05-11 16:18:55 +00:00
case "MODE":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("MODE")
continue
}
cols = strings.SplitN(cols[1], " ", 2)
if cols[0] == client.username {
if len(cols) == 1 {
client.Msg("221 " + client.nickname + " +")
} else {
client.ReplyNicknamed("501", "Unknown MODE flag")
}
continue
}
room := cols[0]
2014-05-11 16:18:55 +00:00
r, found := daemon.rooms[room]
if !found {
client.ReplyNoChannel(room)
continue
}
if len(cols) == 1 {
2014-08-09 12:42:19 +00:00
daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
2014-05-11 16:18:55 +00:00
} else {
2014-08-09 12:42:19 +00:00
daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
2014-05-11 16:18:55 +00:00
}
case "MOTD":
go daemon.SendMotd(client)
case "PART":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("PART")
continue
}
for _, room := range strings.Split(cols[1], ",") {
r, found := daemon.rooms[room]
if !found {
client.ReplyNoChannel(room)
2014-05-18 11:26:15 +00:00
continue
2014-05-11 16:18:55 +00:00
}
2014-08-09 12:42:19 +00:00
daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
2014-05-11 16:18:55 +00:00
}
case "PING":
if len(cols) == 1 {
client.ReplyNicknamed("409", "No origin specified")
continue
}
client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
2014-05-11 16:18:55 +00:00
case "PONG":
continue
case "NOTICE", "PRIVMSG":
if len(cols) == 1 {
client.ReplyNicknamed("411", "No recipient given ("+command+")")
2014-05-11 16:18:55 +00:00
continue
}
cols = strings.SplitN(cols[1], " ", 2)
if len(cols) == 1 {
client.ReplyNicknamed("412", "No text to send")
continue
}
msg := ""
target := strings.ToLower(cols[0])
for c := range daemon.clients {
if c.nickname == target {
msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
2014-05-11 16:18:55 +00:00
c.Msg(msg)
2014-11-14 20:26:32 +00:00
if c.away != nil {
client.ReplyNicknamed("301", c.nickname, *c.away)
}
2014-05-11 16:18:55 +00:00
break
}
}
if msg != "" {
continue
}
r, found := daemon.rooms[target]
if !found {
2014-05-13 19:56:29 +00:00
client.ReplyNoNickChan(target)
continue
2014-05-11 16:18:55 +00:00
}
2015-05-09 15:27:06 +00:00
daemon.roomSinks[r] <- ClientEvent{
client,
EventMsg,
command + " " + strings.TrimLeft(cols[1], ":"),
}
2014-05-11 16:18:55 +00:00
case "TOPIC":
if len(cols) == 1 {
client.ReplyNotEnoughParameters("TOPIC")
continue
}
cols = strings.SplitN(cols[1], " ", 2)
r, found := daemon.rooms[cols[0]]
2014-05-11 16:18:55 +00:00
if !found {
client.ReplyNoChannel(cols[0])
2014-05-18 11:26:15 +00:00
continue
2014-05-11 16:18:55 +00:00
}
var change string
if len(cols) > 1 {
change = cols[1]
} else {
change = ""
}
2014-08-09 12:42:19 +00:00
daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
2014-05-11 16:18:55 +00:00
case "WHO":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("WHO")
continue
}
room := strings.Split(cols[1], " ")[0]
2014-05-11 16:18:55 +00:00
r, found := daemon.rooms[room]
if !found {
client.ReplyNoChannel(room)
2014-05-18 11:26:15 +00:00
continue
2014-05-11 16:18:55 +00:00
}
2014-08-09 12:42:19 +00:00
daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
2014-05-11 16:18:55 +00:00
case "WHOIS":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("WHOIS")
continue
}
cols := strings.Split(cols[1], " ")
nicknames := strings.Split(cols[len(cols)-1], ",")
daemon.SendWhois(client, nicknames)
2014-08-14 10:31:34 +00:00
case "VERSION":
var debug string
if daemon.Verbose {
debug = "debug"
} else {
debug = ""
}
client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
2014-05-11 16:18:55 +00:00
default:
client.ReplyNicknamed("421", command, "Unknown command")
}
}
2014-08-09 12:42:19 +00:00
if aliveness, alive := daemon.clientAliveness[client]; alive {
2014-08-09 11:37:10 +00:00
aliveness.timestamp = now
2014-08-09 12:42:19 +00:00
aliveness.pingSent = false
2014-08-09 11:37:10 +00:00
}
2014-05-11 16:18:55 +00:00
}
}