X-Git-Url: http://www.git.cypherpunks.ru/?p=goircd.git;a=blobdiff_plain;f=daemon.go;h=30d8c5ddc77a8e8980dcfa0a19e8d106e11ab4bb;hp=2cb215390b1ce0bcada4cd0f63d302834f40697f;hb=ad68cf29f652c5bfa7822a10000e9da658fbf1d5;hpb=54d2fcb9cbab1e5693b83b9c506bc0aca74dd90c diff --git a/daemon.go b/daemon.go index 2cb2153..30d8c5d 100644 --- a/daemon.go +++ b/daemon.go @@ -1,6 +1,6 @@ /* goircd -- minimalistic simple Internet Relay Chat (IRC) server -Copyright (C) 2014 Sergey Matveev +Copyright (C) 2014-2015 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 @@ -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 . */ + package main import ( - "bytes" "fmt" - "io" + "io/ioutil" "log" - "os" + "net" "regexp" "sort" "strings" @@ -30,33 +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 ( - 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 } @@ -71,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(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("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) { @@ -105,8 +112,17 @@ 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 { @@ -152,19 +168,27 @@ 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 := cols[1] - for client := range daemon.clients { - if client.nickname == nickname { + // 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 !RE_NICKNAME.MatchString(nickname) { + if !RENickname.MatchString(nickname) { client.ReplyParts("432", "*", cols[1], "Erroneous nickname") return } @@ -183,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 + 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) { @@ -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 @@ -243,75 +292,96 @@ func (daemon *Daemon) HandlerJoin(client *Client, cmd string) { 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") @@ -333,9 +403,9 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { 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) @@ -350,14 +420,14 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { 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,8 +444,11 @@ 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 } } @@ -385,8 +458,13 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { 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") @@ -404,7 +482,7 @@ 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") @@ -416,7 +494,7 @@ func (daemon *Daemon) Processor(events <-chan ClientEvent) { 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 +502,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 + } } }