X-Git-Url: http://www.git.cypherpunks.ru/?p=goircd.git;a=blobdiff_plain;f=daemon.go;h=ce2dd000d2ae1bcd59a92cae8eeb0ca18a70ea79;hp=06916b0d6c39649dd4e5d519a72347fa72125ffd;hb=b7fb219307483d2c31b5dad1f559f325f2fd1a5e;hpb=5c79c4235ec745fa47c1f176657287dab4f61ed5 diff --git a/daemon.go b/daemon.go index 06916b0..ce2dd00 100644 --- a/daemon.go +++ b/daemon.go @@ -1,11 +1,10 @@ /* goircd -- minimalistic simple Internet Relay Chat (IRC) server -Copyright (C) 2014 Sergey Matveev +Copyright (C) 2014-2020 Sergey Matveev 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. +the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,315 +14,124 @@ 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 . */ + package main import ( "fmt" - "io/ioutil" "log" - "net" - "regexp" - "sort" "strings" "time" ) const ( - 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 ( - RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$") + // Max deadline time of client's unresponsiveness + PingTimeout = time.Second * 180 + // Max idle client's time before PING are sent + PingThreshold = time.Second * 90 ) -type Daemon struct { - Verbose bool - hostname string - motd 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, logSink chan<- LogEvent, stateSink chan<- StateEvent) *Daemon { - daemon := Daemon{hostname: hostname, motd: motd} - daemon.clients = make(map[*Client]bool) - daemon.clientAliveness = make(map[*Client]*ClientAlivenessState) - daemon.rooms = make(map[string]*Room) - daemon.roomSinks = make(map[*Room]chan ClientEvent) - daemon.logSink = logSink - daemon.stateSink = stateSink - return &daemon -} - -func (daemon *Daemon) SendLusers(client *Client) { - lusers := 0 - for client := range daemon.clients { - if client.registered { - lusers++ +func Processor(events chan ClientEvent, finished chan struct{}) { + var now time.Time + ticker := time.NewTicker(10 * time.Second) + go func() { + for range ticker.C { + events <- ClientEvent{eventType: EventTick} } - } - client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers)) -} - -func (daemon *Daemon) SendMotd(client *Client) { - if len(daemon.motd) == 0 { - client.ReplyNicknamed("422", "MOTD File is missing") - return - } - - 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("376", "End of /MOTD command") -} - -func (daemon *Daemon) SendWhois(client *Client, nicknames []string) { - for _, nickname := range nicknames { - nickname = strings.ToLower(nickname) - found := false - for c := range daemon.clients { - if strings.ToLower(c.nickname) != nickname { - continue - } - found = true - 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) - subscriptions := []string{} - for _, room := range daemon.rooms { - for subscriber := range room.members { - if subscriber.nickname == nickname { - subscriptions = append(subscriptions, room.name) + }() +EventsCycle: + for e := range events { + now = time.Now() + client := e.client + switch e.eventType { + case EventTick: + clientsLock.RLock() + for c := range clients { + if c.recvTimestamp.Add(PingTimeout).Before(now) { + if *verbose { + log.Println(c, "ping timeout") } - } - } - sort.Strings(subscriptions) - client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " ")) - client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list") - } - if !found { - client.ReplyNoNickChan(nickname) - } - } -} - -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") -} - -// 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 "NICK": - if len(cols) == 1 || len(cols[1]) < 1 { - client.ReplyParts("431", "No nickname given") - return - } - nickname := cols[1] - for existingClient := range daemon.clients { - if existingClient.nickname == nickname { - client.ReplyParts("433", "*", nickname, "Nickname is already in use") - return - } - } - if !RENickname.MatchString(nickname) { - client.ReplyParts("432", "*", cols[1], "Erroneous nickname") - return - } - 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 != "" { - client.registered = true - client.ReplyNicknamed("001", "Hi, welcome to IRC") - client.ReplyNicknamed("002", "Your host is "+daemon.hostname+", running goircd") - client.ReplyNicknamed("003", "This server was created sometime") - client.ReplyNicknamed("004", daemon.hostname+" goircd o o") - daemon.SendLusers(client) - daemon.SendMotd(client) - } -} - -// 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) { - 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) { - 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) { - client.ReplyNoChannel(room) - continue - } - var key string - if (n < len(keys)) && (keys[n] != "") { - key = keys[n] - } else { - key = "" - } - denied := false - joined := false - for roomExisting, roomSink := range daemon.roomSinks { - if room == roomExisting.name { - if (roomExisting.key != "") && (roomExisting.key != key) { - denied = true - } else { - roomSink <- ClientEvent{client, EventNew, ""} - joined = true - } - break - } - } - if denied { - client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key") - } - if denied || joined { - continue - } - roomNew, roomSink := daemon.RoomRegister(room) - if key != "" { - roomNew.key = key - roomNew.StateSave() - } - 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 - if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) { - for c := range daemon.clients { - aliveness, alive := daemon.clientAliveness[c] - if !alive { - continue - } - if aliveness.timestamp.Add(PingTimeout).Before(now) { - log.Println(c, "ping timeout") - c.conn.Close() + c.Close() continue } - if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) { + if c.sendTimestamp.Add(PingThreshold).Before(now) { if c.registered { - c.Msg("PING :" + daemon.hostname) - aliveness.pingSent = true + c.Msg("PING :" + *hostname) + c.sendTimestamp = time.Now() } else { - log.Println(c, "ping timeout") - c.conn.Close() + if *verbose { + log.Println(c, "ping timeout") + } + c.Close() } } } - daemon.lastAlivenessCheck = now - } - - switch event.eventType { + clientsLock.RUnlock() + roomsLock.Lock() + for rn, r := range rooms { + if *statedir == "" && len(r.members) == 0 { + if *verbose { + log.Println(rn, "emptied room") + } + delete(rooms, rn) + close(r.events) + } + } + roomsLock.Unlock() + case EventTerm: + break EventsCycle case EventNew: - daemon.clients[client] = true - daemon.clientAliveness[client] = &ClientAlivenessState{pingSent: false, timestamp: now} + clientsLock.Lock() + clients[client] = struct{}{} + clientsLock.Unlock() case EventDel: - delete(daemon.clients, client) - delete(daemon.clientAliveness, client) - for _, roomSink := range daemon.roomSinks { - roomSink <- event + clientsLock.Lock() + delete(clients, client) + clientsLock.Unlock() + roomsLock.RLock() + for _, r := range rooms { + r.events <- e } + roomsLock.RUnlock() case EventMsg: - cols := strings.SplitN(event.text, " ", 2) - command := strings.ToUpper(cols[0]) - if daemon.Verbose { - log.Println(client, "command", command) + cols := strings.SplitN(e.text, " ", 2) + cmd := strings.ToUpper(cols[0]) + if *verbose { + log.Println(client, "command", cmd) } - if command == "QUIT" { - delete(daemon.clients, client) - delete(daemon.clientAliveness, client) - client.conn.Close() + if cmd == "QUIT" { + client.Close() + if *verbose { + log.Println(client, "quit") + } continue } if !client.registered { - daemon.ClientRegister(client, command, cols) + client.Register(cmd, cols) continue } - switch command { + if client != nil { + client.recvTimestamp = now + } + switch cmd { case "AWAY": - continue + if len(cols) == 1 { + client.away = "" + client.ReplyNicknamed("305", "You are no longer marked as being away") + continue + } + client.away = strings.TrimLeft(cols[1], ":") + client.ReplyNicknamed("306", "You have been marked as being away") case "JOIN": if len(cols) == 1 || len(cols[1]) < 1 { client.ReplyNotEnoughParameters("JOIN") continue } - daemon.HandlerJoin(client, cols[1]) + client.Join(cols[1]) case "LIST": - daemon.SendList(client, cols) + client.SendList(cols) case "LUSERS": - daemon.SendLusers(client) + client.SendLusers() case "MODE": if len(cols) == 1 || len(cols[1]) < 1 { client.ReplyNotEnoughParameters("MODE") @@ -331,50 +139,71 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { } 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") - } + client.Msg("221 " + client.nickname + " +w") + // client.ReplyNicknamed("501", "Unknown MODE flag") continue } room := cols[0] - r, found := daemon.rooms[room] + r, found := rooms[room] if !found { client.ReplyNoChannel(room) continue } if len(cols) == 1 { - daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""} + r.events <- ClientEvent{client, EventMode, ""} } else { - daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]} + r.events <- ClientEvent{client, EventMode, cols[1]} } case "MOTD": - go daemon.SendMotd(client) + client.SendMotd() + case "NAMES": + rs := make([]*Room, len(cols)) + roomsLock.RLock() + if len(cols) == 0 { + for _, r := range rooms { + rs = append(rs, r) + } + } else { + needed := make(map[string]struct{}, len(rs)) + for _, r := range cols { + needed[r] = struct{}{} + } + for rn, r := range rooms { + if _, found := needed[rn]; found { + rs = append(rs, r) + } + } + } + roomsLock.RUnlock() + for _, r := range rs { + r.SendNames(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 { + rs := strings.Split(cols[1], " ")[0] + roomsLock.RLock() + for _, room := range strings.Split(rs, ",") { + if r, found := rooms[room]; found { + r.events <- ClientEvent{client, EventDel, ""} + } else { client.ReplyNoChannel(room) - continue } - daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""} } + roomsLock.RUnlock() 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", *hostname, cols[1])) case "PONG": continue case "NOTICE", "PRIVMSG": if len(cols) == 1 { - client.ReplyNicknamed("411", "No recipient given ("+command+")") + client.ReplyNicknamed("411", "No recipient given ("+cmd+")") continue } cols = strings.SplitN(cols[1], " ", 2) @@ -382,30 +211,43 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { 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]) - c.Msg(msg) - break + roomsLock.RLock() + if r, found := rooms[target]; found { + r.events <- ClientEvent{ + client, + EventMsg, + cmd + " " + strings.TrimLeft(cols[1], ":"), + } + roomsLock.RUnlock() + continue + } + roomsLock.RUnlock() + var msg string + clientsLock.RLock() + for c := range clients { + if c.nickname != target { + continue + } + msg = fmt.Sprintf(":%s %s %s %s", client, cmd, c.nickname, cols[1]) + c.Msg(msg) + if c.away != "" { + client.ReplyNicknamed("301", c.nickname, c.away) } + break } + clientsLock.RUnlock() if msg != "" { continue } - r, found := daemon.rooms[target] - if !found { - client.ReplyNoNickChan(target) - } - daemon.roomSinks[r] <- ClientEvent{client, EventMsg, command + " " + strings.TrimLeft(cols[1], ":")} + client.ReplyNoNickChan(target) case "TOPIC": if len(cols) == 1 { client.ReplyNotEnoughParameters("TOPIC") continue } cols = strings.SplitN(cols[1], " ", 2) - r, found := daemon.rooms[cols[0]] + r, found := rooms[cols[0]] if !found { client.ReplyNoChannel(cols[0]) continue @@ -413,22 +255,20 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { var change string if len(cols) > 1 { change = cols[1] - } else { - change = "" } - daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change} + r.events <- ClientEvent{client, EventTopic, change} case "WHO": if len(cols) == 1 || len(cols[1]) < 1 { client.ReplyNotEnoughParameters("WHO") continue } room := strings.Split(cols[1], " ")[0] - r, found := daemon.rooms[room] - if !found { + r, found := rooms[room] + if found { + r.events <- ClientEvent{client, EventWho, ""} + } else { client.ReplyNoChannel(room) - continue } - daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""} case "WHOIS": if len(cols) == 1 || len(cols[1]) < 1 { client.ReplyNotEnoughParameters("WHOIS") @@ -436,14 +276,99 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { } cols := strings.Split(cols[1], " ") nicknames := strings.Split(cols[len(cols)-1], ",") - daemon.SendWhois(client, nicknames) + client.SendWhois(nicknames) + case "ISON": + if len(cols) == 1 || len(cols[1]) < 1 { + client.ReplyNotEnoughParameters("ISON") + continue + } + nicknamesList := strings.Split(cols[1], " ") + nicknames := make(map[string]bool, len(nicknamesList)) + for _, nickname := range nicknamesList { + nicknames[nickname] = false + } + clientsLock.RLock() + for c := range clients { + if _, exists := nicknames[c.nickname]; exists { + nicknames[c.nickname] = true + } + } + clientsLock.RUnlock() + nicknamesList = nicknamesList[:0] + for n, exists := range nicknames { + if exists { + nicknamesList = append(nicknamesList, n) + } + } + client.ReplyNicknamed("303", strings.Join(nicknamesList, " ")) + case "WALLOPS": + if len(cols) == 1 { + client.ReplyNotEnoughParameters("WALLOPS") + continue + } + cs := make([]*Client, 0, len(clients)) + clientsLock.RLock() + for c := range clients { + if c != client { + cs = append(cs, c) + } + } + clientsLock.RUnlock() + for _, c := range cs { + c.Msg(fmt.Sprintf(":%s NOTICE %s %s", client, c.nickname, cols[1])) + } + case "VERSION": + var debug string + if *verbose { + debug = "debug" + } + client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", Version, debug, *hostname)) default: - client.ReplyNicknamed("421", command, "Unknown command") + client.ReplyNicknamed("421", cmd, "Unknown command") } } - if aliveness, alive := daemon.clientAliveness[client]; alive { - aliveness.timestamp = now - aliveness.pingSent = false + } + ticker.Stop() + + // Notify all clients about shutdown + clientsLock.RLock() + for c := range clients { + c.Msg(fmt.Sprintf( + ":%s NOTICE %s %s", *hostname, c.nickname, + ":Server is shutting down", + )) + c.Close() + } + clientsLock.RUnlock() + + // Read their EventDel + go func() { + for range events { } + }() + + // Stop room processors + roomsLock.RLock() + for _, r := range rooms { + r.events <- ClientEvent{eventType: EventTerm} + } + roomsLock.RUnlock() + roomsWG.Wait() + + // Wait for either 5sec or all clients quitting + t := time.NewTimer(5 * time.Second) + clientsDone := make(chan struct{}) + go func() { + clientsWG.Wait() + close(clientsDone) + }() + select { + case <-t.C: + case <-clientsDone: + } + if !t.Stop() { + <-t.C } + close(events) + close(finished) }