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