From cfbb4be66e3511fb35a122dcd44ce45d97ba94cf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 10:52:08 +0000 Subject: [PATCH] Line speeds: telnet, SSH and web callers may have the BBS send at a modem's speed A caller without a modem's line picks a speed from 300 to 115200 bit/s (or full) on the profile (B) or with Ctrl-B at any prompt, and it is kept with their account. What the BBS sends goes at that pace, ten bits a character, ANSI art drawn as it was; doors are told the speed and paced too. Keys come in at once, and file transfers go at the line's own speed so their protocols do not time out. Modem callers (and calls a modem server reports a rate for) are never slowed again. [general] line_speeds (may callers pick), line_speed (what they get until they do) and line_speed_ask (asked at each login) are on bbs config's Connections page; the sysop can set a user's speed on their account page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRUrCtqbnHANimX37GK --- README.md | 2 +- bbs.conf.sample | 10 ++ docs/wiki/Configuration-Reference.md | 3 + internal/bbs/bbs.go | 9 ++ internal/bbs/prefs.go | 10 ++ internal/bbs/speed.go | 78 ++++++++++ internal/bbs/speed_test.go | 39 +++++ internal/confedit/catalog.go | 1 + internal/confui/fields.go | 11 +- internal/confui/menus.go | 2 + internal/confui/users.go | 46 +++++- internal/server/config.go | 22 +++ internal/server/speed_test.go | 96 +++++++++++++ internal/textui/doors.go | 13 +- internal/textui/frontend.go | 31 +++- internal/textui/speed.go | 203 +++++++++++++++++++++++++++ internal/textui/speed_test.go | 41 ++++++ internal/textui/term.go | 44 +++++- internal/textui/ui.go | 5 + 19 files changed, 649 insertions(+), 17 deletions(-) create mode 100644 internal/bbs/speed.go create mode 100644 internal/bbs/speed_test.go create mode 100644 internal/server/speed_test.go create mode 100644 internal/textui/speed.go create mode 100644 internal/textui/speed_test.go diff --git a/README.md b/README.md index 1b98f54..d16dfb1 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Main menu - 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 (and linking into an IRC network as a TS6 or P10 hub server), AIM and ICQ, MSN Messenger, Yahoo! Messenger, and MRC -- Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics +- Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics, and for telnet, SSH and web callers a modem's line speed (300 to 115200 bit/s) if they like - 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 - Certificates: its own ACME client gets and renews them from Let's Encrypt, ZeroSSL and others, for every TLS server diff --git a/bbs.conf.sample b/bbs.conf.sample index a62c885..7b11160 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -92,6 +92,16 @@ idle_timeout = 600 ; not throttled: one would lock out all throttle_failures = 10 throttle_time = 600 +; line speeds: callers by telnet, SSH or the web (not modem callers, +; whose line has a speed of its own) may have the BBS send to them at a +; modem's speed, 300 to 115200 bit/s, ANSI art drawn as it was. Each +; picks theirs on the profile (B), or with Ctrl-B at any prompt; it is +; kept with their account. line_speeds = no: none may. line_speed: what +; callers get until they pick (off: full speed). line_speed_ask = yes: +; asked at each login +line_speeds = yes +line_speed = off +line_speed_ask = no ; where callers are. geoip: a country database, a MaxMind DB (.mmdb: ; GeoLite2 Country, DB-IP Lite...) or a CSV of ranges, read again when it ; changes; with it the log, who's online and the web forum's flags give diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 1944b43..8efef86 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -101,6 +101,9 @@ The system: its name, database, log, logins, and what callers see. | `idle_timeout` | | yes | seconds to log in, and for a key once logged in. Examples: `600`. | | `throttle_failures` | | yes | this many failed logins (or new accounts) from one IP address or caller ID within throttle_time seconds turn it away until they age out (0: never). Callers with neither (a modem server's, no caller ID) are not throttled: one would lock out all. Examples: `10`. | | `throttle_time` | | yes | this many failed logins (or new accounts) from one IP address or caller ID within throttle_time seconds turn it away until they age out (0: never). Callers with neither (a modem server's, no caller ID) are not throttled: one would lock out all. Examples: `600`. | +| `line_speeds` | | yes | line speeds: callers by telnet, SSH or the web (not modem callers, whose line has a speed of its own) may have the BBS send to them at a modem's speed, 300 to 115200 bit/s, ANSI art drawn as it was. Each picks theirs on the profile (B), or with Ctrl-B at any prompt; it is kept with their account. line_speeds = no: none may. line_speed: what callers get until they pick (off: full speed). line_speed_ask = yes: asked at each login. Examples: `yes`. | +| `line_speed` | | yes | line speeds: callers by telnet, SSH or the web (not modem callers, whose line has a speed of its own) may have the BBS send to them at a modem's speed, 300 to 115200 bit/s, ANSI art drawn as it was. Each picks theirs on the profile (B), or with Ctrl-B at any prompt; it is kept with their account. line_speeds = no: none may. line_speed: what callers get until they pick (off: full speed). line_speed_ask = yes: asked at each login. Examples: `off`. | +| `line_speed_ask` | | yes | line speeds: callers by telnet, SSH or the web (not modem callers, whose line has a speed of its own) may have the BBS send to them at a modem's speed, 300 to 115200 bit/s, ANSI art drawn as it was. Each picks theirs on the profile (B), or with Ctrl-B at any prompt; it is kept with their account. line_speeds = no: none may. line_speed: what callers get until they pick (off: full speed). line_speed_ask = yes: asked at each login. Examples: `no`. | | `geoip` | | yes | where callers are. geoip: a country database, a MaxMind DB (.mmdb: GeoLite2 Country, DB-IP Lite...) or a CSV of ranges, read again when it changes; with it the log, who's online and the web forum's flags give callers' countries. A city database (GeoLite2 City, DB-IP City Lite, IP2Location DB3 and up) gives the log and the sysop their region and city too (some 120 MB of memory). geoip_credit: the credit its licence asks for, at the foot of the pages that show it. See docs/wiki/Modem-Callers.md. Examples: `/var/lib/bbs/dbip-country-lite.mmdb`, `/var/lib/bbs/dbip-city-lite.mmdb`. | | `geoip_credit` | | yes | where callers are. geoip: a country database, a MaxMind DB (.mmdb: GeoLite2 Country, DB-IP Lite...) or a CSV of ranges, read again when it changes; with it the log, who's online and the web forum's flags give callers' countries. A city database (GeoLite2 City, DB-IP City Lite, IP2Location DB3 and up) gives the log and the sysop their region and city too (some 120 MB of memory). geoip_credit: the credit its licence asks for, at the foot of the pages that show it. See docs/wiki/Modem-Callers.md. Examples: `IP geolocation by DB-IP`. | | `geoip_credit_url` | | yes | where callers are. geoip: a country database, a MaxMind DB (.mmdb: GeoLite2 Country, DB-IP Lite...) or a CSV of ranges, read again when it changes; with it the log, who's online and the web forum's flags give callers' countries. A city database (GeoLite2 City, DB-IP City Lite, IP2Location DB3 and up) gives the log and the sysop their region and city too (some 120 MB of memory). geoip_credit: the credit its licence asks for, at the foot of the pages that show it. See docs/wiki/Modem-Callers.md. Examples: `https://db-ip.com`. | diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index 6b9cac4..98d59ca 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -54,6 +54,14 @@ type Settings struct { GeoCreditURL string // and where it links PhoneCountry string // the country (ISO 3166) whose national caller IDs these are ("": none) + // Line speeds for callers without a modem's (telnet, SSH, the web): + // whether they may slow what the BBS sends them to a modem's speed, + // the speed they get until they choose (0: full speed), and whether + // they are asked at each login + LineSpeeds bool + LineSpeedDefault int + LineSpeedAsk bool + Backup BackupSettings // [backup] Levels []Level // [level N], by number @@ -86,6 +94,7 @@ func Defaults() Settings { IdleTimeout: 10 * time.Minute, ThrottleFails: 10, ThrottleTime: 10 * time.Minute, + LineSpeeds: true, } } diff --git a/internal/bbs/prefs.go b/internal/bbs/prefs.go index 786c752..d9d52c0 100644 --- a/internal/bbs/prefs.go +++ b/internal/bbs/prefs.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "sort" + "strconv" "strings" ) @@ -22,6 +23,7 @@ var prefValues = map[string][]string{ "width": {"40", "80"}, // a Commodore's columns "editor": {"full", "line"}, // the full-screen editor, or the line editor "expert": {"on", "off"}, // menus as their prompt alone (? for the rest) + "baud": nil, // the line speed (LineSpeeds, or off): lineSpeedValues // CompuServe Mail's options (SET at "Mail!"), kept when the caller says "cis-mailmode": {"menu", "prompt", "command"}, @@ -29,6 +31,14 @@ var prefValues = map[string][]string{ "cis-mailpage": {"on", "off"}, } +func init() { + vs := []string{"off"} + for _, s := range LineSpeeds { + vs = append(vs, strconv.Itoa(s)) + } + prefValues["baud"] = vs +} + // prefChecks are settings registered by a front end (RegisterPref), each // with what its values may be. var prefChecks = map[string]func(string) bool{} diff --git a/internal/bbs/speed.go b/internal/bbs/speed.go new file mode 100644 index 0000000..e6a61a2 --- /dev/null +++ b/internal/bbs/speed.go @@ -0,0 +1,78 @@ +package bbs + +import ( + "strconv" + "strings" +) + +// LineSpeeds are the speeds, in bit/s, a caller without a modem may have +// the BBS send at, as modems of the time did: 300 baud to a fast serial +// port. +var LineSpeeds = []int{300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 33600, 56000, 57600, 115200} + +// ValidLineSpeed is whether bps is one of LineSpeeds. +func ValidLineSpeed(bps int) bool { + for _, s := range LineSpeeds { + if s == bps { + return true + } + } + return false +} + +// ParseLineSpeed reads a line speed as a caller or the sysop writes it: +// "2400", "14.4k", "56k", or "off" (or "full", "0"): full speed. +func ParseLineSpeed(v string) (int, bool) { + v = strings.ToLower(strings.TrimSpace(v)) + v = strings.TrimSuffix(strings.TrimSuffix(v, "bps"), "bit/s") + v = strings.TrimSpace(v) + switch v { + case "off", "full", "0", "none", "": + return 0, true + } + mul := 1.0 + if strings.HasSuffix(v, "k") { + v, mul = strings.TrimSuffix(v, "k"), 1000 + } + f, err := strconv.ParseFloat(v, 64) + if err != nil { + return 0, false + } + bps := int(f*mul + 0.5) + // 56k is 56000, 14.4k 14400, 115.2k 115200 + if ValidLineSpeed(bps) { + return bps, true + } + return 0, false +} + +// LineSpeedName is a speed as callers know it: "2400", "14.4k", "full". +func LineSpeedName(bps int) string { + switch { + case bps <= 0: + return "full" + case bps < 10000: + return strconv.Itoa(bps) + case bps%1000 == 0: + return strconv.Itoa(bps/1000) + "k" + } + return strconv.FormatFloat(float64(bps)/1000, 'f', 1, 64) + "k" +} + +// HasLine is whether the caller came by a line of its own speed (a modem, +// or what a modem server said of the call): such a caller's speed is the +// line's, and the BBS does not slow it again. +func (c *Caller) HasLine() bool { + return c.Via == "modem" || c.Rate != "" +} + +// LineSpeed is the speed the user chose (0: full speed), and whether they +// chose one at all. +func (p Prefs) LineSpeed() (int, bool) { + v, ok := p["baud"] + if !ok { + return 0, false + } + bps, _ := ParseLineSpeed(v) + return bps, true +} diff --git a/internal/bbs/speed_test.go b/internal/bbs/speed_test.go new file mode 100644 index 0000000..1b59e31 --- /dev/null +++ b/internal/bbs/speed_test.go @@ -0,0 +1,39 @@ +package bbs + +import "testing" + +// TestLineSpeeds: speeds as callers write them, as they are shown, and +// kept as a setting. +func TestLineSpeeds(t *testing.T) { + for in, want := range map[string]int{"2400": 2400, "14.4k": 14400, "56K": 56000, "115.2k": 115200, + "off": 0, "full": 0, "33600 bps": 33600} { + if got, ok := ParseLineSpeed(in); !ok || got != want { + t.Errorf("%q: %d %v, want %d", in, got, ok, want) + } + } + for _, bad := range []string{"2401", "fast", "-300"} { + if _, ok := ParseLineSpeed(bad); ok { + t.Errorf("%q taken", bad) + } + } + for bps, want := range map[int]string{0: "full", 300: "300", 9600: "9600", 14400: "14.4k", 56000: "56k", 115200: "115.2k"} { + if got := LineSpeedName(bps); got != want { + t.Errorf("%d: %q, want %q", bps, got, want) + } + } + if err := CheckPref("baud", "2400"); err != nil { + t.Error(err) + } + if err := CheckPref("baud", "2401"); err == nil { + t.Error("baud=2401 taken") + } + if bps, ok := ParsePrefs("baud=1200 ansi=on").LineSpeed(); !ok || bps != 1200 { + t.Errorf("kept 1200: %d %v", bps, ok) + } + if _, ok := ParsePrefs("ansi=on").LineSpeed(); ok { + t.Error("a speed where none was chosen") + } + if !(&Caller{Via: "modem"}).HasLine() || !(&Caller{Via: "ssh", Rate: "26400/31200"}).HasLine() || (&Caller{Via: "ssh"}).HasLine() { + t.Error("HasLine") + } +} diff --git a/internal/confedit/catalog.go b/internal/confedit/catalog.go index b1d4855..026f94d 100644 --- a/internal/confedit/catalog.go +++ b/internal/confedit/catalog.go @@ -254,6 +254,7 @@ var liveKeys = map[string]map[string]bool{ "general": set("name", "sysop", "location", "postal_address", "phone", "addresses", "banner", "banner_file", "motd", "motd_file", "goodbye", "new_users", "max_nodes", "attempts", "fail_delay", "login_timeout", "idle_timeout", "throttle_failures", "throttle_time", "page_command", "qwk_id", + "line_speeds", "line_speed", "line_speed_ask", "geoip", "geoip_credit", "geoip_credit_url", "phone_country", "new_user_level", "validated_level"), "http": set("forum_guests", "forum_theme", "forum_flags"), diff --git a/internal/confui/fields.go b/internal/confui/fields.go index 3d4f470..0a83ecc 100644 --- a/internal/confui/fields.go +++ b/internal/confui/fields.go @@ -3,8 +3,10 @@ package confui import ( "fmt" "sort" + "strconv" "strings" + "github.com/D-Modem/bbs/internal/bbs" "github.com/D-Modem/bbs/internal/confedit" "github.com/D-Modem/bbs/internal/forum" "github.com/D-Modem/bbs/internal/view" @@ -49,6 +51,11 @@ func init() { themes = append(themes, t.Name) } choices["http.forum_theme"] = themes + speeds := []string{"off"} + for _, bps := range bbs.LineSpeeds { + speeds = append(speeds, strconv.Itoa(bps)) + } + choices["general.line_speed"] = speeds } // labels are keys' names as a sysop reads them, where the key's own is @@ -67,7 +74,9 @@ var labels = map[string]string{ "general.attempts": "Login attempts", "general.fail_delay": "Delay after a wrong one (s)", "general.login_timeout": "Time to log in (s)", "general.idle_timeout": "Idle time out (s)", "general.throttle_failures": "Failures before a lock-out", "general.throttle_time": "Within (s)", - "general.phone_country": "Caller ID country", "general.geoip": "GeoIP database", + "general.line_speeds": "Callers may pick a line speed", "general.line_speed": "Line speed until they pick", + "general.line_speed_ask": "Ask the speed at each login", + "general.phone_country": "Caller ID country", "general.geoip": "GeoIP database", "general.geoip_credit": "GeoIP credit", "general.geoip_credit_url": "GeoIP credit link", "general.new_user_level": "New users' level", "general.validated_level": "Validated users' level", "general.tn3270_symbols": "Programmed symbols (pictures, logo)", "general.tn3270_vector": "Vector graphics (pictures, logo)", diff --git a/internal/confui/menus.go b/internal/confui/menus.go index 5506e22..93b0ece 100644 --- a/internal/confui/menus.go +++ b/internal/confui/menus.go @@ -255,6 +255,8 @@ func (e *Editor) connectionsMenu() page { } out = append(out, e.fields(g, "max_nodes", "attempts", "fail_delay", "login_timeout", "idle_timeout", "throttle_failures", "throttle_time", "page_command")...) + out = append(out, heading("Line speeds (telnet, SSH and web callers)")) + out = append(out, e.fields(g, "line_speeds", "line_speed", "line_speed_ask")...) out = append(out, heading("Passwords by modemmenu (its auth socket)")) out = append(out, e.fields(sec("modemmenu"), "auth_socket", "create_users", "timeout")...) out = append(out, heading("Caller ID and where callers are")) diff --git a/internal/confui/users.go b/internal/confui/users.go index 94f0e35..d1d8d1d 100644 --- a/internal/confui/users.go +++ b/internal/confui/users.go @@ -109,6 +109,21 @@ func (d *data) ops() []op { out = append(out, op{fmt.Sprintf("user %s: locked %s", u.Name, yesno(u.Locked)), func() error { return st.SetLocked(u.ID, u.Locked) }}) } + if bbs.ParsePrefs(u.Prefs)["baud"] != bbs.ParsePrefs(w.Prefs)["baud"] { + out = append(out, op{fmt.Sprintf("user %s: line speed %s", u.Name, speedWords(u.Prefs)), + func() error { + // the line speed alone: the user may have changed the rest since + cur, err := st.UserByID(u.ID) + if err != nil { + return err + } + p, err := bbs.ChangePrefs(cur.Prefs, map[string]string{"baud": bbs.ParsePrefs(u.Prefs)["baud"]}) + if err != nil { + return err + } + return st.SetPrefs(u.ID, p) + }}) + } if pw, ok := d.passwords[u]; ok { out = append(out, op{"user " + u.Name + ": a new password", func() error { return st.SetPassword(u.ID, pw) }}) } @@ -334,9 +349,26 @@ func (e *Editor) userPage(u *store.User) page { d.passwords[u] = v return nil } + speeds := []string{""} + for _, bps := range bbs.LineSpeeds { + speeds = append(speeds, strconv.Itoa(bps)) + } + speeds = append(speeds, "off") + speed := item{Entry: view.Entry{ID: "baud", Kind: view.EntryChoice, Label: "Line speed (bit/s)", + Value: bbs.ParsePrefs(u.Prefs)["baud"], Default: "as [general] line_speed", Choices: speeds, + Changed: bbs.ParsePrefs(u.Prefs)["baud"] != bbs.ParsePrefs(w.Prefs)["baud"] && old, + Help: "What the BBS sends this user at by telnet, SSH or the web, as a modem would (off: full speed). They can change it themselves."}} + speed.set = func(v string) error { + p, err := bbs.ChangePrefs(u.Prefs, map[string]string{"baud": v}) + if err != nil { + return err + } + u.Prefs = p + return nil + } out := []item{ {Entry: view.Entry{Kind: view.EntryInfo, Label: "Name", Value: u.Name}}, - level, flags, + level, flags, speed, boolItem("sysop", "Sysop", &u.Sysop, w.Sysop, "The sysop's tools, and every area and door."), boolItem("locked", "Locked out", &u.Locked, w.Locked, "A locked account cannot log in."), pw, @@ -367,3 +399,15 @@ func (e *Editor) userPage(u *store.User) page { return out }} } + +// speedWords is the line speed kept in prefs, in words. +func speedWords(prefs string) string { + bps, ok := bbs.ParsePrefs(prefs).LineSpeed() + switch { + case !ok: + return "as the BBS's" + case bps == 0: + return "full" + } + return strconv.Itoa(bps) + " bit/s" +} diff --git a/internal/server/config.go b/internal/server/config.go index dc258ff..0e6f37d 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -340,6 +340,19 @@ func (c *Config) general(g *config.Section) error { if s.NewUsers, err = g.Bool("new_users", s.NewUsers); err != nil { return err } + if s.LineSpeeds, err = g.Bool("line_speeds", true); err != nil { + return err + } + if v := g.String("line_speed", "off"); v != "" { + bps, ok := bbs.ParseLineSpeed(v) + if !ok { + return fmt.Errorf("line_speed: %q is not one of off, %s", v, lineSpeedList()) + } + s.LineSpeedDefault = bps + } + if s.LineSpeedAsk, err = g.Bool("line_speed_ask", false); err != nil { + return err + } if c.Graphics.Symbols, err = g.Bool("tn3270_symbols", true); err != nil { return err } @@ -674,3 +687,12 @@ func loopback(addr string) bool { ip := net.ParseIP(h) return ip != nil && ip.IsLoopback() } + +// lineSpeedList is the line speeds there are, for an error. +func lineSpeedList() string { + var out []string + for _, bps := range bbs.LineSpeeds { + out = append(out, strconv.Itoa(bps)) + } + return strings.Join(out, ", ") +} diff --git a/internal/server/speed_test.go b/internal/server/speed_test.go new file mode 100644 index 0000000..c70a1bc --- /dev/null +++ b/internal/server/speed_test.go @@ -0,0 +1,96 @@ +package server + +import ( + "strings" + "testing" + + "github.com/D-Modem/bbs/internal/bbs" + "golang.org/x/crypto/ssh" +) + +// TestLineSpeed: an SSH caller picks a line speed on the profile and with +// Ctrl-B; it is kept, and the next call begins at it. +func TestLineSpeed(t *testing.T) { + e, addr, _ := startSSH(t, nil) + call := func() *dialog { + c, err := sshDial(t, addr, "alice", ssh.Password("alicepass1")) + if err != nil { + t.Fatal(err) + } + d := shell(t, c, "xterm-256color", 100, 40) + d.expect("Command: ") + return d + } + prefs := func() string { + u, _ := e.b.Store.UserByName("alice") + return u.Prefs + } + d := call() + d.send("P") + d.expect("line speed full") + d.expect("[B]aud: line speed (or Ctrl-B)") + d.send("B") + d.expect("Which? ") + d.send("a") // 56k + d.expect("Now at 56000 bit/s.") + d.expect("line speed 56000 bit/s") + if p := prefs(); p != "baud=56000" { + t.Errorf("kept %q", p) + } + d.send("Q") + d.expect("Command: ") + + d = call() + d.send("P") + d.expect("line speed 56000 bit/s") + d.send("Q") + d.expect("Command: ") + d.send("\x02") + d.expect("Line speed\x1b[0m (now 56k):") + d.send("0") + d.expect("Full speed.") + d.expect("Command: ") // the prompt again + d.send("P") + d.expect("line speed full") + if p := prefs(); p != "baud=off" { + t.Errorf("kept %q", p) + } +} + +// TestLineSpeedOff: with line_speeds = no, nor the profile's B nor Ctrl-B +// is there, and a speed kept is not used. +func TestLineSpeedOff(t *testing.T) { + e, addr, _ := startSSH(t, func(s *bbs.Settings) { s.LineSpeeds = false }) + u, _ := e.b.Store.UserByName("alice") + if err := e.b.Store.SetPrefs(u.ID, "baud=300"); err != nil { + t.Fatal(err) + } + c, err := sshDial(t, addr, "alice", ssh.Password("alicepass1")) + if err != nil { + t.Fatal(err) + } + d := shell(t, c, "xterm-256color", 100, 40) + d.expect("Command: ") + d.send("\x02") + d.send("P") + d.expect("Terminal:") + d.expect("[Q]uit: ") + if strings.Contains(string(d.before), "ine speed") { + t.Errorf("line speeds offered: %q", d.before) + } +} + +// TestLineSpeedModem: a modem caller's line has its speed; none is offered. +func TestLineSpeedModem(t *testing.T) { + e := start(t, nil, &Listener{Name: "menu", Kind: "raw", Address: "menu.sock", ANSI: "no", + Header: true, TrustUser: true, CreateUsers: true}) + d := e.dial("menu.sock") + d.send("MODEM_USER=erin\nMODEM_AUTH=pam\nMODEM_RATE=26400/31200\n\n") + d.expect("Command: ") + d.send("P") + d.expect("Terminal:") + d.expect("[Q]uit: ") + if strings.Contains(string(d.before), "ine speed") { + t.Errorf("line speeds offered a modem caller: %q", d.before) + } +} diff --git a/internal/textui/doors.go b/internal/textui/doors.go index ff63f1c..f164c2f 100644 --- a/internal/textui/doors.go +++ b/internal/textui/doors.go @@ -49,13 +49,13 @@ func (s *session) OpenDoor(d *door.Door) error { limit = left } t.Println(t.C(Green, fmt.Sprintf("Opening %s (%d minutes)...", d.Name, int(limit/time.Minute)))) - port, err := t.Port() + port, err := t.DoorPort() 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), + ANSI: t.ANSI, Rows: t.Rows, Cols: t.Cols, Baud: s.doorBaud(), BBSName: s.b.Conf().Name, SysopName: s.b.Conf().Sysop, Level: u.Level} if left, ok := s.n.TimeLeft(); ok { in.TimeLeft = max(left, time.Minute) @@ -91,3 +91,12 @@ func (s *session) OpenDoor(d *door.Door) error { t.Println(t.C(Green, "Back on "+s.b.Conf().Name+".")) return nil } + +// doorBaud is the speed a door is told: the line speed the caller chose, +// or the modem's. +func (s *session) doorBaud() int { + if bps := s.t.LineSpeed(); bps > 0 { + return bps + } + return baud(s.c) +} diff --git a/internal/textui/frontend.go b/internal/textui/frontend.go index e7552b1..e5c4a93 100644 --- a/internal/textui/frontend.go +++ b/internal/textui/frontend.go @@ -24,11 +24,18 @@ func (s *session) TerminalInfo() error { // Terminal is the terminal's line on the profile. func (s *session) Terminal() string { t := s.t + speed := "" + if s.lineSpeeds() { + speed = ", line speed full" + if bps := t.LineSpeed(); bps > 0 { + speed = ", line speed " + strconv.Itoa(bps) + " bit/s" + } + } switch { case t.PETSCII: - return fmt.Sprintf("Commodore, %dx%d", t.Cols, t.Rows) + return fmt.Sprintf("Commodore, %dx%d%s", t.Cols, t.Rows, speed) case t.VT52: - return fmt.Sprintf("VT52, %dx%d", t.Cols, t.Rows) + return fmt.Sprintf("VT52, %dx%d%s", t.Cols, t.Rows, speed) } onOff := map[bool]string{true: "on", false: "off"} ident := "" @@ -45,18 +52,22 @@ func (s *session) Terminal() string { } pictures := map[string]string{picNone: "off", picKitty: "kitty", picSixel: "sixel", picITerm: "iTerm2", picBlocks: "blocks"}[t.PictureMode()] - return fmt.Sprintf("%s%dx%d, ANSI %s, UTF-8 %s%s, sixel %s, RIP %s%s, pictures %s", ident, t.Cols, t.Rows, - onOff[t.ANSI], onOff[t.UTF8], charset, onOff[t.Sixel], onOff[t.RIP], editor, pictures) + return fmt.Sprintf("%s%dx%d, ANSI %s, UTF-8 %s%s, sixel %s, RIP %s%s, pictures %s%s", ident, t.Cols, t.Rows, + onOff[t.ANSI], onOff[t.UTF8], charset, onOff[t.Sixel], onOff[t.RIP], editor, pictures, speed) } // TerminalActions are what the caller may switch on the profile. func (s *session) TerminalActions() []view.Action { + var speed []view.Action + if s.lineSpeeds() { + speed = []view.Action{{ID: "baud", Label: "Baud: line speed (or Ctrl-B)", Key: 'B'}} + } t := s.t switch { case t.PETSCII: - return []view.Action{{ID: "width", Label: "Width 40/80", Key: 'W'}} + return append([]view.Action{{ID: "width", Label: "Width 40/80", Key: 'W'}}, speed...) case t.VT52: - return nil + return speed } acts := []view.Action{{ID: "ansi", Label: "ANSI on/off", Key: 'A'}, {ID: "utf8", Label: "8-bit UTF-8 on/off", Key: '8'}, @@ -66,7 +77,7 @@ func (s *session) TerminalActions() []view.Action { if t.ANSI { acts = append(acts, view.Action{ID: "editor", Label: "Editor full/line", Key: 'E'}) } - return acts + return append(acts, speed...) } // applyPrefs treats the terminal as the user said to last time: ANSI and @@ -136,6 +147,12 @@ func (s *session) savePrefs(id string) error { // TerminalAction switches what was chosen, and keeps it for next time. func (s *session) TerminalAction(id string) error { + if id == "baud" { + if !s.lineSpeeds() { + return nil + } + return s.pickSpeed(false) + } if err := s.switchTerminal(id); err != nil { return err } diff --git a/internal/textui/speed.go b/internal/textui/speed.go new file mode 100644 index 0000000..7e7f405 --- /dev/null +++ b/internal/textui/speed.go @@ -0,0 +1,203 @@ +package textui + +import ( + "strconv" + "sync" + "time" + + "github.com/D-Modem/bbs/internal/bbs" +) + +// Line speeds: a caller by telnet, SSH or the web may have what the BBS +// sends come at a modem's speed, as it did when ANSI art was drawn a line +// at a time. Only what is sent is slowed: keys come in at once, and the +// BBS reads them as soon as it is done sending. + +// pacer is the line under a terminal, sending at most bps bits a second +// (8N1: ten bits a character); 0 is the line's own speed. +type pacer struct { + Conn + mu sync.Mutex + bps int + next time.Time // when the next byte may go + direct bool // a file transfer's bytes: at the line's own speed + sleep func(time.Duration) +} + +// pace is how far ahead of the line a write may get: the bytes of this +// long go in one write. +const pace = 20 * time.Millisecond + +// Write sends p at the speed set, a few bytes at a time. +func (p *pacer) Write(b []byte) (int, error) { + p.mu.Lock() + defer p.mu.Unlock() + if p.bps <= 0 || p.direct { + return p.Conn.Write(b) + } + // a byte is 10 bits; this many go in each pace + chunk := int(int64(p.bps) * int64(pace) / int64(10*time.Second)) + if chunk < 1 { + chunk = 1 + } + if now := time.Now(); p.next.Before(now) { + p.next = now // no credit for the time the line was quiet + } + sent := 0 + for sent < len(b) { + n := min(chunk, len(b)-sent) + if d := time.Until(p.next); d > 0 { + p.sleep(d) + } + m, err := p.Conn.Write(b[sent : sent+n]) + sent += m + if err != nil { + return sent, err + } + p.next = p.next.Add(time.Duration(n) * 10 * time.Second / time.Duration(p.bps)) + } + return sent, nil +} + +// setDirect has writes go at the line's own speed (on: a transfer +// protocol's packets, which would time out at a slow speed's pace). +func (p *pacer) setDirect(on bool) { + p.mu.Lock() + p.direct = on + p.mu.Unlock() +} + +// SetLineSpeed has what is sent go at bps bit/s from now on (0: as fast +// as the line goes). +func (t *Term) SetLineSpeed(bps int) { + t.Flush() + t.line.mu.Lock() + t.line.bps = bps + t.line.mu.Unlock() +} + +// LineSpeed is the speed what is sent goes at (0: the line's own). +func (t *Term) LineSpeed() int { + t.line.mu.Lock() + defer t.line.mu.Unlock() + return t.line.bps +} + +// lineSpeedKey is Ctrl-B: at any prompt, the line speed's picker. +const lineSpeedKey = 0x02 + +// speedKeys are the picker's keys: 0 full speed, then bbs.LineSpeeds. +const speedKeys = "0123456789ABCDEFGHIJ" + +// PickLineSpeed asks for a line speed, below the line being typed; +// restore: that line is drawn again after (a prompt Ctrl-B was pressed +// at). ok false if the caller pressed none of the speeds' keys. +func (t *Term) PickLineSpeed(restore bool) (bps int, ok bool, err error) { + cur := string(t.cur) + if cur != "" { + t.Print("\n") + } + t.Println(t.C(Cyan, "Line speed") + " (now " + bbs.LineSpeedName(t.LineSpeed()) + "):") + // the choices, as many to a line as fit + line, width := "", 0 + for i := 0; i <= len(bbs.LineSpeeds); i++ { + name := "full" + if i > 0 { + name = bbs.LineSpeedName(bbs.LineSpeeds[i-1]) + } + w := 2 + len(name) + 2 + if width > 0 && width+w > t.Cols-1 { + t.Println(line) + line, width = "", 0 + } + line += " " + t.C(White, speedKeys[i:i+1]) + " " + name + width += w + } + t.Println(line) + t.Print("Which? ") + t.picking = true + r, err := t.readRune() + t.picking = false + if err != nil { + return 0, false, err + } + if r >= 'a' && r <= 'z' { + r -= 'a' - 'A' + } + i := -1 + for j := 0; j <= len(bbs.LineSpeeds); j++ { + if rune(speedKeys[j]) == r { + i = j + } + } + if i < 0 { + t.Println("") + } else { + if i > 0 { + bps = bbs.LineSpeeds[i-1] + } + t.Println(speedKeys[i : i+1]) + if bps == 0 { + t.Println(t.C(Dim, "Full speed.")) + } else { + t.Println(t.C(Dim, "Now at "+strconv.Itoa(bps)+" bit/s.")) + } + t.SetLineSpeed(bps) + } + if restore { + t.Print(cur) + } + return bps, i >= 0, nil +} + +// lineSpeeds is whether this caller may pick a line speed: the sysop +// lets them, and they have no modem's line (whose speed is its own). +func (s *session) lineSpeeds() bool { + return s.b.Conf().LineSpeeds && !s.c.HasLine() +} + +// startLineSpeed is the speed from the connect, before the login: the +// sysop's line_speed, with Ctrl-B to change it. +func (s *session) startLineSpeed() { + if !s.lineSpeeds() { + return + } + s.t.SetLineSpeed(s.b.Conf().LineSpeedDefault) + s.t.OnLineSpeedKey = s.pickLineSpeed +} + +// applyLineSpeed is the speed the user chose last time once they are +// logged in, or asked now if the sysop says to. +func (s *session) applyLineSpeed() error { + if !s.lineSpeeds() { + return nil + } + if bps, ok := s.n.Prefs().LineSpeed(); ok { + s.t.SetLineSpeed(bps) + } + if !s.b.Conf().LineSpeedAsk { + return nil + } + return s.pickSpeed(false) +} + +// pickLineSpeed is the line speed's picker (Ctrl-B, the profile's B, the +// login's question); what is picked is kept for the next call. +func (s *session) pickLineSpeed() error { return s.pickSpeed(true) } + +// pickSpeed is pickLineSpeed; restore: the line being typed is drawn again +// after. +func (s *session) pickSpeed(restore bool) error { + bps, ok, err := s.t.PickLineSpeed(restore) + if err != nil || !ok { + return err + } + if s.n.User() == nil { + return nil // not logged in yet: for this call + } + v := "off" + if bps > 0 { + v = strconv.Itoa(bps) + } + return s.n.SetPref("baud", v) +} diff --git a/internal/textui/speed_test.go b/internal/textui/speed_test.go new file mode 100644 index 0000000..30326b5 --- /dev/null +++ b/internal/textui/speed_test.go @@ -0,0 +1,41 @@ +package textui + +import ( + "bytes" + "testing" + "time" +) + +// TestPacer: at a line speed, what is sent takes as long as at a modem's +// (ten bits a character); transfers' bytes and full speed do not wait. +func TestPacer(t *testing.T) { + c := &bufConn{} + term := NewTerm(c) + data := bytes.Repeat([]byte("x"), 480) + + timed := func() time.Duration { + start := time.Now() + term.Print(string(data)) + term.Flush() + return time.Since(start) + } + if d := timed(); d > 100*time.Millisecond { + t.Errorf("full speed took %v", d) + } + term.SetLineSpeed(9600) // 960 characters a second: half a second + if d := timed(); d < 400*time.Millisecond || d > 900*time.Millisecond { + t.Errorf("480 bytes at 9600 took %v, not about 500ms", d) + } + p, _ := term.Port() + start := time.Now() + p.Write(data) + if d := time.Since(start); d > 100*time.Millisecond { + t.Errorf("a transfer's bytes took %v", d) + } + if c.Len() != 3*len(data) { + t.Errorf("sent %d bytes, not %d", c.Len(), 3*len(data)) + } + if term.LineSpeed() != 9600 { + t.Errorf("speed %d", term.LineSpeed()) + } +} diff --git a/internal/textui/term.go b/internal/textui/term.go index a31baa0..0b5c25b 100644 --- a/internal/textui/term.go +++ b/internal/textui/term.go @@ -90,6 +90,12 @@ type Term struct { latin1 bool // a DEC terminal's 8-bit characters are Latin-1 sinceKey int // lines printed since a key was read ripScene bool // a RIP scene is on the screen + + // OnLineSpeedKey, if set, is called for Ctrl-B at a prompt: the line + // speed's picker (PickLineSpeed) + OnLineSpeedKey func() error + line *pacer // under echo: what is sent, at the line speed + picking bool // in PickLineSpeed: Ctrl-B is a key } // translator turns what the BBS writes (UTF-8, ANSI) into a terminal's. @@ -158,8 +164,9 @@ func (t *Term) Raw(b []byte) error { // NewTerm makes a terminal on c, 80x24 plain ASCII until told otherwise. func NewTerm(c Conn) *Term { - ec := &echoConn{Conn: c} - return &Term{c: ec, echo: ec, r: bufio.NewReaderSize(c, 1024), w: bufio.NewWriterSize(ec, 4096), + line := &pacer{Conn: c, sleep: time.Sleep} + ec := &echoConn{Conn: line} + return &Term{c: ec, echo: ec, line: line, r: bufio.NewReaderSize(c, 1024), w: bufio.NewWriterSize(ec, 4096), Cols: 80, Rows: 24, Idle: 10 * time.Minute} } @@ -420,6 +427,16 @@ func (t *Term) read(keys bool) (rune, error) { } continue } + if r == lineSpeedKey && t.OnLineSpeedKey != nil && !t.picking && !t.PETSCII { + if err := t.OnLineSpeedKey(); err != nil { + return 0, err + } + if err := t.Flush(); err != nil { + return 0, err + } + start = time.Now() + continue + } t.sinceKey = 0 return r, nil } @@ -1061,13 +1078,23 @@ func (t *Term) RIPClear() { // port is the terminal as a line for file transfers: the same buffered // reader (what was typed ahead is not lost), writes straight through. -type port struct{ t *Term } +type port struct { + t *Term + paced bool // at the line speed (a door's); else the line's own (a transfer's) +} // Read reads from the terminal's reader, what was typed ahead first. func (p port) Read(b []byte) (int, error) { return p.t.r.Read(b) } // Write writes b to the line as it is, past any translation. -func (p port) Write(b []byte) (int, error) { return p.t.c.Write(b) } +func (p port) Write(b []byte) (int, error) { + // the protocol's own timing: not slowed to the line speed + if !p.paced { + p.t.line.setDirect(true) + defer p.t.line.setDirect(false) + } + return p.t.c.Write(b) +} // SetReadDeadline sets the line's read deadline. func (p port) SetReadDeadline(d time.Time) error { return p.t.c.SetReadDeadline(d) } @@ -1077,7 +1104,14 @@ func (t *Term) Port() (port, error) { if err := t.Flush(); err != nil { return port{}, err } - return port{t}, nil + return port{t: t}, nil +} + +// DoorPort is Port for a door: what it sends comes at the line speed. +func (t *Term) DoorPort() (port, error) { + p, err := t.Port() + p.paced = true + return p, err } // Settle waits for the line to be quiet for d (the end of a transfer, a diff --git a/internal/textui/ui.go b/internal/textui/ui.go index 03c7c6a..022f43e 100644 --- a/internal/textui/ui.go +++ b/internal/textui/ui.go @@ -60,6 +60,8 @@ func (s *session) run() error { t := s.t t.Clear() t.PausePrompt = s.str("pause") + s.startLineSpeed() + defer func() { t.OnLineSpeedKey = nil }() if err := s.logon(); err != nil { return err } @@ -67,6 +69,9 @@ func (s *session) run() error { return err } s.applyPrefs() + if err := s.applyLineSpeed(); err != nil { + return err + } t.Notify = s.notify defer func() { t.Notify = nil }() err := app.Run(s.b, s.n, s)