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