From e75f4ea03d6f2e8cb31a1e1aec54be378a0cbc5c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:00:22 +0000 Subject: [PATCH] AOL host: AOL clients sign on with BBS accounts internal/aol serves AOL's own clients over P3: each token the client sends is handled, and the host answers with atom streams compiled from FDO91 source. - Dd, the Welcome form's screen name and password (its two de_data), is a BBS login (Authenticate, throttled and logged as any); the client becomes a node, is taken online (async_online, its main window 32-296) and shown the BBS's Welcome window. A failed one gets an alert and async_force_off; "New User" is told to join by telnet or the web. - pE (Sign Off) is answered with XS, the host's sign-off. - Other tokens are answered with uni_wait_off, so the client doesn't wait on them, and are logged; before sign-on they're ignored. - Streams go as aT in one packet, or at pieces with one 4-byte id when long; a stream the client spreads over packets (4.0) is put together. [aol] turns it on, at :5190 by default. When [oscar] listens there too the two share the port: OSCAR hands over connections that begin as P3. Tested with a scripted client (sign-on, refusals, sign-off, long streams both ways) and through OSCAR's port. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRRm1WrfJdB863kw36V --- TODO.md | 18 +- bbs.conf.sample | 10 + cmd/bbs/main.go | 36 +++ docs/wiki/AOL.md | 47 ++++ docs/wiki/Configuration-Reference.md | 12 + docs/wiki/Home.md | 1 + docs/wiki/_Sidebar.md | 1 + internal/aol/aol.go | 113 +++++++++ internal/aol/aol_test.go | 330 +++++++++++++++++++++++++++ internal/aol/forms.go | 52 +++++ internal/aol/session.go | 279 ++++++++++++++++++++++ internal/server/aolconfig.go | 36 +++ internal/server/config.go | 7 +- 13 files changed, 933 insertions(+), 9 deletions(-) create mode 100644 docs/wiki/AOL.md create mode 100644 internal/aol/aol.go create mode 100644 internal/aol/aol_test.go create mode 100644 internal/aol/forms.go create mode 100644 internal/aol/session.go create mode 100644 internal/server/aolconfig.go diff --git a/TODO.md b/TODO.md index 50ba3e3..5ef228f 100644 --- a/TODO.md +++ b/TODO.md @@ -4,8 +4,8 @@ Ideas not yet started, with what is known of them. ## An AOL front end -*Status: started; the FDO91 layer (`internal/aol/fdo`) and P3 -(`internal/aol/p3`) are done.* +*Status: started; FDO91 (`internal/aol/fdo`), P3 (`internal/aol/p3`) and +the host's sign-on (`internal/aol`, `[aol]`) are done.* For AOL 3.0 and 4.0 for Windows, the real clients, over TCP (port 5190, the client's `AmericaOnline.aol.com`) and by modem. @@ -19,12 +19,14 @@ client's `AmericaOnline.aol.com`) and by modem. end of a link: INIT acknowledged, DATA in order in and within a window of 16 out, ACKs every 8 or soon after, NAKs and go-back-N resends, heartbeats after 12 seconds, 10 of them and the link is down. -- **Listener**, next: OSCAR's port 5190 already hands a connection that - starts with P3's sync byte to `oscar.Server.P3`; serve it there with - `p3.Serve`, and sniff a P3 INIT (`p3.Sniff`) on the telnet port too. -- **Tokens**: `Dd` sign-on (the form's two `de_data`) to the BBS's login, - then chat (`Aa`), IMs (`iS`), mail (`m4`, MIP), keywords (`k1`/`f1`) to - areas, `pE` sign-off; each answered with forms compiled from source. +- **Host** (started): `[aol]`, sharing 5190 with `[oscar]` through its P3 + hook; `Dd` signs on with a BBS account (a node, as any caller), then + `async_online`, the client's main window (32-296) and the BBS's own + Welcome; `pE` answered with `XS`; other tokens with `uni_wait_off`. + Streams go as `aT`, or `at` pieces when long; the client's long ones + are put together. Not yet tried with a real client. +- **Tokens**, next: chat (`Aa`), IMs (`iS`), mail (`m4`, MIP), keywords + (`k1`/`f1`) to areas; each answered with forms compiled from source. - **Modem callers**: the client's CCL script expects a network's prompts (SprintNet, Tymnet) before P3; emulate one, or ship a CCL that dials straight in. diff --git a/bbs.conf.sample b/bbs.conf.sample index 4483b9c..b133fb8 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -670,6 +670,16 @@ address = 127.0.0.1:2513 ; the screen name the BBS's notices come from ;system = OnlineHost +; 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). +;[aol] +;address = :5190 +;max_clients = 256 +;max_per_ip = 4 + ; Multi Relay Chat: the BBSes' chat network. Its rooms are the chat rooms ; beginning mrc- here (mrc-lobby is its lobby), on terminals and IRC alike. ; See docs/wiki/MRC.md diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index 3f106e6..0f2b65c 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -48,6 +48,7 @@ import ( "io" "log" "log/syslog" + "net" "os" "os/signal" "path/filepath" @@ -58,6 +59,7 @@ import ( "golang.org/x/term" + "github.com/D-Modem/bbs/internal/aol" "github.com/D-Modem/bbs/internal/api" "github.com/D-Modem/bbs/internal/bbs" "github.com/D-Modem/bbs/internal/events" @@ -269,6 +271,9 @@ func main() { if o := cfg.OSCAR; o != nil { fmt.Printf("oscar: %q, reconnect at %q, ICQ numbers from %d\n", o.Address, o.Host, o.UINBase) } + if a := cfg.AOL; a != nil { + fmt.Printf("aol: %q\n", a.Address) + } if cfg.Finger != nil { fmt.Printf("finger: %s (online %v, users %v)\n", cfg.Finger.Address, cfg.Finger.Online, cfg.Finger.Users) } @@ -462,12 +467,23 @@ func serve(cfg *server.Config, path string) int { } }() } + var asrv *aol.Server + if cfg.AOL != nil { + if asrv, err = aol.New(b, *cfg.AOL); err != nil { + lg.Printf("%v", err) + return 1 + } + } if cfg.OSCAR != nil { osrv, err := oscar.New(b, *cfg.OSCAR) if err != nil { lg.Printf("%v", err) return 1 } + if asrv != nil && sameAddress(cfg.OSCAR.Address, cfg.AOL.Address) { + osrv.P3 = asrv.Handle // AOL's clients come to OSCAR's port + asrv = nil + } go func() { if err := osrv.Run(ctx); err != nil { lg.Printf("%v", err) @@ -475,6 +491,14 @@ func serve(cfg *server.Config, path string) int { } }() } + if asrv != nil { + go func() { + if err := asrv.Run(ctx); err != nil { + lg.Printf("%v", err) + stop() + } + }() + } if cfg.Finger != nil { fs := &finger.Server{B: b, S: *cfg.Finger} go func() { @@ -1667,3 +1691,15 @@ func dbCmd(cfg *server.Config, args []string) { } fmt.Println("done: set database = in the configuration to the new one") } + +// sameAddress is whether two listening addresses are one port: the same +// port, on the same host or on every one. +func sameAddress(a, b string) bool { + ah, ap, err1 := net.SplitHostPort(a) + bh, bp, err2 := net.SplitHostPort(b) + if err1 != nil || err2 != nil || ap != bp { + return false + } + any := func(h string) bool { return h == "" || h == "0.0.0.0" || h == "::" } + return ah == bh || any(ah) || any(bh) +} diff --git a/docs/wiki/AOL.md b/docs/wiki/AOL.md new file mode 100644 index 0000000..f4bcc43 --- /dev/null +++ b/docs/wiki/AOL.md @@ -0,0 +1,47 @@ +The BBS can be an AOL host for AOL's own Windows clients (3.0, 4.0 and +later) over TCP. A caller signs on in the client with their BBS name and +password, and the BBS draws its Welcome window. This is early work: sign-on +and sign-off work, and chat, IMs, mail and keywords are still to come. + +```ini +[aol] +address = :5190 +``` + +| Setting | Default | What it sets | +|---|---|---| +| `address` | `:5190` | where to listen | +| `max_clients` | `256` | clients at once | +| `max_per_ip` | `4` | from one address | + +Port 5190 is also the [AIM and ICQ](AIM-and-ICQ) server's. With `[oscar]` +on the same address, the two share it: a connection that begins as an AOL +client's goes to the AOL host, and everything else stays with OSCAR. + +## Pointing the client at the BBS + +The client's TCP connection (`TCP.CCL` in its folder) dials +`AmericaOnline.aol.com` on port 5190. Either point that name at the BBS in +the hosts file of the client's machine +(`C:\Windows\hosts` on Windows 95 and 98), or change the name in `TCP.CCL`. +Then pick "TCP/IP" as the connection in the client's Setup. + +## Signing on + +The screen name and password on the client's Welcome window are a BBS +account's. "New User" does not make an account; callers join by telnet or +the web first. A failed sign-on is shown in the client, and counts against +the address as failed logins do everywhere else. The deny list and bans in +`[security]` apply. + +A signed-on client is a node, as any caller is, and appears in Who's On +as `AOL`. Sign Off in the client signs off and hangs up. + +## How it is built + +- `internal/aol/p3`: P3, the client's link layer (packets, checksums, + acknowledgements, resends). +- `internal/aol/fdo`: FDO91, the forms language the client draws windows + from. It has a compiler from FDO91 source, so the host's windows are + written as source. +- `internal/aol`: the host, which handles each token the client sends. diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 1132fd3..069edb5 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -32,6 +32,7 @@ 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. | +| [`[aol]`](#aol) | AOL: a host for AOL's own clients (3.0, 4.0 and on, over TCP). | | [`[mrc]`](#mrc) | Multi Relay Chat: the BBSes' chat network. | | [`[finger]`](#finger) | finger: who is on ("finger @host"), and who a user is ("finger name@host"). | | [`[gopher]`](#gopher) | gopher: about the system, who is on, and what areas the sysop opens: no login, so anyone sees them. | @@ -449,6 +450,17 @@ 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`. | +## `[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). + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:5190`. | +| `max_clients` | | | See the section above. Examples: `256`. | +| `max_per_ip` | | | See the section above. Examples: `4`. | + + ## `[mrc]` Multi Relay Chat: the BBSes' chat network. Its rooms are the chat rooms beginning mrc- here (mrc-lobby is its lobby), on terminals and IRC alike. See docs/wiki/MRC.md. diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 8357ebb..ba7d31a 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -135,6 +135,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 | +| [AOL clients](AOL) | a host for AOL's own clients (3.0, 4.0): sign-on with BBS accounts | | [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes | | [Finger and gopher](Finger-and-Gopher) | who is on, and the BBS in gopherspace | | [Web forum](Web-Forum) | the message areas as a web forum | diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 4dcd373..6a8de74 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -34,6 +34,7 @@ - [Chat and paging](Chat-and-Paging) - [IRC](IRC) - [AIM and ICQ](AIM-and-ICQ) +- [AOL clients](AOL) - [MRC](MRC) - [Finger and gopher](Finger-and-Gopher) - [Web forum](Web-Forum) diff --git a/internal/aol/aol.go b/internal/aol/aol.go new file mode 100644 index 0000000..401b7fc --- /dev/null +++ b/internal/aol/aol.go @@ -0,0 +1,113 @@ +// Package aol is the BBS as an AOL host, for AOL's own clients (3.0, 4.0 +// and on) over TCP: P3 (package p3) carries tokens, a two-letter name and +// what follows it, each way; the client's forms send their fields as FDO91 +// atom streams (package fdo), and the host answers with streams of its +// own that draw windows and run actions. +// +// The client signs on with a BBS account (the Welcome form's screen name +// and password, token Dd), and signs off with pE. The client's own +// database has most of its windows; the host draws its own Welcome. +// +// Sources for what the client expects: Dialtone (MIT) and other hosts +// serving live clients, and notes on the 3.0 client's code. +package aol + +import ( + "context" + "errors" + "fmt" + "net" + "sync" + + "github.com/D-Modem/bbs/internal/aol/p3" + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/sockets" + "github.com/D-Modem/bbs/internal/tcpserv" +) + +// Settings are the [aol] section's. +type Settings struct { + // Address is where to listen: the client's port is 5190, which the + // OSCAR server (AIM, ICQ) shares when it listens there too. + Address string + MaxClients int + MaxPerIP int +} + +// Server serves AOL clients. +type Server struct { + B *bbs.BBS + S Settings + + // Trace, if set, is told of every packet (for the sysop's debugging). + Trace func(remote string, in bool, p p3.Packet) + + mu sync.Mutex + sessions map[*session]bool +} + +// New checks the settings and makes the server. +func New(b *bbs.BBS, s Settings) (*Server, error) { + if s.Address != "" { + if _, _, err := net.SplitHostPort(s.Address); err != nil { + return nil, fmt.Errorf("aol: address: %w", err) + } + } + if s.MaxClients == 0 { + s.MaxClients = 256 + } + return &Server{B: b, S: s, sessions: map[*session]bool{}}, nil +} + +// Run listens on the settings' address until ctx is done. +func (s *Server) Run(ctx context.Context) error { + if s.S.Address == "" { + return errors.New("aol: no address to listen on") + } + ln, err := sockets.Listen("tcp", s.S.Address) + if err != nil { + return fmt.Errorf("aol: %w", err) + } + return s.Serve(ctx, ln) +} + +// Serve answers on ln until ctx is done. +func (s *Server) Serve(ctx context.Context, ln net.Listener) error { + ts := &tcpserv.Server{Name: "aol", MaxClients: s.S.MaxClients, MaxPerIP: s.S.MaxPerIP, Log: s.B.Log, + Handle: s.Handle, + Refuse: func(c net.Conn) bool { return s.B.Refuse("aol", c.RemoteAddr()) }} + return ts.Serve(ctx, ln) +} + +// Clients is how many clients are connected. +func (s *Server) Clients() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.sessions) +} + +// Handle serves one client's connection, from its first P3 packet (the +// OSCAR server hands over those that begin as P3). +func (s *Server) Handle(c net.Conn) { + host, _, _ := net.SplitHostPort(c.RemoteAddr().String()) + opt := p3.Options{Logf: func(f string, a ...any) { s.B.Log.Printf("aol: %s: "+f, append([]any{host}, a...)...) }} + if s.Trace != nil { + opt.Trace = func(in bool, p p3.Packet) { s.Trace(host, in, p) } + } + l, err := p3.Serve(c, opt) + if err != nil { + s.B.Log.Printf("aol: %s: %v", host, err) + return + } + ss := &session{s: s, l: l, host: host, init: l.Init(), parts: map[partKey][]byte{}} + s.mu.Lock() + s.sessions[ss] = true + s.mu.Unlock() + defer func() { + s.mu.Lock() + delete(s.sessions, ss) + s.mu.Unlock() + }() + s.B.Log.Printf("aol: %s: %s", host, ss.init) + ss.serve() +} diff --git a/internal/aol/aol_test.go b/internal/aol/aol_test.go new file mode 100644 index 0000000..187c788 --- /dev/null +++ b/internal/aol/aol_test.go @@ -0,0 +1,330 @@ +package aol + +import ( + "bytes" + "context" + "log" + "net" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/D-Modem/bbs/internal/aol/fdo" + "github.com/D-Modem/bbs/internal/aol/p3" + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/oscar" + "github.com/D-Modem/bbs/internal/store" +) + +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuf) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// newServer is a BBS (alice, password1) with an AOL host. +func newServer(t *testing.T) (*Server, *syncBuf) { + 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() }) + if _, err := st.CreateUser("alice", "password1", "Here", false); err != nil { + t.Fatal(err) + } + s := bbs.Defaults() + s.Name, s.FailDelay = "Test BBS", 0 + logs := &syncBuf{} + b := bbs.New(s, st, log.New(logs, "", 0)) + srv, err := New(b, Settings{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if t.Failed() { + t.Log("log:\n" + logs.String()) + } + }) + return srv, logs +} + +// client is a scripted AOL client: P3 by hand, tokens in DATA. +type client struct { + t *testing.T + c net.Conn + tx, rx uint8 + pkts chan p3.Packet +} + +func connect(t *testing.T, srv *Server) *client { + t.Helper() + a, b := net.Pipe() + go srv.Handle(b) + return attach(t, a) +} + +// attach begins P3 on a, a connection to the host. +func attach(t *testing.T, a net.Conn) *client { + t.Helper() + c := &client{t: t, c: a, tx: p3.SeqInit, rx: p3.SeqInit, pkts: make(chan p3.Packet, 256)} + go func() { + r := p3.NewReader(a) + for { + p, err := r.Read() + if err != nil { + close(c.pkts) + return + } + c.pkts <- p + } + }() + t.Cleanup(func() { a.Close() }) + init := make([]byte, 0x34) + init[0], init[1] = p3.PlatformWindows, 3 + c.write(p3.Packet{TX: p3.SeqInit, RX: p3.SeqInit, Type: p3.INIT, Data: init}) + if p := c.next(); p.Type != p3.ACK { + t.Fatalf("INIT answered with %v", p) + } + return c +} + +func (c *client) write(p p3.Packet) { + p.Type |= p3.FromClient + if _, err := c.c.Write(p3.Append(nil, p)); err != nil { + c.t.Fatal(err) + } +} + +// send sends a token in a DATA packet. +func (c *client) send(token string, data []byte) { + c.tx = next(c.tx) + c.write(p3.Packet{TX: c.tx, RX: c.rx, Type: p3.DATA, Data: append([]byte(token), data...)}) +} + +func next(s uint8) uint8 { + if s >= p3.SeqMax { + return p3.SeqMin + } + return s + 1 +} + +func (c *client) next() p3.Packet { + c.t.Helper() + select { + case p, ok := <-c.pkts: + if !ok { + c.t.Fatal("hung up") + } + return p + case <-time.After(3 * time.Second): + c.t.Fatal("nothing from the host") + } + return p3.Packet{} +} + +// token is the next token the host sends (acknowledging it), and its +// data; the host's ACKs are passed over. +func (c *client) token() (string, []byte) { + c.t.Helper() + for { + p := c.next() + if p.Kind() != p3.DATA { + continue + } + c.rx = p.TX + c.write(p3.Packet{TX: c.tx, RX: c.rx, Type: p3.ACK}) + tok, rest := p3.Token(p.Data) + return tok, rest + } +} + +// stream is the next atom stream the host sends (aT, or at in pieces), +// decompiled. +func (c *client) stream() string { + c.t.Helper() + var held []byte + for { + tok, d := c.token() + switch tok { + case "aT": + src, err := fdo.Decompile(d) + if err != nil { + c.t.Fatal(err) + } + return src + case "at": + held = append(held, d[4:]...) + if src, err := fdo.Decompile(held); err == nil && strings.Contains(src, "uni_end_stream") { + return src + } + default: + c.t.Fatalf("token %q, wanted a stream", tok) + } + } +} + +// signOnForm is the Welcome form's Dd, as the 3.0 client sends it: its +// stream id, then the screen name and password as de_data. +func signOnForm(name, pw string) []byte { + src := `uni_start_stream + man_set_context_relative <00x, 00x, 00x, 01x> + man_set_context_index <00x, 00x, 00x, 01x> + de_data <` + fdo.Quote(name) + `> + man_end_context + man_end_context + man_set_context_relative <00x, 00x, 00x, 02x> + de_data <` + fdo.Quote(pw) + `> + man_end_context +uni_end_stream +` + return append([]byte{0x00, 0x15}, fdo.MustCompile(src)...) +} + +func TestSignOn(t *testing.T) { + srv, logs := newServer(t) + c := connect(t, srv) + c.send("Dd", signOnForm("alice ", "password1")) + if s := c.stream(); !strings.Contains(s, "async_online") || !strings.Contains(s, "uni_invoke_local <32-296>") { + t.Errorf("online:\n%s", s) + } + if s := c.stream(); !strings.Contains(s, `man_start_object `) || + !strings.Contains(s, "Welcome to Test BBS, alice!") { + t.Errorf("welcome:\n%s", s) + } + nodes := srv.B.Nodes() + if len(nodes) != 1 || nodes[0].User != "alice" { + t.Errorf("nodes %+v", nodes) + } + + // a token not served yet is answered, so the client doesn't wait + c.send("k1", []byte{0, 1}) + if s := c.stream(); !strings.Contains(s, "uni_wait_off") { + t.Errorf("k1:\n%s", s) + } + + // Sign Off + c.send("pE", []byte{0, 1}) + if tok, d := c.token(); tok != "XS" || !bytes.Equal(d, []byte{0}) { + t.Errorf("pE answered %q % x", tok, d) + } + c.c.Close() + for i := 0; len(srv.B.Nodes()) > 0; i++ { + if i > 100 { + t.Fatal("node not given back") + } + time.Sleep(10 * time.Millisecond) + } + if !strings.Contains(logs.String(), "alice on AOL") { + t.Error("not logged") + } +} + +func TestSignOnRefused(t *testing.T) { + srv, _ := newServer(t) + for _, c := range []struct{ name, pw, want string }{ + {"alice", "wrong", "Incorrect screen name or password"}, + {"New User", "", "call it by telnet or the web first"}, + } { + cl := connect(t, srv) + cl.send("Dd", signOnForm(c.name, c.pw)) + if s := cl.stream(); !strings.Contains(s, "async_alert +uni_end_stream +` + +// alertForm is a message box. +func alertForm(text string) string { + return fmt.Sprintf("uni_start_stream\n async_alert \nuni_end_stream\n", fdo.Quote(text)) +} + +// welcomeForm is the BBS's Welcome window. +func welcomeForm(bbsName, user string, online int) string { + others := "You are the only one here." + switch { + case online == 2: + others = "One other caller is here." + case online > 2: + others = fmt.Sprintf("%d other callers are here.", online-1) + } + text := strings.Join([]string{ + fmt.Sprintf("Welcome to %s, %s!", bbsName, user), + "", + "You are signed on with your BBS account. " + others, + }, "\r\n") // the client drops what follows a bare CR + return fmt.Sprintf(`uni_start_stream + man_start_object + mat_orientation + mat_position + man_start_object + mat_size <40, 6> + man_append_data <%s> + man_end_data + man_end_object + man_update_display + uni_wait_off +uni_end_stream +`, fdo.Quote("Welcome, "+user+"!"), fdo.Quote(text)) +} diff --git a/internal/aol/session.go b/internal/aol/session.go new file mode 100644 index 0000000..da9b0cb --- /dev/null +++ b/internal/aol/session.go @@ -0,0 +1,279 @@ +package aol + +import ( + "bytes" + "crypto/rand" + "errors" + "fmt" + "strings" + "sync" + + "github.com/D-Modem/bbs/internal/aol/fdo" + "github.com/D-Modem/bbs/internal/aol/p3" + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +// streamChunk is the most of an atom stream the host puts in one packet. +const streamChunk = 900 + +// session is one client's. +type session struct { + s *Server + l *p3.Link + host string + init p3.Init + + mu sync.Mutex + u *store.User // signed on as + n *bbs.Node + + parts map[partKey][]byte // streams the client has sent part of +} + +type partKey struct { + token string + sid string +} + +func (ss *session) logf(format string, args ...any) { + ss.s.B.Log.Printf("aol: %s: "+format, append([]any{ss.host}, args...)...) +} + +// serve reads the client's tokens until the link is down. +func (ss *session) serve() { + defer func() { + ss.l.Close() + ss.mu.Lock() + n, u := ss.n, ss.u + ss.mu.Unlock() + if n != nil { + n.Leave() + ss.s.B.Log.Printf("node %d: gone (aol)", n.Num) + } else if u == nil { + ss.logf("gone before signing on") + } + }() + for { + d, err := ss.l.Read() + if err != nil { + if !errors.Is(err, p3.ErrClosed) { + ss.logf("%v", err) + } + return + } + tok, body := p3.Token(d) + if tok == "" { + continue + } + ss.token(tok, body) + } +} + +// signedOn is whether the client has signed on. +func (ss *session) signedOn() bool { + ss.mu.Lock() + defer ss.mu.Unlock() + return ss.u != nil +} + +// token handles one token from the client. +func (ss *session) token(tok string, body []byte) { + sid, atoms := splitStream(tok, body) + if atoms = ss.whole(tok, sid, atoms); atoms == nil { + return // more to come + } + switch { + case tok == "Dd": + ss.signOn(atoms) + case !ss.signedOn(): + ss.logf("token %q before signing on", tok) + case tok == "pE": + ss.signOff() + default: + ss.logf("token %q (not served yet)", tok) + // never leave the client waiting on an answer that won't come + ss.send("uni_start_stream\n uni_wait_off\nuni_end_stream\n") + } +} + +// splitStream splits a token's data into its stream id and the atoms +// after it. The id is two bytes, but for the a/A t/T family: "aT" none, +// "At" three, "at" four. +func splitStream(tok string, body []byte) (sid, atoms []byte) { + n := 2 + switch tok { + case "aT": + n = 0 + case "At": + n = 3 + case "at": + n = 4 + } + if len(body) < n { + return body, nil + } + return body[:n], body[n:] +} + +// whole is a stream the client sent, once all of it has come: AOL 4.0 +// spreads a long one (a mail, an IM) over packets of the same token and +// stream id, from uni_start_stream to uni_end_stream. nil: more to come. +func (ss *session) whole(tok string, sid, atoms []byte) []byte { + k := partKey{tok, string(sid)} + if held, ok := ss.parts[k]; ok { + atoms = append(held, atoms...) + delete(ss.parts, k) + } + frames, err := fdo.Decode(atoms) + if len(sid) > 0 && (err != nil || len(frames) > 0 && frames[0].Name() == "uni_start_stream" && !hasEnd(frames)) { + if len(atoms) > 64<<10 { + ss.logf("token %q: a stream of more than 64K; dropped", tok) + return nil + } + ss.parts[k] = append([]byte(nil), atoms...) + return nil + } + if atoms == nil { + atoms = []byte{} + } + return atoms +} + +func hasEnd(frames []fdo.Frame) bool { + _, ok := fdo.Find(frames, "uni_end_stream") + return ok +} + +// send compiles FDO91 source and sends it to the client to run. A +// source of more than one stream goes as one stream at a time. +func (ss *session) send(src string) error { + b, err := fdo.Compile(src) + if err != nil { + ss.logf("a form that doesn't compile: %v", err) + return err + } + return ss.sendAtoms(b) +} + +// sendAtoms sends an atom stream: in one packet as token aT, or, too big +// for one, in pieces as token at, each with the same four-byte id. +func (ss *session) sendAtoms(b []byte) error { + frames, err := fdo.Decode(b) + if err != nil { + return err + } + for _, st := range topStreams(frames) { + enc := fdo.Encode(st) + if len(enc) <= streamChunk { + if err := ss.l.WriteToken("aT", enc); err != nil { + return err + } + continue + } + var id [4]byte + rand.Read(id[:]) + for _, piece := range fdo.Packets(st, streamChunk) { + if err := ss.l.WriteToken("at", append(id[:], piece...)); err != nil { + return err + } + } + } + return nil +} + +// topStreams splits frames into its streams at the top level, each from +// uni_start_stream to its uni_end_stream. +func topStreams(frames []fdo.Frame) [][]fdo.Frame { + var out [][]fdo.Frame + depth, start := 0, 0 + for i, f := range frames { + switch f.Name() { + case "uni_start_stream": + if depth == 0 { + start = i + } + depth++ + case "uni_end_stream": + depth-- + if depth == 0 { + out = append(out, frames[start:i+1]) + start = i + 1 + } + } + } + if start < len(frames) { + out = append(out, frames[start:]) + } + return out +} + +// signOn is Dd: the Welcome form's screen name and password, its two +// de_data, checked as a BBS login. +func (ss *session) signOn(atoms []byte) { + if ss.signedOn() { + return + } + frames, err := fdo.Decode(atoms) + if err != nil { + ss.logf("Dd: %v", err) + } + de := fdo.FindAll(frames, "de_data") + if len(de) < 2 { + ss.logf("Dd without a name and password: % x", atoms) + ss.refuse("Please type your screen name and password.") + return + } + name := strings.TrimSpace(fdo.FromLatin1(de[0].Data)) + pw := strings.TrimSpace(fdo.FromLatin1(bytes.TrimRight(de[1].Data, "\x00"))) + b := ss.s.B + if strings.EqualFold(name, "New User") { + ss.refuse(fmt.Sprintf("To join %s, call it by telnet or the web first; then sign on here with "+ + "your name and password.", b.Conf().Name)) + return + } + u, err := b.Authenticate("aol", "ip:"+ss.host, name, pw) + if err != nil { + ss.logf("%s: %v", name, err) + msg := "Incorrect screen name or password. Please check them and try again." + switch { + case errors.Is(err, bbs.ErrLocked): + msg = "This account is locked." + case errors.Is(err, bbs.ErrThrottled): + msg = "Too many failed sign-ons. Please try again later." + } + ss.refuse(msg) + return + } + n, err := b.Enter(&bbs.Caller{Via: "aol", Listener: "aol", Remote: ss.host, Source: "ip:" + ss.host, + Terminal: ss.init.String()}, func() { ss.l.Close() }) + if err != nil { + ss.refuse("All lines are busy. Please try again later.") + return + } + n.SetUser(u) + n.Doing("AOL") + ss.mu.Lock() + ss.u, ss.n = u, n + ss.mu.Unlock() + b.Log.Printf("node %d: %s on AOL (%s, %s)", n.Num, u.Name, ss.host, ss.init) + ss.send(onlineForm) + ss.send(welcomeForm(b.Conf().Name, u.Name, len(b.Nodes()))) +} + +// refuse tells the client why it can't sign on, and has it hang up. +func (ss *session) refuse(why string) { + ss.send(alertForm(why) + "uni_start_stream\n async_force_off\nuni_end_stream\n") +} + +// signOff is pE, the Sign Off menu: XS has the client sign off as if the +// host had (its offline broadcast, the Goodbye window), and hang up. +func (ss *session) signOff() { + ss.mu.Lock() + u := ss.u + ss.mu.Unlock() + if u != nil { + ss.logf("%s signs off", u.Name) + } + ss.l.WriteToken("XS", []byte{0}) +} diff --git a/internal/server/aolconfig.go b/internal/server/aolconfig.go new file mode 100644 index 0000000..24088e0 --- /dev/null +++ b/internal/server/aolconfig.go @@ -0,0 +1,36 @@ +package server + +import ( + "fmt" + "net" + + "github.com/D-Modem/bbs/internal/aol" + "github.com/D-Modem/bbs/internal/config" +) + +// aolSection reads [aol]: the host for AOL's own clients. +func (c *Config) aolSection(cf *config.File) error { + s := cf.Get("aol", "") + if s == nil { + return nil + } + err := func() error { + a := &aol.Settings{Address: s.String("address", ":5190")} + if _, _, err := net.SplitHostPort(a.Address); err != nil { + return fmt.Errorf("address: %v", err) + } + var err error + if a.MaxClients, err = s.Int("max_clients", 256, 1, 100000); err != nil { + return err + } + if a.MaxPerIP, err = s.Int("max_per_ip", 4, 0, 1000); err != nil { + return err + } + c.AOL = a + return nil + }() + if err != nil { + return fmt.Errorf("[aol] %w", err) + } + return nil +} diff --git a/internal/server/config.go b/internal/server/config.go index 4bbe265..d4ff92d 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "errors" "fmt" + "github.com/D-Modem/bbs/internal/aol" "github.com/D-Modem/bbs/internal/api" "net" "os" @@ -61,6 +62,7 @@ type Config struct { 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 MRC *mrc.Settings // nil: not on Multi Relay Chat Screens *screens.Set // nil: no screens of the sysop's ScriptsDir string // "": no scripts @@ -139,6 +141,9 @@ func load(cf *config.File) (*Config, error) { if err := c.oscarSection(cf); err != nil { return nil, err } + if err := c.aolSection(cf); err != nil { + return nil, err + } if err := c.mrcSection(cf); err != nil { return nil, err } @@ -208,7 +213,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", "irc", "oscar", "mrc", "menu", "strings", "http", "level", "chan": + case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "oscar", "aol", "mrc", "menu", "strings", "http", "level", "chan": default: return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind) }