From bb65fc1fc583efa13b2f56ac805720ad7232a217 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 20:51:24 +0000 Subject: [PATCH] Doors: drop files, a door runner and a Doors menu; dosemu2 image (WIP) [door NAME] sections configure door programs for text callers: the BBS writes DOOR.SYS, DORINFO1.DEF, DOOR32.SYS and CHAIN.TXT into the node's directory and joins the caller's line to the program (pipes or a pty), translating CP437 for UTF-8 terminals, with a time limit, idle limit and hangup handling, single-caller doors and a cleanup command. doors/dosemu2 builds dosemu2 from source in Docker, with a rundoor wrapper putting the caller on COM1 behind dosemu2's FOSSIL; it is still being tested. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr --- bbs.conf.sample | 31 +++ cmd/bbs/main.go | 5 + doors/dosemu2/Dockerfile | 61 +++++ doors/dosemu2/build.sh | 13 ++ doors/dosemu2/dosemurc | 7 + doors/dosemu2/rundoor | 41 ++++ doors/dosemu2/testdoor/FOSDOOR.COM | Bin 0 -> 358 bytes doors/dosemu2/testdoor/fosdoor.asm | 130 +++++++++++ internal/bbs/bbs.go | 3 + internal/door/door.go | 364 +++++++++++++++++++++++++++++ internal/door/door_test.go | 185 +++++++++++++++ internal/door/dropfile.go | 227 ++++++++++++++++++ internal/door/pty.go | 47 ++++ internal/server/config.go | 7 +- internal/server/doorconfig.go | 92 ++++++++ internal/server/doorconfig_test.go | 94 ++++++++ internal/textui/doors.go | 110 +++++++++ internal/textui/ui.go | 21 +- 18 files changed, 1431 insertions(+), 7 deletions(-) create mode 100644 doors/dosemu2/Dockerfile create mode 100755 doors/dosemu2/build.sh create mode 100644 doors/dosemu2/dosemurc create mode 100755 doors/dosemu2/rundoor create mode 100644 doors/dosemu2/testdoor/FOSDOOR.COM create mode 100644 doors/dosemu2/testdoor/fosdoor.asm create mode 100644 internal/door/door.go create mode 100644 internal/door/door_test.go create mode 100644 internal/door/dropfile.go create mode 100644 internal/door/pty.go create mode 100644 internal/server/doorconfig.go create mode 100644 internal/server/doorconfig_test.go create mode 100644 internal/textui/doors.go diff --git a/bbs.conf.sample b/bbs.conf.sample index 783df67..54424da 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -227,3 +227,34 @@ address = 127.0.0.1:2513 ;poll = 3600 ; which of our addresses it knows us by (default: ours in its zone) ;aka = 21:1/999 + +; Doors: programs callers on the text BBS play (D on the main menu). The +; BBS writes drop files (DOOR.SYS, DORINFO1.DEF, DOOR32.SYS, CHAIN.TXT) into +; the node's own directory and joins the caller's line to the door until it +; ends, the caller hangs up, or the time is up. One section each +; +; A DOS door, in dosemu2 in Docker (doors/dosemu2: docker build -t +; bbs-dosemu2 doors/dosemu2). D: is /srv/doors, E: the node's drop files, +; and the caller is on COM1 behind a FOSSIL +;[door lord] +;description = Legend of the Red Dragon +;command = docker run --rm -i --name bbs-door{node} -v /srv/doors:/doors -v {dir}:/node bbs-dosemu2 'D:\LORD' 'START.BAT {node}' +; the node's directory ({node} its number): mounted as /node above +;dir = /var/lib/bbs/doors/node{node} +;drop_files = door.sys dorinfo1.def door32.sys chain.txt +; cp437: shown as UTF-8 to UTF-8 terminals; utf-8; raw: as it comes +;charset = cp437 +; minutes a visit +;time_limit = 60 +;sysop_only = no +; yes: one caller at a time (a door that is not multi-node) +;single = no +; after the door: make sure its container is gone +;cleanup = docker rm -f bbs-door{node} +; +; A program for Linux: on a pseudo-terminal, in UTF-8 +;[door adventure] +;command = /usr/games/adventure +;charset = utf-8 +;pty = yes +;door32_comm = local diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index e285e11..e5ae66a 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -134,6 +134,10 @@ func main() { fmt.Printf("[link %s] %s, host %q, echoes %s, route %v\n", l.Name, l.Addr, l.Host, l.Echoes, l.Route) } } + for _, d := range cfg.Doors { + fmt.Printf("[door %s] %q, drop files %s in %s, %v\n", d.Name, d.Command, + strings.Join(d.DropFiles, " "), d.Dir, d.TimeLimit) + } fmt.Println("configuration OK") case "init": st := open(cfg) @@ -216,6 +220,7 @@ func serve(cfg *server.Config) int { defer st.Close() b := bbs.New(cfg.Settings, st, lg) b.News = cfg.News + b.Doors = cfg.Doors if b.Files, err = files.Open(st, cfg.FilesDir, cfg.MaxFileSize, cfg.UploadQuota); err != nil { lg.Printf("files: %v", err) return 1 diff --git a/doors/dosemu2/Dockerfile b/doors/dosemu2/Dockerfile new file mode 100644 index 0000000..325339b --- /dev/null +++ b/doors/dosemu2/Dockerfile @@ -0,0 +1,61 @@ +# DOS doors for the BBS: dosemu2 (with the fdpp kernel and the comcom64 +# shell), built from source as dosemu2's own Dockerfile.debian does (on Ubuntu, which has every +# build dependency), so +# that no PPA is needed. The BBS runs a door as +# +# docker run --rm -i -v DOORS:/doors -v NODEDIR:/node bbs-dosemu2 \ +# rundoor 'CD \LORD' 'LORD.EXE /N{node}' +# +# and the caller's line is the door's COM1 (a FOSSIL is loaded). +# +# docker build -t bbs-dosemu2 doors/dosemu2 + +ARG BASE=ubuntu:26.04 + +FROM ${BASE} AS builder +WORKDIR /src +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential devscripts meson git python3-ply ca-certificates \ + nasm pkgconf libelf-dev binutils-i686-linux-gnu smallerc ninja-build \ + debhelper universal-ctags gcc-i686-linux-gnu \ + libb64-dev libjson-c-dev libslirp-dev libseccomp-dev libslang2-dev \ + libsearpc-dev libsdl3-dev libfluidsynth-dev gawk xfonts-utils \ + libgpm-dev libsdl3-ttf-dev libfontconfig1-dev ladspa-sdk libao-dev \ + libieee1284-3-dev valgrind bison flex autoconf automake libreadline-dev \ + libasound2-dev libx11-dev libxext-dev libglib2.0-dev + +# the pieces, in order; each a git ref (a tag or commit to pin a build) +ARG THUNK_GEN_REF=HEAD FDPP_REF=HEAD DJSTUB_REF=HEAD DJDEV64_REF=HEAD \ + DJ64DEV_REF=HEAD COMCOM64_REF=HEAD DOSEMU2_REF=HEAD +COPY build.sh /src/ +RUN ./build.sh thunk_gen https://github.com/stsp/thunk_gen.git $THUNK_GEN_REF && \ + apt-get install -y ./thunk-gen*.deb +RUN ./build.sh fdpp https://github.com/dosemu2/fdpp.git $FDPP_REF && \ + apt-get install -y ./libfdpp*.deb ./libfdldr*.deb ./fdpp*.deb +RUN ./build.sh djstub https://github.com/stsp/djstub.git $DJSTUB_REF && \ + apt-get install -y ./djstub*.deb +RUN ./build.sh djdev64 https://github.com/dosemu2/djdev64.git $DJDEV64_REF && \ + apt-get install -y ./libdjstub64*.deb ./libdjdev64*.deb ./djdev64-dev*.deb +RUN ./build.sh dj64dev https://github.com/stsp/dj64dev.git $DJ64DEV_REF && \ + apt-get install -y ./dj64*.deb ./dj32*.deb +RUN ./build.sh comcom64 https://github.com/dosemu2/comcom64.git $COMCOM64_REF && \ + apt-get install -y ./comcom64*.deb +RUN ./build.sh dosemu2 https://github.com/dosemu2/dosemu2.git $DOSEMU2_REF && \ + apt-get install -y ./dosemu2*.deb +RUN mkdir /debs && cp *.deb /debs/ && ls /debs + +FROM ${BASE} +ARG DEBIAN_FRONTEND=noninteractive +COPY --from=builder /debs /debs +RUN apt-get update && \ + apt-get install -y --no-install-recommends socat \ + $(ls /debs/*.deb | grep -v -e '-dev_' -e '/thunk-gen' -e '/dj64_' -e '/dj32_' -e '/djstub_') && \ + rm -rf /debs /var/lib/apt/lists/* +RUN useradd -m -u 1000 door && mkdir -p /doors /node && chown door /node +COPY rundoor /usr/local/bin/rundoor +COPY dosemurc /home/door/.dosemurc +RUN chmod 755 /usr/local/bin/rundoor && chown door /home/door/.dosemurc +USER door +WORKDIR /home/door +ENTRYPOINT ["/usr/local/bin/rundoor"] diff --git a/doors/dosemu2/build.sh b/doors/dosemu2/build.sh new file mode 100755 index 0000000..7266f41 --- /dev/null +++ b/doors/dosemu2/build.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# build.sh NAME URL REF: clone a dosemu2 piece at REF and build its .debs +# into the current directory. +set -e +name=$1 url=$2 ref=${3:-HEAD} +if [ "$ref" = HEAD ]; then + git clone --depth 1 "$url" "$name" +else + git clone "$url" "$name" + git -C "$name" checkout "$ref" +fi +cd "$name" +debuild -i -us -uc -b diff --git a/doors/dosemu2/dosemurc b/doors/dosemu2/dosemurc new file mode 100644 index 0000000..da19f6e --- /dev/null +++ b/doors/dosemu2/dosemurc @@ -0,0 +1,7 @@ +# dosemu2 for doors: no sound, no mouse, no network, a dumb console (which +# the caller does not see: the door talks to COM1) +$_cpu_vm = "auto" +$_cpu_vm_dpmi = "auto" +$_sound = (off) +$_mouse_internal = (off) +$_hogthreshold = (1) diff --git a/doors/dosemu2/rundoor b/doors/dosemu2/rundoor new file mode 100755 index 0000000..f4c0500 --- /dev/null +++ b/doors/dosemu2/rundoor @@ -0,0 +1,41 @@ +#!/bin/sh +# rundoor DOSDIR COMMAND...: run a DOS door in dosemu2 with the caller's +# line (this program's standard input and output) on COM1, behind +# dosemu2's FOSSIL. +# +# D: is /doors, the doors (mount them there: -v /srv/doors:/doors) +# E: is /node, this node's drop files (-v /var/lib/bbs/doors/node1:/node) +# +# rundoor 'D:\LORD' 'LORD.EXE /PE:\' +# +# The door's screen (dosemu's console) goes to /node/dosemu.out, not to the +# caller: the caller sees only what the door sends to COM1. +set -eu + +if [ $# -lt 2 ]; then + echo "usage: rundoor DOSDIR COMMAND..." >&2 + exit 2 +fi +dir=$1 +shift +cmd=$* +sock=/tmp/com1.sock +rm -f "$sock" + +# the batch file the door runs from: the FOSSIL, the door's directory, the door +printf '@ECHO OFF\r\nFOSSIL\r\n%s\r\nCD %s\r\n%s\r\n' "${dir%%:*}:" "$dir" "$cmd" > /node/DOOR.BAT + +# COM1's other end: socat, which dosemu2 runs on the port's pty, joins it +# to this socket; the socat here joins the socket to the caller +socat -b 4096 UNIX-LISTEN:"$sock",unlink-early STDIO & +bridge=$! +trap 'kill $bridge 2>/dev/null; kill $dos 2>/dev/null' TERM INT HUP + +dosemu -n -f /home/door/.dosemurc \ + -I "serial { com 1 exec 'socat -b 4096 STDIO,raw,echo=0 UNIX-CONNECT:$sock' }" \ + -d /doors -d /node -q -E 'E:\DOOR.BAT' /node/dosemu.out 2>&1 & +dos=$! +status=0 +wait $dos || status=$? +kill $bridge 2>/dev/null || true +exit $status diff --git a/doors/dosemu2/testdoor/FOSDOOR.COM b/doors/dosemu2/testdoor/FOSDOOR.COM new file mode 100644 index 0000000000000000000000000000000000000000..6fbb654cba77059d1408e09ee11ee2418c28f110 GIT binary patch literal 358 zcmdnOVtDDSh;4{u3D2%4j9WO*D(+zPIjgwu2jh!93|)K;31{*ghqu7ikP}YixK+IDx{fF9H}|f7+MK^dgYqHQPQdrWc+J`z)DWI5TWv z0=dejuteS_utXZD{GAO~$*X{UflM#d7$ROsGJrJ6FucCLFNW!b2*Vaukn$Z2K!*oy zVFau-ns@)g|tgM&SN6jF*Z%TkN 0 { + out := buf[:n] + if utf8Term && d.Charset == CP437 { + conv = conv[:0] + for _, c := range out { + if c < 0x80 { + conv = append(conv, c) + } else { + conv = utf8.AppendRune(conv, charmap.CodePage437.DecodeByte(c)) + } + } + out = conv + } + if _, err := line.Write(out); err != nil { + return + } + } + if err != nil { + return + } + } + }() + + // the caller's input to the door + deadline := time.Now().Add(d.TimeLimit) + lastKey := time.Now() + buf := make([]byte, 1024) + var pending []byte // a UTF-8 character cut in two + lastCR := false + finished := false + for !finished { + select { + case err := <-exited: + res.ExitErr = err + finished = true + continue + default: + } + if d.TimeLimit > 0 && time.Now().After(deadline) { + res.TimeUp = true + stop() + break + } + if idle > 0 && time.Since(lastKey) > idle { + res.Idle = true + stop() + break + } + line.SetReadDeadline(time.Now().Add(500 * time.Millisecond)) + n, err := line.Read(buf) + if n > 0 { + lastKey = time.Now() + var out []byte + for _, c := range buf[:n] { + // a terminal's CR LF is the door's CR + if c == '\n' && lastCR { + lastCR = false + continue + } + lastCR = c == '\r' + out = append(out, c) + } + if utf8Term && d.Charset == CP437 { + out = toCP437(append(pending, out...), &pending) + } + if len(out) > 0 { + toDoor.Write(out) + } + } + if err != nil { + var ne interface{ Timeout() bool } + if errors.As(err, &ne) && ne.Timeout() { + continue + } + res.HungUp = true + stop() + break + } + } + line.SetReadDeadline(time.Time{}) + if !d.PTY { + toDoor.Close() // a pty's master is its output too: closed after + } + if !finished { + res.ExitErr = <-exited + } + // what it wrote last, unless something it left behind holds the pipe + select { + case <-outDone: + case <-time.After(2 * time.Second): + fromDoor.Close() + <-outDone + } + logf("door %s: ended (time up %v, hung up %v, idle %v, %v)", d.Name, res.TimeUp, res.HungUp, res.Idle, res.ExitErr) + return res, nil +} + +// toCP437 turns UTF-8 typed by the caller into CP437; an incomplete +// character at the end is kept in pending for the next read. +func toCP437(b []byte, pending *[]byte) []byte { + var out []byte + for len(b) > 0 { + r, size := utf8.DecodeRune(b) + if r == utf8.RuneError && size <= 1 { + if !utf8.FullRune(b) { + break + } + b = b[1:] + continue + } + b = b[size:] + if r < 0x80 { + out = append(out, byte(r)) + } else if c, ok := charmap.CodePage437.EncodeRune(r); ok { + out = append(out, c) + } + } + *pending = append((*pending)[:0], b...) + return out +} diff --git a/internal/door/door_test.go b/internal/door/door_test.go new file mode 100644 index 0000000..80f3593 --- /dev/null +++ b/internal/door/door_test.go @@ -0,0 +1,185 @@ +package door + +import ( + "bufio" + "io" + "net" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func info() *Info { + return &Info{Node: 3, UserID: 7, UserName: "Alice Smith", Location: "Zürich", Logins: 5, Posts: 2, + LastLogin: time.Date(2026, 10, 9, 18, 30, 0, 0, time.UTC), ANSI: true, Rows: 24, Cols: 80, + Baud: 38400, BBSName: "Test BBS", SysopName: "Sid Sysop", Now: time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)} +} + +func TestDropFiles(t *testing.T) { + dir := t.TempDir() + in := info() + in.TimeLeft = 30 * time.Minute + in.ComPort, in.CommType = 1, 1 + if err := WriteDropFiles(dir, in, DropFiles); err != nil { + t.Fatal(err) + } + read := func(name string) []string { + b, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(string(b), "\r\n") { + t.Errorf("%s: lines not CR LF", name) + } + return strings.Split(strings.TrimSuffix(string(b), "\r\n"), "\r\n") + } + ds := read("DOOR.SYS") + if len(ds) != 52 || ds[0] != "COM1:" || ds[3] != "3" || ds[9] != "Alice Smith" || ds[10] != "Z\x81rich" || + ds[17] != "1800" || ds[18] != "30" || ds[19] != "GR" || ds[25] != "7" || ds[34] != "Sid Sysop" { + t.Errorf("DOOR.SYS %q", ds) + } + di := read("DORINFO1.DEF") + if len(di) != 13 || di[0] != "Test BBS" || di[1] != "Sid" || di[2] != "Sysop" || di[3] != "COM1" || + di[6] != "Alice" || di[7] != "Smith" || di[9] != "1" || di[11] != "30" { + t.Errorf("DORINFO1.DEF %q", di) + } + d32 := read("DOOR32.SYS") + if len(d32) != 11 || d32[0] != "1" || d32[1] != "1" || d32[5] != "Alice Smith" || d32[8] != "30" || d32[10] != "3" { + t.Errorf("DOOR32.SYS %q", d32) + } + ch := read("CHAIN.TXT") + if len(ch) != 31 || ch[0] != "7" || ch[1] != "Alice Smith" || ch[15] != "1800.00" { + t.Errorf("CHAIN.TXT %q", ch) + } +} + +func TestSplit(t *testing.T) { + got, err := Split(`docker run -v {dir}:/node bbs 'CD \LORD' "LORD.EXE /P\"x\"" C:\DOORS`) + want := []string{"docker", "run", "-v", "{dir}:/node", "bbs", `CD \LORD`, `LORD.EXE /P"x"`, `C:\DOORS`} + if err != nil || strings.Join(got, "|") != strings.Join(want, "|") { + t.Fatalf("%q %v", got, err) + } + if _, err := Split(`a 'b`); err == nil { + t.Fatal("unclosed quote") + } +} + +// script is a door: a shell script. +func script(t *testing.T, body string) *Door { + t.Helper() + dir := t.TempDir() + p := filepath.Join(dir, "door.sh") + os.WriteFile(p, []byte("#!/bin/sh\n"+body), 0755) + return &Door{Name: "test", Command: []string{p}, Dir: filepath.Join(dir, "node{node}"), + DropFiles: []string{DoorSys}, Charset: CP437, TimeLimit: time.Minute, CommType: 1} +} + +// caller runs the door on a pipe, and gives the caller's end. +func caller(t *testing.T, d *Door, utf8 bool, idle time.Duration) (net.Conn, chan Result) { + ours, theirs := net.Pipe() + done := make(chan Result, 1) + go func() { + res, err := d.Run(ours, info(), utf8, idle, t.Logf) + if err != nil { + t.Error(err) + } + ours.Close() + done <- res + }() + return theirs, done +} + +func TestRun(t *testing.T) { + // it reads its drop file, prints CP437, echoes a line + d := script(t, `sed -n 10p DOOR.SYS | tr -d '\r' +printf 'caf\202\r\n' +read -r line +printf 'got:%s\r\n' "$line" | od -An -c | tr -s ' ' +exit 3 +`) + c, done := caller(t, d, true, 0) + r := bufio.NewReader(c) + if l, _ := r.ReadString('\n'); l != "Alice Smith\n" { + t.Errorf("%q", l) + } + if l, _ := r.ReadString('\n'); l != "café\r\n" { + t.Errorf("CP437 to UTF-8: %q", l) + } + c.Write([]byte("é\r\n")) // CR LF: the door gets CR only? sh reads to LF + c.Write([]byte("\n")) + rest, _ := io.ReadAll(r) + if !strings.Contains(string(rest), "g o t : 202 \\r") { + t.Errorf("UTF-8 to CP437: %q", rest) + } + res := <-done + if res.ExitErr == nil || res.TimeUp || res.HungUp { + t.Errorf("%+v", res) + } +} + +func TestTimeLimitAndHangup(t *testing.T) { + d := script(t, "trap '' HUP\nsleep 30\n") + d.TimeLimit = time.Second + _, done := caller(t, d, false, 0) + select { + case res := <-done: + if !res.TimeUp { + t.Errorf("%+v", res) + } + case <-time.After(15 * time.Second): + t.Fatal("the time limit did not end it") + } + + d = script(t, "sleep 30\n") + c, done := caller(t, d, false, 0) + time.Sleep(200 * time.Millisecond) + c.Close() + select { + case res := <-done: + if !res.HungUp { + t.Errorf("%+v", res) + } + case <-time.After(15 * time.Second): + t.Fatal("hanging up did not end it") + } + + d = script(t, "sleep 30\n") + _, done = caller(t, d, false, 300*time.Millisecond) + if res := <-done; !res.Idle { + t.Errorf("idle: %+v", res) + } +} + +func TestSingleAndCleanup(t *testing.T) { + d := script(t, "sleep 1\n") + d.Single = true + mark := filepath.Join(t.TempDir(), "cleaned") + d.Cleanup = []string{"touch", mark + "{node}"} + c, done := caller(t, d, false, 0) + defer c.Close() + time.Sleep(200 * time.Millisecond) + ours, _ := net.Pipe() + if _, err := d.Run(ours, info(), false, 0, t.Logf); err != ErrBusy { + t.Errorf("a second caller: %v", err) + } + <-done + if _, err := os.Stat(mark + "3"); err != nil { + t.Error("cleanup did not run") + } +} + +func TestPTY(t *testing.T) { + d := script(t, `tty; stty size; printf 'x\n'`) + d.PTY = true + c, done := caller(t, d, false, 0) + out, _ := io.ReadAll(c) + <-done + if !strings.Contains(string(out), "/dev/pts/") || !strings.Contains(string(out), "24 80") { + t.Errorf("%q", out) + } + if strings.Contains(string(out), "x\r\n") { + t.Errorf("output post-processed: %q", out) + } +} diff --git a/internal/door/dropfile.go b/internal/door/dropfile.go new file mode 100644 index 0000000..cffaa2a --- /dev/null +++ b/internal/door/dropfile.go @@ -0,0 +1,227 @@ +package door + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "golang.org/x/text/encoding/charmap" +) + +// Drop files a door may want, by name. +const ( + DoorSys = "door.sys" // GAP, PCBoard and most doors since + DorInfo = "dorinfo1.def" // RBBS, QuickBBS + Door32Sys = "door32.sys" // Door32: newer doors, socket or FOSSIL + ChainTxt = "chain.txt" // WWIV + DropDefault = "door.sys dorinfo1.def door32.sys chain.txt" +) + +// DropFiles are those the BBS writes. +var DropFiles = []string{DoorSys, DorInfo, Door32Sys, ChainTxt} + +// Info is what drop files say of the caller and the system. +type Info struct { + Node int + UserID int64 + UserName string + Location string + Sysop bool + Logins int + Posts int + LastLogin time.Time + ANSI bool + Rows, Cols int + Baud int // the caller's line; 38400 for a network caller + TimeLeft time.Duration + BBSName string + SysopName string + ComPort int // the door's COM port: 1 + CommType int // DOOR32.SYS: 0 local, 1 serial (FOSSIL), 2 telnet + Now time.Time +} + +// security is the level drop files give: 255 for sysops, 30 for others. +func (in *Info) security() int { + if in.Sysop { + return 255 + } + return 30 +} + +// names splits a name into first and last, as DORINFO wants. +func names(n string) (string, string) { + f := strings.Fields(n) + switch len(f) { + case 0: + return "Unknown", "User" + case 1: + return f[0], "" + } + return f[0], strings.Join(f[1:], " ") +} + +func yn(b bool) string { + if b { + return "Y" + } + return "N" +} + +func onezero(b bool) string { + if b { + return "1" + } + return "0" +} + +// cp437 is a line as DOS doors read it: CP437, no line breaks. +func cp437(s string) string { + var b strings.Builder + for _, r := range s { + if r < 0x20 || r == 0x7f { + continue + } + if c, ok := charmap.CodePage437.EncodeRune(r); ok { + b.WriteByte(c) + } else { + b.WriteByte('?') + } + } + return b.String() +} + +func (in *Info) doorSys() []string { + ansi := "NG" + if in.ANSI { + ansi = "GR" + } + secs := int(in.TimeLeft / time.Second) + last := in.LastLogin + if last.IsZero() { + last = in.Now + } + return []string{ + fmt.Sprintf("COM%d:", in.ComPort), // 1 the port + fmt.Sprint(in.Baud), // 2 the caller's rate + "8", // 3 data bits + fmt.Sprint(in.Node), // 4 node + fmt.Sprint(in.Baud), // 5 the port's rate + "Y", "N", "Y", "Y", // 6-9 screen, printer, page bell, caller alarm + in.UserName, // 10 name + in.Location, // 11 calling from + "000-000-0000", "000-000-0000", // 12-13 phones + "", // 14 password: not given + fmt.Sprint(in.security()), // 15 security level + fmt.Sprint(in.Logins), // 16 times on + last.Format("01/02/06"), // 17 last call + fmt.Sprint(secs), // 18 seconds left + fmt.Sprint(secs / 60), // 19 minutes left + ansi, // 20 graphics + fmt.Sprint(in.Rows), // 21 screen length + "Y", // 22 expert + "", "1", // 23-24 conferences + "12/31/99", // 25 expiration + fmt.Sprint(in.UserID), // 26 record number + "Z", // 27 protocol + "0", "0", "0", "9999", // 28-31 uploads, downloads, K today, K a day + "01/01/80", // 32 birthday + `C:\`, `C:\`, // 33-34 main and gen dirs + in.SysopName, // 35 sysop + in.UserName, // 36 alias + "00:00", // 37 event + "Y", "N", "Y", // 38-40 error correcting, ANSI in NG, record locking + "7", "0", // 41-42 color, time credits + last.Format("01/02/06"), // 43 last new files scan + in.Now.Format("15:04"), // 44 this call + last.Format("15:04"), // 45 last call + "9999", "0", "0", "0", // 46-49 files a day, today, K up, K down + "", // 50 comment + "0", // 51 doors opened + fmt.Sprint(in.Posts), // 52 messages left + } +} + +func (in *Info) dorInfo() []string { + sf, sl := names(in.SysopName) + uf, ul := names(in.UserName) + return []string{ + in.BBSName, sf, sl, + fmt.Sprintf("COM%d", in.ComPort), + fmt.Sprintf("%d BAUD,N,8,1", in.Baud), + "0", uf, ul, in.Location, + onezero(in.ANSI), + fmt.Sprint(in.security()), + fmt.Sprint(int(in.TimeLeft / time.Minute)), + "-1", // a FOSSIL + } +} + +func (in *Info) door32Sys() []string { + emu := "0" + if in.ANSI { + emu = "1" + } + return []string{ + fmt.Sprint(in.CommType), + fmt.Sprint(in.ComPort), // the handle: for a FOSSIL, the port + fmt.Sprint(in.Baud), + "bbs-sec", + fmt.Sprint(in.UserID), + in.UserName, in.UserName, + fmt.Sprint(in.security()), + fmt.Sprint(int(in.TimeLeft / time.Minute)), + emu, + fmt.Sprint(in.Node), + } +} + +func (in *Info) chainTxt() []string { + secs := int(in.TimeLeft / time.Second) + midnight := time.Date(in.Now.Year(), in.Now.Month(), in.Now.Day(), 0, 0, 0, 0, in.Now.Location()) + return []string{ + fmt.Sprint(in.UserID), in.UserName, in.UserName, "", "21", "M", "0", + in.LastLogin.Format("01/02/06"), + fmt.Sprint(in.Cols), fmt.Sprint(in.Rows), + fmt.Sprint(in.security()), + onezero(in.Sysop), onezero(in.Sysop), onezero(in.ANSI), "1", + fmt.Sprintf("%d.00", secs), + `C:\`, `C:\`, "BBS.LOG", + fmt.Sprint(in.Baud), fmt.Sprint(in.ComPort), + in.BBSName, in.SysopName, + fmt.Sprint(int(in.Now.Sub(midnight) / time.Second)), + "0", "0", "0", "0", "0", "8N1", + fmt.Sprint(in.Baud), + } +} + +// WriteDropFiles writes the drop files named (DOS style: upper case +// names, CP437, CR LF) into dir. +func WriteDropFiles(dir string, in *Info, which []string) error { + for _, name := range which { + var lines []string + switch strings.ToLower(name) { + case DoorSys: + lines = in.doorSys() + case DorInfo: + lines = in.dorInfo() + case Door32Sys: + lines = in.door32Sys() + case ChainTxt: + lines = in.chainTxt() + default: + return fmt.Errorf("no such drop file: %s", name) + } + var b bytes.Buffer + for _, l := range lines { + b.WriteString(cp437(l) + "\r\n") + } + if err := os.WriteFile(filepath.Join(dir, strings.ToUpper(name)), b.Bytes(), 0644); err != nil { + return err + } + } + return nil +} diff --git a/internal/door/pty.go b/internal/door/pty.go new file mode 100644 index 0000000..377a36b --- /dev/null +++ b/internal/door/pty.go @@ -0,0 +1,47 @@ +package door + +import ( + "fmt" + "os" + "strconv" + + "golang.org/x/sys/unix" +) + +// openPTY opens a pseudo-terminal of the given size: its master, and its +// slave for the door. +func openPTY(rows, cols int) (*os.File, *os.File, error) { + m, err := os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) + if err != nil { + return nil, nil, err + } + fd := int(m.Fd()) + if err := unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil { + m.Close() + return nil, nil, fmt.Errorf("unlockpt: %w", err) + } + n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN) + if err != nil { + m.Close() + return nil, nil, fmt.Errorf("ptsname: %w", err) + } + s, err := os.OpenFile("/dev/pts/"+strconv.Itoa(n), os.O_RDWR|unix.O_NOCTTY, 0) + if err != nil { + m.Close() + return nil, nil, err + } + if rows > 0 && cols > 0 { + unix.IoctlSetWinsize(int(s.Fd()), unix.TIOCSWINSZ, &unix.Winsize{Row: uint16(rows), Col: uint16(cols)}) + } + // raw: the door's bytes as they are, both ways + if t, err := unix.IoctlGetTermios(int(s.Fd()), unix.TCGETS); err == nil { + t.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON + t.Oflag &^= unix.OPOST + t.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN + t.Cflag &^= unix.CSIZE | unix.PARENB + t.Cflag |= unix.CS8 + t.Cc[unix.VMIN], t.Cc[unix.VTIME] = 1, 0 + unix.IoctlSetTermios(int(s.Fd()), unix.TCSETS, t) + } + return m, s, nil +} diff --git a/internal/server/config.go b/internal/server/config.go index 49d6886..2ed704e 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -11,6 +11,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/config" + "github.com/Neo-Desktop/bbs-sec/internal/door" "github.com/Neo-Desktop/bbs-sec/internal/fido" "github.com/Neo-Desktop/bbs-sec/internal/ftp" "github.com/Neo-Desktop/bbs-sec/internal/logo" @@ -36,6 +37,7 @@ type Config struct { Peers []*nntp.Peer Fido *fido.Settings // nil: not on FidoNet Binkp *BinkpSettings // nil: no binkp answering + Doors []*door.Door Database string Log string // syslog, stderr, none, or a file Listeners []*Listener @@ -76,6 +78,9 @@ func Load(path string) (*Config, error) { if err := c.fidoSections(cf); err != nil { return nil, err } + if err := c.doorSections(cf); err != nil { + return nil, err + } if err := c.ftpSection(cf.Get("ftp", "")); err != nil { return nil, fmt.Errorf("[ftp] %w", err) } @@ -100,7 +105,7 @@ func Load(path string) (*Config, error) { } for _, s := range cf.Sections { switch s.Kind { - case "general", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link": + case "general", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link", "door": default: return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind) } diff --git a/internal/server/doorconfig.go b/internal/server/doorconfig.go new file mode 100644 index 0000000..208b79b --- /dev/null +++ b/internal/server/doorconfig.go @@ -0,0 +1,92 @@ +package server + +import ( + "errors" + "fmt" + "path/filepath" + "strings" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/config" + "github.com/Neo-Desktop/bbs-sec/internal/door" +) + +// doorSections reads the [door NAME]s. +func (c *Config) doorSections(cf *config.File) error { + names := map[string]bool{} + for _, s := range cf.All("door") { + d, err := doorSection(s) + if err != nil { + return fmt.Errorf("[door %s] %w", s.Name, err) + } + if names[strings.ToLower(d.Name)] { + return fmt.Errorf("[door %s] given twice", d.Name) + } + names[strings.ToLower(d.Name)] = true + c.Doors = append(c.Doors, d) + } + return nil +} + +func doorSection(s *config.Section) (*door.Door, error) { + if s.Name == "" { + return nil, errors.New("a door needs a name: [door NAME]") + } + d := &door.Door{Name: s.Name, Description: s.String("description", "")} + var err error + if d.Command, err = door.Split(s.String("command", "")); err != nil { + return nil, fmt.Errorf("command: %w", err) + } + if len(d.Command) == 0 { + return nil, errors.New("command: none given") + } + d.Dir = s.String("dir", filepath.Join("doors", "node{node}")) + if !strings.Contains(d.Dir, "{node}") { + return nil, errors.New("dir: must have {node} in it: each node its own drop files") + } + d.DropFiles = strings.Fields(strings.ToLower(strings.ReplaceAll(s.String("drop_files", door.DropDefault), ",", " "))) + for _, f := range d.DropFiles { + ok := false + for _, k := range door.DropFiles { + ok = ok || f == k + } + if !ok { + return nil, fmt.Errorf("drop_files: %q is not one of %s", f, strings.Join(door.DropFiles, ", ")) + } + } + switch d.Charset = strings.ToLower(s.String("charset", door.CP437)); d.Charset { + case door.CP437, door.UTF8, door.Raw: + case "utf8": + d.Charset = door.UTF8 + default: + return nil, fmt.Errorf("charset: %q is not cp437, utf-8 or raw", d.Charset) + } + mins, err := s.Int("time_limit", 60, 1, 24*60) + if err != nil { + return nil, err + } + d.TimeLimit = time.Duration(mins) * time.Minute + if d.SysopOnly, err = s.Bool("sysop_only", false); err != nil { + return nil, err + } + if d.Single, err = s.Bool("single", false); err != nil { + return nil, err + } + if d.PTY, err = s.Bool("pty", false); err != nil { + return nil, err + } + if d.Cleanup, err = door.Split(s.String("cleanup", "")); err != nil { + return nil, fmt.Errorf("cleanup: %w", err) + } + switch ct := strings.ToLower(s.String("door32_comm", "serial")); ct { + case "serial": + d.CommType = 1 + case "telnet": + d.CommType = 2 + case "local": + d.CommType = 0 + default: + return nil, fmt.Errorf("door32_comm: %q is not serial, telnet or local", ct) + } + return d, nil +} diff --git a/internal/server/doorconfig_test.go b/internal/server/doorconfig_test.go new file mode 100644 index 0000000..7001fb3 --- /dev/null +++ b/internal/server/doorconfig_test.go @@ -0,0 +1,94 @@ +package server + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/door" +) + +func TestDoorConfig(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) + } + c, err := load(` +[door lord] +description = Legend of the Red Dragon +command = docker run --rm -i -v /srv/doors:/doors -v {dir}:/node bbs-dosemu2 'D:\LORD' 'LORD.EXE /PE:\' +dir = /var/lib/bbs/doors/node{node} +drop_files = door.sys +time_limit = 30 +single = yes +cleanup = docker rm -f door-{node} +[door native] +command = /usr/games/adventure +charset = utf-8 +pty = yes +door32_comm = local +`) + if err != nil { + t.Fatal(err) + } + if len(c.Doors) != 2 { + t.Fatal(c.Doors) + } + l := c.Doors[0] + if l.Command[len(l.Command)-2] != `D:\LORD` || l.Command[len(l.Command)-1] != `LORD.EXE /PE:\` || + l.TimeLimit != 30*time.Minute || !l.Single || l.Charset != "cp437" || len(l.DropFiles) != 1 || + l.CommType != 1 || strings.Join(l.Cleanup, " ") != "docker rm -f door-{node}" { + t.Fatalf("%+v", l) + } + n := c.Doors[1] + if !n.PTY || n.Charset != "utf-8" || n.CommType != 0 || len(n.DropFiles) != 4 || n.Dir != "doors/node{node}" { + t.Fatalf("%+v", n) + } + for body, want := range map[string]string{ + "[door x]\n": "command", + "[door x]\ncommand = a 'b\n": "quote", + "[door x]\ncommand = a\ndir = /tmp/x\n": "{node}", + "[door x]\ncommand = a\ndrop_files = pcb.sys\n": "drop_files", + "[door x]\ncommand = a\ncharset = koi8\n": "charset", + "[door x]\ncommand = a\n[door X]\ncommand = b\n": "twice", + } { + if _, err := load(body); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: %v, want %q", body, err, want) + } + } +} + +// TestDoorSession: a caller opens a door from the menu, plays, and comes +// back to the BBS. +func TestDoorSession(t *testing.T) { + e := start(t, nil, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"}) + sh := filepath.Join(e.dir, "door.sh") + os.WriteFile(sh, []byte("#!/bin/sh\nprintf 'In the door, %s\\r\\n' \"$(sed -n 10p DOOR.SYS | tr -d '\\r')\"\n"+ + "read -r k\nprintf 'Bye from the door\\r\\n'\n"), 0755) + e.b.Doors = []*door.Door{{Name: "Test door", Description: "A script", Command: []string{sh}, + Dir: filepath.Join(e.dir, "node{node}"), DropFiles: door.DropFiles, Charset: door.CP437, + TimeLimit: time.Minute, CommType: 1}, + {Name: "Sysop door", Command: []string{"true"}, Dir: e.dir + "/{node}", SysopOnly: true}} + d := e.dial("modem.sock") + d.expect("Name (or NEW): ") + d.send("alice\r") + d.expect("Password: ") + d.send("alicepass1\r") + d.expect("[D] Doors") + d.expect("Command: ") + d.send("D") + d.expect("1 Test door") + d.expect("Door number (Enter to go back): ") + d.send("2\r") + d.expect("No such door.") // the sysop's is not shown to alice + d.expect("Door number (Enter to go back): ") + d.send("1\r") + d.expect("In the door, alice") + d.send("x\n") // a CR LF would be a CR, as DOS doors want: sh wants LF + d.expect("Bye from the door") + d.expect("Back on ") + d.expect("Door number (Enter to go back): ") +} diff --git a/internal/textui/doors.go b/internal/textui/doors.go new file mode 100644 index 0000000..5a484a1 --- /dev/null +++ b/internal/textui/doors.go @@ -0,0 +1,110 @@ +package textui + +import ( + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/door" +) + +// doorsFor are the doors a user may open. +func (s *session) doorsFor() []*door.Door { + var out []*door.Door + for _, d := range s.b.Doors { + if !d.SysopOnly || s.user.Sysop { + out = append(out, d) + } + } + return out +} + +// baud is the caller's line rate as drop files want it: a modem's, or +// 38400 for the network. +func baud(c *bbs.Caller) int { + if c != nil { + f := strings.FieldsFunc(c.Rate, func(r rune) bool { return r < '0' || r > '9' }) + if len(f) > 0 { + if n, err := strconv.Atoi(f[0]); err == nil && n >= 300 && n <= 115200 { + return n + } + } + } + return 38400 +} + +// doors: the list of doors, and into one +func (s *session) doors() error { + t := s.t + for { + s.n.Doing("Doors") + ds := s.doorsFor() + t.Println("") + t.Println(t.C(Cyan, "Doors")) + for i, d := range ds { + t.Printf(" %s %s %s\n", t.C(Yellow, fmt.Sprintf("%2d", i+1)), bbs.Fit(d.Name, 20), t.C(Dim, d.Description)) + } + if len(ds) == 0 { + t.Println(" (none)") + } + num, err := t.Input("\nDoor number (Enter to go back): ", 3) + if err != nil || num == "" { + return err + } + i, err := strconv.Atoi(num) + if err != nil || i < 1 || i > len(ds) { + t.Println("No such door.") + continue + } + if err := s.openDoor(ds[i-1]); err != nil { + return err + } + } +} + +func (s *session) openDoor(d *door.Door) error { + t := s.t + u := s.n.Refresh() + t.Println(t.C(Green, fmt.Sprintf("Opening %s (%d minutes)...", d.Name, int(d.TimeLimit/time.Minute)))) + port, err := t.Port() + if err != nil { + return err + } + in := &door.Info{Node: s.n.Num, UserID: u.ID, UserName: u.Name, Location: u.Location, + Sysop: u.Sysop, Logins: u.Logins, Posts: u.Posts, LastLogin: u.LastLogin, + ANSI: t.ANSI, Rows: t.Rows, Cols: t.Cols, Baud: baud(s.c), + BBSName: s.b.Name, SysopName: s.b.Sysop} + s.n.Doing("In " + d.Name) + s.b.Log.Printf("node %d: %s opened door %s", s.n.Num, u.Name, d.Name) + res, err := d.Run(port, in, t.UTF8, t.Idle, func(f string, a ...any) { + s.b.Log.Printf("node %d: "+f, append([]any{s.n.Num}, a...)...) + }) + if errors.Is(err, door.ErrBusy) { + t.Println(t.C(Red, err.Error()+".")) + return nil + } + if err != nil { + s.b.Log.Printf("node %d: door %s: %v", s.n.Num, d.Name, err) + t.Println(t.C(Red, "The door would not open.")) + return nil + } + if res.HungUp { + return errHangup + } + if res.Idle { + return ErrIdle + } + t.Settle(300 * time.Millisecond) + if t.ANSI { + t.Print("\x1b[0m") + } + t.Println("") + if res.TimeUp { + t.Println(t.C(Red, "Your time in "+d.Name+" is up.")) + } + t.Println(t.C(Green, "Back on "+s.b.Name+".")) + return nil +} diff --git a/internal/textui/ui.go b/internal/textui/ui.go index bf0a316..9803bd2 100644 --- a/internal/textui/ui.go +++ b/internal/textui/ui.go @@ -236,13 +236,18 @@ func (s *session) mainMenu() error { item := func(k, label string) string { return t.C(Yellow, "["+k+"]") + " " + bbs.Fit(label, 22) } - t.Println(" " + item("M", "Message areas") + item("E", mail)) - t.Println(" " + item("W", "Who's online") + item("U", "User list")) - t.Println(" " + item("P", "Your profile") + item("I", "System info")) + items := []string{item("M", "Message areas"), item("E", mail), + item("W", "Who's online"), item("U", "User list"), + item("P", "Your profile"), item("I", "System info")} if s.b.Files != nil { - t.Println(" " + item("F", "File areas") + item("G", "Goodbye")) - } else { - t.Println(" " + item("G", "Goodbye")) + items = append(items, item("F", "File areas")) + } + if len(s.doorsFor()) > 0 { + items = append(items, item("D", "Doors")) + } + items = append(items, item("G", "Goodbye")) + for i := 0; i < len(items); i += 2 { + t.Println(" " + strings.Join(items[i:min(i+2, len(items))], "")) } t.Print("\nCommand: ") k, err := t.Key() @@ -265,6 +270,10 @@ func (s *session) mainMenu() error { if s.b.Files != nil { err = s.fileAreas() } + case 'D': + if len(s.doorsFor()) > 0 { + err = s.doors() + } case 'U': err = s.users() case 'P':