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