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