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