]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
ISON command support
[goircd.git] / daemon.go
1 /*
2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2015 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
19 package main
20
21 import (
22         "fmt"
23         "io/ioutil"
24         "log"
25         "net"
26         "regexp"
27         "sort"
28         "strings"
29         "sync"
30         "time"
31 )
32
33 const (
34         // Max deadline time of client's unresponsiveness
35         PingTimeout = time.Second * 180
36         // Max idle client's time before PING are sent
37         PingThreshold = time.Second * 90
38 )
39
40 var (
41         RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
42
43         roomsGroup sync.WaitGroup
44
45         clients map[*Client]struct{} = make(map[*Client]struct{})
46 )
47
48 func SendLusers(client *Client) {
49         lusers := 0
50         for client := range clients {
51                 if client.registered {
52                         lusers++
53                 }
54         }
55         client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
56 }
57
58 func SendMotd(client *Client) {
59         if motd == nil {
60                 client.ReplyNicknamed("422", "MOTD File is missing")
61                 return
62         }
63         motdText, err := ioutil.ReadFile(*motd)
64         if err != nil {
65                 log.Printf("Can not read motd file %s: %v", *motd, err)
66                 client.ReplyNicknamed("422", "Error reading MOTD File")
67                 return
68         }
69         client.ReplyNicknamed("375", "- "+*hostname+" Message of the day -")
70         for _, s := range strings.Split(strings.TrimSuffix(string(motdText), "\n"), "\n") {
71                 client.ReplyNicknamed("372", "- "+s)
72         }
73         client.ReplyNicknamed("376", "End of /MOTD command")
74 }
75
76 func SendWhois(client *Client, nicknames []string) {
77         var c *Client
78         var hostPort string
79         var err error
80         var subscriptions []string
81         var room *Room
82         var subscriber *Client
83         for _, nickname := range nicknames {
84                 nickname = strings.ToLower(nickname)
85                 for c = range clients {
86                         if strings.ToLower(*c.nickname) == nickname {
87                                 goto Found
88                         }
89                 }
90                 client.ReplyNoNickChan(nickname)
91                 continue
92         Found:
93                 hostPort, _, err = net.SplitHostPort(c.conn.RemoteAddr().String())
94                 if err != nil {
95                         log.Printf("Can't parse RemoteAddr %q: %v", hostPort, err)
96                         hostPort = "Unknown"
97                 }
98                 client.ReplyNicknamed("311", *c.nickname, *c.username, hostPort, "*", *c.realname)
99                 client.ReplyNicknamed("312", *c.nickname, *hostname, *hostname)
100                 if c.away != nil {
101                         client.ReplyNicknamed("301", *c.nickname, *c.away)
102                 }
103                 subscriptions = make([]string, 0)
104                 for _, room = range 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 }
116
117 func SendList(client *Client, cols []string) {
118         var rs []string
119         var r string
120         if (len(cols) > 1) && (cols[1] != "") {
121                 rs = strings.Split(strings.Split(cols[1], " ")[0], ",")
122         } else {
123                 rs = make([]string, 0)
124                 for r = range rooms {
125                         rs = append(rs, r)
126                 }
127         }
128         sort.Strings(rs)
129         var room *Room
130         var found bool
131         for _, r = range rs {
132                 if room, found = rooms[r]; found {
133                         client.ReplyNicknamed(
134                                 "322",
135                                 r,
136                                 fmt.Sprintf("%d", len(room.members)),
137                                 *room.topic,
138                         )
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 ClientRegister(client *Client, cmd string, cols []string) {
150         switch cmd {
151         case "PASS":
152                 if len(cols) == 1 || len(cols[1]) < 1 {
153                         client.ReplyNotEnoughParameters("PASS")
154                         return
155                 }
156                 client.password = &cols[1]
157         case "NICK":
158                 if len(cols) == 1 || len(cols[1]) < 1 {
159                         client.ReplyParts("431", "No nickname given")
160                         return
161                 }
162                 nickname := cols[1]
163                 // Compatibility with some clients prepending colons to nickname
164                 nickname = strings.TrimPrefix(nickname, ":")
165                 nickname = strings.ToLower(nickname)
166                 for existingClient := range clients {
167                         if *existingClient.nickname == nickname {
168                                 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
169                                 return
170                         }
171                 }
172                 if !RENickname.MatchString(nickname) {
173                         client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
174                         return
175                 }
176                 client.nickname = &nickname
177         case "USER":
178                 if len(cols) == 1 {
179                         client.ReplyNotEnoughParameters("USER")
180                         return
181                 }
182                 args := strings.SplitN(cols[1], " ", 4)
183                 if len(args) < 4 {
184                         client.ReplyNotEnoughParameters("USER")
185                         return
186                 }
187                 client.username = &args[0]
188                 realname := strings.TrimLeft(args[3], ":")
189                 client.realname = &realname
190         }
191         if *client.nickname != "*" && *client.username != "" {
192                 if passwords != nil && *passwords != "" {
193                         if client.password == nil {
194                                 client.ReplyParts("462", "You may not register")
195                                 client.Close()
196                                 return
197                         }
198                         contents, err := ioutil.ReadFile(*passwords)
199                         if err != nil {
200                                 log.Fatalf("Can no read passwords file %s: %s", *passwords, err)
201                                 return
202                         }
203                         for _, entry := range strings.Split(string(contents), "\n") {
204                                 if entry == "" {
205                                         continue
206                                 }
207                                 if lp := strings.Split(entry, ":"); lp[0] == *client.nickname && lp[1] != *client.password {
208                                         client.ReplyParts("462", "You may not register")
209                                         client.Close()
210                                         return
211                                 }
212                         }
213                 }
214                 client.registered = true
215                 client.ReplyNicknamed("001", "Hi, welcome to IRC")
216                 client.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+version)
217                 client.ReplyNicknamed("003", "This server was created sometime")
218                 client.ReplyNicknamed("004", *hostname+" goircd o o")
219                 SendLusers(client)
220                 SendMotd(client)
221                 log.Println(client, "logged in")
222         }
223 }
224
225 // Register new room in Daemon. Create an object, events sink, save pointers
226 // to corresponding daemon's places and start room's processor goroutine.
227 func RoomRegister(name string) (*Room, chan ClientEvent) {
228         roomNew := NewRoom(name)
229         roomSink := make(chan ClientEvent)
230         rooms[name] = roomNew
231         roomSinks[roomNew] = roomSink
232         go roomNew.Processor(roomSink)
233         roomsGroup.Add(1)
234         return roomNew, roomSink
235 }
236
237 func HandlerJoin(client *Client, cmd string) {
238         args := strings.Split(cmd, " ")
239         rs := strings.Split(args[0], ",")
240         var keys []string
241         if len(args) > 1 {
242                 keys = strings.Split(args[1], ",")
243         } else {
244                 keys = make([]string, 0)
245         }
246         var roomExisting *Room
247         var roomSink chan ClientEvent
248         var roomNew *Room
249         for n, room := range rs {
250                 if !RoomNameValid(room) {
251                         client.ReplyNoChannel(room)
252                         continue
253                 }
254                 var key string
255                 if (n < len(keys)) && (keys[n] != "") {
256                         key = keys[n]
257                 } else {
258                         key = ""
259                 }
260                 for roomExisting, roomSink = range roomSinks {
261                         if room == *roomExisting.name {
262                                 if (*roomExisting.key != "") && (*roomExisting.key != key) {
263                                         goto Denied
264                                 }
265                                 roomSink <- ClientEvent{client, EventNew, ""}
266                                 goto Joined
267                         }
268                 }
269                 roomNew, roomSink = RoomRegister(room)
270                 log.Println("Room", roomNew, "created")
271                 if key != "" {
272                         roomNew.key = &key
273                         roomNew.StateSave()
274                 }
275                 roomSink <- ClientEvent{client, EventNew, ""}
276                 continue
277         Denied:
278                 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
279         Joined:
280         }
281 }
282
283 func Processor(events chan ClientEvent, finished chan struct{}) {
284         var now time.Time
285         go func() {
286                 for {
287                         time.Sleep(10 * time.Second)
288                         events <- ClientEvent{eventType: EventTick}
289                 }
290         }()
291         for event := range events {
292                 now = time.Now()
293                 client := event.client
294                 switch event.eventType {
295                 case EventTick:
296                         for c := range clients {
297                                 if c.recvTimestamp.Add(PingTimeout).Before(now) {
298                                         log.Println(c, "ping timeout")
299                                         c.Close()
300                                         continue
301                                 }
302                                 if c.sendTimestamp.Add(PingThreshold).Before(now) {
303                                         if c.registered {
304                                                 c.Msg("PING :" + *hostname)
305                                                 c.sendTimestamp = time.Now()
306                                         } else {
307                                                 log.Println(c, "ping timeout")
308                                                 c.Close()
309                                         }
310                                 }
311                         }
312                         for rn, r := range rooms {
313                                 if *statedir == "" && len(r.members) == 0 {
314                                         log.Println(rn, "emptied room")
315                                         delete(rooms, rn)
316                                         close(roomSinks[r])
317                                         delete(roomSinks, r)
318                                 }
319                         }
320                 case EventTerm:
321                         for _, sink := range roomSinks {
322                                 sink <- ClientEvent{eventType: EventTerm}
323                         }
324                         roomsGroup.Wait()
325                         close(finished)
326                         return
327                 case EventNew:
328                         clients[client] = struct{}{}
329                 case EventDel:
330                         delete(clients, client)
331                         for _, roomSink := range roomSinks {
332                                 roomSink <- event
333                         }
334                 case EventMsg:
335                         cols := strings.SplitN(event.text, " ", 2)
336                         cmd := strings.ToUpper(cols[0])
337                         if *verbose {
338                                 log.Println(client, "command", cmd)
339                         }
340                         if cmd == "QUIT" {
341                                 log.Println(client, "quit")
342                                 client.Close()
343                                 continue
344                         }
345                         if !client.registered {
346                                 ClientRegister(client, cmd, cols)
347                                 continue
348                         }
349                         switch cmd {
350                         case "AWAY":
351                                 if len(cols) == 1 {
352                                         client.away = nil
353                                         client.ReplyNicknamed("305", "You are no longer marked as being away")
354                                         continue
355                                 }
356                                 msg := strings.TrimLeft(cols[1], ":")
357                                 client.away = &msg
358                                 client.ReplyNicknamed("306", "You have been marked as being away")
359                         case "JOIN":
360                                 if len(cols) == 1 || len(cols[1]) < 1 {
361                                         client.ReplyNotEnoughParameters("JOIN")
362                                         continue
363                                 }
364                                 HandlerJoin(client, cols[1])
365                         case "LIST":
366                                 SendList(client, cols)
367                         case "LUSERS":
368                                 SendLusers(client)
369                         case "MODE":
370                                 if len(cols) == 1 || len(cols[1]) < 1 {
371                                         client.ReplyNotEnoughParameters("MODE")
372                                         continue
373                                 }
374                                 cols = strings.SplitN(cols[1], " ", 2)
375                                 if cols[0] == *client.username {
376                                         if len(cols) == 1 {
377                                                 client.Msg("221 " + *client.nickname + " +")
378                                         } else {
379                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
380                                         }
381                                         continue
382                                 }
383                                 room := cols[0]
384                                 r, found := rooms[room]
385                                 if !found {
386                                         client.ReplyNoChannel(room)
387                                         continue
388                                 }
389                                 if len(cols) == 1 {
390                                         roomSinks[r] <- ClientEvent{client, EventMode, ""}
391                                 } else {
392                                         roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
393                                 }
394                         case "MOTD":
395                                 SendMotd(client)
396                         case "PART":
397                                 if len(cols) == 1 || len(cols[1]) < 1 {
398                                         client.ReplyNotEnoughParameters("PART")
399                                         continue
400                                 }
401                                 rs := strings.Split(cols[1], " ")[0]
402                                 for _, room := range strings.Split(rs, ",") {
403                                         if r, found := rooms[room]; found {
404                                                 roomSinks[r] <- ClientEvent{client, EventDel, ""}
405                                         } else {
406                                                 client.ReplyNoChannel(room)
407                                                 continue
408                                         }
409                                 }
410                         case "PING":
411                                 if len(cols) == 1 {
412                                         client.ReplyNicknamed("409", "No origin specified")
413                                         continue
414                                 }
415                                 client.Reply(fmt.Sprintf("PONG %s :%s", *hostname, cols[1]))
416                         case "PONG":
417                                 continue
418                         case "NOTICE", "PRIVMSG":
419                                 if len(cols) == 1 {
420                                         client.ReplyNicknamed("411", "No recipient given ("+cmd+")")
421                                         continue
422                                 }
423                                 cols = strings.SplitN(cols[1], " ", 2)
424                                 if len(cols) == 1 {
425                                         client.ReplyNicknamed("412", "No text to send")
426                                         continue
427                                 }
428                                 msg := ""
429                                 target := strings.ToLower(cols[0])
430                                 for c := range clients {
431                                         if *c.nickname == target {
432                                                 msg = fmt.Sprintf(":%s %s %s %s", client, cmd, *c.nickname, cols[1])
433                                                 c.Msg(msg)
434                                                 if c.away != nil {
435                                                         client.ReplyNicknamed("301", *c.nickname, *c.away)
436                                                 }
437                                                 break
438                                         }
439                                 }
440                                 if msg != "" {
441                                         continue
442                                 }
443                                 if r, found := rooms[target]; found {
444                                         roomSinks[r] <- ClientEvent{
445                                                 client,
446                                                 EventMsg,
447                                                 cmd + " " + strings.TrimLeft(cols[1], ":"),
448                                         }
449                                 } else {
450                                         client.ReplyNoNickChan(target)
451                                 }
452                         case "TOPIC":
453                                 if len(cols) == 1 {
454                                         client.ReplyNotEnoughParameters("TOPIC")
455                                         continue
456                                 }
457                                 cols = strings.SplitN(cols[1], " ", 2)
458                                 r, found := rooms[cols[0]]
459                                 if !found {
460                                         client.ReplyNoChannel(cols[0])
461                                         continue
462                                 }
463                                 var change string
464                                 if len(cols) > 1 {
465                                         change = cols[1]
466                                 } else {
467                                         change = ""
468                                 }
469                                 roomSinks[r] <- ClientEvent{client, EventTopic, change}
470                         case "WHO":
471                                 if len(cols) == 1 || len(cols[1]) < 1 {
472                                         client.ReplyNotEnoughParameters("WHO")
473                                         continue
474                                 }
475                                 room := strings.Split(cols[1], " ")[0]
476                                 if r, found := rooms[room]; found {
477                                         roomSinks[r] <- ClientEvent{client, EventWho, ""}
478                                 } else {
479                                         client.ReplyNoChannel(room)
480                                 }
481                         case "WHOIS":
482                                 if len(cols) == 1 || len(cols[1]) < 1 {
483                                         client.ReplyNotEnoughParameters("WHOIS")
484                                         continue
485                                 }
486                                 cols := strings.Split(cols[1], " ")
487                                 nicknames := strings.Split(cols[len(cols)-1], ",")
488                                 SendWhois(client, nicknames)
489                         case "ISON":
490                                 if len(cols) == 1 || len(cols[1]) < 1 {
491                                         client.ReplyNotEnoughParameters("ISON")
492                                         continue
493                                 }
494                                 nicksKnown := make(map[string]struct{})
495                                 for c := range clients {
496                                         nicksKnown[*c.nickname] = struct{}{}
497                                 }
498                                 var nicksExists []string
499                                 for _, nickname := range strings.Split(cols[1], " ") {
500                                         if _, exists := nicksKnown[nickname]; exists {
501                                                 nicksExists = append(nicksExists, nickname)
502                                         }
503                                 }
504                                 client.ReplyNicknamed("303", strings.Join(nicksExists, " "))
505                         case "VERSION":
506                                 var debug string
507                                 if *verbose {
508                                         debug = "debug"
509                                 } else {
510                                         debug = ""
511                                 }
512                                 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", version, debug, *hostname))
513                         default:
514                                 client.ReplyNicknamed("421", cmd, "Unknown command")
515                         }
516                 }
517                 if client != nil {
518                         client.recvTimestamp = now
519                 }
520         }
521 }