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