2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2015 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/>.
33 // Max time deadline for client's unresponsiveness
34 PingTimeout = time.Second * 180
35 // Max idle client's time before PING are sent
36 PingThreshold = time.Second * 90
37 // Client's aliveness check period
38 AlivenessCheck = time.Second * 10
42 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
51 clients map[*Client]bool
52 clientAliveness map[*Client]*ClientAlivenessState
53 rooms map[string]*Room
54 roomSinks map[*Room]chan ClientEvent
55 lastAlivenessCheck time.Time
56 logSink chan<- LogEvent
57 stateSink chan<- StateEvent
60 func NewDaemon(version string, hostname, motd, passwords *string, logSink chan<- LogEvent, stateSink chan<- StateEvent) *Daemon {
67 daemon.clients = make(map[*Client]bool)
68 daemon.clientAliveness = make(map[*Client]*ClientAlivenessState)
69 daemon.rooms = make(map[string]*Room)
70 daemon.roomSinks = make(map[*Room]chan ClientEvent)
71 daemon.logSink = logSink
72 daemon.stateSink = stateSink
76 func (daemon *Daemon) SendLusers(client *Client) {
78 for client := range daemon.clients {
79 if client.registered {
83 client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
86 func (daemon *Daemon) SendMotd(client *Client) {
87 if daemon.motd == nil || *daemon.motd == "" {
88 client.ReplyNicknamed("422", "MOTD File is missing")
92 motd, err := ioutil.ReadFile(*daemon.motd)
94 log.Printf("Can not read motd file %s: %v", *daemon.motd, err)
95 client.ReplyNicknamed("422", "Error reading MOTD File")
99 client.ReplyNicknamed("375", "- "+*daemon.hostname+" Message of the day -")
100 for _, s := range strings.Split(strings.Trim(string(motd), "\n"), "\n") {
101 client.ReplyNicknamed("372", "- "+string(s))
103 client.ReplyNicknamed("376", "End of /MOTD command")
106 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
107 for _, nickname := range nicknames {
108 nickname = strings.ToLower(nickname)
110 for c := range daemon.clients {
111 if strings.ToLower(c.nickname) != nickname {
115 h := c.conn.RemoteAddr().String()
116 h, _, err := net.SplitHostPort(h)
118 log.Printf("Can't parse RemoteAddr %q: %v", h, err)
121 client.ReplyNicknamed("311", c.nickname, c.username, h, "*", c.realname)
122 client.ReplyNicknamed("312", c.nickname, *daemon.hostname, *daemon.hostname)
124 client.ReplyNicknamed("301", c.nickname, *c.away)
126 subscriptions := []string{}
127 for _, room := range daemon.rooms {
128 for subscriber := range room.members {
129 if subscriber.nickname == nickname {
130 subscriptions = append(subscriptions, room.name)
134 sort.Strings(subscriptions)
135 client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
136 client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
139 client.ReplyNoNickChan(nickname)
144 func (daemon *Daemon) SendList(client *Client, cols []string) {
146 if (len(cols) > 1) && (cols[1] != "") {
147 rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
150 for room := range daemon.rooms {
151 rooms = append(rooms, room)
155 for _, room := range rooms {
156 r, found := daemon.rooms[room]
158 client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
161 client.ReplyNicknamed("323", "End of /LIST")
164 // Unregistered client workflow processor. Unregistered client:
166 // * only QUIT, NICK and USER commands are processed
167 // * other commands are quietly ignored
168 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
169 func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
172 if len(cols) == 1 || len(cols[1]) < 1 {
173 client.ReplyNotEnoughParameters("PASS")
176 client.password = cols[1]
178 if len(cols) == 1 || len(cols[1]) < 1 {
179 client.ReplyParts("431", "No nickname given")
183 if (strings.HasPrefix(nickname, ":")) {
184 nickname = strings.TrimPrefix(nickname, ":")
186 for existingClient := range daemon.clients {
187 if existingClient.nickname == nickname {
188 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
192 if !RENickname.MatchString(nickname) {
193 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
196 client.nickname = nickname
199 client.ReplyNotEnoughParameters("USER")
202 args := strings.SplitN(cols[1], " ", 4)
204 client.ReplyNotEnoughParameters("USER")
207 client.username = args[0]
208 client.realname = strings.TrimLeft(args[3], ":")
210 if client.nickname != "*" && client.username != "" {
211 if daemon.passwords != nil && *daemon.passwords != "" {
212 if client.password == "" {
213 client.ReplyParts("462", "You may not register")
217 contents, err := ioutil.ReadFile(*daemon.passwords)
219 log.Fatalf("Can no read passwords file %s: %s", *daemon.passwords, err)
222 for _, entry := range strings.Split(string(contents), "\n") {
226 if lp := strings.Split(entry, ":"); lp[0] == client.nickname && lp[1] != client.password {
227 client.ReplyParts("462", "You may not register")
234 client.registered = true
235 client.ReplyNicknamed("001", "Hi, welcome to IRC")
236 client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
237 client.ReplyNicknamed("003", "This server was created sometime")
238 client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
239 daemon.SendLusers(client)
240 daemon.SendMotd(client)
241 log.Println(client, "logged in")
245 // Register new room in Daemon. Create an object, events sink, save pointers
246 // to corresponding daemon's places and start room's processor goroutine.
247 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
248 roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
249 roomNew.Verbose = daemon.Verbose
250 roomSink := make(chan ClientEvent)
251 daemon.rooms[name] = roomNew
252 daemon.roomSinks[roomNew] = roomSink
253 go roomNew.Processor(roomSink)
254 return roomNew, roomSink
257 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
258 args := strings.Split(cmd, " ")
259 rooms := strings.Split(args[0], ",")
262 keys = strings.Split(args[1], ",")
266 for n, room := range rooms {
267 if !RoomNameValid(room) {
268 client.ReplyNoChannel(room)
272 if (n < len(keys)) && (keys[n] != "") {
279 for roomExisting, roomSink := range daemon.roomSinks {
280 if room == roomExisting.name {
281 if (roomExisting.key != "") && (roomExisting.key != key) {
284 roomSink <- ClientEvent{client, EventNew, ""}
291 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
293 if denied || joined {
296 roomNew, roomSink := daemon.RoomRegister(room)
297 log.Println("Room", roomNew, "created")
302 roomSink <- ClientEvent{client, EventNew, ""}
306 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
307 for event := range events {
309 client := event.client
311 // Check for clients aliveness
312 if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
313 for c := range daemon.clients {
314 aliveness, alive := daemon.clientAliveness[c]
318 if aliveness.timestamp.Add(PingTimeout).Before(now) {
319 log.Println(c, "ping timeout")
323 if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
325 c.Msg("PING :" + *daemon.hostname)
326 aliveness.pingSent = true
328 log.Println(c, "ping timeout")
333 daemon.lastAlivenessCheck = now
336 switch event.eventType {
338 daemon.clients[client] = true
339 daemon.clientAliveness[client] = &ClientAlivenessState{
344 delete(daemon.clients, client)
345 delete(daemon.clientAliveness, client)
346 for _, roomSink := range daemon.roomSinks {
350 cols := strings.SplitN(event.text, " ", 2)
351 command := strings.ToUpper(cols[0])
353 log.Println(client, "command", command)
355 if command == "QUIT" {
356 log.Println(client, "quit")
357 delete(daemon.clients, client)
358 delete(daemon.clientAliveness, client)
362 if !client.registered {
363 daemon.ClientRegister(client, command, cols)
370 client.ReplyNicknamed("305", "You are no longer marked as being away")
373 msg := strings.TrimLeft(cols[1], ":")
375 client.ReplyNicknamed("306", "You have been marked as being away")
377 if len(cols) == 1 || len(cols[1]) < 1 {
378 client.ReplyNotEnoughParameters("JOIN")
381 daemon.HandlerJoin(client, cols[1])
383 daemon.SendList(client, cols)
385 daemon.SendLusers(client)
387 if len(cols) == 1 || len(cols[1]) < 1 {
388 client.ReplyNotEnoughParameters("MODE")
391 cols = strings.SplitN(cols[1], " ", 2)
392 if cols[0] == client.username {
394 client.Msg("221 " + client.nickname + " +")
396 client.ReplyNicknamed("501", "Unknown MODE flag")
401 r, found := daemon.rooms[room]
403 client.ReplyNoChannel(room)
407 daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
409 daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
412 go daemon.SendMotd(client)
414 if len(cols) == 1 || len(cols[1]) < 1 {
415 client.ReplyNotEnoughParameters("PART")
418 for _, room := range strings.Split(cols[1], ",") {
419 r, found := daemon.rooms[room]
421 client.ReplyNoChannel(room)
424 daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
428 client.ReplyNicknamed("409", "No origin specified")
431 client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
434 case "NOTICE", "PRIVMSG":
436 client.ReplyNicknamed("411", "No recipient given ("+command+")")
439 cols = strings.SplitN(cols[1], " ", 2)
441 client.ReplyNicknamed("412", "No text to send")
445 target := strings.ToLower(cols[0])
446 for c := range daemon.clients {
447 if c.nickname == target {
448 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
451 client.ReplyNicknamed("301", c.nickname, *c.away)
459 r, found := daemon.rooms[target]
461 client.ReplyNoNickChan(target)
463 daemon.roomSinks[r] <- ClientEvent{
466 command + " " + strings.TrimLeft(cols[1], ":"),
470 client.ReplyNotEnoughParameters("TOPIC")
473 cols = strings.SplitN(cols[1], " ", 2)
474 r, found := daemon.rooms[cols[0]]
476 client.ReplyNoChannel(cols[0])
485 daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
487 if len(cols) == 1 || len(cols[1]) < 1 {
488 client.ReplyNotEnoughParameters("WHO")
491 room := strings.Split(cols[1], " ")[0]
492 r, found := daemon.rooms[room]
494 client.ReplyNoChannel(room)
497 daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
499 if len(cols) == 1 || len(cols[1]) < 1 {
500 client.ReplyNotEnoughParameters("WHOIS")
503 cols := strings.Split(cols[1], " ")
504 nicknames := strings.Split(cols[len(cols)-1], ",")
505 daemon.SendWhois(client, nicknames)
513 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
515 client.ReplyNicknamed("421", command, "Unknown command")
518 if aliveness, alive := daemon.clientAliveness[client]; alive {
519 aliveness.timestamp = now
520 aliveness.pingSent = false