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