]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
Decrease log verbosity.
[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         "bytes"
22         "fmt"
23         "io"
24         "log"
25         "os"
26         "regexp"
27         "sort"
28         "strings"
29         "time"
30 )
31
32 const (
33         PING_TIMEOUT    = time.Second * 180 // Max time deadline for client's unresponsiveness
34         PING_THRESHOLD  = time.Second * 90  // Max idle client's time before PING are sent
35         ALIVENESS_CHECK = time.Second * 10  // Client's aliveness check period
36 )
37
38 var (
39         RE_NICKNAME = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
40 )
41
42 type Daemon struct {
43         Verbose              bool
44         hostname             string
45         motd                 string
46         clients              map[*Client]bool
47         rooms                map[string]*Room
48         room_sinks           map[*Room]chan ClientEvent
49         last_aliveness_check time.Time
50         log_sink             chan<- LogEvent
51         state_sink           chan<- StateEvent
52 }
53
54 func NewDaemon(hostname, motd string, log_sink chan<- LogEvent, state_sink chan<- StateEvent) *Daemon {
55         daemon := Daemon{hostname: hostname, motd: motd}
56         daemon.clients = make(map[*Client]bool)
57         daemon.rooms = make(map[string]*Room)
58         daemon.room_sinks = make(map[*Room]chan ClientEvent)
59         daemon.log_sink = log_sink
60         daemon.state_sink = state_sink
61         return &daemon
62 }
63
64 func (daemon *Daemon) SendLusers(client *Client) {
65         lusers := 0
66         for client := range daemon.clients {
67                 if client.registered {
68                         lusers++
69                 }
70         }
71         client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
72 }
73
74 func (daemon *Daemon) SendMotd(client *Client) {
75         if daemon.motd != "" {
76                 fd, err := os.Open(daemon.motd)
77                 if err == nil {
78                         defer fd.Close()
79                         motd := []byte{}
80                         var err error
81                         for err != io.EOF {
82                                 buf := make([]byte, 1024)
83                                 _, err = fd.Read(buf)
84                                 motd = append(motd, bytes.TrimRight(buf, "\x00")...)
85                         }
86
87                         client.ReplyNicknamed("375", "- "+daemon.hostname+" Message of the day -")
88                         for _, s := range bytes.Split(bytes.TrimRight(motd, "\n"), []byte("\n")) {
89                                 client.ReplyNicknamed("372", "- "+string(s))
90                         }
91                         client.ReplyNicknamed("376", "End of /MOTD command")
92                         return
93                 } else {
94                         log.Println("Can not open motd file", daemon.motd, err)
95                 }
96         }
97         client.ReplyNicknamed("422", "MOTD File is missing")
98 }
99
100 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
101         for _, nickname := range nicknames {
102                 nickname = strings.ToLower(nickname)
103                 found := false
104                 for c := range daemon.clients {
105                         if strings.ToLower(c.nickname) != nickname {
106                                 continue
107                         }
108                         found = true
109                         client.ReplyNicknamed("311", c.nickname, c.username, c.conn.RemoteAddr().String(), "*", c.realname)
110                         client.ReplyNicknamed("312", c.nickname, daemon.hostname, daemon.hostname)
111                         subscriptions := []string{}
112                         for _, room := range daemon.rooms {
113                                 for subscriber := range room.members {
114                                         if subscriber.nickname == nickname {
115                                                 subscriptions = append(subscriptions, room.name)
116                                         }
117                                 }
118                         }
119                         sort.Strings(subscriptions)
120                         client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
121                         client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
122                 }
123                 if !found {
124                         client.ReplyNoNickChan(nickname)
125                 }
126         }
127 }
128
129 func (daemon *Daemon) SendList(client *Client, cols []string) {
130         var rooms []string
131         if (len(cols) > 1) && (cols[1] != "") {
132                 rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
133         } else {
134                 rooms = []string{}
135                 for room := range daemon.rooms {
136                         rooms = append(rooms, room)
137                 }
138         }
139         sort.Strings(rooms)
140         for _, room := range rooms {
141                 r, found := daemon.rooms[room]
142                 if found {
143                         client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
144                 }
145         }
146         client.ReplyNicknamed("323", "End of /LIST")
147 }
148
149 // Unregistered client workflow processor. Unregistered client:
150 // * is not PINGed
151 // * only QUIT, NICK and USER commands are processed
152 // * other commands are quietly ignored
153 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
154 func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
155         switch command {
156         case "NICK":
157                 if len(cols) == 1 || len(cols[1]) < 1 {
158                         client.ReplyParts("431", "No nickname given")
159                         return
160                 }
161                 nickname := cols[1]
162                 for client := range daemon.clients {
163                         if client.nickname == nickname {
164                                 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
165                                 return
166                         }
167                 }
168                 if !RE_NICKNAME.MatchString(nickname) {
169                         client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
170                         return
171                 }
172                 client.nickname = nickname
173         case "USER":
174                 if len(cols) == 1 {
175                         client.ReplyNotEnoughParameters("USER")
176                         return
177                 }
178                 args := strings.SplitN(cols[1], " ", 4)
179                 if len(args) < 4 {
180                         client.ReplyNotEnoughParameters("USER")
181                         return
182                 }
183                 client.username = args[0]
184                 client.realname = strings.TrimLeft(args[3], ":")
185         }
186         if client.nickname != "*" && client.username != "" {
187                 client.registered = true
188                 client.ReplyNicknamed("001", "Hi, welcome to IRC")
189                 client.ReplyNicknamed("002", "Your host is "+daemon.hostname+", running goircd")
190                 client.ReplyNicknamed("003", "This server was created sometime")
191                 client.ReplyNicknamed("004", daemon.hostname+" goircd o o")
192                 daemon.SendLusers(client)
193                 daemon.SendMotd(client)
194         }
195 }
196
197 // Register new room in Daemon. Create an object, events sink, save pointers
198 // to corresponding daemon's places and start room's processor goroutine.
199 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
200         room_new := NewRoom(daemon.hostname, name, daemon.log_sink, daemon.state_sink)
201         room_new.Verbose = daemon.Verbose
202         room_sink := make(chan ClientEvent)
203         daemon.rooms[name] = room_new
204         daemon.room_sinks[room_new] = room_sink
205         go room_new.Processor(room_sink)
206         return room_new, room_sink
207 }
208
209 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
210         args := strings.Split(cmd, " ")
211         rooms := strings.Split(args[0], ",")
212         var keys []string
213         if len(args) > 1 {
214                 keys = strings.Split(args[1], ",")
215         } else {
216                 keys = []string{}
217         }
218         for n, room := range rooms {
219                 if !RoomNameValid(room) {
220                         client.ReplyNoChannel(room)
221                         continue
222                 }
223                 var key string
224                 if (n < len(keys)) && (keys[n] != "") {
225                         key = keys[n]
226                 } else {
227                         key = ""
228                 }
229                 denied := false
230                 joined := false
231                 for room_existing, room_sink := range daemon.room_sinks {
232                         if room == room_existing.name {
233                                 if (room_existing.key != "") && (room_existing.key != key) {
234                                         denied = true
235                                 } else {
236                                         room_sink <- ClientEvent{client, EVENT_NEW, ""}
237                                         joined = true
238                                 }
239                                 break
240                         }
241                 }
242                 if denied {
243                         client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
244                 }
245                 if denied || joined {
246                         continue
247                 }
248                 room_new, room_sink := daemon.RoomRegister(room)
249                 if key != "" {
250                         room_new.key = key
251                         room_new.StateSave()
252                 }
253                 room_sink <- ClientEvent{client, EVENT_NEW, ""}
254         }
255 }
256
257 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
258         for event := range events {
259
260                 // Check for clients aliveness
261                 now := time.Now()
262                 if daemon.last_aliveness_check.Add(ALIVENESS_CHECK).Before(now) {
263                         for c := range daemon.clients {
264                                 if c.timestamp.Add(PING_TIMEOUT).Before(now) {
265                                         log.Println(c, "ping timeout")
266                                         c.conn.Close()
267                                         continue
268                                 }
269                                 if !c.ping_sent && c.timestamp.Add(PING_THRESHOLD).Before(now) {
270                                         if c.registered {
271                                                 c.Msg("PING :" + daemon.hostname)
272                                                 c.ping_sent = true
273                                         } else {
274                                                 log.Println(c, "ping timeout")
275                                                 c.conn.Close()
276                                         }
277                                 }
278                         }
279                         daemon.last_aliveness_check = now
280                 }
281
282                 client := event.client
283                 switch event.event_type {
284                 case EVENT_NEW:
285                         daemon.clients[client] = true
286                 case EVENT_DEL:
287                         delete(daemon.clients, client)
288                         for _, room_sink := range daemon.room_sinks {
289                                 room_sink <- event
290                         }
291                 case EVENT_MSG:
292                         cols := strings.SplitN(event.text, " ", 2)
293                         command := strings.ToUpper(cols[0])
294                         if daemon.Verbose {
295                                 log.Println(client, "command", command)
296                         }
297                         if command == "QUIT" {
298                                 delete(daemon.clients, client)
299                                 client.conn.Close()
300                                 continue
301                         }
302                         if !client.registered {
303                                 go daemon.ClientRegister(client, command, cols)
304                                 continue
305                         }
306                         switch command {
307                         case "AWAY":
308                                 continue
309                         case "JOIN":
310                                 if len(cols) == 1 || len(cols[1]) < 1 {
311                                         client.ReplyNotEnoughParameters("JOIN")
312                                         continue
313                                 }
314                                 go daemon.HandlerJoin(client, cols[1])
315                         case "LIST":
316                                 daemon.SendList(client, cols)
317                         case "LUSERS":
318                                 go daemon.SendLusers(client)
319                         case "MODE":
320                                 if len(cols) == 1 || len(cols[1]) < 1 {
321                                         client.ReplyNotEnoughParameters("MODE")
322                                         continue
323                                 }
324                                 cols = strings.SplitN(cols[1], " ", 2)
325                                 if cols[0] == client.username {
326                                         if len(cols) == 1 {
327                                                 client.Msg("221 " + client.nickname + " +")
328                                         } else {
329                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
330                                         }
331                                         continue
332                                 }
333                                 room := cols[0]
334                                 r, found := daemon.rooms[room]
335                                 if !found {
336                                         client.ReplyNoChannel(room)
337                                         continue
338                                 }
339                                 if len(cols) == 1 {
340                                         daemon.room_sinks[r] <- ClientEvent{client, EVENT_MODE, ""}
341                                 } else {
342                                         daemon.room_sinks[r] <- ClientEvent{client, EVENT_MODE, cols[1]}
343                                 }
344                         case "MOTD":
345                                 go daemon.SendMotd(client)
346                         case "PART":
347                                 if len(cols) == 1 || len(cols[1]) < 1 {
348                                         client.ReplyNotEnoughParameters("PART")
349                                         continue
350                                 }
351                                 for _, room := range strings.Split(cols[1], ",") {
352                                         r, found := daemon.rooms[room]
353                                         if !found {
354                                                 client.ReplyNoChannel(room)
355                                                 continue
356                                         }
357                                         daemon.room_sinks[r] <- ClientEvent{client, EVENT_DEL, ""}
358                                 }
359                         case "PING":
360                                 if len(cols) == 1 {
361                                         client.ReplyNicknamed("409", "No origin specified")
362                                         continue
363                                 }
364                                 client.Reply(fmt.Sprintf("PONG %s :%s", daemon.hostname, cols[1]))
365                         case "PONG":
366                                 continue
367                         case "NOTICE", "PRIVMSG":
368                                 if len(cols) == 1 {
369                                         client.ReplyNicknamed("411", "No recipient given ("+command+")")
370                                         continue
371                                 }
372                                 cols = strings.SplitN(cols[1], " ", 2)
373                                 if len(cols) == 1 {
374                                         client.ReplyNicknamed("412", "No text to send")
375                                         continue
376                                 }
377                                 msg := ""
378                                 target := strings.ToLower(cols[0])
379                                 for c := range daemon.clients {
380                                         if c.nickname == target {
381                                                 msg = fmt.Sprintf(":%s %s %s :%s", client, command, c.nickname, cols[1])
382                                                 c.Msg(msg)
383                                                 break
384                                         }
385                                 }
386                                 if msg != "" {
387                                         continue
388                                 }
389                                 r, found := daemon.rooms[target]
390                                 if !found {
391                                         client.ReplyNoNickChan(target)
392                                 }
393                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_MSG, command + " " + strings.TrimLeft(cols[1], ":")}
394                         case "TOPIC":
395                                 if len(cols) == 1 {
396                                         client.ReplyNotEnoughParameters("TOPIC")
397                                         continue
398                                 }
399                                 cols = strings.SplitN(cols[1], " ", 2)
400                                 r, found := daemon.rooms[cols[0]]
401                                 if !found {
402                                         client.ReplyNoChannel(cols[0])
403                                         continue
404                                 }
405                                 var change string
406                                 if len(cols) > 1 {
407                                         change = cols[1]
408                                 } else {
409                                         change = ""
410                                 }
411                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_TOPIC, change}
412                         case "WHO":
413                                 if len(cols) == 1 || len(cols[1]) < 1 {
414                                         client.ReplyNotEnoughParameters("WHO")
415                                         continue
416                                 }
417                                 room := strings.Split(cols[1], " ")[0]
418                                 r, found := daemon.rooms[room]
419                                 if !found {
420                                         client.ReplyNoChannel(room)
421                                         continue
422                                 }
423                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_WHO, ""}
424                         case "WHOIS":
425                                 if len(cols) == 1 || len(cols[1]) < 1 {
426                                         client.ReplyNotEnoughParameters("WHOIS")
427                                         continue
428                                 }
429                                 cols := strings.Split(cols[1], " ")
430                                 nicknames := strings.Split(cols[len(cols)-1], ",")
431                                 go daemon.SendWhois(client, nicknames)
432                         default:
433                                 client.ReplyNicknamed("421", command, "Unknown command")
434                         }
435                 }
436         }
437 }