2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2023 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/>.
42 CRLF []byte = []byte{'\x0d', '\x0a'}
43 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
45 clients map[*Client]struct{} = make(map[*Client]struct{})
46 clientsLock sync.RWMutex
47 clientsWG sync.WaitGroup
58 recvTimestamp time.Time
59 sendTimestamp time.Time
65 func (c *Client) Host() string {
69 addr := c.conn.RemoteAddr().String()
70 if host, _, err := net.SplitHostPort(addr); err == nil {
73 if domains, err := net.LookupAddr(addr); err == nil {
74 addr = strings.TrimSuffix(domains[0], ".")
79 func (c *Client) String() string {
80 return strings.Join([]string{c.nickname, "!", c.username, "@", c.Host()}, "")
83 func NewClient(conn net.Conn, events chan ClientEvent) *Client {
88 recvTimestamp: time.Now(),
89 sendTimestamp: time.Now(),
91 outBuf: make(chan string, MaxOutBuf),
95 go c.Processor(events)
99 func (c *Client) Close() {
108 func (c *Client) Processor(events chan ClientEvent) {
109 events <- ClientEvent{c, EventNew, ""}
111 log.Println(c, "connected")
113 buf := make([]byte, BufSize*2)
119 log.Println(c, "input buffer size exceeded, kicking him")
122 n, err = c.conn.Read(buf[prev:])
128 i = bytes.Index(buf[:prev], CRLF)
133 log.Println(c, "<-", msg)
135 msg = string(buf[:i])
137 log.Println(c, "->", msg)
139 events <- ClientEvent{c, EventMsg, msg}
140 copy(buf, buf[i+2:prev])
146 log.Println(c, "disconnected")
148 events <- ClientEvent{c, EventDel, ""}
152 func (c *Client) MsgSender() {
154 for msg := range c.outBuf {
156 log.Println(c, "<-", msg)
158 if _, err = c.conn.Write(append([]byte(msg), CRLF...)); err != nil {
160 log.Println(c, "error writing", err)
169 func (c *Client) Msg(text string) {
175 if len(c.outBuf) == MaxOutBuf {
176 log.Println(c, "output buffer size exceeded, kicking him")
186 func (c *Client) Reply(text string) {
187 c.Msg(":" + *hostname + " " + text)
190 func (c *Client) ReplyParts(code string, text ...string) {
191 parts := append([]string{code}, text...)
192 parts[len(parts)-1] = ":" + parts[len(parts)-1]
193 c.Reply(strings.Join(parts, " "))
196 func (c *Client) ReplyNicknamed(code string, text ...string) {
197 c.ReplyParts(code, append([]string{c.nickname}, text...)...)
200 func (c *Client) ReplyNotEnoughParameters(command string) {
201 c.ReplyNicknamed("461", command, "Not enough parameters")
204 func (c *Client) ReplyNoChannel(channel string) {
205 c.ReplyNicknamed("403", channel, "No such channel")
208 func (c *Client) ReplyNoNickChan(channel string) {
209 c.ReplyNicknamed("401", channel, "No such nick/channel")
212 func (c *Client) SendLusers() {
215 for client := range clients {
216 if client.registered {
220 clientsLock.RUnlock()
223 fmt.Sprintf("There are %d users and 0 invisible on 1 servers",
228 func (c *Client) SendMotd() {
230 c.ReplyNicknamed("422", "MOTD File is missing")
233 motdText, err := os.ReadFile(*motd)
235 log.Printf("can not read motd file %s: %v", *motd, err)
236 c.ReplyNicknamed("422", "Error reading MOTD File")
239 c.ReplyNicknamed("375", "- "+*hostname+" Message of the day -")
240 for _, s := range strings.Split(strings.TrimSuffix(string(motdText), "\n"), "\n") {
241 c.ReplyNicknamed("372", "- "+s)
243 c.ReplyNicknamed("376", "End of /MOTD command")
246 func (c *Client) Join(cmd string) {
247 args := strings.Split(cmd, " ")
248 rs := strings.Split(args[0], ",")
251 keys = strings.Split(args[1], ",")
254 for n, roomName := range rs {
255 if !RERoom.MatchString(roomName) {
256 c.ReplyNoChannel(roomName)
260 if (n < len(keys)) && (keys[n] != "") {
264 for roomNameExisting, room := range rooms {
265 if roomName != roomNameExisting {
268 if (room.key != "") && (room.key != key) {
269 c.ReplyNicknamed("475", roomName, "Cannot join channel (+k)")
273 room.events <- ClientEvent{c, EventNew, ""}
278 roomNew := RoomRegister(roomName)
280 log.Println("room", roomName, "created")
286 roomNew.events <- ClientEvent{c, EventNew, ""}
290 func (client *Client) SendWhois(nicknames []string) {
292 for _, nickname := range nicknames {
293 nickname = strings.ToLower(nickname)
295 for c = range clients {
296 if strings.ToLower(c.nickname) == nickname {
297 clientsLock.RUnlock()
301 clientsLock.RUnlock()
302 client.ReplyNoNickChan(nickname)
309 host, _, err := net.SplitHostPort(c.conn.RemoteAddr().String())
311 log.Printf("can't parse RemoteAddr %q: %v", host, err)
315 client.ReplyNicknamed("311", c.nickname, c.username, host, "*", c.realname)
316 client.ReplyNicknamed("312", c.nickname, *hostname, *hostname)
318 client.ReplyNicknamed("301", c.nickname, c.away)
320 subscriptions := make([]string, 0)
322 for _, room := range rooms {
323 for subscriber := range room.members {
324 if subscriber.nickname == nickname {
325 subscriptions = append(subscriptions, room.name)
330 sort.Strings(subscriptions)
331 client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
332 client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
336 func (c *Client) SendList(cols []string) {
338 if (len(cols) > 1) && (cols[1] != "") {
339 rs = strings.Split(strings.Split(cols[1], " ")[0], ",")
341 rs = make([]string, 0)
343 for r := range rooms {
350 for _, r := range rs {
351 if room, found := rooms[r]; found {
355 fmt.Sprintf("%d", len(room.members)),
361 c.ReplyNicknamed("323", "End of /LIST")
364 func (c *Client) Register(cmd string, cols []string) {
367 if len(cols) == 1 || len(cols[1]) < 1 {
368 c.ReplyNotEnoughParameters("PASS")
371 password := strings.TrimPrefix(cols[1], ":")
372 c.password = password
374 if len(cols) == 1 || len(cols[1]) < 1 {
375 c.ReplyParts("431", "No nickname given")
379 // Compatibility with some clients prepending colons to nickname
380 nickname = strings.TrimPrefix(nickname, ":")
381 nickname = strings.ToLower(nickname)
382 if !RENickname.MatchString(nickname) {
383 c.ReplyParts("432", "*", cols[1], "Erroneous nickname")
387 for existingClient := range clients {
388 if existingClient.nickname == nickname {
389 clientsLock.RUnlock()
390 c.ReplyParts("433", "*", nickname, "Nickname is already in use")
394 clientsLock.RUnlock()
395 c.nickname = nickname
398 c.ReplyNotEnoughParameters("USER")
401 args := strings.SplitN(cols[1], " ", 4)
403 c.ReplyNotEnoughParameters("USER")
407 realname := strings.TrimLeft(args[3], ":")
408 c.realname = realname
410 if c.nickname != "*" && c.username != "" {
411 if *passwords != "" {
412 authenticated := false
413 if c.password == "" {
414 c.ReplyParts("462", "You may not register")
418 contents, err := os.ReadFile(*passwords)
420 log.Fatalf("can not read passwords file %s: %s", *passwords, err)
423 for n, entry := range strings.Split(string(contents), "\n") {
424 if entry == "" || strings.HasPrefix(entry, "#") {
427 cols := strings.Split(entry, ":")
429 log.Fatalf("bad passwords format: %s:%d", *passwords, n)
432 if cols[0] != c.nickname {
435 h := sha256.Sum256([]byte(c.password))
436 authenticated = subtle.ConstantTimeCompare(
437 []byte(hex.EncodeToString(h[:])),
443 c.ReplyParts("462", "You may not register")
449 c.ReplyNicknamed("001", "Hi, welcome to IRC")
450 c.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+Version)
451 c.ReplyNicknamed("003", "This server was created sometime")
452 c.ReplyNicknamed("004", *hostname+" goircd o o")
456 log.Println(c, "logged in")