]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
Raise copyright years
[goircd.git] / daemon.go
1 /*
2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2016 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                         if client != nil {
350                                 client.recvTimestamp = now
351                         }
352                         switch cmd {
353                         case "AWAY":
354                                 if len(cols) == 1 {
355                                         client.away = nil
356                                         client.ReplyNicknamed("305", "You are no longer marked as being away")
357                                         continue
358                                 }
359                                 msg := strings.TrimLeft(cols[1], ":")
360                                 client.away = &msg
361                                 client.ReplyNicknamed("306", "You have been marked as being away")
362                         case "JOIN":
363                                 if len(cols) == 1 || len(cols[1]) < 1 {
364                                         client.ReplyNotEnoughParameters("JOIN")
365                                         continue
366                                 }
367                                 HandlerJoin(client, cols[1])
368                         case "LIST":
369                                 SendList(client, cols)
370                         case "LUSERS":
371                                 SendLusers(client)
372                         case "MODE":
373                                 if len(cols) == 1 || len(cols[1]) < 1 {
374                                         client.ReplyNotEnoughParameters("MODE")
375                                         continue
376                                 }
377                                 cols = strings.SplitN(cols[1], " ", 2)
378                                 if cols[0] == *client.username {
379                                         if len(cols) == 1 {
380                                                 client.Msg("221 " + *client.nickname + " +")
381                                         } else {
382                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
383                                         }
384                                         continue
385                                 }
386                                 room := cols[0]
387                                 r, found := rooms[room]
388                                 if !found {
389                                         client.ReplyNoChannel(room)
390                                         continue
391                                 }
392                                 if len(cols) == 1 {
393                                         roomSinks[r] <- ClientEvent{client, EventMode, ""}
394                                 } else {
395                                         roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
396                                 }
397                         case "MOTD":
398                                 SendMotd(client)
399                         case "PART":
400                                 if len(cols) == 1 || len(cols[1]) < 1 {
401                                         client.ReplyNotEnoughParameters("PART")
402                                         continue
403                                 }
404                                 rs := strings.Split(cols[1], " ")[0]
405                                 for _, room := range strings.Split(rs, ",") {
406                                         if r, found := rooms[room]; found {
407                                                 roomSinks[r] <- ClientEvent{client, EventDel, ""}
408                                         } else {
409                                                 client.ReplyNoChannel(room)
410                                                 continue
411                                         }
412                                 }
413                         case "PING":
414                                 if len(cols) == 1 {
415                                         client.ReplyNicknamed("409", "No origin specified")
416                                         continue
417                                 }
418                                 client.Reply(fmt.Sprintf("PONG %s :%s", *hostname, cols[1]))
419                         case "PONG":
420                                 continue
421                         case "NOTICE", "PRIVMSG":
422                                 if len(cols) == 1 {
423                                         client.ReplyNicknamed("411", "No recipient given ("+cmd+")")
424                                         continue
425                                 }
426                                 cols = strings.SplitN(cols[1], " ", 2)
427                                 if len(cols) == 1 {
428                                         client.ReplyNicknamed("412", "No text to send")
429                                         continue
430                                 }
431                                 msg := ""
432                                 target := strings.ToLower(cols[0])
433                                 for c := range clients {
434                                         if *c.nickname == target {
435                                                 msg = fmt.Sprintf(":%s %s %s %s", client, cmd, *c.nickname, cols[1])
436                                                 c.Msg(msg)
437                                                 if c.away != nil {
438                                                         client.ReplyNicknamed("301", *c.nickname, *c.away)
439                                                 }
440                                                 break
441                                         }
442                                 }
443                                 if msg != "" {
444                                         continue
445                                 }
446                                 if r, found := rooms[target]; found {
447                                         roomSinks[r] <- ClientEvent{
448                                                 client,
449                                                 EventMsg,
450                                                 cmd + " " + strings.TrimLeft(cols[1], ":"),
451                                         }
452                                 } else {
453                                         client.ReplyNoNickChan(target)
454                                 }
455                         case "TOPIC":
456                                 if len(cols) == 1 {
457                                         client.ReplyNotEnoughParameters("TOPIC")
458                                         continue
459                                 }
460                                 cols = strings.SplitN(cols[1], " ", 2)
461                                 r, found := rooms[cols[0]]
462                                 if !found {
463                                         client.ReplyNoChannel(cols[0])
464                                         continue
465                                 }
466                                 var change string
467                                 if len(cols) > 1 {
468                                         change = cols[1]
469                                 } else {
470                                         change = ""
471                                 }
472                                 roomSinks[r] <- ClientEvent{client, EventTopic, change}
473                         case "WHO":
474                                 if len(cols) == 1 || len(cols[1]) < 1 {
475                                         client.ReplyNotEnoughParameters("WHO")
476                                         continue
477                                 }
478                                 room := strings.Split(cols[1], " ")[0]
479                                 if r, found := rooms[room]; found {
480                                         roomSinks[r] <- ClientEvent{client, EventWho, ""}
481                                 } else {
482                                         client.ReplyNoChannel(room)
483                                 }
484                         case "WHOIS":
485                                 if len(cols) == 1 || len(cols[1]) < 1 {
486                                         client.ReplyNotEnoughParameters("WHOIS")
487                                         continue
488                                 }
489                                 cols := strings.Split(cols[1], " ")
490                                 nicknames := strings.Split(cols[len(cols)-1], ",")
491                                 SendWhois(client, nicknames)
492                         case "ISON":
493                                 if len(cols) == 1 || len(cols[1]) < 1 {
494                                         client.ReplyNotEnoughParameters("ISON")
495                                         continue
496                                 }
497                                 nicksKnown := make(map[string]struct{})
498                                 for c := range clients {
499                                         nicksKnown[*c.nickname] = struct{}{}
500                                 }
501                                 var nicksExists []string
502                                 for _, nickname := range strings.Split(cols[1], " ") {
503                                         if _, exists := nicksKnown[nickname]; exists {
504                                                 nicksExists = append(nicksExists, nickname)
505                                         }
506                                 }
507                                 client.ReplyNicknamed("303", strings.Join(nicksExists, " "))
508                         case "VERSION":
509                                 var debug string
510                                 if *verbose {
511                                         debug = "debug"
512                                 } else {
513                                         debug = ""
514                                 }
515                                 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", version, debug, *hostname))
516                         default:
517                                 client.ReplyNicknamed("421", cmd, "Unknown command")
518                         }
519                 }
520         }
521 }