]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
Fix /whois for mixed case nicks.
[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         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 daemon.motd != "" {
75                 fd, err := os.Open(daemon.motd)
76                 if err == nil {
77                         defer fd.Close()
78                         motd := []byte{}
79                         var err error
80                         for err != io.EOF {
81                                 buf := make([]byte, 1024)
82                                 _, err = fd.Read(buf)
83                                 motd = append(motd, bytes.TrimRight(buf, "\x00")...)
84                         }
85
86                         client.ReplyNicknamed("375", "- "+daemon.hostname+" Message of the day -")
87                         for _, s := range bytes.Split(bytes.TrimRight(motd, "\n"), []byte("\n")) {
88                                 client.ReplyNicknamed("372", "- "+string(s))
89                         }
90                         client.ReplyNicknamed("376", "End of /MOTD command")
91                         return
92                 } else {
93                         log.Println("Can not open motd file", daemon.motd, err)
94                 }
95         }
96         client.ReplyNicknamed("422", "MOTD File is missing")
97 }
98
99 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
100         for _, nickname := range nicknames {
101                 nickname = strings.ToLower(nickname)
102                 found := false
103                 for c := range daemon.clients {
104                         if strings.ToLower(c.nickname) != nickname {
105                                 continue
106                         }
107                         found = true
108                         client.ReplyNicknamed("311", c.nickname, c.username, c.conn.RemoteAddr().String(), "*", 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 client := range daemon.clients {
162                         if 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_sink := make(chan ClientEvent)
201         daemon.rooms[name] = room_new
202         daemon.room_sinks[room_new] = room_sink
203         go room_new.Processor(room_sink)
204         return room_new, room_sink
205 }
206
207 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
208         args := strings.Split(cmd, " ")
209         rooms := strings.Split(args[0], ",")
210         var keys []string
211         if len(args) > 1 {
212                 keys = strings.Split(args[1], ",")
213         } else {
214                 keys = []string{}
215         }
216         for n, room := range rooms {
217                 if !RoomNameValid(room) {
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                 }
243                 if denied || joined {
244                         continue
245                 }
246                 room_new, room_sink := daemon.RoomRegister(room)
247                 if key != "" {
248                         room_new.key = key
249                         room_new.StateSave()
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 := 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                                         r, found := daemon.rooms[room]
349                                         if !found {
350                                                 client.ReplyNoChannel(room)
351                                                 continue
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 ("+command+")")
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                                 r, found := daemon.rooms[target]
386                                 if !found {
387                                         client.ReplyNoNickChan(target)
388                                 }
389                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_MSG, command + " " + strings.TrimLeft(cols[1], ":")}
390                         case "TOPIC":
391                                 if len(cols) == 1 {
392                                         client.ReplyNotEnoughParameters("TOPIC")
393                                         continue
394                                 }
395                                 cols = strings.SplitN(cols[1], " ", 2)
396                                 r, found := daemon.rooms[cols[0]]
397                                 if !found {
398                                         client.ReplyNoChannel(cols[0])
399                                         continue
400                                 }
401                                 var change string
402                                 if len(cols) > 1 {
403                                         change = cols[1]
404                                 } else {
405                                         change = ""
406                                 }
407                                 daemon.room_sinks[r] <- ClientEvent{client, EVENT_TOPIC, change}
408                         case "WHO":
409                                 if len(cols) == 1 || len(cols[1]) < 1 {
410                                         client.ReplyNotEnoughParameters("WHO")
411                                         continue
412                                 }
413                                 room := strings.Split(cols[1], " ")[0]
414                                 r, found := daemon.rooms[room]
415                                 if !found {
416                                         client.ReplyNoChannel(room)
417                                         continue
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 }