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