]> Cypherpunks.ru repositories - goircd.git/blob - daemon.go
Fixed unkeyed room mode getting
[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.Trim(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                 for existingClient := range clients {
166                         if *existingClient.nickname == nickname {
167                                 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
168                                 return
169                         }
170                 }
171                 if !RENickname.MatchString(nickname) {
172                         client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
173                         return
174                 }
175                 client.nickname = &nickname
176         case "USER":
177                 if len(cols) == 1 {
178                         client.ReplyNotEnoughParameters("USER")
179                         return
180                 }
181                 args := strings.SplitN(cols[1], " ", 4)
182                 if len(args) < 4 {
183                         client.ReplyNotEnoughParameters("USER")
184                         return
185                 }
186                 client.username = &args[0]
187                 realname := strings.TrimLeft(args[3], ":")
188                 client.realname = &realname
189         }
190         if *client.nickname != "*" && *client.username != "" {
191                 if passwords != nil && *passwords != "" {
192                         if client.password == nil {
193                                 client.ReplyParts("462", "You may not register")
194                                 client.Close()
195                                 return
196                         }
197                         contents, err := ioutil.ReadFile(*passwords)
198                         if err != nil {
199                                 log.Fatalf("Can no read passwords file %s: %s", *passwords, err)
200                                 return
201                         }
202                         for _, entry := range strings.Split(string(contents), "\n") {
203                                 if entry == "" {
204                                         continue
205                                 }
206                                 if lp := strings.Split(entry, ":"); lp[0] == *client.nickname && lp[1] != *client.password {
207                                         client.ReplyParts("462", "You may not register")
208                                         client.Close()
209                                         return
210                                 }
211                         }
212                 }
213                 client.registered = true
214                 client.ReplyNicknamed("001", "Hi, welcome to IRC")
215                 client.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+version)
216                 client.ReplyNicknamed("003", "This server was created sometime")
217                 client.ReplyNicknamed("004", *hostname+" goircd o o")
218                 SendLusers(client)
219                 SendMotd(client)
220                 log.Println(client, "logged in")
221         }
222 }
223
224 // Register new room in Daemon. Create an object, events sink, save pointers
225 // to corresponding daemon's places and start room's processor goroutine.
226 func RoomRegister(name string) (*Room, chan ClientEvent) {
227         roomNew := NewRoom(name)
228         roomSink := make(chan ClientEvent)
229         rooms[name] = roomNew
230         roomSinks[roomNew] = roomSink
231         go roomNew.Processor(roomSink)
232         roomsGroup.Add(1)
233         return roomNew, roomSink
234 }
235
236 func HandlerJoin(client *Client, cmd string) {
237         args := strings.Split(cmd, " ")
238         rs := strings.Split(args[0], ",")
239         var keys []string
240         if len(args) > 1 {
241                 keys = strings.Split(args[1], ",")
242         } else {
243                 keys = make([]string, 0)
244         }
245         var roomExisting *Room
246         var roomSink chan ClientEvent
247         var roomNew *Room
248         for n, room := range rs {
249                 if !RoomNameValid(room) {
250                         client.ReplyNoChannel(room)
251                         continue
252                 }
253                 var key string
254                 if (n < len(keys)) && (keys[n] != "") {
255                         key = keys[n]
256                 } else {
257                         key = ""
258                 }
259                 for roomExisting, roomSink = range roomSinks {
260                         if room == *roomExisting.name {
261                                 if (*roomExisting.key != "") && (*roomExisting.key != key) {
262                                         goto Denied
263                                 }
264                                 roomSink <- ClientEvent{client, EventNew, ""}
265                                 goto Joined
266                         }
267                 }
268                 roomNew, roomSink = RoomRegister(room)
269                 log.Println("Room", roomNew, "created")
270                 if key != "" {
271                         roomNew.key = &key
272                         roomNew.StateSave()
273                 }
274                 roomSink <- ClientEvent{client, EventNew, ""}
275                 continue
276         Denied:
277                 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
278         Joined:
279         }
280 }
281
282 func Processor(events chan ClientEvent, finished chan struct{}) {
283         var now time.Time
284         go func() {
285                 for {
286                         time.Sleep(10 * time.Second)
287                         events <- ClientEvent{eventType: EventTick}
288                 }
289         }()
290         for event := range events {
291                 now = time.Now()
292                 client := event.client
293                 switch event.eventType {
294                 case EventTick:
295                         for c := range clients {
296                                 if c.recvTimestamp.Add(PingTimeout).Before(now) {
297                                         log.Println(c, "ping timeout")
298                                         c.Close()
299                                         continue
300                                 }
301                                 if c.sendTimestamp.Add(PingThreshold).Before(now) {
302                                         if c.registered {
303                                                 c.Msg("PING :" + *hostname)
304                                                 c.sendTimestamp = time.Now()
305                                         } else {
306                                                 log.Println(c, "ping timeout")
307                                                 c.Close()
308                                         }
309                                 }
310                         }
311                 case EventTerm:
312                         for _, sink := range roomSinks {
313                                 sink <- ClientEvent{eventType: EventTerm}
314                         }
315                         roomsGroup.Wait()
316                         close(finished)
317                         return
318                 case EventNew:
319                         clients[client] = struct{}{}
320                 case EventDel:
321                         delete(clients, client)
322                         for _, roomSink := range roomSinks {
323                                 roomSink <- event
324                         }
325                 case EventMsg:
326                         cols := strings.SplitN(event.text, " ", 2)
327                         cmd := strings.ToUpper(cols[0])
328                         if *verbose {
329                                 log.Println(client, "command", cmd)
330                         }
331                         if cmd == "QUIT" {
332                                 log.Println(client, "quit")
333                                 client.Close()
334                                 continue
335                         }
336                         if !client.registered {
337                                 ClientRegister(client, cmd, cols)
338                                 continue
339                         }
340                         switch cmd {
341                         case "AWAY":
342                                 if len(cols) == 1 {
343                                         client.away = nil
344                                         client.ReplyNicknamed("305", "You are no longer marked as being away")
345                                         continue
346                                 }
347                                 msg := strings.TrimLeft(cols[1], ":")
348                                 client.away = &msg
349                                 client.ReplyNicknamed("306", "You have been marked as being away")
350                         case "JOIN":
351                                 if len(cols) == 1 || len(cols[1]) < 1 {
352                                         client.ReplyNotEnoughParameters("JOIN")
353                                         continue
354                                 }
355                                 HandlerJoin(client, cols[1])
356                         case "LIST":
357                                 SendList(client, cols)
358                         case "LUSERS":
359                                 SendLusers(client)
360                         case "MODE":
361                                 if len(cols) == 1 || len(cols[1]) < 1 {
362                                         client.ReplyNotEnoughParameters("MODE")
363                                         continue
364                                 }
365                                 cols = strings.SplitN(cols[1], " ", 2)
366                                 if cols[0] == *client.username {
367                                         if len(cols) == 1 {
368                                                 client.Msg("221 " + *client.nickname + " +")
369                                         } else {
370                                                 client.ReplyNicknamed("501", "Unknown MODE flag")
371                                         }
372                                         continue
373                                 }
374                                 room := cols[0]
375                                 r, found := rooms[room]
376                                 if !found {
377                                         client.ReplyNoChannel(room)
378                                         continue
379                                 }
380                                 if len(cols) == 1 {
381                                         roomSinks[r] <- ClientEvent{client, EventMode, ""}
382                                 } else {
383                                         roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
384                                 }
385                         case "MOTD":
386                                 SendMotd(client)
387                         case "PART":
388                                 if len(cols) == 1 || len(cols[1]) < 1 {
389                                         client.ReplyNotEnoughParameters("PART")
390                                         continue
391                                 }
392                                 rs := strings.Split(cols[1], " ")[0]
393                                 for _, room := range strings.Split(rs, ",") {
394                                         if r, found := rooms[room]; found {
395                                                 roomSinks[r] <- ClientEvent{client, EventDel, ""}
396                                         } else {
397                                                 client.ReplyNoChannel(room)
398                                                 continue
399                                         }
400                                 }
401                         case "PING":
402                                 if len(cols) == 1 {
403                                         client.ReplyNicknamed("409", "No origin specified")
404                                         continue
405                                 }
406                                 client.Reply(fmt.Sprintf("PONG %s :%s", *hostname, cols[1]))
407                         case "PONG":
408                                 continue
409                         case "NOTICE", "PRIVMSG":
410                                 if len(cols) == 1 {
411                                         client.ReplyNicknamed("411", "No recipient given ("+cmd+")")
412                                         continue
413                                 }
414                                 cols = strings.SplitN(cols[1], " ", 2)
415                                 if len(cols) == 1 {
416                                         client.ReplyNicknamed("412", "No text to send")
417                                         continue
418                                 }
419                                 msg := ""
420                                 target := strings.ToLower(cols[0])
421                                 for c := range clients {
422                                         if *c.nickname == target {
423                                                 msg = fmt.Sprintf(":%s %s %s %s", client, cmd, *c.nickname, cols[1])
424                                                 c.Msg(msg)
425                                                 if c.away != nil {
426                                                         client.ReplyNicknamed("301", *c.nickname, *c.away)
427                                                 }
428                                                 break
429                                         }
430                                 }
431                                 if msg != "" {
432                                         continue
433                                 }
434                                 if r, found := rooms[target]; found {
435                                         roomSinks[r] <- ClientEvent{
436                                                 client,
437                                                 EventMsg,
438                                                 cmd + " " + strings.TrimLeft(cols[1], ":"),
439                                         }
440                                 } else {
441                                         client.ReplyNoNickChan(target)
442                                 }
443                         case "TOPIC":
444                                 if len(cols) == 1 {
445                                         client.ReplyNotEnoughParameters("TOPIC")
446                                         continue
447                                 }
448                                 cols = strings.SplitN(cols[1], " ", 2)
449                                 r, found := rooms[cols[0]]
450                                 if !found {
451                                         client.ReplyNoChannel(cols[0])
452                                         continue
453                                 }
454                                 var change string
455                                 if len(cols) > 1 {
456                                         change = cols[1]
457                                 } else {
458                                         change = ""
459                                 }
460                                 roomSinks[r] <- ClientEvent{client, EventTopic, change}
461                         case "WHO":
462                                 if len(cols) == 1 || len(cols[1]) < 1 {
463                                         client.ReplyNotEnoughParameters("WHO")
464                                         continue
465                                 }
466                                 room := strings.Split(cols[1], " ")[0]
467                                 if r, found := rooms[room]; found {
468                                         roomSinks[r] <- ClientEvent{client, EventWho, ""}
469                                 } else {
470                                         client.ReplyNoChannel(room)
471                                 }
472                         case "WHOIS":
473                                 if len(cols) == 1 || len(cols[1]) < 1 {
474                                         client.ReplyNotEnoughParameters("WHOIS")
475                                         continue
476                                 }
477                                 cols := strings.Split(cols[1], " ")
478                                 nicknames := strings.Split(cols[len(cols)-1], ",")
479                                 SendWhois(client, nicknames)
480                         case "VERSION":
481                                 var debug string
482                                 if *verbose {
483                                         debug = "debug"
484                                 } else {
485                                         debug = ""
486                                 }
487                                 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", version, debug, *hostname))
488                         default:
489                                 client.ReplyNicknamed("421", cmd, "Unknown command")
490                         }
491                 }
492                 if client != nil {
493                         client.recvTimestamp = now
494                 }
495         }
496 }