2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2016 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/>.
34 // Max deadline time of client's unresponsiveness
35 PingTimeout = time.Second * 180
36 // Max idle client's time before PING are sent
37 PingThreshold = time.Second * 90
41 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
43 roomsGroup sync.WaitGroup
45 clients map[*Client]struct{} = make(map[*Client]struct{})
48 func SendLusers(client *Client) {
50 for client := range clients {
51 if client.registered {
55 client.ReplyNicknamed("251", fmt.Sprintf("There are %d users and 0 invisible on 1 servers", lusers))
58 func SendMotd(client *Client) {
60 client.ReplyNicknamed("422", "MOTD File is missing")
63 motdText, err := ioutil.ReadFile(*motd)
65 log.Printf("Can not read motd file %s: %v", *motd, err)
66 client.ReplyNicknamed("422", "Error reading MOTD File")
69 client.ReplyNicknamed("375", "- "+*hostname+" Message of the day -")
70 for _, s := range strings.Split(strings.TrimSuffix(string(motdText), "\n"), "\n") {
71 client.ReplyNicknamed("372", "- "+s)
73 client.ReplyNicknamed("376", "End of /MOTD command")
76 func SendWhois(client *Client, nicknames []string) {
80 var subscriptions []string
82 var subscriber *Client
83 for _, nickname := range nicknames {
84 nickname = strings.ToLower(nickname)
85 for c = range clients {
86 if strings.ToLower(*c.nickname) == nickname {
90 client.ReplyNoNickChan(nickname)
93 hostPort, _, err = net.SplitHostPort(c.conn.RemoteAddr().String())
95 log.Printf("Can't parse RemoteAddr %q: %v", hostPort, err)
98 client.ReplyNicknamed("311", *c.nickname, *c.username, hostPort, "*", *c.realname)
99 client.ReplyNicknamed("312", *c.nickname, *hostname, *hostname)
101 client.ReplyNicknamed("301", *c.nickname, *c.away)
103 subscriptions = make([]string, 0)
104 for _, room = range rooms {
105 for subscriber = range room.members {
106 if *subscriber.nickname == nickname {
107 subscriptions = append(subscriptions, *room.name)
111 sort.Strings(subscriptions)
112 client.ReplyNicknamed("319", *c.nickname, strings.Join(subscriptions, " "))
113 client.ReplyNicknamed("318", *c.nickname, "End of /WHOIS list")
117 func SendList(client *Client, cols []string) {
120 if (len(cols) > 1) && (cols[1] != "") {
121 rs = strings.Split(strings.Split(cols[1], " ")[0], ",")
123 rs = make([]string, 0)
124 for r = range rooms {
131 for _, r = range rs {
132 if room, found = rooms[r]; found {
133 client.ReplyNicknamed(
136 fmt.Sprintf("%d", len(room.members)),
141 client.ReplyNicknamed("323", "End of /LIST")
144 // Unregistered client workflow processor. Unregistered client:
146 // * only QUIT, NICK and USER commands are processed
147 // * other commands are quietly ignored
148 // When client finishes NICK/USER workflow, then MOTD and LUSERS are send to him.
149 func ClientRegister(client *Client, cmd string, cols []string) {
152 if len(cols) == 1 || len(cols[1]) < 1 {
153 client.ReplyNotEnoughParameters("PASS")
156 client.password = &cols[1]
158 if len(cols) == 1 || len(cols[1]) < 1 {
159 client.ReplyParts("431", "No nickname given")
163 // Compatibility with some clients prepending colons to nickname
164 nickname = strings.TrimPrefix(nickname, ":")
165 nickname = strings.ToLower(nickname)
166 for existingClient := range clients {
167 if *existingClient.nickname == nickname {
168 client.ReplyParts("433", "*", nickname, "Nickname is already in use")
172 if !RENickname.MatchString(nickname) {
173 client.ReplyParts("432", "*", cols[1], "Erroneous nickname")
176 client.nickname = &nickname
179 client.ReplyNotEnoughParameters("USER")
182 args := strings.SplitN(cols[1], " ", 4)
184 client.ReplyNotEnoughParameters("USER")
187 client.username = &args[0]
188 realname := strings.TrimLeft(args[3], ":")
189 client.realname = &realname
191 if *client.nickname != "*" && *client.username != "" {
192 if passwords != nil && *passwords != "" {
193 if client.password == nil {
194 client.ReplyParts("462", "You may not register")
198 contents, err := ioutil.ReadFile(*passwords)
200 log.Fatalf("Can no read passwords file %s: %s", *passwords, err)
203 for _, entry := range strings.Split(string(contents), "\n") {
207 if lp := strings.Split(entry, ":"); lp[0] == *client.nickname && lp[1] != *client.password {
208 client.ReplyParts("462", "You may not register")
214 client.registered = true
215 client.ReplyNicknamed("001", "Hi, welcome to IRC")
216 client.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+version)
217 client.ReplyNicknamed("003", "This server was created sometime")
218 client.ReplyNicknamed("004", *hostname+" goircd o o")
221 log.Println(client, "logged in")
225 // Register new room in Daemon. Create an object, events sink, save pointers
226 // to corresponding daemon's places and start room's processor goroutine.
227 func RoomRegister(name string) (*Room, chan ClientEvent) {
228 roomNew := NewRoom(name)
229 roomSink := make(chan ClientEvent)
230 rooms[name] = roomNew
231 roomSinks[roomNew] = roomSink
232 go roomNew.Processor(roomSink)
234 return roomNew, roomSink
237 func HandlerJoin(client *Client, cmd string) {
238 args := strings.Split(cmd, " ")
239 rs := strings.Split(args[0], ",")
242 keys = strings.Split(args[1], ",")
244 keys = make([]string, 0)
246 var roomExisting *Room
247 var roomSink chan ClientEvent
249 for n, room := range rs {
250 if !RoomNameValid(room) {
251 client.ReplyNoChannel(room)
255 if (n < len(keys)) && (keys[n] != "") {
260 for roomExisting, roomSink = range roomSinks {
261 if room == *roomExisting.name {
262 if (*roomExisting.key != "") && (*roomExisting.key != key) {
265 roomSink <- ClientEvent{client, EventNew, ""}
269 roomNew, roomSink = RoomRegister(room)
270 log.Println("Room", roomNew, "created")
275 roomSink <- ClientEvent{client, EventNew, ""}
278 client.ReplyNicknamed("475", room, "Cannot join channel (+k) - bad key")
283 func Processor(events chan ClientEvent, finished chan struct{}) {
287 time.Sleep(10 * time.Second)
288 events <- ClientEvent{eventType: EventTick}
291 for event := range events {
293 client := event.client
294 switch event.eventType {
296 for c := range clients {
297 if c.recvTimestamp.Add(PingTimeout).Before(now) {
298 log.Println(c, "ping timeout")
302 if c.sendTimestamp.Add(PingThreshold).Before(now) {
304 c.Msg("PING :" + *hostname)
305 c.sendTimestamp = time.Now()
307 log.Println(c, "ping timeout")
312 for rn, r := range rooms {
313 if *statedir == "" && len(r.members) == 0 {
314 log.Println(rn, "emptied room")
321 for _, sink := range roomSinks {
322 sink <- ClientEvent{eventType: EventTerm}
328 clients[client] = struct{}{}
330 delete(clients, client)
331 for _, roomSink := range roomSinks {
335 cols := strings.SplitN(event.text, " ", 2)
336 cmd := strings.ToUpper(cols[0])
338 log.Println(client, "command", cmd)
341 log.Println(client, "quit")
345 if !client.registered {
346 ClientRegister(client, cmd, cols)
350 client.recvTimestamp = now
356 client.ReplyNicknamed("305", "You are no longer marked as being away")
359 msg := strings.TrimLeft(cols[1], ":")
361 client.ReplyNicknamed("306", "You have been marked as being away")
363 if len(cols) == 1 || len(cols[1]) < 1 {
364 client.ReplyNotEnoughParameters("JOIN")
367 HandlerJoin(client, cols[1])
369 SendList(client, cols)
373 if len(cols) == 1 || len(cols[1]) < 1 {
374 client.ReplyNotEnoughParameters("MODE")
377 cols = strings.SplitN(cols[1], " ", 2)
378 if cols[0] == *client.username {
380 client.Msg("221 " + *client.nickname + " +")
382 client.ReplyNicknamed("501", "Unknown MODE flag")
387 r, found := rooms[room]
389 client.ReplyNoChannel(room)
393 roomSinks[r] <- ClientEvent{client, EventMode, ""}
395 roomSinks[r] <- ClientEvent{client, EventMode, cols[1]}
400 if len(cols) == 1 || len(cols[1]) < 1 {
401 client.ReplyNotEnoughParameters("PART")
404 rs := strings.Split(cols[1], " ")[0]
405 for _, room := range strings.Split(rs, ",") {
406 if r, found := rooms[room]; found {
407 roomSinks[r] <- ClientEvent{client, EventDel, ""}
409 client.ReplyNoChannel(room)
415 client.ReplyNicknamed("409", "No origin specified")
418 client.Reply(fmt.Sprintf("PONG %s :%s", *hostname, cols[1]))
421 case "NOTICE", "PRIVMSG":
423 client.ReplyNicknamed("411", "No recipient given ("+cmd+")")
426 cols = strings.SplitN(cols[1], " ", 2)
428 client.ReplyNicknamed("412", "No text to send")
432 target := strings.ToLower(cols[0])
433 for c := range clients {
434 if *c.nickname == target {
435 msg = fmt.Sprintf(":%s %s %s %s", client, cmd, *c.nickname, cols[1])
438 client.ReplyNicknamed("301", *c.nickname, *c.away)
446 if r, found := rooms[target]; found {
447 roomSinks[r] <- ClientEvent{
450 cmd + " " + strings.TrimLeft(cols[1], ":"),
453 client.ReplyNoNickChan(target)
457 client.ReplyNotEnoughParameters("TOPIC")
460 cols = strings.SplitN(cols[1], " ", 2)
461 r, found := rooms[cols[0]]
463 client.ReplyNoChannel(cols[0])
472 roomSinks[r] <- ClientEvent{client, EventTopic, change}
474 if len(cols) == 1 || len(cols[1]) < 1 {
475 client.ReplyNotEnoughParameters("WHO")
478 room := strings.Split(cols[1], " ")[0]
479 if r, found := rooms[room]; found {
480 roomSinks[r] <- ClientEvent{client, EventWho, ""}
482 client.ReplyNoChannel(room)
485 if len(cols) == 1 || len(cols[1]) < 1 {
486 client.ReplyNotEnoughParameters("WHOIS")
489 cols := strings.Split(cols[1], " ")
490 nicknames := strings.Split(cols[len(cols)-1], ",")
491 SendWhois(client, nicknames)
493 if len(cols) == 1 || len(cols[1]) < 1 {
494 client.ReplyNotEnoughParameters("ISON")
497 nicksKnown := make(map[string]struct{})
498 for c := range clients {
499 nicksKnown[*c.nickname] = struct{}{}
501 var nicksExists []string
502 for _, nickname := range strings.Split(cols[1], " ") {
503 if _, exists := nicksKnown[nickname]; exists {
504 nicksExists = append(nicksExists, nickname)
507 client.ReplyNicknamed("303", strings.Join(nicksExists, " "))
515 client.ReplyNicknamed("351", fmt.Sprintf("%s.%s %s :", version, debug, *hostname))
517 client.ReplyNicknamed("421", cmd, "Unknown command")