2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2016 Sergey Matveev <stargrave@stargrave.org>
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.
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.
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/>.
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
41 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
43 clients map[*Client]struct{} = make(map[*Client]struct{})
45 rooms map[string]*Room = make(map[string]*Room)
47 roomsGroup sync.WaitGroup
48 roomSinks map[*Room]chan ClientEvent = make(map[*Room]chan ClientEvent)
51 func SendLusers(client *Client) {
54 for client := range clients {
55 if client.registered {
60 client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
63 func SendMotd(client *Client) {
65 client.ReplyNicknamed("422", "MOTD File is missing")
68 motdText, err := ioutil.ReadFile(*motd)
70 log.Printf("Can not read motd file %s: %v", *motd, err)
71 client.ReplyNicknamed("422", "Error reading MOTD File")
74 client.ReplyNicknamed("375", "- "+*hostname+" Message of the day -")
75 for _, s := range strings.Split(strings.TrimSuffix(string(motdText), "\n"), "\n") {
76 client.ReplyNicknamed("372", "- "+s)
78 client.ReplyNicknamed("376", "End of /MOTD command")
81 func SendWhois(client *Client, nicknames []string) {
85 var subscriptions []string
87 var subscriber *Client
88 for _, nickname := range nicknames {
89 nickname = strings.ToLower(nickname)
91 for c = range clients {
92 if strings.ToLower(*c.nickname) == nickname {
98 client.ReplyNoNickChan(nickname)
101 hostPort, _, err = net.SplitHostPort(c.conn.RemoteAddr().String())
103 log.Printf("Can't parse RemoteAddr %q: %v", hostPort, err)
106 client.ReplyNicknamed("311", *c.nickname, *c.username, hostPort, "*", *c.realname)
107 client.ReplyNicknamed("312", *c.nickname, *hostname, *hostname)
109 client.ReplyNicknamed("301", *c.nickname, *c.away)
111 subscriptions = make([]string, 0)
113 for _, room = range rooms {
114 for subscriber = range room.members {
115 if *subscriber.nickname == nickname {
116 subscriptions = append(subscriptions, *room.name)
121 sort.Strings(subscriptions)
122 client.ReplyNicknamed("319", *c.nickname, strings.Join(subscriptions, " "))
123 client.ReplyNicknamed("318", *c.nickname, "End of /WHOIS list")
127 func SendList(client *Client, cols []string) {
130 if (len(cols) > 1) && (cols[1] != "") {
131 rs = strings.Split(strings.Split(cols[1], " ")[0], ",")
133 rs = make([]string, 0)
135 for r = range rooms {
143 for _, r = range rs {
145 if room, found = rooms[r]; found {
146 client.ReplyNicknamed(
149 fmt.Sprintf("%d", len(room.members)),
155 client.ReplyNicknamed("323", "End of /LIST")
158 // Unregistered client workflow processor. Unregistered client:
160 // * only QUIT, NICK and USER commands are processed
161 // * other commands are quietly ignored
162 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
163 func ClientRegister(client *Client, cmd string, cols []string) {
166 if len(cols) == 1 || len(cols[1]) < 1 {
167 client.ReplyNotEnoughParameters("PASS")
170 password := strings.TrimPrefix(cols[1], ":")
171 client.password = &password
173 if len(cols) == 1 || len(cols[1]) < 1 {
174 client.ReplyParts("431", "No nickname given")
178 // Compatibility with some clients prepending colons to nickname
179 nickname = strings.TrimPrefix(nickname, ":")
180 nickname = strings.ToLower(nickname)
182 for existingClient := range clients {
183 if *existingClient.nickname == nickname {
185 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
190 if !RENickname.MatchString(nickname) {
191 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
194 client.nickname = &nickname
197 client.ReplyNotEnoughParameters("USER")
200 args := strings.SplitN(cols[1], " ", 4)
202 client.ReplyNotEnoughParameters("USER")
205 client.username = &args[0]
206 realname := strings.TrimLeft(args[3], ":")
207 client.realname = &realname
209 if *client.nickname != "*" && *client.username != "" {
210 if passwords != nil && *passwords != "" {
211 if client.password == nil {
212 client.ReplyParts("462", "You may not register")
216 contents, err := ioutil.ReadFile(*passwords)
218 log.Fatalf("Can no read passwords file %s: %s", *passwords, err)
221 for _, entry := range strings.Split(string(contents), "\n") {
225 if lp := strings.Split(entry, ":"); lp[0] == *client.nickname && lp[1] != *client.password {
226 client.ReplyParts("462", "You may not register")
232 client.registered = true
233 client.ReplyNicknamed("001", "Hi, welcome to IRC")
234 client.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+version)
235 client.ReplyNicknamed("003", "This server was created sometime")
236 client.ReplyNicknamed("004", *hostname+" goircd o o")
239 log.Println(client, "logged in")
243 // Register new room in Daemon. Create an object, events sink, save pointers
244 // to corresponding daemon's places and start room's processor goroutine.
245 func RoomRegister(name string) (*Room, chan ClientEvent) {
246 roomNew := NewRoom(name)
247 roomSink := make(chan ClientEvent)
249 rooms[name] = roomNew
250 roomSinks[roomNew] = roomSink
252 go roomNew.Processor(roomSink)
254 return roomNew, roomSink
257 func HandlerJoin(client *Client, cmd string) {
258 args := strings.Split(cmd, " ")
259 rs := strings.Split(args[0], ",")
262 keys = strings.Split(args[1], ",")
264 keys = make([]string, 0)
266 var roomExisting *Room
267 var roomSink chan ClientEvent
269 for n, room := range rs {
270 if !RoomNameValid(room) {
271 client.ReplyNoChannel(room)
275 if (n < len(keys)) && (keys[n] != "") {
281 for roomExisting, roomSink = range roomSinks {
282 if room == *roomExisting.name {
284 if (*roomExisting.key != "") && (*roomExisting.key != key) {
287 roomSink <- ClientEvent{client, EventNew, ""}
292 roomNew, roomSink = RoomRegister(room)
293 log.Println("Room", roomNew, "created")
298 roomSink <- ClientEvent{client, EventNew, ""}
301 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
306 func Processor(events chan ClientEvent, finished chan struct{}) {
310 time.Sleep(10 * time.Second)
311 events <- ClientEvent{eventType: EventTick}
314 for event := range events {
316 client := event.client
317 switch event.eventType {
320 for c := range clients {
321 if c.recvTimestamp.Add(PingTimeout).Before(now) {
322 log.Println(c, "ping timeout")
326 if c.sendTimestamp.Add(PingThreshold).Before(now) {
328 c.Msg("PING :" + *hostname)
329 c.sendTimestamp = time.Now()
331 log.Println(c, "ping timeout")
338 for rn, r := range rooms {
339 if *statedir == "" && len(r.members) == 0 {
340 log.Println(rn, "emptied room")
349 for _, sink := range roomSinks {
350 sink <- ClientEvent{eventType: EventTerm}
358 clients[client] = struct{}{}
362 delete(clients, client)
365 for _, roomSink := range roomSinks {
370 cols := strings.SplitN(event.text, " ", 2)
371 cmd := strings.ToUpper(cols[0])
373 log.Println(client, "command", cmd)
376 log.Println(client, "quit")
380 if !client.registered {
381 ClientRegister(client, cmd, cols)
385 client.recvTimestamp = now
391 client.ReplyNicknamed("305", "You are no longer marked as being away")
394 msg := strings.TrimLeft(cols[1], ":")
396 client.ReplyNicknamed("306", "You have been marked as being away")
398 if len(cols) == 1 || len(cols[1]) < 1 {
399 client.ReplyNotEnoughParameters("JOIN")
402 HandlerJoin(client, cols[1])
404 SendList(client, cols)
408 if len(cols) == 1 || len(cols[1]) < 1 {
409 client.ReplyNotEnoughParameters("MODE")
412 cols = strings.SplitN(cols[1], " ", 2)
413 if cols[0] == *client.username {
415 client.Msg("221 " + *client.nickname + " +")
417 client.ReplyNicknamed("501", "Unknown MODE flag")
423 r, found := rooms[room]
425 client.ReplyNoChannel(room)
430 roomSinks[r] <- ClientEvent{client, EventMode, ""}
432 roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
438 if len(cols) == 1 || len(cols[1]) < 1 {
439 client.ReplyNotEnoughParameters("PART")
442 rs := strings.Split(cols[1], " ")[0]
444 for _, room := range strings.Split(rs, ",") {
445 if r, found := rooms[room]; found {
446 roomSinks[r] <- ClientEvent{client, EventDel, ""}
449 client.ReplyNoChannel(room)
456 client.ReplyNicknamed("409", "No origin specified")
459 client.Reply(fmt.Sprintf("PONG %s :%s", *hostname, cols[1]))
462 case "NOTICE", "PRIVMSG":
464 client.ReplyNicknamed("411", "No recipient given ("+cmd+")")
467 cols = strings.SplitN(cols[1], " ", 2)
469 client.ReplyNicknamed("412", "No text to send")
473 target := strings.ToLower(cols[0])
475 for c := range clients {
476 if *c.nickname == target {
477 msg = fmt.Sprintf(":%s %s %s %s", client, cmd, *c.nickname, cols[1])
480 client.ReplyNicknamed("301", *c.nickname, *c.away)
490 if r, found := rooms[target]; found {
491 roomSinks[r] <- ClientEvent{
494 cmd + " " + strings.TrimLeft(cols[1], ":"),
497 client.ReplyNoNickChan(target)
502 client.ReplyNotEnoughParameters("TOPIC")
505 cols = strings.SplitN(cols[1], " ", 2)
507 r, found := rooms[cols[0]]
510 client.ReplyNoChannel(cols[0])
520 roomSinks[r] <- ClientEvent{client, EventTopic, change}
523 if len(cols) == 1 || len(cols[1]) < 1 {
524 client.ReplyNotEnoughParameters("WHO")
527 room := strings.Split(cols[1], " ")[0]
529 if r, found := rooms[room]; found {
530 roomSinks[r] <- ClientEvent{client, EventWho, ""}
532 client.ReplyNoChannel(room)
536 if len(cols) == 1 || len(cols[1]) < 1 {
537 client.ReplyNotEnoughParameters("WHOIS")
540 cols := strings.Split(cols[1], " ")
541 nicknames := strings.Split(cols[len(cols)-1], ",")
542 SendWhois(client, nicknames)
544 if len(cols) == 1 || len(cols[1]) < 1 {
545 client.ReplyNotEnoughParameters("ISON")
548 nicksKnown := make(map[string]struct{})
550 for c := range clients {
551 nicksKnown[*c.nickname] = struct{}{}
554 var nicksExists []string
555 for _, nickname := range strings.Split(cols[1], " ") {
556 if _, exists := nicksKnown[nickname]; exists {
557 nicksExists = append(nicksExists, nickname)
560 client.ReplyNicknamed("303", strings.Join(nicksExists, " "))
568 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", version, debug, *hostname))
570 client.ReplyNicknamed("421", cmd, "Unknown command")