1 // goircd -- minimalistic simple Internet Relay Chat (IRC) server
2 // Copyright (C) 2014-2024 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
40 CRLF []byte = []byte{'\x0d', '\x0a'}
41 RENickname = regexp.MustCompile("^[a-zA-Z0-9-]{1,24}$")
43 clients map[*Client]struct{} = make(map[*Client]struct{})
44 clientsLock sync.RWMutex
45 clientsWG sync.WaitGroup
56 recvTimestamp time.Time
57 sendTimestamp time.Time
63 func (c *Client) Host() string {
67 addr := c.conn.RemoteAddr().String()
68 if host, _, err := net.SplitHostPort(addr); err == nil {
71 if domains, err := net.LookupAddr(addr); err == nil {
72 addr = strings.TrimSuffix(domains[0], ".")
77 func (c *Client) String() string {
78 return strings.Join([]string{c.nickname, "!", c.username, "@", c.Host()}, "")
81 func NewClient(conn net.Conn, events chan ClientEvent) *Client {
86 recvTimestamp: time.Now(),
87 sendTimestamp: time.Now(),
89 outBuf: make(chan string, MaxOutBuf),
93 go c.Processor(events)
97 func (c *Client) Close() {
106 func (c *Client) Processor(events chan ClientEvent) {
107 events <- ClientEvent{c, EventNew, ""}
109 log.Println(c, "connected")
111 buf := make([]byte, BufSize*2)
117 log.Println(c, "input buffer size exceeded, kicking him")
120 n, err = c.conn.Read(buf[prev:])
126 i = bytes.Index(buf[:prev], CRLF)
131 log.Println(c, "<-", msg)
133 msg = string(buf[:i])
135 log.Println(c, "->", msg)
137 events <- ClientEvent{c, EventMsg, msg}
138 copy(buf, buf[i+2:prev])
144 log.Println(c, "disconnected")
146 events <- ClientEvent{c, EventDel, ""}
150 func (c *Client) MsgSender() {
152 for msg := range c.outBuf {
154 log.Println(c, "<-", msg)
156 if _, err = c.conn.Write(append([]byte(msg), CRLF...)); err != nil {
158 log.Println(c, "error writing", err)
167 func (c *Client) Msg(text string) {
173 if len(c.outBuf) == MaxOutBuf {
174 log.Println(c, "output buffer size exceeded, kicking him")
184 func (c *Client) Reply(text string) {
185 c.Msg(":" + *hostname + " " + text)
188 func (c *Client) ReplyParts(code string, text ...string) {
189 parts := append([]string{code}, text...)
190 parts[len(parts)-1] = ":" + parts[len(parts)-1]
191 c.Reply(strings.Join(parts, " "))
194 func (c *Client) ReplyNicknamed(code string, text ...string) {
195 c.ReplyParts(code, append([]string{c.nickname}, text...)...)
198 func (c *Client) ReplyNotEnoughParameters(command string) {
199 c.ReplyNicknamed("461", command, "Not enough parameters")
202 func (c *Client) ReplyNoChannel(channel string) {
203 c.ReplyNicknamed("403", channel, "No such channel")
206 func (c *Client) ReplyNoNickChan(channel string) {
207 c.ReplyNicknamed("401", channel, "No such nick/channel")
210 func (c *Client) SendLusers() {
213 for client := range clients {
214 if client.registered {
218 clientsLock.RUnlock()
221 fmt.Sprintf("There are %d users and 0 invisible on 1 servers",
226 func (c *Client) SendMotd() {
228 c.ReplyNicknamed("422", "MOTD File is missing")
231 motdText, err := os.ReadFile(*motd)
233 log.Printf("can not read motd file %s: %v", *motd, err)
234 c.ReplyNicknamed("422", "Error reading MOTD File")
237 c.ReplyNicknamed("375", "- "+*hostname+" Message of the day -")
238 for _, s := range strings.Split(strings.TrimSuffix(string(motdText), "\n"), "\n") {
239 c.ReplyNicknamed("372", "- "+s)
241 c.ReplyNicknamed("376", "End of /MOTD command")
244 func (c *Client) Join(cmd string) {
245 args := strings.Split(cmd, " ")
246 rs := strings.Split(args[0], ",")
249 keys = strings.Split(args[1], ",")
252 for n, roomName := range rs {
253 if !RERoom.MatchString(roomName) {
254 c.ReplyNoChannel(roomName)
258 if (n < len(keys)) && (keys[n] != "") {
262 for roomNameExisting, room := range rooms {
263 if roomName != roomNameExisting {
266 if (room.key != "") && (room.key != key) {
267 c.ReplyNicknamed("475", roomName, "Cannot join channel (+k)")
271 room.events <- ClientEvent{c, EventNew, ""}
276 roomNew := RoomRegister(roomName)
278 log.Println("room", roomName, "created")
284 roomNew.events <- ClientEvent{c, EventNew, ""}
288 func (client *Client) SendWhois(nicknames []string) {
290 for _, nickname := range nicknames {
291 nickname = strings.ToLower(nickname)
293 for c = range clients {
294 if strings.ToLower(c.nickname) == nickname {
295 clientsLock.RUnlock()
299 clientsLock.RUnlock()
300 client.ReplyNoNickChan(nickname)
307 host, _, err := net.SplitHostPort(c.conn.RemoteAddr().String())
309 log.Printf("can't parse RemoteAddr %q: %v", host, err)
313 client.ReplyNicknamed("311", c.nickname, c.username, host, "*", c.realname)
314 client.ReplyNicknamed("312", c.nickname, *hostname, *hostname)
316 client.ReplyNicknamed("301", c.nickname, c.away)
318 subscriptions := make([]string, 0)
320 for _, room := range rooms {
321 for subscriber := range room.members {
322 if subscriber.nickname == nickname {
323 subscriptions = append(subscriptions, room.name)
328 sort.Strings(subscriptions)
329 client.ReplyNicknamed("319", c.nickname, strings.Join(subscriptions, " "))
330 client.ReplyNicknamed("318", c.nickname, "End of /WHOIS list")
334 func (c *Client) SendList(cols []string) {
336 if (len(cols) > 1) && (cols[1] != "") {
337 rs = strings.Split(strings.Split(cols[1], " ")[0], ",")
339 rs = make([]string, 0)
341 for r := range rooms {
348 for _, r := range rs {
349 if room, found := rooms[r]; found {
353 fmt.Sprintf("%d", len(room.members)),
359 c.ReplyNicknamed("323", "End of /LIST")
362 func (c *Client) Register(cmd string, cols []string) {
365 if len(cols) == 1 || len(cols[1]) < 1 {
366 c.ReplyNotEnoughParameters("PASS")
369 password := strings.TrimPrefix(cols[1], ":")
370 c.password = password
372 if len(cols) == 1 || len(cols[1]) < 1 {
373 c.ReplyParts("431", "No nickname given")
377 // Compatibility with some clients prepending colons to nickname
378 nickname = strings.TrimPrefix(nickname, ":")
379 nickname = strings.ToLower(nickname)
380 if !RENickname.MatchString(nickname) {
381 c.ReplyParts("432", "*", cols[1], "Erroneous nickname")
385 for existingClient := range clients {
386 if existingClient.nickname == nickname {
387 clientsLock.RUnlock()
388 c.ReplyParts("433", "*", nickname, "Nickname is already in use")
392 clientsLock.RUnlock()
393 c.nickname = nickname
396 c.ReplyNotEnoughParameters("USER")
399 args := strings.SplitN(cols[1], " ", 4)
401 c.ReplyNotEnoughParameters("USER")
405 realname := strings.TrimLeft(args[3], ":")
406 c.realname = realname
408 if c.nickname != "*" && c.username != "" {
409 if *passwords != "" {
410 authenticated := false
411 if c.password == "" {
412 c.ReplyParts("462", "You may not register")
416 contents, err := os.ReadFile(*passwords)
418 log.Fatalf("can not read passwords file %s: %s", *passwords, err)
421 for n, entry := range strings.Split(string(contents), "\n") {
422 if entry == "" || strings.HasPrefix(entry, "#") {
425 cols := strings.Split(entry, ":")
427 log.Fatalf("bad passwords format: %s:%d", *passwords, n)
430 if cols[0] != c.nickname {
433 h := sha256.Sum256([]byte(c.password))
434 authenticated = subtle.ConstantTimeCompare(
435 []byte(hex.EncodeToString(h[:])),
441 c.ReplyParts("462", "You may not register")
447 c.ReplyNicknamed("001", "Hi, welcome to IRC")
448 c.ReplyNicknamed("002", "Your host is "+*hostname+", running goircd "+Version)
449 c.ReplyNicknamed("003", "This server was created sometime")
450 c.ReplyNicknamed("004", *hostname+" goircd o o")
454 log.Println(c, "logged in")