]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
Remove signal processor for password reloading and use pointers to strings
[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         PingTimeout    = time.Second * 180 // Max time deadline for client's unresponsiveness
33         PingThreshold  = time.Second * 90  // Max idle client's time before PING are sent
34         AlivenessCheck = time.Second * 10  // Client's aliveness check period
35 )
36
37 var (
38         RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
39 )
40
41 type Daemon struct {
42         Verbose            bool
43         version            string
44         hostname           *string
45         motd               *string
46         passwords          *string
47         clients            map[*Client]bool
48         clientAliveness    map[*Client]*ClientAlivenessState
49         rooms              map[string]*Room
50         roomSinks          map[*Room]chan ClientEvent
51         lastAlivenessCheck time.Time
52         logSink            chan<- LogEvent
53         stateSink          chan<- StateEvent
54 }
55
56 func NewDaemon(version string, hostname, motd, passwords *string, logSink chan<- LogEvent, stateSink chan<- StateEvent) *Daemon {
57         daemon := Daemon{version: version, hostname: hostname, motd: motd, passwords: passwords}
58         daemon.clients = make(map[*Client]bool)
59         daemon.clientAliveness = make(map[*Client]*ClientAlivenessState)
60         daemon.rooms = make(map[string]*Room)
61         daemon.roomSinks = make(map[*Room]chan ClientEvent)
62         daemon.logSink = logSink
63         daemon.stateSink = stateSink
64         return &daemon
65 }
66
67 func (daemon *Daemon) SendLusers(client *Client) {
68         lusers := 0
69         for client := range daemon.clients {
70                 if client.registered {
71                         lusers++
72                 }
73         }
74         client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
75 }
76
77 func (daemon *Daemon) SendMotd(client *Client) {
78         if daemon.motd == nil || *daemon.motd == "" {
79                 client.ReplyNicknamed("422", "MOTD File is missing")
80                 return
81         }
82
83         motd, err := ioutil.ReadFile(*daemon.motd)
84         if err != nil {
85                 log.Printf("Can not read motd file %s: %v", *daemon.motd, err)
86                 client.ReplyNicknamed("422", "Error reading MOTD File")
87                 return
88         }
89
90         client.ReplyNicknamed("375", "- "+*daemon.hostname+" Message of the day -")
91         for _, s := range strings.Split(strings.Trim(string(motd), "\n"), "\n") {
92                 client.ReplyNicknamed("372", "- "+string(s))
93         }
94         client.ReplyNicknamed("376", "End of /MOTD command")
95 }
96
97 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
98         for _, nickname := range nicknames {
99                 nickname = strings.ToLower(nickname)
100                 found := false
101                 for c := range daemon.clients {
102                         if strings.ToLower(c.nickname) != nickname {
103                                 continue
104                         }
105                         found = true
106                         h := c.conn.RemoteAddr().String()
107                         h, _, err := net.SplitHostPort(h)
108                         if err != nil {
109                                 log.Printf("Can't parse RemoteAddr %q: %v", h, err)
110                                 h = "Unknown"
111                         }
112                         client.ReplyNicknamed("311", c.nickname, c.username, h, "*", c.realname)
113                         client.ReplyNicknamed("312", c.nickname, *daemon.hostname, *daemon.hostname)
114                         subscriptions := []string{}
115                         for _, room := range daemon.rooms {
116                                 for subscriber := range room.members {
117                                         if subscriber.nickname == nickname {
118                                                 subscriptions = append(subscriptions, room.name)
119                                         }
120                                 }
121                         }
122                         sort.Strings(subscriptions)
123                         client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
124                         client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
125                 }
126                 if !found {
127                         client.ReplyNoNickChan(nickname)
128                 }
129         }
130 }
131
132 func (daemon *Daemon) SendList(client *Client, cols []string) {
133         var rooms []string
134         if (len(cols) > 1) && (cols[1] != "") {
135                 rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
136         } else {
137                 rooms = []string{}
138                 for room := range daemon.rooms {
139                         rooms = append(rooms, room)
140                 }
141         }
142         sort.Strings(rooms)
143         for _, room := range rooms {
144                 r, found := daemon.rooms[room]
145                 if found {
146                         client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
147                 }
148         }
149         client.ReplyNicknamed("323", "End of /LIST")
150 }
151
152 // Unregistered client workflow processor. Unregistered client:
153 // * is not PINGed
154 // * only QUIT, NICK and USER commands are processed
155 // * other commands are quietly ignored
156 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
157 func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
158         switch command {
159         case "PASS":
160                 if len(cols) == 1 || len(cols[1]) < 1 {
161                         client.ReplyNotEnoughParameters("PASS")
162                         return
163                 }
164                 client.password = cols[1]
165         case "NICK":
166                 if len(cols) == 1 || len(cols[1]) < 1 {
167                         client.ReplyParts("431", "No nickname given")
168                         return
169                 }
170                 nickname := cols[1]
171                 for existingClient := range daemon.clients {
172                         if existingClient.nickname == nickname {
173                                 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
174                                 return
175                         }
176                 }
177                 if !RENickname.MatchString(nickname) {
178                         client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
179                         return
180                 }
181                 client.nickname = nickname
182         case "USER":
183                 if len(cols) == 1 {
184                         client.ReplyNotEnoughParameters("USER")
185                         return
186                 }
187                 args := strings.SplitN(cols[1], " ", 4)
188                 if len(args) < 4 {
189                         client.ReplyNotEnoughParameters("USER")
190                         return
191                 }
192                 client.username = args[0]
193                 client.realname = strings.TrimLeft(args[3], ":")
194         }
195         if client.nickname != "*" && client.username != "" {
196                 if daemon.passwords != nil && *daemon.passwords != "" {
197                         if client.password == "" {
198                                 client.ReplyParts("462", "You may not register")
199                                 client.conn.Close()
200                                 return
201                         }
202                         contents, err := ioutil.ReadFile(*daemon.passwords)
203                         if err != nil {
204                                 log.Fatalf("Can no read passwords file %s: %s", *daemon.passwords, err)
205                                 return
206                         }
207                         for _, entry := range strings.Split(string(contents), "\n") {
208                                 if entry == "" {
209                                         continue
210                                 }
211                                 if lp := strings.Split(entry, ":"); lp[0] == client.nickname && lp[1] != client.password {
212                                         client.ReplyParts("462", "You may not register")
213                                         client.conn.Close()
214                                         return
215                                 }
216                         }
217                 }
218
219                 client.registered = true
220                 client.ReplyNicknamed("001", "Hi, welcome to IRC")
221                 client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
222                 client.ReplyNicknamed("003", "This server was created sometime")
223                 client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
224                 daemon.SendLusers(client)
225                 daemon.SendMotd(client)
226                 log.Println(client, "logged in")
227         }
228 }
229
230 // Register new room in Daemon. Create an object, events sink, save pointers
231 // to corresponding daemon's places and start room's processor goroutine.
232 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
233         roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
234         roomNew.Verbose = daemon.Verbose
235         roomSink := make(chan ClientEvent)
236         daemon.rooms[name] = roomNew
237         daemon.roomSinks[roomNew] = roomSink
238         go roomNew.Processor(roomSink)
239         return roomNew, roomSink
240 }
241
242 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
243         args := strings.Split(cmd, " ")
244         rooms := strings.Split(args[0], ",")
245         var keys []string
246         if len(args) > 1 {
247                 keys = strings.Split(args[1], ",")
248         } else {
249                 keys = []string{}
250         }
251         for n, room := range rooms {
252                 if !RoomNameValid(room) {
253                         client.ReplyNoChannel(room)
254                         continue
255                 }
256                 var key string
257                 if (n < len(keys)) && (keys[n] != "") {
258                         key = keys[n]
259                 } else {
260                         key = ""
261                 }
262                 denied := false
263                 joined := false
264                 for roomExisting, roomSink := range daemon.roomSinks {
265                         if room == roomExisting.name {
266                                 if (roomExisting.key != "") && (roomExisting.key != key) {
267                                         denied = true
268                                 } else {
269                                         roomSink <- ClientEvent{client, EventNew, ""}
270                                         joined = true
271                                 }
272                                 break
273                         }
274                 }
275                 if denied {
276                         client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
277                 }
278                 if denied || joined {
279                         continue
280                 }
281                 roomNew, roomSink := daemon.RoomRegister(room)
282                 log.Println("Room", roomNew, "created")
283                 if key != "" {
284                         roomNew.key = key
285                         roomNew.StateSave()
286                 }
287                 roomSink <- ClientEvent{client, EventNew, ""}
288         }
289 }
290
291 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
292         for event := range events {
293                 now := time.Now()
294                 client := event.client
295
296                 // Check for clients aliveness
297                 if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
298                         for c := range daemon.clients {
299                                 aliveness, alive := daemon.clientAliveness[c]
300                                 if !alive {
301                                         continue
302                                 }
303                                 if aliveness.timestamp.Add(PingTimeout).Before(now) {
304                                         log.Println(c, "ping timeout")
305                                         c.conn.Close()
306                                         continue
307                                 }
308                                 if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
309                                         if c.registered {
310                                                 c.Msg("PING :" + *daemon.hostname)
311                                                 aliveness.pingSent = true
312                                         } else {
313                                                 log.Println(c, "ping timeout")
314                                                 c.conn.Close()
315                                         }
316                                 }
317                         }
318                         daemon.lastAlivenessCheck = now
319                 }
320
321                 switch event.eventType {
322                 case EventNew:
323                         daemon.clients[client] = true
324                         daemon.clientAliveness[client] = &ClientAlivenessState{pingSent: false, timestamp: now}
325                 case EventDel:
326                         delete(daemon.clients, client)
327                         delete(daemon.clientAliveness, client)
328                         for _, roomSink := range daemon.roomSinks {
329                                 roomSink <- event
330                         }
331                 case EventMsg:
332                         cols := strings.SplitN(event.text, " ", 2)
333                         command := strings.ToUpper(cols[0])
334                         if daemon.Verbose {
335                                 log.Println(client, "command", command)
336                         }
337                         if command == "QUIT" {
338                                 log.Println(client, "quit")
339                                 delete(daemon.clients, client)
340                                 delete(daemon.clientAliveness, client)
341                                 client.conn.Close()
342                                 continue
343                         }
344                         if !client.registered {
345                                 daemon.ClientRegister(client, command, cols)
346                                 continue
347                         }
348                         switch command {
349                         case "AWAY":
350                                 continue
351                         case "JOIN":
352                                 if len(cols) == 1 || len(cols[1]) < 1 {
353                                         client.ReplyNotEnoughParameters("JOIN")
354                                         continue
355                                 }
356                                 daemon.HandlerJoin(client, cols[1])
357                         case "LIST":
358                                 daemon.SendList(client, cols)
359                         case "LUSERS":
360                                 daemon.SendLusers(client)
361                         case "MODE":
362                                 if len(cols) == 1 || len(cols[1]) < 1 {
363                                         client.ReplyNotEnoughParameters("MODE")
364                                         continue
365                                 }
366                                 cols = strings.SplitN(cols[1], " ", 2)
367                                 if cols[0] == client.username {
368                                         if len(cols) == 1 {
369                                                 client.Msg("221 " + client.nickname + " +")
370                                         } else {
371                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
372                                         }
373                                         continue
374                                 }
375                                 room := cols[0]
376                                 r, found := daemon.rooms[room]
377                                 if !found {
378                                         client.ReplyNoChannel(room)
379                                         continue
380                                 }
381                                 if len(cols) == 1 {
382                                         daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
383                                 } else {
384                                         daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
385                                 }
386                         case "MOTD":
387                                 go daemon.SendMotd(client)
388                         case "PART":
389                                 if len(cols) == 1 || len(cols[1]) < 1 {
390                                         client.ReplyNotEnoughParameters("PART")
391                                         continue
392                                 }
393                                 for _, room := range strings.Split(cols[1], ",") {
394                                         r, found := daemon.rooms[room]
395                                         if !found {
396                                                 client.ReplyNoChannel(room)
397                                                 continue
398                                         }
399                                         daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
400                                 }
401                         case "PING":
402                                 if len(cols) == 1 {
403                                         client.ReplyNicknamed("409", "No origin specified")
404                                         continue
405                                 }
406                                 client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
407                         case "PONG":
408                                 continue
409                         case "NOTICE", "PRIVMSG":
410                                 if len(cols) == 1 {
411                                         client.ReplyNicknamed("411", "No recipient given ("+command+")")
412                                         continue
413                                 }
414                                 cols = strings.SplitN(cols[1], " ", 2)
415                                 if len(cols) == 1 {
416                                         client.ReplyNicknamed("412", "No text to send")
417                                         continue
418                                 }
419                                 msg := ""
420                                 target := strings.ToLower(cols[0])
421                                 for c := range daemon.clients {
422                                         if c.nickname == target {
423                                                 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
424                                                 c.Msg(msg)
425                                                 break
426                                         }
427                                 }
428                                 if msg != "" {
429                                         continue
430                                 }
431                                 r, found := daemon.rooms[target]
432                                 if !found {
433                                         client.ReplyNoNickChan(target)
434                                 }
435                                 daemon.roomSinks[r] <- ClientEvent{client, EventMsg, command + " " + strings.TrimLeft(cols[1], ":")}
436                         case "TOPIC":
437                                 if len(cols) == 1 {
438                                         client.ReplyNotEnoughParameters("TOPIC")
439                                         continue
440                                 }
441                                 cols = strings.SplitN(cols[1], " ", 2)
442                                 r, found := daemon.rooms[cols[0]]
443                                 if !found {
444                                         client.ReplyNoChannel(cols[0])
445                                         continue
446                                 }
447                                 var change string
448                                 if len(cols) > 1 {
449                                         change = cols[1]
450                                 } else {
451                                         change = ""
452                                 }
453                                 daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
454                         case "WHO":
455                                 if len(cols) == 1 || len(cols[1]) < 1 {
456                                         client.ReplyNotEnoughParameters("WHO")
457                                         continue
458                                 }
459                                 room := strings.Split(cols[1], " ")[0]
460                                 r, found := daemon.rooms[room]
461                                 if !found {
462                                         client.ReplyNoChannel(room)
463                                         continue
464                                 }
465                                 daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
466                         case "WHOIS":
467                                 if len(cols) == 1 || len(cols[1]) < 1 {
468                                         client.ReplyNotEnoughParameters("WHOIS")
469                                         continue
470                                 }
471                                 cols := strings.Split(cols[1], " ")
472                                 nicknames := strings.Split(cols[len(cols)-1], ",")
473                                 daemon.SendWhois(client, nicknames)
474                         case "VERSION":
475                                 var debug string
476                                 if daemon.Verbose {
477                                         debug = "debug"
478                                 } else {
479                                         debug = ""
480                                 }
481                                 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
482                         default:
483                                 client.ReplyNicknamed("421", command, "Unknown command")
484                         }
485                 }
486                 if aliveness, alive := daemon.clientAliveness[client]; alive {
487                         aliveness.timestamp = now
488                         aliveness.pingSent = false
489                 }
490         }
491 }