diff --git a/irc/commands.go b/irc/commands.go index 2988a57..ecef5d7 100644 --- a/irc/commands.go +++ b/irc/commands.go @@ -4,8 +4,6 @@ import ( "fmt" "log" "strings" - - "github.com/sparques/kiss" ) type serverCommand func(s *Server, user *User, args []string) (quit bool) @@ -35,8 +33,17 @@ var cmdSet = map[string]serverCommand{ } func capabilities(s *Server, user *User, args []string) (quit bool) { - // We don't support much... - s.reply(user, "CAP", "*", "LS", "") + // We don't support any capabilities. Only answer the subcommands that + // expect a reply; answering CAP END makes some clients loop. + if len(args) < 2 { + return + } + switch sub := strings.ToUpper(args[1]); sub { + case "LS", "LIST": + s.reply(user, "CAP", replyNick(user), sub, "") + case "REQ": + s.reply(user, "CAP", replyNick(user), "NAK", strings.Join(args[2:], " ")) + } return } @@ -81,11 +88,16 @@ func user(s *Server, user *User, args []string) (quit bool) { } func join(s *Server, user *User, args []string) (quit bool) { - if len(args) != 2 { + if len(args) < 2 { s.reply(user, ERR_NEEDMOREPARAMS, replyNick(user), "JOIN", "Not enough parameters") return } + // channel keys (args[2]) are accepted and ignored for _, ch := range strings.Split(args[1], ",") { + if !strings.HasPrefix(ch, "#") { + s.reply(user, ERR_NOSUCHCHANNEL, user.Nick, ch, "Channel names must start with #") + continue + } s.joinChannel(user, ch) } return @@ -225,7 +237,9 @@ func part(s *Server, user *User, args []string) (quit bool) { s.Unlock() s.partChannel(user, chName, reason) + s.Lock() user.partedChannels = append(user.partedChannels, channelKey(chName)) + s.Unlock() } return } @@ -247,23 +261,18 @@ func frequency(s *Server, user *User, args []string) (quit bool) { case 3: rx, tx = args[1], args[2] default: - // do error - log.Printf("Frequency called with %d args", len(args)) + s.reply(user, ERR_NEEDMOREPARAMS, replyNick(user), "FREQUENCY", "Usage: FREQUENCY [tx]") + return } - frame := []byte(fmt.Sprintf("AT+DMOSETGROUP=1,%s,%s,0000,0,0000", tx, rx)) - - s.CommandPort().Write(kiss.WithCommand(kiss.FrameTypeSetHardware, frame)) - reply := make([]byte, 1024) - n, err := s.CommandPort().Read(reply) + frame := fmt.Sprintf("AT+DMOSETGROUP=1,%s,%s,0000,0,0000", tx, rx) + reply, err := s.SetHardware(frame) if err != nil { - log.Printf("Error reading SetHardware response: %v", err) - + log.Printf("SetHardware %s: %v", frame, err) + s.reply(user, "FREQUENCY", fmt.Sprintf("Failed to change frequency: %v", err)) return } - - // s.reply(user, "FREQUENCY", fmt.Sprintf("Failed to change Frequency: %v", )) - log.Printf("SetHardware: %s; Reply: %s", frame, string(reply[:n])) + log.Printf("SetHardware: %s; Reply: %s", frame, reply) s.reply(user, "FREQUENCY", fmt.Sprintf("Changed Frequency: RX: %s; TX: %s", rx, tx)) @@ -271,16 +280,17 @@ func frequency(s *Server, user *User, args []string) (quit bool) { } func sethardware(s *Server, user *User, args []string) (quit bool) { - cmd := strings.Join(args, " ") - s.CommandPort().Write(kiss.WithCommand(kiss.FrameTypeSetHardware, []byte(cmd))) - reply := make([]byte, 1024) - n, err := s.CommandPort().Read(reply) + if len(args) < 2 { + s.reply(user, ERR_NEEDMOREPARAMS, replyNick(user), "SETHARDWARE", "Not enough parameters") + return + } + reply, err := s.SetHardware(strings.Join(args[1:], " ")) if err != nil { - log.Printf("Error reading SetHardware response: %v", err) - return false + s.reply(user, "SETHARDWARE", err.Error()) + return } - s.reply(user, "SETHARDWARE", string(reply[:n])) + s.reply(user, "SETHARDWARE", reply) return } diff --git a/irc/commands_test.go b/irc/commands_test.go index 82d2e40..56770d9 100644 --- a/irc/commands_test.go +++ b/irc/commands_test.go @@ -84,7 +84,7 @@ func TestPartBroadcastsAndRemovesUser(t *testing.T) { if _, ok := channel.Users[nickKey(sender.Nick)]; ok { t.Fatal("sender was not removed from channel") } - want := ":Maple!N0CALL@ PART #hamirc :done\r\n" + want := ":Maple!N0CALL@* PART #hamirc :done\r\n" if senderOut.String() != want { t.Fatalf("sender PART message = %q, want %q", senderOut.String(), want) } @@ -175,3 +175,50 @@ func TestNickChangeBroadcastsToChannelMembers(t *testing.T) { t.Fatalf("other nick-change message = %q, want %q", otherOut.String(), want) } } + +func TestCapEndGetsNoReply(t *testing.T) { + server := NewServer() + server.Name = "hamirc" + var out bytes.Buffer + user := NewUser("", &out) + + server.handleCommand(user, "CAP LS 302") + if want := ":hamirc CAP * LS :\r\n"; out.String() != want { + t.Fatalf("CAP LS reply = %q, want %q", out.String(), want) + } + out.Reset() + server.handleCommand(user, "CAP END") + if out.Len() != 0 { + t.Fatalf("CAP END got reply %q", out.String()) + } +} + +func TestNickChangeOutsideChannelsEchoesToUser(t *testing.T) { + server := NewServer() + var out bytes.Buffer + user := NewUser("Maple", &out) + user.local = true + server.Users[nickKey(user.Nick)] = user + + nick(server, user, []string{"NICK", "Cedar"}) + if want := ":Maple NICK :Cedar\r\n"; out.String() != want { + t.Fatalf("nick-change message = %q, want %q", out.String(), want) + } +} + +func TestNickCaseChangeKeepsChannelMembership(t *testing.T) { + server := NewServer() + user := NewUser("Maple", &bytes.Buffer{}) + user.local = true + server.Users[nickKey(user.Nick)] = user + channel := server.Channel("#hamirc") + channel.Users[nickKey(user.Nick)] = user + + nick(server, user, []string{"NICK", "MAPLE"}) + if user.Nick != "MAPLE" { + t.Fatalf("nick = %q, want MAPLE", user.Nick) + } + if channel.Users[nickKey(user.Nick)] != user { + t.Fatal("case-only nick change dropped user from channel") + } +} diff --git a/irc/server.go b/irc/server.go index 7629685..1394041 100644 --- a/irc/server.go +++ b/irc/server.go @@ -105,6 +105,30 @@ func (s *Server) CommandPort() io.ReadWriter { return s.tnc.CommandPort(uint8(s.tncport)) } +// SetHardware sends a KISS SetHardware frame and waits briefly for the TNC's +// reply. Many TNCs (direwolf included) never answer, and an unbounded read +// would hang the caller. +// ponytail: a timed-out read stays parked and eats the next reply; add a reply router if that bites. +func (s *Server) SetHardware(cmd string) (string, error) { + port := s.CommandPort() + if _, err := port.Write(kiss.WithCommand(kiss.FrameTypeSetHardware, []byte(cmd))); err != nil { + return "", err + } + replies := make(chan string, 1) + go func() { + buf := make([]byte, 1024) + if n, err := port.Read(buf); err == nil { + replies <- string(buf[:min(n, len(buf))]) + } + }() + select { + case reply := <-replies: + return reply, nil + case <-time.After(2 * time.Second): + return "", errors.New("no reply from TNC") + } +} + func (s *Server) debugf(format string, v ...any) { if s.Debug { log.Printf(format, v...) @@ -117,7 +141,9 @@ func (s *Server) userPurge() { for _, ch := range s.Channels { ch.Lock() for nick, user := range ch.Users { - if time.Since(user.LastSeen) > s.UserPurgeAfter { + // local users stay until they part or disconnect; their client + // still shows them as joined + if !user.Local() && time.Since(user.LastSeen) > s.UserPurgeAfter { delete(ch.Users, nick) } } @@ -331,17 +357,16 @@ func (s *Server) handleTNC() { continue } // add user to server if not previously seen - if existingUser := s.Nick(incomingUser.Nick); existingUser == nil { - s.Lock() - if existingUser = s.Users[nickKey(incomingUser.Nick)]; existingUser == nil { - s.Users[nickKey(incomingUser.Nick)] = incomingUser - } else { - incomingUser = existingUser - } - s.Unlock() - } else { + s.Lock() + if existingUser := s.Users[nickKey(incomingUser.Nick)]; existingUser == nil { + s.Users[nickKey(incomingUser.Nick)] = incomingUser + } else if !existingUser.Local() { incomingUser = existingUser } + // If a local user holds this nick, the radio user stays untracked. + // Reusing the local user would make the message look like ours and + // send() would retransmit it. + s.Unlock() // do user-level ban check here? @@ -360,7 +385,10 @@ func (s *Server) handleTNC() { ch := s.Channel(args[2]) // add user to channel if not already there - if nil == ch.Nick(incomingUser.Nick) { + s.Lock() + _, inChannel := ch.Users[nickKey(incomingUser.Nick)] + s.Unlock() + if !inChannel { s.joinChannel(incomingUser, ch.Name) } @@ -412,11 +440,6 @@ func (s *Server) handleConnection(conn net.Conn) { user.local = true user.conn = conn - // send a notice when local user connects - if s.Announce { - fmt.Fprintf(s.tnc.Port(uint8(s.tncport)), ":%s %s %s :%s", user.String(), "NOTICE", "#hamirc", "hamirc - IRC for Amateur Radio - https://github.com/sparques/hamirc") - } - // Handle commands for scanner.Scan() { if s.handleCommand(user, strings.TrimSpace(scanner.Text())) { @@ -454,6 +477,11 @@ func (s *Server) acceptUser(user *User) { s.Users[nickKey(user.Nick)] = user s.Unlock() + // Announce after registration so the transmission carries the callsign. + if s.Announce && s.tnc != nil { + s.transmit(":%s NOTICE #hamirc :hamirc - IRC for Amateur Radio - https://github.com/sparques/hamirc", user.ID()) + } + s.motd(user) } @@ -533,7 +561,7 @@ func (s *Server) changeNick(user *User, newNick string) { // Check if the new nickname is already in use // allow person to snag a remote user though existingUser, ok := s.Users[newNickLower] - if ok && existingUser.Local() { + if ok && existingUser != user && existingUser.Local() { s.Unlock() s.reply(user, ERR_NICKNAMEINUSE, replyNick(user), newNick, "Nickname is already in use") return @@ -542,7 +570,9 @@ func (s *Server) changeNick(user *User, newNick string) { // Update the server's user list oldNick := user.Nick user.Nick = newNick - var recipients []*User + // The user must always see their own NICK, or their client keeps the + // old nick and won't recognize its own JOINs. + recipients := []*User{user} if oldNickLower != "" { delete(s.Users, oldNickLower) s.Users[newNickLower] = user @@ -552,8 +582,8 @@ func (s *Server) changeNick(user *User, newNick string) { for _, ch := range s.Channels { if _, ok := ch.Users[oldNickLower]; ok { - ch.Users[newNickLower] = user delete(ch.Users, oldNickLower) + ch.Users[newNickLower] = user for _, chUser := range ch.Users { recipients = append(recipients, chUser) } @@ -621,10 +651,7 @@ func (s *Server) send(sender *User, cmd, target, msg string) { sender.LastSeen = time.Now() senderID := sender.ID() - var tncWriter io.Writer - if sender.Local() && s.tnc != nil { - tncWriter = s.tnc.Port(uint8(s.tncport)) - } + transmit := sender.Local() && s.tnc != nil var recipients []*User if strings.HasPrefix(target, "#") { @@ -634,10 +661,10 @@ func (s *Server) send(sender *User, cmd, target, msg string) { return } for _, u := range ch.Users { - if u.Nick == sender.Nick && cmd != "PART" { + if u == sender && cmd != "PART" { continue } - if slices.Contains(u.partedChannels, target) { + if slices.Contains(u.partedChannels, channelKey(target)) { continue } recipients = append(recipients, u) @@ -648,8 +675,8 @@ func (s *Server) send(sender *User, cmd, target, msg string) { s.Unlock() // Transmit local messages via radio after releasing the server lock. - if tncWriter != nil { - fmt.Fprintf(tncWriter, ":%s %s %s :%s", senderID, cmd, target, msg) + if transmit { + s.transmit(":%s %s %s :%s", senderID, cmd, target, msg) } for _, recipient := range recipients { @@ -657,6 +684,13 @@ func (s *Server) send(sender *User, cmd, target, msg string) { } } +// transmit sends one line over the radio. +func (s *Server) transmit(format string, args ...any) { + if _, err := fmt.Fprintf(s.tnc.Port(uint8(s.tncport)), format, args...); err != nil { + log.Printf("error transmitting to TNC: %v", err) + } +} + func (s *Server) Notice(sender *User, target string, msg string) { s.send(sender, "NOTICE", target, msg) } @@ -697,12 +731,8 @@ func (s *Server) joinChannel(user *User, channelName string) { s.reply(user, RPL_TOPIC, user.Nick, channelName, topic) } - fmt.Fprintf(user, ":%s 353 %s = %s :", s.Name, user.Nick, channelName) - - for _, name := range names { - fmt.Fprintf(user, "%s ", name) - } - fmt.Fprintf(user, "\r\n") + // one Write per line so concurrent writers can't splice into it + fmt.Fprintf(user, ":%s 353 %s = %s :%s\r\n", s.Name, user.Nick, channelName, strings.Join(names, " ")) s.reply(user, RPL_ENDOFNAMES, user.Nick, channelName, "End of /NAMES list") } @@ -713,7 +743,8 @@ func (s *Server) partChannel(user *User, channelName, reason string) bool { s.Unlock() return false } - if _, ok := ch.Users[nickKey(user.Nick)]; !ok { + // compare pointers: a local user may share a nick with a radio user + if ch.Users[nickKey(user.Nick)] != user { s.Unlock() return false } @@ -733,30 +764,36 @@ func (s *Server) userHost(user *User, nicks []string) { defer s.Unlock() //:irc.example.com 302 Sparques :Nick1=-user1@host1 Nick2=+user2@host2 - fmt.Fprintf(user, ":%s 302 %s :", s.Name, user.Nick) - + var replies []string for _, nick := range nicks { u, ok := s.Users[nickKey(nick)] if !ok { continue } - fmt.Fprintf(user, "%s=-%s@%s ", nick, u.Callsign, strings.ReplaceAll(u.RealName, " ", "_")) + replies = append(replies, fmt.Sprintf("%s=-%s@%s", nick, u.Callsign, strings.ReplaceAll(u.RealName, " ", "_"))) } - fmt.Fprintf(user, "\r\n") + fmt.Fprintf(user, ":%s 302 %s :%s\r\n", s.Name, user.Nick, strings.Join(replies, " ")) } func (s *Server) quit(user *User, reason string) { s.Lock() - channels := make([]string, 0, len(s.Channels)) + var recipients []*User for _, ch := range s.Channels { - if _, ok := ch.Users[nickKey(user.Nick)]; ok { - channels = append(channels, ch.Name) + if ch.Users[nickKey(user.Nick)] != user { + continue + } + for _, u := range ch.Users { + if u != user { + recipients = append(recipients, u) + } } } + userID := user.ID() s.Unlock() - for _, channel := range channels { - s.send(user, "QUIT", channel, reason) + // Local only: radio stations drop QUIT, so transmitting it wastes airtime. + for _, recipient := range uniqueUsers(recipients) { + fmt.Fprintf(recipient, ":%s QUIT :%s\r\n", userID, reason) } } @@ -824,18 +861,15 @@ func (s *Server) setTopic(user *User, ch *Channel, topic string) { } chName := ch.Name userID := user.ID() - var tncWriter io.Writer - if user.Local() && s.tnc != nil { - tncWriter = s.tnc.Port(uint8(s.tncport)) - } + transmit := user.Local() && s.tnc != nil s.Unlock() for _, recipient := range recipients { - s.reply(recipient, RPL_TOPIC, recipient.Nick, chName, topic) + fmt.Fprintf(recipient, ":%s TOPIC %s :%s\r\n", userID, chName, topic) } // also push out topic change - if tncWriter != nil { - fmt.Fprintf(tncWriter, ":%s %s %s :%s", userID, "TOPIC", chName, topic) + if transmit { + s.transmit(":%s TOPIC %s :%s", userID, chName, topic) } } diff --git a/irc/server_test.go b/irc/server_test.go index e74c240..48b1d0f 100644 --- a/irc/server_test.go +++ b/irc/server_test.go @@ -295,7 +295,7 @@ func TestSendLocalMessageWithoutTNCStillDeliversLocally(t *testing.T) { server.send(sender, "NOTICE", "Birch", "copy") - want := ":Maple!N0CALL@ NOTICE Birch :copy\r\n" + want := ":Maple!N0CALL@* NOTICE Birch :copy\r\n" if recipientOut.String() != want { t.Fatalf("recipient = %q, want %q", recipientOut.String(), want) } @@ -332,7 +332,7 @@ func TestJoinChannelBroadcastsAndSendsNames(t *testing.T) { server.joinChannel(joining, "#hamirc") - joinLine := ":Maple!N0CALL@ JOIN :#hamirc\r\n" + joinLine := ":Maple!N0CALL@* JOIN :#hamirc\r\n" if !strings.Contains(joiningOut.String(), joinLine) { t.Fatalf("joining user did not receive JOIN line: %q", joiningOut.String()) } @@ -368,7 +368,7 @@ func TestPartChannelBroadcastsAndRemovesRemoteUser(t *testing.T) { t.Fatal("remote user was not removed from channel") } - want := ":Maple!N0CALL@ PART #hamirc :73\r\n" + want := ":Maple!N0CALL@* PART #hamirc :73\r\n" if remoteOut.String() != want { t.Fatalf("remote PART message = %q, want %q", remoteOut.String(), want) } @@ -477,13 +477,12 @@ func TestSetTopicLocalWithoutTNCBroadcastsLocally(t *testing.T) { if channel.Topic != "check in" { t.Fatalf("topic = %q, want check in", channel.Topic) } - wantSetter := ":hamirc 332 Maple #hamirc :check in\r\n" - if setterOut.String() != wantSetter { - t.Fatalf("setter topic reply = %q, want %q", setterOut.String(), wantSetter) + want := ":Maple!N0CALL@* TOPIC #hamirc :check in\r\n" + if setterOut.String() != want { + t.Fatalf("setter topic message = %q, want %q", setterOut.String(), want) } - wantOther := ":hamirc 332 Birch #hamirc :check in\r\n" - if otherOut.String() != wantOther { - t.Fatalf("other topic reply = %q, want %q", otherOut.String(), wantOther) + if otherOut.String() != want { + t.Fatalf("other topic message = %q, want %q", otherOut.String(), want) } } @@ -509,3 +508,36 @@ func TestListChannelsIncludesClientOnStartAndEnd(t *testing.T) { t.Fatalf("LIST end reply missing client nick: %q", got) } } + +func TestUserIDRoundTripsThroughParse(t *testing.T) { + for _, realName := range []string{"", "Joe joe@example.com", "Hi!"} { + sent := NewUser("Maple", io.Discard) + sent.Callsign = "N0CALL" + sent.RealName = realName + + got := NewUser("", io.Discard) + got.Parse(sent.ID()) + if got.Nick != "Maple" || got.Callsign != "N0CALL" { + t.Fatalf("Parse(%q) = nick %q callsign %q", sent.ID(), got.Nick, got.Callsign) + } + } +} + +func TestHandleTNCNickCollisionDeliversToLocalUser(t *testing.T) { + server := NewServer() + var out bytes.Buffer + local := NewUser("Maple", &out) + local.local = true + local.Callsign = "N0CALL" + server.Users[nickKey(local.Nick)] = local + server.Channel("#hamirc").Users[nickKey(local.Nick)] = local + + runSingleTNCFrame(t, server, ":Maple!K1ABC@Far_Away PRIVMSG #hamirc :hello") + + if server.Nick("Maple") != local { + t.Fatal("radio user replaced local user") + } + if want := ":Maple!K1ABC@Far_Away PRIVMSG #hamirc :hello\r\n"; out.String() != want { + t.Fatalf("local user got %q, want %q", out.String(), want) + } +} diff --git a/irc/user.go b/irc/user.go index ddc9b54..ea891a6 100644 --- a/irc/user.go +++ b/irc/user.go @@ -7,6 +7,7 @@ import ( "io" "net" "strings" + "sync" "time" ) @@ -22,7 +23,8 @@ type User struct { conn net.Conn local bool - buf *bufio.Writer + bufMu sync.Mutex // User is written from several goroutines + buf *bufio.Writer } func NewUser(nick string, wr io.Writer) *User { @@ -35,6 +37,8 @@ func NewUser(nick string, wr io.Writer) *User { // Write writes to the user, in discrete lines, buffering if we did // not get a line-feed. func (u *User) Write(buf []byte) (n int, err error) { + u.bufMu.Lock() + defer u.bufMu.Unlock() var n2 int for len(buf) > 0 { i := bytes.Index(buf, []byte{'\n'}) @@ -60,7 +64,13 @@ func (u *User) Write(buf []byte) (n int, err error) { // ID generates a user id in the form of !@. ID converts spaces to underscores // for Real Name. func (u *User) ID() string { - return fmt.Sprintf("%s!%s@%s", u.Nick, u.Callsign, strings.Join(strings.Fields(u.RealName), "_")) + // Receivers need exactly one '!' and one '@' and a non-empty host. + host := strings.Join(strings.Fields(u.RealName), "_") + host = strings.NewReplacer("!", "_", "@", "_").Replace(host) + if host == "" { + host = "*" + } + return fmt.Sprintf("%s!%s@%s", u.Nick, u.Callsign, host) } // Parse breaks apart a nick!user@host identifier into its constituent parts and @@ -71,20 +81,16 @@ func (u *User) ID() string { func (u *User) Parse(id string) { // More rigorous nick/id validation can be added if malformed traffic // becomes a practical issue. - fields := strings.FieldsFunc(id, func(r rune) bool { - if r == '!' || r == '@' { - return true - } - return false - }) + nick, rest, ok1 := strings.Cut(id, "!") + callsign, realName, ok2 := strings.Cut(rest, "@") // don't populate anything if we can't do this simple bit of parsing // chances are we were sent junk or the message was garbled - if len(fields) != 3 { + if !ok1 || !ok2 || nick == "" || callsign == "" { return } - u.Nick = fields[0] - u.Callsign = fields[1] - u.RealName = fields[2] + u.Nick = nick + u.Callsign = callsign + u.RealName = realName } // Local returns true if the user is connected via TCP. This is used diff --git a/main.go b/main.go index cb7ff34..f8fd785 100644 --- a/main.go +++ b/main.go @@ -11,7 +11,6 @@ import ( "syscall" "github.com/sparques/hamirc/irc" - "github.com/sparques/kiss" ) var ( @@ -79,14 +78,12 @@ func main() { if len(sethardware) > 0 { for _, frame := range sethardware { - server.CommandPort().Write(kiss.WithCommand(kiss.FrameTypeSetHardware, []byte(frame))) - reply := make([]byte, 1024) - n, err := server.CommandPort().Read(reply) + reply, err := server.SetHardware(frame) if err != nil { - log.Printf("Error reading SetHardware resposne: %v", err) + log.Printf("SetHardware %s: %v", frame, err) continue } - log.Printf("SetHardware: %s; Reply: %s", frame, string(reply[:n])) + log.Printf("SetHardware: %s; Reply: %s", frame, reply) } }