2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2020 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, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
33 // Max deadline time of client's unresponsiveness
34 PingTimeout = time.Second * 180
35 // Max idle client's time before PING are sent
36 PingThreshold = time.Second * 90
40 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
42 clients map[*Client]struct{} = make(map[*Client]struct{})
44 rooms map[string]*Room = make(map[string]*Room)
46 roomsGroup sync.WaitGroup
47 roomSinks map[*Room]chan ClientEvent = make(map[*Room]chan ClientEvent)
50 func SendLusers(client *Client) {
53 for client := range clients {
54 if client.registered {
59 client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
62 func SendMotd(client *Client) {
64 client.ReplyNicknamed("422", "MOTD File is missing")
67 motdText, err := ioutil.ReadFile(*motd)
69 log.Printf("Can not read motd file %s: %v", *motd, err)
70 client.ReplyNicknamed("422", "Error reading MOTD File")
73 client.ReplyNicknamed("375", "- "+*hostname+" Message of the day -")
74 for _, s := range strings.Split(strings.TrimSuffix(string(motdText), "\n"), "\n") {
75 client.ReplyNicknamed("372", "- "+s)
77 client.ReplyNicknamed("376", "End of /MOTD command")
80 func SendWhois(client *Client, nicknames []string) {
84 var subscriptions []string
86 var subscriber *Client
87 for _, nickname := range nicknames {
88 nickname = strings.ToLower(nickname)
90 for c = range clients {
91 if strings.ToLower(*c.nickname) == nickname {
97 client.ReplyNoNickChan(nickname)
100 hostPort, _, err = net.SplitHostPort(c.conn.RemoteAddr().String())
102 log.Printf("Can't parse RemoteAddr %q: %v", hostPort, err)
105 client.ReplyNicknamed("311", *c.nickname, *c.username, hostPort, "*", *c.realname)
106 client.ReplyNicknamed("312", *c.nickname, *hostname, *hostname)
108 client.ReplyNicknamed("301", *c.nickname, *c.away)
110 subscriptions = make([]string, 0)
112 for _, room = range rooms {
113 for subscriber = range room.members {
114 if *subscriber.nickname == nickname {
115 subscriptions = append(subscriptions, *room.name)
120 sort.Strings(subscriptions)
121 client.ReplyNicknamed("319", *c.nickname, strings.Join(subscriptions, " "))
122 client.ReplyNicknamed("318", *c.nickname, "End of /WHOIS list")
126 func SendList(client *Client, cols []string) {
129 if (len(cols) > 1) && (cols[1] != "") {
130 rs = strings.Split(strings.Split(cols[1], " ")[0], ",")
132 rs = make([]string, 0)
134 for r = range rooms {
142 for _, r = range rs {
144 if room, found = rooms[r]; found {
145 client.ReplyNicknamed(
148 fmt.Sprintf("%d", len(room.members)),
154 client.ReplyNicknamed("323", "End of /LIST")
157 // Unregistered client workflow processor. Unregistered client:
159 // * only QUIT, NICK and USER commands are processed
160 // * other commands are quietly ignored
161 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
162 func ClientRegister(client *Client, cmd string, cols []string) {
165 if len(cols) == 1 || len(cols[1]) < 1 {
166 client.ReplyNotEnoughParameters("PASS")
169 password := strings.TrimPrefix(cols[1], ":")
170 client.password = &password
172 if len(cols) == 1 || len(cols[1]) < 1 {
173 client.ReplyParts("431", "No nickname given")
177 // Compatibility with some clients prepending colons to nickname
178 nickname = strings.TrimPrefix(nickname, ":")
179 nickname = strings.ToLower(nickname)
181 for existingClient := range clients {
182 if *existingClient.nickname == nickname {
184 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
189 if !RENickname.MatchString(nickname) {
190 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
193 client.nickname = &nickname
196 client.ReplyNotEnoughParameters("USER")
199 args := strings.SplitN(cols[1], " ", 4)
201 client.ReplyNotEnoughParameters("USER")
204 client.username = &args[0]
205 realname := strings.TrimLeft(args[3], ":")
206 client.realname = &realname
208 if *client.nickname != "*" && *client.username != "" {
209 if passwords != nil && *passwords != "" {
210 if client.password == nil {
211 client.ReplyParts("462", "You may not register")
215 contents, err := ioutil.ReadFile(*passwords)
217 log.Fatalf("Can no read passwords file %s: %s", *passwords, err)
220 for _, entry := range strings.Split(string(contents), "\n") {
224 if lp := strings.Split(entry, ":"); lp[0] == *client.nickname && lp[1] != *client.password {
225 client.ReplyParts("462", "You may not register")
231 client.registered = true
232 client.ReplyNicknamed("001", "Hi, welcome to IRC")
233 client.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+Version)
234 client.ReplyNicknamed("003", "This server was created sometime")
235 client.ReplyNicknamed("004", *hostname+" goircd o o")
238 log.Println(client, "logged in")
242 // Register new room in Daemon. Create an object, events sink, save pointers
243 // to corresponding daemon's places and start room's processor goroutine.
244 func RoomRegister(name string) (*Room, chan ClientEvent) {
245 roomNew := NewRoom(name)
246 roomSink := make(chan ClientEvent)
248 rooms[name] = roomNew
249 roomSinks[roomNew] = roomSink
251 go roomNew.Processor(roomSink)
253 return roomNew, roomSink
256 func HandlerJoin(client *Client, cmd string) {
257 args := strings.Split(cmd, " ")
258 rs := strings.Split(args[0], ",")
261 keys = strings.Split(args[1], ",")
263 keys = make([]string, 0)
265 var roomExisting *Room
266 var roomSink chan ClientEvent
268 for n, room := range rs {
269 if !RoomNameValid(room) {
270 client.ReplyNoChannel(room)
274 if (n < len(keys)) && (keys[n] != "") {
280 for roomExisting, roomSink = range roomSinks {
281 if room == *roomExisting.name {
283 if (*roomExisting.key != "") && (*roomExisting.key != key) {
286 roomSink <- ClientEvent{client, EventNew, ""}
291 roomNew, roomSink = RoomRegister(room)
292 log.Println("Room", roomNew, "created")
297 roomSink <- ClientEvent{client, EventNew, ""}
300 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
305 func Processor(events chan ClientEvent, finished chan struct{}) {
309 time.Sleep(10 * time.Second)
310 events <- ClientEvent{eventType: EventTick}
313 for event := range events {
315 client := event.client
316 switch event.eventType {
319 for c := range clients {
320 if c.recvTimestamp.Add(PingTimeout).Before(now) {
321 log.Println(c, "ping timeout")
325 if c.sendTimestamp.Add(PingThreshold).Before(now) {
327 c.Msg("PING :" + *hostname)
328 c.sendTimestamp = time.Now()
330 log.Println(c, "ping timeout")
337 for rn, r := range rooms {
338 if *statedir == "" && len(r.members) == 0 {
339 log.Println(rn, "emptied room")
348 for _, sink := range roomSinks {
349 sink <- ClientEvent{eventType: EventTerm}
357 clients[client] = struct{}{}
361 delete(clients, client)
364 for _, roomSink := range roomSinks {
369 cols := strings.SplitN(event.text, " ", 2)
370 cmd := strings.ToUpper(cols[0])
372 log.Println(client, "command", cmd)
375 log.Println(client, "quit")
379 if !client.registered {
380 ClientRegister(client, cmd, cols)
384 client.recvTimestamp = now
390 client.ReplyNicknamed("305", "You are no longer marked as being away")
393 msg := strings.TrimLeft(cols[1], ":")
395 client.ReplyNicknamed("306", "You have been marked as being away")
397 if len(cols) == 1 || len(cols[1]) < 1 {
398 client.ReplyNotEnoughParameters("JOIN")
401 HandlerJoin(client, cols[1])
403 SendList(client, cols)
407 if len(cols) == 1 || len(cols[1]) < 1 {
408 client.ReplyNotEnoughParameters("MODE")
411 cols = strings.SplitN(cols[1], " ", 2)
412 if cols[0] == *client.username {
414 client.Msg("221 " + *client.nickname + " +")
416 client.ReplyNicknamed("501", "Unknown MODE flag")
422 r, found := rooms[room]
424 client.ReplyNoChannel(room)
429 roomSinks[r] <- ClientEvent{client, EventMode, ""}
431 roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
437 if len(cols) == 1 || len(cols[1]) < 1 {
438 client.ReplyNotEnoughParameters("PART")
441 rs := strings.Split(cols[1], " ")[0]
443 for _, room := range strings.Split(rs, ",") {
444 if r, found := rooms[room]; found {
445 roomSinks[r] <- ClientEvent{client, EventDel, ""}
447 client.ReplyNoChannel(room)
453 client.ReplyNicknamed("409", "No origin specified")
456 client.Reply(fmt.Sprintf("PONG %s :%s", *hostname, cols[1]))
459 case "NOTICE", "PRIVMSG":
461 client.ReplyNicknamed("411", "No recipient given ("+cmd+")")
464 cols = strings.SplitN(cols[1], " ", 2)
466 client.ReplyNicknamed("412", "No text to send")
470 target := strings.ToLower(cols[0])
472 for c := range clients {
473 if *c.nickname == target {
474 msg = fmt.Sprintf(":%s %s %s %s", client, cmd, *c.nickname, cols[1])
477 client.ReplyNicknamed("301", *c.nickname, *c.away)
487 if r, found := rooms[target]; found {
488 roomSinks[r] <- ClientEvent{
491 cmd + " " + strings.TrimLeft(cols[1], ":"),
494 client.ReplyNoNickChan(target)
499 client.ReplyNotEnoughParameters("TOPIC")
502 cols = strings.SplitN(cols[1], " ", 2)
504 r, found := rooms[cols[0]]
507 client.ReplyNoChannel(cols[0])
517 roomSinks[r] <- ClientEvent{client, EventTopic, change}
520 if len(cols) == 1 || len(cols[1]) < 1 {
521 client.ReplyNotEnoughParameters("WHO")
524 room := strings.Split(cols[1], " ")[0]
526 if r, found := rooms[room]; found {
527 roomSinks[r] <- ClientEvent{client, EventWho, ""}
529 client.ReplyNoChannel(room)
533 if len(cols) == 1 || len(cols[1]) < 1 {
534 client.ReplyNotEnoughParameters("WHOIS")
537 cols := strings.Split(cols[1], " ")
538 nicknames := strings.Split(cols[len(cols)-1], ",")
539 SendWhois(client, nicknames)
541 if len(cols) == 1 || len(cols[1]) < 1 {
542 client.ReplyNotEnoughParameters("ISON")
545 nicksKnown := make(map[string]struct{})
547 for c := range clients {
548 nicksKnown[*c.nickname] = struct{}{}
551 var nicksExists []string
552 for _, nickname := range strings.Split(cols[1], " ") {
553 if _, exists := nicksKnown[nickname]; exists {
554 nicksExists = append(nicksExists, nickname)
557 client.ReplyNicknamed("303", strings.Join(nicksExists, " "))
565 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", Version, debug, *hostname))
567 client.ReplyNicknamed("421", cmd, "Unknown command")