Merge pull request #33 from D-Modem/claude/project-thread-xuwf2f

IRC server linking: the BBS as a TS6 hub on an IRC network
This commit is contained in:
Neo authored and GitHub committed 2026-11-08 18:26:09 -08:00
commit e7eb9b15a1
26 files changed
+2989 -30

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ Main menu
- Message areas, private mail, chat, paging and doors (DOS doors in dosemu2, or Linux programs)
- File areas with X/Y/ZMODEM, Kermit, IND$FILE and FTP
- E-mail: IMAP, POP3 and SMTP, to and from the internet, directly or through a smarthost
- Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC, AIM and ICQ, MSN Messenger, and MRC
- Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC (and linking into an IRC network as a TS6 hub server), AIM and ICQ, MSN Messenger, and MRC
- Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics
- On the web: a forum, image boards, a web terminal and an HTTP API
- Time: follows NTP, NTS and PTP servers, and serves all three
+47
View File
@@ -747,6 +747,53 @@ address = 127.0.0.1:2513
; the screen name the BBS's notices come from
;system = OnlineHost
; IRC server linking: the BBS as a hub server on an IRC network, by TS6
; (Solanum, charybdis, ircd-ratbox; ircd-hybrid 8 with protocol = hybrid).
; Every BBS user online is a user there, whom anyone can /msg and /whois;
; the rooms beginning irc- are its channels (irc-retro is #retro). A nick
; taken there is the BBS user's as Nick|Tag. See docs/wiki/IRC-Linking.md
;[irclink]
; the BBS's server name on the network
;server_name = irc.bbs.example.org
; the TS6 server ID: a digit, then two letters or digits, the network's own
;sid = 1BB
; its description, in LINKS (default: the BBS's name)
;description = The D-Modem BBS
; the network's name, as WHOIS of its users shows it
;network = MyNet
; Nick|Tag for a BBS user whose nick is taken
;tag = DM
; the BBS users' host, as the network sees them (default: server_name)
;host = users.bbs.example.org
; the rooms that are channels (none: every room)
;prefix = irc-
; the network's NICKLEN (Solanum's 31 less one; ratbox and hybrid: 9)
;nick_length = 30
; where servers link in (and address = none for none)
;address = :7000
;tls_address = :7001
; the certificate and key for tls_address
;tls_cert = /etc/bbs/tls.crt
;tls_key = /etc/bbs/tls.key
; between tries of a link out, in seconds
;retry = 30
; A server the BBS links with, one section each: [ircpeer ITS.NAME]
;[ircpeer hub.example.net]
; where to link out to (none: it links in)
;address = hub.example.net:7000
; link out by TLS
;tls = yes
; check its certificate (a self-signed one: no)
;tls_verify = yes
; the password we send it (its accept_password)
;send_password = ours-to-it
; the password it sends us (its send_password)
;accept_password = its-to-us
; its users' tag, beside a BBS user of the same nick (Nick|Tag)
;tag = HUB
; ts6 (Solanum, charybdis, ratbox) or hybrid (ircd-hybrid 8)
;protocol = ts6
; AOL: a host for AOL's own clients (3.0, 4.0 and on, over TCP). Users sign
; on with their BBS names and passwords and get the BBS's Welcome window.
; The client's port is 5190: with [oscar] there too, the two share it. The
+16 -1
View File
@@ -73,6 +73,7 @@ import (
"github.com/D-Modem/bbs/internal/gopher"
"github.com/D-Modem/bbs/internal/imageboard"
"github.com/D-Modem/bbs/internal/ircd"
"github.com/D-Modem/bbs/internal/irclink"
"github.com/D-Modem/bbs/internal/mrc"
"github.com/D-Modem/bbs/internal/msn"
"github.com/D-Modem/bbs/internal/news"
@@ -526,9 +527,23 @@ func serve(cfg *server.Config, path string) int {
lg.Printf("%v", err)
return 1
}
b.SetRelay(mc)
b.AddRelay(mc)
go mc.Run(ctx)
}
if cfg.IRCLink != nil {
hub, err := irclink.New(b, *cfg.IRCLink)
if err != nil {
lg.Printf("%v", err)
return 1
}
b.AddRelay(hub)
go func() {
if err := hub.Run(ctx); err != nil {
lg.Printf("%v", err)
stop()
}
}()
}
if cfg.IRC != nil {
is, err := ircd.New(b, *cfg.IRC)
if err != nil {
+3 -1
View File
@@ -36,7 +36,9 @@ A caller can say up to 8 lines in 10 seconds; more than that is refused
("slow down").
Rooms whose names begin with `mrc-` belong to [MRC](MRC) and are shared
with other BBSes. The rooms are also channels on the BBS's [IRC](IRC)
with other BBSes. With [IRC server linking](IRC-Linking), rooms beginning
`irc-` are an IRC network's channels, and `/msg NICK TEXT` reaches
someone on that network. The rooms are also channels on the BBS's [IRC](IRC)
server (`#main` and the rest), with IRC clients in them alongside the
callers.
+40
View File
@@ -39,6 +39,8 @@ the file is laid out.
| [`[door NAME]`](#door-name) | A door: a program callers play, or another system's doors. |
| [`[irc]`](#irc) | IRC: the chat rooms as channels (#main ...), for IRC clients. |
| [`[oscar]`](#oscar) | AIM and ICQ: the chat for AIM and ICQ clients (OSCAR), beside IRC. |
| [`[irclink]`](#irclink) | IRC server linking: the BBS as a hub server on an IRC network, by TS6 (Solanum, charybdis, ircd-ratbox; ircd-hybrid 8 with protocol = hybrid). |
| [`[ircpeer NAME]`](#ircpeer-name) | A server the BBS links with, one section each: [ircpeer ITS.NAME]. |
| [`[aol]`](#aol) | AOL: a host for AOL's own clients (3.0, 4.0 and on, over TCP). |
| [`[msn]`](#msn) | MSN Messenger: the chat for MSN Messenger 1.0 to 4.7 and Windows Messenger 4.x (MSNP2 to 7), beside IRC and AIM. |
| [`[mrc]`](#mrc) | Multi Relay Chat: the BBSes' chat network. |
@@ -547,6 +549,44 @@ AIM and ICQ: the chat for AIM and ICQ clients (OSCAR), beside IRC. Users sign o
| `system` | | | the screen name the BBS's notices come from. Examples: `OnlineHost`. |
## `[irclink]`
IRC server linking: the BBS as a hub server on an IRC network, by TS6 (Solanum, charybdis, ircd-ratbox; ircd-hybrid 8 with protocol = hybrid). Every BBS user online is a user there, whom anyone can /msg and /whois; the rooms beginning irc- are its channels (irc-retro is #retro). A nick taken there is the BBS user's as Nick|Tag. See docs/wiki/IRC-Linking.md.
| key | default | live | what it does |
|---|---|---|---|
| `server_name` | | | the BBS's server name on the network. Examples: `irc.bbs.example.org`. |
| `sid` | | | the TS6 server ID: a digit, then two letters or digits, the network's own. Examples: `1BB`. |
| `description` | | | its description, in LINKS (default: the BBS's name) Examples: `The D-Modem BBS`. |
| `network` | | | the network's name, as WHOIS of its users shows it. Examples: `MyNet`. |
| `tag` | | | Nick\|Tag for a BBS user whose nick is taken. Examples: `DM`. |
| `host` | | | the BBS users' host, as the network sees them (default: server_name) Examples: `users.bbs.example.org`. |
| `prefix` | | | the rooms that are channels (none: every room) Examples: `irc-`. |
| `nick_length` | | | the network's NICKLEN (Solanum's 31 less one; ratbox and hybrid: 9) Examples: `30`. |
| `address` | | | where servers link in (and address = none for none) Examples: `:7000`. |
| `tls_address` | | | where servers link in (and address = none for none) Examples: `:7001`. |
| `tls_cert` | | | the certificate and key for tls_address. Examples: `/etc/bbs/tls.crt`. |
| `tls_key` | | | the certificate and key for tls_address. Examples: `/etc/bbs/tls.key`. |
| `retry` | | | between tries of a link out, in seconds. Examples: `30`. |
## `[ircpeer NAME]`
A server the BBS links with, one section each: [ircpeer ITS.NAME].
There may be any number of these, each with its own NAME.
| key | default | live | what it does |
|---|---|---|---|
| `address` | | | where to link out to (none: it links in) Examples: `hub.example.net:7000`. |
| `tls` | | | link out by TLS. Examples: `yes`. |
| `tls_verify` | | | check its certificate (a self-signed one: no) Examples: `yes`. |
| `send_password` | | | the password we send it (its accept_password) Examples: `ours-to-it`. |
| `accept_password` | | | the password it sends us (its send_password) Examples: `its-to-us`. |
| `tag` | | | its users' tag, beside a BBS user of the same nick (Nick\|Tag) Examples: `HUB`. |
| `protocol` | | | ts6 (Solanum, charybdis, ratbox) or hybrid (ircd-hybrid 8) Examples: `ts6`. |
## `[aol]`
AOL: a host for AOL's own clients (3.0, 4.0 and on, over TCP). Users sign on with their BBS names and passwords and get the BBS's Welcome window. The client's port is 5190: with [oscar] there too, the two share it. The client finds its host as AmericaOnline.aol.com (point that name here in its machine's hosts file, or edit its TCP.CCL).
+1
View File
@@ -141,6 +141,7 @@ which is generated from `bbs.conf.sample`.
| [Chat and paging](Chat-and-Paging) | chat rooms, node messages, paging the sysop |
| [IRC](IRC) | the IRC server, with the chat rooms as channels |
| [AIM and ICQ](AIM-and-ICQ) | the OSCAR server: AIM and ICQ clients, buddies, IMs and chat rooms |
| [IRC server linking](IRC-Linking) | The BBS as a hub server on an IRC network (TS6): every user reachable there |
| [AOL clients](AOL) | a host for AOL's own clients (3.0, 4.0): sign-on with BBS accounts |
| [MSN Messenger](MSN-Messenger) | the MSN server: MSN Messenger 1.0 to 4.7, contacts and IMs |
| [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes |
+117
View File
@@ -0,0 +1,117 @@
The BBS can be a server on an IRC network: a hub that links to any
number of other servers, in and out, and routes between them. It speaks
TS6, the server protocol of Solanum (Libera.Chat), charybdis,
ircd-ratbox and ircd-hybrid (EFnet). It needs no ircd of its own.
- **Every BBS user is on the network.** Whoever is online, on a terminal,
a 3270, the web, [IRC](IRC), [AIM or ICQ](AIM-and-ICQ), is a user there
under their name (`Carol Ann` is `Carol_Ann`). Anyone on the network can
`/msg` and `/whois` them; the message reaches them however they came.
- **The rooms beginning `irc-` are the network's channels.** `irc-retro`
is `#retro`: whoever is in the room is in the channel, and talk in one is
talk in the other. The network's users are in the room's member list.
- **A taken nick is never fought over.** When a BBS user comes on and
their nick is in use on the network, or a link comes up with someone
there by that nick, the BBS user is renamed `Nick|Tag`, Tag being the
BBS's short tag (`alice|DM`). It is cut to fit the network's nick length,
and numbered (`alice|DM2`) if that too is taken. The BBS user's name on
the BBS does not change.
```ini
[irclink]
server_name = irc.bbs.example.org
sid = 1BB
tag = DM
address = :7000
[ircpeer hub.example.net]
address = hub.example.net:7000
send_password = ours-to-it
accept_password = its-to-us
```
| Setting | Default | What it sets |
|---|---|---|
| `server_name` | (required) | the BBS's server name on the network |
| `sid` | (required) | its TS6 server ID: a digit and two letters or digits, unique on the network |
| `description` | the BBS's name | its description, in `LINKS` |
| `network` | the BBS's name | the network's name, as `WHOIS` of its users shows it on the BBS |
| `tag` | the BBS name's first letters | `Nick\|Tag` for a BBS user whose nick is taken |
| `host` | `server_name` | the BBS users' host, as the network sees them (`alice!bbs@host`) |
| `prefix` | `irc-` | the rooms that are channels (`none`: every room but `sysop-` ones) |
| `nick_length` | `30` | the network's `NICKLEN` (Solanum's is 31 less one; ratbox and hybrid: 9) |
| `address` | `:7000` | where servers link in (`none`: nowhere) |
| `tls_address`, `tls_cert`, `tls_key` | (none) | servers linking in by TLS |
| `retry` | `30` | seconds between tries of a link out |
Each server the BBS links with directly has an `[ircpeer NAME]`, its name
being the server's:
| Setting | Default | What it sets |
|---|---|---|
| `address` | (none: it links in) | where to link out to; the BBS links again whenever the link drops |
| `tls` | `no` | link out by TLS |
| `tls_verify` | `yes` | check its certificate (`no` for a self-signed one) |
| `send_password` | (required) | the password the BBS sends (its `accept_password`) |
| `accept_password` | (required) | the password it must send (its `send_password`) |
| `tag` | its name's first letters | its users' tag, beside a BBS user of the same nick |
| `protocol` | `ts6` | `ts6` (Solanum, charybdis, ratbox) or `hybrid` (ircd-hybrid 8, whose TS6 differs); one linking in is told apart by its handshake |
The other side's `connect` block names the BBS's `server_name`, with the
passwords the other way round. For Solanum:
```
connect "irc.bbs.example.org" {
host = "192.0.2.10";
port = 7000;
send_password = "its-to-us";
accept_password = "ours-to-it";
class = "server";
flags = topicburst;
};
```
A server name, SID, password or address that is wrong, or a server already
on the network by another way (a loop), is refused with an `ERROR` that
says why.
## On the BBS
- In the chat, `/msg NICK TEXT` sends to someone on the network (`/msg 3
TEXT` is still node 3).
- On the BBS's own [IRC server](IRC), the network's users are in the
linked channels' `NAMES` and `WHO`, and `/msg`, `/whois` and `ISON` reach
them as they reach BBS users.
- Someone on the network with the nick of a BBS user online is shown on
the BBS as `Nick|Tag`, with their server's tag (`alice|hub`), so the two
are never confused; `/msg alice|hub` reaches them.
- Topics set on the network are told to the room.
## As a hub
The BBS keeps the network's map: which servers are behind which link,
their users and channels. A server linking in is given everything not
behind it: the servers (`SID`), users (`EUID`, or `UID`), channels
(`SJOIN`) and topics (`TB`). What comes from one link goes on to the
others; a private message goes only toward the one it is for. When a link
drops, the servers behind it are gone from the network (a netsplit): the
rooms are told those users left, and the other links get the `SQUIT`.
The BBS sends its burst once the other side's has come (the answer to its
`PING`), so a BBS user whose nick the other side has is renamed `Nick|Tag`
before they are sent. When two users of other servers collide, the TS6
rules apply: the newer is killed, or both if they are as old. A BBS user
killed off the network (by an oper, or services) is back on it when they
next log in. Channel modes, bans and the like (`TMODE`, `BMASK`, `ENCAP`
...) are passed on as they come; the BBS sets none of its own.
The BBS answers `WHOIS`, `VERSION`, `MOTD`, `ADMIN`, `INFO`, `TIME` and
`LINKS` for itself, and passes those for other servers on.
## Testing against a real ircd
`internal/irclink`'s `TestLive` links to a real ircd when one is set up:
see the top of `live_test.go`. It has been run against Solanum (built from
its main branch) and ircd-hybrid 8.2.43.
**See also:** [IRC](IRC), [Chat and paging](Chat-and-Paging), [MRC](MRC)
+1 -1
View File
@@ -147,4 +147,4 @@ The IRC protocol's parts come from [ergo](https://github.com/ergochat/ergo):
Its tests also use irc-go's client (`ircevent`).
**See also:** [Chat and paging](Chat-and-Paging), [MRC](MRC), [Security](Security)
**See also:** [Chat and paging](Chat-and-Paging), [IRC server linking](IRC-Linking), [MRC](MRC), [Security](Security)
+1
View File
@@ -34,6 +34,7 @@
- [FidoNet](FidoNet)
- [Chat and paging](Chat-and-Paging)
- [IRC](IRC)
- [IRC server linking](IRC-Linking)
- [AIM and ICQ](AIM-and-ICQ)
- [AOL clients](AOL)
- [MSN Messenger](MSN-Messenger)
+1 -1
View File
@@ -194,7 +194,7 @@ type BBS struct {
failures map[string][]time.Time
hubOnce sync.Once
chat *hub
relay Relay // a chat network's rooms (MRC)
relays []Relay // chat networks' rooms (MRC, IRC links)
geoMu sync.Mutex
geo *geoip.File
presMu sync.Mutex
+13 -4
View File
@@ -39,6 +39,9 @@ type Event struct {
// the CB handle the sender goes by ("": none; From is still the
// user's name, for those that do not show handles)
Handle string
// the sender as an IRC network names them (nick!user@host), for one
// from a linked IRC network ("": none)
Mask string
}
// String is the event as a line for the caller.
@@ -315,15 +318,16 @@ func (b *BBS) RoomMembers(name string) []RoomMember {
out = append(out, RoomMember{Name: m.name(), Node: m.Num, Via: via, Handle: m.Handle()})
}
sort.Slice(out, func(i, j int) bool { return out[i].Node < out[j].Node })
return out
return append(out, b.remoteMembers(name)...)
}
// RoomMember is one in a room.
type RoomMember struct {
Name string
Node int
Via string
Node int // 0: someone on a network elsewhere
Via string // how they came (for one elsewhere, the network's ident)
Handle string // a CB handle ("": none)
Host string // for one elsewhere, their host
}
// enter puts the node in a room's members, tells the others, and gives
@@ -491,7 +495,6 @@ func (n *Node) Rooms() []RoomInfo {
u := n.User()
h := n.b.hub()
h.mu.Lock()
defer h.mu.Unlock()
var out []RoomInfo
for name, r := range h.rooms {
if strings.HasPrefix(name, "sysop-") && name != pageRoom(n.Num) && (u == nil || !u.Sysop) {
@@ -504,6 +507,12 @@ func (n *Node) Rooms() []RoomInfo {
sort.Strings(ri.Users)
out = append(out, ri)
}
h.mu.Unlock()
for i := range out {
for _, m := range n.b.remoteMembers(out[i].Name) {
out[i].Users = append(out[i].Users, m.Name+" ("+m.Via+")")
}
}
sortRooms(out)
return out
}
+7
View File
@@ -16,6 +16,7 @@ var ChatHelp = []string{
" /history [WHO] your talks with a user /friends your friends list",
" /friend WHO put one on your list /unfriend WHO take one off it",
" /block WHO stop their messages /unblock WHO let them again",
" /msg NICK TEXT to someone on a linked IRC network",
" /quit leave the chat",
"Sysops: /pages callers paging /answer [NODE] answer one /busy pages on or off",
" /topic TEXT set a permanent room's topic",
@@ -106,6 +107,12 @@ func (n *Node) ChatCommand(line string) (out []string, leave bool, err error) {
}
u, err := n.b.Store.UserByName(to)
if err != nil {
// not one of ours: someone on a linked chat network?
if err := n.MessageRemote(to, text, false, false); err == nil {
return []string{"Sent to " + to + "."}, false, nil
} else if err != ErrNoSuchNick {
return nil, false, err
}
return nil, false, ErrNoUser
}
online, err := n.TellUser(u, text)
+125 -7
View File
@@ -1,6 +1,8 @@
package bbs
import (
"errors"
"strings"
"time"
"github.com/D-Modem/bbs/internal/store"
@@ -20,24 +22,140 @@ type Relay interface {
Command(room, user, line string)
}
// SetRelay links the relay's rooms (nil: none).
// MemberLister is a relay that knows who is in its rooms elsewhere (an
// IRC network's users), for the rooms' member lists.
type MemberLister interface {
Members(room string) []RoomMember
}
// RemoteUser is someone on a chat network elsewhere, as a Messenger finds
// them.
type RemoteUser struct {
Nick string // the name they go by there
User string // their ident
Host string
Server string // the server they are on
Network string // the network's name
Real string // their real name (IRC's gecos)
Account string // their services account ("": none)
Away string
Since time.Time // when they came on ("": not known)
}
// Messenger is a relay that reaches people elsewhere by name: private
// messages to and from a network's users.
type Messenger interface {
Lookup(nick string) (RemoteUser, bool)
SendPrivate(from, to, text string, notice, emote bool) error
}
// SetRelay links the relay's rooms, in place of any others (nil: none).
func (b *BBS) SetRelay(r Relay) {
b.mu.Lock()
b.relay = r
b.relays = nil
if r != nil {
b.relays = []Relay{r}
}
b.mu.Unlock()
}
// relayFor is the relay if it carries room (nil if not, or no relay).
func (b *BBS) relayFor(room string) Relay {
// AddRelay links one more relay's rooms (a room is the first's that
// carries it).
func (b *BBS) AddRelay(r Relay) {
b.mu.Lock()
r := b.relay
b.relays = append(b.relays, r)
b.mu.Unlock()
if r != nil && r.Carries(room) {
return r
}
// relaysNow are the relays.
func (b *BBS) relaysNow() []Relay {
b.mu.Lock()
defer b.mu.Unlock()
return append([]Relay(nil), b.relays...)
}
// relayFor is the relay that carries room (nil if none does).
func (b *BBS) relayFor(room string) Relay {
for _, r := range b.relaysNow() {
if r.Carries(room) {
return r
}
}
return nil
}
// remoteMembers are those a relay knows in a room it carries.
func (b *BBS) remoteMembers(room string) []RoomMember {
if ml, ok := b.relayFor(room).(MemberLister); ok {
return ml.Members(room)
}
return nil
}
// LookupRemote finds someone of that name on a chat network.
func (b *BBS) LookupRemote(nick string) (RemoteUser, bool) {
for _, r := range b.relaysNow() {
if m, ok := r.(Messenger); ok {
if u, ok := m.Lookup(nick); ok {
return u, true
}
}
}
return RemoteUser{}, false
}
// ErrNoSuchNick: no one of that name is on, here or on a network.
var ErrNoSuchNick = errors.New("no one of that name is on")
// MessageRemote sends a private line to someone on a chat network (a
// notice, or an emote: /me).
func (n *Node) MessageRemote(nick, text string, notice, emote bool) error {
text = Clean(text, MaxChatLine)
if text == "" {
return errors.New("say something")
}
u := n.User()
if u == nil {
return errors.New("not logged in")
}
for _, r := range n.b.relaysNow() {
m, ok := r.(Messenger)
if !ok {
continue
}
if _, ok := m.Lookup(nick); !ok {
continue
}
if n.flood() {
return ErrFlood
}
return m.SendPrivate(u.Name, nick, text, notice, emote)
}
return ErrNoSuchNick
}
// RelayPrivate gives a user's nodes a private message from a network; it
// is how many nodes were told (0: the user is not on).
func (b *BBS) RelayPrivate(user string, e Event) int {
if e.Time.IsZero() {
e.Time = time.Now()
}
e.Kind = Private
e.Text = Clean(e.Text, 2*MaxChatLine)
b.mu.Lock()
var ns []*Node
for _, n := range b.nodes {
if n.user != nil && strings.EqualFold(n.user.Name, user) {
ns = append(ns, n)
}
}
b.mu.Unlock()
for _, n := range ns {
n.deliver(e)
}
return len(ns)
}
// RelayEvent gives a carried room's members what came from the network
// (said and emoted lines go in its history too).
func (b *BBS) RelayEvent(e Event) {
+55 -5
View File
@@ -70,7 +70,7 @@ func (c *client) command(m *ircmsg.Message) {
var on []string
for _, nick := range m.Params {
for _, w := range strings.Fields(nick) {
if len(c.nodesOf(w)) > 0 || fold(w) == fold(c.s.svc.Name) {
if _, remote := c.s.B.LookupRemote(w); len(c.nodesOf(w)) > 0 || remote || fold(w) == fold(c.s.svc.Name) {
on = append(on, w)
}
}
@@ -202,6 +202,9 @@ func (c *client) part(ch string) {
// member is a room member as NAMES and WHO give one: nick, user (how they
// came), host (their node), and op for a sysop (@).
func (c *client) member(m bbs.RoomMember) (nick, user, host string, op bool) {
if m.Node == 0 { // on a linked network: as it names them
return m.Name, m.Via, m.Host, false
}
nick, user, host = Nick(m.Name), m.Via, fmt.Sprintf("node%d", m.Node)
if u, err := c.s.B.Store.UserByName(m.Name); err == nil && u.Sysop {
op = true
@@ -331,6 +334,10 @@ func (c *client) whois(nick string) {
return
}
ns := c.nodesOf(nick)
if r, ok := c.s.B.LookupRemote(nick); len(ns) == 0 && ok {
c.whoisRemote(r)
return
}
if len(ns) == 0 {
c.reply(ERR_NOSUCHNICK, nick, "No such nick")
c.reply(RPL_ENDOFWHOIS, nick, "End of /WHOIS list")
@@ -359,6 +366,22 @@ func (c *client) whois(nick string) {
c.reply(RPL_ENDOFWHOIS, nick, "End of /WHOIS list")
}
// whoisRemote is WHOIS of someone on a linked network.
func (c *client) whoisRemote(r bbs.RemoteUser) {
c.reply(RPL_WHOISUSER, r.Nick, r.User, r.Host, "*", r.Real)
c.reply(RPL_WHOISSERVER, r.Nick, r.Server, "on "+r.Network)
if r.Away != "" {
c.reply(RPL_AWAY, r.Nick, r.Away)
}
if r.Account != "" {
c.reply(RPL_WHOISACCOUNT, r.Nick, r.Account, "is logged in as")
}
if !r.Since.IsZero() {
c.reply(RPL_WHOISIDLE, r.Nick, "0", strconv.FormatInt(r.Since.Unix(), 10), "seconds idle, signon time")
}
c.reply(RPL_ENDOFWHOIS, r.Nick, "End of /WHOIS list")
}
// list is LIST: the rooms, their numbers of callers (the service counted
// in a permanent room) and their topics.
func (c *client) list() {
@@ -467,6 +490,25 @@ func (c *client) privmsg(command, target, text string) {
return
}
ns := c.nodesOf(target)
if len(ns) == 0 && c.userOfNick(target) == nil {
// someone on a linked network?
err := c.n.MessageRemote(target, text, notice, emote)
switch {
case err == nil:
if emote {
text = "\x01ACTION " + text + "\x01"
}
if c.caps["echo-message"] {
c.send(map[string]string{"time": stamp(time.Now())}, c.source(), command, target, text)
}
case notice:
case errors.Is(err, bbs.ErrNoSuchNick):
c.reply(ERR_NOSUCHNICK, target, "No such nick")
default:
c.reply(ERR_CANNOTSENDTOCHAN, target, "Cannot send: "+err.Error())
}
return
}
if emote {
text = "* " + c.u.Name + " " + text
}
@@ -537,6 +579,14 @@ func (c *client) events() {
}
}
// sourceOfEvent is how an event's sender is named.
func (c *client) sourceOfEvent(e bbs.Event) string {
if e.Mask != "" {
return e.Mask // someone on a linked IRC network
}
return c.sourceOf(e.From, e.Node)
}
// sourceOf is how one on a node is named.
func (c *client) sourceOf(name string, node int) string {
if _, site, ok := strings.Cut(name, "@"); ok && node == 0 {
@@ -564,14 +614,14 @@ func (c *client) event(e bbs.Event) {
if e.Kind == bbs.Emoted {
text = "\x01ACTION " + text + "\x01"
}
c.send(tags, c.sourceOf(e.From, e.Node), "PRIVMSG", "#"+e.Room, text)
c.send(tags, c.sourceOfEvent(e), "PRIVMSG", "#"+e.Room, text)
case bbs.Joined:
if e.Node != c.n.Num {
c.send(tags, c.sourceOf(e.From, e.Node), "JOIN", "#"+e.Room)
c.send(tags, c.sourceOfEvent(e), "JOIN", "#"+e.Room)
}
case bbs.Left:
if e.Node != c.n.Num {
c.send(tags, c.sourceOf(e.From, e.Node), "PART", "#"+e.Room)
c.send(tags, c.sourceOfEvent(e), "PART", "#"+e.Room)
}
case bbs.Topic:
c.send(tags, c.s.svc.source(c), "TOPIC", "#"+e.Room, e.Text)
@@ -580,7 +630,7 @@ func (c *client) event(e bbs.Event) {
if e.Kept && !c.caps["server-time"] {
text = "[" + e.Time.Format("Jan 2 15:04") + "] " + text
}
c.send(tags, c.sourceOf(e.From, e.Node), "PRIVMSG", c.nick, text)
c.send(tags, c.sourceOfEvent(e), "PRIVMSG", c.nick, text)
case bbs.Paged:
text := fmt.Sprintf("%s (node %d) is paging you", e.From, e.Node)
if e.Text != "" {
+66
View File
@@ -11,6 +11,7 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"net"
@@ -465,6 +466,71 @@ func TestRelayedLines(t *testing.T) {
c.expect(":irc.test NOTICE #mrc-lobby :- dave has arrived.")
}
// network is a linked network as the BBS's relays see one: dave in its
// rooms (net-), the lines sent to him kept.
type network struct {
mu sync.Mutex
sent []string
}
func (n *network) Carries(room string) bool { return strings.HasPrefix(room, "net-") }
func (n *network) Allows(room string, u *store.User) bool { return true }
func (n *network) Joined(room, user string) {}
func (n *network) Left(room, user string) {}
func (n *network) Said(room, user, text string, emote bool) {}
func (n *network) Command(room, user, line string) {}
func (n *network) Members(room string) []bbs.RoomMember {
return []bbs.RoomMember{{Name: "dave", Via: "~dv", Host: "far.example"}}
}
func (n *network) Lookup(nick string) (bbs.RemoteUser, bool) {
if !strings.EqualFold(nick, "dave") {
return bbs.RemoteUser{}, false
}
return bbs.RemoteUser{Nick: "dave", User: "~dv", Host: "far.example", Server: "hub.far.example",
Network: "FarNet", Real: "Dave", Account: "dave"}, true
}
func (n *network) SendPrivate(from, to, text string, notice, emote bool) error {
n.mu.Lock()
defer n.mu.Unlock()
n.sent = append(n.sent, fmt.Sprintf("%s>%s %v %v: %s", from, to, notice, emote, text))
return nil
}
// TestLinkedNetwork: a linked network's users in a room's NAMES and WHO,
// in WHOIS and ISON; PRIVMSGs to them (an ACTION too) sent by the relay;
// and their lines named as the network names them.
func TestLinkedNetwork(t *testing.T) {
e := start(t)
net := &network{}
e.b.AddRelay(net)
c := e.dial(t)
c.login("alice", "alice")
c.send("JOIN #net-retro")
if l := c.expect(" 353 "); !strings.Contains(l, "dave") {
t.Errorf("names %q", l)
}
c.send("WHO #net-retro")
c.expect(" 352 alice #net-retro ~dv far.example irc.test dave H")
c.send("WHOIS dave")
c.expect(" 311 alice dave ~dv far.example * :Dave")
c.expect(" 312 alice dave hub.far.example :on FarNet")
c.expect(" 330 alice dave dave")
c.send("ISON dave nobody")
c.expect(" 303 alice :dave")
c.send("PRIVMSG dave :hello", "PRIVMSG dave :\x01ACTION waves\x01", "PRIVMSG nobody :hm")
c.expect(" 401 alice nobody")
net.mu.Lock()
sent := strings.Join(net.sent, "|")
net.mu.Unlock()
if sent != "alice>dave false false: hello|alice>dave false true: waves" {
t.Errorf("sent %q", sent)
}
e.b.RelayEvent(bbs.Event{Kind: bbs.Said, Room: "net-retro", From: "dave", Mask: "dave!~dv@far.example", Text: "hi"})
c.expect(":dave!~dv@far.example PRIVMSG #net-retro :hi")
e.b.RelayPrivate("alice", bbs.Event{From: "dave", Mask: "dave!~dv@far.example", Text: "psst"})
c.expect(":dave!~dv@far.example PRIVMSG alice :psst")
}
// TestKeptMessages: a PRIVMSG to a user not on is kept (301 says so), and
// given them when they come, by IRC (its time as server-time) or the
// terminal; a terminal's /msg by name, and the conversation read back.
+401
View File
@@ -0,0 +1,401 @@
package irclink
import (
"strconv"
"strings"
"time"
"github.com/D-Modem/bbs/internal/bbs"
)
// eventNotice is a notice for a BBS user from the network.
func eventNotice(text string) bbs.Event {
return bbs.Event{Kind: bbs.Private, From: "IRC", Text: text}
}
// newUser is UID or EUID: a user behind the link. A nick of a BBS user
// is theirs no more (the BBS user is renamed Nick|Tag); one of a user
// elsewhere goes by the TS6 rules: the newer is killed (both, if as old).
func (h *Hub) newUser(l *link, src, nick, ts, umodes, ident, host, ip, uid, account, real, raw string) {
s := h.servers[src]
if s == nil || s.link != l || h.users[uid] != nil || len(uid) != 9 || uid[:3] != s.sid {
return
}
t, _ := strconv.ParseInt(ts, 10, 64)
u := &user{uid: uid, nick: nick, ts: t, umodes: umodes, ident: ident, host: host, ip: ip, real: real,
account: account, srv: s, since: time.Now()}
if o := h.nicks[fold(nick)]; o != nil {
switch {
case o.local != "":
h.renameLocal(o)
case t < o.ts:
h.killUser(o, nil, "Nick collision (older nick overruled)")
case t > o.ts:
l.send(h.me.sid, "KILL", uid, h.me.name+" (Nick collision (newer killed))")
return
default:
h.killUser(o, nil, "Nick collision (both killed)")
l.send(h.me.sid, "KILL", uid, h.me.name+" (Nick collision (both killed))")
return
}
}
h.addUser(u)
h.forward(l, raw)
}
// nickChange is NICK from a user, by the same rules.
func (h *Hub) nickChange(l *link, src, nick, ts, raw string) {
u := h.users[src]
if u == nil || u.local != "" || nick == "" {
return
}
t, _ := strconv.ParseInt(ts, 10, 64)
if o := h.nicks[fold(nick)]; o != nil && o != u {
switch {
case o.local != "":
h.renameLocal(o)
case t < o.ts:
h.killUser(o, nil, "Nick collision (older nick overruled)")
default:
h.killUser(u, nil, "Nick collision (newer killed)")
return
}
}
h.renick(u, nick, t)
h.forward(l, raw)
}
// renick changes a user's nick, telling the rooms they are in.
func (h *Hub) renick(u *user, nick string, ts int64) {
was := h.display(u)
if h.nicks[fold(u.nick)] == u {
delete(h.nicks, fold(u.nick))
}
u.nick, u.ts = nick, ts
h.nicks[fold(nick)] = u
if u.local != "" {
return
}
now := h.display(u)
if fold(now) == fold(was) {
return
}
for ch := range u.chans {
if r := h.room(ch.name); r != "" {
h.B.RelayEvent(bbs.Event{Kind: bbs.Notice, Room: r, Text: was + " is now known as " + now})
}
}
}
// renameLocal renames a BBS user, whose nick someone elsewhere has, to
// Nick|Tag, and tells the network.
func (h *Hub) renameLocal(u *user) {
old := u.nick
nick := h.tagged(nickOf(u.local), h.me, u, old)
if o := h.nicks[fold(nick)]; o != nil && o != u {
return
}
now := time.Now().Unix()
h.renick(u, nick, now)
if h.nicks[fold(old)] == u {
delete(h.nicks, fold(old))
}
h.broadcast(line(u.uid, "NICK", nick, strconv.FormatInt(now, 10)))
h.B.Log.Printf("irclink: %s is %s on the network (%s was taken)", u.local, nick, old)
}
// killUser takes a user off the network, telling every link but from.
func (h *Hub) killUser(u *user, from *link, why string) {
h.removeUser(u, why)
h.forward(from, line(h.me.sid, "KILL", u.uid, h.me.name+" ("+why+")"))
}
// kill is KILL: one elsewhere is gone; one of ours is off the network
// until they come on the BBS again.
func (h *Hub) kill(l *link, src, target, why, raw string) {
u := h.users[target]
if u == nil {
return
}
if u.local != "" {
h.killed[fold(u.local)] = true
h.B.RelayPrivate(u.local, eventNotice("You were removed from the IRC network: "+why))
h.B.Log.Printf("irclink: %s killed by %s: %s", u.local, src, why)
}
h.removeUser(u, "Killed: "+why)
h.forward(l, raw)
}
// sjoin is SJOIN: a channel and members behind the link, by the TS rules
// (an older channel's modes and ops win; a newer one's are dropped).
func (h *Hub) sjoin(l *link, ts, name, modes string, rest []string, raw string) {
if !strings.HasPrefix(name, "#") || len(rest) == 0 {
return
}
t, _ := strconv.ParseInt(ts, 10, 64)
ch := h.channel(name, t)
keepTheirs := true
switch {
case t < ch.ts:
ch.ts, ch.modes = t, modes
for u := range ch.members {
u.chans[ch] = "" // ours lose their ops
}
case t > ch.ts:
keepTheirs = false
}
if len(ch.members) == 0 {
ch.modes = modes
}
for _, m := range strings.Fields(rest[len(rest)-1]) {
uid := strings.TrimLeft(m, "@+%~&!")
u := h.users[uid]
if u == nil || u.srv.link != l {
continue
}
prefix := ""
if keepTheirs {
prefix = m[:len(m)-len(uid)]
}
h.join(u, ch, prefix)
}
h.forward(l, raw)
}
// userJoin is JOIN from a user: "0" parts all, else one channel by the
// simple TS rules.
func (h *Hub) userJoin(l *link, src, ts, name, raw string) {
u := h.users[src]
if u == nil {
return
}
if ts == "0" {
for ch := range u.chans {
h.part(u, ch, h.display(u), "")
}
h.forward(l, raw)
return
}
t, _ := strconv.ParseInt(ts, 10, 64)
ch := h.channel(name, t)
if t < ch.ts {
ch.ts = t
for o := range ch.members {
o.chans[ch] = ""
}
}
h.join(u, ch, "")
h.forward(l, raw)
}
// topic is TOPIC, TB or ETB: a channel's topic, told to its room.
func (h *Hub) topic(l *link, command string, params []string, raw string) {
if len(params) < 2 {
return
}
ch := h.chans[fold(params[0])]
if ch != nil {
text := params[len(params)-1]
if command == "TB" && len(params) >= 3 {
// TB keeps the older topic
if t, _ := strconv.ParseInt(params[1], 10, 64); ch.topic != "" && t >= ch.ts && t != 0 {
h.forward(l, raw)
return
}
}
ch.topic = text
if r := h.room(ch.name); r != "" {
h.B.RelayEvent(bbs.Event{Kind: bbs.Notice, Room: r, Text: "Topic of " + ch.name + ": " + text})
}
}
h.forward(l, raw)
}
// message is PRIVMSG or NOTICE: to a channel (its room told, and on to
// the others), or to a user (one of ours told; else on toward them).
func (h *Hub) message(l *link, src, command, target, text, raw string) {
from := h.users[src]
switch {
case target == "":
case strings.HasPrefix(target, "$"): // to the servers matching: everyone
h.forward(l, raw)
case strings.ContainsRune("#@+=", rune(target[0])):
name := strings.TrimLeft(target, "@+=")
h.forward(l, raw)
ch := h.chans[fold(name)]
if ch == nil || from == nil || name != target {
return // to a channel's ops (or voiced): the BBS's users are neither
}
r := h.room(ch.name)
if r == "" {
return
}
nick := h.display(from)
e := bbs.Event{Kind: bbs.Said, Room: r, From: nick, Mask: from.mask(nick), Text: text}
if body, ok := ctcp(text); ok {
action, isAction := strings.CutPrefix(body, "ACTION ")
if !isAction {
return
}
e.Kind, e.Text = bbs.Emoted, action
} else if command == "NOTICE" {
e.Kind, e.Text = bbs.Notice, "-"+nick+"- "+text
}
h.B.RelayEvent(e)
default:
u := h.users[target]
if u == nil {
if nick, _, ok := strings.Cut(target, "@"); ok {
u = h.nicks[fold(nick)]
} else {
u = h.nicks[fold(target)]
}
}
if u == nil {
return
}
if u.local == "" {
h.route(u.uid, l, raw)
return
}
if from == nil {
return // from a server: nothing to answer
}
nick := h.display(from)
if body, ok := ctcp(text); ok {
action, isAction := strings.CutPrefix(body, "ACTION ")
if !isAction {
if command == "PRIVMSG" && body == "VERSION" {
l.send(u.uid, "NOTICE", from.uid, "\x01VERSION bbs-sec, the chat of "+h.B.Conf().Name+"\x01")
}
return
}
text = "* " + nick + " " + action
}
h.B.RelayPrivate(u.local, bbs.Event{From: nick, Mask: from.mask(nick), Text: text})
}
}
// ctcp is a CTCP's body (\x01...\x01).
func ctcp(text string) (string, bool) {
if !strings.HasPrefix(text, "\x01") {
return "", false
}
return strings.TrimSuffix(text[1:], "\x01"), true
}
// whois is WHOIS for a user: answered for one of ours, else sent on.
func (h *Hub) whois(l *link, src, target, nick, raw string) {
if !h.isMe(target) {
if u := h.users[target]; u == nil || u.local == "" {
h.route(target, l, raw)
return
}
}
from := h.users[src]
if from == nil {
return
}
if nick == "" {
nick = target
}
reply := func(numeric string, params ...string) {
l.send(h.me.sid, numeric, append([]string{from.uid}, params...)...)
}
u := h.nicks[fold(nick)]
if u == nil || u.local == "" {
reply("401", nick, "No such nick/channel")
reply("318", nick, "End of /WHOIS list.")
return
}
real := u.real
if bu, err := h.B.Store.UserByName(u.local); err == nil && bu.Location != "" {
real += ", " + bu.Location
}
reply("311", u.nick, u.ident, u.host, "*", real)
var chans []string
for ch, prefix := range u.chans {
chans = append(chans, prefix+ch.name)
}
if len(chans) > 0 {
reply("319", u.nick, strings.Join(chans, " "))
}
reply("312", u.nick, h.me.name, h.me.desc)
for _, n := range h.B.Nodes() {
if strings.EqualFold(n.User, u.local) {
reply("320", u.nick, "is on node "+strconv.Itoa(n.Num)+" of "+h.B.Conf().Name+" by "+n.Via+": "+n.Activity)
}
}
if u.away != "" {
reply("301", u.nick, u.away)
}
reply("330", u.nick, u.account, "is logged in as")
reply("317", u.nick, "0", strconv.FormatInt(u.since.Unix(), 10), "seconds idle, signon time")
reply("318", u.nick, "End of /WHOIS list.")
}
// query is a query of a server (VERSION, MOTD, ...): answered if it is
// the BBS's, else sent on toward it.
func (h *Hub) query(l *link, src, command string, params []string, raw string) {
target := ""
switch command {
case "STATS", "TRACE":
if len(params) > 1 {
target = params[1]
}
default:
if len(params) > 0 {
target = params[len(params)-1]
}
}
if target != "" && !h.isMe(target) {
h.route(target, l, raw)
return
}
from := h.users[src]
if from == nil {
return
}
reply := func(numeric string, params ...string) {
l.send(h.me.sid, numeric, append([]string{from.uid}, params...)...)
}
switch command {
case "VERSION":
reply("351", "bbs-sec.", h.me.name, "TS6 hub for the chat of "+h.B.Conf().Name)
case "MOTD":
text := strings.TrimRight(h.B.MOTDText(), "\n")
if text == "" {
reply("422", "MOTD File is missing")
return
}
reply("375", "- "+h.me.name+" Message of the Day - ")
for _, s := range strings.Split(text, "\n") {
reply("372", "- "+strings.TrimRight(s, "\r"))
}
reply("376", "End of /MOTD command.")
case "ADMIN":
reply("256", h.me.name, "Administrative info")
reply("257", h.B.Conf().Name)
reply("258", "Sysop: "+h.B.Conf().Sysop)
case "INFO":
reply("371", h.B.Conf().Name+": its chat rooms, as a TS6 server")
reply("374", "End of /INFO list.")
case "TIME":
reply("391", h.me.name, time.Now().Format(time.RFC1123))
case "LINKS":
for _, s := range h.servers {
up := s
if s.uplink != nil {
up = s.uplink
}
reply("364", s.name, up.name, strconv.Itoa(s.hops)+" "+s.desc)
}
reply("365", "*", "End of /LINKS list.")
case "STATS":
reply("219", strings.Join(params[:min(len(params), 1)], ""), "End of /STATS report")
case "TRACE":
reply("262", h.me.name, "End of TRACE")
default:
reply("265", strconv.Itoa(len(h.local)), "Local users")
}
}
+328
View File
@@ -0,0 +1,328 @@
// Package irclink links the BBS's chat into an IRC network as a hub
// server, by TS6: the server-to-server protocol of Solanum (Libera.Chat),
// charybdis, ircd-ratbox and ircd-hybrid (EFnet). It takes any number of
// server links, in and out, and routes between them as a hub does.
//
// Every BBS user online, on a terminal, the web, IRC, AIM or any other way,
// is a user on the network, whom anyone there can /msg and /whois. The
// BBS's rooms beginning with the prefix (irc- by default) are the network's
// channels: irc-retro is #retro, and talk in one is talk in the other.
//
// A nick taken on the network when a BBS user comes on, or found taken
// when a link comes up, is not fought over: the BBS user is renamed
// Nick|Tag, Tag being the BBS's short tag. When two users of other
// servers collide, the TS6 rules apply (the newer nick is killed).
package irclink
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"regexp"
"strings"
"sync"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/ircd"
"github.com/D-Modem/bbs/internal/sockets"
)
// Settings are the [irclink] section's.
type Settings struct {
ServerName string // the BBS's server name on the network (irc.bbs.example)
SID string // its TS6 server ID: a digit, then two letters or digits
Description string
Network string // the network's name, as WHOIS shows it
Tag string // the short tag of a renamed nick (Nick|Tag)
Host string // the BBS users' host (default: the server name)
Prefix string // the rooms that are channels ("": every room but sysop-)
NickLen int // the network's longest nick
Address string // where servers link in ("": nowhere)
TLSAddress string // the same, by TLS
CertFile string
KeyFile string
Peers []Peer
Retry time.Duration // between tries of a link out (default 30s)
}
// Peer is a server the BBS links with ([ircpeer NAME]).
type Peer struct {
Name string // its server name
Address string // host:port to link out to ("": it links in)
TLS bool // link out by TLS
TLSVerify bool // check its certificate
SendPassword string // the password we send it
AcceptPassword string // the password it must send us
Tag string // its users' tag, beside a BBS user of the same nick
Hybrid bool // it is ircd-hybrid 8, whose TS6 differs (protocol = hybrid)
}
var (
sidRE = regexp.MustCompile(`^[0-9][0-9A-Z]{2}$`)
tagRE = regexp.MustCompile(`^[A-Za-z0-9]{1,8}$`)
nameRE = regexp.MustCompile(`^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$`)
)
// Check checks the settings, filling in the defaults.
func (s *Settings) Check(bbsName string) error {
if !nameRE.MatchString(s.ServerName) {
return errors.New("server_name: a host-like name with a dot (irc.bbs.example)")
}
s.SID = strings.ToUpper(s.SID)
if !sidRE.MatchString(s.SID) {
return errors.New("sid: a digit and two letters or digits (1BB)")
}
if s.Description == "" {
s.Description = bbsName
}
if s.Tag == "" {
s.Tag = defaultTag(bbsName)
}
if !tagRE.MatchString(s.Tag) {
return errors.New("tag: 1 to 8 letters or digits")
}
if s.Host == "" {
s.Host = s.ServerName
}
if s.NickLen == 0 {
s.NickLen = 30
}
if s.Retry == 0 {
s.Retry = 30 * time.Second
}
seen := map[string]bool{}
for i := range s.Peers {
p := &s.Peers[i]
if !nameRE.MatchString(p.Name) {
return fmt.Errorf("[ircpeer %s]: the section's name is the server's name", p.Name)
}
if seen[fold(p.Name)] || fold(p.Name) == fold(s.ServerName) {
return fmt.Errorf("[ircpeer %s] given twice, or our own name", p.Name)
}
seen[fold(p.Name)] = true
if p.AcceptPassword == "" || p.SendPassword == "" {
return fmt.Errorf("[ircpeer %s]: send_password and accept_password", p.Name)
}
if strings.ContainsAny(p.SendPassword+p.AcceptPassword, " :") {
return fmt.Errorf("[ircpeer %s]: a password has no spaces or colons", p.Name)
}
if p.Tag == "" {
p.Tag = defaultTag(p.Name)
}
if !tagRE.MatchString(p.Tag) {
return fmt.Errorf("[ircpeer %s] tag: 1 to 8 letters or digits", p.Name)
}
}
return nil
}
// defaultTag is a name's first letters and digits, up to 4, as a tag.
func defaultTag(name string) string {
var b strings.Builder
for _, r := range name {
if r == '.' && b.Len() > 0 {
break
}
if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' {
b.WriteRune(r)
}
if b.Len() == 4 {
break
}
}
if b.Len() == 0 {
return "BBS"
}
return b.String()
}
// Hub is the BBS as a server on the network.
type Hub struct {
B *bbs.BBS
S Settings
mu sync.Mutex
me *server
servers map[string]*server // by SID
names map[string]*server // by folded name
users map[string]*user // by UID
nicks map[string]*user // by folded nick
chans map[string]*channel
local map[string]*user // ours, by folded BBS name
killed map[string]bool // BBS users killed off the network, until they come on again
links map[*link]bool
nextUID int
started time.Time
}
// New makes the hub (Check the settings first).
func New(b *bbs.BBS, s Settings) (*Hub, error) {
if err := s.Check(b.Conf().Name); err != nil {
return nil, err
}
h := &Hub{B: b, S: s, servers: map[string]*server{}, names: map[string]*server{},
users: map[string]*user{}, nicks: map[string]*user{}, chans: map[string]*channel{},
local: map[string]*user{}, killed: map[string]bool{}, links: map[*link]bool{}, started: time.Now()}
h.me = &server{sid: s.SID, name: s.ServerName, desc: s.Description, tag: s.Tag}
h.servers[h.me.sid] = h.me
h.names[fold(h.me.name)] = h.me
return h, nil
}
// Run links until ctx is done: it listens for servers linking in, links
// out to those with addresses (again whenever a link drops), and puts the
// BBS's users on the network as they come and go.
func (h *Hub) Run(ctx context.Context) error {
stop := h.B.WatchPresence(h.presence)
defer stop()
seen := map[string]bool{}
for _, n := range h.B.Nodes() {
if n.User != "" && !seen[fold(n.User)] {
seen[fold(n.User)] = true
h.presence(n.User, true)
}
}
var lns []net.Listener
if h.S.Address != "" {
ln, err := sockets.Listen("tcp", h.S.Address)
if err != nil {
return fmt.Errorf("irclink: %w", err)
}
lns = append(lns, ln)
}
if h.S.TLSAddress != "" {
cert, err := tls.LoadX509KeyPair(h.S.CertFile, h.S.KeyFile)
if err != nil {
return fmt.Errorf("irclink: certificate: %w", err)
}
ln, err := sockets.Listen("tcp", h.S.TLSAddress)
if err != nil {
return fmt.Errorf("irclink: %w", err)
}
lns = append(lns, tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}))
}
var wg sync.WaitGroup
for _, ln := range lns {
wg.Add(1)
go func() {
defer wg.Done()
for {
c, err := ln.Accept()
if err != nil {
return
}
if h.B.Refuse("irclink", c.RemoteAddr()) {
c.Close()
continue
}
go h.serve(ctx, c, nil)
}
}()
}
for i := range h.S.Peers {
if p := &h.S.Peers[i]; p.Address != "" {
wg.Add(1)
go func() { defer wg.Done(); h.linkOut(ctx, p) }()
}
}
<-ctx.Done()
for _, ln := range lns {
ln.Close()
}
h.mu.Lock()
for l := range h.links {
l.sendRaw("ERROR :Shutting down")
go l.finish()
}
h.mu.Unlock()
wg.Wait()
return nil
}
// linkOut links to a peer, and again after its link drops.
func (h *Hub) linkOut(ctx context.Context, p *Peer) {
for ctx.Err() == nil {
if !h.linked(p.Name) {
d := net.Dialer{Timeout: 20 * time.Second}
c, err := d.DialContext(ctx, "tcp", p.Address)
if err == nil && p.TLS {
host, _, _ := net.SplitHostPort(p.Address)
tc := tls.Client(c, &tls.Config{ServerName: host, InsecureSkipVerify: !p.TLSVerify, MinVersion: tls.VersionTLS12})
if err = tc.HandshakeContext(ctx); err != nil {
c.Close()
}
c = tc
}
if err != nil {
h.B.Log.Printf("irclink: %s: %v", p.Name, err)
} else {
h.serve(ctx, c, p)
}
}
select {
case <-ctx.Done():
case <-time.After(h.S.Retry):
}
}
}
// linked: a server of that name is on the network.
func (h *Hub) linked(name string) bool {
h.mu.Lock()
defer h.mu.Unlock()
return h.names[fold(name)] != nil
}
// peer is the configured peer of a name (nil: none).
func (h *Hub) peer(name string) *Peer {
for i := range h.S.Peers {
if fold(h.S.Peers[i].Name) == fold(name) {
return &h.S.Peers[i]
}
}
return nil
}
// Links is how many servers are linked to the BBS directly, and how many
// are on the network besides it.
func (h *Hub) Links() (direct, network int) {
h.mu.Lock()
defer h.mu.Unlock()
for l := range h.links {
if l.srv != nil {
direct++
}
}
return direct, len(h.servers) - 1
}
// fold is a nick or channel as compared (rfc1459, as TS6 servers fold).
func fold(s string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= 'A' && r <= 'Z':
return r + 32
case r == '[':
return '{'
case r == ']':
return '}'
case r == '\\':
return '|'
case r == '~':
return '^'
}
return r
}, s)
}
// nickOf is a BBS name as a nick on the network.
func nickOf(name string) string {
n := ircd.Nick(name)
if n == "" || n[0] >= '0' && n[0] <= '9' || n[0] == '-' {
n = "_" + n
}
return n
}
+329
View File
@@ -0,0 +1,329 @@
package irclink
import (
"bufio"
"bytes"
"context"
"log"
"net"
"path/filepath"
"strings"
"testing"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
)
// peerServer is a TS6 server the hub links out to, as a test drives it.
type peerServer struct {
t *testing.T
ln net.Listener
conn net.Conn
lines chan string
seen []string
}
// newPeer listens for the hub's link.
func newPeer(t *testing.T) *peerServer {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
return &peerServer{t: t, ln: ln, lines: make(chan string, 1000)}
}
// accept takes the hub's link and reads its lines.
func (p *peerServer) accept() {
p.t.Helper()
p.ln.(*net.TCPListener).SetDeadline(time.Now().Add(5 * time.Second))
c, err := p.ln.Accept()
if err != nil {
p.t.Fatal(err)
}
p.conn = c
p.t.Cleanup(func() { c.Close() })
go func() {
r := bufio.NewScanner(c)
for r.Scan() {
p.lines <- strings.TrimRight(r.Text(), "\r")
}
close(p.lines)
}()
}
// say sends lines to the hub.
func (p *peerServer) say(lines ...string) {
for _, l := range lines {
p.conn.Write([]byte(l + "\r\n"))
}
}
// expect waits for a line from the hub with every one of wants in it.
func (p *peerServer) expect(wants ...string) string {
p.t.Helper()
deadline := time.After(3 * time.Second)
for {
select {
case l, ok := <-p.lines:
if !ok {
p.t.Fatalf("link closed; no %q among %q", wants, p.seen)
}
p.seen = append(p.seen, l)
all := true
for _, w := range wants {
if !strings.Contains(l, w) {
all = false
}
}
if all {
return l
}
case <-deadline:
p.t.Fatalf("no %q among %q", wants, p.seen)
}
}
}
// link is the TS6 handshake from the peer's side, with its burst.
func (p *peerServer) link(name, sid string, burst ...string) {
p.t.Helper()
p.accept()
p.expect("PASS", "sendpw", "TS", "6", "1BB")
p.expect("CAPAB", "EUID")
p.expect("SERVER", "irc.test.example", "1")
p.expect("PING")
p.say("PASS acceptpw TS 6 :"+sid, "CAPAB :QS EX IE ENCAP TB EUID SAVE", "SERVER "+name+" 1 :a test server",
"SVINFO 6 6 0 :1700000000")
p.say(burst...)
p.say(":" + sid + " PONG " + name + " :irc.test.example")
}
type env struct {
b *bbs.BBS
hub *Hub
}
// start is a BBS (alice and bob) with its hub, linking out to peers.
func start(t *testing.T, peers ...*peerServer) *env {
t.Helper()
store.BcryptCost = 4
st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
for _, n := range []string{"alice", "bob"} {
st.CreateUser(n, "password1", "", false)
}
s := bbs.Defaults()
s.Name = "Test BBS"
b := bbs.New(s, st, log.New(&bytes.Buffer{}, "", 0))
set := Settings{ServerName: "irc.test.example", SID: "1BB", Network: "TestNet", Prefix: "irc-",
Retry: 100 * time.Millisecond}
names := []string{"far.example", "other.example"}
for i, p := range peers {
set.Peers = append(set.Peers, Peer{Name: names[i], Address: p.ln.Addr().String(),
SendPassword: "sendpw", AcceptPassword: "acceptpw"})
}
h, err := New(b, set)
if err != nil {
t.Fatal(err)
}
b.AddRelay(h)
return &env{b: b, hub: h}
}
// run runs the hub until the test ends.
func (e *env) run(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { e.hub.Run(ctx); close(done) }()
t.Cleanup(func() { cancel(); <-done })
}
// node is a node on telnet with the user name.
func (e *env) node(t *testing.T, name string) *bbs.Node {
t.Helper()
u, _ := e.b.Store.UserByName(name)
n, err := e.b.Enter(&bbs.Caller{Via: "telnet"}, nil)
if err != nil {
t.Fatal(err)
}
n.SetUser(u)
t.Cleanup(n.Leave)
return n
}
// held are events taken from a node and not yet waited for.
var held = map[*bbs.Node][]bbs.Event{}
// wait waits for a node's event with want in it; it is the event.
func wait(t *testing.T, n *bbs.Node, want string) bbs.Event {
t.Helper()
deadline := time.After(3 * time.Second)
var seen []string
for {
evs := append(held[n], n.Pending()...)
held[n] = nil
for i, e := range evs {
if strings.Contains(e.String(), want) {
held[n] = evs[i+1:]
return e
}
seen = append(seen, e.String())
}
select {
case <-n.Wake():
case <-deadline:
t.Fatalf("no %q among %q", want, seen)
}
}
}
// TestLink: the handshake; a BBS user whose nick the peer has renamed
// Nick|Tag before they are sent; the rooms and channels as one (joins,
// talk, emotes, members, the other's name beside a BBS user's); private
// messages both ways; WHOIS of a BBS user from the network; one coming on
// the BBS later put on the network.
func TestLink(t *testing.T) {
p := newPeer(t)
e := start(t, p)
alice := e.node(t, "alice")
e.run(t)
p.link("far.example", "42X",
":42X UID alice 1 100 +i al far.host 0 42XAAAAAA :Alice of far",
":42X UID carol 1 100 +i ca far.host 0 42XAAAAAB :Carol",
":42X SJOIN 100 #retro +nt :@42XAAAAAA 42XAAAAAB")
p.expect("EUID alice|Test 1", "+i bbs irc.test.example 0 1BBAAAAAA * alice :alice")
p.expect(":1BB PING irc.test.example :42X")
// the room is the channel
if _, err := alice.JoinRoom("irc-retro"); err != nil {
t.Fatal(err)
}
p.expect(":1BBAAAAAA JOIN 100 #retro +")
names := map[string]bool{}
for _, m := range e.b.RoomMembers("irc-retro") {
names[m.Name] = true
}
if !names["alice"] || !names["alice|far"] || !names["carol"] {
t.Errorf("members %v", names)
}
p.say(":42XAAAAAB PRIVMSG #retro :hi there", ":42XAAAAAA PRIVMSG #retro :\x01ACTION waves\x01")
if ev := wait(t, alice, "carol: hi there"); ev.Mask != "carol!ca@far.host" {
t.Errorf("mask %q", ev.Mask)
}
wait(t, alice, "* alice|far waves")
if err := alice.Say("hello all", false); err != nil {
t.Fatal(err)
}
p.expect(":1BBAAAAAA PRIVMSG #retro :hello all")
if err := alice.Say("dances", true); err != nil {
t.Fatal(err)
}
p.expect(":1BBAAAAAA PRIVMSG #retro :\x01ACTION dances\x01")
// private messages
p.say(":42XAAAAAB PRIVMSG 1BBAAAAAA :psst")
wait(t, alice, "carol")
if err := alice.MessageRemote("carol", "hi carol", false, false); err != nil {
t.Fatal(err)
}
p.expect(":1BBAAAAAA PRIVMSG 42XAAAAAB :hi carol")
if err := alice.MessageRemote("alice|far", "hello me", false, false); err != nil {
t.Fatal(err)
}
p.expect(":1BBAAAAAA PRIVMSG 42XAAAAAA :hello me")
if r, ok := e.b.LookupRemote("carol"); !ok || r.Server != "far.example" || r.Host != "far.host" {
t.Errorf("lookup %+v %v", r, ok)
}
// WHOIS from the network
p.say(":42XAAAAAB WHOIS 1BB :alice|Test")
p.expect(":1BB 311 42XAAAAAB alice|Test bbs irc.test.example *")
p.expect(":1BB 319 42XAAAAAB alice|Test :#retro")
p.expect(":1BB 318 42XAAAAAB alice|Test")
// a nick change to one of ours: ours is renamed
bob := e.node(t, "bob")
p.expect("EUID bob 1", "1BBAAAAAB")
p.say(":42XAAAAAB NICK bob :200")
p.expect(":1BBAAAAAB NICK bob|Test")
bob.Leave()
p.expect(":1BBAAAAAB QUIT :Signed off")
// a remote user leaves the channel: the room is told
p.say(":42XAAAAAB PART #retro :bye")
wait(t, alice, "<- bob left") // carol is bob now, and the BBS's bob is gone: bob as is
}
// TestHub: a second server is given the first's servers, users and
// channels; lines between them go through; a split of one is told to the
// other; a collision between their users is settled by TS.
func TestHub(t *testing.T) {
p1, p2 := newPeer(t), newPeer(t)
e := start(t, p1, p2)
e.run(t)
p1.link("far.example", "42X",
":42X SID leaf.example 2 42Y :behind far",
":42Y UID dave 2 100 +i da leaf.host 0 42YAAAAAA :Dave",
":42X UID erin 1 100 +i er far.host 0 42XAAAAAA :Erin",
":42X SJOIN 100 #retro +nt :@42XAAAAAA 42YAAAAAA")
p1.expect(":1BB PING irc.test.example :42X")
p2.link("other.example", "43Z",
":43Z UID erin 1 50 +i er2 other.host 0 43ZAAAAAA :Older Erin",
":43Z UID frank 1 100 +i fr other.host 0 43ZAAAAAB :Frank")
// p2 gets the network
p2.expect(":1BB SID far.example 2 42X")
p2.expect(":42X SID leaf.example 3 42Y")
p2.expect("EUID dave", "42YAAAAAA")
p2.expect(":1BB SJOIN 100 #retro +nt", "42YAAAAAA")
// the newer erin (far's) was killed, everywhere
p1.expect(":1BB KILL 42XAAAAAA")
p1.expect(":43Z UID erin 1 50")
p1.expect(":43Z UID frank")
// lines go through
p2.say(":43ZAAAAAB PRIVMSG 42YAAAAAA :hi dave")
p1.expect(":43ZAAAAAB PRIVMSG 42YAAAAAA :hi dave")
p1.say(":42YAAAAAA PRIVMSG #retro :hi all")
p2.expect(":42YAAAAAA PRIVMSG #retro :hi all")
// a split
p1.conn.Close()
p2.expect(":1BB SQUIT 42X")
if d, n := e.hub.Links(); d != 1 || n != 1 {
t.Errorf("links %d, %d", d, n)
}
if _, ok := e.b.LookupRemote("dave"); ok {
t.Error("dave is still on")
}
}
// TestRefused: a bad password, and a server not configured, are refused.
func TestRefused(t *testing.T) {
p := newPeer(t)
e := start(t, p)
e.run(t)
p.accept()
p.expect("PING")
p.say("PASS wrong TS 6 :42X", "CAPAB :QS ENCAP", "SERVER far.example 1 :x")
p.expect("ERROR", "bad password")
}
// TestTagged: Nick|Tag cut to the nick length, then numbered.
func TestTagged(t *testing.T) {
e := start(t)
h := e.hub
h.S.NickLen = 9
if n := h.tagged("alexander", h.me, nil, ""); n != "alex|Test" {
t.Errorf("tagged %q", n)
}
h.nicks[fold("alex|Test")] = &user{}
if n := h.tagged("alexander", h.me, nil, ""); n != "ale|Test2" {
t.Errorf("numbered %q", n)
}
if fold("Nick[A]~") != "nick{a}^" {
t.Error("rfc1459 folding")
}
}
+637
View File
@@ -0,0 +1,637 @@
package irclink
import (
"bufio"
"context"
"errors"
"net"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/ergochat/irc-go/ircmsg"
"github.com/ergochat/irc-go/ircreader"
)
// limits of a link
const (
maxLine = 512
sendQ = 8192 // lines waiting to be written; more drops the link
registerLimit = time.Minute
idleLimit = 3 * time.Minute // without a line: a PING
pingLimit = 2 * time.Minute // for its answer
writeLimit = 60 * time.Second
)
// capab is what the BBS tells its peers it speaks.
const capab = "QS EX CHW IE KNOCK TB ENCAP SAVE EUID EOPMOD"
var roomRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,19}$`)
// link is a connection to a server.
type link struct {
h *Hub
conn net.Conn
peer *Peer // as configured (nil until its SERVER, for one linking in)
out chan string
done chan struct{}
written chan struct{} // the writer is done
once sync.Once
// registering
pass, sid string
caps map[string]bool
srv *server // its server, once linked
hybrid bool // it speaks ircd-hybrid 8's TS6 (SERVER with a SID, its UID, TBURST, EOB)
pinged bool // our PING after the handshake is sent
bursted bool // our burst is sent: lines may go to it
}
// line makes a line: source (a SID or UID; "": none), command and
// parameters, the last as trailing.
func line(source, command string, params ...string) string {
m := ircmsg.MakeMessage(nil, source, command, params...)
switch command {
case "JOIN", "PART", "NICK", "MODE", "TMODE":
default:
if len(params) > 0 {
m.ForceTrailing() // text, a list or a description
}
}
b, err := m.LineBytesStrict(false, maxLine)
if err != nil && !errors.Is(err, ircmsg.ErrorBodyTooLong) {
return ""
}
return strings.TrimRight(string(b), "\r\n")
}
// trace is told every line, when set (tests).
var trace func(string)
// sendRaw queues a line to the link; a full queue drops it.
func (l *link) sendRaw(s string) {
if s == "" {
return
}
if trace != nil && s != flushClose {
trace("-> " + l.name() + " " + s)
}
select {
case <-l.done:
case l.out <- s:
default:
l.h.B.Log.Printf("irclink: %s: send queue full", l.name())
l.close()
}
}
// send queues a line made of its parts.
func (l *link) send(source, command string, params ...string) {
l.sendRaw(line(source, command, params...))
}
// close ends the link (once).
func (l *link) close() {
l.once.Do(func() {
close(l.done)
l.conn.Close()
})
}
// name is the link's server name, or its address before it says.
func (l *link) name() string {
if l.srv != nil {
return l.srv.name
}
if l.peer != nil {
return l.peer.Name
}
return l.conn.RemoteAddr().String()
}
// flushClose is the line that has the writer write what is queued
// before it, then end the link.
const flushClose = "\x00close"
// finish ends the link once what is queued (an ERROR) is written, or in
// a few seconds.
func (l *link) finish() {
l.sendRaw(flushClose)
select {
case <-l.written:
case <-time.After(3 * time.Second):
}
l.close()
}
// writer writes the queued lines until the link ends.
func (l *link) writer() {
defer close(l.written)
w := bufio.NewWriter(l.conn)
for {
select {
case <-l.done:
return
case s := <-l.out:
last := s == flushClose
if !last {
w.WriteString(s + "\r\n")
}
for more := !last; more; {
select {
case s := <-l.out:
if s == flushClose {
last, more = true, false
break
}
w.WriteString(s + "\r\n")
default:
more = false
}
}
l.conn.SetWriteDeadline(time.Now().Add(writeLimit))
if err := w.Flush(); err != nil || last {
l.close()
return
}
}
}
}
// serve runs a link (peer: the one linked out to; nil for one linking in)
// until it drops; then the servers behind it are gone from the network.
func (h *Hub) serve(ctx context.Context, conn net.Conn, peer *Peer) {
l := &link{h: h, conn: conn, peer: peer, out: make(chan string, sendQ), done: make(chan struct{}),
written: make(chan struct{}), caps: map[string]bool{}}
h.mu.Lock()
h.links[l] = true
h.mu.Unlock()
go l.writer()
stop := context.AfterFunc(ctx, l.close)
defer stop()
if peer != nil {
l.handshake()
}
why := l.read()
l.finish()
h.mu.Lock()
delete(h.links, l)
if l.srv != nil && h.servers[l.srv.sid] == l.srv {
h.B.Log.Printf("irclink: %s split: %s", l.srv.name, why)
h.squit(l.srv, l, h.me.name+" "+l.srv.name)
}
h.mu.Unlock()
}
// handshake sends the BBS's PASS, CAPAB, SERVER and SVINFO, and then a
// PING: its answer comes after the peer's burst.
func (l *link) handshake() {
h := l.h
if l.peer.Hybrid {
l.hybrid = true
}
if l.hybrid {
l.send("", "PASS", l.peer.SendPassword)
l.send("", "CAPAB", "KNOCK TBURST ENCAP EOB")
l.send("", "SERVER", h.me.name, "1", h.me.sid, "+", h.me.desc)
} else {
l.send("", "PASS", l.peer.SendPassword, "TS", "6", h.me.sid)
l.send("", "CAPAB", capab)
l.send("", "SERVER", h.me.name, "1", h.me.desc)
}
l.send("", "SVINFO", "6", "6", "0", strconv.FormatInt(time.Now().Unix(), 10))
l.send("", "PING", h.me.name)
l.pinged = true
}
// read reads the link's lines until it ends; it is why.
func (l *link) read() string {
var r ircreader.Reader
r.Initialize(l.conn, 1024, 8192)
registerBy := time.Now().Add(registerLimit)
pinged := false
for {
if l.srv == nil {
l.conn.SetReadDeadline(registerBy)
} else if pinged {
l.conn.SetReadDeadline(time.Now().Add(pingLimit))
} else {
l.conn.SetReadDeadline(time.Now().Add(idleLimit))
}
raw, err := r.ReadLine()
if err != nil {
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() && l.srv != nil && !pinged {
pinged = true
l.send(l.h.me.sid, "PING", l.h.me.name, l.srv.sid)
continue
}
if ne != nil && ne.Timeout() {
l.sendRaw("ERROR :Ping timeout")
return "ping timeout"
}
select {
case <-l.done:
return "link closed"
default:
}
return err.Error()
}
pinged = false
m, err := ircmsg.ParseLine(string(raw))
if err != nil {
continue
}
m.Command = strings.ToUpper(m.Command)
if trace != nil {
trace("<- " + l.name() + " " + string(raw))
}
h := l.h
h.mu.Lock()
why, ok := h.handle(l, &m, string(raw))
h.mu.Unlock()
if !ok {
l.sendRaw("ERROR :Closing link: " + why)
return why
}
}
}
// handle is a line from a link; false drops the link, for why. The hub's
// lock is held.
func (h *Hub) handle(l *link, m *ircmsg.Message, raw string) (why string, ok bool) {
if l.srv == nil {
return h.register(l, m)
}
p := func(i int) string {
if i < len(m.Params) {
return m.Params[i]
}
return ""
}
src := m.Source
if src == "" {
src = l.srv.sid
}
if i := strings.IndexByte(src, '!'); i >= 0 {
src = src[:i]
}
// a source behind another link: a loop, or a server gone
if s := h.sourceServer(src); s != nil && s != l.srv && s.link != l {
return "", true
}
switch m.Command {
case "PING":
if dest := p(1); dest != "" && !h.isMe(dest) {
h.route(dest, l, raw)
return "", true
}
l.send(h.me.sid, "PONG", h.me.name, p(0))
case "PONG":
if dest := p(1); dest != "" && !h.isMe(dest) {
h.route(dest, l, raw)
return "", true
}
if l.pinged && !l.bursted {
h.burst(l)
}
case "ERROR":
return "ERROR from " + l.srv.name + ": " + p(0), false
case "SID":
return h.sid(l, src, p(0), p(1), p(2), p(3), raw)
case "SERVER":
return "a server without a SID: not TS6", false
case "SQUIT":
target := h.servers[p(0)]
if target == nil {
target = h.names[fold(p(0))]
}
if target == nil {
return "", true
}
if target == h.me || target == l.srv {
return "SQUIT: " + p(1), false
}
if target.link == l {
h.squit(target, l, p(1))
}
case "UID":
switch {
case len(m.Params) >= 11: // hybrid 8: nick hops ts umodes user host realhost ip uid account :gecos
account := p(9)
if account == "*" || account == "0" {
account = ""
}
h.newUser(l, src, p(0), p(2), p(3), p(4), p(5), p(7), p(8), account, p(10), raw)
case len(m.Params) >= 9:
h.newUser(l, src, p(0), p(2), p(3), p(4), p(5), p(6), p(7), "", p(8), raw)
}
case "EUID":
if len(m.Params) < 11 {
return "", true
}
account := p(9)
if account == "*" || account == "0" {
account = ""
}
h.newUser(l, src, p(0), p(2), p(3), p(4), p(5), p(6), p(7), account, p(10), raw)
case "NICK":
h.nickChange(l, src, p(0), p(1), raw)
case "QUIT":
if u := h.users[src]; u != nil {
h.removeUser(u, p(0))
h.forward(l, raw)
}
case "KILL":
h.kill(l, src, p(0), p(1), raw)
case "SAVE":
if u := h.users[p(0)]; u != nil {
h.renick(u, u.uid, time.Now().Unix())
h.forward(l, raw)
}
case "SJOIN":
h.sjoin(l, p(0), p(1), p(2), m.Params[min(len(m.Params), 3):], raw)
case "JOIN":
h.userJoin(l, src, p(0), p(1), raw)
case "PART":
if u := h.users[src]; u != nil {
for _, name := range strings.Split(p(0), ",") {
if ch := h.chans[fold(name)]; ch != nil {
h.part(u, ch, h.display(u), p(1))
}
}
h.forward(l, raw)
}
case "KICK":
if ch, u := h.chans[fold(p(0))], h.users[p(1)]; ch != nil && u != nil {
h.part(u, ch, h.display(u), "kicked: "+p(2))
if u.local != "" {
h.B.RelayPrivate(u.local, eventNotice("You were kicked from "+ch.name+" on the IRC network: "+p(2)))
}
}
h.forward(l, raw)
case "EOB":
h.forward(l, raw)
case "TBURST":
// TBURST channel-ts channel topic-ts setter :topic (hybrid)
if len(m.Params) >= 5 {
h.topic(l, "TB", []string{p(1), p(2), p(3), p(4)}, raw)
}
case "TOPIC", "TB", "ETB":
h.topic(l, m.Command, m.Params, raw)
case "AWAY":
if u := h.users[src]; u != nil {
u.away = p(0)
}
h.forward(l, raw)
case "CHGHOST":
if u := h.users[p(0)]; u != nil && p(1) != "" {
u.host = p(1)
}
h.forward(l, raw)
case "ENCAP":
if p(1) == "CHGHOST" {
if u := h.users[p(2)]; u != nil && p(3) != "" {
u.host = p(3)
}
}
if p(1) == "LOGIN" {
if u := h.users[src]; u != nil {
u.account = p(2)
}
}
h.forward(l, raw)
case "PRIVMSG", "NOTICE":
h.message(l, src, m.Command, p(0), p(1), raw)
case "WHOIS":
h.whois(l, src, p(0), p(1), raw)
case "VERSION", "MOTD", "ADMIN", "INFO", "TIME", "LUSERS", "STATS", "LINKS", "TRACE", "USERS":
h.query(l, src, m.Command, m.Params, raw)
case "SVINFO", "CAPAB", "PASS":
default:
if len(m.Command) == 3 && m.Command[0] >= '0' && m.Command[0] <= '9' {
// a numeric: to the user it answers
h.route(p(0), l, raw)
return "", true
}
h.forward(l, raw) // TMODE, BMASK, MODE, OPERWALL, BAN, ...: on to the others
}
return "", true
}
// register is a line before the link's SERVER is taken.
func (h *Hub) register(l *link, m *ircmsg.Message) (string, bool) {
p := func(i int) string {
if i < len(m.Params) {
return m.Params[i]
}
return ""
}
switch m.Command {
case "PASS":
// PASS password TS 6 :SID; hybrid 8's SERVER gives the SID instead
l.pass = p(0)
if strings.ToUpper(p(1)) == "TS" {
if p(2) != "6" || !sidRE.MatchString(p(3)) {
return "TS6 only (PASS password TS 6 :SID)", false
}
l.sid = p(3)
}
case "CAPAB":
for _, c := range strings.Fields(strings.ToUpper(p(0))) {
l.caps[c] = true
}
case "SERVER":
name := p(0)
peer := h.peer(name)
desc := m.Params[len(m.Params)-1]
if len(m.Params) >= 4 && sidRE.MatchString(p(2)) {
l.sid = p(2) // SERVER name hops SID +flags :description (hybrid 8)
l.hybrid = true
}
switch {
case l.sid == "" || len(m.Params) < 3:
return "no SID (PASS password TS 6 :SID)", false
case peer == nil:
return "no link for " + name, false
case l.peer != nil && fold(l.peer.Name) != fold(name):
return "linked to " + l.peer.Name + ", not " + name, false
case l.pass != peer.AcceptPassword:
return "bad password", false
case !l.caps["ENCAP"]:
return "the BBS needs ENCAP", false
case h.names[fold(name)] != nil:
return name + " is on the network already", false
case h.servers[l.sid] != nil:
return "SID " + l.sid + " is in use", false
}
if l.peer == nil {
l.peer = peer
l.handshake()
}
s := &server{sid: l.sid, name: name, desc: desc, hops: 1, uplink: h.me, link: l, tag: peer.Tag}
h.servers[s.sid] = s
h.names[fold(name)] = s
l.srv = s
h.B.Log.Printf("irclink: %s linked (%s)", name, l.conn.RemoteAddr())
// the others are told of it at once
for o := range h.links {
if o != l && o.bursted {
o.send(h.me.sid, "SID", s.name, "2", s.sid, s.desc)
}
}
case "ERROR":
return "ERROR: " + p(0), false
case "PING":
l.send("", "PONG", h.me.name, p(0))
case "SVINFO", "PONG", "NOTICE":
default:
return "not registered: " + m.Command, false
}
return "", true
}
// isMe: a name or SID is the BBS's.
func (h *Hub) isMe(s string) bool { return s == h.me.sid || fold(s) == fold(h.me.name) }
// sourceServer is the server a source (a SID or UID) is on (nil: not
// known).
func (h *Hub) sourceServer(src string) *server {
if s := h.servers[src]; s != nil {
return s
}
if u := h.users[src]; u != nil {
return u.srv
}
return nil
}
// forward sends a line on to every link but the one it came by.
func (h *Hub) forward(from *link, raw string) {
for l := range h.links {
if l != from && l.bursted && l.srv != nil {
l.sendRaw(raw)
}
}
}
// broadcast sends a line to every link.
func (h *Hub) broadcast(raw string) { h.forward(nil, raw) }
// route sends a line toward a server or user (a SID, UID, server name or
// nick), but never back by the link it came by.
func (h *Hub) route(target string, from *link, raw string) {
var s *server
if u := h.users[target]; u != nil {
s = u.srv
} else if u := h.nicks[fold(target)]; u != nil {
s = u.srv
} else if s = h.servers[target]; s == nil {
s = h.names[fold(target)]
}
if s == nil || s.link == nil || s.link == from || !s.link.bursted {
return
}
s.link.sendRaw(raw)
}
// sid is SID: a server behind the link.
func (h *Hub) sid(l *link, src, name, hops, sid, desc, raw string) (string, bool) {
up := h.servers[src]
if up == nil || up.link != l && up != l.srv {
return "", true
}
if h.names[fold(name)] != nil || h.servers[sid] != nil {
// on the network by another way: a loop
return "server " + name + " (" + sid + ") is on the network already", false
}
n, _ := strconv.Atoi(hops)
s := &server{sid: sid, name: name, desc: desc, hops: max(n, up.hops+1), uplink: up, link: l}
h.servers[sid] = s
h.names[fold(name)] = s
h.forward(l, raw)
return "", true
}
// squit takes a server behind a link off the network (the link itself:
// all behind it), and tells the other links.
func (h *Hub) squit(s *server, from *link, why string) {
h.removeServer(s, why)
for l := range h.links {
if l != from && l.bursted && l.srv != nil && l.srv != s {
l.send(h.me.sid, "SQUIT", s.sid, why)
}
}
}
// burst gives a link the network as the BBS has it: the servers, users
// and channels not behind it. Lines may go to it from now on.
func (h *Hub) burst(l *link) {
// collisions with what it brought are settled first: ours renamed
for _, u := range h.local {
if o := h.nicks[fold(u.nick)]; o != nil && o != u {
h.renameLocal(u)
}
}
var srvs []*server
for _, s := range h.servers {
if s != h.me && s.link != l {
srvs = append(srvs, s)
}
}
sort.Slice(srvs, func(i, j int) bool { return srvs[i].hops < srvs[j].hops })
for _, s := range srvs {
l.send(s.uplink.sid, "SID", s.name, strconv.Itoa(s.hops+1), s.sid, s.desc)
}
var us []*user
for _, u := range h.users {
if u.srv.link != l {
us = append(us, u)
}
}
sort.Slice(us, func(i, j int) bool { return us[i].uid < us[j].uid })
for _, u := range us {
l.sendRaw(h.introduce(u, l))
if u.away != "" {
l.send(u.uid, "AWAY", u.away)
}
}
for _, ch := range h.chans {
var members []string
for u := range ch.members {
if u.srv.link != l {
members = append(members, u.chans[ch]+u.uid)
}
}
if len(members) == 0 {
continue
}
sort.Strings(members)
ts := strconv.FormatInt(ch.ts, 10)
for len(members) > 0 {
k, size := 0, 0
for k < len(members) && size+len(members[k])+1 < 400 {
size += len(members[k]) + 1
k++
}
l.send(h.me.sid, "SJOIN", ts, ch.name, ch.modes, strings.Join(members[:k], " "))
members = members[k:]
}
if ch.topic != "" {
if l.hybrid {
l.send(h.me.sid, "TBURST", ts, ch.name, ts, h.me.name, ch.topic)
} else {
l.send(h.me.sid, "TB", ch.name, ts, h.me.name, ch.topic)
}
}
}
if l.hybrid {
l.send(h.me.sid, "EOB")
}
l.bursted = true
l.send(h.me.sid, "PING", h.me.name, l.srv.sid)
}
+132
View File
@@ -0,0 +1,132 @@
package irclink
import (
"bufio"
"fmt"
"net"
"os"
"strconv"
"strings"
"testing"
"time"
)
// TestLive links to a real TS6 ircd, when one is set up (it is skipped
// otherwise):
//
// IRCLINK_LIVE_PEER its server name, linking in to 127.0.0.1:17000
// IRCLINK_LIVE_SEND the password we send it (its accept_password)
// IRCLINK_LIVE_ACCEPT the password it sends us (its send_password)
// IRCLINK_LIVE_CLIENT its address for clients (127.0.0.1:16667)
// IRCLINK_LIVE_NICKLEN its NICKLEN, if not 30 (hybrid's is 9)
// IRCLINK_LIVE_LINKOUT its address for servers, if the BBS links out
//
// A client on it sees the BBS's alice (and the network's carol beside her
// as Nick|Tag), talks with her in #retro, messages her, and WHOISes her.
func TestLive(t *testing.T) {
peer := os.Getenv("IRCLINK_LIVE_PEER")
if peer == "" {
t.Skip("no IRCLINK_LIVE_PEER")
}
trace = func(s string) { t.Log(s) }
t.Cleanup(func() { trace = nil })
e := start(t)
e.hub.S.Address = "127.0.0.1:17000"
e.hub.S.NickLen = 30
if n, err := strconv.Atoi(os.Getenv("IRCLINK_LIVE_NICKLEN")); err == nil {
e.hub.S.NickLen = n // hybrid's is 9
}
ours := e.hub.tagged("alice", e.hub.me, nil, "")
e.hub.S.Peers = []Peer{{Name: peer, SendPassword: os.Getenv("IRCLINK_LIVE_SEND"),
AcceptPassword: os.Getenv("IRCLINK_LIVE_ACCEPT"), Tag: "far", Address: os.Getenv("IRCLINK_LIVE_LINKOUT")}}
// a user there who has alice's nick
c := dialIRC(t, os.Getenv("IRCLINK_LIVE_CLIENT"), "alice")
alice := e.node(t, "alice")
e.run(t)
deadline := time.Now().Add(20 * time.Second)
for !e.hub.linked(peer) {
if time.Now().After(deadline) {
t.Fatal("never linked")
}
time.Sleep(100 * time.Millisecond)
}
if _, err := alice.JoinRoom("irc-retro"); err != nil {
t.Fatal(err)
}
c.send("JOIN #retro")
c.expect("366")
wait(t, alice, "-> alice|far came in")
c.send("WHOIS " + ours)
c.expect(" 311 alice " + ours + " bbs irc.test.example")
c.expect(" 319 alice " + ours + " :#retro")
c.send("PRIVMSG #retro :hello from " + peer)
wait(t, alice, "alice|far: hello from "+peer)
alice.Say("hi there", false)
c.expect(":" + ours + "!bbs@irc.test.example PRIVMSG #retro :hi there")
c.send("PRIVMSG " + ours + " :psst")
wait(t, alice, "Message from alice|far")
if err := alice.MessageRemote("alice|far", "hello back", false, false); err != nil {
t.Fatal(err)
}
c.expect("PRIVMSG alice :hello back")
alice.Leave()
c.expect(":" + ours + "!bbs@irc.test.example PART #retro")
}
// ircClient is a client of the live ircd.
type ircClient struct {
t *testing.T
conn net.Conn
lines chan string
seen []string
}
// dialIRC connects and registers as nick.
func dialIRC(t *testing.T, addr, nick string) *ircClient {
t.Helper()
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
c := &ircClient{t: t, conn: conn, lines: make(chan string, 1000)}
go func() {
s := bufio.NewScanner(conn)
for s.Scan() {
l := strings.TrimRight(s.Text(), "\r")
if strings.HasPrefix(l, "PING ") {
fmt.Fprintf(conn, "PONG %s\r\n", l[5:])
}
c.lines <- l
}
close(c.lines)
}()
c.send("NICK "+nick, "USER "+nick+" 0 * :"+nick)
c.expect(" 001 ")
return c
}
func (c *ircClient) send(lines ...string) {
for _, l := range lines {
fmt.Fprintf(c.conn, "%s\r\n", l)
}
}
func (c *ircClient) expect(want string) {
c.t.Helper()
deadline := time.After(10 * time.Second)
for {
select {
case l, ok := <-c.lines:
if !ok {
c.t.Fatalf("closed; no %q among %q", want, c.seen)
}
c.seen = append(c.seen, l)
if strings.Contains(l, want) {
return
}
case <-deadline:
c.t.Fatalf("no %q among %q", want, c.seen)
}
}
}
+204
View File
@@ -0,0 +1,204 @@
package irclink
import (
"strconv"
"strings"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
)
// presence puts a BBS user on the network as they come on, and takes
// them off as they go. It is the BBS's WatchPresence; it does not block.
func (h *Hub) presence(name string, online bool) {
h.mu.Lock()
defer h.mu.Unlock()
u := h.local[fold(name)]
if !online {
delete(h.killed, fold(name))
if u != nil {
h.removeUser(u, "Signed off")
h.broadcast(line(u.uid, "QUIT", "Signed off"))
}
return
}
if u != nil {
return
}
h.introduceLocal(name)
}
// introduceLocal puts a BBS user on the network (Nick|Tag if their nick
// is taken), in the linked rooms they are in. The hub's lock is held.
func (h *Hub) introduceLocal(name string) *user {
if h.killed[fold(name)] {
return nil
}
nick := nickOf(name)
if len(nick) > h.S.NickLen {
nick = nick[:h.S.NickLen]
}
if h.nicks[fold(nick)] != nil {
nick = h.tagged(nick, h.me, nil, "")
}
u := &user{uid: h.uid(), nick: nick, ts: time.Now().Unix(), umodes: "+i", ident: "bbs", host: h.S.Host,
ip: "0", real: name, account: accountOf(name), srv: h.me, local: name, since: time.Now()}
h.addUser(u)
for l := range h.links {
if l.bursted {
l.sendRaw(h.introduce(u, l))
}
}
return u
}
// accountOf is a BBS name as a services account (no spaces).
func accountOf(name string) string { return strings.ReplaceAll(name, " ", "_") }
// ours is the network user of a BBS user online (put on now if they came
// before the hub knew; nil if killed off). The hub's lock is held.
func (h *Hub) ours(name string) *user {
if u := h.local[fold(name)]; u != nil {
return u
}
return h.introduceLocal(name)
}
// Carries: the room is a channel.
func (h *Hub) Carries(room string) bool {
return strings.HasPrefix(room, h.S.Prefix) && len(room) > len(h.S.Prefix) && !strings.HasPrefix(room, "sysop-")
}
// Allows: anyone who may chat may be in a channel.
func (h *Hub) Allows(room string, u *store.User) bool { return true }
// Joined: a BBS user came into a channel's room.
func (h *Hub) Joined(room, name string) {
ch := h.channelOf(room)
if ch == "" {
return
}
h.mu.Lock()
defer h.mu.Unlock()
u := h.ours(name)
if u == nil {
return
}
c := h.channel(ch, time.Now().Unix())
if c.members[u] {
return
}
h.join(u, c, "")
h.broadcast(line(u.uid, "JOIN", strconv.FormatInt(c.ts, 10), c.name, "+"))
}
// Left: a BBS user left a channel's room (off the channel once no node of
// theirs is in it).
func (h *Hub) Left(room, name string) {
ch := h.channelOf(room)
if ch == "" {
return
}
for _, m := range h.B.RoomMembers(room) {
if m.Node != 0 && strings.EqualFold(m.Name, name) {
return // still in it on another node
}
}
h.mu.Lock()
defer h.mu.Unlock()
u := h.local[fold(name)]
c := h.chans[fold(ch)]
if u == nil || c == nil || !c.members[u] {
return
}
h.part(u, c, u.nick, "")
h.broadcast(line(u.uid, "PART", c.name))
}
// Said: a BBS user said a line in a channel's room.
func (h *Hub) Said(room, name, text string, emote bool) {
ch := h.channelOf(room)
if ch == "" {
return
}
h.mu.Lock()
defer h.mu.Unlock()
u := h.local[fold(name)]
c := h.chans[fold(ch)]
if u == nil || c == nil || !c.members[u] {
return
}
if emote {
text = "\x01ACTION " + text + "\x01"
}
h.broadcast(line(u.uid, "PRIVMSG", c.name, text))
}
// Command: a line beginning ! is only talk on IRC.
func (h *Hub) Command(room, name, line string) { h.Said(room, name, "!"+line, false) }
// Members are those of elsewhere in a channel's room.
func (h *Hub) Members(room string) []bbs.RoomMember {
ch := h.channelOf(room)
if ch == "" {
return nil
}
h.mu.Lock()
defer h.mu.Unlock()
c := h.chans[fold(ch)]
if c == nil {
return nil
}
var out []bbs.RoomMember
for u := range c.members {
if u.local == "" {
out = append(out, bbs.RoomMember{Name: h.display(u), Via: u.ident, Host: u.host})
}
}
return out
}
// Lookup finds someone on the network (not a BBS user) by nick, or as the
// BBS names them.
func (h *Hub) Lookup(nick string) (bbs.RemoteUser, bool) {
h.mu.Lock()
defer h.mu.Unlock()
u := h.byDisplay(nick)
if u == nil {
return bbs.RemoteUser{}, false
}
return h.remote(u), true
}
// SendPrivate sends a BBS user's private line to someone on the network.
func (h *Hub) SendPrivate(from, to, text string, notice, emote bool) error {
h.mu.Lock()
defer h.mu.Unlock()
t := h.byDisplay(to)
if t == nil {
return bbs.ErrNoSuchNick
}
u := h.ours(from)
if u == nil {
return errKilled
}
if emote {
text = "\x01ACTION " + text + "\x01"
}
command := "PRIVMSG"
if notice {
command = "NOTICE"
}
if t.srv.link != nil && t.srv.link.bursted {
t.srv.link.send(u.uid, command, t.uid, text)
}
return nil
}
// errKilled: the user was killed off the network.
var errKilled = errorString("you were removed from the IRC network; it is yours again when you next log in")
type errorString string
func (e errorString) Error() string { return string(e) }
+300
View File
@@ -0,0 +1,300 @@
package irclink
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/D-Modem/bbs/internal/bbs"
)
// server is a server on the network.
type server struct {
sid, name, desc string
hops int
uplink *server // nil: the BBS itself
link *link // the link it is behind (nil: the BBS itself)
tag string // its users' tag ("": its name's)
}
// user is someone on the network.
type user struct {
uid, nick string
ts int64
umodes string
ident string
host string
ip string
real string
account string
away string
srv *server
local string // the BBS user's name, for one of ours ("": elsewhere)
since time.Time
chans map[*channel]string // the channels they are in, their prefixes (@, +)
}
// channel is a channel on the network.
type channel struct {
name string // as it was first given (#Retro)
ts int64
modes string
topic string
members map[*user]bool
}
// mask is how a user is named: nick!ident@host.
func (u *user) mask(nick string) string { return nick + "!" + u.ident + "@" + u.host }
// uid makes the next UID of ours: our SID, a letter and five letters or
// digits.
func (h *Hub) uid() string {
for {
n := h.nextUID
h.nextUID++
const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := []byte(h.me.sid + "AAAAAA")
for i := 8; i > 3; i-- {
b[i] = digits[n%36]
n /= 36
}
b[3] = digits[n%26]
if id := string(b); h.users[id] == nil {
return id
}
}
}
// tagFor is the tag of a server's users.
func (h *Hub) tagFor(s *server) string {
if s.tag != "" {
return s.tag
}
if p := h.peer(s.name); p != nil {
return p.Tag
}
return defaultTag(s.name)
}
// tagged is a nick with a server's tag (Nick|Tag), cut to the network's
// nick length, and numbered if that too is taken (by another than self,
// or is avoid).
func (h *Hub) tagged(nick string, s *server, self *user, avoid string) string {
tag := h.tagFor(s)
for i := 1; ; i++ {
suffix := "|" + tag
if i > 1 {
suffix += strconv.Itoa(i)
}
base := nick
if max := h.S.NickLen - len(suffix); len(base) > max {
if max < 1 {
max = 1
}
base = base[:max]
}
n := base + suffix
if o := h.nicks[fold(n)]; (o == nil || o == self) && fold(n) != fold(avoid) {
return n
}
}
}
// display is how a user of elsewhere is named on the BBS: their nick, or
// Nick|Tag if a BBS user online goes by it.
func (h *Hub) display(u *user) string {
if u.local != "" {
return u.local
}
if h.localNick(u.nick) {
return h.tagged(u.nick, u.srv, u, "")
}
return u.nick
}
// localNick: a BBS user online is called that, as the BBS's IRC server
// names them.
func (h *Hub) localNick(nick string) bool {
for _, l := range h.local {
if fold(nickOf(l.local)) == fold(nick) {
return true
}
}
return false
}
// byDisplay finds a user of elsewhere by their nick or as the BBS names
// them.
func (h *Hub) byDisplay(nick string) *user {
if u := h.nicks[fold(nick)]; u != nil && u.local == "" && fold(h.display(u)) == fold(nick) {
return u
}
for _, u := range h.users {
if u.local == "" && fold(h.display(u)) == fold(nick) {
return u
}
}
return nil
}
// room is a channel's BBS room ("": not one carried).
func (h *Hub) room(ch string) string {
name, ok := strings.CutPrefix(fold(ch), "#")
if !ok {
return ""
}
r := h.S.Prefix + name
if !roomRE.MatchString(r) || strings.HasPrefix(r, "sysop-") {
return ""
}
return r
}
// channelOf is a room's channel name ("": not carried).
func (h *Hub) channelOf(room string) string {
if !h.Carries(room) {
return ""
}
return "#" + strings.TrimPrefix(room, h.S.Prefix)
}
// addUser puts a user on the network.
func (h *Hub) addUser(u *user) {
if u.chans == nil {
u.chans = map[*channel]string{}
}
h.users[u.uid] = u
h.nicks[fold(u.nick)] = u
if u.local != "" {
h.local[fold(u.local)] = u
}
}
// removeUser takes a user off the network, out of their channels (the
// rooms told).
func (h *Hub) removeUser(u *user, why string) {
name := h.display(u)
for ch := range u.chans {
h.part(u, ch, name, why)
}
delete(h.users, u.uid)
if h.nicks[fold(u.nick)] == u {
delete(h.nicks, fold(u.nick))
}
if u.local != "" && h.local[fold(u.local)] == u {
delete(h.local, fold(u.local))
}
}
// channel finds a channel, made with ts if new.
func (h *Hub) channel(name string, ts int64) *channel {
ch := h.chans[fold(name)]
if ch == nil {
ch = &channel{name: name, ts: ts, modes: "+nt", members: map[*user]bool{}}
h.chans[fold(name)] = ch
}
return ch
}
// join puts a user in a channel, its room told of one of elsewhere.
func (h *Hub) join(u *user, ch *channel, prefix string) {
if ch.members[u] {
return
}
ch.members[u] = true
u.chans[ch] = prefix
if r := h.room(ch.name); r != "" && u.local == "" {
h.B.RelayEvent(bbs.Event{Kind: bbs.Joined, Room: r, From: h.display(u), Mask: u.mask(h.display(u))})
}
}
// part takes a user out of a channel, its room told of one of elsewhere
// (name: as they were named).
func (h *Hub) part(u *user, ch *channel, name, why string) {
if !ch.members[u] {
return
}
delete(ch.members, u)
delete(u.chans, ch)
if len(ch.members) == 0 {
delete(h.chans, fold(ch.name))
}
if r := h.room(ch.name); r != "" && u.local == "" {
h.B.RelayEvent(bbs.Event{Kind: bbs.Left, Room: r, From: name, Mask: u.mask(name), Text: why})
}
}
// behind are the servers behind a server (it too), farthest first.
func (h *Hub) behind(s *server) []*server {
var out []*server
for _, o := range h.servers {
for p := o; p != nil; p = p.uplink {
if p == s {
out = append(out, o)
break
}
}
}
sort.Slice(out, func(i, j int) bool { return out[i].hops > out[j].hops })
return out
}
// removeServer takes a server and those behind it off the network, with
// their users.
func (h *Hub) removeServer(s *server, why string) {
gone := h.behind(s)
set := map[*server]bool{}
for _, o := range gone {
set[o] = true
}
for _, u := range h.users {
if set[u.srv] {
h.removeUser(u, why)
}
}
for _, o := range gone {
delete(h.servers, o.sid)
delete(h.names, fold(o.name))
}
}
// introduce is the line that puts a user on the network, for a link.
func (h *Hub) introduce(u *user, l *link) string {
modes := u.umodes
if modes == "" {
modes = "+"
}
ip := u.ip
if ip == "" {
ip = "0"
}
if l.hybrid {
account := u.account
if account == "" {
account = "*"
}
return line(u.srv.sid, "UID", u.nick, strconv.Itoa(u.srv.hops+1), strconv.FormatInt(u.ts, 10), modes,
u.ident, u.host, u.host, ip, u.uid, account, u.real)
}
if l.caps["EUID"] {
account := u.account
if account == "" {
account = "*"
}
return line(u.srv.sid, "EUID", u.nick, strconv.Itoa(u.srv.hops+1), strconv.FormatInt(u.ts, 10), modes,
u.ident, u.host, ip, u.uid, "*", account, u.real)
}
return line(u.srv.sid, "UID", u.nick, strconv.Itoa(u.srv.hops+1), strconv.FormatInt(u.ts, 10), modes,
u.ident, u.host, ip, u.uid, u.real)
}
// remote is a user of elsewhere as the BBS shows them.
func (h *Hub) remote(u *user) bbs.RemoteUser {
return bbs.RemoteUser{Nick: h.display(u), User: u.ident, Host: u.host, Server: u.srv.name,
Network: h.S.Network, Real: u.real, Account: u.account, Away: u.away, Since: u.since}
}
// String is the user, for the log.
func (u *user) String() string { return fmt.Sprintf("%s(%s)", u.nick, u.uid) }
+14 -9
View File
@@ -27,6 +27,7 @@ import (
"github.com/D-Modem/bbs/internal/guard"
"github.com/D-Modem/bbs/internal/imageboard"
"github.com/D-Modem/bbs/internal/ircd"
"github.com/D-Modem/bbs/internal/irclink"
"github.com/D-Modem/bbs/internal/logo"
"github.com/D-Modem/bbs/internal/mrc"
"github.com/D-Modem/bbs/internal/msn"
@@ -63,14 +64,15 @@ type Config struct {
QWKNets []*qwknet.Net // [qwknet NAME]: QWK networks this is a node of
Binkp *BinkpSettings // nil: no binkp answering
Doors []*door.Door
Finger *finger.Settings // nil: no finger server
IRC *ircd.Settings // nil: no IRC server
OSCAR *oscar.Settings // nil: no AIM/ICQ server
AOL *aol.Settings // nil: no host for AOL clients
MSN *msn.Settings // nil: no MSN Messenger server
MRC *mrc.Settings // nil: not on Multi Relay Chat
Screens *screens.Set // nil: no screens of the sysop's
ScriptsDir string // "": no scripts
Finger *finger.Settings // nil: no finger server
IRC *ircd.Settings // nil: no IRC server
OSCAR *oscar.Settings // nil: no AIM/ICQ server
AOL *aol.Settings // nil: no host for AOL clients
MSN *msn.Settings // nil: no MSN Messenger server
MRC *mrc.Settings // nil: not on Multi Relay Chat
IRCLink *irclink.Settings // nil: not linked to an IRC network
Screens *screens.Set // nil: no screens of the sysop's
ScriptsDir string // "": no scripts
Menus map[string]*bbs.Menu
Text map[string]string // [strings]
HTTP *api.Settings // nil: no HTTP API
@@ -159,6 +161,9 @@ func load(cf *config.File) (*Config, error) {
if err := c.mrcSection(cf); err != nil {
return nil, err
}
if err := c.irclinkSection(cf); err != nil {
return nil, err
}
if err := c.timeSections(cf); err != nil {
return nil, err
}
@@ -228,7 +233,7 @@ func load(cf *config.File) (*Config, error) {
}
for _, s := range cf.Sections {
switch s.Kind {
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "time", "ntp", "nts", "ptp", "irc", "oscar", "aol", "msn", "mrc", "menu", "strings", "http", "level", "chan",
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "time", "ntp", "nts", "ptp", "irc", "oscar", "aol", "msn", "mrc", "irclink", "ircpeer", "menu", "strings", "http", "level", "chan",
"mail", "smarthost", "pop3", "imap", "smtp", "mx", "lmtp":
default:
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
+98
View File
@@ -0,0 +1,98 @@
package server
import (
"errors"
"fmt"
"net"
"strings"
"github.com/D-Modem/bbs/internal/config"
"github.com/D-Modem/bbs/internal/irclink"
)
// irclinkSection reads [irclink] and its [ircpeer NAME]s: the BBS as a
// server on an IRC network.
func (c *Config) irclinkSection(cf *config.File) error {
s := cf.Get("irclink", "")
peers := cf.All("ircpeer")
if s == nil {
if len(peers) > 0 {
return errors.New("[ircpeer] without [irclink]")
}
return nil
}
err := func() error {
l := &irclink.Settings{ServerName: s.String("server_name", ""), SID: s.String("sid", ""),
Description: s.String("description", ""), Network: s.String("network", ""),
Tag: s.String("tag", ""), Host: s.String("host", ""), Prefix: s.String("prefix", "irc-"),
Address: s.String("address", ":7000"), TLSAddress: s.String("tls_address", ""),
CertFile: s.String("tls_cert", ""), KeyFile: s.String("tls_key", "")}
if l.Prefix == "none" {
l.Prefix = ""
}
if l.Prefix != "" && !roomPrefix.MatchString(l.Prefix) {
return errors.New("prefix: what begins the linked rooms: up to 10 lower case letters, digits and -")
}
if l.Address == "none" {
l.Address = ""
}
var err error
if l.NickLen, err = s.Int("nick_length", 30, 9, 64); err != nil {
return err
}
if l.Retry, err = s.Seconds("retry", 30, 1, 3600); err != nil {
return err
}
for _, a := range []struct{ key, v string }{{"address", l.Address}, {"tls_address", l.TLSAddress}} {
if _, _, err := net.SplitHostPort(a.v); a.v != "" && err != nil {
return fmt.Errorf("%s: %v", a.key, err)
}
}
if l.TLSAddress != "" && (l.CertFile == "" || l.KeyFile == "") {
return errors.New("tls_address needs tls_cert and tls_key")
}
if l.Network == "" {
l.Network = c.Settings.Name
}
for _, ps := range peers {
p := irclink.Peer{Name: ps.Name, Address: ps.String("address", ""),
SendPassword: ps.String("send_password", ""), AcceptPassword: ps.String("accept_password", ""),
Tag: ps.String("tag", "")}
if p.TLS, err = ps.Bool("tls", false); err != nil {
return fmt.Errorf("[ircpeer %s] %w", ps.Name, err)
}
if p.TLSVerify, err = ps.Bool("tls_verify", true); err != nil {
return fmt.Errorf("[ircpeer %s] %w", ps.Name, err)
}
switch proto := strings.ToLower(ps.String("protocol", "ts6")); proto {
case "ts6":
case "hybrid":
p.Hybrid = true
default:
return fmt.Errorf("[ircpeer %s] protocol: ts6 or hybrid, not %q", ps.Name, proto)
}
if p.Address == "none" {
p.Address = ""
}
if _, _, err := net.SplitHostPort(p.Address); p.Address != "" && err != nil {
return fmt.Errorf("[ircpeer %s] address: %v", ps.Name, err)
}
l.Peers = append(l.Peers, p)
}
if err := l.Check(c.Settings.Name); err != nil {
return err
}
if len(l.Peers) == 0 {
c.Warnings = append(c.Warnings, "[irclink] no [ircpeer NAME]: nothing links to it")
}
if l.Address != "" && l.TLSAddress == "" {
c.Warnings = append(c.Warnings, "[irclink] links in by plain TCP: their passwords go in the clear (tls_address)")
}
c.IRCLink = l
return nil
}()
if err != nil {
return fmt.Errorf("[irclink] %w", err)
}
return nil
}
+51
View File
@@ -0,0 +1,51 @@
package server
import (
"os"
"path/filepath"
"strings"
"testing"
)
// TestIRCLinkConfig: [irclink] and its peers with their defaults, none
// without it, and bad names, IDs, tags, protocols and passwords refused.
func TestIRCLinkConfig(t *testing.T) {
load := func(body string) (*Config, error) {
p := filepath.Join(t.TempDir(), "bbs.conf")
os.WriteFile(p, []byte("[listen telnet]\ntype = telnet\naddress = :2300\n"+body), 0600)
return Load(p)
}
const base = "[irclink]\nserver_name = irc.bbs.example\nsid = 1bb\n"
c, err := load(base + "tag = DM\n[ircpeer hub.example.net]\naddress = hub.example.net:7000\n" +
"send_password = a\naccept_password = b\nprotocol = hybrid\n[ircpeer leaf.example.net]\nsend_password = c\naccept_password = d\n")
if err != nil {
t.Fatal(err)
}
l := c.IRCLink
if l.SID != "1BB" || l.Tag != "DM" || l.Prefix != "irc-" || l.Address != ":7000" || l.NickLen != 30 || len(l.Peers) != 2 {
t.Fatalf("irclink %+v", l)
}
if p := l.Peers[0]; !p.Hybrid || !p.TLSVerify || p.Tag != "hub" || p.SendPassword != "a" {
t.Errorf("peer %+v", p)
}
if p := l.Peers[1]; p.Hybrid || p.Address != "" || p.Tag != "leaf" {
t.Errorf("peer %+v", p)
}
if c, err := load(""); err != nil || c.IRCLink != nil {
t.Errorf("no [irclink]: %+v %v", c.IRCLink, err)
}
for body, want := range map[string]string{
"[irclink]\nsid = 1BB\n": "server_name",
"[irclink]\nserver_name = irc.bbs.example\n": "sid",
base + "tag = no-dashes\n": "tag",
base + "prefix = Bad_\n": "prefix",
base + "nick_length = 3\n": "nick_length",
base + "[ircpeer x.example]\nsend_password = a\n": "accept_password",
base + "[ircpeer x.example]\nsend_password = a\naccept_password = b\nprotocol = p10\n": "protocol",
"[ircpeer x.example]\n": "without [irclink]",
} {
if _, err := load(body); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%q: %v", body, err)
}
}
}
+1
View File
@@ -50,6 +50,7 @@ nav:
- "FidoNet": FidoNet.md
- "Chat and paging": Chat-and-Paging.md
- "IRC": IRC.md
- "IRC server linking": IRC-Linking.md
- "AIM and ICQ": AIM-and-ICQ.md
- "MSN Messenger": MSN-Messenger.md
- "MRC": MRC.md