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)
114 subscriptions := []string{}
115 for _, room := range daemon.rooms {
116 for subscriber := range room.members {
117 if subscriber.nickname == nickname {
118 subscriptions = append(subscriptions, room.name)
122 sort.Strings(subscriptions)
123 client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
124 client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
127 client.ReplyNoNickChan(nickname)
132 func (daemon *Daemon) SendList(client *Client, cols []string) {
134 if (len(cols) > 1) && (cols[1] != "") {
135 rooms = strings.Split(strings.Split(cols[1], " ")[0], ",")
138 for room := range daemon.rooms {
139 rooms = append(rooms, room)
143 for _, room := range rooms {
144 r, found := daemon.rooms[room]
146 client.ReplyNicknamed("322", room, fmt.Sprintf("%d", len(r.members)), r.topic)
149 client.ReplyNicknamed("323", "End of /LIST")
152 // Unregistered client workflow processor. Unregistered client:
154 // * only QUIT, NICK and USER commands are processed
155 // * other commands are quietly ignored
156 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
157 func (daemon *Daemon) ClientRegister(client *Client, command string, cols []string) {
160 if len(cols) == 1 || len(cols[1]) < 1 {
161 client.ReplyNotEnoughParameters("PASS")
164 client.password = cols[1]
166 if len(cols) == 1 || len(cols[1]) < 1 {
167 client.ReplyParts("431", "No nickname given")
171 for existingClient := range daemon.clients {
172 if existingClient.nickname == nickname {
173 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
177 if !RENickname.MatchString(nickname) {
178 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
181 client.nickname = nickname
184 client.ReplyNotEnoughParameters("USER")
187 args := strings.SplitN(cols[1], " ", 4)
189 client.ReplyNotEnoughParameters("USER")
192 client.username = args[0]
193 client.realname = strings.TrimLeft(args[3], ":")
195 if client.nickname != "*" && client.username != "" {
196 if daemon.passwords != nil && *daemon.passwords != "" {
197 if client.password == "" {
198 client.ReplyParts("462", "You may not register")
202 contents, err := ioutil.ReadFile(*daemon.passwords)
204 log.Fatalf("Can no read passwords file %s: %s", *daemon.passwords, err)
207 for _, entry := range strings.Split(string(contents), "\n") {
211 if lp := strings.Split(entry, ":"); lp[0] == client.nickname && lp[1] != client.password {
212 client.ReplyParts("462", "You may not register")
219 client.registered = true
220 client.ReplyNicknamed("001", "Hi, welcome to IRC")
221 client.ReplyNicknamed("002", "Your host is "+*daemon.hostname+", running goircd "+daemon.version)
222 client.ReplyNicknamed("003", "This server was created sometime")
223 client.ReplyNicknamed("004", *daemon.hostname+" goircd o o")
224 daemon.SendLusers(client)
225 daemon.SendMotd(client)
226 log.Println(client, "logged in")
230 // Register new room in Daemon. Create an object, events sink, save pointers
231 // to corresponding daemon's places and start room's processor goroutine.
232 func (daemon *Daemon) RoomRegister(name string) (*Room, chan<- ClientEvent) {
233 roomNew := NewRoom(daemon.hostname, name, daemon.logSink, daemon.stateSink)
234 roomNew.Verbose = daemon.Verbose
235 roomSink := make(chan ClientEvent)
236 daemon.rooms[name] = roomNew
237 daemon.roomSinks[roomNew] = roomSink
238 go roomNew.Processor(roomSink)
239 return roomNew, roomSink
242 func (daemon *Daemon) HandlerJoin(client *Client, cmd string) {
243 args := strings.Split(cmd, " ")
244 rooms := strings.Split(args[0], ",")
247 keys = strings.Split(args[1], ",")
251 for n, room := range rooms {
252 if !RoomNameValid(room) {
253 client.ReplyNoChannel(room)
257 if (n < len(keys)) && (keys[n] != "") {
264 for roomExisting, roomSink := range daemon.roomSinks {
265 if room == roomExisting.name {
266 if (roomExisting.key != "") && (roomExisting.key != key) {
269 roomSink <- ClientEvent{client, EventNew, ""}
276 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
278 if denied || joined {
281 roomNew, roomSink := daemon.RoomRegister(room)
282 log.Println("Room", roomNew, "created")
287 roomSink <- ClientEvent{client, EventNew, ""}
291 func (daemon *Daemon) Processor(events <-chan ClientEvent) {
292 for event := range events {
294 client := event.client
296 // Check for clients aliveness
297 if daemon.lastAlivenessCheck.Add(AlivenessCheck).Before(now) {
298 for c := range daemon.clients {
299 aliveness, alive := daemon.clientAliveness[c]
303 if aliveness.timestamp.Add(PingTimeout).Before(now) {
304 log.Println(c, "ping timeout")
308 if !aliveness.pingSent && aliveness.timestamp.Add(PingThreshold).Before(now) {
310 c.Msg("PING :" + *daemon.hostname)
311 aliveness.pingSent = true
313 log.Println(c, "ping timeout")
318 daemon.lastAlivenessCheck = now
321 switch event.eventType {
323 daemon.clients[client] = true
324 daemon.clientAliveness[client] = &ClientAlivenessState{pingSent: false, timestamp: now}
326 delete(daemon.clients, client)
327 delete(daemon.clientAliveness, client)
328 for _, roomSink := range daemon.roomSinks {
332 cols := strings.SplitN(event.text, " ", 2)
333 command := strings.ToUpper(cols[0])
335 log.Println(client, "command", command)
337 if command == "QUIT" {
338 log.Println(client, "quit")
339 delete(daemon.clients, client)
340 delete(daemon.clientAliveness, client)
344 if !client.registered {
345 daemon.ClientRegister(client, command, cols)
352 if len(cols) == 1 || len(cols[1]) < 1 {
353 client.ReplyNotEnoughParameters("JOIN")
356 daemon.HandlerJoin(client, cols[1])
358 daemon.SendList(client, cols)
360 daemon.SendLusers(client)
362 if len(cols) == 1 || len(cols[1]) < 1 {
363 client.ReplyNotEnoughParameters("MODE")
366 cols = strings.SplitN(cols[1], " ", 2)
367 if cols[0] == client.username {
369 client.Msg("221 " + client.nickname + " +")
371 client.ReplyNicknamed("501", "Unknown MODE flag")
376 r, found := daemon.rooms[room]
378 client.ReplyNoChannel(room)
382 daemon.roomSinks[r] <- ClientEvent{client, EventMode, ""}
384 daemon.roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
387 go daemon.SendMotd(client)
389 if len(cols) == 1 || len(cols[1]) < 1 {
390 client.ReplyNotEnoughParameters("PART")
393 for _, room := range strings.Split(cols[1], ",") {
394 r, found := daemon.rooms[room]
396 client.ReplyNoChannel(room)
399 daemon.roomSinks[r] <- ClientEvent{client, EventDel, ""}
403 client.ReplyNicknamed("409", "No origin specified")
406 client.Reply(fmt.Sprintf("PONG %s :%s", *daemon.hostname, cols[1]))
409 case "NOTICE", "PRIVMSG":
411 client.ReplyNicknamed("411", "No recipient given ("+command+")")
414 cols = strings.SplitN(cols[1], " ", 2)
416 client.ReplyNicknamed("412", "No text to send")
420 target := strings.ToLower(cols[0])
421 for c := range daemon.clients {
422 if c.nickname == target {
423 msg = fmt.Sprintf(":%s %s %s %s", client, command, c.nickname, cols[1])
431 r, found := daemon.rooms[target]
433 client.ReplyNoNickChan(target)
435 daemon.roomSinks[r] <- ClientEvent{client, EventMsg, command + " " + strings.TrimLeft(cols[1], ":")}
438 client.ReplyNotEnoughParameters("TOPIC")
441 cols = strings.SplitN(cols[1], " ", 2)
442 r, found := daemon.rooms[cols[0]]
444 client.ReplyNoChannel(cols[0])
453 daemon.roomSinks[r] <- ClientEvent{client, EventTopic, change}
455 if len(cols) == 1 || len(cols[1]) < 1 {
456 client.ReplyNotEnoughParameters("WHO")
459 room := strings.Split(cols[1], " ")[0]
460 r, found := daemon.rooms[room]
462 client.ReplyNoChannel(room)
465 daemon.roomSinks[r] <- ClientEvent{client, EventWho, ""}
467 if len(cols) == 1 || len(cols[1]) < 1 {
468 client.ReplyNotEnoughParameters("WHOIS")
471 cols := strings.Split(cols[1], " ")
472 nicknames := strings.Split(cols[len(cols)-1], ",")
473 daemon.SendWhois(client, nicknames)
481 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", daemon.version, debug, *daemon.hostname))
483 client.ReplyNicknamed("421", command, "Unknown command")
486 if aliveness, alive := daemon.clientAliveness[client]; alive {
487 aliveness.timestamp = now
488 aliveness.pingSent = false