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 // Compatibility with some clients prepending colons to nickname
184 nickname = strings.TrimPrefix(nickname, ":")
185 for existingClient := range daemon.clients {
186 if existingClient.nickname == nickname {
187 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
191 if !RENickname.MatchString(nickname) {
192 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
195 client.nickname = nickname
198 client.ReplyNotEnoughParameters("USER")
201 args := strings.SplitN(cols[1], " ", 4)
203 client.ReplyNotEnoughParameters("USER")
206 client.username = args[0]
207 client.realname = strings.TrimLeft(args[3], ":")
209 if client.nickname != "*" && client.username != "" {
210 if daemon.passwords != nil && *daemon.passwords != "" {
211 if client.password == "" {
212 client.ReplyParts("462", "You may not register")
216 contents, err := ioutil.ReadFile(*daemon.passwords)
218 log.Fatalf("Can no read passwords file %s: %s", *daemon.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")
233 client.registered = true
234 client.ReplyNicknamed("001", "Hi, welcome to IRC")
235 client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
236 client.ReplyNicknamed("003", "This server was created sometime")
237 client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
238 daemon.SendLusers(client)
239 daemon.SendMotd(client)
240 log.Println(client, "logged in")
244 // Register new room in Daemon. Create an object, events sink, save pointers
245 // to corresponding daemon's places and start room's processor goroutine.
246 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
247 roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
248 roomNew.Verbose = daemon.Verbose
249 roomSink := make(chan ClientEvent)
250 daemon.rooms[name] = roomNew
251 daemon.roomSinks[roomNew] = roomSink
252 go roomNew.Processor(roomSink)
253 return roomNew, roomSink
256 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
257 args := strings.Split(cmd, " ")
258 rooms := strings.Split(args[0], ",")
261 keys = strings.Split(args[1], ",")
265 for n, room := range rooms {
266 if !RoomNameValid(room) {
267 client.ReplyNoChannel(room)
271 if (n < len(keys)) && (keys[n] != "") {
278 for roomExisting, roomSink := range daemon.roomSinks {
279 if room == roomExisting.name {
280 if (roomExisting.key != "") && (roomExisting.key != key) {
283 roomSink <- ClientEvent{client, EventNew, ""}
290 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
292 if denied || joined {
295 roomNew, roomSink := daemon.RoomRegister(room)
296 log.Println("Room", roomNew, "created")
301 roomSink <- ClientEvent{client, EventNew, ""}
305 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
306 for event := range events {
308 client := event.client
310 // Check for clients aliveness
311 if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
312 for c := range daemon.clients {
313 aliveness, alive := daemon.clientAliveness[c]
317 if aliveness.timestamp.Add(PingTimeout).Before(now) {
318 log.Println(c, "ping timeout")
322 if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
324 c.Msg("PING :" + *daemon.hostname)
325 aliveness.pingSent = true
327 log.Println(c, "ping timeout")
332 daemon.lastAlivenessCheck = now
335 switch event.eventType {
337 daemon.clients[client] = true
338 daemon.clientAliveness[client] = &ClientAlivenessState{
343 delete(daemon.clients, client)
344 delete(daemon.clientAliveness, client)
345 for _, roomSink := range daemon.roomSinks {
349 cols := strings.SplitN(event.text, " ", 2)
350 command := strings.ToUpper(cols[0])
352 log.Println(client, "command", command)
354 if command == "QUIT" {
355 log.Println(client, "quit")
356 delete(daemon.clients, client)
357 delete(daemon.clientAliveness, client)
361 if !client.registered {
362 daemon.ClientRegister(client, command, cols)
369 client.ReplyNicknamed("305", "You are no longer marked as being away")
372 msg := strings.TrimLeft(cols[1], ":")
374 client.ReplyNicknamed("306", "You have been marked as being away")
376 if len(cols) == 1 || len(cols[1]) < 1 {
377 client.ReplyNotEnoughParameters("JOIN")
380 daemon.HandlerJoin(client, cols[1])
382 daemon.SendList(client, cols)
384 daemon.SendLusers(client)
386 if len(cols) == 1 || len(cols[1]) < 1 {
387 client.ReplyNotEnoughParameters("MODE")
390 cols = strings.SplitN(cols[1], " ", 2)
391 if cols[0] == client.username {
393 client.Msg("221 " + client.nickname + " +")
395 client.ReplyNicknamed("501", "Unknown MODE flag")
400 r, found := daemon.rooms[room]
402 client.ReplyNoChannel(room)
406 daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
408 daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
411 go daemon.SendMotd(client)
413 if len(cols) == 1 || len(cols[1]) < 1 {
414 client.ReplyNotEnoughParameters("PART")
417 for _, room := range strings.Split(cols[1], ",") {
418 r, found := daemon.rooms[room]
420 client.ReplyNoChannel(room)
423 daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
427 client.ReplyNicknamed("409", "No origin specified")
430 client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
433 case "NOTICE", "PRIVMSG":
435 client.ReplyNicknamed("411", "No recipient given ("+command+")")
438 cols = strings.SplitN(cols[1], " ", 2)
440 client.ReplyNicknamed("412", "No text to send")
444 target := strings.ToLower(cols[0])
445 for c := range daemon.clients {
446 if c.nickname == target {
447 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
450 client.ReplyNicknamed("301", c.nickname, *c.away)
458 r, found := daemon.rooms[target]
460 client.ReplyNoNickChan(target)
462 daemon.roomSinks[r] <- ClientEvent{
465 command + " " + strings.TrimLeft(cols[1], ":"),
469 client.ReplyNotEnoughParameters("TOPIC")
472 cols = strings.SplitN(cols[1], " ", 2)
473 r, found := daemon.rooms[cols[0]]
475 client.ReplyNoChannel(cols[0])
484 daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
486 if len(cols) == 1 || len(cols[1]) < 1 {
487 client.ReplyNotEnoughParameters("WHO")
490 room := strings.Split(cols[1], " ")[0]
491 r, found := daemon.rooms[room]
493 client.ReplyNoChannel(room)
496 daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
498 if len(cols) == 1 || len(cols[1]) < 1 {
499 client.ReplyNotEnoughParameters("WHOIS")
502 cols := strings.Split(cols[1], " ")
503 nicknames := strings.Split(cols[len(cols)-1], ",")
504 daemon.SendWhois(client, nicknames)
512 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
514 client.ReplyNicknamed("421", command, "Unknown command")
517 if aliveness, alive := daemon.clientAliveness[client]; alive {
518 aliveness.timestamp = now
519 aliveness.pingSent = false