package main
import (
- "bytes"
"fmt"
- "io"
+ "io/ioutil"
"log"
- "os"
+ "net"
"regexp"
"sort"
"strings"
)
const (
- PING_TIMEOUT = time.Second * 180 // Max time deadline for client's unresponsiveness
- PING_THRESHOLD = time.Second * 90 // Max idle client's time before PING are sent
- ALIVENESS_CHECK = time.Second * 10 // Client's aliveness check period
+ PingTimeout = time.Second * 180 // Max time deadline for client's unresponsiveness
+ PingThreshold = time.Second * 90 // Max idle client's time before PING are sent
+ AlivenessCheck = time.Second * 10 // Client's aliveness check period
)
var (
- RE_NICKNAME = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
+ RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
)
type Daemon struct {
- hostname string
- motd string
- clients map[*Client]bool
- rooms map[string]*Room
- room_sinks map[*Room]chan ClientEvent
- last_aliveness_check time.Time
- log_sink chan<- LogEvent
- state_sink chan<- StateEvent
+ Verbose bool
+ version string
+ hostname *string
+ motd *string
+ passwords *string
+ clients map[*Client]bool
+ clientAliveness map[*Client]*ClientAlivenessState
+ rooms map[string]*Room
+ roomSinks map[*Room]chan ClientEvent
+ lastAlivenessCheck time.Time
+ logSink chan<- LogEvent
+ stateSink chan<- StateEvent
}
-func NewDaemon(hostname, motd string, log_sink chan<- LogEvent, state_sink chan<- StateEvent) *Daemon {
- daemon := Daemon{hostname: hostname, motd: motd}
+func NewDaemon(version string, hostname, motd, passwords *string, logSink chan<- LogEvent, stateSink chan<- StateEvent) *Daemon {
+ daemon := Daemon{version: version, hostname: hostname, motd: motd, passwords: passwords}
daemon.clients = make(map[*Client]bool)
+ daemon.clientAliveness = make(map[*Client]*ClientAlivenessState)
daemon.rooms = make(map[string]*Room)
- daemon.room_sinks = make(map[*Room]chan ClientEvent)
- daemon.log_sink = log_sink
- daemon.state_sink = state_sink
+ daemon.roomSinks = make(map[*Room]chan ClientEvent)
+ daemon.logSink = logSink
+ daemon.stateSink = stateSink
return &daemon
}
}
func (daemon *Daemon) SendMotd(client *Client) {
- if daemon.motd != "" {
- fd, err := os.Open(daemon.motd)
- if err == nil {
- defer fd.Close()
- motd := []byte{}
- var err error
- for err != io.EOF {
- buf := make([]byte, 1024)
- _, err = fd.Read(buf)
- motd = append(motd, bytes.TrimRight(buf, "\x00")...)
- }
+ if daemon.motd == nil || *daemon.motd == "" {
+ client.ReplyNicknamed("422", "MOTD File is missing")
+ return
+ }
- client.ReplyNicknamed("375", "- "+daemon.hostname+" Message of the day -")
- for _, s := range bytes.Split(bytes.TrimRight(motd, "\n"), []byte("\n")) {
- client.ReplyNicknamed("372", "- "+string(s))
- }
- client.ReplyNicknamed("376", "End of /MOTD command")
- return
- } else {
- log.Println("Can not open motd file", daemon.motd, err)
- }
+ motd, err := ioutil.ReadFile(*daemon.motd)
+ if err != nil {
+ log.Printf("Can not read motd file %s: %v", *daemon.motd, err)
+ client.ReplyNicknamed("422", "Error reading MOTD File")
+ return
+ }
+
+ client.ReplyNicknamed("375", "- "+*daemon.hostname+" Message of the day -")
+ for _, s := range strings.Split(strings.Trim(string(motd), "\n"), "\n") {
+ client.ReplyNicknamed("372", "- "+string(s))
}
- client.ReplyNicknamed("422", "MOTD File is missing")
+ client.ReplyNicknamed("376", "End of /MOTD command")
}
func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
continue
}
found = true
- client.ReplyNicknamed("311", c.nickname, c.username, c.conn.RemoteAddr().String(), "*", c.realname)
- client.ReplyNicknamed("312", c.nickname, daemon.hostname, daemon.hostname)
+ 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)
+ if c.away != nil {
+ client.ReplyNicknamed("301", c.nickname, *c.away)
+ }
subscriptions := []string{}
for _, room := range daemon.rooms {
for subscriber := range room.members {
// 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]
case "NICK":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyParts("431", "No nickname given")
return
}
nickname := cols[1]
- for client := range daemon.clients {
- if client.nickname == nickname {
+ for existingClient := range daemon.clients {
+ if existingClient.nickname == nickname {
client.ReplyParts("433", "*", nickname, "Nickname is already in use")
return
}
}
- if !RE_NICKNAME.MatchString(nickname) {
+ if !RENickname.MatchString(nickname) {
client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
return
}
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
+ }
+ }
+ }
+
client.registered = true
client.ReplyNicknamed("001", "Hi, welcome to IRC")
- client.ReplyNicknamed("002", "Your host is "+daemon.hostname+", running goircd")
+ client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
client.ReplyNicknamed("003", "This server was created sometime")
- client.ReplyNicknamed("004", daemon.hostname+" goircd o o")
+ client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
daemon.SendLusers(client)
daemon.SendMotd(client)
+ log.Println(client, "logged in")
}
}
// Register new room in Daemon. Create an object, events sink, save pointers
// to corresponding daemon's places and start room's processor goroutine.
func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
- room_new := NewRoom(daemon.hostname, name, daemon.log_sink, daemon.state_sink)
- room_sink := make(chan ClientEvent)
- daemon.rooms[name] = room_new
- daemon.room_sinks[room_new] = room_sink
- go room_new.Processor(room_sink)
- return room_new, room_sink
+ 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
}
func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
}
denied := false
joined := false
- for room_existing, room_sink := range daemon.room_sinks {
- if room == room_existing.name {
- if (room_existing.key != "") && (room_existing.key != key) {
+ for roomExisting, roomSink := range daemon.roomSinks {
+ if room == roomExisting.name {
+ if (roomExisting.key != "") && (roomExisting.key != key) {
denied = true
} else {
- room_sink <- ClientEvent{client, EVENT_NEW, ""}
+ roomSink <- ClientEvent{client, EventNew, ""}
joined = true
}
break
if denied || joined {
continue
}
- room_new, room_sink := daemon.RoomRegister(room)
+ roomNew, roomSink := daemon.RoomRegister(room)
+ log.Println("Room", roomNew, "created")
if key != "" {
- room_new.key = key
- room_new.StateSave()
+ roomNew.key = key
+ roomNew.StateSave()
}
- room_sink <- ClientEvent{client, EVENT_NEW, ""}
+ roomSink <- ClientEvent{client, EventNew, ""}
}
}
func (daemon *Daemon) Processor(events <-chan ClientEvent) {
for event := range events {
+ now := time.Now()
+ client := event.client
// Check for clients aliveness
- now := time.Now()
- if daemon.last_aliveness_check.Add(ALIVENESS_CHECK).Before(now) {
+ if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
for c := range daemon.clients {
- if c.timestamp.Add(PING_TIMEOUT).Before(now) {
+ aliveness, alive := daemon.clientAliveness[c]
+ if !alive {
+ continue
+ }
+ if aliveness.timestamp.Add(PingTimeout).Before(now) {
log.Println(c, "ping timeout")
c.conn.Close()
continue
}
- if !c.ping_sent && c.timestamp.Add(PING_THRESHOLD).Before(now) {
+ if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
if c.registered {
- c.Msg("PING :" + daemon.hostname)
- c.ping_sent = true
+ c.Msg("PING :" + *daemon.hostname)
+ aliveness.pingSent = true
} else {
log.Println(c, "ping timeout")
c.conn.Close()
}
}
}
- daemon.last_aliveness_check = now
+ daemon.lastAlivenessCheck = now
}
- client := event.client
- switch event.event_type {
- case EVENT_NEW:
+ switch event.eventType {
+ case EventNew:
daemon.clients[client] = true
- case EVENT_DEL:
+ daemon.clientAliveness[client] = &ClientAlivenessState{pingSent: false, timestamp: now}
+ case EventDel:
delete(daemon.clients, client)
- for _, room_sink := range daemon.room_sinks {
- room_sink <- event
+ delete(daemon.clientAliveness, client)
+ for _, roomSink := range daemon.roomSinks {
+ roomSink <- event
}
- case EVENT_MSG:
+ case EventMsg:
cols := strings.SplitN(event.text, " ", 2)
command := strings.ToUpper(cols[0])
- log.Println(client, "command", command)
+ if daemon.Verbose {
+ log.Println(client, "command", command)
+ }
if command == "QUIT" {
+ log.Println(client, "quit")
delete(daemon.clients, client)
+ delete(daemon.clientAliveness, client)
client.conn.Close()
continue
}
if !client.registered {
- go daemon.ClientRegister(client, command, cols)
+ daemon.ClientRegister(client, command, cols)
continue
}
switch command {
case "AWAY":
- continue
+ 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")
case "JOIN":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("JOIN")
continue
}
- go daemon.HandlerJoin(client, cols[1])
+ daemon.HandlerJoin(client, cols[1])
case "LIST":
daemon.SendList(client, cols)
case "LUSERS":
- go daemon.SendLusers(client)
+ daemon.SendLusers(client)
case "MODE":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("MODE")
continue
}
if len(cols) == 1 {
- daemon.room_sinks[r] <- ClientEvent{client, EVENT_MODE, ""}
+ daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
} else {
- daemon.room_sinks[r] <- ClientEvent{client, EVENT_MODE, cols[1]}
+ daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
}
case "MOTD":
go daemon.SendMotd(client)
client.ReplyNoChannel(room)
continue
}
- daemon.room_sinks[r] <- ClientEvent{client, EVENT_DEL, ""}
+ daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
}
case "PING":
if len(cols) == 1 {
client.ReplyNicknamed("409", "No origin specified")
continue
}
- client.Reply(fmt.Sprintf("PONG %s :%s", daemon.hostname, cols[1]))
+ client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
case "PONG":
continue
case "NOTICE", "PRIVMSG":
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])
+ msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
c.Msg(msg)
+ if c.away != nil {
+ client.ReplyNicknamed("301", c.nickname, *c.away)
+ }
break
}
}
if !found {
client.ReplyNoNickChan(target)
}
- daemon.room_sinks[r] <- ClientEvent{client, EVENT_MSG, command + " " + strings.TrimLeft(cols[1], ":")}
+ daemon.roomSinks[r] <- ClientEvent{client, EventMsg, command + " " + strings.TrimLeft(cols[1], ":")}
case "TOPIC":
if len(cols) == 1 {
client.ReplyNotEnoughParameters("TOPIC")
} else {
change = ""
}
- daemon.room_sinks[r] <- ClientEvent{client, EVENT_TOPIC, change}
+ daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
case "WHO":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("WHO")
client.ReplyNoChannel(room)
continue
}
- daemon.room_sinks[r] <- ClientEvent{client, EVENT_WHO, ""}
+ daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
case "WHOIS":
if len(cols) == 1 || len(cols[1]) < 1 {
client.ReplyNotEnoughParameters("WHOIS")
}
cols := strings.Split(cols[1], " ")
nicknames := strings.Split(cols[len(cols)-1], ",")
- go daemon.SendWhois(client, nicknames)
+ daemon.SendWhois(client, nicknames)
+ 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))
default:
client.ReplyNicknamed("421", command, "Unknown command")
}
}
+ if aliveness, alive := daemon.clientAliveness[client]; alive {
+ aliveness.timestamp = now
+ aliveness.pingSent = false
+ }
}
}