]> Cypherpunks.ru repositories - goircd.git/blobdiff - daemon.go
Increase maximum nickname length for convenience
[goircd.git] / daemon.go
index 487e5876ff5605d47db4adb93fd3734238affecf..9145ba08dd950e345b2df1c7843b93817de17d24 100644 (file)
--- a/daemon.go
+++ b/daemon.go
@@ -1,6 +1,6 @@
 /*
 goircd -- minimalistic simple Internet Relay Chat (IRC) server
-Copyright (C) 2014 Sergey Matveev <stargrave@stargrave.org>
+Copyright (C) 2014-2015 Sergey Matveev <stargrave@stargrave.org>
 
 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
@@ -15,14 +15,14 @@ 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/>.
 */
+
 package main
 
 import (
-       "bytes"
        "fmt"
-       "io"
+       "io/ioutil"
        "log"
-       "os"
+       "net"
        "regexp"
        "sort"
        "strings"
@@ -30,29 +30,46 @@ import (
 )
 
 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
+       // 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
+)
+
+var (
+       RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
 )
 
 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]struct{}
+       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}
-       daemon.clients = make(map[*Client]bool)
+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]struct{})
+       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
 }
 
@@ -67,29 +84,23 @@ func (daemon *Daemon) SendLusers(client *Client) {
 }
 
 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(motd, []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("422", "MOTD File is missing")
+
+       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("376", "End of /MOTD command")
 }
 
 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
@@ -97,12 +108,21 @@ func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
                nickname = strings.ToLower(nickname)
                found := false
                for c := range daemon.clients {
-                       if c.nickname != nickname {
+                       if strings.ToLower(c.nickname) != nickname {
                                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 {
@@ -148,24 +168,29 @@ func (daemon *Daemon) SendList(client *Client, cols []string) {
 // 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 := strings.ToLower(cols[1])
-               nickname_found := false
-               for client := range daemon.clients {
-                       if client.nickname == nickname {
-                               nickname_found = true
+               nickname := cols[1]
+               // Compatibility with some clients prepending colons to nickname
+               nickname = strings.TrimPrefix(nickname, ":")
+               for existingClient := range daemon.clients {
+                       if existingClient.nickname == nickname {
+                               client.ReplyParts("433", "*", nickname, "Nickname is already in use")
+                               return
                        }
                }
-               if nickname_found {
-                       client.ReplyParts("433", "*", cols[1], "Nickname is already in use")
-                       return
-               }
-               if ok, _ := regexp.MatchString("^[^_-][_a-z0-9-]{1,50}$", nickname); !ok {
+               if !RENickname.MatchString(nickname) {
                        client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
+                       return
                }
                client.nickname = nickname
        case "USER":
@@ -182,25 +207,50 @@ func (daemon *Daemon) ClientRegister(client *Client, command string, cols []stri
                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
+func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
+       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) {
@@ -213,8 +263,7 @@ func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
                keys = []string{}
        }
        for n, room := range rooms {
-               room, valid := RoomNameSanitize(room)
-               if !valid {
+               if !RoomNameValid(room) {
                        client.ReplyNoChannel(room)
                        continue
                }
@@ -226,12 +275,12 @@ 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
@@ -239,79 +288,101 @@ func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
                }
                if denied {
                        client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
-                       continue
                }
                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
+                       roomNew.key = key
+                       roomNew.StateSave()
                }
-               room_sink <- ClientEvent{client, EVENT_NEW, ""}
+               roomSink <- ClientEvent{client, EventNew, ""}
        }
 }
 
-func (daemon *Daemon) Processor(events chan ClientEvent) {
+func (daemon *Daemon) Processor(events <-chan ClientEvent) {
+       var now time.Time
        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:
-                       daemon.clients[client] = true
-               case EVENT_DEL:
+               switch event.eventType {
+               case EventNew:
+                       daemon.clients[client] = struct{}{}
+                       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")
@@ -326,16 +397,16 @@ func (daemon *Daemon) Processor(events chan ClientEvent) {
                                        }
                                        continue
                                }
-                               room, _ := RoomNameSanitize(cols[0])
+                               room := cols[0]
                                r, found := daemon.rooms[room]
                                if !found {
                                        client.ReplyNoChannel(room)
                                        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)
@@ -344,20 +415,21 @@ func (daemon *Daemon) Processor(events chan ClientEvent) {
                                        client.ReplyNotEnoughParameters("PART")
                                        continue
                                }
-                               for _, room := range strings.Split(cols[1], ",") {
-                                       room, _ = RoomNameSanitize(room)
+                               rooms := strings.Split(cols[1], " ")[0]
+                               for _, room := range strings.Split(rooms, ",") {
                                        r, found := daemon.rooms[room]
                                        if !found {
                                                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":
@@ -374,30 +446,37 @@ func (daemon *Daemon) Processor(events chan ClientEvent) {
                                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 msg != "" {
                                        continue
                                }
-                               target, _ = RoomNameSanitize(target)
                                r, found := daemon.rooms[target]
                                if !found {
                                        client.ReplyNoNickChan(target)
+                                       continue
+                               }
+                               daemon.roomSinks[r] <- ClientEvent{
+                                       client,
+                                       EventMsg,
+                                       command + " " + strings.TrimLeft(cols[1], ":"),
                                }
-                               daemon.room_sinks[r] <- ClientEvent{client, EVENT_MSG, command + " " + strings.TrimLeft(cols[1], ":")}
                        case "TOPIC":
                                if len(cols) == 1 {
                                        client.ReplyNotEnoughParameters("TOPIC")
                                        continue
                                }
                                cols = strings.SplitN(cols[1], " ", 2)
-                               room, _ := RoomNameSanitize(cols[0])
-                               r, found := daemon.rooms[room]
+                               r, found := daemon.rooms[cols[0]]
                                if !found {
-                                       client.ReplyNoChannel(room)
+                                       client.ReplyNoChannel(cols[0])
+                                       continue
                                }
                                var change string
                                if len(cols) > 1 {
@@ -405,18 +484,19 @@ func (daemon *Daemon) Processor(events chan ClientEvent) {
                                } 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")
                                        continue
                                }
-                               room, _ := RoomNameSanitize(strings.Split(cols[1], " ")[0])
+                               room := strings.Split(cols[1], " ")[0]
                                r, found := daemon.rooms[room]
                                if !found {
                                        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")
@@ -424,10 +504,22 @@ func (daemon *Daemon) Processor(events chan ClientEvent) {
                                }
                                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
+               }
        }
 }