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..c1af673 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -92,6 +92,17 @@ 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. Break (telnet's or SSH's) or Ctrl-X sends the +; rest of a slow screen at once. 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..fe98506 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. Break (telnet's or SSH's) or Ctrl-X sends the rest of a slow screen at once. 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. Break (telnet's or SSH's) or Ctrl-X sends the rest of a slow screen at once. 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. Break (telnet's or SSH's) or Ctrl-X sends the rest of a slow screen at once. 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/server.go b/internal/server/server.go index 35654a8..8d4e875 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -605,6 +605,11 @@ func (s *Server) text(rw io.ReadWriter, c deadliner, l *Listener, node *bbs.Node deadliner }{rw, c} t := textui.NewTerm(conn) + if b, ok := rw.(interface{ SetOnBreak(func()) }); ok { + // Break (telnet's, SSH's) skips the rest of a screen slowed to a line speed + b.SetOnBreak(t.Break) + defer b.SetOnBreak(nil) + } t.Clean8 = true t.Ident = node.Caller.Ident if sz, ok := rw.(interface{ Size() (int, int) }); ok { diff --git a/internal/server/speed_test.go b/internal/server/speed_test.go new file mode 100644 index 0000000..ca07f2c --- /dev/null +++ b/internal/server/speed_test.go @@ -0,0 +1,142 @@ +package server + +import ( + "io" + "net" + "strings" + "testing" + "time" + + "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) + } +} + +// TestLineSpeedSkip: at 300 bit/s an SSH Break (RFC 4335), or Ctrl-X, +// sends the rest of the screen at once. +func TestLineSpeedSkip(t *testing.T) { + e, addr, _ := startSSH(t, nil) + 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) + } + s, err := c.NewSession() + if err != nil { + t.Fatal(err) + } + if err := s.RequestPty("xterm-256color", 40, 100, ssh.TerminalModes{}); err != nil { + t.Fatal(err) + } + in, _ := s.StdinPipe() + out, _ := s.StdoutPipe() + if err := s.Shell(); err != nil { + t.Fatal(err) + } + a, b := net.Pipe() + go func() { io.Copy(a, out); a.Close() }() + go io.Copy(in, a) + t.Cleanup(func() { s.Close(); b.Close() }) + d := &dialog{t: t, c: b} + + // the main menu, some 1500 bytes: most of a minute at 300 bit/s + time.Sleep(300 * time.Millisecond) + if ok, err := s.SendRequest("break", true, ssh.Marshal(struct{ Ms uint32 }{500})); err != nil || !ok { + t.Fatalf("break: %v %v", ok, err) + } + d.expect("Command: ") + // and slow again after: the profile, skipped by Ctrl-X + d.send("P") + time.Sleep(300 * time.Millisecond) + d.send("\x18") + d.expect("[Q]uit: ") +} diff --git a/internal/server/ssh.go b/internal/server/ssh.go index 5643265..ecda5b3 100644 --- a/internal/server/ssh.go +++ b/internal/server/ssh.go @@ -263,10 +263,15 @@ func (s *Server) sshCall(c net.Conn, l *Listener, caller *bbs.Caller, remote str } } c.SetReadDeadline(time.Time{}) + t := newSSHTerm(ch, c, pty) + defer t.close() go func() { for req := range creqs { + if req.Type == "break" { // RFC 4335: OpenSSH's ~B, PuTTY's Break + t.sendBreak() + } // window-change: the size is the one the session began with - req.Reply(req.Type == "window-change", nil) + req.Reply(req.Type == "window-change" || req.Type == "break", nil) } }() @@ -274,8 +279,6 @@ func (s *Server) sshCall(c net.Conn, l *Listener, caller *bbs.Caller, remote str caller.TrustedUser, caller.TrustedHow = u, sc.Permissions.Extensions["how"] } caller.Terminal = bbs.Clean(pty.Term, 40) - t := newSSHTerm(ch, c, pty) - defer t.close() node, err := s.B.Enter(caller, func() { c.Close() }) if err != nil { s.B.Log.Printf("[listen %s] %s: %v", l.Name, remote, err) @@ -319,6 +322,24 @@ type sshTerm struct { mu sync.Mutex dl time.Time changed chan struct{} // closed when dl changes + onBreak func() // SetOnBreak's +} + +// SetOnBreak has f called when the client sends a break. +func (t *sshTerm) SetOnBreak(f func()) { + t.mu.Lock() + t.onBreak = f + t.mu.Unlock() +} + +// sendBreak is the client's break: SetOnBreak's func, if set. +func (t *sshTerm) sendBreak() { + t.mu.Lock() + f := t.onBreak + t.mu.Unlock() + if f != nil { + f() + } } // newSSHTerm is ch as a terminal, conn closed when a write hangs; the pty's diff --git a/internal/telnet/telnet.go b/internal/telnet/telnet.go index 7cbcfe2..3d73375 100644 --- a/internal/telnet/telnet.go +++ b/internal/telnet/telnet.go @@ -21,6 +21,9 @@ import ( const ( SE = 240 NOP = 241 + BRK = 243 // Break + IP = 244 // Interrupt Process + AO = 245 // Abort Output GA = 249 SB = 250 WILL = 251 @@ -72,6 +75,8 @@ type Conn struct { lastCR bool early []byte // data that came while negotiating out []byte // answers to send, in order + + onBreak func() // SetOnBreak's } const ( @@ -87,6 +92,15 @@ func New(c net.Conn) *Conn { return &Conn{Conn: c, r: bufio.NewReaderSize(c, 4096)} } +// SetOnBreak has f called when the client sends Break, Interrupt Process +// or Abort Output (its Break key, or a menu's "send break"); they are seen +// as the client's data is read. +func (c *Conn) SetOnBreak(f func()) { + c.mu.Lock() + c.onBreak = f + c.mu.Unlock() +} + // TermType is the terminal type the client gave ("" if none). func (c *Conn) TermType() string { c.mu.Lock() @@ -222,6 +236,11 @@ func (c *Conn) input(b byte) (byte, bool) { c.cmd, c.state = b, stOpt case SB: c.sub, c.state = c.sub[:0], stSub + case BRK, IP, AO: + if c.onBreak != nil { + c.onBreak() + } + c.state = stData default: // NOP, GA, AYT, ...: nothing to do c.state = stData } diff --git a/internal/telnet/telnet_test.go b/internal/telnet/telnet_test.go index 3b8d7fc..60e8c71 100644 --- a/internal/telnet/telnet_test.go +++ b/internal/telnet/telnet_test.go @@ -240,3 +240,27 @@ func TestHandoffContrary(t *testing.T) { t.Error("the terminal type asked for again after DONT") } } + +// TestBreak: Break, Interrupt Process and Abort Output call SetOnBreak's +// func, and are not data. +func TestBreak(t *testing.T) { + a, b := net.Pipe() + defer a.Close() + defer b.Close() + c := New(a) + n := 0 + c.SetOnBreak(func() { n++ }) + go b.Write([]byte{'a', IAC, BRK, 'b', IAC, IP, IAC, AO, 'c'}) + got := make([]byte, 0, 3) + buf := make([]byte, 16) + for len(got) < 3 { + k, err := c.Read(buf) + if err != nil { + t.Fatal(err) + } + got = append(got, buf[:k]...) + } + if string(got) != "abc" || n != 3 { + t.Errorf("data %q, %d breaks", got, n) + } +} 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..34248a7 --- /dev/null +++ b/internal/textui/speed.go @@ -0,0 +1,248 @@ +package textui + +import ( + "strconv" + "sync" + "sync/atomic" + "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. A Break (telnet's, SSH's) +// or Ctrl-X while a screen is coming sends the rest of it at once, up to +// the next prompt: skipped, but drawn whole, with no escape sequence cut. + +// 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) + + skip atomic.Bool // Break or Ctrl-X: at the line's own speed to the next prompt + poll func() // looks for Ctrl-X (and a telnet Break) among the keys come + lastPoll time.Time + noPoll atomic.Bool // a door reads the keys: poll is not called +} + +// pollEvery is how often keys are looked at while a screen is slowed. +const pollEvery = 100 * time.Millisecond + +// 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) { + if p.poll != nil && !p.noPoll.Load() && time.Since(p.lastPoll) >= pollEvery { + p.lastPoll = time.Now() + p.poll() + } + if p.skip.Load() { + m, err := p.Conn.Write(b[sent:]) + p.next = time.Now() + return sent + m, err + } + 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) +} + +// skipKey is Ctrl-X: while a screen is slowed, the rest of it at once. +const skipKey = 0x18 + +// Break is the caller's Break (telnet's, SSH's): a screen being slowed to +// the line speed comes the rest of the way at once. Any goroutine may +// call it. +func (t *Term) Break() { t.line.skip.Store(true) } + +// pollSkip looks at the keys come while a screen is slowed: a Ctrl-X first +// among them is taken as Break. Reading lets a telnet Break be seen. +func (t *Term) pollSkip() { + if t.r.Buffered() == 0 { + t.c.SetReadDeadline(time.Now().Add(2 * time.Millisecond)) + t.r.Peek(1) + t.c.SetReadDeadline(time.Time{}) + } + if t.r.Buffered() == 0 { + return + } + if b, err := t.r.Peek(1); err == nil && b[0] == skipKey && !t.PETSCII { + t.r.ReadByte() + t.Break() + } +} diff --git a/internal/textui/speed_test.go b/internal/textui/speed_test.go new file mode 100644 index 0000000..5a916bd --- /dev/null +++ b/internal/textui/speed_test.go @@ -0,0 +1,99 @@ +package textui + +import ( + "bytes" + "os" + "strings" + "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 := &keysConn{in: bytes.NewReader(nil)} + 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.out.Len() != 3*len(data) { + t.Errorf("sent %d bytes, not %d", c.out.Len(), 3*len(data)) + } + if term.LineSpeed() != 9600 { + t.Errorf("speed %d", term.LineSpeed()) + } +} + +// keysConn is a line with keys typed ahead, keeping what is written. +type keysConn struct { + in *bytes.Reader + out bytes.Buffer +} + +func (c *keysConn) Read(p []byte) (int, error) { + if c.in.Len() == 0 { + time.Sleep(time.Millisecond) + return 0, os.ErrDeadlineExceeded + } + return c.in.Read(p) +} +func (c *keysConn) Write(p []byte) (int, error) { return c.out.Write(p) } +func (c *keysConn) SetReadDeadline(time.Time) error { return nil } + +// TestSkip: Ctrl-X typed, or a Break, while a screen comes slowly sends the +// rest of it at once, all of it, and the next key read is slow again. +func TestSkip(t *testing.T) { + screen := strings.Repeat("ANSI art line\x1b[1;36m!\x1b[0m\r\n", 120) // 3000 bytes: 25 s at 1200 + c := &keysConn{in: bytes.NewReader([]byte{0x18, 'x'})} + term := NewTerm(c) + term.SetLineSpeed(1200) + start := time.Now() + term.Raw([]byte(screen)) + if d := time.Since(start); d > 2*time.Second { + t.Errorf("Ctrl-X: the screen took %v", d) + } + if !strings.Contains(c.out.String(), screen) { + t.Errorf("sent %d bytes, not the whole screen", c.out.Len()) + } + if r, err := term.readRune(); err != nil || r != 'x' { + t.Errorf("the key after Ctrl-X: %q %v", r, err) + } + if term.line.skip.Load() { + t.Error("still skipping after a key was read") + } + + // a Break from another goroutine (SSH's) + c2 := &keysConn{in: bytes.NewReader(nil)} + term = NewTerm(c2) + term.SetLineSpeed(1200) + go func() { + time.Sleep(200 * time.Millisecond) + term.Break() + }() + start = time.Now() + term.Raw([]byte(screen)) + if d := time.Since(start); d < 150*time.Millisecond || d > 2*time.Second { + t.Errorf("Break: the screen took %v", d) + } + if c2.out.String() != screen { + t.Errorf("sent %d bytes, not the screen", c2.out.Len()) + } +} diff --git a/internal/textui/term.go b/internal/textui/term.go index a31baa0..5406d49 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,9 +164,12 @@ 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} + t := &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} + line.poll = t.pollSkip + return t } // echoConn gives what is written to the caller to Echo as well (for a @@ -380,6 +389,8 @@ func (t *Term) read(keys bool) (rune, error) { if err := t.Flush(); err != nil { return 0, err } + t.line.skip.Store(false) // a skipped screen ends at its prompt + t.line.noPoll.Store(false) start := time.Now() for { limit := start.Add(t.Idle) @@ -420,6 +431,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 +1082,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 +1108,16 @@ 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 + // the door's own goroutine reads the keys till it is done: not polled + t.line.noPoll.Store(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) diff --git a/internal/ymsg/ymsg_test.go b/internal/ymsg/ymsg_test.go index 2959d6c..6377fc2 100644 --- a/internal/ymsg/ymsg_test.go +++ b/internal/ymsg/ymsg_test.go @@ -574,8 +574,14 @@ func TestConference(t *testing.T) { t.Errorf("invite: %v", inv.pairs) } // Carol Ann, not on Yahoo, has it as a private message + // (the invitations go out one by one: bob's can come before hers is kept) carol, _ := e.st.UserByName("Carol Ann") - if cs, _ := e.st.KeptChats(carol.ID); len(cs) != 1 || !strings.Contains(cs[0].Text, "yc-alice-1234") { + cs, _ := e.st.KeptChats(carol.ID) + for end := time.Now().Add(2 * time.Second); len(cs) == 0 && time.Now().Before(end); { + time.Sleep(10 * time.Millisecond) + cs, _ = e.st.KeptChats(carol.ID) + } + if len(cs) != 1 || !strings.Contains(cs[0].Text, "yc-alice-1234") { t.Errorf("Carol Ann's invitation: %+v", cs) } bob.send(svcConfLogon, 0, kv(1, "bob"), kv(3, "alice"), kv(57, "alice-1234"))