]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
ed708de9875a7b054f27e5a27bfad6e122ad90d3
[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                         if c.away != nil {
115                                 client.ReplyNicknamed("301", c.nickname, *c.away)
116                         }
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                 if daemon.passwords != nil && *daemon.passwords != "" {
200                         if client.password == "" {
201                                 client.ReplyParts("462", "You may not register")
202                                 client.conn.Close()
203                                 return
204                         }
205                         contents, err := ioutil.ReadFile(*daemon.passwords)
206                         if err != nil {
207                                 log.Fatalf("Can no read passwords file %s: %s", *daemon.passwords, err)
208                                 return
209                         }
210                         for _, entry := range strings.Split(string(contents), "\n") {
211                                 if entry == "" {
212                                         continue
213                                 }
214                                 if lp := strings.Split(entry, ":"); lp[0] == client.nickname && lp[1] != client.password {
215                                         client.ReplyParts("462", "You may not register")
216                                         client.conn.Close()
217                                         return
218                                 }
219                         }
220                 }
221
222                 client.registered = true
223                 client.ReplyNicknamed("001", "Hi, welcome to IRC")
224                 client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
225                 client.ReplyNicknamed("003", "This server was created sometime")
226                 client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
227                 daemon.SendLusers(client)
228                 daemon.SendMotd(client)
229                 log.Println(client, "logged in")
230         }
231 }
232
233 // Register new room in Daemon. Create an object, events sink, save pointers
234 // to corresponding daemon's places and start room's processor goroutine.
235 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
236         roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
237         roomNew.Verbose = daemon.Verbose
238         roomSink := make(chan ClientEvent)
239         daemon.rooms[name] = roomNew
240         daemon.roomSinks[roomNew] = roomSink
241         go roomNew.Processor(roomSink)
242         return roomNew, roomSink
243 }
244
245 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
246         args := strings.Split(cmd, " ")
247         rooms := strings.Split(args[0], ",")
248         var keys []string
249         if len(args) > 1 {
250                 keys = strings.Split(args[1], ",")
251         } else {
252                 keys = []string{}
253         }
254         for n, room := range rooms {
255                 if !RoomNameValid(room) {
256                         client.ReplyNoChannel(room)
257                         continue
258                 }
259                 var key string
260                 if (n < len(keys)) && (keys[n] != "") {
261                         key = keys[n]
262                 } else {
263                         key = ""
264                 }
265                 denied := false
266                 joined := false
267                 for roomExisting, roomSink := range daemon.roomSinks {
268                         if room == roomExisting.name {
269                                 if (roomExisting.key != "") && (roomExisting.key != key) {
270                                         denied = true
271                                 } else {
272                                         roomSink <- ClientEvent{client, EventNew, ""}
273                                         joined = true
274                                 }
275                                 break
276                         }
277                 }
278                 if denied {
279                         client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
280                 }
281                 if denied || joined {
282                         continue
283                 }
284                 roomNew, roomSink := daemon.RoomRegister(room)
285                 log.Println("Room", roomNew, "created")
286                 if key != "" {
287                         roomNew.key = key
288                         roomNew.StateSave()
289                 }
290                 roomSink <- ClientEvent{client, EventNew, ""}
291         }
292 }
293
294 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
295         for event := range events {
296                 now := time.Now()
297                 client := event.client
298
299                 // Check for clients aliveness
300                 if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
301                         for c := range daemon.clients {
302                                 aliveness, alive := daemon.clientAliveness[c]
303                                 if !alive {
304                                         continue
305                                 }
306                                 if aliveness.timestamp.Add(PingTimeout).Before(now) {
307                                         log.Println(c, "ping timeout")
308                                         c.conn.Close()
309                                         continue
310                                 }
311                                 if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
312                                         if c.registered {
313                                                 c.Msg("PING :" + *daemon.hostname)
314                                                 aliveness.pingSent = true
315                                         } else {
316                                                 log.Println(c, "ping timeout")
317                                                 c.conn.Close()
318                                         }
319                                 }
320                         }
321                         daemon.lastAlivenessCheck = now
322                 }
323
324                 switch event.eventType {
325                 case EventNew:
326                         daemon.clients[client] = true
327                         daemon.clientAliveness[client] = &ClientAlivenessState{pingSent: false, timestamp: now}
328                 case EventDel:
329                         delete(daemon.clients, client)
330                         delete(daemon.clientAliveness, client)
331                         for _, roomSink := range daemon.roomSinks {
332                                 roomSink <- event
333                         }
334                 case EventMsg:
335                         cols := strings.SplitN(event.text, " ", 2)
336                         command := strings.ToUpper(cols[0])
337                         if daemon.Verbose {
338                                 log.Println(client, "command", command)
339                         }
340                         if command == "QUIT" {
341                                 log.Println(client, "quit")
342                                 delete(daemon.clients, client)
343                                 delete(daemon.clientAliveness, client)
344                                 client.conn.Close()
345                                 continue
346                         }
347                         if !client.registered {
348                                 daemon.ClientRegister(client, command, cols)
349                                 continue
350                         }
351                         switch command {
352                         case "AWAY":
353                                 if len(cols) == 1 {
354                                         client.away = nil
355                                         client.ReplyNicknamed("305", "You are no longer marked as being away")
356                                         continue
357                                 }
358                                 msg := strings.TrimLeft(cols[1], ":")
359                                 client.away = &msg
360                                 client.ReplyNicknamed("306", "You have been marked as being away")
361                         case "JOIN":
362                                 if len(cols) == 1 || len(cols[1]) < 1 {
363                                         client.ReplyNotEnoughParameters("JOIN")
364                                         continue
365                                 }
366                                 daemon.HandlerJoin(client, cols[1])
367                         case "LIST":
368                                 daemon.SendList(client, cols)
369                         case "LUSERS":
370                                 daemon.SendLusers(client)
371                         case "MODE":
372                                 if len(cols) == 1 || len(cols[1]) < 1 {
373                                         client.ReplyNotEnoughParameters("MODE")
374                                         continue
375                                 }
376                                 cols = strings.SplitN(cols[1], " ", 2)
377                                 if cols[0] == client.username {
378                                         if len(cols) == 1 {
379                                                 client.Msg("221 " + client.nickname + " +")
380                                         } else {
381                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
382                                         }
383                                         continue
384                                 }
385                                 room := cols[0]
386                                 r, found := daemon.rooms[room]
387                                 if !found {
388                                         client.ReplyNoChannel(room)
389                                         continue
390                                 }
391                                 if len(cols) == 1 {
392                                         daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
393                                 } else {
394                                         daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
395                                 }
396                         case "MOTD":
397                                 go daemon.SendMotd(client)
398                         case "PART":
399                                 if len(cols) == 1 || len(cols[1]) < 1 {
400                                         client.ReplyNotEnoughParameters("PART")
401                                         continue
402                                 }
403                                 for _, room := range strings.Split(cols[1], ",") {
404                                         r, found := daemon.rooms[room]
405                                         if !found {
406                                                 client.ReplyNoChannel(room)
407                                                 continue
408                                         }
409                                         daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
410                                 }
411                         case "PING":
412                                 if len(cols) == 1 {
413                                         client.ReplyNicknamed("409", "No origin specified")
414                                         continue
415                                 }
416                                 client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
417                         case "PONG":
418                                 continue
419                         case "NOTICE", "PRIVMSG":
420                                 if len(cols) == 1 {
421                                         client.ReplyNicknamed("411", "No recipient given ("+command+")")
422                                         continue
423                                 }
424                                 cols = strings.SplitN(cols[1], " ", 2)
425                                 if len(cols) == 1 {
426                                         client.ReplyNicknamed("412", "No text to send")
427                                         continue
428                                 }
429                                 msg := ""
430                                 target := strings.ToLower(cols[0])
431                                 for c := range daemon.clients {
432                                         if c.nickname == target {
433                                                 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
434                                                 c.Msg(msg)
435                                                 if c.away != nil {
436                                                         client.ReplyNicknamed("301", c.nickname, *c.away)
437                                                 }
438                                                 break
439                                         }
440                                 }
441                                 if msg != "" {
442                                         continue
443                                 }
444                                 r, found := daemon.rooms[target]
445                                 if !found {
446                                         client.ReplyNoNickChan(target)
447                                 }
448                                 daemon.roomSinks[r] <- ClientEvent{client, EventMsg, command + " " + strings.TrimLeft(cols[1], ":")}
449                         case "TOPIC":
450                                 if len(cols) == 1 {
451                                         client.ReplyNotEnoughParameters("TOPIC")
452                                         continue
453                                 }
454                                 cols = strings.SplitN(cols[1], " ", 2)
455                                 r, found := daemon.rooms[cols[0]]
456                                 if !found {
457                                         client.ReplyNoChannel(cols[0])
458                                         continue
459                                 }
460                                 var change string
461                                 if len(cols) > 1 {
462                                         change = cols[1]
463                                 } else {
464                                         change = ""
465                                 }
466                                 daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
467                         case "WHO":
468                                 if len(cols) == 1 || len(cols[1]) < 1 {
469                                         client.ReplyNotEnoughParameters("WHO")
470                                         continue
471                                 }
472                                 room := strings.Split(cols[1], " ")[0]
473                                 r, found := daemon.rooms[room]
474                                 if !found {
475                                         client.ReplyNoChannel(room)
476                                         continue
477                                 }
478                                 daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
479                         case "WHOIS":
480                                 if len(cols) == 1 || len(cols[1]) < 1 {
481                                         client.ReplyNotEnoughParameters("WHOIS")
482                                         continue
483                                 }
484                                 cols := strings.Split(cols[1], " ")
485                                 nicknames := strings.Split(cols[len(cols)-1], ",")
486                                 daemon.SendWhois(client, nicknames)
487                         case "VERSION":
488                                 var debug string
489                                 if daemon.Verbose {
490                                         debug = "debug"
491                                 } else {
492                                         debug = ""
493                                 }
494                                 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
495                         default:
496                                 client.ReplyNicknamed("421", command, "Unknown command")
497                         }
498                 }
499                 if aliveness, alive := daemon.clientAliveness[client]; alive {
500                         aliveness.timestamp = now
501                         aliveness.pingSent = false
502                 }
503         }
504 }