2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014 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/>.
32 PingTimeout = time.Second * 180 // Max time deadline for client's unresponsiveness
33 PingThreshold = time.Second * 90 // Max idle client's time before PING are sent
34 AlivenessCheck = time.Second * 10 // Client's aliveness check period
38 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,9}$")
47 clients map[*Client]bool
48 clientAliveness map[*Client]*ClientAlivenessState
49 rooms map[string]*Room
50 roomSinks map[*Room]chan ClientEvent
51 lastAlivenessCheck time.Time
52 logSink chan<- LogEvent
53 stateSink chan<- StateEvent
56 func NewDaemon(version string, hostname, motd, passwords *string, logSink chan<- LogEvent, stateSink chan<- StateEvent) *Daemon {
57 daemon := Daemon{version: version, hostname: hostname, motd: motd, passwords: passwords}
58 daemon.clients = make(map[*Client]bool)
59 daemon.clientAliveness = make(map[*Client]*ClientAlivenessState)
60 daemon.rooms = make(map[string]*Room)
61 daemon.roomSinks = make(map[*Room]chan ClientEvent)
62 daemon.logSink = logSink
63 daemon.stateSink = stateSink
67 func (daemon *Daemon) SendLusers(client *Client) {
69 for client := range daemon.clients {
70 if client.registered {
74 client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
77 func (daemon *Daemon) SendMotd(client *Client) {
78 if daemon.motd == nil || *daemon.motd == "" {
79 client.ReplyNicknamed("422", "MOTD File is missing")
83 motd, err := ioutil.ReadFile(*daemon.motd)
85 log.Printf("Can not read motd file %s: %v", *daemon.motd, err)
86 client.ReplyNicknamed("422", "Error reading MOTD File")
90 client.ReplyNicknamed("375", "- "+*daemon.hostname+" Message of the day -")
91 for _, s := range strings.Split(strings.Trim(string(motd), "\n"), "\n") {
92 client.ReplyNicknamed("372", "- "+string(s))
94 client.ReplyNicknamed("376", "End of /MOTD command")
97 func (daemon *Daemon) SendWhois(client *Client, nicknames []string) {
98 for _, nickname := range nicknames {
99 nickname = strings.ToLower(nickname)
101 for c := range daemon.clients {
102 if strings.ToLower(c.nickname) != nickname {
106 h := c.conn.RemoteAddr().String()
107 h, _, err := net.SplitHostPort(h)
109 log.Printf("Can't parse RemoteAddr %q: %v", h, err)
112 client.ReplyNicknamed("311", c.nickname, c.username, h, "*", c.realname)
113 client.ReplyNicknamed("312", c.nickname, *daemon.hostname, *daemon.hostname)
115 client.ReplyNicknamed("301", c.nickname, *c.away)
117 subscriptions := []string{}
118 for _, room := range daemon.rooms {
119 for subscriber := range room.members {
120 if subscriber.nickname == nickname {
121 subscriptions = append(subscriptions, room.name)
125 sort.Strings(subscriptions)
126 client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
127 client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
130 client.ReplyNoNickChan(nickname)
135 func (daemon *Daemon) SendList(client *Client, cols []string) {
137 if (len(cols) > 1) && (cols[1] != "") {
138 rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
141 for room := range daemon.rooms {
142 rooms = append(rooms, room)
146 for _, room := range rooms {
147 r, found := daemon.rooms[room]
149 client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
152 client.ReplyNicknamed("323", "End of /LIST")
155 // Unregistered client workflow processor. Unregistered client:
157 // * only QUIT, NICK and USER commands are processed
158 // * other commands are quietly ignored
159 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
160 func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
163 if len(cols) == 1 || len(cols[1]) < 1 {
164 client.ReplyNotEnoughParameters("PASS")
167 client.password = cols[1]
169 if len(cols) == 1 || len(cols[1]) < 1 {
170 client.ReplyParts("431", "No nickname given")
174 for existingClient := range daemon.clients {
175 if existingClient.nickname == nickname {
176 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
180 if !RENickname.MatchString(nickname) {
181 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
184 client.nickname = nickname
187 client.ReplyNotEnoughParameters("USER")
190 args := strings.SplitN(cols[1], " ", 4)
192 client.ReplyNotEnoughParameters("USER")
195 client.username = args[0]
196 client.realname = strings.TrimLeft(args[3], ":")
198 if client.nickname != "*" && client.username != "" {
199 if daemon.passwords != nil && *daemon.passwords != "" {
200 if client.password == "" {
201 client.ReplyParts("462", "You may not register")
205 contents, err := ioutil.ReadFile(*daemon.passwords)
207 log.Fatalf("Can no read passwords file %s: %s", *daemon.passwords, err)
210 for _, entry := range strings.Split(string(contents), "\n") {
214 if lp := strings.Split(entry, ":"); lp[0] == client.nickname && lp[1] != client.password {
215 client.ReplyParts("462", "You may not register")
222 client.registered = true
223 client.ReplyNicknamed("001", "Hi, welcome to IRC")
224 client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
225 client.ReplyNicknamed("003", "This server was created sometime")
226 client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
227 daemon.SendLusers(client)
228 daemon.SendMotd(client)
229 log.Println(client, "logged in")
233 // Register new room in Daemon. Create an object, events sink, save pointers
234 // to corresponding daemon's places and start room's processor goroutine.
235 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
236 roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
237 roomNew.Verbose = daemon.Verbose
238 roomSink := make(chan ClientEvent)
239 daemon.rooms[name] = roomNew
240 daemon.roomSinks[roomNew] = roomSink
241 go roomNew.Processor(roomSink)
242 return roomNew, roomSink
245 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
246 args := strings.Split(cmd, " ")
247 rooms := strings.Split(args[0], ",")
250 keys = strings.Split(args[1], ",")
254 for n, room := range rooms {
255 if !RoomNameValid(room) {
256 client.ReplyNoChannel(room)
260 if (n < len(keys)) && (keys[n] != "") {
267 for roomExisting, roomSink := range daemon.roomSinks {
268 if room == roomExisting.name {
269 if (roomExisting.key != "") && (roomExisting.key != key) {
272 roomSink <- ClientEvent{client, EventNew, ""}
279 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
281 if denied || joined {
284 roomNew, roomSink := daemon.RoomRegister(room)
285 log.Println("Room", roomNew, "created")
290 roomSink <- ClientEvent{client, EventNew, ""}
294 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
295 for event := range events {
297 client := event.client
299 // Check for clients aliveness
300 if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
301 for c := range daemon.clients {
302 aliveness, alive := daemon.clientAliveness[c]
306 if aliveness.timestamp.Add(PingTimeout).Before(now) {
307 log.Println(c, "ping timeout")
311 if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
313 c.Msg("PING :" + *daemon.hostname)
314 aliveness.pingSent = true
316 log.Println(c, "ping timeout")
321 daemon.lastAlivenessCheck = now
324 switch event.eventType {
326 daemon.clients[client] = true
327 daemon.clientAliveness[client] = &ClientAlivenessState{pingSent: false, timestamp: now}
329 delete(daemon.clients, client)
330 delete(daemon.clientAliveness, client)
331 for _, roomSink := range daemon.roomSinks {
335 cols := strings.SplitN(event.text, " ", 2)
336 command := strings.ToUpper(cols[0])
338 log.Println(client, "command", command)
340 if command == "QUIT" {
341 log.Println(client, "quit")
342 delete(daemon.clients, client)
343 delete(daemon.clientAliveness, client)
347 if !client.registered {
348 daemon.ClientRegister(client, command, cols)
355 client.ReplyNicknamed("305", "You are no longer marked as being away")
358 msg := strings.TrimLeft(cols[1], ":")
360 client.ReplyNicknamed("306", "You have been marked as being away")
362 if len(cols) == 1 || len(cols[1]) < 1 {
363 client.ReplyNotEnoughParameters("JOIN")
366 daemon.HandlerJoin(client, cols[1])
368 daemon.SendList(client, cols)
370 daemon.SendLusers(client)
372 if len(cols) == 1 || len(cols[1]) < 1 {
373 client.ReplyNotEnoughParameters("MODE")
376 cols = strings.SplitN(cols[1], " ", 2)
377 if cols[0] == client.username {
379 client.Msg("221 " + client.nickname + " +")
381 client.ReplyNicknamed("501", "Unknown MODE flag")
386 r, found := daemon.rooms[room]
388 client.ReplyNoChannel(room)
392 daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
394 daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
397 go daemon.SendMotd(client)
399 if len(cols) == 1 || len(cols[1]) < 1 {
400 client.ReplyNotEnoughParameters("PART")
403 for _, room := range strings.Split(cols[1], ",") {
404 r, found := daemon.rooms[room]
406 client.ReplyNoChannel(room)
409 daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
413 client.ReplyNicknamed("409", "No origin specified")
416 client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
419 case "NOTICE", "PRIVMSG":
421 client.ReplyNicknamed("411", "No recipient given ("+command+")")
424 cols = strings.SplitN(cols[1], " ", 2)
426 client.ReplyNicknamed("412", "No text to send")
430 target := strings.ToLower(cols[0])
431 for c := range daemon.clients {
432 if c.nickname == target {
433 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
436 client.ReplyNicknamed("301", c.nickname, *c.away)
444 r, found := daemon.rooms[target]
446 client.ReplyNoNickChan(target)
448 daemon.roomSinks[r] <- ClientEvent{client, EventMsg, command + " " + strings.TrimLeft(cols[1], ":")}
451 client.ReplyNotEnoughParameters("TOPIC")
454 cols = strings.SplitN(cols[1], " ", 2)
455 r, found := daemon.rooms[cols[0]]
457 client.ReplyNoChannel(cols[0])
466 daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
468 if len(cols) == 1 || len(cols[1]) < 1 {
469 client.ReplyNotEnoughParameters("WHO")
472 room := strings.Split(cols[1], " ")[0]
473 r, found := daemon.rooms[room]
475 client.ReplyNoChannel(room)
478 daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
480 if len(cols) == 1 || len(cols[1]) < 1 {
481 client.ReplyNotEnoughParameters("WHOIS")
484 cols := strings.Split(cols[1], " ")
485 nicknames := strings.Split(cols[len(cols)-1], ",")
486 daemon.SendWhois(client, nicknames)
494 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
496 client.ReplyNicknamed("421", command, "Unknown command")
499 if aliveness, alive := daemon.clientAliveness[client]; alive {
500 aliveness.timestamp = now
501 aliveness.pingSent = false