]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
Fix several races
[goircd.git] / daemon.go
1 /*
2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18 package main
19
20 import (
21         "fmt"
22         "io/ioutil"
23         "log"
24         "net"
25         "regexp"
26         "sort"
27         "strings"
28         "time"
29 )
30
31 const (
32         PING_TIMEOUT    = time.Second * 180 // Max time deadline for client's unresponsiveness
33         PING_THRESHOLD  = time.Second * 90  // Max idle client's time before PING are sent
34         ALIVENESS_CHECK = time.Second * 10  // Client's aliveness check period
35 )
36
37 var (
38         RE_NICKNAME = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
39 )
40
41 type Daemon struct {
42         Verbose              bool
43         hostname             string
44         motd                 string
45         clients              map[*Client]bool
46         client_aliveness     map[*Client]*ClientAlivenessState
47         rooms                map[string]*Room
48         room_sinks           map[*Room]chan ClientEvent
49         last_aliveness_check time.Time
50         log_sink             chan<- LogEvent
51         state_sink           chan<- StateEvent
52 }
53
54 func NewDaemon(hostname, motd string, log_sink chan<- LogEvent, state_sink chan<- StateEvent) *Daemon {
55         daemon := Daemon{hostname: hostname, motd: motd}
56         daemon.clients = make(map[*Client]bool)
57         daemon.client_aliveness = make(map[*Client]*ClientAlivenessState)
58         daemon.rooms = make(map[string]*Room)
59         daemon.room_sinks = make(map[*Room]chan ClientEvent)
60         daemon.log_sink = log_sink
61         daemon.state_sink = state_sink
62         return &daemon
63 }
64
65 func (daemon *Daemon) SendLusers(client *Client) {
66         lusers := 0
67         for client := range daemon.clients {
68                 if client.registered {
69                         lusers++
70                 }
71         }
72         client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
73 }
74
75 func (daemon *Daemon) SendMotd(client *Client) {
76         if len(daemon.motd) == 0 {
77                 client.ReplyNicknamed("422", "MOTD File is missing")
78                 return
79         }
80
81         motd, err := ioutil.ReadFile(daemon.motd)
82         if err != nil {
83                 log.Printf("Can not read motd file %s: %v", daemon.motd, err)
84                 client.ReplyNicknamed("422", "Error reading MOTD File")
85                 return
86         }
87
88         client.ReplyNicknamed("375", "- "+daemon.hostname+" Message of the day -")
89         for _, s := range strings.Split(strings.Trim(string(motd), "\n"), "\n") {
90                 client.ReplyNicknamed("372", "- "+string(s))
91         }
92         client.ReplyNicknamed("376", "End of /MOTD command")
93 }
94
95 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
96         for _, nickname := range nicknames {
97                 nickname = strings.ToLower(nickname)
98                 found := false
99                 for c := range daemon.clients {
100                         if strings.ToLower(c.nickname) != nickname {
101                                 continue
102                         }
103                         found = true
104                         h := c.conn.RemoteAddr().String()
105                         h, _, err := net.SplitHostPort(h)
106                         if err != nil {
107                                 log.Printf("Can't parse RemoteAddr %q: %v", h, err)
108                                 h = "Unknown"
109                         }
110                         client.ReplyNicknamed("311", c.nickname, c.username, h, "*", c.realname)
111                         client.ReplyNicknamed("312", c.nickname, daemon.hostname, daemon.hostname)
112                         subscriptions := []string{}
113                         for _, room := range daemon.rooms {
114                                 for subscriber := range room.members {
115                                         if subscriber.nickname == nickname {
116                                                 subscriptions = append(subscriptions, room.name)
117                                         }
118                                 }
119                         }
120                         sort.Strings(subscriptions)
121                         client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
122                         client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
123                 }
124                 if !found {
125                         client.ReplyNoNickChan(nickname)
126                 }
127         }
128 }
129
130 func (daemon *Daemon) SendList(client *Client, cols []string) {
131         var rooms []string
132         if (len(cols) > 1) && (cols[1] != "") {
133                 rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
134         } else {
135                 rooms = []string{}
136                 for room := range daemon.rooms {
137                         rooms = append(rooms, room)
138                 }
139         }
140         sort.Strings(rooms)
141         for _, room := range rooms {
142                 r, found := daemon.rooms[room]
143                 if found {
144                         client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
145                 }
146         }
147         client.ReplyNicknamed("323", "End of /LIST")
148 }
149
150 // Unregistered client workflow processor. Unregistered client:
151 // * is not PINGed
152 // * only QUIT, NICK and USER commands are processed
153 // * other commands are quietly ignored
154 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
155 func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
156         switch command {
157         case "NICK":
158                 if len(cols) == 1 || len(cols[1]) < 1 {
159                         client.ReplyParts("431", "No nickname given")
160                         return
161                 }
162                 nickname := cols[1]
163                 for existing_client := range daemon.clients {
164                         if existing_client.nickname == nickname {
165                                 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
166                                 return
167                         }
168                 }
169                 if !RE_NICKNAME.MatchString(nickname) {
170                         client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
171                         return
172                 }
173                 client.nickname = nickname
174         case "USER":
175                 if len(cols) == 1 {
176                         client.ReplyNotEnoughParameters("USER")
177                         return
178                 }
179                 args := strings.SplitN(cols[1], " ", 4)
180                 if len(args) < 4 {
181                         client.ReplyNotEnoughParameters("USER")
182                         return
183                 }
184                 client.username = args[0]
185                 client.realname = strings.TrimLeft(args[3], ":")
186         }
187         if client.nickname != "*" && client.username != "" {
188                 client.registered = true
189                 client.ReplyNicknamed("001", "Hi, welcome to IRC")
190                 client.ReplyNicknamed("002", "Your host is "+daemon.hostname+", running goircd")
191                 client.ReplyNicknamed("003", "This server was created sometime")
192                 client.ReplyNicknamed("004", daemon.hostname+" goircd o o")
193                 daemon.SendLusers(client)
194                 daemon.SendMotd(client)
195         }
196 }
197
198 // Register new room in Daemon. Create an object, events sink, save pointers
199 // to corresponding daemon's places and start room's processor goroutine.
200 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
201         room_new := NewRoom(daemon.hostname, name, daemon.log_sink, daemon.state_sink)
202         room_new.Verbose = daemon.Verbose
203         room_sink := make(chan ClientEvent)
204         daemon.rooms[name] = room_new
205         daemon.room_sinks[room_new] = room_sink
206         go room_new.Processor(room_sink)
207         return room_new, room_sink
208 }
209
210 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
211         args := strings.Split(cmd, " ")
212         rooms := strings.Split(args[0], ",")
213         var keys []string
214         if len(args) > 1 {
215                 keys = strings.Split(args[1], ",")
216         } else {
217                 keys = []string{}
218         }
219         for n, room := range rooms {
220                 if !RoomNameValid(room) {
221                         client.ReplyNoChannel(room)
222                         continue
223                 }
224                 var key string
225                 if (n < len(keys)) && (keys[n] != "") {
226                         key = keys[n]
227                 } else {
228                         key = ""
229                 }
230                 denied := false
231                 joined := false
232                 for room_existing, room_sink := range daemon.room_sinks {
233                         if room == room_existing.name {
234                                 if (room_existing.key != "") && (room_existing.key != key) {
235                                         denied = true
236                                 } else {
237                                         room_sink <- ClientEvent{client, EVENT_NEW, ""}
238                                         joined = true
239                                 }
240                                 break
241                         }
242                 }
243                 if denied {
244                         client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
245                 }
246                 if denied || joined {
247                         continue
248                 }
249                 room_new, room_sink := daemon.RoomRegister(room)
250                 if key != "" {
251                         room_new.key = key
252                         room_new.StateSave()
253                 }
254                 room_sink <- ClientEvent{client, EVENT_NEW, ""}
255         }
256 }
257
258 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
259         for event := range events {
260                 now := time.Now()
261                 client := event.client
262
263                 // Check for clients aliveness
264                 if daemon.last_aliveness_check.Add(ALIVENESS_CHECK).Before(now) {
265                         for c := range daemon.clients {
266                                 aliveness, alive := daemon.client_aliveness[c]
267                                 if !alive {
268                                         continue
269                                 }
270                                 if aliveness.timestamp.Add(PING_TIMEOUT).Before(now) {
271                                         log.Println(c, "ping timeout")
272                                         c.conn.Close()
273                                         continue
274                                 }
275                                 if !aliveness.ping_sent && aliveness.timestamp.Add(PING_THRESHOLD).Before(now) {
276                                         if c.registered {
277                                                 c.Msg("PING :" + daemon.hostname)
278                                                 aliveness.ping_sent = true
279                                         } else {
280                                                 log.Println(c, "ping timeout")
281                                                 c.conn.Close()
282                                         }
283                                 }
284                         }
285                         daemon.last_aliveness_check = now
286                 }
287
288                 switch event.event_type {
289                 case EVENT_NEW:
290                         daemon.clients[client] = true
291                         daemon.client_aliveness[client] = &ClientAlivenessState{ping_sent: false, timestamp: now}
292                 case EVENT_DEL:
293                         delete(daemon.clients, client)
294                         delete(daemon.client_aliveness, client)
295                         for _, room_sink := range daemon.room_sinks {
296                                 room_sink <- event
297                         }
298                 case EVENT_MSG:
299                         cols := strings.SplitN(event.text, " ", 2)
300                         command := strings.ToUpper(cols[0])
301                         if daemon.Verbose {
302                                 log.Println(client, "command", command)
303                         }
304                         if command == "QUIT" {
305                                 delete(daemon.clients, client)
306                                 delete(daemon.client_aliveness, client)
307                                 client.conn.Close()
308                                 continue
309                         }
310                         if !client.registered {
311                                 daemon.ClientRegister(client, command, cols)
312                                 continue
313                         }
314                         switch command {
315                         case "AWAY":
316                                 continue
317                         case "JOIN":
318                                 if len(cols) == 1 || len(cols[1]) < 1 {
319                                         client.ReplyNotEnoughParameters("JOIN")
320                                         continue
321                                 }
322                                 daemon.HandlerJoin(client, cols[1])
323                         case "LIST":
324                                 daemon.SendList(client, cols)
325                         case "LUSERS":
326                                 go daemon.SendLusers(client)
327                         case "MODE":
328                                 if len(cols) == 1 || len(cols[1]) < 1 {
329                                         client.ReplyNotEnoughParameters("MODE")
330                                         continue
331                                 }
332                                 cols = strings.SplitN(cols[1], " ", 2)
333                                 if cols[0] == client.username {
334                                         if len(cols) == 1 {
335                                                 client.Msg("221 " + client.nickname + " +")
336                                         } else {
337                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
338                                         }
339                                         continue
340                                 }
341                                 room := cols[0]
342                                 r, found := daemon.rooms[room]
343                                 if !found {
344                                         client.ReplyNoChannel(room)
345                                         continue
346                                 }
347                                 if len(cols) == 1 {
348                                         daemon.room_sinks[r] <- ClientEvent{client, EVENT_MODE, ""}
349                                 } else {
350                                         daemon.room_sinks[r] <- ClientEvent{client, EVENT_MODE, cols[1]}
351                                 }
352                         case "MOTD":
353                                 go daemon.SendMotd(client)
354                         case "PART":
355                                 if len(cols) == 1 || len(cols[1]) < 1 {
356                                         client.ReplyNotEnoughParameters("PART")
357                                         continue
358                                 }
359                                 for _, room := range strings.Split(cols[1], ",") {
360                                         r, found := daemon.rooms[room]
361                                         if !found {
362                                                 client.ReplyNoChannel(room)
363                                                 continue
364                                         }
365                                         daemon.room_sinks[r] <- ClientEvent{client, EVENT_DEL, ""}
366                                 }
367                         case "PING":
368                                 if len(cols) == 1 {
369                                         client.ReplyNicknamed("409", "No origin specified")
370                                         continue
371                                 }
372                                 client.Reply(fmt.Sprintf("PONG %s :%s", daemon.hostname, cols[1]))
373                         case "PONG":
374                                 continue
375                         case "NOTICE", "PRIVMSG":
376                                 if len(cols) == 1 {
377                                         client.ReplyNicknamed("411", "No recipient given ("+command+")")
378                                         continue
379                                 }
380                                 cols = strings.SplitN(cols[1], " ", 2)
381                                 if len(cols) == 1 {
382                                         client.ReplyNicknamed("412", "No text to send")
383                                         continue
384                                 }
385                                 msg := ""
386                                 target := strings.ToLower(cols[0])
387                                 for c := range daemon.clients {
388                                         if c.nickname == target {
389                                                 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
390                                                 c.Msg(msg)
391                                                 break
392                                         }
393                                 }
394                                 if msg != "" {
395                                         continue
396                                 }
397                                 r, found := daemon.rooms[target]
398                                 if !found {
399                                         client.ReplyNoNickChan(target)
400                                 }
401                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_MSG, command + " " + strings.TrimLeft(cols[1], ":")}
402                         case "TOPIC":
403                                 if len(cols) == 1 {
404                                         client.ReplyNotEnoughParameters("TOPIC")
405                                         continue
406                                 }
407                                 cols = strings.SplitN(cols[1], " ", 2)
408                                 r, found := daemon.rooms[cols[0]]
409                                 if !found {
410                                         client.ReplyNoChannel(cols[0])
411                                         continue
412                                 }
413                                 var change string
414                                 if len(cols) > 1 {
415                                         change = cols[1]
416                                 } else {
417                                         change = ""
418                                 }
419                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_TOPIC, change}
420                         case "WHO":
421                                 if len(cols) == 1 || len(cols[1]) < 1 {
422                                         client.ReplyNotEnoughParameters("WHO")
423                                         continue
424                                 }
425                                 room := strings.Split(cols[1], " ")[0]
426                                 r, found := daemon.rooms[room]
427                                 if !found {
428                                         client.ReplyNoChannel(room)
429                                         continue
430                                 }
431                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_WHO, ""}
432                         case "WHOIS":
433                                 if len(cols) == 1 || len(cols[1]) < 1 {
434                                         client.ReplyNotEnoughParameters("WHOIS")
435                                         continue
436                                 }
437                                 cols := strings.Split(cols[1], " ")
438                                 nicknames := strings.Split(cols[len(cols)-1], ",")
439                                 go daemon.SendWhois(client, nicknames)
440                         default:
441                                 client.ReplyNicknamed("421", command, "Unknown command")
442                         }
443                 }
444                 if aliveness, alive := daemon.client_aliveness[client]; alive {
445                         aliveness.timestamp = now
446                         aliveness.ping_sent = false
447                 }
448         }
449 }