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