From a93a2cf303d7d3b51e9ee4c36c580970f492ea67 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 17:45:05 +0000 Subject: [PATCH] Add the sysop's tools: watching nodes, chat, users, statistics, events A sysop's main menu has * (and custom menus a sysop action), on every terminal: - Watch a node: what a text caller is sent, as it is sent (the text terminal's connection echoes to bbs.Node.Echo; a slow watcher misses some, never slows the caller). A key stops; the caller leaving ends it. Text terminals only. - Chat with a node: the caller is told and taken into a private chat (their page's room) at their next menu; the sysop waits there. - Kick a node. - Users: level, flags, lock, sysop rights, a new password (not one's own lock or rights). - Statistics: totals, and calls, new users, posts and uploads for each of the last 14 days as bars. - The bans (lifted by number) and the hack log. - Scheduled events ([event NAME]: a program run without a shell, daily at a time or every N minutes, with a timeout; internal/events): when they run next, the last run's end and output, run now. - Available: whether pages reach the sysop; when not, a caller who pages may leave a message. The API: GET /admin/events, POST /admin/events/{name}/run, PUT /admin/available. Sysop-Tools is the wiki page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr --- bbs.conf.sample | 7 + cmd/bbs/main.go | 7 + docs/wiki/Configuration.md | 2 + docs/wiki/Customization.md | 2 +- docs/wiki/Development.md | 8 +- docs/wiki/HTTP-API.md | 2 + docs/wiki/Sysop-Tools.md | 50 ++++ docs/wiki/_Sidebar.md | 1 + internal/api/api_test.go | 25 ++ internal/api/openapi.go | 6 + internal/api/rest.go | 59 +++++ internal/app/app.go | 22 ++ internal/app/app_test.go | 57 +++- internal/app/sysop.go | 461 +++++++++++++++++++++++++++++++++ internal/bbs/bbs.go | 7 + internal/bbs/chat.go | 2 +- internal/bbs/custom.go | 1 + internal/bbs/sysop.go | 127 +++++++++ internal/bbs/sysop_test.go | 68 +++++ internal/events/events.go | 272 +++++++++++++++++++ internal/events/events_test.go | 75 ++++++ internal/server/config.go | 56 +++- internal/server/sysop_test.go | 97 +++++++ internal/store/stats.go | 54 ++++ internal/textui/frontend.go | 59 +++++ internal/textui/term.go | 31 ++- internal/textui/ui.go | 2 + internal/ui3270/frontend.go | 6 + 28 files changed, 1559 insertions(+), 7 deletions(-) create mode 100644 docs/wiki/Sysop-Tools.md create mode 100644 internal/app/sysop.go create mode 100644 internal/bbs/sysop.go create mode 100644 internal/bbs/sysop_test.go create mode 100644 internal/events/events.go create mode 100644 internal/events/events_test.go create mode 100644 internal/server/sysop_test.go create mode 100644 internal/store/stats.go diff --git a/bbs.conf.sample b/bbs.conf.sample index 2d6c79a..ef8221e 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -125,6 +125,13 @@ throttle_time = 600 ;hack_log = /var/log/bbs/hack.log ;ban_minutes = 60 +; scheduled events: a program (no shell), daily at a time or every N +; minutes; see the wiki's Sysop tools +;[event backup] +;command = /usr/local/bin/bbs-backup --to /var/backups/bbs +;at = 03:30 +;timeout = 600 + ; telnet and TN3270, for everyone (port 23 needs root or ; CAP_NET_BIND_SERVICE) [listen telnet] diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index 6a12a38..e623e20 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -45,6 +45,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/api" "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/events" "github.com/Neo-Desktop/bbs-sec/internal/fido" "github.com/Neo-Desktop/bbs-sec/internal/files" "github.com/Neo-Desktop/bbs-sec/internal/finger" @@ -284,6 +285,9 @@ func serve(cfg *server.Config) int { b.Doors = cfg.Doors b.Screens, b.Menus, b.Text, b.ScriptsDir = cfg.Screens, cfg.Menus, cfg.Text, cfg.ScriptsDir b.Guard = cfg.Guard + if len(cfg.Events) > 0 { + b.Events = &events.Scheduler{Events: cfg.Events, Log: b.Log} + } if b.Files, err = files.Open(st, cfg.FilesDir, cfg.MaxFileSize, cfg.UploadQuota); err != nil { lg.Printf("files: %v", err) return 1 @@ -343,6 +347,9 @@ func serve(cfg *server.Config) int { } go fd.Run(ctx) } + if b.Events != nil { + go b.Events.Run(ctx) + } srv := server.New(b, cfg.Listeners) srv.Graphics = cfg.Graphics srv.LogoFile = cfg.LogoFile diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index a921c62..2a02f55 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -28,6 +28,8 @@ whether terminals are asked what they are: [Terminal identification](Terminal-Id | `[door NAME]` | a door program | [Doors](Doors) | | `screens_dir` (in `[general]`), `[menu NAME]`, `[strings]` | the sysop's screens, menus and prompts | [Customization](Customization) | | `scripts_dir` (in `[general]`) | the sysop's JavaScript | [Scripting](Scripting) | +| `[security]` | deny lists, bans, the hack log | [Security](Security) | +| `[event NAME]` | scheduled programs | [Sysop tools](Sysop-Tools) | | `[finger]`, `[gopher]` | the finger and gopher servers | [Finger and gopher](Finger-and-Gopher) | | `database` (in `[general]`) | SQLite's file, or a PostgreSQL, MySQL or MariaDB server | [Databases](Databases) | | `[level N]`, `new_user_level`, `validated_level` (in `[general]`) | access levels | [Access levels](Access-Levels) | diff --git a/docs/wiki/Customization.md b/docs/wiki/Customization.md index eb79593..ee4c573 100644 --- a/docs/wiki/Customization.md +++ b/docs/wiki/Customization.md @@ -112,7 +112,7 @@ begin comments), then what it does: | action | | |---|---| -| `areas` `mail` `who` `users` `profile` `info` `files` `doors` `chat` `page` `callers` `feedback` | the built-in parts (`callers`: the last callers; `feedback`: mail to the sysop) | +| `areas` `mail` `who` `users` `profile` `info` `files` `doors` `chat` `page` `callers` `feedback` `sysop` | the built-in parts (`callers`: the last callers; `feedback`: mail to the sysop; `sysop`: the [sysop tools](Sysop-Tools), for sysops) | | `terminal` | a 3270's terminal details | | `logoff` | log off (asking first on a text terminal) | | `back` | back to the menu before | diff --git a/docs/wiki/Development.md b/docs/wiki/Development.md index 91dc30e..f2dbcc5 100644 --- a/docs/wiki/Development.md +++ b/docs/wiki/Development.md @@ -7,6 +7,8 @@ | `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 | | `internal/view` | what the screens show, described once: menus, tables, messages, forms, panels, drafts | | `internal/script` | the sysop's JavaScript (goja): screens of internal/view, the BBS as the caller, data kept, the time a script may compute | +| `internal/guard` | deny lists, bans, the name filter, the hack log | +| `internal/events` | the sysop's scheduled events | | `internal/app` | the screens after the login, for every front end: menus, areas, mail, files, who's online, the profile, validation, paging the sysop | | `internal/textui` | the text front end: the login, line editing, ANSI detection, paging, RIP menus; the screens as prompts and keys; chat, doors, transfers | | `internal/ui3270` | the 3270 front end: the logon, the screens as fields and PF keys on go3270; chat, IND$FILE, its graphics | @@ -133,7 +135,11 @@ The full-screen editor: its text (wrapping as typed and as given, a word too long for a line, joining lines by Backspace and Delete, moving over line ends, quoting, the line limit), and an SSH caller writing a post with the cursor keys, replying with lines from the quote window and -`/S`, then choosing the line editor; the last callers, feedback to the +`/S`, then choosing the line editor; the sysop's tools (a sysop watching +a caller's screen as it is sent, calling them into chat at their next +menu, being away when they page; the user editor, statistics, bans, the +hack log and events through internal/app; events run, failing, timed +out and not run twice; their configuration and the API); the last callers, feedback to the sysop, a user's details (more of them to a sysop) and mail from there, a line about oneself, expert menus and `?` on a text terminal; keeping callers out (the deny file read again as it changes, networks and IPv6, bans after the throttle and diff --git a/docs/wiki/HTTP-API.md b/docs/wiki/HTTP-API.md index 1abdf87..12d79db 100644 --- a/docs/wiki/HTTP-API.md +++ b/docs/wiki/HTTP-API.md @@ -82,6 +82,8 @@ Errors are `{"error": "...", "code": "..."}`. | `GET /files?q=` or `?since=` | files by words in their names and descriptions, or added since a time (RFC 3339), newest first | files | | `GET /admin/bans`, `DELETE /admin/bans/{ip}` | addresses banned for failed logins; lift a ban | sysop | | `GET /admin/hacklog?lines=` | the hack log's last lines | sysop | +| `GET /admin/events`, `POST /admin/events/{name}/run` | the scheduled events; run one now | sysop | +| `PUT /admin/available` | `{"available": false}`: pages reach no sysop | sysop | | `GET /files/{id}/listing` | what is in an archive (ZIP, tar, tar.gz); 422 for another file | files | | `GET /chat/rooms` | chat rooms in use | chat | | `POST /nodes/{n}/message`, `POST /page` | a line to a node; page the sysop (both need an open stream) | chat | diff --git a/docs/wiki/Sysop-Tools.md b/docs/wiki/Sysop-Tools.md new file mode 100644 index 0000000..2115ac9 --- /dev/null +++ b/docs/wiki/Sysop-Tools.md @@ -0,0 +1,50 @@ +A sysop's main menu has `*`, *Sysop tools* (and a custom menu may have a +`sysop` item). It works on any terminal; watching a node needs a text +terminal. + +| | key | | +|---|---|---| +| watch a node | `W` | what a text caller is sent, as it is sent, on your screen: their menus, their door, their typing echoed. A key stops; their leaving ends it. Their screen size and character set are theirs | +| chat with a node | `C` | the caller is told you would like a word, and taken into a private chat with you at their next menu (their page's room, `sysop-N`); you wait there | +| kick a node | `K` | throw a caller off, after a yes | +| users | `U` | every user's level, flags and state; for one: their level, flags (`+AB -C` adds and takes), lock or unlock, sysop rights given or taken, a new password. Not your own lock or rights | +| statistics | `S` | totals (users, messages, mail, files; logins, posts, pages and failed logins since the start), and calls, new users, posts and uploads for each of the last 14 days, as bars | +| hack log and bans | `H` | the addresses banned now (a number lifts its ban), and `L` the [hack log](Security#keeping-callers-out)'s last 100 lines | +| scheduled events | `E` | the events, when they run next and how their last run went; one's command and output, and `R` runs it now | +| available | `A` | whether pages reach you; when not, a caller who pages is told you are not available and may leave you a message | + +Validating new users stays on the main menu (`V`, when some wait). + +## Scheduled events + +``` +; bbs.conf +[event backup] +command = /usr/local/bin/bbs-backup --to "/var/backups/bbs" +at = 03:30 ; every day, at this local time + +[event fidopoll] +command = /usr/local/bin/bbs fido poll +every = 60 ; minutes +timeout = 300 ; seconds it may take (default 600) +``` + +An event is a program and its arguments (words parted by spaces; `"..."` +or `'...'` keep spaces in one), run without a shell, with `BBS_EVENT` set +to its name, at most one at a time. It runs `at` a time each day or +`every` so many minutes (the first after that many minutes from the +start). A run that goes past `timeout` is stopped. The log has each +run; the last run's end and output (its last 4 KB) are kept for the +sysop tools and the API. `bbs check` warns of a program it cannot find. + +## The API + +| | | +|---|---| +| `GET /api/v1/admin/events` | the events, their next and last runs | +| `POST /api/v1/admin/events/{name}/run` | run one now, and wait for it | +| `PUT /api/v1/admin/available` | `{"available": false}`: pages reach no one | +| `GET /api/v1/admin/bans`, `DELETE /api/v1/admin/bans/{ip}`, `GET /api/v1/admin/hacklog` | bans and the hack log | +| `POST /api/v1/admin/nodes/{n}/kick` | throw a caller off | + +**See also:** [Administration](Administration), [Security](Security), [Chat and paging](Chat-and-Paging) diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index b0db750..5e0fe28 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -4,6 +4,7 @@ - [Building](Building) - [Running](Running) - [Administration](Administration) +- [Sysop tools](Sysop-Tools) - [Configuration](Configuration) - [Databases](Databases) - [Customization](Customization) diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 6e53f8e..ffc8d54 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -22,6 +22,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/api/pb" "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/events" "github.com/Neo-Desktop/bbs-sec/internal/files" "github.com/Neo-Desktop/bbs-sec/internal/guard" "github.com/Neo-Desktop/bbs-sec/internal/store" @@ -763,3 +764,27 @@ func TestCallersAndAbout(t *testing.T) { t.Errorf("user: %v", m) } } + +func TestEventsAndAvailable(t *testing.T) { + s := setup(t, Settings{}) + s.b.Events = &events.Scheduler{Events: []*events.Event{{Name: "hello", Command: []string{"/bin/echo", "hi"}, Every: time.Hour}}} + sys := s.login("sysop", "sysoppass1") + code, m, _ := s.do("POST", "/api/v1/admin/events/hello/run", sys, nil) + if code != 200 || m["ok"] != true || m["output"] != "hi\n" || m["by"] != "sysop" { + t.Errorf("run: %d %v", code, m) + } + if code, _, _ := s.do("POST", "/api/v1/admin/events/nope/run", sys, nil); code != 404 { + t.Errorf("no such event: %d", code) + } + if code, _, l := s.do("GET", "/api/v1/admin/events", sys, nil); code != 200 || len(l) != 1 || + l[0].(map[string]any)["last"].(map[string]any)["ok"] != true { + t.Errorf("events: %d %v", code, l) + } + if code, m, _ := s.do("PUT", "/api/v1/admin/available", sys, map[string]any{"available": false}); code != 200 || + m["available"] != false || s.b.SysopAvailable() { + t.Errorf("away: %d %v", code, m) + } + if code, _, _ := s.do("PUT", "/api/v1/admin/available", sys, map[string]any{}); code != 400 { + t.Errorf("nothing said: %d", code) + } +} diff --git a/internal/api/openapi.go b/internal/api/openapi.go index 0b0f1a9..5306951 100644 --- a/internal/api/openapi.go +++ b/internal/api/openapi.go @@ -60,6 +60,9 @@ var ops = []op{ {"POST", "/api/v1/admin/nodes/{n}/kick", "Throw a caller off", "sysop", "", "", 204}, {"GET", "/api/v1/admin/bans", "Addresses banned for failed logins, and until when", "sysop", "", "Bans", 200}, {"DELETE", "/api/v1/admin/bans/{ip}", "Lift a ban", "sysop", "", "", 204}, + {"GET", "/api/v1/admin/events", "The scheduled events: when, and how the last run went", "sysop", "", "Events", 200}, + {"POST", "/api/v1/admin/events/{name}/run", "Run an event now (and wait for it)", "sysop", "", "EventResult", 200}, + {"PUT", "/api/v1/admin/available", "Whether pages reach the sysop", "sysop", "Available", "Available", 200}, {"GET", "/api/v1/admin/hacklog", "The hack log's last lines (?lines=, up to 1000)", "sysop", "", "Lines", 200}, {"GET", "/api/v1/admin/fido", "FidoNet: addresses, links, files waiting", "sysop", "", "Object", 200}, {"POST", "/api/v1/admin/fido/poll", "Call the FidoNet links now", "sysop", "", "Object", 202}, @@ -113,6 +116,9 @@ var schemas = map[string]any{ "FileAreas": map[string]any{"type": "array", "items": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_upload": boo, "files": num, "can_upload": boo})}, "File": obj(map[string]any{"id": num, "area": num, "name": str, "description": str, "size": num, "sha256": str, "uploader": str, "created": date, "downloads": num, "long_description": str}), "Callers": map[string]any{"type": "array", "items": obj(map[string]any{"user": str, "location": str, "via": str, "node": num, "at": date})}, + "EventResult": obj(map[string]any{"start": date, "seconds": num, "ok": boo, "error": str, "output": str, "by": str}), + "Events": map[string]any{"type": "array", "items": obj(map[string]any{"name": str, "command": map[string]any{"type": "array", "items": str}, "schedule": str, "next": date, "running": boo, "last": ref("EventResult")})}, + "Available": obj(map[string]any{"available": boo}, "available"), "Bans": map[string]any{"type": "array", "items": obj(map[string]any{"ip": str, "until": date})}, "Lines": map[string]any{"type": "array", "items": str}, "Listing": map[string]any{"type": "array", "items": obj(map[string]any{"name": str, "size": num, "dir": boo, "modified": date})}, diff --git a/internal/api/rest.go b/internal/api/rest.go index 19fafb2..572ac3b 100644 --- a/internal/api/rest.go +++ b/internal/api/rest.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/events" "github.com/Neo-Desktop/bbs-sec/internal/files" "github.com/Neo-Desktop/bbs-sec/internal/ftn" "github.com/Neo-Desktop/bbs-sec/internal/news" @@ -72,6 +73,9 @@ func (s *Server) routes() map[string]route { "GET /api/v1/admin/bans": {scope: "sysop", h: s.bans}, "DELETE /api/v1/admin/bans/{ip}": {scope: "sysop", h: s.unban}, "GET /api/v1/admin/hacklog": {scope: "sysop", h: s.hackLog}, + "GET /api/v1/admin/events": {scope: "sysop", h: s.scheduled}, + "POST /api/v1/admin/events/{name}/run": {scope: "sysop", h: s.runEvent}, + "PUT /api/v1/admin/available": {scope: "sysop", h: s.setAvailable}, "GET /api/v1/admin/fido": {scope: "sysop", h: s.fido}, "POST /api/v1/admin/fido/poll": {scope: "sysop", h: s.fidoPoll}, "GET /api/v1/admin/news": {scope: "sysop", h: s.news}, @@ -1232,6 +1236,61 @@ func (s *Server) hackLog(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, lines) } +func resultOut(r *events.Result) map[string]any { + m := map[string]any{"start": r.Start, "seconds": r.Took.Seconds(), "ok": r.Err == "", "output": r.Output, "by": r.By} + if r.Err != "" { + m["error"] = r.Err + } + return m +} + +// scheduled: the scheduled events +func (s *Server) scheduled(w http.ResponseWriter, r *http.Request) { + out := []map[string]any{} + if s.B.Events != nil { + for _, e := range s.B.Events.Status() { + m := map[string]any{"name": e.Name, "command": e.Command, "schedule": e.Schedule(), "next": e.Next, + "running": e.Running} + if e.Last != nil { + m["last"] = resultOut(e.Last) + } + out = append(out, m) + } + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) runEvent(w http.ResponseWriter, r *http.Request) { + if s.B.Events == nil { + fail(w, http.StatusNotFound, "there are no events") + return + } + res, err := s.B.Events.RunNow(r.Context(), r.PathValue("name"), whoOf(r).user.Name) + switch { + case errors.Is(err, events.ErrRunning): + fail(w, http.StatusConflict, "it is running already") + case err != nil: + fail(w, http.StatusNotFound, err.Error()) + default: + writeJSON(w, http.StatusOK, resultOut(res)) + } +} + +func (s *Server) setAvailable(w http.ResponseWriter, r *http.Request) { + var req struct { + Available *bool `json:"available"` + } + if !s.decode(w, r, &req) { + return + } + if req.Available == nil { + fail(w, http.StatusBadRequest, `give {"available": true} or false`) + return + } + s.B.SetSysopAvailable(*req.Available) + writeJSON(w, http.StatusOK, map[string]any{"available": s.B.SysopAvailable()}) +} + func (s *Server) fido(w http.ResponseWriter, r *http.Request) { if s.Fido == nil { fail(w, http.StatusNotFound, "the BBS is not on FidoNet") diff --git a/internal/app/app.go b/internal/app/app.go index 8006a94..cbd2496 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -60,6 +60,9 @@ type Frontend interface { TerminalAction(id string) error // TerminalInfo shows all that is known of the terminal (a 3270's). TerminalInfo() error + // Watch shows a sysop another node's screen as it is sent, until a + // key (a text terminal's). + Watch(node int) error // Logoff says goodbye; false if the caller thought better of it. Logoff() (bool, error) } @@ -148,6 +151,9 @@ func (s *Session) welcome(shown bool) []view.Line { // mainMenu is the built-in main menu. func (s *Session) mainMenu(intro []view.Line) error { for { + if err := s.summoned(); err != nil { + return err + } u := s.refresh() s.N.Doing("Main menu") unread, _ := s.B.Store.UnreadMail(u.ID) @@ -186,6 +192,9 @@ func (s *Session) mainMenu(intro []view.Line) error { } items = append(items, view.Item{Key: "L", Label: "Last callers"}, view.Item{Key: "K", Label: "Feedback to the sysop"}) + if u.Sysop { + items = append(items, view.Item{Key: "*", Label: "Sysop tools"}) + } if s.UI.Kind() == TN3270 { items = append(items, view.Item{Key: "T", Label: "Your terminal"}) } @@ -202,6 +211,10 @@ func (s *Session) mainMenu(intro []view.Line) error { err = s.mail() case "L": err = s.lastCallers() + case "*": + if u.Sysop { + err = s.sysopMenu() + } case "K": err = s.feedback() case "W": @@ -261,6 +274,9 @@ func (s *Session) logoff() error { func (s *Session) runMenu(full *bbs.Menu, depth int, intro []view.Line) error { vars := s.N.Vars() for { + if err := s.summoned(); err != nil { + return err + } u := s.refresh() m := s.B.MenuFor(full, u) title := screens.String(m.Title, vars) @@ -344,6 +360,12 @@ func (s *Session) do(it *bbs.MenuItem, depth int) error { return s.UI.Chat("", "") case "callers": return s.lastCallers() + case "sysop": + if !s.User.Sysop { + s.UI.Say(view.Bad, "That is for the sysop.") + return nil + } + return s.sysopMenu() case "feedback": return s.feedback() case "page": diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 61194e3..299e7cb 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -3,14 +3,18 @@ package app import ( "archive/zip" "bytes" + "fmt" "log" "path/filepath" "strings" "testing" + "time" "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/door" + "github.com/Neo-Desktop/bbs-sec/internal/events" "github.com/Neo-Desktop/bbs-sec/internal/files" + "github.com/Neo-Desktop/bbs-sec/internal/guard" "github.com/Neo-Desktop/bbs-sec/internal/store" "github.com/Neo-Desktop/bbs-sec/internal/view" ) @@ -114,7 +118,11 @@ func (f *fake) Confirm(q string, def bool) (bool, error) { } func (f *fake) Say(tn view.Tone, msg string) { f.said = append(f.said, msg) } func (f *fake) Show(title string, ls []view.Line) error { - f.shown = append(f.shown, "show "+title) + var out []string + for _, l := range ls { + out = append(out, l.Label+l.Text) + } + f.shown = append(f.shown, "show "+title+": "+strings.Join(out, "; ")) return nil } @@ -137,7 +145,11 @@ func (f *fake) Terminal() string { return "te func (f *fake) TerminalActions() []view.Action { return nil } func (f *fake) TerminalAction(string) error { return nil } func (f *fake) TerminalInfo() error { return nil } -func (f *fake) Logoff() (bool, error) { return true, nil } +func (f *fake) Watch(n int) error { + f.shown = append(f.shown, fmt.Sprintf("watch %d", n)) + return nil +} +func (f *fake) Logoff() (bool, error) { return true, nil } // setup is a BBS with an area, and nodes for alice and the sysop. func setup(t *testing.T) (*bbs.BBS, *bbs.Node, *bbs.Node) { @@ -347,6 +359,47 @@ func TestUserFeatures(t *testing.T) { has(t, "screens", f.shown, "About:Calls from a C64; Access:level 20 (Level 20)") } +func TestSysopTools(t *testing.T) { + b, alice, sysop := setup(t) + dir := t.TempDir() + b.Guard = &guard.Guard{HackLog: filepath.Join(dir, "hack.log"), BanTime: time.Hour} + b.Guard.Ban("192.0.2.9", "too many failed logins") + b.Events = &events.Scheduler{Events: []*events.Event{{Name: "hello", Command: []string{"/bin/echo", "hi"}, Every: time.Hour}}} + aliceID := alice.User().ID + f := run(t, b, sysop, + "*", + // alice's level and flags, locked and unlocked + "U", view.Choice{Action: view.Pick, Row: 0}, "level", map[string]string{"level": "300"}, + "level", map[string]string{"level": "40"}, "flags", map[string]string{"flags": "+AB"}, "lock", "lock", view.Back, + view.Choice{Action: view.Back}, + "S", + "H", view.Choice{Action: view.Pick, Row: 0}, view.Choice{Action: "log"}, view.Choice{Action: view.Back}, + "E", view.Choice{Action: view.Pick, Row: 0}, "run", view.Choice{Action: view.Back}, + "W", view.Choice{Action: view.Pick, Row: -1, Num: "1"}, + "A", "Q") + has(t, "said", f.said, "That is not a level.") + if u, _ := b.Store.UserByID(aliceID); u.Level != 40 || u.Flags != "AB" || u.Locked { + t.Errorf("alice: %+v", u) + } + has(t, "screens", f.shown, "show Statistics:") + has(t, "said", f.said, "The ban on 192.0.2.9 is lifted.") + has(t, "screens", f.shown, "ban lifted by sysop") + has(t, "said", f.said, "hello: done.") + has(t, "screens", f.shown, "table Scheduled events: hello|every 1h0m0s|") + has(t, "screens", f.shown, "watch 1") + has(t, "screens", f.shown, "menu Sysop tools") + if b.SysopAvailable() { + t.Error("still available") + } + // alice has no sysop tools + f = run(t, b, alice, "*") + for _, s := range f.shown { + if strings.Contains(s, "Sysop tools") { + t.Errorf("alice got them: %q", f.shown) + } + } +} + func TestMailAndWho(t *testing.T) { b, alice, sysop := setup(t) f := run(t, b, alice, diff --git a/internal/app/sysop.go b/internal/app/sysop.go new file mode 100644 index 0000000..a5b47e8 --- /dev/null +++ b/internal/app/sysop.go @@ -0,0 +1,461 @@ +package app + +import ( + "context" + "errors" + "fmt" + "sort" + "strconv" + "strings" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/events" + "github.com/Neo-Desktop/bbs-sec/internal/view" +) + +// The sysop's tools: the nodes (watching, chat, kicking), the users, the +// statistics, the hack log and bans, the scheduled events, and whether +// pages reach them. + +func (s *Session) sysopMenu() error { + for { + u := s.refresh() + if !u.Sysop { + return nil + } + s.N.Doing("Sysop tools") + avail := "yes" + if !s.B.SysopAvailable() { + avail = "no" + } + var items []view.Item + if s.UI.Kind() == Text { + items = append(items, view.Item{Key: "W", Label: "Watch a node"}) + } + items = append(items, view.Item{Key: "C", Label: "Chat with a node"}, + view.Item{Key: "K", Label: "Kick a node"}, + view.Item{Key: "U", Label: "Users"}, + view.Item{Key: "S", Label: "Statistics"}, + view.Item{Key: "H", Label: "Hack log and bans"}) + if s.B.Events != nil { + items = append(items, view.Item{Key: "E", Label: "Scheduled events"}) + } + items = append(items, view.Item{Key: "A", Label: "Available: " + avail}, + view.Item{Key: "Q", Label: "Back"}) + k, err := s.UI.Menu(&view.Menu{Title: "Sysop tools", Items: items, Brief: s.expert()}) + if err != nil { + return err + } + switch strings.ToUpper(k) { + case "Q", view.Back: + return nil + case "W": + if n, ok, err := s.pickNode("Watch which node?"); err != nil || !ok { + if err != nil { + return err + } + } else if err := s.UI.Watch(n); err != nil { + return err + } + case "C": + if err := s.chatWith(); err != nil { + return err + } + case "K": + n, ok, err := s.pickNode("Kick which node?") + if err != nil { + return err + } + if !ok { + continue + } + if yes, err := s.UI.Confirm(fmt.Sprintf("Throw node %d's caller off?", n), false); err != nil || !yes { + if err != nil { + return err + } + continue + } + if err := s.B.Kick(n); err != nil { + s.UI.Say(view.Bad, capital(err.Error())+".") + } else { + s.B.Log.Printf("node %d: %s kicked node %d", s.N.Num, u.Name, n) + s.UI.Say(view.Good, fmt.Sprintf("Node %d is off.", n)) + } + case "U": + err = s.userEditor() + case "S": + err = s.statistics() + case "H": + err = s.hackLog() + case "E": + if s.B.Events != nil { + err = s.eventsScreen() + } + case "A": + s.B.SetSysopAvailable(!s.B.SysopAvailable()) + } + if err != nil { + return err + } + } +} + +// pickNode: a node chosen from those online but the sysop's own. +func (s *Session) pickNode(prompt string) (int, bool, error) { + t := &view.Table{Title: "Nodes", Pick: "Node", Prompt: prompt + " (its number, Enter for none): ", + Empty: "No one else is on.", + Columns: []view.Column{{Title: "User", Width: 20}, {Title: "Via", Width: 16}, {Title: "Doing", Wide: true}}} + for _, n := range s.B.Nodes() { + if n.Num == s.N.Num { + continue + } + name := n.User + if name == "" { + name = "(logging in)" + } + t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(n.Num), Cells: []string{name, n.Via, n.Activity}}) + } + c, err := s.UI.Table(t) + if err != nil || c.Action != view.Pick { + return 0, false, err + } + n, err := strconv.Atoi(c.Num) + if err != nil { + s.UI.Say(view.Bad, "That is not a node's number.") + return 0, false, nil + } + return n, true, nil +} + +// chatWith calls a caller into chat with the sysop. +func (s *Session) chatWith() error { + n, ok, err := s.pickNode("Chat with which node?") + if err != nil || !ok { + return err + } + room, err := s.N.Summon(n) + if err != nil { + s.UI.Say(view.Bad, capital(err.Error())+".") + return nil + } + return s.UI.Chat(room, fmt.Sprintf("Node %d's caller is called here at their next menu.", n)) +} + +// summoned takes the caller into chat if the sysop has called them. +func (s *Session) summoned() error { + if room := s.N.Summoned(); room != "" { + return s.UI.Chat(room, "The sysop would like a word.") + } + return nil +} + +// --- users + +func (s *Session) userEditor() error { + for { + us, err := s.B.Store.Users() + if err != nil { + return err + } + t := &view.Table{Title: "Users", Pick: "Number to edit", + Columns: []view.Column{{Title: "User", Width: 22}, {Title: "Level", Width: 5, Right: true}, + {Title: "Flags", Width: 8}, {Title: "", Width: 7}, {Title: "Last call", Width: 10, Wide: true}}} + for i, u := range us { + state := "" + switch { + case u.Locked: + state = "locked" + case u.Sysop: + state = "sysop" + } + last := "never" + if !u.LastLogin.IsZero() { + last = u.LastLogin.Format("2006-01-02") + } + t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Hot: u.Sysop, + Cells: []string{u.Name, strconv.Itoa(u.Level), u.Flags, state, last}}) + } + c, err := s.UI.Table(t) + if err != nil || c.Action == view.Back { + return err + } + if c.Action != view.Pick || c.Row < 0 { + continue + } + if err := s.editUser(us[c.Row].ID); err != nil { + return err + } + } +} + +func (s *Session) editUser(id int64) error { + by := fmt.Sprintf("node %d: %s", s.N.Num, s.User.Name) + for { + u, err := s.B.Store.UserByID(id) + if err != nil { + return nil + } + lvl := s.B.LevelOf(u) + p := &view.Panel{Title: u.Name, Lines: []view.Line{ + view.V("From:", u.Location), + view.V("Member:", fmt.Sprintf("since %s, %d calls, %d posts", u.Created.Format("2006-01-02"), u.Logins, u.Posts)), + view.V("Access:", fmt.Sprintf("level %d (%s), flags %q", u.Level, lvl.Name, u.Flags)), + view.V("Files:", fmt.Sprintf("%d downloaded, %d uploaded", u.Downloads, u.Uploads)), + view.V("State:", map[bool]string{true: "locked", false: "may log in"}[u.Locked]+ + map[bool]string{true: ", a sysop", false: ""}[u.Sysop])}, + Actions: []view.Action{{ID: "level", Label: "Level", Key: 'L', PF: 5}, + {ID: "flags", Label: "Flags", Key: 'F', PF: 6}}} + if u.ID != s.User.ID { + p.Actions = append(p.Actions, + view.Action{ID: "lock", Label: map[bool]string{true: "Unlock", false: "lock"}[u.Locked], Key: 'K', PF: 9, + Short: map[bool]string{true: "Unlock", false: "Lock"}[u.Locked]}, + view.Action{ID: "sysop", Label: map[bool]string{true: "Sysop no more", false: "Sysop"}[u.Sysop], Key: 'S', PF: 10}) + } + if !u.External { + p.Actions = append(p.Actions, view.Action{ID: "password", Label: "Password", Key: 'P', PF: 11}) + } + act, err := s.UI.Panel(p) + if err != nil { + return err + } + switch act { + case view.Back: + return nil + case "level": + v, ok, err := s.UI.Form(&view.Form{Title: "Level for " + u.Name, Submit: "Set", Fields: []view.Field{ + {Name: "level", Label: "Level (0-255)", Width: 3, Value: strconv.Itoa(u.Level)}}}) + if err != nil { + return err + } + l, e := strconv.Atoi(strings.TrimSpace(v["level"])) + if !ok { + continue + } + if e != nil || l < 0 || l > bbs.MaxLevel { + s.UI.Say(view.Bad, "That is not a level.") + continue + } + if err := s.B.Store.SetLevel(u.ID, l); err != nil { + return err + } + s.B.Log.Printf("%s set %s's level to %d", by, u.Name, l) + case "flags": + v, ok, err := s.UI.Form(&view.Form{Title: "Flags for " + u.Name, Submit: "Set", Fields: []view.Field{ + {Name: "flags", Label: "Flags", Prompt: "Flags (letters; +AB -C adds and takes): ", Width: 30}}}) + if err != nil { + return err + } + if !ok { + continue + } + fl, err := bbs.EditFlags(u.Flags, v["flags"]) + if err != nil { + s.UI.Say(view.Bad, capital(err.Error())+".") + continue + } + if err := s.B.Store.SetFlags(u.ID, fl); err != nil { + return err + } + s.B.Log.Printf("%s set %s's flags to %q", by, u.Name, fl) + case "lock": + if u.ID == s.User.ID { + continue + } + if err := s.B.Store.SetLocked(u.ID, !u.Locked); err != nil { + return err + } + s.B.Log.Printf("%s %s %s", by, map[bool]string{true: "unlocked", false: "locked"}[u.Locked], u.Name) + case "sysop": + if u.ID == s.User.ID { + continue + } + if ok, err := s.UI.Confirm(map[bool]string{true: "Take " + u.Name + "'s sysop rights away?", + false: "Make " + u.Name + " a sysop?"}[u.Sysop], false); err != nil || !ok { + if err != nil { + return err + } + continue + } + if err := s.B.Store.SetSysop(u.ID, !u.Sysop); err != nil { + return err + } + s.B.Log.Printf("%s made %s %s", by, u.Name, map[bool]string{true: "no longer a sysop", false: "a sysop"}[u.Sysop]) + case "password": + v, ok, err := s.UI.Form(&view.Form{Title: "A new password for " + u.Name, Submit: "Set", Fields: []view.Field{ + {Name: "pw", Label: "New password", Width: 32, Secret: true}, + {Name: "again", Label: "Again", Width: 32, Secret: true}}}) + if err != nil { + return err + } + if !ok { + continue + } + if v["pw"] != v["again"] { + s.UI.Say(view.Bad, "They differ.") + continue + } + if msg := bbs.ValidPassword(v["pw"], u.Name); msg != "" { + s.UI.Say(view.Bad, msg) + continue + } + if err := s.B.Store.SetPassword(u.ID, v["pw"]); err != nil { + return err + } + s.B.Log.Printf("%s set a new password for %s", by, u.Name) + s.UI.Say(view.Good, "Set.") + } + } +} + +// --- statistics + +// days is how many days the statistics go back. +const days = 14 + +func (s *Session) statistics() error { + s.N.Doing("Statistics") + totals, err := s.B.Store.Totals() + if err != nil { + return err + } + lines := []view.Line{ + view.V("Users:", strconv.Itoa(totals["users"])), + view.V("Messages:", strconv.Itoa(totals["messages"])), + view.V("Mail:", strconv.Itoa(totals["mail"])), + view.V("Files:", strconv.Itoa(totals["files"])), + view.V("Since start:", fmt.Sprintf("%d logins, %d posts, %d pages, %d failed logins", + s.B.Stats.Logins.Load(), s.B.Stats.Posts.Load(), s.B.Stats.Pages.Load(), s.B.Stats.LoginFailures.Load())), + } + now := time.Now() + start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).AddDate(0, 0, -(days - 1)) + for _, what := range []struct{ key, title string }{{"calls", "Calls"}, {"users", "New users"}, + {"posts", "Posts"}, {"uploads", "Uploads"}} { + ts, err := s.B.Store.Times(what.key, start) + if err != nil { + return err + } + per := make([]int, days) + for _, t := range ts { + if d := int(t.In(now.Location()).Sub(start).Hours() / 24); d >= 0 && d < days { + per[d]++ + } + } + most, total := 0, 0 + for _, n := range per { + most, total = max(most, n), total+n + } + lines = append(lines, view.L(""), view.T(view.Bright, fmt.Sprintf("%s by day (%d in %d days)", what.title, total, days))) + for d := days - 1; d >= 0; d-- { + share := 0.0 + if most > 0 { + share = float64(per[d]) / float64(most) + } + lines = append(lines, view.Line{Label: start.AddDate(0, 0, d).Format("Mon 01-02"), + Text: strconv.Itoa(per[d]), Bar: share}) + } + } + return s.UI.Show("Statistics", lines) +} + +// --- the hack log and bans + +func (s *Session) hackLog() error { + for { + s.N.Doing("Hack log") + bans := s.B.Guard.Bans() + ips := make([]string, 0, len(bans)) + for ip := range bans { + ips = append(ips, ip) + } + sort.Strings(ips) + t := &view.Table{Title: "Bans", Empty: "No address is banned.", Pick: "Number to lift its ban", + Columns: []view.Column{{Title: "Address", Width: 39}, {Title: "Until", Width: 16}}, + Actions: []view.Action{{ID: "log", Label: "Log", Key: 'L', PF: 5}}} + for i, ip := range ips { + t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), + Cells: []string{ip, bans[ip].Format("2006-01-02 15:04")}}) + } + if s.B.Guard == nil || s.B.Guard.HackLog == "" { + t.Note = []view.Line{view.T(view.Dim, "There is no hack log: [security] hack_log in bbs.conf.")} + } + c, err := s.UI.Table(t) + if err != nil || c.Action == view.Back { + return err + } + switch { + case c.Action == "log": + var ls []view.Line + for _, l := range s.B.Guard.Tail(100) { + ls = append(ls, view.L(l)) + } + if len(ls) == 0 { + ls = []view.Line{view.L("The hack log is empty.")} + } + if err := s.UI.Show("Hack log", ls); err != nil { + return err + } + case c.Action == view.Pick && c.Row >= 0: + if s.B.Guard.Unban(ips[c.Row]) { + s.B.Guard.Hack("%s ban lifted by %s", ips[c.Row], s.User.Name) + s.UI.Say(view.Good, "The ban on "+ips[c.Row]+" is lifted.") + } + } + } +} + +// --- scheduled events + +func (s *Session) eventsScreen() error { + for { + s.N.Doing("Scheduled events") + st := s.B.Events.Status() + t := &view.Table{Title: "Scheduled events", Pick: "Number to see (and run)", + Columns: []view.Column{{Title: "Event", Width: 14}, {Title: "When", Width: 18}, + {Title: "Next", Width: 11}, {Title: "Last", Wide: true}}} + for i, e := range st { + last := "not yet" + if e.Running { + last = "running" + } else if e.Last != nil { + last = e.Last.Describe() + } + t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Mark: e.Last != nil && e.Last.Err != "", + Cells: []string{e.Name, e.Schedule(), e.Next.Format("01-02 15:04"), last}}) + } + c, err := s.UI.Table(t) + if err != nil || c.Action == view.Back { + return err + } + if c.Action != view.Pick || c.Row < 0 { + continue + } + e := st[c.Row] + lines := []view.Line{view.V("Command:", strings.Join(e.Command, " ")), view.V("When:", e.Schedule())} + if e.Last != nil { + lines = append(lines, view.V("Last:", e.Last.Describe()), view.L("")) + for _, l := range strings.Split(strings.TrimRight(e.Last.Output, "\n"), "\n") { + lines = append(lines, view.L(bbs.Clean(l, 200))) + } + } + act, err := s.UI.Panel(&view.Panel{Title: "Event " + e.Name, Lines: lines, + Actions: []view.Action{{ID: "run", Label: "Run it now", Key: 'R', PF: 5, Short: "Run"}}}) + if err != nil { + return err + } + if act == "run" { + s.UI.Say(view.Plain, "Running "+e.Name+"...") + r, err := s.B.Events.RunNow(context.Background(), e.Name, s.User.Name) + switch { + case errors.Is(err, events.ErrRunning): + s.UI.Say(view.Bad, e.Name+" is running already.") + case err != nil: + s.UI.Say(view.Bad, e.Name+": "+err.Error()+".") + case r.Err != "": + s.UI.Say(view.Bad, e.Name+": "+r.Err+".") + default: + s.UI.Say(view.Good, e.Name+": done.") + } + } + } +} diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index ae8e75c..9cb621f 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "github.com/Neo-Desktop/bbs-sec/internal/door" + "github.com/Neo-Desktop/bbs-sec/internal/events" "github.com/Neo-Desktop/bbs-sec/internal/guard" "github.com/Neo-Desktop/bbs-sec/internal/screens" "log" @@ -15,6 +16,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" "github.com/Neo-Desktop/bbs-sec/internal/files" @@ -128,8 +130,12 @@ type BBS struct { ScriptsDir string // Guard keeps addresses and names out, and the hack log (nil: none) Guard *guard.Guard + // Events are the sysop's scheduled events (nil: none) + Events *events.Scheduler // Stats count logins, posts and the like Stats Stats + // sysopAway: the sysop is not to be paged (pages leave a message) + sysopAway atomic.Bool mu sync.Mutex nodes map[int]*Node @@ -160,6 +166,7 @@ type Node struct { chatOnce sync.Once cs *chatState clock *clock // the day's time limit, for a caller logged in + sysopTap tap // sysops watching the node } // ErrBusy: every node is taken. diff --git a/internal/bbs/chat.go b/internal/bbs/chat.go index 5cd4897..a22462d 100644 --- a/internal/bbs/chat.go +++ b/internal/bbs/chat.go @@ -399,7 +399,7 @@ func (n *Node) PageSysop(reason string) (string, int, error) { } n.b.mu.Unlock() for _, o := range sysops { - if !o.Busy() { + if !o.Busy() && n.b.SysopAvailable() { o.deliver(e) told++ } diff --git a/internal/bbs/custom.go b/internal/bbs/custom.go index f99449b..782c6e5 100644 --- a/internal/bbs/custom.go +++ b/internal/bbs/custom.go @@ -55,6 +55,7 @@ var MenuActions = map[string]string{ "page": "page the sysop", "callers": "the last callers", "feedback": "mail to the sysop", + "sysop": "the sysop's tools (sysops only)", "terminal": "a 3270's terminal details (nothing elsewhere)", "back": "back to the menu before", "logoff": "log off", diff --git a/internal/bbs/sysop.go b/internal/bbs/sysop.go new file mode 100644 index 0000000..c8b1ea6 --- /dev/null +++ b/internal/bbs/sysop.go @@ -0,0 +1,127 @@ +package bbs + +import ( + "errors" + "fmt" + "sync" + "time" +) + +// What the sysop does to and for other nodes: watching one, calling its +// caller into chat; and whether they are to be paged. + +// tap copies a node's output to the sysops watching it. +type tap struct { + mu sync.Mutex + echoing bool // the node's front end gives its output (a text terminal's) + watchers map[chan []byte]bool + summon string // the room the caller is called into ("": none) +} + +// Errors of watching. +var ( + ErrNoEcho = errors.New("that node's screen cannot be watched (a 3270's, or no caller yet)") + ErrSelf = errors.New("that is your own node") + ErrNotSysop = errors.New("only a sysop does that") +) + +// SetEchoing says the node's front end gives Echo what it sends. +func (n *Node) SetEchoing() { + n.sysopTap.mu.Lock() + n.sysopTap.echoing = true + n.sysopTap.mu.Unlock() +} + +// Echo gives what was sent to the node's caller to those watching it; a +// watcher too slow to keep up misses some. +func (n *Node) Echo(p []byte) { + t := &n.sysopTap + t.mu.Lock() + defer t.mu.Unlock() + if len(t.watchers) == 0 { + return + } + cp := append([]byte(nil), p...) + for ch := range t.watchers { + select { + case ch <- cp: + default: + } + } +} + +// Watch gives a sysop on node by what node num's caller is sent, until +// stop is called. +func (by *Node) Watch(num int) (<-chan []byte, func(), error) { + if u := by.User(); u == nil || !u.Sysop { + return nil, nil, ErrNotSysop + } + if num == by.Num { + return nil, nil, ErrSelf + } + o := by.b.node(num) + if o == nil { + return nil, nil, ErrNoNode + } + t := &o.sysopTap + t.mu.Lock() + defer t.mu.Unlock() + if !t.echoing { + return nil, nil, ErrNoEcho + } + ch := make(chan []byte, 256) + if t.watchers == nil { + t.watchers = map[chan []byte]bool{} + } + t.watchers[ch] = true + by.b.Log.Printf("node %d: %s watches node %d", by.Num, by.name(), num) + stop := func() { + t.mu.Lock() + delete(t.watchers, ch) + t.mu.Unlock() + } + return ch, stop, nil +} + +// Summon calls node num's caller into a private chat with the sysop on +// node by: they are told now, and taken there at their next menu. The +// room is the one by joins. +func (by *Node) Summon(num int) (string, error) { + u := by.User() + if u == nil || !u.Sysop { + return "", ErrNotSysop + } + if num == by.Num { + return "", ErrSelf + } + o := by.b.node(num) + if o == nil || o.User() == nil { + return "", ErrNoNode + } + room := pageRoom(num) + o.sysopTap.mu.Lock() + o.sysopTap.summon = room + o.sysopTap.mu.Unlock() + o.deliver(Event{Kind: Notice, Text: fmt.Sprintf("%s would like a word with you: you are going to chat.", u.Name), + Time: time.Now()}) + by.b.Log.Printf("node %d: %s calls node %d into chat", by.Num, u.Name, num) + return room, nil +} + +// Summoned is the room the caller has been called into ("": none), once. +func (n *Node) Summoned() string { + n.sysopTap.mu.Lock() + defer n.sysopTap.mu.Unlock() + r := n.sysopTap.summon + n.sysopTap.summon = "" + return r +} + +// SysopAvailable: pages reach the sysop. +func (b *BBS) SysopAvailable() bool { return !b.sysopAway.Load() } + +// SetSysopAvailable says whether pages reach the sysop. +func (b *BBS) SetSysopAvailable(on bool) { + b.sysopAway.Store(!on) + b.Log.Printf("the sysop is %s", map[bool]string{true: "available for chat", false: "not available for chat"}[on]) +} diff --git a/internal/bbs/sysop_test.go b/internal/bbs/sysop_test.go new file mode 100644 index 0000000..7b8dd97 --- /dev/null +++ b/internal/bbs/sysop_test.go @@ -0,0 +1,68 @@ +package bbs + +import ( + "strings" + "testing" +) + +func TestWatchSummonAvailable(t *testing.T) { + b, ns := chatBBS(t) + alice, bob, sysop := ns["alice"], ns["bob"], ns["sysop"] + if _, _, err := bob.Watch(alice.Num); err != ErrNotSysop { + t.Errorf("bob watches: %v", err) + } + if _, _, err := sysop.Watch(alice.Num); err != ErrNoEcho { + t.Errorf("no echo yet: %v", err) + } + if _, _, err := sysop.Watch(sysop.Num); err != ErrSelf { + t.Errorf("oneself: %v", err) + } + alice.SetEchoing() + alice.Echo([]byte("before")) + ch, stop, err := sysop.Watch(alice.Num) + if err != nil { + t.Fatal(err) + } + alice.Echo([]byte("hello")) + if got := string(<-ch); got != "hello" { + t.Errorf("watched %q", got) + } + stop() + alice.Echo([]byte("after")) + select { + case p := <-ch: + t.Errorf("after stop: %q", p) + default: + } + + room, err := sysop.Summon(alice.Num) + if err != nil || room != "sysop-1" { + t.Fatalf("summon %q %v", room, err) + } + if _, err := bob.Summon(alice.Num); err != ErrNotSysop { + t.Errorf("bob summons: %v", err) + } + if ev := alice.Pending(); len(ev) != 1 || !strings.Contains(ev[0].String(), "would like a word") { + t.Errorf("told %v", ev) + } + if alice.Summoned() != "sysop-1" || alice.Summoned() != "" { + t.Error("summoned once") + } + if _, err := alice.JoinRoom(room); err != nil { + t.Errorf("alice into the room: %v", err) + } + if _, err := sysop.JoinRoom(room); err != nil { + t.Errorf("the sysop into the room: %v", err) + } + + // pages reach no one while the sysop is away + b.SetSysopAvailable(false) + if _, told, err := bob.PageSysop("help"); err != nil || told != 0 { + t.Errorf("away: %d %v", told, err) + } + b.SetSysopAvailable(true) + bob.CancelPage() + if !b.SysopAvailable() { + t.Error("available") + } +} diff --git a/internal/events/events.go b/internal/events/events.go new file mode 100644 index 0000000..7910a9c --- /dev/null +++ b/internal/events/events.go @@ -0,0 +1,272 @@ +// Package events runs the sysop's scheduled events: programs (no shell) +// run every day at a time, or every so many minutes, each with a time +// limit, their output kept with how they ended. +package events + +import ( + "bytes" + "context" + "errors" + "fmt" + "log" + "os" + "os/exec" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// Event is a scheduled program. +type Event struct { + Name string + Command []string // the program and its arguments + At string // HH:MM, every day ("": not daily) + Every time.Duration // or this often + Timeout time.Duration // how long it may take (0: ten minutes) +} + +// Schedule is how the event's times are said. +func (e *Event) Schedule() string { + if e.At != "" { + return "daily at " + e.At + } + return "every " + e.Every.String() +} + +// Result is how a run went. +type Result struct { + Start time.Time + Took time.Duration + Err string // "": it ended well + Output string // its last lines + By string // "schedule", or who ran it +} + +// Status is an event and what is known of it. +type Status struct { + *Event + Next time.Time + Last *Result + Running bool +} + +// maxOutput is how much of a run's output is kept. +const maxOutput = 4096 + +// Scheduler runs the events. +type Scheduler struct { + Events []*Event + Log *log.Logger + + mu sync.Mutex + last map[string]*Result + running map[string]bool + started time.Time + now func() time.Time +} + +func (s *Scheduler) clock() time.Time { + if s.now != nil { + return s.now() + } + return time.Now() +} + +// ParseAt reads a time of day, HH:MM. +func ParseAt(at string) error { + t, err := time.Parse("15:04", at) + if err != nil || t.Format("15:04") != at { + return fmt.Errorf("%q is not a time of day as 03:30", at) + } + return nil +} + +// Split splits a command line into words: spaces part them, and "..." or +// '...' keep spaces in one. No shell: nothing else is special. +func Split(line string) ([]string, error) { + var out []string + var cur strings.Builder + in, quote, word := false, rune(0), false + for _, r := range line { + switch { + case in && r == quote: + in = false + case in: + cur.WriteRune(r) + case r == '"' || r == '\'': + in, quote, word = true, r, true + case r == ' ' || r == '\t': + if word { + out = append(out, cur.String()) + cur.Reset() + word = false + } + default: + cur.WriteRune(r) + word = true + } + } + if in { + return nil, errors.New("a quote is not closed") + } + if word { + out = append(out, cur.String()) + } + return out, nil +} + +// next is when an event runs next after now. +func (s *Scheduler) next(e *Event, now time.Time) time.Time { + if e.At != "" { + t, _ := time.ParseInLocation("15:04", e.At, now.Location()) + d := time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, now.Location()) + if !d.After(now) { + d = d.AddDate(0, 0, 1) + } + return d + } + from := s.started + if r := s.last[e.Name]; r != nil && r.Start.After(from) { + from = r.Start + } + n := from.Add(e.Every) + if n.Before(now) { + return now + } + return n +} + +// Status is every event's state, by name. +func (s *Scheduler) Status() []Status { + s.mu.Lock() + defer s.mu.Unlock() + now := s.clock() + if s.started.IsZero() { + s.started = now + } + var out []Status + for _, e := range s.Events { + st := Status{Event: e, Next: s.next(e, now), Running: s.running[e.Name]} + if r := s.last[e.Name]; r != nil { + cp := *r + st.Last = &cp + } + out = append(out, st) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +// Run runs the events as their times come, until ctx is done. +func (s *Scheduler) Run(ctx context.Context) { + s.mu.Lock() + if s.started.IsZero() { + s.started = s.clock() + } + nexts := map[string]time.Time{} + for _, e := range s.Events { + nexts[e.Name] = s.next(e, s.started) + } + s.mu.Unlock() + t := time.NewTicker(15 * time.Second) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + now := s.clock() + for _, e := range s.Events { + if now.Before(nexts[e.Name]) { + continue + } + go s.RunNow(ctx, e.Name, "schedule") + s.mu.Lock() + nexts[e.Name] = s.next(e, now.Add(time.Second)) + if e.Every > 0 { + nexts[e.Name] = now.Add(e.Every) + } + s.mu.Unlock() + } + } +} + +// ErrRunning: the event is running already. +var ErrRunning = errors.New("it is running already") + +// RunNow runs an event now (by: "schedule", or who asked), and waits for +// it to end. +func (s *Scheduler) RunNow(ctx context.Context, name, by string) (*Result, error) { + var e *Event + for _, x := range s.Events { + if x.Name == name { + e = x + } + } + if e == nil { + return nil, fmt.Errorf("there is no event %q", name) + } + s.mu.Lock() + if s.running == nil { + s.running, s.last = map[string]bool{}, map[string]*Result{} + } + if s.running[name] { + s.mu.Unlock() + return nil, ErrRunning + } + s.running[name] = true + s.mu.Unlock() + + timeout := e.Timeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + cctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + r := &Result{Start: s.clock(), By: by} + cmd := exec.CommandContext(cctx, e.Command[0], e.Command[1:]...) + cmd.Env = append(os.Environ(), "BBS_EVENT="+e.Name) + var out bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &out + cmd.WaitDelay = 5 * time.Second + err := cmd.Run() + r.Took = s.clock().Sub(r.Start) + if errors.Is(cctx.Err(), context.DeadlineExceeded) { + err = fmt.Errorf("stopped after %v", timeout) + } + if err != nil { + r.Err = err.Error() + } + o := out.Bytes() + if len(o) > maxOutput { + o = o[len(o)-maxOutput:] + } + r.Output = strings.ToValidUTF8(string(o), "?") + s.mu.Lock() + s.running[name] = false + s.last[name] = r + s.mu.Unlock() + if s.Log != nil { + how := "ok" + if r.Err != "" { + how = r.Err + } + s.Log.Printf("event %s (%s): %s in %v", name, by, how, r.Took.Round(time.Millisecond)) + } + return r, nil +} + +// Minutes is n minutes, for config. +func Minutes(n int) time.Duration { return time.Duration(n) * time.Minute } + +// Describe is a result in a line. +func (r *Result) Describe() string { + how := "ok" + if r.Err != "" { + how = r.Err + } + return r.Start.Format("01-02 15:04") + " " + how + " (" + strconv.FormatFloat(r.Took.Seconds(), 'f', 1, 64) + "s, " + r.By + ")" +} diff --git a/internal/events/events_test.go b/internal/events/events_test.go new file mode 100644 index 0000000..7746259 --- /dev/null +++ b/internal/events/events_test.go @@ -0,0 +1,75 @@ +package events + +import ( + "context" + "strings" + "testing" + "time" +) + +func TestSplit(t *testing.T) { + for in, want := range map[string]string{ + `/usr/bin/backup --to "/var/backups/my bbs" -v`: `/usr/bin/backup|--to|/var/backups/my bbs|-v`, + `echo 'a "b" c' d`: `echo|a "b" c|d`, + ` x `: `x`, + `x ""`: `x|`, + } { + got, err := Split(in) + if err != nil || strings.Join(got, "|") != want { + t.Errorf("%q: %q %v", in, got, err) + } + } + if _, err := Split(`echo "open`); err == nil { + t.Error("an open quote") + } + if ParseAt("03:30") != nil || ParseAt("3:30") == nil || ParseAt("25:00") == nil { + t.Error("ParseAt") + } +} + +func TestNext(t *testing.T) { + now := time.Date(2026, 10, 12, 10, 0, 0, 0, time.Local) + s := &Scheduler{started: now} + if n := s.next(&Event{At: "03:30"}, now); !n.Equal(time.Date(2026, 10, 13, 3, 30, 0, 0, time.Local)) { + t.Errorf("tomorrow %v", n) + } + if n := s.next(&Event{At: "12:00"}, now); !n.Equal(time.Date(2026, 10, 12, 12, 0, 0, 0, time.Local)) { + t.Errorf("today %v", n) + } + if n := s.next(&Event{Every: time.Hour}, now.Add(time.Minute)); !n.Equal(now.Add(time.Hour)) { + t.Errorf("every %v", n) + } +} + +func TestRun(t *testing.T) { + s := &Scheduler{Events: []*Event{ + {Name: "hello", Command: []string{"/bin/sh", "-c", `echo "hi from $BBS_EVENT"`}, Every: time.Hour}, + {Name: "fails", Command: []string{"/bin/sh", "-c", "echo oops >&2; exit 3"}, At: "04:00"}, + {Name: "slow", Command: []string{"/bin/sleep", "5"}, Every: time.Hour, Timeout: 200 * time.Millisecond}, + }} + ctx := context.Background() + r, err := s.RunNow(ctx, "hello", "sysop") + if err != nil || r.Err != "" || r.Output != "hi from hello\n" || r.By != "sysop" { + t.Errorf("hello: %+v %v", r, err) + } + r, _ = s.RunNow(ctx, "fails", "schedule") + if r.Err != "exit status 3" || r.Output != "oops\n" { + t.Errorf("fails: %+v", r) + } + done := make(chan *Result) + go func() { r, _ := s.RunNow(ctx, "slow", "x"); done <- r }() + time.Sleep(50 * time.Millisecond) + if _, err := s.RunNow(ctx, "slow", "y"); err != ErrRunning { + t.Errorf("twice: %v", err) + } + if r := <-done; !strings.Contains(r.Err, "stopped after 200ms") { + t.Errorf("slow: %+v", r) + } + if _, err := s.RunNow(ctx, "nope", "x"); err == nil { + t.Error("no such event") + } + st := s.Status() + if len(st) != 3 || st[0].Name != "fails" || st[0].Last == nil || st[0].Schedule() != "daily at 04:00" { + t.Errorf("status %+v", st) + } +} diff --git a/internal/server/config.go b/internal/server/config.go index ec07ae4..f00817d 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -7,6 +7,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/api" "net" "os" + "os/exec" "path/filepath" "strconv" "strings" @@ -15,6 +16,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/events" "github.com/Neo-Desktop/bbs-sec/internal/fido" "github.com/Neo-Desktop/bbs-sec/internal/finger" "github.com/Neo-Desktop/bbs-sec/internal/ftp" @@ -58,6 +60,7 @@ type Config struct { Listeners []*Listener Warnings []string Guard *guard.Guard // [security] + Events []*events.Event } // DefaultListeners are used when the file has no [listen] section: telnet @@ -115,6 +118,18 @@ func Load(path string) (*Config, error) { if err := c.securitySection(cf.Get("security", "")); err != nil { return nil, fmt.Errorf("[security] %w", err) } + for _, sec := range cf.All("event") { + e, err := c.event(sec) + if err != nil { + return nil, fmt.Errorf("[event %s] %w", sec.Name, err) + } + for _, o := range c.Events { + if o.Name == e.Name { + return nil, fmt.Errorf("[event %s] given twice", e.Name) + } + } + c.Events = append(c.Events, e) + } names := map[string]bool{} for _, sec := range cf.All("listen") { l, err := listener(sec) @@ -139,7 +154,7 @@ func Load(path string) (*Config, error) { } for _, s := range cf.Sections { switch s.Kind { - case "general", "security", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link", "door", "finger", "gopher", "menu", "strings", "http", "level": + case "general", "security", "event", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link", "door", "finger", "gopher", "menu", "strings", "http", "level": default: return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind) } @@ -232,6 +247,45 @@ func (c *Config) general(g *config.Section) error { return nil } +// event reads an [event NAME]: a program run daily at a time, or every so +// many minutes. +func (c *Config) event(sec *config.Section) (*events.Event, error) { + if sec.Name == "" { + return nil, errors.New("an event needs a name: [event backup]") + } + e := &events.Event{Name: strings.ToLower(sec.Name), At: sec.String("at", "")} + cmd, err := events.Split(sec.String("command", "")) + if err != nil { + return nil, fmt.Errorf("command: %v", err) + } + if len(cmd) == 0 { + return nil, errors.New("command: none given (a program and its arguments; no shell)") + } + if _, err := exec.LookPath(cmd[0]); err != nil { + c.Warnings = append(c.Warnings, fmt.Sprintf("[event %s] command: %v", e.Name, err)) + } + e.Command = cmd + mins, err := sec.Int("every", 0, 0, 7*24*60) + if err != nil { + return nil, err + } + e.Every = events.Minutes(mins) + switch { + case e.At != "" && e.Every > 0: + return nil, errors.New("at or every, not both") + case e.At != "": + if err := events.ParseAt(e.At); err != nil { + return nil, fmt.Errorf("at: %v", err) + } + case e.Every <= 0: + return nil, errors.New("at = HH:MM (daily) or every = MINUTES") + } + if e.Timeout, err = sec.Seconds("timeout", 600, 1, 24*3600); err != nil { + return nil, err + } + return e, nil +} + // securitySection reads [security]: the deny files, the hack log, bans. func (c *Config) securitySection(sec *config.Section) error { g := &guard.Guard{} diff --git a/internal/server/sysop_test.go b/internal/server/sysop_test.go new file mode 100644 index 0000000..43bc9b0 --- /dev/null +++ b/internal/server/sysop_test.go @@ -0,0 +1,97 @@ +package server + +import ( + "fmt" + "os" + "strings" + "testing" +) + +func writeFile(p, s string) error { return os.WriteFile(p, []byte(s), 0600) } +func contains(s, sub string) bool { return strings.Contains(s, sub) } +func containsAny(ss []string, sub string) bool { + return strings.Contains(strings.Join(ss, "\n"), sub) +} + +// TestSysopTools: the sysop watches a caller's screen, calls them into +// chat, and is away when they page. +func TestSysopTools(t *testing.T) { + e := start(t, nil, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"}) + sysop := login(e, "sysop", "sysoppass1") + alice := login(e, "alice", "alicepass1") + aliceNode := 0 + for _, n := range e.b.Nodes() { + if n.User == "alice" { + aliceNode = n.Num + } + } + + sysop.send("*") + sysop.expect("[W] Watch a node") + sysop.send("W") + sysop.expect("Watch which node? (its number, Enter for none): ") + sysop.send(fmt.Sprintf("%d\r", aliceNode)) + sysop.expect(fmt.Sprintf("Watching node %d", aliceNode)) + alice.send("L") + alice.expect("Last callers") + sysop.expect("Last callers") // what alice was sent + sysop.send(" ") + sysop.expect(fmt.Sprintf("Watching node %d no more.", aliceNode)) + + sysop.send("C") + sysop.expect("Chat with which node?") + sysop.send(fmt.Sprintf("%d\r", aliceNode)) + sysop.expect("is called here at their next menu") + sysop.expect("> ") + alice.expect("would like a word with you") + alice.send("\r") + alice.expect("The sysop would like a word.") + alice.expect(fmt.Sprintf("You are in sysop-%d.", aliceNode)) + sysop.expect("-> alice came in") + sysop.send("all well?\r") + alice.expect("sysop: all well?") + alice.send("/quit\r") + alice.expect("Command: ") + sysop.send("/quit\r") + sysop.expect("[A] Available: yes") + + sysop.send("A") + sysop.expect("[A] Available: no") + alice.send("S") + alice.expect("Page the sysop about (Enter to give up): ") + alice.send("a question\r") + alice.expect("The sysop is not available just now.") +} + +func TestEventConfig(t *testing.T) { + dir := t.TempDir() + load := func(body string) (*Config, error) { + p := dir + "/bbs.conf" + if err := writeFile(p, "[listen t]\ntype = telnet\naddress = :2300\n"+body); err != nil { + t.Fatal(err) + } + return Load(p) + } + c, err := load("[event backup]\ncommand = /bin/echo \"nightly backup\"\nat = 03:30\ntimeout = 60\n" + + "[event poll]\ncommand = /bin/true\nevery = 15\n") + if err != nil || len(c.Events) != 2 || c.Events[0].At != "03:30" || c.Events[0].Command[1] != "nightly backup" || + c.Events[0].Timeout.Seconds() != 60 || c.Events[1].Every.Minutes() != 15 { + t.Fatalf("%+v %v", c.Events, err) + } + c, err = load("[event x]\ncommand = /no/such/program\nevery = 5\n") + if err != nil || !containsAny(c.Warnings, "/no/such/program") { + t.Errorf("a missing program: %v %v", c.Warnings, err) + } + for body, want := range map[string]string{ + "[event x]\nevery = 5\n": "command: none given", + "[event x]\ncommand = /bin/true\n": "at = HH:MM", + "[event x]\ncommand = /bin/true\nat = 3:30\n": "not a time of day", + "[event x]\ncommand = /bin/true\nat = 03:30\nevery = 5\n": "not both", + "[event x]\ncommand = \"/bin/true\nevery = 5\n": "quote", + "[event x]\ncommand = /bin/true\nevery = 5\n[event X]\ncommand = /bin/true\nevery = 5\n": "given twice", + } { + if _, err := load(body); err == nil || !contains(err.Error(), want) { + t.Errorf("%q: %v, want %q", body, err, want) + } + } +} diff --git a/internal/store/stats.go b/internal/store/stats.go new file mode 100644 index 0000000..664a89a --- /dev/null +++ b/internal/store/stats.go @@ -0,0 +1,54 @@ +package store + +import ( + "fmt" + "time" +) + +// What Times counts: a table and its time column. +var timeColumns = map[string]string{ + "calls": "SELECT at FROM calls WHERE at >= ?", + "posts": "SELECT created FROM messages WHERE created >= ?", + "users": "SELECT created FROM users WHERE created >= ?", + "uploads": "SELECT created FROM files WHERE created >= ?", + "mail": "SELECT created FROM mail WHERE created >= ?", + "messages": "SELECT created FROM messages WHERE created >= ?", +} + +// Times are when what happened since t: calls, posts, users (made), +// uploads, mail. +func (s *Store) Times(what string, since time.Time) ([]time.Time, error) { + q, ok := timeColumns[what] + if !ok { + return nil, fmt.Errorf("no times of %q", what) + } + rows, err := s.db.Query(q, since.Unix()) + if err != nil { + return nil, err + } + defer rows.Close() + var out []time.Time + for rows.Next() { + var at int64 + if err := rows.Scan(&at); err != nil { + return nil, err + } + out = append(out, unix(at)) + } + return out, rows.Err() +} + +// Totals are how many users, messages, mail, files and calls (kept) there +// are. +func (s *Store) Totals() (map[string]int, error) { + out := map[string]int{} + for k, q := range map[string]string{"users": "SELECT COUNT(*) FROM users", "messages": "SELECT COUNT(*) FROM messages", + "mail": "SELECT COUNT(*) FROM mail", "files": "SELECT COUNT(*) FROM files", "calls": "SELECT COUNT(*) FROM calls"} { + var n int + if err := s.db.QueryRow(q).Scan(&n); err != nil { + return nil, err + } + out[k] = n + } + return out, nil +} diff --git a/internal/textui/frontend.go b/internal/textui/frontend.go index 84985aa..666d8e7 100644 --- a/internal/textui/frontend.go +++ b/internal/textui/frontend.go @@ -1,6 +1,7 @@ package textui import ( + "errors" "fmt" "strconv" "time" @@ -182,3 +183,61 @@ func (s *session) switchTerminal(id string) error { } return nil } + +// Watch shows the sysop node num's screen as it is sent, until a key or +// the caller goes. +func (s *session) Watch(num int) error { + t := s.t + ch, stop, err := s.n.Watch(num) + if err != nil { + t.Println(t.C(Red, capital(err.Error())+".")) + return nil + } + defer stop() + t.Println(t.C(Cyan, fmt.Sprintf("Watching node %d: what you see is what is sent to it. A key stops.", num))) + t.Flush() + since := time.Now() + for { + for more := true; more; { + select { + case p := <-ch: + if err := t.Raw(p); err != nil { + return err + } + default: + more = false + } + } + _, err := t.RawKey(200 * time.Millisecond) + if err == nil { + break + } + if !errors.Is(err, ErrIdle) { + return err + } + if time.Since(since) > time.Second { + since = time.Now() + if !s.online(num) { + t.Println("") + t.Println(t.C(Yellow, fmt.Sprintf("Node %d's caller is gone.", num))) + return nil + } + } + } + if t.ANSI { + t.Print("\x1b[0m") + } + t.Println("") + t.Println(t.C(Cyan, fmt.Sprintf("Watching node %d no more.", num))) + return nil +} + +// online: a caller is on the node. +func (s *session) online(num int) bool { + for _, n := range s.b.Nodes() { + if n.Num == num { + return true + } + } + return false +} diff --git a/internal/textui/term.go b/internal/textui/term.go index ac3addb..4f4c603 100644 --- a/internal/textui/term.go +++ b/internal/textui/term.go @@ -13,6 +13,7 @@ import ( "regexp" "strconv" "strings" + "sync" "time" "unicode" "unicode/utf8" @@ -82,6 +83,7 @@ type Term struct { // PausePrompt is Pause's ("": "[Press a key]") PausePrompt string + echo *echoConn // what is sent, for a sysop watching xl translator // under w: PETSCII, DEC, VT52 latin1 bool // a DEC terminal's 8-bit characters are Latin-1 sinceKey int // lines printed since a key was read @@ -152,10 +154,37 @@ func (t *Term) Raw(b []byte) error { // NewTerm makes a terminal on c, 80x24 plain ASCII until told otherwise. func NewTerm(c Conn) *Term { - return &Term{c: c, r: bufio.NewReaderSize(c, 1024), w: bufio.NewWriterSize(c, 4096), + ec := &echoConn{Conn: c} + return &Term{c: ec, echo: ec, r: bufio.NewReaderSize(c, 1024), w: bufio.NewWriterSize(ec, 4096), Cols: 80, Rows: 24, Idle: 10 * time.Minute} } +// echoConn gives what is written to the caller to Echo as well (for a +// sysop watching). +type echoConn struct { + Conn + mu sync.Mutex + echo func([]byte) +} + +func (c *echoConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + c.mu.Lock() + echo := c.echo + c.mu.Unlock() + if echo != nil && n > 0 { + echo(p[:n]) + } + return n, err +} + +// SetEcho gives f a copy of everything the terminal sends from now on. +func (t *Term) SetEcho(f func([]byte)) { + t.echo.mu.Lock() + t.echo.echo = f + t.echo.mu.Unlock() +} + // SetDeadline sets a limit for every key from now on (zero: none). func (t *Term) SetDeadline(d time.Time) { t.deadline = d } diff --git a/internal/textui/ui.go b/internal/textui/ui.go index 24eed40..0618627 100644 --- a/internal/textui/ui.go +++ b/internal/textui/ui.go @@ -37,6 +37,8 @@ var errHangup = errors.New("logged off") // goodbye. It returns when the caller logs off or goes away. func Run(b *bbs.BBS, n *bbs.Node, t *Term, o Options) error { s := &session{b: b, n: n, t: t, c: n.Caller, o: o} + t.SetEcho(n.Echo) + n.SetEchoing() t.Idle = b.IdleTimeout err := s.run() if errors.Is(err, errHangup) { diff --git a/internal/ui3270/frontend.go b/internal/ui3270/frontend.go index 989f126..78462d7 100644 --- a/internal/ui3270/frontend.go +++ b/internal/ui3270/frontend.go @@ -52,6 +52,12 @@ func (u *ui) TerminalActions() []view.Action { return nil } func (u *ui) TerminalAction(string) error { return nil } func (u *ui) TerminalInfo() error { return u.terminal() } +// Watch: a 3270 shows a node's screen no more than it shows a door's. +func (u *ui) Watch(int) error { + u.Say(view.Bad, "Watching a node is for text terminals.") + return nil +} + // Logoff: the goodbye screen. func (u *ui) Logoff() (bool, error) { u.bye()