Configuration: full-screen menus, changes held until F10

The configuration screens are menus by what a sysop looks for: Board
(names, location, postal address, dial-in numbers, internet addresses,
what callers see, menus and prompts), System (database, log, file
locations, security, scheduled events, every section), Connections and
modems (modem lines, listeners, login limits, caller ID, GeoIP), Services
(telnet, TN3270, SSH, RLogin, finger, gopher, FTP, IRC, news, the web,
MRC, FidoNet, QWK networks, doors), Users and groups (accounts and
access levels) and Maintenance (disk space, what areas keep, old
messages taken out, the image boards' archive, backups).  Running as
another user, PAM, LDAP and database and file backups are shown as not
available yet.

Nothing changes until F10 (or Save and exit): changed lines are marked
and counted; then the file is checked and written, the accounts' and
areas' changes made, and on a running BBS the live ones put in force.
F9 (or Quit without saving) leaves it all, after a yes.

view.Sheet is the full-screen page: drawn with the cursor keys on ANSI
terminals (the terminal now reads F1-F12), with fields and PF keys on a
3270, as numbered lines elsewhere.  [general] gains postal_address,
phone and addresses, in the system info and as @POSTAL@, @PHONE@ and
@ADDRESSES@.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-14 19:53:03 +00:00
1 parent 6fa851dfdb
commit d0cb9fdaae
23 files changed
+2763 -567

No files matched your search

+5
View File
@@ -12,6 +12,11 @@
name = D-Modem BBS
sysop = Sysop
;location = Somewhere, Earth
; how to reach it, for the system info (and @POSTAL@, @PHONE@, @ADDRESSES@):
; its postal address, the numbers callers dial, and its internet addresses
;postal_address = "1 Main St, Springfield"
;phone = "+1 555 0100 (300-33600), +1 555 0101 (V.92)"
;addresses = "telnet bbs.example.org, ssh bbs.example.org:2222, https://bbs.example.org/"
; the database: SQLite's file, or a PostgreSQL, MySQL or MariaDB server (whose
; password then lives here: keep this file 0640). bbs db copy moves one
; into another. See docs/wiki/Databases.md
+22 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/confedit"
"github.com/Neo-Desktop/bbs-sec/internal/confui"
"github.com/Neo-Desktop/bbs-sec/internal/server"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/textui"
)
@@ -124,9 +125,29 @@ func configScreens(path string) {
if cols, rows, err := term.GetSize(out); err == nil && cols > 0 {
t.Cols, t.Rows = cols, rows
}
var st *store.Store
ed := &confui.Editor{UI: textui.Console(b, n, t),
Tools: bbs.ConfigTools{Path: path, Check: server.Check}}
Tools: bbs.ConfigTools{Path: path, Check: server.Check},
Open: func() (*bbs.BBS, error) {
// the database the file names, as it was read
cfg, err := server.Load(path)
if err != nil {
return nil, err
}
if p := strings.TrimPrefix(cfg.Database, "sqlite:"); store.IsFile(cfg.Database) {
if _, err := os.Stat(p); err != nil {
return nil, fmt.Errorf("%s: no database yet (bbs init makes it)", p)
}
}
if st, err = store.Open(cfg.Database); err != nil {
return nil, err
}
return bbs.New(cfg.Settings, st, log.New(io.Discard, "", 0)), nil
}}
err = ed.Run()
if st != nil {
st.Close()
}
t.Flush()
term.Restore(in, old)
fmt.Println()
+44 -20
View File
@@ -47,27 +47,51 @@ trusts whoever connects, a link without a password).
## Editing it: the configuration screens
`bbs -config /etc/bbs/bbs.conf config` is screens on your terminal for the
file, the BBS running or not: its sections, each key's value with the
sample's comment on it, its default and examples, and whether it takes
effect at once or when the BBS starts again. The same screens are on the
[sysop's tools](Sysop-Tools) (`F`, Configuration), on a text terminal or a
3270.
`bbs -config /etc/bbs/bbs.conf config` is full-screen menus on your
terminal for the file and the accounts, the BBS running or not. The same
menus are on the [sysop's tools](Sysop-Tools) (`F`, Configuration): full
screen on ANSI terminals, with PF keys on a 3270, and numbered lines on a
terminal with neither.
| | key | |
|---|---|---|
| sections | `S` | the file's sections; one's keys, set ones first, then those it may have. `A` adds a key (a menu's item keys, a QWK net's conferences), `D` deletes the section (commented out, to be had back with New section), `R` renames a `[KIND NAME]` |
| a key | | `E` edits the value in place, `U` unsets it (its line commented out: the default holds), `T` takes one of the sample's examples |
| new section | `N` | a kind of section, and its name for those there may be many of. One the file has commented out (`;[http]`) is uncommented where it is, its examples below it |
| check | `C` | the file as the BBS would read it: why it would not start, or its warnings |
| view changes | `V` | what has changed since the file was read: green takes effect at once, yellow at a restart |
| write | `W` | written whole (a new file renamed over it, its permissions and owner kept), the old one as `bbs.conf.bak`. Not written if the BBS would not start with it, or if the file changed since it was read (`U` reads it again) |
| menu | what is in it |
|---|---|
| Board configuration | the BBS's name, the sysop's, the location, postal address, dial-in numbers and internet addresses; the banner, message of the day, goodbye, logo; menus and prompts |
| System configuration | the database and log; where files are kept and how large they may be; deny lists, the hack log, bans; scheduled events; every section of the file as it is |
| Connections and modems | modem lines and every listener; callers at once, logins, time-outs, lock-outs; the caller ID country and GeoIP |
| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors |
| Users and groups | the accounts (level, flags, sysop, locked, a new password; new ones; deleted ones) and the access levels |
| Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups |
Every comment and blank line stays where it was: a key changed is changed
on its own line, a new one goes below the sample's commented example of it,
or below the section's last key. With no file, the screens offer to begin
it from the sample. Values with spaces at their ends, quotes around them
or control characters are written quoted.
Running as another user and group, PAM and LDAP logins, and backups of
the database and files are shown as not available yet: they are to come.
| key | |
|---|---|
| arrows, PgUp, PgDn, Home, End | move (a letter goes to the next line beginning with it) |
| Enter | open a menu, change a value (typed on the foot line, Enter to keep it), do an action |
| Space | turn a yes/no over, or go to the next choice |
| Esc, left arrow | back |
| F1 or `?` | the whole help for the line (from bbs.conf.sample) |
| F9 | quit without saving (after a yes, if anything changed) |
| F10 | save and exit |
| `A`, `D` | add one (a listener, a door, a user ...), delete it |
On a 3270, `S` by a menu opens it, values are typed over and sent with
Enter, PF1 is help, PF3 back, PF9 and PF10 as F9 and F10. On a terminal
without ANSI, a number opens or changes a line, `S` saves and exits, `X`
leaves without saving.
Nothing changes until you save: a changed line is marked `*` and the
foot counts what is not saved. The main menu's Review changes lists it
all, and Check the configuration reads the file as the BBS would. On
saving, the file is checked first (it is not saved if the BBS would not
start with it, or if someone changed it since it was read), written whole
with its permissions and owner kept and the last one as `bbs.conf.bak`,
every comment kept where it was (a new key goes below the sample's
commented example of it); then the accounts' and areas' changes are made.
On the sysop's menu, what may change while callers are on is put in force
at once, and the screen says what waits for a restart. With no file, the
screens offer to begin it from the sample.
A key at a time, for scripts:
@@ -88,7 +112,7 @@ rest, which wait for a restart:
| section | live keys |
|---|---|
| `[general]` | `name`, `sysop`, `location`, `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`, `geoip`, `geoip_credit`, `geoip_credit_url`, `phone_country`, `new_user_level`, `validated_level` |
| `[general]` | `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`, `geoip`, `geoip_credit`, `geoip_credit_url`, `phone_country`, `new_user_level`, `validated_level` |
| `[level N]` | all, and levels added or taken out |
| `[menu NAME]`, `[strings]` | all (a caller in a menu has it until they leave it) |
| `[chan]` | all but `dir` |
+1
View File
@@ -52,6 +52,7 @@ that are filled in when shown:
| code | |
|---|---|
| `@BBS@` `@SYSOP@` `@LOCATION@` | the system |
| `@PHONE@` `@ADDRESSES@` `@POSTAL@` | how to reach it: `[general]`'s `phone`, `addresses`, `postal_address` |
| `@USER@` `@USERLOC@` | the caller's name, where they call from |
| `@CALLS@` `@POSTS@` `@LASTON@` `@SINCE@` | their calls, posts, last call, when they joined |
| `@NEWMAIL@` | their unread mail |
+1 -1
View File
@@ -6,7 +6,7 @@
| `internal/server` | listeners, session headers, rlogin, SSH, telling 3270s from the rest |
| `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 |
| `internal/confedit` | bbs.conf edited as a sysop would by hand, comments kept; the catalog of keys read from bbs.conf.sample (embedded by the root package), and which take effect at a reload |
| `internal/confui` | the configuration screens (on internal/view), for `bbs config` and the sysop's tools |
| `internal/confui` | the configuration menus (sheets of internal/view), for `bbs config` and the sysop's tools: changes held until saved |
| `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 |
+1 -1
View File
@@ -11,7 +11,7 @@ terminal.
| 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 |
| configuration | `F` | bbs.conf's sections and keys, with the sample's help: changed, checked, written, and what may change while callers are on put in force at once ([Configuration](Configuration#editing-it-the-configuration-screens)). Shown when the BBS runs with `-config` |
| configuration | `F` | the configuration menus: the board, the system, connections, services, users and groups, maintenance; nothing changes until F10 saves (F9 quits), and then what may change while callers are on is put in force at once ([Configuration](Configuration#editing-it-the-configuration-screens)). Shown when the BBS runs with `-config` |
| 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).
+9
View File
@@ -194,6 +194,15 @@ func (s *Session) info() error {
if b.Conf().Location != "" {
lines = append(lines, view.V("Location:", b.Conf().Location))
}
if c := b.Conf(); c.PostalAddress != "" {
lines = append(lines, view.V("Post:", c.PostalAddress))
}
if c := b.Conf(); c.Phone != "" {
lines = append(lines, view.V("Dial in:", c.Phone))
}
if c := b.Conf(); c.Addresses != "" {
lines = append(lines, view.V("Internet:", c.Addresses))
}
lines = append(lines,
view.V("Sysop:", b.Conf().Sysop),
view.V("Users:", strconv.Itoa(len(us))),
+2 -1
View File
@@ -99,7 +99,8 @@ func (s *Session) sysopMenu() error {
case "F":
if s.B.Config != nil {
s.N.Doing("Configuration")
err = (&confui.Editor{UI: s.UI, Tools: *s.B.Config, Who: u.Name, Log: s.B.Log.Printf}).Run()
err = (&confui.Editor{UI: s.UI, Tools: *s.B.Config, Who: u.Name, Log: s.B.Log.Printf,
Open: func() (*bbs.BBS, error) { return s.B, nil }}).Run()
}
case "A":
s.B.SetSysopAvailable(!s.B.SysopAvailable())
+3
View File
@@ -30,6 +30,9 @@ type Settings struct {
Name string // the system's name
Sysop string // the sysop's name, for the system info
Location string // where the system is
PostalAddress string // its postal address ("": not told)
Phone string // the numbers callers dial, for the system info ("": none)
Addresses string // where to reach it on the internet (telnet, SSH, web), for the system info
Banner string // shown on connect, before the login
MOTD string // shown after the login (text or file)
MOTDFile string // read at each login
+7
View File
@@ -99,6 +99,7 @@ func (n *Node) StrMarked(key string) (string, bool) {
// Vars are the @-codes' values for the node's caller:
//
// BBS SYSOP LOCATION the system
// PHONE ADDRESSES POSTAL how to reach it
// USER USERLOC CALLS POSTS the caller
// LASTON SINCE NEWMAIL
// NODE VIA BAUD ONLINE this call, and how many are on
@@ -114,6 +115,12 @@ func (n *Node) Vars() screens.Vars {
v = n.b.Conf().Sysop
case "LOCATION":
v = n.b.Conf().Location
case "PHONE":
v = n.b.Conf().Phone
case "ADDRESSES":
v = n.b.Conf().Addresses
case "POSTAL":
v = n.b.Conf().PostalAddress
case "NODE":
v = fmt.Sprint(n.Num)
case "VIA":
+1 -1
View File
@@ -246,7 +246,7 @@ func (c *Catalog) Key(kind, key string) *Key {
// what takes effect while the BBS runs (a reload: SIGHUP, or the sysop's
// Configuration); the rest when it starts again
var liveKeys = map[string]map[string]bool{
"general": set("name", "sysop", "location", "banner", "banner_file", "motd", "motd_file",
"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",
"geoip", "geoip_credit", "geoip_credit_url", "phone_country", "new_user_level",
+265 -419
View File
@@ -1,9 +1,12 @@
// Package confui is the configuration screens: bbs.conf's sections and
// keys, each with the sample file's help and when it takes effect,
// changed, checked as the BBS would read them, and written back with
// every comment kept. The same screens run on the console (bbs config,
// with the BBS stopped or not) and on the sysop's menu, where what may
// change while callers are on is put in force at once.
// Package confui is the configuration screens: menus by what a sysop
// thinks of (the board, the system, connections, services, users,
// maintenance) over bbs.conf's sections and the accounts in the database.
// Nothing is changed until the sysop saves (F10, or Save and exit on the
// main menu): then the file is checked as the BBS would read it and
// written with every comment kept, the accounts' and areas' changes are
// made, and on a running BBS what may change while callers are on is put
// in force. F9 (or Quit without saving) leaves it all as it was. The
// same screens run on the console (bbs config) and on the sysop's menu.
package confui
import (
@@ -12,7 +15,6 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
bbssec "github.com/Neo-Desktop/bbs-sec"
@@ -25,73 +27,56 @@ import (
type Editor struct {
UI view.UI
Tools bbs.ConfigTools
Who string // who edits, for the log ("": the console)
Log func(format string, a ...any) // nil: none
// Open is the BBS whose database the accounts and areas are in
// (nil, or an error: those menus say why they are not there)
Open func() (*bbs.BBS, error)
Who string // who edits, for the log ("": the console)
Log func(format string, a ...any) // nil: none
cat *confedit.Catalog
read []byte // the file as read (absent: none)
read []byte // the file as read
absent bool // there was no file: it is begun from the sample
orig *confedit.Doc
doc *confedit.Doc
db *data // the accounts and areas, as read and as changed (nil: not read yet)
crumbs []string
flash string // a word for the next screen's foot
}
// Run shows the screens until the sysop leaves them.
var (
errSave = errors.New("save") // F10: save all and leave
errQuit = errors.New("quit") // F9: leave without
errClose = errors.New("close") // the page's subject is gone: back a page
)
// Run shows the screens until the sysop saves or leaves.
func (e *Editor) Run() error {
e.cat = confedit.NewCatalog(bbssec.Sample)
if ok, err := e.load(); err != nil || !ok {
return err
}
for {
n := len(confedit.Diff(e.orig, e.doc))
changes := "View changes"
if n > 0 {
changes += fmt.Sprintf(" (%d)", n)
}
write := "Write"
if e.Tools.Reload != nil {
write = "Write and put in force"
}
k, err := e.UI.Menu(&view.Menu{Title: "Configuration: " + e.Tools.Path, Prompt: "Configuration: ",
Items: []view.Item{{Key: "S", Label: "Sections"}, {Key: "N", Label: "New section"},
{Key: "C", Label: "Check"}, {Key: "V", Label: changes}, {Key: "W", Label: write},
{Key: "U", Label: "Undo all changes"}, {Key: "Q", Label: "Quit"}}})
if err != nil {
return err
}
switch strings.ToUpper(k) {
case "S":
err = e.sections()
case "N":
err = e.newSection()
case "C":
err = e.check()
case "V":
err = e.changes()
case "W":
err = e.write()
case "U":
if n == 0 {
e.UI.Say(view.Plain, "Nothing has changed.")
continue
}
if yes, err := e.UI.Confirm(fmt.Sprintf("Forget %d changes and read the file again?", n), false); err != nil || !yes {
e.crumbs = nil
err := e.show(e.mainMenu())
switch {
case err == nil || errors.Is(err, errQuit):
if n := e.changes(); n > 0 {
yes, err := e.UI.Confirm(fmt.Sprintf("Leave without saving %d changes?", n), false)
if err != nil {
return err
}
continue
if !yes {
continue
}
}
if ok, err := e.load(); err != nil || !ok {
return nil
case errors.Is(err, errSave):
done, err := e.save()
if err != nil || done {
return err
}
case "Q", view.Back:
if n == 0 {
return nil
}
if yes, err := e.UI.Confirm(fmt.Sprintf("Leave without writing %d changes?", n), false); err != nil || yes {
return err
}
}
if err != nil {
default:
return err
}
}
@@ -130,298 +115,153 @@ func (e *Editor) load() (bool, error) {
return true, nil
}
// --- sections
// --- pages
func (e *Editor) sections() error {
// item is an entry and what it does.
type item struct {
view.Entry
open func() error // EntryMenu: another page
set func(v string) error // a value's
do func() error // EntryAction
help string // the whole help, for F1 (Entry.Help: its first line)
}
// page is a screen of items, made again each time it is drawn.
type page struct {
title string
note []view.Line
items func() []item
keys []view.Action
key func(id string) error // a key of keys
}
func (e *Editor) show(p page) error {
e.crumbs = append(e.crumbs, p.title)
defer func() { e.crumbs = e.crumbs[:len(e.crumbs)-1] }()
cursor := 0
for {
secs := e.doc.Sections()
t := &view.Table{Title: "Sections", Pick: "Number to see",
Columns: []view.Column{{Title: "Section", Width: 24}, {Title: "Keys", Width: 4, Right: true},
{Title: "What it is", Wide: true}},
Empty: "No sections: the defaults.",
Actions: []view.Action{{ID: "new", Label: "New section", Key: 'N', PF: 5, Short: "New"}}}
for i, s := range secs {
help := ""
if k := e.cat.Kind(s.Kind); k != nil {
help = firstSentence(k.Help)
}
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1),
Cells: []string{s.String(), strconv.Itoa(len(e.doc.Keys(s))), help}})
}
c, err := e.UI.Table(t)
if err != nil || c.Action == view.Back {
return err
}
switch {
case c.Action == "new":
err = e.newSection()
case c.Action == view.Pick && c.Row >= 0:
err = e.section(secs[c.Row])
its := p.items()
sh := &view.Sheet{Title: p.title, Crumbs: strings.Join(e.crumbs, " > "), Note: p.note,
Cursor: cursor, Keys: p.keys, Status: e.status()}
for _, it := range its {
sh.Entries = append(sh.Entries, it.Entry)
}
r, err := view.ShowSheet(e.UI, sh)
if err != nil {
return err
}
}
}
func (e *Editor) newSection() error {
t := &view.Table{Title: "New section", Pick: "Number of the kind",
Columns: []view.Column{{Title: "Kind", Width: 9}, {Title: "Many", Width: 4},
{Title: "What it is", Width: 0}}}
kinds := e.cat.Kinds
for i, k := range kinds {
many := ""
if k.Named {
many = "yes"
if r.Entry >= 0 && r.Entry < len(its) {
cursor = r.Entry
}
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Cells: []string{k.Name, many, firstSentence(k.Help)}})
}
c, err := e.UI.Table(t)
if err != nil || c.Action != view.Pick || c.Row < 0 {
return err
}
k := kinds[c.Row]
s := confedit.Section{Kind: k.Name}
if k.Named {
v, ok, err := e.UI.Form(&view.Form{Title: "New [" + k.Name + "]",
Intro: []view.Line{view.L("Its name (one word): [" + k.Name + " NAME]")},
Fields: []view.Field{{Name: "name", Label: "Name", Width: 32}}, Submit: "Make"})
if err != nil || !ok || strings.TrimSpace(v["name"]) == "" {
return err
}
s.Name = strings.TrimSpace(v["name"])
}
if e.doc.Has(s) {
e.UI.Say(view.Plain, s.String()+" is there already.")
} else if err := e.doc.AddSection(s); err != nil {
e.UI.Say(view.Bad, capital(err.Error())+".")
return nil
} else {
e.UI.Say(view.Good, s.String()+" made.")
}
return e.section(s)
}
// section is a section's keys: those set, then those it may have.
func (e *Editor) section(s confedit.Section) error {
for {
if !e.doc.Has(s) {
switch r.Action {
case view.Back:
return nil
}
kind := e.cat.Kind(s.Kind)
set := e.doc.Keys(s)
keys := append([]string(nil), set...)
isSet := map[string]bool{}
for _, k := range set {
isSet[k] = true
}
if kind != nil {
for _, k := range kind.Keys {
if !isSet[k.Name] {
keys = append(keys, k.Name)
}
case view.SheetSave:
return errSave
case view.SheetQuit:
return errQuit
case view.SheetHelp:
if r.Entry >= 0 && r.Entry < len(its) {
err = e.helpOf(its[r.Entry])
}
}
t := &view.Table{Title: s.String(), Pick: "Number to see or change",
Columns: []view.Column{{Title: "Key", Width: 18}, {Title: "Value", Width: 0},
{Title: "Takes effect", Width: 12, Wide: true}},
Actions: []view.Action{{ID: "add", Label: "Add a key", Key: 'A', PF: 5, Short: "Add"},
{ID: "help", Label: "Help", Key: 'H', PF: 1},
{ID: "del", Label: "Delete section", Key: 'D', PF: 9, Short: "Delete"}}}
if kind != nil && kind.Named {
t.Actions = append(t.Actions, view.Action{ID: "rename", Label: "Rename", Key: 'R', PF: 10})
}
for i, k := range keys {
v := "-"
if isSet[k] {
v, _ = e.doc.Get(s, k)
v = mask(k, v)
} else if x := e.cat.Key(s.Kind, k); x != nil && x.Default != "" {
v = "- (" + x.Default + ")"
}
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Hot: isSet[k],
Cells: []string{k, v, when(s.Kind, k)}})
}
c, err := e.UI.Table(t)
if err != nil || c.Action == view.Back {
return err
}
switch c.Action {
case view.Pick:
if c.Row >= 0 {
err = e.key(s, keys[c.Row])
if r.Entry < 0 || r.Entry >= len(its) {
continue
}
case "add":
err = e.addKey(s)
case "help":
help := "A section of its own: the BBS does not know it."
if kind != nil {
help = kind.Help
if kind.Free != "" {
help += " Its own keys: " + kind.Free + "."
switch it := its[r.Entry]; {
case it.open != nil:
err = it.open()
case it.do != nil:
err = it.do()
}
case view.SheetSet:
for id, v := range r.Values {
for _, it := range its {
if it.ID == id && it.set != nil {
if err := it.set(v); err != nil {
e.say(view.Bad, capital(err.Error())+".")
}
}
}
}
err = e.UI.Show(s.String(), wrap(help, e.width()))
case "rename":
v, ok, err := e.UI.Form(&view.Form{Title: "Rename " + s.String(),
Fields: []view.Field{{Name: "name", Label: "New name", Width: 32, Value: s.Name, Edit: true}}, Submit: "Rename"})
if err != nil {
return err
}
if ok && v["name"] != s.Name {
if err := e.doc.Rename(s, strings.TrimSpace(v["name"])); err != nil {
e.UI.Say(view.Bad, capital(err.Error())+".")
} else {
s.Name = strings.TrimSpace(v["name"])
e.changed()
}
}
case "del":
yes, err := e.UI.Confirm("Delete "+s.String()+"? (It is commented out, to be had back.)", false)
if err != nil {
return err
}
if yes {
e.doc.RemoveSection(s)
e.changed()
return nil
}
}
if err != nil {
return err
}
}
}
func (e *Editor) addKey(s confedit.Section) error {
v, ok, err := e.UI.Form(&view.Form{Title: "A key in " + s.String(),
Fields: []view.Field{{Name: "key", Label: "Key", Width: 32}, {Name: "value", Label: "Value", Width: 60, Edit: true}},
Submit: "Add"})
if err != nil || !ok {
return err
}
key := strings.ToLower(strings.TrimSpace(v["key"]))
if key == "" {
return nil
}
if e.cat.Kind(s.Kind) != nil && e.cat.Key(s.Kind, key) == nil {
yes, err := e.UI.Confirm(key+" is not a key "+s.String()+" has: add it anyway?", false)
if err != nil || !yes {
return err
}
}
if err := e.doc.Set(s, key, v["value"]); err != nil {
e.UI.Say(view.Bad, capital(err.Error())+".")
return nil
}
e.changed()
return nil
}
// key is a key: its help, value, and what it may be.
func (e *Editor) key(s confedit.Section, key string) error {
x := e.cat.Key(s.Kind, key)
for {
v, isSet := e.doc.Get(s, key)
var lines []view.Line
if isSet {
lines = append(lines, view.V("Value:", mask(key, v)))
} else {
lines = append(lines, view.V("Value:", "not set"))
}
var acts []view.Action
acts = append(acts, view.Action{ID: "edit", Label: "Edit", Key: 'E', PF: 5})
if isSet {
acts = append(acts, view.Action{ID: "unset", Label: "Unset: its default", Key: 'U', PF: 6, Short: "Unset"})
}
if x != nil {
if x.Default != "" {
lines = append(lines, view.V("Default:", x.Default))
}
if len(x.Examples) > 0 {
lines = append(lines, view.V("Examples:", strings.Join(quoted(x.Examples), ", ")))
acts = append(acts, view.Action{ID: "example", Label: "Take an example", Key: 'T', PF: 9, Short: "Example"})
}
}
lines = append(lines, view.V("Takes effect:", effect(s.Kind, key, e.Tools.Reload != nil)), view.L(""))
switch {
case x != nil && x.Help != "":
lines = append(lines, wrap(x.Help, e.width())...)
case x != nil:
if k := e.cat.Kind(s.Kind); k != nil {
lines = append(lines, wrap("(No help of its own.) "+k.Help, e.width())...)
}
default:
lines = append(lines, view.T(view.Warn, "The BBS does not know this key: a mistake?"))
if p.key != nil {
err = p.key(r.Action)
}
}
act, err := e.UI.Panel(&view.Panel{Title: s.String() + " " + key, Lines: lines, Actions: acts})
if err != nil || act == view.Back || act == "" {
if errors.Is(err, errClose) {
return nil
}
if err != nil {
return err
}
switch act {
case "edit":
f, ok, err := e.UI.Form(&view.Form{Title: s.String() + " " + key,
Fields: []view.Field{{Name: "v", Label: key, Width: 72, Value: v, Edit: true, Secret: confedit.Secret(key)}},
Submit: "Set"})
if err != nil {
return err
}
if !ok {
continue
}
nv := f["v"]
if nv == "" && isSet {
e.doc.Unset(s, key)
e.UI.Say(view.Plain, key+": unset, its default holds.")
} else if nv != v || !isSet {
if err := e.doc.Set(s, key, nv); err != nil {
e.UI.Say(view.Bad, capital(err.Error())+".")
continue
}
}
e.changed()
case "unset":
e.doc.Unset(s, key)
e.changed()
case "example":
ex := x.Examples
if len(ex) > 1 {
t := &view.Table{Title: key + ": examples", Pick: "Number to take",
Columns: []view.Column{{Title: "Value"}}}
for i, v := range ex {
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Cells: []string{v}})
}
c, err := e.UI.Table(t)
if err != nil {
return err
}
if c.Action != view.Pick || c.Row < 0 {
continue
}
ex = ex[c.Row:]
}
if err := e.doc.Set(s, key, ex[0]); err != nil {
e.UI.Say(view.Bad, capital(err.Error())+".")
continue
}
e.changed()
}
}
}
// changed: the file as it now is is checked, and anything that would stop
// the BBS starting said at once.
func (e *Editor) changed() {
func (e *Editor) helpOf(it item) error {
help := it.help
if help == "" {
help = it.Help
}
if help == "" {
help = "No help for this."
}
lines := wrap(help, e.width())
if it.Note != "" {
lines = append(lines, view.L(""), view.T(view.Dim, "Takes effect: "+it.Note))
}
return e.UI.Show(it.Label, lines)
}
// say puts a word at the foot of the next screen.
func (e *Editor) say(tone view.Tone, msg string) {
e.flash = msg
if _, ok := e.UI.(view.SheetUI); !ok {
e.UI.Say(tone, msg)
e.flash = ""
}
}
func (e *Editor) status() string {
if e.flash != "" {
s := e.flash
e.flash = ""
return s
}
switch n := e.changes(); n {
case 0:
return ""
case 1:
return "1 change not saved"
default:
return fmt.Sprintf("%d changes not saved", n)
}
}
// changes counts what saving would do.
func (e *Editor) changes() int {
n := len(confedit.Diff(e.orig, e.doc))
if e.absent && n == 0 {
n = 1 // the file itself
}
if e.db != nil {
n += len(e.db.ops())
}
return n
}
// --- checking, changes, saving
// checkDoc: anything that would stop the BBS starting said at once.
func (e *Editor) checkDoc() {
if e.Tools.Check == nil {
return
}
if _, err := e.Tools.Check(e.doc.Bytes()); err != nil {
e.UI.Say(view.Bad, "The BBS would not take this: "+err.Error()+".")
e.say(view.Bad, "The BBS would not take this: "+err.Error()+".")
}
}
// --- checking, changes, writing
func (e *Editor) check() error {
if e.Tools.Check == nil {
return nil
@@ -439,16 +279,106 @@ func (e *Editor) check() error {
return e.UI.Show("Check", lines)
}
func (e *Editor) changes() error {
ch := confedit.Diff(e.orig, e.doc)
if len(ch) == 0 {
e.UI.Say(view.Plain, "Nothing has changed.")
return nil
// review shows what saving would do.
func (e *Editor) review() error {
lines := e.changeLines()
if len(lines) == 0 {
lines = []view.Line{view.L("Nothing has changed.")}
}
return e.UI.Show("Changes", e.changeLines(ch))
return e.UI.Show("Changes not saved", lines)
}
func (e *Editor) changeLines(ch []confedit.Change) []view.Line {
func (e *Editor) changeLines() []view.Line {
var lines []view.Line
for _, c := range confedit.Diff(e.orig, e.doc) {
if c.Live() {
lines = append(lines, view.T(view.Good, c.String()))
} else {
lines = append(lines, view.T(view.Warn, c.String()+" (at a restart)"))
}
}
if e.db != nil {
for _, o := range e.db.ops() {
lines = append(lines, view.T(view.Good, o.desc))
}
}
return lines
}
// save writes the file and makes the database's changes: true when it is
// done (the screens close), false when it could not be (they stay).
func (e *Editor) save() (bool, error) {
ch := confedit.Diff(e.orig, e.doc)
var ops []op
if e.db != nil {
ops = e.db.ops()
}
if len(ch) == 0 && !e.absent && len(ops) == 0 {
return true, nil
}
data := e.doc.Bytes()
var lines []view.Line
if len(ch) > 0 || e.absent {
if e.Tools.Check != nil {
if _, err := e.Tools.Check(data); err != nil {
e.say(view.Bad, "Not saved: the BBS would not start: "+err.Error()+".")
return false, nil
}
}
disk, err := os.ReadFile(e.Tools.Path)
if e.absent && err == nil || !e.absent && (err != nil || !bytes.Equal(disk, e.read)) {
e.say(view.Bad, "Not saved: "+e.Tools.Path+" has changed since it was read. Quit, and run it again.")
return false, nil
}
if err := confedit.WriteFile(e.Tools.Path, data, e.read, e.absent); err != nil {
e.say(view.Bad, "Not saved: "+err.Error()+".")
return false, nil
}
var cs []string
for _, c := range ch {
cs = append(cs, c.String())
}
e.log("configuration: %s written by %s: %s", e.Tools.Path, e.who(), strings.Join(cs, "; "))
lines = append(lines, view.T(view.Good, "Written: "+e.Tools.Path+" (the last as "+filepath.Base(e.Tools.Path)+".bak)."))
e.read, e.absent = data, false
}
for _, o := range ops {
if err := o.run(); err != nil {
lines = append(lines, view.T(view.Bad, o.desc+": "+err.Error()))
continue
}
e.log("configuration: %s by %s", o.desc, e.who())
lines = append(lines, view.T(view.Good, o.desc))
}
if len(ch) > 0 {
if e.Tools.Reload == nil {
lines = append(lines, view.L(""),
view.L("A BBS running puts the green changes in force at a reload (systemctl reload"),
view.L("bbs, or SIGHUP); the yellow ones when it starts again."), view.L(""))
lines = append(lines, e.diffLines(ch)...)
} else {
applied, restart, err := e.Tools.Reload()
if err != nil {
lines = append(lines, view.T(view.Bad, "Not put in force: "+err.Error()))
}
if len(applied) > 0 {
lines = append(lines, view.L(""), view.T(view.Bright, "In force now:"))
for _, a := range applied {
lines = append(lines, view.T(view.Good, " "+a))
}
}
if len(restart) > 0 {
lines = append(lines, view.L(""), view.T(view.Bright, "When the BBS starts again:"))
for _, r := range restart {
lines = append(lines, view.T(view.Warn, " "+r))
}
}
}
}
return true, e.UI.Show("Saved", lines)
}
func (e *Editor) diffLines(ch []confedit.Change) []view.Line {
var lines []view.Line
for _, c := range ch {
if c.Live() {
@@ -460,66 +390,17 @@ func (e *Editor) changeLines(ch []confedit.Change) []view.Line {
return lines
}
func (e *Editor) write() error {
ch := confedit.Diff(e.orig, e.doc)
if len(ch) == 0 && !e.absent {
e.UI.Say(view.Plain, "Nothing has changed.")
return nil
}
data := e.doc.Bytes()
if e.Tools.Check != nil {
if _, err := e.Tools.Check(data); err != nil {
e.UI.Say(view.Bad, "Not written: the BBS would not start: "+err.Error()+".")
return nil
}
}
disk, err := os.ReadFile(e.Tools.Path)
if e.absent && err == nil || !e.absent && (err != nil || !bytes.Equal(disk, e.read)) {
e.UI.Say(view.Bad, "Not written: "+e.Tools.Path+" has changed since it was read. Undo (U) reads it again.")
return nil
}
if err := confedit.WriteFile(e.Tools.Path, data, e.read, e.absent); err != nil {
e.UI.Say(view.Bad, "Not written: "+err.Error()+".")
return nil
}
func (e *Editor) log(format string, a ...any) {
if e.Log != nil {
who := e.Who
if who == "" {
who = "the console"
}
var cs []string
for _, c := range ch {
cs = append(cs, c.String())
}
e.Log("configuration: %s written by %s: %s", e.Tools.Path, who, strings.Join(cs, "; "))
e.Log(format, a...)
}
e.read, e.absent = data, false
e.orig, _ = confedit.Parse(data)
lines := []view.Line{view.T(view.Good, "Written ("+e.Tools.Path+"; the last as "+filepath.Base(e.Tools.Path)+".bak).")}
if e.Tools.Reload == nil {
lines = append(lines, view.L(""),
view.L("A BBS running takes the changes marked live at a reload (systemctl reload bbs,"),
view.L("or SIGHUP); the rest when it starts again."), view.L(""))
lines = append(lines, e.changeLines(ch)...)
return e.UI.Show("Written", lines)
}
func (e *Editor) who() string {
if e.Who == "" {
return "the console"
}
applied, restart, err := e.Tools.Reload()
if err != nil {
lines = append(lines, view.T(view.Bad, "Not put in force: "+err.Error()))
}
if len(applied) > 0 {
lines = append(lines, view.L(""), view.T(view.Bright, "In force now:"))
for _, a := range applied {
lines = append(lines, view.T(view.Good, " "+a))
}
}
if len(restart) > 0 {
lines = append(lines, view.L(""), view.T(view.Bright, "When the BBS starts again:"))
for _, r := range restart {
lines = append(lines, view.T(view.Warn, " "+r))
}
}
return e.UI.Show("Written", lines)
return e.Who
}
// --- words
@@ -531,41 +412,6 @@ func (e *Editor) width() int {
return 74
}
func when(kind, key string) string {
if confedit.Live(kind, key) {
return "live"
}
return "restart"
}
func effect(kind, key string, online bool) string {
switch {
case !confedit.Live(kind, key):
return "when the BBS starts again"
case online:
return "at once, when written"
}
return "when written, at a reload (SIGHUP)"
}
func mask(key, v string) string {
if confedit.Secret(key) && v != "" {
return "********"
}
return v
}
func quoted(vs []string) []string {
out := make([]string, len(vs))
for i, v := range vs {
out[i] = confedit.Quote(v)
if out[i] == "" {
out[i] = `""`
}
}
return out
}
func firstSentence(s string) string {
if i := strings.Index(s, ". "); i > 0 {
return s[:i+1]
+301 -84
View File
@@ -2,6 +2,8 @@ package confui
import (
"errors"
"io"
"log"
"os"
"path/filepath"
"strings"
@@ -9,49 +11,69 @@ import (
bbssec "github.com/Neo-Desktop/bbs-sec"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
// script is a view.UI that answers from a list, and keeps what it was
// told.
// step is the sysop's doing on a sheet (or a confirm, a form).
type step func(t *testing.T, sh *view.Sheet) view.SheetResult
// script is a view.UI (and SheetUI) that does what its steps say, and
// keeps what it was told.
type script struct {
t *testing.T
answers []any // string (a Menu's key, a Panel's action), view.Choice, map[string]string, bool
said []string
t *testing.T
steps []step
confirms []bool
forms []map[string]string
said []string
sheets []string // the crumbs of each sheet drawn
}
func (s *script) next() any {
func (s *script) Sheet(sh *view.Sheet) (view.SheetResult, error) {
s.t.Helper()
if len(s.answers) == 0 {
s.t.Fatal("out of answers")
s.sheets = append(s.sheets, sh.Crumbs)
if sh.Status != "" {
s.said = append(s.said, sh.Status)
}
a := s.answers[0]
s.answers = s.answers[1:]
return a
if len(s.steps) == 0 {
s.t.Fatalf("out of steps at %s", sh.Crumbs)
}
st := s.steps[0]
s.steps = s.steps[1:]
return st(s.t, sh), nil
}
func (s *script) PageSize() int { return 20 }
func (s *script) Narrow() bool { return false }
func (s *script) Menu(m *view.Menu) (string, error) {
return s.next().(string), nil
}
func (s *script) PageSize() int { return 20 }
func (s *script) Narrow() bool { return false }
func (s *script) Menu(m *view.Menu) (string, error) { return view.Back, nil }
func (s *script) Table(t *view.Table) (view.Choice, error) {
return s.next().(view.Choice), nil
return view.Choice{Action: view.Back}, nil
}
func (s *script) Message(m *view.Message) (string, error) { return view.Back, nil }
func (s *script) Panel(p *view.Panel) (string, error) { return view.Back, nil }
func (s *script) Edit(d *view.Draft) (bool, error) { return false, nil }
func (s *script) Say(tn view.Tone, msg string) { s.said = append(s.said, msg) }
func (s *script) Form(f *view.Form) (map[string]string, bool, error) {
return s.next().(map[string]string), true, nil
if len(s.forms) == 0 {
s.t.Fatalf("out of forms at %s", f.Title)
}
v := s.forms[0]
s.forms = s.forms[1:]
return v, true, nil
}
func (s *script) Panel(p *view.Panel) (string, error) { return s.next().(string), nil }
func (s *script) Edit(d *view.Draft) (bool, error) { return false, nil }
func (s *script) Confirm(q string, def bool) (bool, error) {
s.said = append(s.said, q)
return s.next().(bool), nil
if len(s.confirms) == 0 {
s.t.Fatalf("out of confirms at %q", q)
}
a := s.confirms[0]
s.confirms = s.confirms[1:]
return a, nil
}
func (s *script) Say(tn view.Tone, msg string) { s.said = append(s.said, msg) }
func (s *script) Show(title string, ls []view.Line) error {
s.said = append(s.said, title)
for _, l := range ls {
s.said = append(s.said, l.Text)
s.said = append(s.said, l.Label+l.Text)
}
return nil
}
@@ -60,98 +82,258 @@ func (s *script) told(sub string) bool {
return strings.Contains(strings.Join(s.said, "\n"), sub)
}
const file = "[general]\nname = Test BBS\n\n[listen telnet]\ntype = telnet\naddress = :2300\n"
func pick(row int) view.Choice { return view.Choice{Action: view.Pick, Row: row} }
var back = view.Choice{Action: view.Back}
// rename: Sections, [general], name, Edit to v, back out to the menu
func rename(v string) []any {
return []any{"S", pick(0), pick(0), "edit", map[string]string{"v": v}, view.Back, back, back}
// entry is the index of the entry labelled label.
func entry(t *testing.T, sh *view.Sheet, label string) int {
t.Helper()
for i, e := range sh.Entries {
if e.Label == label {
return i
}
}
var ls []string
for _, e := range sh.Entries {
ls = append(ls, e.Label)
}
t.Fatalf("%s: no %q in %q", sh.Crumbs, label, ls)
return -1
}
func TestWrite(t *testing.T) {
p := filepath.Join(t.TempDir(), "bbs.conf")
os.WriteFile(p, []byte(file), 0o600)
var checked []byte
check := func(data []byte) ([]string, error) {
checked = data
if strings.Contains(string(data), "name = bad") {
return nil, errors.New("[general] name: bad")
func open(label string) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult {
return view.SheetResult{Action: view.Pick, Entry: entry(t, sh, label)}
}
}
func set(label, v string) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult {
i := entry(t, sh, label)
return view.SheetResult{Action: view.SheetSet, Entry: i, Values: map[string]string{sh.Entries[i].ID: v}}
}
}
// expect checks an entry as drawn, and goes on with next.
func expect(label, value string, changed bool, next step) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult {
e := sh.Entries[entry(t, sh, label)]
if e.Value != value || e.Changed != changed {
t.Errorf("%s %s: %q changed %v, want %q %v", sh.Crumbs, label, e.Value, e.Changed, value, changed)
}
return []string{"a warning"}, nil
return next(t, sh)
}
}
func key(action string) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult { return view.SheetResult{Action: action} }
}
var (
back = key(view.Back)
save = key(view.SheetSave)
quit = key(view.SheetQuit)
)
const file = "[general]\nname = Test BBS\n; how to reach it\n;phone = 555 0100\n\n[listen telnet]\ntype = telnet\naddress = :2300\n"
func writeConf(t *testing.T) string {
p := filepath.Join(t.TempDir(), "bbs.conf")
if err := os.WriteFile(p, []byte(file), 0o600); err != nil {
t.Fatal(err)
}
return p
}
func check(data []byte) ([]string, error) {
if strings.Contains(string(data), "max_nodes = lots") {
return nil, errors.New("[general] max_nodes: \"lots\" is not a number")
}
return []string{"a warning"}, nil
}
// TestSaveAndExit: changes wait for F10, then the file is written whole
// (comments kept, the last as .bak) and put in force.
func TestSaveAndExit(t *testing.T) {
p := writeConf(t)
reloaded := false
reload := func() ([]string, []string, error) {
reloaded = true
return []string{"~[general] name = New BBS (was Test BBS)"}, nil, nil
}
ui := &script{t: t}
ui.answers = append(rename("bad"), "W")
ui.answers = append(ui.answers, rename("New BBS")...)
ui.answers = append(ui.answers, "C", "W", "Q")
e := &Editor{UI: ui, Tools: bbs.ConfigTools{Path: p, Check: check, Reload: reload}}
ui := &script{t: t, steps: []step{
open("Board configuration"),
set("BBS name", "New BBS"),
set("Dial-in numbers", "+1 555 0100"),
expect("BBS name", "New BBS", true, func(t *testing.T, sh *view.Sheet) view.SheetResult {
if data, _ := os.ReadFile(p); string(data) != file {
t.Error("written before the save")
}
if sh.Status != "2 changes not saved" {
t.Errorf("status %q", sh.Status)
}
return save(t, sh)
}),
}}
e := &Editor{UI: ui, Tools: bbs.ConfigTools{Path: p, Check: check,
Reload: func() ([]string, []string, error) { reloaded = true; return []string{"in force"}, nil, nil }}}
if err := e.Run(); err != nil {
t.Fatal(err)
}
if !ui.told("The BBS would not take this: [general] name: bad") || !ui.told("Not written: the BBS would not start") {
t.Errorf("a bad value not refused: %q", ui.said)
}
if !ui.told("Warning: a warning") || !reloaded || !ui.told("In force now:") {
t.Errorf("said %q", ui.said)
}
data, _ := os.ReadFile(p)
if string(data) != strings.Replace(file, "Test BBS", "New BBS", 1) || string(checked) != string(data) {
want := strings.Replace(strings.Replace(file, "Test BBS", "New BBS", 1), ";phone = 555 0100\n", ";phone = 555 0100\nphone = +1 555 0100\n", 1)
if string(data) != want {
t.Errorf("written:\n%s", data)
}
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
t.Errorf("mode %v", fi.Mode())
}
if old, _ := os.ReadFile(p + ".bak"); string(old) != file {
t.Errorf(".bak:\n%s", old)
}
if !reloaded || !ui.told("In force now:") || !ui.told("Saved") {
t.Errorf("said %q", ui.said)
}
}
// TestQuitWithoutSaving: F9 asks, and then nothing is written; no keeps
// the screens open.
func TestQuitWithoutSaving(t *testing.T) {
p := writeConf(t)
ui := &script{t: t, confirms: []bool{false, true}, steps: []step{
open("Board configuration"), set("BBS name", "Gone BBS"), quit,
// not yet: back at the main menu, the change kept
open("Board configuration"), expect("BBS name", "Gone BBS", true, back),
open("Quit without saving (F9)"),
}}
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil {
t.Fatal(err)
}
if data, _ := os.ReadFile(p); string(data) != file {
t.Errorf("written:\n%s", data)
}
if !ui.told("Leave without saving 1 changes?") {
t.Errorf("said %q", ui.said)
}
if _, err := os.Stat(p + ".bak"); err == nil {
t.Error("a .bak")
}
}
// TestBadNotSaved: a file the BBS would not start with is said at once,
// and not saved until it is put right.
func TestBadNotSaved(t *testing.T) {
p := writeConf(t)
ui := &script{t: t, steps: []step{
open("Connections and modems"), set("Callers at once", "lots"), save,
open("Connections and modems"), set("Callers at once", "50"), save,
}}
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p, Check: check}}).Run(); err != nil {
t.Fatal(err)
}
if !ui.told("The BBS would not take this") || !ui.told("Not saved: the BBS would not start") {
t.Errorf("said %q", ui.said)
}
if data, _ := os.ReadFile(p); !strings.Contains(string(data), "max_nodes = 50\n") {
t.Errorf("written:\n%s", data)
}
}
// TestChangedOnDisk: a file changed by another since it was read is not
// written over.
// saved over.
func TestChangedOnDisk(t *testing.T) {
p := filepath.Join(t.TempDir(), "bbs.conf")
os.WriteFile(p, []byte(file), 0o600)
// the sysop edits by hand meanwhile: when the key's panel is left
byHand := func() any {
os.WriteFile(p, []byte(file+"\n; by hand\n"), 0o600)
return view.Back
}
ui := &script{t: t, answers: []any{"S", pick(0), pick(0), "edit", map[string]string{"v": "New BBS"},
byHand, back, back, "W", "Q", true}}
e := &Editor{UI: &hook{ui}, Tools: bbs.ConfigTools{Path: p}}
if err := e.Run(); err != nil {
p := writeConf(t)
ui := &script{t: t, confirms: []bool{true}, steps: []step{
open("Board configuration"),
func(t *testing.T, sh *view.Sheet) view.SheetResult {
os.WriteFile(p, []byte(file+"; by hand\n"), 0o600)
return set("BBS name", "New BBS")(t, sh)
},
save, quit,
}}
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil {
t.Fatal(err)
}
if !ui.told("has changed since it was read") || !ui.told("Leave without writing 1 changes?") {
if !ui.told("has changed since it was read") {
t.Errorf("said %q", ui.said)
}
if data, _ := os.ReadFile(p); !strings.Contains(string(data), "by hand") {
t.Error("written over")
t.Error("saved over")
}
}
// hook runs an answer that is a func when its turn comes.
type hook struct{ *script }
// TestServices: a server turned on (its section uncommented where it
// was), a listener added, and one's TN3270 turned off.
func TestServices(t *testing.T) {
p := writeConf(t)
os.WriteFile(p, []byte(file+"\n; finger\n;[finger]\n;address = :79\n"), 0o600)
ui := &script{t: t, forms: []map[string]string{{"name": "ssh"}}, steps: []step{
open("Services"),
open("Finger"), expect("Enabled", "no", false, set("Enabled", "yes")), set("online", "no"), back,
open("SSH"), key("add"),
expect("type", "ssh", true, set("address", ":2222")), back, back,
open("TN3270"), set("[listen telnet] takes 3270s", "no"), back,
expect("Telnet", "1 listener", false, back),
save,
}}
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(p)
for _, want := range []string{"\n[finger]\n;address = :79\nonline = no\n", "[listen ssh]\naddress = :2222\ntype = ssh\n",
"address = :2300\ntn3270 = no\n"} {
if !strings.Contains(string(data), want) {
t.Errorf("no %q in:\n%s", want, data)
}
}
}
func (h *hook) Panel(p *view.Panel) (string, error) {
if f, ok := h.answers[0].(func() any); ok {
h.answers = h.answers[1:]
return f().(string), nil
// TestAccounts: accounts changed, made and deleted on the screens are so
// in the database only at the save.
func TestAccounts(t *testing.T) {
p := writeConf(t)
st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db"))
if err != nil {
t.Fatal(err)
}
defer st.Close()
st.CreateUser("sysop", "sysoppass1", "", true)
alice, _ := st.CreateUser("alice", "alicepass1", "", false)
st.CreateUser("bob", "bobpass123", "", false)
b := bbs.New(bbs.Defaults(), st, log.New(io.Discard, "", 0))
ui := &script{t: t, forms: []map[string]string{{"name": "carol", "pw": "carolpass1"}}, steps: []step{
open("Users and groups"), open("User accounts"),
open("alice"), set("Level", "30"), set("Flags", "ba"), set("Locked out", "yes"), back,
open("bob"), open("Delete this user"), back,
key("add"), back,
// the sysop's own: not to be locked by themselves
open("sysop"), func(t *testing.T, sh *view.Sheet) view.SheetResult {
if !sh.Entries[entry(t, sh, "Locked out")].Disabled {
t.Error("the sysop may lock themselves out")
}
if u, _ := st.UserByName("alice"); u.Level != alice.Level || u.Locked {
t.Error("changed before the save")
}
return save(t, sh)
},
}}
e := &Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}, Who: "sysop", Open: func() (*bbs.BBS, error) { return b, nil }}
if err := e.Run(); err != nil {
t.Fatal(err)
}
if u, _ := st.UserByName("alice"); u.Level != 30 || u.Flags != "AB" || !u.Locked {
t.Errorf("alice: %+v", u)
}
if _, err := st.UserByName("bob"); err == nil {
t.Error("bob is there")
}
if u, err := st.UserByName("carol"); err != nil || u.Level != 20 {
t.Errorf("carol: %+v %v", u, err)
} else if _, err := st.CheckPassword("carol", "carolpass1"); err != nil {
t.Errorf("carol's password: %v", err)
}
if !ui.told("user alice: level 30") || !ui.told("user bob: deleted") {
t.Errorf("said %q", ui.said)
}
if data, _ := os.ReadFile(p); string(data) != file {
t.Error("the file written for no change of its own")
}
return h.script.Panel(p)
}
// TestFromSample: with no file, the sample is begun from.
func TestFromSample(t *testing.T) {
p := filepath.Join(t.TempDir(), "bbs.conf")
ui := &script{t: t, answers: []any{true, "W", "Q"}}
ui := &script{t: t, confirms: []bool{true}, steps: []step{save}}
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil {
t.Fatal(err)
}
@@ -161,7 +343,42 @@ func TestFromSample(t *testing.T) {
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o640 {
t.Errorf("mode %v", fi.Mode())
}
if _, err := os.Stat(p + ".bak"); err == nil {
t.Error("a .bak of nothing")
}
// TestEveryMenu: every menu and page opens on the sample, and comes back.
func TestEveryMenu(t *testing.T) {
p := filepath.Join(t.TempDir(), "bbs.conf")
os.WriteFile(p, bbssec.Sample, 0o600)
var steps []step
var walk func(depth int) step
// open each menu entry of a sheet in turn, depth first, then back
seen := map[string]bool{}
walk = func(depth int) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult {
for i, e := range sh.Entries {
k := sh.Crumbs + "/" + e.Label
if e.Kind != view.EntryMenu || seen[k] || depth > 4 {
continue
}
seen[k] = true
// after it opens: walk it; then this sheet again
ui := currentUI
ui.steps = append([]step{walk(depth + 1), walk(depth)}, ui.steps...)
return view.SheetResult{Action: view.Pick, Entry: i}
}
return back(t, sh)
}
}
steps = append(steps, walk(0))
ui := &script{t: t, steps: steps}
currentUI = ui
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil {
t.Fatal(err)
}
t.Logf("%d menus opened", len(seen))
if len(seen) < 30 {
t.Errorf("only %d menus opened", len(seen))
}
}
var currentUI *script
+400
View File
@@ -0,0 +1,400 @@
package confui
import (
"fmt"
"sort"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/confedit"
"github.com/Neo-Desktop/bbs-sec/internal/forum"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
// sec is a section by kind and name.
func sec(kind string, name ...string) confedit.Section {
s := confedit.Section{Kind: kind}
if len(name) > 0 {
s.Name = name[0]
}
return s
}
// choices are the values some keys take (by "kind.key"); "" is the
// default, the key unset.
var choices = map[string][]string{
"listen.type": {"telnet", "raw", "rlogin", "ssh"},
"listen.ansi": {"auto", "yes", "no"},
"listen.utf8": {"auto", "yes", "no"},
"listen.sixel": {"auto", "yes", "no"},
"listen.vt": {"auto", "yes", "no"},
"listen.rip": {"auto", "yes", "no"},
"listen.petscii": {"no", "auto", "yes"},
"ftp.tls": {"required", "implicit", "optional", "no"},
"nntp.tls": {"no", "optional", "required", "implicit"},
"nntp.read": {"anyone", "users"},
"peer.tls": {"no", "starttls", "implicit"},
"qwknet.tls": {"explicit", "implicit", "no"},
"chan.captcha_level": {"easy", "normal", "hard"},
"chan.style": {"", "yotsuba", "yotsuba-b", "futaba", "burichan", "photon", "tomorrow"},
"fido.charset": {"cp437", "utf-8"},
"door.charset": {"cp437", "utf-8", "raw"},
"door.type": {"", "telnet", "rlogin", "bbslink", "doorparty"},
"link.packer": {"zip", "arc", "arj", "lha", "none"},
}
func init() {
var themes []string
for _, t := range forum.Themes {
themes = append(themes, t.Name)
}
choices["http.forum_theme"] = themes
}
// labels are keys' names as a sysop reads them, where the key's own is
// not plain enough
var labels = map[string]string{
"general.name": "BBS name", "general.sysop": "Sysop's name", "general.location": "Location",
"general.postal_address": "Postal address", "general.phone": "Dial-in numbers",
"general.addresses": "Internet addresses", "general.qwk_id": "QWK packet name",
"general.banner": "Banner (before login)", "general.banner_file": "Banner file",
"general.motd": "Message of the day", "general.motd_file": "Message of the day file",
"general.goodbye": "Goodbye", "general.new_users": "New users may sign up",
"general.logo": "Logo (PNG)", "general.database": "Database", "general.log": "Log",
"general.files_dir": "File areas' files", "general.max_file_size": "Largest file",
"general.upload_quota": "Uploads a day (each)", "general.screens_dir": "Display files",
"general.scripts_dir": "Scripts", "general.max_nodes": "Callers at once",
"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.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": "Logo as programmed symbols", "general.tn3270_vector": "Logo as vector graphics",
"general.tn3270_logo": "3270 logo (PNG)", "general.page_command": "Page command",
"security.deny_file": "Addresses refused (file)", "security.name_deny_file": "Names refused (file)",
"security.hack_log": "Hack log", "security.ban_minutes": "Ban after a lock-out (min)",
"chan.dir": "Image boards' files", "fido.dir": "FidoNet's packets",
}
func labelOf(kind, key string) string {
if l, ok := labels[kind+"."+key]; ok {
return l
}
return key
}
// field is an item for a key of a section: its value as it is now
// (marked if not saved), its help, when it takes effect; set or unset as
// it is changed (in the file as it will be written: nothing is saved
// until the sysop says).
func (e *Editor) field(s confedit.Section, key string, label ...string) item {
x := e.cat.Key(s.Kind, key)
v, _ := e.doc.Get(s, key)
ov, _ := e.orig.Get(s, key)
it := item{Entry: view.Entry{ID: s.String() + " " + key, Kind: view.EntryText, Label: labelOf(s.Kind, key),
Value: v, Changed: v != ov || e.doc.Has(s) != e.orig.Has(s) && v != "", Secret: confedit.Secret(key)}}
if len(label) > 0 {
it.Label = label[0]
}
if x != nil {
it.help = x.Help
it.Help = firstSentence(x.Help)
if x.Default != "" && !strings.ContainsAny(x.Default, ".:/") {
it.Default = x.Default
}
if bool := isBool(x); bool {
it.Kind = view.EntryBool
}
}
if it.Default == "" && v == "" {
it.Default = "default"
}
if cs, ok := choices[s.Kind+"."+key]; ok {
it.Kind, it.Choices = view.EntryChoice, cs
}
if !confedit.Live(s.Kind, key) {
it.Note = "restart"
}
it.set = func(nv string) error {
nv = strings.TrimSpace(nv)
if it.Kind == view.EntryBool && nv != "" && nv != "yes" && nv != "no" {
return fmt.Errorf("%s: yes or no", it.Label)
}
if it.Kind == view.EntryChoice && nv != "" && !contains(it.Choices, nv) {
return fmt.Errorf("%s: one of %s", it.Label, strings.Join(it.Choices, ", "))
}
if nv == "" {
e.doc.Unset(s, key)
} else if err := e.doc.Set(s, key, nv); err != nil {
return err
}
e.checkDoc()
return nil
}
return it
}
func isBool(x *confedit.Key) bool {
vals := append([]string{x.Default}, x.Examples...)
n := 0
for _, v := range vals {
switch v {
case "yes", "no":
n++
case "":
default:
return false
}
}
return n > 0
}
func contains(ss []string, s string) bool {
for _, x := range ss {
if x == s {
return true
}
}
return false
}
func heading(label string) item {
return item{Entry: view.Entry{Kind: view.EntryHeading, Label: label}}
}
func menu(label, value string, open func() error) item {
return item{Entry: view.Entry{ID: "menu " + label, Kind: view.EntryMenu, Label: label, Value: value}, open: open}
}
func action(label string, do func() error) item {
return item{Entry: view.Entry{ID: "do " + label, Kind: view.EntryAction, Label: label}, do: do}
}
// notYet is a menu entry for what is to come.
func notYet(label, what string) item {
return item{Entry: view.Entry{ID: "later " + label, Kind: view.EntryInfo, Label: label, Value: "not available yet",
Disabled: true, Help: what}}
}
// fields are items for keys of a section.
func (e *Editor) fields(s confedit.Section, keys ...string) []item {
var out []item
for _, k := range keys {
out = append(out, e.field(s, k))
}
return out
}
// --- sections
// enabled is the yes/no of whether a section is there (one whose being
// there turns a server on).
func (e *Editor) enabled(s confedit.Section, label string) item {
on, was := e.doc.Has(s), e.orig.Has(s)
it := item{Entry: view.Entry{ID: "on " + s.String(), Kind: view.EntryBool, Label: label,
Value: yesno(on), Changed: on != was, Note: "restart"}}
if k := e.cat.Kind(s.Kind); k != nil {
it.help = k.Help
it.Help = firstSentence(k.Help)
}
it.set = func(v string) error {
switch {
case v == "yes" && !e.doc.Has(s):
if err := e.doc.AddSection(s); err != nil {
return err
}
case v == "no" && e.doc.Has(s):
e.doc.RemoveSection(s)
}
e.checkDoc()
return nil
}
if s.Kind == "level" || s.Kind == "menu" || s.Kind == "strings" || s.Kind == "chan" {
it.Note = ""
}
return it
}
func yesno(b bool) string {
if b {
return "yes"
}
return "no"
}
// sectionPage is a section's keys: those the sample has for its kind (and
// any others it has), with an Enabled for a section whose being there is
// a server's being on.
func (e *Editor) sectionPage(s confedit.Section, title string, toggle bool) page {
return page{title: title, items: func() []item {
var out []item
if toggle {
out = append(out, e.enabled(s, "Enabled"))
}
out = append(out, e.sectionFields(s)...)
return out
}}
}
// sectionFields are a section's keys as items: the sample's for its
// kind, then any others it has.
func (e *Editor) sectionFields(s confedit.Section) []item {
var out []item
seen := map[string]bool{}
if k := e.cat.Kind(s.Kind); k != nil {
for _, x := range k.Keys {
seen[x.Name] = true
out = append(out, e.field(s, x.Name))
}
}
for _, key := range e.doc.Keys(s) {
if !seen[key] {
seen[key] = true
out = append(out, e.field(s, key))
}
}
return out
}
// instances are the named sections of a kind, those keep says.
func (e *Editor) instances(kind string, keep func(confedit.Section) bool) []confedit.Section {
var out []confedit.Section
for _, s := range e.doc.Sections() {
if s.Kind == kind && (keep == nil || keep(s)) {
out = append(out, s)
}
}
return out
}
// listPage is the named sections of a kind (those keep says): each opens
// its page; A adds one (made with the keys of with), and each page has
// its name to change and a Delete.
func (e *Editor) listPage(title, kind, noun string, keep func(confedit.Section) bool, summary func(confedit.Section) string,
with map[string]string) page {
return page{title: title,
keys: []view.Action{{ID: "add", Label: "Add", Key: 'A', PF: 5}},
items: func() []item {
var out []item
for _, s := range e.instances(kind, keep) {
s := s
v := ""
if summary != nil {
v = summary(s)
}
it := menu(s.Name, v, func() error { return e.show(e.instancePage(s, noun)) })
it.Changed = !e.orig.Has(s)
out = append(out, it)
}
if len(out) == 0 {
out = append(out, item{Entry: view.Entry{Kind: view.EntryInfo, Label: "None yet: A adds one."}})
}
out = append(out, action("Add a "+noun, func() error { return e.addInstance(kind, noun, with) }))
return out
},
key: func(id string) error {
if id == "add" {
return e.addInstance(kind, noun, with)
}
return nil
}}
}
func (e *Editor) addInstance(kind, noun string, with map[string]string) error {
v, ok, err := e.UI.Form(&view.Form{Title: "A new " + noun,
Intro: []view.Line{view.L("Its name: one word, [" + kind + " NAME] in the file.")},
Fields: []view.Field{{Name: "name", Label: "Name", Width: 32}}, Submit: "Add"})
if err != nil || !ok {
return err
}
name := strings.TrimSpace(v["name"])
if name == "" {
return nil
}
s := sec(kind, name)
if e.doc.Has(s) {
e.say(view.Bad, s.String()+" is there already.")
return nil
}
if err := e.doc.AddSection(s); err != nil {
e.say(view.Bad, capital(err.Error())+".")
return nil
}
keys := make([]string, 0, len(with))
for k := range with {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
e.doc.Set(s, k, with[k])
}
return e.show(e.instancePage(s, noun))
}
// instancePage is a named section's page: its name, its keys, Delete.
func (e *Editor) instancePage(s confedit.Section, noun string) page {
cur := s
return page{title: s.String(),
keys: []view.Action{{ID: "del", Label: "Delete", Key: 'D', PF: 11}},
items: func() []item {
name := item{Entry: view.Entry{ID: "name", Kind: view.EntryText, Label: "Name", Value: cur.Name,
Help: "Its name: [" + cur.Kind + " NAME]"}}
name.set = func(v string) error {
v = strings.TrimSpace(v)
if v == "" || v == cur.Name {
return nil
}
if err := e.doc.Rename(cur, v); err != nil {
return err
}
cur.Name = v
return nil
}
out := []item{name}
out = append(out, e.sectionFields(cur)...)
out = append(out, action("Delete this "+noun, func() error { return e.deleteSection(cur) }))
return out
},
key: func(id string) error {
if id == "del" {
return e.deleteSection(cur)
}
return nil
}}
}
func (e *Editor) deleteSection(s confedit.Section) error {
yes, err := e.UI.Confirm("Delete "+s.String()+"?", false)
if err != nil || !yes {
return err
}
e.doc.RemoveSection(s)
e.checkDoc()
return errClose
}
// allSections is every section of the file, for what the menus do not
// reach.
func (e *Editor) allSections() page {
return page{title: "All settings, by section",
note: []view.Line{view.T(view.Dim, "Every section of the file as it is.")},
items: func() []item {
var out []item
for _, s := range e.doc.Sections() {
s := s
help := ""
if k := e.cat.Kind(s.Kind); k != nil {
help = firstSentence(k.Help)
}
it := menu(s.String(), fmt.Sprintf("%d keys", len(e.doc.Keys(s))), func() error {
if s.Name != "" {
return e.show(e.instancePage(s, s.Kind))
}
return e.show(e.sectionPage(s, s.String(), true))
})
it.Help = help
out = append(out, it)
}
return out
}}
}
+196
View File
@@ -0,0 +1,196 @@
package confui
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/Neo-Desktop/bbs-sec/internal/imageboard"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
func (e *Editor) maintenanceMenu() page {
return page{title: "Maintenance", items: func() []item {
out := []item{
action("Disk space", e.diskSpace),
heading("Pruning and archiving"),
menu("Message areas: what they keep", "", func() error { return e.show(e.retentionPage()) }),
}
purge := item{Entry: view.Entry{ID: "purge", Kind: view.EntryBool, Label: "Take out old messages at the save",
Help: "What areas keep no more (the newest N, for N days) taken out now, not at the hourly look."}}
if d := e.db; d != nil {
purge.Value, purge.Changed = yesno(d.purge), d.purge
} else {
purge.Value = "no"
}
purge.set = func(v string) error {
d, err := e.data()
if err != nil {
return err
}
d.purge = v == "yes"
return nil
}
out = append(out, purge, e.field(sec("chan"), "archive_days", "Image boards' archive (days)"))
out = append(out, heading("Backups"),
item{Entry: view.Entry{Kind: view.EntryInfo, Label: "Configuration",
Value: filepath.Base(e.Tools.Path) + ".bak, at each save"}},
notYet("Database", "A copy of the database, now or on a schedule: to come. Today: bbs db copy."),
notYet("Files", "A copy of the file areas', image boards' and FidoNet's files: to come."))
return out
}}
}
// retentionPage is each message area's keeping: the newest N, N days.
func (e *Editor) retentionPage() page {
return page{title: "Message areas: what they keep", items: func() []item {
d, err := e.data()
if err != nil {
return noData(err)
}
var out []item
for _, a := range d.areas {
a := a
w := d.areasWas[a.ID]
it := menu(a.Name, keeps(a), func() error { return e.show(e.areaKeepPage(a)) })
it.Changed = a.MaxMsgs != w.MaxMsgs || a.MaxDays != w.MaxDays
it.Help = fmt.Sprintf("%d messages now", a.Messages)
out = append(out, it)
}
if len(out) == 0 {
out = append(out, item{Entry: view.Entry{Kind: view.EntryInfo, Label: "No message areas yet."}})
}
return out
}}
}
func (e *Editor) areaKeepPage(a *store.Area) page {
return page{title: "Area " + a.Name, items: func() []item {
w := e.db.areasWas[a.ID]
num := func(id, label string, p *int, was int, help string) item {
it := item{Entry: view.Entry{ID: id, Kind: view.EntryText, Label: label, Value: strconv.Itoa(*p),
Changed: *p != was, Help: help}}
it.set = func(v string) error {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 {
return fmt.Errorf("%s: a number, 0 or more", label)
}
*p = n
return nil
}
return it
}
return []item{
{Entry: view.Entry{Kind: view.EntryInfo, Label: "Messages", Value: strconv.Itoa(a.Messages)}},
num("msgs", "Keep the newest", &a.MaxMsgs, w.MaxMsgs, "Messages kept (0: all)."),
num("days", "Keep for days", &a.MaxDays, w.MaxDays, "Days a message is kept (0: for ever)."),
}
}}
}
// diskSpace shows what the BBS's files take, and what is free where they
// are.
func (e *Editor) diskSpace() error {
g := sec("general")
db := e.value(g, "database", "bbs.db")
paths := []struct{ label, path string }{
{"File areas", e.value(g, "files_dir", "files")},
{"Image boards", e.value(sec("chan"), "dir", imageboard.Defaults().Dir)},
{"FidoNet", e.value(sec("fido"), "dir", "fido")},
{"Display files", e.value(g, "screens_dir", "")},
{"Scripts", e.value(g, "scripts_dir", "")},
}
if !strings.Contains(db, "://") {
paths = append([]struct{ label, path string }{{"Database", strings.TrimPrefix(db, "sqlite:")}}, paths...)
}
var lines []view.Line
seen := map[string]bool{} // file systems told of
for _, p := range paths {
if p.path == "" {
continue
}
size, files, err := du(p.path)
if err != nil {
lines = append(lines, view.V(p.label+":", errText(err)), view.T(view.Dim, " "+p.path))
continue
}
v := fmt.Sprintf("%s in %d files", bytesText(size), files)
if files == 1 {
v = bytesText(size)
}
lines = append(lines, view.V(p.label+":", v), view.T(view.Dim, " "+p.path))
var st syscall.Statfs_t
if syscall.Statfs(p.path, &st) == nil && !seen[fmt.Sprint(st.Fsid)] {
seen[fmt.Sprint(st.Fsid)] = true
total, free := st.Blocks*uint64(st.Bsize), st.Bavail*uint64(st.Bsize)
used := 0.0
if total > 0 {
used = 1 - float64(free)/float64(total)
}
lines = append(lines, view.Line{Label: " Disk used:", Text: fmt.Sprintf("%s free of %s", bytesText(int64(free)),
bytesText(int64(total))), Bar: used})
}
}
if strings.Contains(db, "://") {
lines = append(lines, view.V("Database:", "on a server ("+db[:strings.Index(db, "://")]+"): its size is the server's to say"))
}
if d, err := e.data(); err == nil {
msgs := 0
for _, a := range d.areas {
msgs += a.Messages
}
lines = append(lines, view.L(""), view.V("Messages:", fmt.Sprintf("%d in %d areas", msgs, len(d.areas))))
if fas, err := d.b.Store.FileAreas(); err == nil {
n, b := 0, int64(0)
for _, fa := range fas {
n += fa.Files
b += fa.Bytes
}
lines = append(lines, view.V("Files:", fmt.Sprintf("%d in %d areas, %s", n, len(fas), bytesText(b))))
}
}
return e.UI.Show("Disk space", lines)
}
// du is the bytes and files under path.
func du(path string) (int64, int, error) {
var size int64
n := 0
err := filepath.WalkDir(path, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.Type().IsRegular() {
if fi, err := d.Info(); err == nil {
size += fi.Size()
n++
}
}
return nil
})
return size, n, err
}
func errText(err error) string {
if os.IsNotExist(err) {
return "not there"
}
return err.Error()
}
func bytesText(n int64) string {
switch {
case n >= 1<<30:
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
}
return fmt.Sprintf("%d bytes", n)
}
+259
View File
@@ -0,0 +1,259 @@
package confui
import (
"fmt"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/confedit"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
// The menus, by what a sysop looks for.
func (e *Editor) mainMenu() page {
return page{title: "Configuration", items: func() []item {
g := sec("general")
name, _ := e.doc.Get(g, "name")
n := e.changes()
review := menu("Review changes", fmt.Sprintf("%d not saved", n), e.review)
review.Kind = view.EntryAction
review.do, review.open = e.review, nil
return []item{
menu("Board configuration", name, func() error { return e.show(e.boardMenu()) }),
menu("System configuration", "", func() error { return e.show(e.systemMenu()) }),
menu("Connections and modems", e.count("listen", nil, "listener"), func() error { return e.show(e.connectionsMenu()) }),
menu("Services", "", func() error { return e.show(e.servicesMenu()) }),
menu("Users and groups", "", func() error { return e.show(e.usersMenu()) }),
menu("Maintenance", "", func() error { return e.show(e.maintenanceMenu()) }),
heading(""),
review,
action("Check the configuration", e.check),
action("Save and exit (F10)", func() error { return errSave }),
action("Quit without saving (F9)", func() error { return errQuit }),
}
}}
}
// count is how many sections of a kind there are, in words.
func (e *Editor) count(kind string, keep func(confedit.Section) bool, noun string) string {
n := len(e.instances(kind, keep))
switch n {
case 0:
return "none"
case 1:
return "1 " + noun
}
return fmt.Sprintf("%d %ss", n, noun)
}
func (e *Editor) boardMenu() page {
g := sec("general")
return page{title: "Board configuration", items: func() []item {
out := e.fields(g, "name", "sysop", "location", "postal_address", "phone", "addresses", "qwk_id")
out = append(out, heading("What callers see"))
out = append(out, e.fields(g, "banner", "banner_file", "motd", "motd_file", "goodbye", "new_users", "logo")...)
out = append(out, heading("Menus and prompts"),
menu("Menus", e.count("menu", nil, "menu"), func() error {
return e.show(e.listPage("Menus", "menu", "menu", nil, func(s confedit.Section) string {
t, _ := e.doc.Get(s, "title")
return t
}, nil))
}),
menu("Prompts and messages", "", func() error { return e.show(e.stringsPage()) }))
return out
}}
}
// stringsPage is [strings]: every prompt the BBS has, its default shown.
func (e *Editor) stringsPage() page {
s := sec("strings")
return page{title: "Prompts and messages", items: func() []item {
var out []item
for _, k := range []string{"name_prompt", "new_name_prompt", "password_prompt", "command_prompt", "pause",
"logoff_confirm", "welcome"} {
out = append(out, e.field(s, k))
}
return out
}}
}
func (e *Editor) systemMenu() page {
g := sec("general")
return page{title: "System configuration", items: func() []item {
out := e.fields(g, "database", "log")
out = append(out, heading("File locations"))
out = append(out, e.fields(g, "files_dir", "max_file_size", "upload_quota", "screens_dir", "scripts_dir")...)
out = append(out, e.field(sec("chan"), "dir"), e.field(sec("fido"), "dir"))
out = append(out, heading("Security"))
out = append(out, e.fields(sec("security"), "deny_file", "name_deny_file", "hack_log", "ban_minutes")...)
out = append(out, heading("The process and logins"),
notYet("Run as user and group", "Binding the ports as root, then running as another user and group: to come. Today systemd's User= and Group= do it (bbs.service.sample)."),
notYet("PAM", "Passwords checked by PAM: to come."),
notYet("LDAP", "Passwords (and accounts) checked by an LDAP server: to come."),
heading("More"),
menu("Scheduled events", e.count("event", nil, "event"), func() error {
return e.show(e.listPage("Scheduled events", "event", "event", nil, func(s confedit.Section) string {
c, _ := e.doc.Get(s, "command")
return c
}, nil))
}),
menu("All settings, by section", "", func() error { return e.show(e.allSections()) }))
return out
}}
}
// listener kinds
func listenType(e *Editor, s confedit.Section) string {
t, _ := e.doc.Get(s, "type")
if t == "" {
t = "telnet"
}
return t
}
func (e *Editor) listeners(keep func(confedit.Section) bool, title string, with map[string]string) page {
return e.listPage(title, "listen", "listener", keep, func(s confedit.Section) string {
a, _ := e.doc.Get(s, "address")
return listenType(e, s) + " " + a
}, with)
}
func (e *Editor) isModem(s confedit.Section) bool {
h, _ := e.doc.Get(s, "header")
return listenType(e, s) == "raw" || h == "yes"
}
func (e *Editor) connectionsMenu() page {
g := sec("general")
return page{title: "Connections and modems", items: func() []item {
out := []item{
menu("Modem lines", e.count("listen", e.isModem, "line"), func() error {
return e.show(e.listeners(e.isModem, "Modem lines", map[string]string{"type": "raw", "address": "127.0.0.1:2323"}))
}),
menu("All listeners", e.count("listen", nil, "listener"), func() error {
return e.show(e.listeners(nil, "All listeners", map[string]string{"type": "telnet", "address": ":23"}))
}),
heading("Callers"),
}
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("Caller ID and where callers are"))
out = append(out, e.fields(g, "phone_country", "geoip", "geoip_credit", "geoip_credit_url")...)
return out
}}
}
func (e *Editor) onOff(s confedit.Section) string {
if e.doc.Has(s) {
return "on"
}
return "off"
}
func (e *Editor) servicesMenu() page {
ofType := func(t string) func(confedit.Section) bool {
return func(s confedit.Section) bool { return listenType(e, s) == t }
}
listeners := func(label, t, addr string) item {
return menu(label, e.count("listen", ofType(t), "listener"), func() error {
return e.show(e.listeners(ofType(t), label, map[string]string{"type": t, "address": addr}))
})
}
single := func(label, kind string) item {
return menu(label, e.onOff(sec(kind)), func() error { return e.show(e.sectionPage(sec(kind), label, true)) })
}
return page{title: "Services", items: func() []item {
return []item{
heading("Callers' terminals"),
listeners("Telnet", "telnet", ":23"),
menu("TN3270", "", func() error { return e.show(e.tn3270Page()) }),
listeners("SSH", "ssh", ":22"),
listeners("RLogin", "rlogin", "127.0.0.1:513"),
heading("Servers"),
single("Finger", "finger"),
single("Gopher", "gopher"),
single("FTP", "ftp"),
single("IRC (ircd)", "irc"),
menu("News (NNTP)", e.onOff(sec("nntp")), func() error { return e.show(e.newsPage()) }),
menu("Web: API, forum, image boards", e.onOff(sec("http")), func() error { return e.show(e.webPage()) }),
heading("Networks and doors"),
single("Multi Relay Chat", "mrc"),
menu("FidoNet", e.onOff(sec("fido")), func() error { return e.show(e.fidoPage()) }),
menu("QWK networks", e.count("qwknet", nil, "network"), func() error {
return e.show(e.listPage("QWK networks", "qwknet", "network", nil, func(s confedit.Section) string {
a, _ := e.doc.Get(s, "address")
return a
}, nil))
}),
menu("Doors", e.count("door", nil, "door"), func() error {
return e.show(e.listPage("Doors", "door", "door", nil, func(s confedit.Section) string {
d, _ := e.doc.Get(s, "description")
return d
}, nil))
}),
}
}}
}
func (e *Editor) tn3270Page() page {
g := sec("general")
return page{title: "TN3270", note: []view.Line{view.T(view.Dim, "3270s come in by telnet listeners with TN3270 on.")},
items: func() []item {
out := e.fields(g, "tn3270_symbols", "tn3270_vector", "tn3270_logo")
out = append(out, heading("Telnet listeners"))
for _, s := range e.instances("listen", func(s confedit.Section) bool { return listenType(e, s) == "telnet" }) {
out = append(out, e.field(s, "tn3270", s.String()+" takes 3270s"))
}
return out
}}
}
func (e *Editor) newsPage() page {
return page{title: "News (NNTP)", items: func() []item {
out := []item{e.enabled(sec("nntp"), "NNTP server")}
out = append(out, e.sectionFields(sec("nntp"))...)
out = append(out, heading("This site's name in the news"))
out = append(out, e.sectionFields(sec("news"))...)
out = append(out, heading("Peers"), menu("Peer news servers", e.count("peer", nil, "peer"), func() error {
return e.show(e.listPage("Peer news servers", "peer", "peer", nil, func(s confedit.Section) string {
a, _ := e.doc.Get(s, "address")
return a
}, nil))
}))
return out
}}
}
func (e *Editor) webPage() page {
return page{title: "Web: API, forum, image boards", items: func() []item {
out := []item{e.enabled(sec("http"), "HTTP server")}
out = append(out, e.sectionFields(sec("http"))...)
out = append(out, heading("Image boards"))
for _, it := range e.sectionFields(sec("chan")) {
if !strings.HasSuffix(it.ID, " dir") {
out = append(out, it)
}
}
return out
}}
}
func (e *Editor) fidoPage() page {
return page{title: "FidoNet", items: func() []item {
out := []item{e.enabled(sec("fido"), "On FidoNet")}
for _, it := range e.sectionFields(sec("fido")) {
if !strings.HasSuffix(it.ID, " dir") {
out = append(out, it)
}
}
out = append(out, heading("binkp: answering the links' calls"), e.enabled(sec("binkp"), "Answer"))
out = append(out, e.sectionFields(sec("binkp"))...)
out = append(out, heading("Links"), menu("Links", e.count("link", nil, "link"), func() error {
return e.show(e.listPage("Links", "link", "link", nil, func(s confedit.Section) string {
a, _ := e.doc.Get(s, "address")
return a
}, nil))
}))
return out
}}
}
+355
View File
@@ -0,0 +1,355 @@
package confui
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/confedit"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
// data is what the screens change in the database: copies of the
// accounts and areas as read, changed as the sysop says, and made so at
// the save.
type data struct {
b *bbs.BBS
users []*store.User // as they will be (ID 0: a new one)
was map[int64]store.User
passwords map[*store.User]string // new passwords
deleted map[int64]bool
areas []*store.Area
areasWas map[int64]store.Area
purge bool // old messages taken out at the save
}
// op is a change to make at the save.
type op struct {
desc string
run func() error
}
// data reads the accounts and areas, the first time they are wanted.
func (e *Editor) data() (*data, error) {
if e.db != nil {
return e.db, nil
}
if e.Open == nil {
return nil, errors.New("no database here")
}
b, err := e.Open()
if err != nil {
return nil, err
}
d := &data{b: b, was: map[int64]store.User{}, passwords: map[*store.User]string{}, deleted: map[int64]bool{},
areasWas: map[int64]store.Area{}}
us, err := b.Store.Users()
if err != nil {
return nil, err
}
for _, u := range us {
c := *u
d.users = append(d.users, &c)
d.was[u.ID] = *u
}
as, err := b.Store.Areas()
if err != nil {
return nil, err
}
for _, a := range as {
c := *a
d.areas = append(d.areas, &c)
d.areasWas[a.ID] = *a
}
e.db = d
return d, nil
}
// ops are the changes, in the order they are made.
func (d *data) ops() []op {
st := d.b.Store
var out []op
for _, u := range d.users {
u := u
if u.ID == 0 {
pw := d.passwords[u]
out = append(out, op{"user " + u.Name + ": new", func() error {
nu, err := st.CreateUser(u.Name, pw, "", u.Sysop)
if err != nil {
return err
}
if err := st.SetLevel(nu.ID, u.Level); err != nil {
return err
}
return st.SetFlags(nu.ID, u.Flags)
}})
continue
}
if d.deleted[u.ID] {
out = append(out, op{"user " + u.Name + ": deleted", func() error { return st.DeleteUser(u.ID) }})
continue
}
w := d.was[u.ID]
if u.Level != w.Level {
out = append(out, op{fmt.Sprintf("user %s: level %d (was %d)", u.Name, u.Level, w.Level),
func() error { return st.SetLevel(u.ID, u.Level) }})
}
if u.Flags != w.Flags {
out = append(out, op{fmt.Sprintf("user %s: flags %q (was %q)", u.Name, u.Flags, w.Flags),
func() error { return st.SetFlags(u.ID, u.Flags) }})
}
if u.Sysop != w.Sysop {
out = append(out, op{fmt.Sprintf("user %s: sysop %s", u.Name, yesno(u.Sysop)),
func() error { return st.SetSysop(u.ID, u.Sysop) }})
}
if u.Locked != w.Locked {
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 pw, ok := d.passwords[u]; ok {
out = append(out, op{"user " + u.Name + ": a new password", func() error { return st.SetPassword(u.ID, pw) }})
}
}
for _, a := range d.areas {
a := a
w := d.areasWas[a.ID]
if a.MaxMsgs != w.MaxMsgs || a.MaxDays != w.MaxDays {
out = append(out, op{fmt.Sprintf("area %s: keeps %s", a.Name, keeps(a)),
func() error { return st.SetAreaKeep(a.ID, a.MaxMsgs, a.MaxDays) }})
}
}
if d.purge {
out = append(out, op{"old messages taken out", func() error {
_, err := d.b.PurgeAreas()
return err
}})
}
return out
}
func keeps(a *store.Area) string {
m, days := "all messages", "for ever"
if a.MaxMsgs > 0 {
m = fmt.Sprintf("the newest %d", a.MaxMsgs)
}
if a.MaxDays > 0 {
days = fmt.Sprintf("for %d days", a.MaxDays)
}
return m + ", " + days
}
// noData is a page's word that the database is not to be had.
func noData(err error) []item {
return []item{{Entry: view.Entry{Kind: view.EntryInfo, Label: "The database",
Value: "not to be had: " + err.Error(), Disabled: true}}}
}
func (e *Editor) usersMenu() page {
g := sec("general")
return page{title: "Users and groups", items: func() []item {
out := []item{menu("User accounts", e.userCount(), func() error { return e.show(e.accountsPage()) })}
out = append(out, heading("Access levels and flags"))
out = append(out, e.fields(g, "new_user_level", "validated_level")...)
out = append(out, menu("Levels", e.count("level", nil, "level"), func() error {
return e.show(e.listPage("Access levels", "level", "level", nil, func(s confedit.Section) string {
n, _ := e.doc.Get(s, "name")
return n
}, nil))
}))
return out
}}
}
func (e *Editor) userCount() string {
if e.db == nil {
return ""
}
n := 0
for _, u := range e.db.users {
if !e.db.deleted[u.ID] || u.ID == 0 {
n++
}
}
return fmt.Sprintf("%d", n)
}
func (e *Editor) accountsPage() page {
return page{title: "User accounts",
keys: []view.Action{{ID: "add", Label: "Add", Key: 'A', PF: 5}},
items: func() []item {
d, err := e.data()
if err != nil {
return noData(err)
}
var out []item
for _, u := range d.users {
u := u
w, old := d.was[u.ID]
v := fmt.Sprintf("level %d", u.Level)
if u.Flags != "" {
v += ", flags " + u.Flags
}
if u.Sysop {
v += ", sysop"
}
if u.Locked {
v += ", locked"
}
if d.deleted[u.ID] && old {
v = "deleted at the save"
}
it := menu(u.Name, v, func() error { return e.show(e.userPage(u)) })
_, pw := d.passwords[u]
it.Changed = !old || d.deleted[u.ID] || pw || u.Level != w.Level || u.Flags != w.Flags ||
u.Sysop != w.Sysop || u.Locked != w.Locked
out = append(out, it)
}
out = append(out, action("Add a user", e.addUser))
return out
},
key: func(id string) error {
if id == "add" {
return e.addUser()
}
return nil
}}
}
func (e *Editor) addUser() error {
d, err := e.data()
if err != nil {
e.say(view.Bad, capital(err.Error())+".")
return nil
}
v, ok, err := e.UI.Form(&view.Form{Title: "A new user",
Fields: []view.Field{{Name: "name", Label: "Name", Width: bbs.MaxNameLen},
{Name: "pw", Label: "Password", Width: 72, Secret: true}}, Submit: "Add"})
if err != nil || !ok {
return err
}
name := strings.TrimSpace(v["name"])
if name == "" {
return nil
}
if msg := bbs.ValidName(name); msg != "" {
e.say(view.Bad, msg)
return nil
}
for _, u := range d.users {
if strings.EqualFold(u.Name, name) {
e.say(view.Bad, name+" is there already.")
return nil
}
}
if msg := bbs.ValidPassword(v["pw"], name); msg != "" {
e.say(view.Bad, msg)
return nil
}
lvl := 0
if l, err := strconv.Atoi(e.value(sec("general"), "new_user_level", "20")); err == nil {
lvl = l
}
u := &store.User{Name: name, Level: lvl}
d.users = append(d.users, u)
d.passwords[u] = v["pw"]
return e.show(e.userPage(u))
}
// value is a key's value as it will be, or def.
func (e *Editor) value(s confedit.Section, key, def string) string {
if v, ok := e.doc.Get(s, key); ok && v != "" {
return v
}
return def
}
func (e *Editor) userPage(u *store.User) page {
d := e.db
return page{title: "User " + u.Name, items: func() []item {
w, old := d.was[u.ID]
if !old {
w = store.User{Level: -1}
}
self := e.Who != "" && strings.EqualFold(e.Who, u.Name)
level := item{Entry: view.Entry{ID: "level", Kind: view.EntryText, Label: "Level", Value: strconv.Itoa(u.Level),
Changed: u.Level != w.Level, Help: "0 to 255: what the [level] at or below it allows."}}
level.set = func(v string) error {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 || n > bbs.MaxLevel {
return fmt.Errorf("a level is 0 to %d", bbs.MaxLevel)
}
u.Level = n
return nil
}
flags := item{Entry: view.Entry{ID: "flags", Kind: view.EntryText, Label: "Flags", Value: u.Flags,
Changed: u.Flags != w.Flags && old, Help: "Letters A to Z, for areas, doors and menus that require them."}}
flags.set = func(v string) error {
f, err := bbs.EditFlags("", strings.ToUpper(strings.ReplaceAll(v, " ", "")))
if err != nil {
return err
}
u.Flags = f
return nil
}
boolItem := func(id, label string, p *bool, was bool, help string) item {
it := item{Entry: view.Entry{ID: id, Kind: view.EntryBool, Label: label, Value: yesno(*p),
Changed: *p != was && old, Help: help, Disabled: self}}
if self {
it.Note = "not your own"
}
it.set = func(v string) error {
*p = v == "yes"
return nil
}
return it
}
_, newPW := d.passwords[u]
pw := item{Entry: view.Entry{ID: "pw", Kind: view.EntryText, Label: "New password", Secret: true,
Changed: newPW && old, Value: map[bool]string{true: "set", false: ""}[newPW],
Help: "Typed unseen; nothing typed keeps the one there is."}}
pw.set = func(v string) error {
if v == "" {
return nil
}
if msg := bbs.ValidPassword(v, u.Name); msg != "" {
return errors.New(strings.TrimSuffix(msg, "."))
}
d.passwords[u] = v
return nil
}
out := []item{
{Entry: view.Entry{Kind: view.EntryInfo, Label: "Name", Value: u.Name}},
level, flags,
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,
}
if old {
out = append(out, item{Entry: view.Entry{Kind: view.EntryInfo, Label: "Calls, posts",
Value: fmt.Sprintf("%d, %d", u.Logins, u.Posts)}})
}
del := "Delete this user"
if d.deleted[u.ID] && old {
del = "Keep this user (not deleted)"
}
da := action(del, func() error {
if !old {
for i, x := range d.users {
if x == u {
d.users = append(d.users[:i], d.users[i+1:]...)
}
}
delete(d.passwords, u)
return errClose
}
d.deleted[u.ID] = !d.deleted[u.ID]
return nil
})
da.Disabled = self
out = append(out, da)
return out
}}
}
+3
View File
@@ -219,6 +219,9 @@ func (c *Config) general(g *config.Section) error {
s.Name = g.String("name", s.Name)
s.Sysop = g.String("sysop", s.Sysop)
s.Location = g.String("location", s.Location)
s.PostalAddress = g.String("postal_address", "")
s.Phone = g.String("phone", "")
s.Addresses = g.String("addresses", "")
s.Banner = g.String("banner", s.Banner)
if f := g.String("banner_file", ""); f != "" {
data, err := os.ReadFile(f)
+128 -38
View File
@@ -4,6 +4,7 @@ import (
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -73,10 +74,9 @@ func TestReload(t *testing.T) {
}
}
// TestConfigScreens: the sysop changes the system's name on the
// Configuration screens; it is written, kept in bbs.conf.bak, and in force
// for the next caller.
func TestConfigScreens(t *testing.T) {
// configEnv is a BBS run from a file of its own, its Configuration on
// the sysop's menu.
func configEnv(t *testing.T, ansi string) (*env, string) {
var p string
e := startFull(t, ui3270.Graphics{}, nil, func(b *bbs.BBS, dir string) {
p = filepath.Join(dir, "bbs.conf")
@@ -85,41 +85,13 @@ func TestConfigScreens(t *testing.T) {
}
r := NewReloader(p, b)
b.Config = &bbs.ConfigTools{Path: p, Check: Check, Reload: r.Reload}
}, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"})
s := login(e, "sysop", "sysoppass1")
s.send("*")
s.expect("[F] Configuration")
s.send("F")
s.expect("[W] Write and put in force")
s.send("S")
s.expect("[listen modem]")
s.send("1\r")
s.expect("-- More --")
s.send("\r")
s.expect("[D]elete section")
s.send("1\r")
s.expect("Takes effect: at once, when written")
s.expect("the system's name, its sysop's") // the sample's help
s.send("E")
s.expect("name: Test BBS")
s.send("\x15Renamed BBS\r")
s.expect("Value: Renamed BBS")
s.send("Q")
s.expect("-- More --")
s.send("Q")
s.expect("[D]elete section")
s.send("Q\r")
s.expect("[N]ew section")
s.send("Q\r")
s.expect("View changes (1)")
s.send("V")
s.expect("~[general] name = Renamed BBS (was Test BBS)")
s.send(" ")
s.expect("Configuration: ")
s.send("W")
s.expect("In force now:")
s.expect("~[general] name = Renamed BBS")
}, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: ansi, VT: "no", RIP: "no", Sixel: "no"})
return e, p
}
// saved: the name is written, kept in bbs.conf.bak, and in force for the
// next caller.
func saved(t *testing.T, e *env, p string) {
if e.b.Conf().Name != "Renamed BBS" {
t.Errorf("name in force: %q", e.b.Conf().Name)
}
@@ -133,3 +105,121 @@ func TestConfigScreens(t *testing.T) {
c := e.dial("modem.sock")
c.expect("Renamed BBS")
}
// TestConfigScreens: on a terminal without ANSI, the sysop changes the
// system's name on the Configuration's numbered screens and saves.
func TestConfigScreens(t *testing.T) {
e, p := configEnv(t, "no")
s := login(e, "sysop", "sysoppass1")
s.send("*")
s.expect("[F] Configuration")
s.send("F")
s.expect("Board configuration >")
s.expect("[S]ave and exit, [X] Exit without saving")
s.send("1\r")
s.expect("BBS name")
s.send("1\r")
s.expect("BBS name: Test BBS")
s.send("\x15Renamed BBS\r")
s.expect("1 change not saved")
if data, _ := os.ReadFile(p); string(data) != reloadConf {
t.Fatal("written before the save")
}
s.send("S\r")
s.expect("In force now:")
s.expect("~[general] name = Renamed BBS")
saved(t, e, p)
}
// TestConfigScreensANSI: on an ANSI terminal, the full screen: the arrow
// keys, Enter to change a value, F10 to save and leave.
func TestConfigScreensANSI(t *testing.T) {
e, p := configEnv(t, "yes")
s := ansiLogin(e)
s.send("*")
s.expect("Configuration")
s.send("F")
s.expect("F10 save+exit")
s.send("\x1b[B\x1b[A\r") // down, up: Board configuration
s.expect("Configuration > Board configuration")
s.send("\r")
s.expect("BBS name: ")
s.send("\x15Renamed BBS\r")
s.expect("1 change not saved")
s.send("\x1b[21~") // F10
s.expect("In force now:")
saved(t, e, p)
}
// TestConfigQuit: F9 leaves without saving, after a yes.
func TestConfigQuit(t *testing.T) {
e, p := configEnv(t, "yes")
s := ansiLogin(e)
s.send("*F")
s.expect("F10 save+exit")
s.send("\r\r")
s.expect("BBS name: ")
s.send("\x15Not Saved\r")
s.expect("1 change not saved")
s.send("\x1b[20~") // F9
s.expect("Leave without saving 1 changes?")
s.send("y")
s.expect("Sysop tools")
if data, _ := os.ReadFile(p); string(data) != reloadConf || e.b.Conf().Name == "Not Saved" {
t.Errorf("saved:\n%s", data)
}
}
// ansiLogin logs the sysop in on an ANSI terminal (the prompts in color).
func ansiLogin(e *env) *dialog {
d := e.dial("modem.sock")
d.expect("(or NEW)")
d.send("sysop\r")
d.expect("Password")
d.send("sysoppass1\r")
d.expect("Command")
return d
}
// TestConfig3270: on a 3270, S by a menu opens it, a value is typed over
// and sent with Enter, PF10 saves.
func TestConfig3270(t *testing.T) {
if _, err := exec.LookPath("s3270"); err != nil {
t.Skip("no s3270")
}
addr := freeTCP(t)
var p string
e := startFull(t, ui3270.Graphics{}, nil, func(b *bbs.BBS, dir string) {
p = filepath.Join(dir, "bbs.conf")
writeFile(p, reloadConf)
r := NewReloader(p, b)
b.Config = &bbs.ConfigTools{Path: p, Check: Check, Reload: r.Reload}
}, &Listener{Name: "telnet", Kind: "telnet", Address: addr, TN3270: true},
&Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"})
script := strings.Join([]string{
"Connect(" + addr + ")", "Wait(10,InputField)",
`String("sysop")`, "Tab()", `String("sysoppass1")`, "Enter()", "Wait(5,InputField)",
`String("*")`, "Enter()", "Wait(5,InputField)",
`String("f")`, "Enter()", "Wait(5,InputField)", "Ascii()",
`String("s")`, "Enter()", "Wait(5,InputField)", "Ascii()",
"EraseEOF()", `String("Renamed BBS")`, "Enter()", "Wait(5,InputField)", "Ascii()",
"PF(10)", "Wait(5,InputField)", "Ascii()", "Quit()", ""}, "\n")
cmd := exec.Command("s3270", "-model", "3279-2")
cmd.Stdin = strings.NewReader(script)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("s3270: %v\n%s", err, out)
}
for _, want := range []string{"Board configuration >", "PF10=Save+exit", "BBS name", "1 change not saved",
"In force now:"} {
if !strings.Contains(string(out), want) {
t.Errorf("no %q:\n%s", want, out)
}
}
if os.Getenv("SHOW3270") != "" {
t.Logf("%s", out)
}
if e.b.Conf().Name != "Renamed BBS" {
t.Errorf("name in force: %q", e.b.Conf().Name)
}
}
+345
View File
@@ -0,0 +1,345 @@
package textui
import (
"strings"
"unicode"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
// Sheets on ANSI terminals: the whole screen, a bar of where it is at the
// top, the entries in a window the cursor keys move through, the entry's
// help and the keys at the foot. Elsewhere a sheet is view.LineSheet's
// table.
// Sheet draws a sheet and waits for the caller to do something on it.
func (s *session) Sheet(sh *view.Sheet) (view.SheetResult, error) {
t := s.t
if !t.ANSI || t.VT52 || t.PETSCII || t.Rows < 12 || t.Cols < 40 {
return view.LineSheet(s, sh)
}
notify := t.Notify
t.Notify = nil // what other nodes send waits: it would draw over the sheet
defer func() {
t.Notify = notify
t.Print("\x1b[?25h\x1b[0m\x1b[2J\x1b[H")
t.Flush()
}()
d := &sheetDraw{t: t, sh: sh, cur: -1}
d.cur = d.step(sh.Cursor-1, 1)
if d.cur < 0 {
d.cur = max(sh.Cursor, 0)
}
d.drawAll()
for {
t.Print("\x1b[?25l") // no cursor while moving: the bar shows where
k, err := t.EditKey()
if err != nil {
return view.SheetResult{}, err
}
res := func(action string) view.SheetResult { return view.SheetResult{Action: action, Entry: d.cur} }
switch {
case k == KeyF1 || k == '?':
return res(view.SheetHelp), nil
case k == KeyF1+9:
return res(view.SheetSave), nil
case k == KeyF1+8:
return res(view.SheetQuit), nil
case k == 0x1b || k == KeyLeft:
return res(view.Back), nil
case k == KeyUp:
d.move(d.step(d.cur, -1))
case k == KeyDown || k == '\t':
d.move(d.step(d.cur, 1))
case k == KeyPgUp:
d.move(d.page(-1))
case k == KeyPgDn:
d.move(d.page(1))
case k == KeyHome:
d.move(d.step(-1, 1))
case k == KeyEnd:
d.move(d.step(len(sh.Entries), -1))
case k == 0x0c: // ^L
d.drawAll()
case k == '\r' || k == ' ' || k == KeyRight:
if d.cur < 0 || d.cur >= len(sh.Entries) {
continue
}
e := sh.Entries[d.cur]
switch e.Kind {
case view.EntryMenu, view.EntryAction:
if k != ' ' {
return res(view.Pick), nil
}
case view.EntryBool, view.EntryChoice:
if k != KeyRight {
r := res(view.SheetSet)
r.Values = map[string]string{e.ID: e.Next()}
return r, nil
}
case view.EntryText:
if k == ' ' {
continue
}
v, ok, err := d.edit(e)
if err != nil {
return view.SheetResult{}, err
}
if ok {
r := res(view.SheetSet)
r.Values = map[string]string{e.ID: v}
return r, nil
}
d.drawAll()
}
default:
if id := action(sh.Keys, k); id != "" {
return res(id), nil
}
// a letter: the next entry beginning with it
d.move(d.letter(unicode.ToUpper(k)))
}
}
}
type sheetDraw struct {
t *Term
sh *view.Sheet
cur int // the entry the cursor is on
top int // the first entry shown
}
// rows: where the entries' window begins, and how many rows it has
func (d *sheetDraw) first() int { return 3 + min(len(d.sh.Note), 3) }
func (d *sheetDraw) height() int { return max(d.t.Rows-3-d.first()+1, 3) }
// step is the next entry the cursor may rest on from i, by dir (-1 if none).
func (d *sheetDraw) step(i, dir int) int {
for j := i + dir; j >= 0 && j < len(d.sh.Entries); j += dir {
if d.sh.Entries[j].Choosable() {
return j
}
}
if i >= 0 && i < len(d.sh.Entries) && d.sh.Entries[i].Choosable() {
return i
}
return -1
}
func (d *sheetDraw) page(dir int) int {
j := min(max(d.cur+dir*(d.height()-1), 0), len(d.sh.Entries)-1)
if n := d.step(j-dir, dir); n >= 0 {
return n
}
return d.step(j, -dir)
}
func (d *sheetDraw) letter(r rune) int {
n := len(d.sh.Entries)
for k := 1; k <= n; k++ {
j := (d.cur + k) % n
e := d.sh.Entries[j]
if e.Choosable() && strings.HasPrefix(strings.ToUpper(e.Label), string(r)) {
return j
}
}
return -1
}
// move puts the cursor on entry j, drawing what changed.
func (d *sheetDraw) move(j int) {
if j < 0 || j == d.cur {
return
}
old := d.cur
d.cur = j
if d.scroll() {
d.drawEntries()
} else {
d.drawEntry(old)
d.drawEntry(j)
}
d.drawFoot()
}
// scroll keeps the cursor's entry in the window; true if the window moved.
func (d *sheetDraw) scroll() bool {
top := d.top
if d.cur < d.top {
d.top = d.cur
// a heading just above comes too
if d.top > 0 && d.sh.Entries[d.top-1].Kind == view.EntryHeading {
d.top--
}
}
if d.cur >= d.top+d.height() {
d.top = d.cur - d.height() + 1
}
return top != d.top
}
func (d *sheetDraw) drawAll() {
t := d.t
d.scroll()
var w strings.Builder
w.WriteString("\x1b[0m\x1b[2J")
bar := " " + d.sh.Title
if d.sh.Crumbs != "" {
bar = " " + d.sh.Crumbs
}
w.WriteString(at(1, 1) + "\x1b[0;1;37;44m" + bbs.Fit(bbs.Trunc(bar, t.Cols-1), t.Cols-1) + "\x1b[0m")
for i, l := range d.sh.Note {
if i == 3 {
break
}
w.WriteString(at(2+i, 1) + d.tone(l))
}
t.Print(w.String())
d.drawEntries()
d.drawFoot()
}
func (d *sheetDraw) tone(l view.Line) string {
t := d.t
s := bbs.Trunc(" "+l.Label+l.Text, t.Cols-1)
switch l.Tone {
case view.Bad:
return t.C(Red, s)
case view.Warn:
return t.C(Yellow, s)
case view.Good:
return t.C(Green, s)
case view.Dim:
return t.C(Dim, s)
case view.Bright:
return t.C(White, s)
}
return s
}
func (d *sheetDraw) drawEntries() {
for r := 0; r < d.height(); r++ {
d.drawEntry(d.top + r)
}
}
// columns: the label's, the note's
func (d *sheetDraw) widths() (label, note int) {
note = 0
for _, e := range d.sh.Entries {
note = max(note, len(e.Note))
if e.Kind != view.EntryHeading {
label = max(label, len([]rune(e.Label))+2)
}
}
label = min(max(label, 16), d.t.Cols/2)
return label, min(note, d.t.Cols/4)
}
func (d *sheetDraw) drawEntry(i int) {
t := d.t
row := d.first() + i - d.top
if i < d.top || row >= d.first()+d.height() {
return
}
if i < 0 || i >= len(d.sh.Entries) {
t.Print(at(row, 1) + "\x1b[0m\x1b[K")
return
}
e := d.sh.Entries[i]
if e.Kind == view.EntryHeading {
t.Print(at(row, 1) + "\x1b[0m\x1b[K" + t.C(Cyan, bbs.Trunc(" "+e.Label, t.Cols-1)))
return
}
lw, nw := d.widths()
room := t.Cols - 1
mark := " "
if e.Changed {
mark = " *"
}
label := e.Label
val := e.Shown()
switch e.Kind {
case view.EntryMenu:
label += " >"
}
vw := max(room-2-lw-1-nw-1, 4)
cells := mark + bbs.Fit(bbs.Trunc(label, lw), lw) + " " + bbs.Fit(bbs.Trunc(val, vw), vw) + " " +
bbs.Fit(bbs.Trunc(e.Note, nw), nw)
cells = bbs.Fit(bbs.Trunc(cells, room), room)
var out string
switch {
case i == d.cur:
out = "\x1b[0;7m" + cells + "\x1b[0m"
case e.Disabled:
out = t.C(Dim, cells)
default:
// the parts in their colors
vc := val
switch {
case e.Changed:
vc = t.C(Yellow, bbs.Fit(bbs.Trunc(val, vw), vw))
case e.Value == "":
vc = t.C(Dim, bbs.Fit(bbs.Trunc(val, vw), vw))
default:
vc = t.C(White, bbs.Fit(bbs.Trunc(val, vw), vw))
}
m := mark
if e.Changed {
m = t.C(Yellow, mark)
}
out = m + bbs.Fit(bbs.Trunc(label, lw), lw) + " " + vc + " " + t.C(Dim, bbs.Fit(bbs.Trunc(e.Note, nw), nw))
}
t.Print(at(row, 1) + "\x1b[0m\x1b[K" + out)
}
// drawFoot draws the entry's help, the status and the keys.
func (d *sheetDraw) drawFoot() {
t := d.t
help := ""
if d.cur >= 0 && d.cur < len(d.sh.Entries) {
e := d.sh.Entries[d.cur]
help = e.Help
if help == "" && e.Kind == view.EntryText && len(e.Value) > t.Cols/2 {
help = e.Value // a long value: whole here
}
}
keys := "Enter change Esc back F1 help F9 quit F10 save+exit"
for _, a := range d.sh.Keys {
keys = string(a.Key) + " " + a.Label + " " + keys
}
w := t.Cols - 1
var b strings.Builder
b.WriteString(at(t.Rows-2, 1) + "\x1b[0m\x1b[K" + t.C(Dim, bbs.Trunc(" "+help, w)))
b.WriteString(at(t.Rows-1, 1) + "\x1b[0m\x1b[K" + t.C(Yellow, bbs.Trunc(" "+d.sh.Status, w)))
b.WriteString(at(t.Rows, 1) + "\x1b[0;30;46m" + bbs.Fit(bbs.Trunc(" "+keys, w), w) + "\x1b[0m")
t.Print(b.String())
}
// edit reads a text entry's new value on the help row: false if it was
// left as it was.
func (d *sheetDraw) edit(e view.Entry) (string, bool, error) {
t := d.t
prompt := " " + e.Label + ": "
t.Print(at(t.Rows-2, 1) + "\x1b[0m\x1b[K" + t.C(Cyan, prompt) + "\x1b[?25h")
max := e.Width
if max <= 0 {
max = 255
}
var l Line
var err error
if e.Secret {
l, err = t.ReadLine(LineOpts{Max: max, Mask: true})
if err == nil && l.Text == "" {
return "", false, nil // nothing typed: kept
}
} else {
l, err = t.ReadLine(LineOpts{Max: max, Initial: e.Value})
}
t.Print("\x1b[?25l")
if err != nil {
return "", false, err
}
return l.Text, l.Text != e.Value, nil
}
+21 -1
View File
@@ -357,8 +357,13 @@ const (
KeyPgDn
KeyInsert
KeyDelete
KeyF1 // and on to KeyF12: KeyF1 + 11
)
// fkeys are ESC [ N ~'s function keys (xterm, SyncTERM)
var fkeys = map[string]rune{"11": KeyF1, "12": KeyF1 + 1, "13": KeyF1 + 2, "14": KeyF1 + 3, "15": KeyF1 + 4,
"17": KeyF1 + 5, "18": KeyF1 + 6, "19": KeyF1 + 7, "20": KeyF1 + 8, "21": KeyF1 + 9, "23": KeyF1 + 10, "24": KeyF1 + 11}
// EditKey reads one key as typed, for a full-screen editor: runes and
// control characters as they are (CR LF as CR), the cursor and editing
// keys as KeyUp and the rest, a lone ESC as ESC.
@@ -578,10 +583,22 @@ func (t *Term) escapeKey() (rune, error) {
if err != nil {
return 0, nil
}
if c == '[' && i == 0 {
// the Linux console's F1-F5: ESC [ [ A to E
c, err := t.r.ReadByte()
if err != nil || c < 'A' || c > 'E' {
return 0, nil
}
return KeyF1 + rune(c-'A'), nil
}
if c >= 0x40 && c <= 0x7e {
if c == '~' {
p, _, _ := strings.Cut(string(param), ";") // ;2 and the like: shift, ctrl
if k, ok := fkeys[p]; ok {
return k, nil
}
return map[string]rune{"1": KeyHome, "7": KeyHome, "4": KeyEnd, "8": KeyEnd,
"2": KeyInsert, "3": KeyDelete, "5": KeyPgUp, "6": KeyPgDn}[string(param)], nil
"2": KeyInsert, "3": KeyDelete, "5": KeyPgUp, "6": KeyPgDn}[p], nil
}
return final[c], nil
}
@@ -593,6 +610,9 @@ func (t *Term) escapeKey() (rune, error) {
if err != nil {
return 0, nil
}
if c >= 'P' && c <= 'S' {
return KeyF1 + rune(c-'P'), nil // F1-F4
}
return final[c], nil
case 'A', 'B', 'C', 'D':
if t.VT52 {
+179
View File
@@ -0,0 +1,179 @@
package ui3270
import (
"strconv"
"strings"
"github.com/racingmars/go3270"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/view"
)
// Sheet is a sheet as a 3270 screen: the values as fields to type over
// (all sent with Enter), S by a menu or action to choose it, PF10 to save
// and leave, PF9 to leave without.
func (u *ui) Sheet(sh *view.Sheet) (view.SheetResult, error) {
per := u.rows - 5 // rows 2 .. rows-4
top := 0
if sh.Cursor >= per {
top = sh.Cursor / per * per
}
lw := min(28, max(u.cols/3, 16))
nw := 0
for _, e := range sh.Entries {
nw = max(nw, len(e.Note))
}
nw = min(nw, u.cols/5)
keys := "S+Enter=Open PF1=Help PF3=Back PF7/8=Page PF9=Quit PF10=Save+exit"
if k := pfKeys(sh.Keys, " "); k != "" {
keys = k + " " + keys
}
if len(keys) > u.cols-1 {
keys = strings.ReplaceAll(strings.ReplaceAll(keys, " ", " "), "S+Enter=Open", "S=Open")
}
msg := ""
for {
status := msg
if status == "" {
status = sh.Status
}
scr := u.frame(sh.Title, keys, status)
msg = ""
crumbs := sh.Crumbs
if len(sh.Note) > 0 {
crumbs = sh.Note[0].Text
}
scr = append(scr, u.text(1, 1, crumbs, go3270.Blue, false))
vals := map[string]string{}
long := map[int]bool{} // text entries too long for their field: chosen, they get a form
for r := 0; r < per && top+r < len(sh.Entries); r++ {
i := top + r
e := sh.Entries[i]
row := 2 + r
id := strconv.Itoa(i)
if e.Kind == view.EntryHeading {
scr = append(scr, u.text(row, 1, e.Label, go3270.Turquoise, true))
continue
}
color := go3270.Green
if e.Changed {
color = go3270.Yellow
}
mark := " "
if e.Changed {
mark = "*"
}
label := e.Label
if e.Kind == view.EntryMenu {
label += " >"
}
scr = append(scr, u.text(row, 2, mark+bbs.Fit(bbs.Trunc(label, lw), lw), color, e.Changed))
vcol := 2 + 1 + lw + 1
vw := u.cols - vcol - 3 - nw
if e.Note != "" {
scr = append(scr, u.text(row, u.cols-nw-2, e.Note, go3270.Blue, false))
}
switch {
case e.Disabled || e.Kind == view.EntryInfo:
scr = append(scr, u.text(row, vcol, e.Shown(), go3270.Blue, false))
case e.Kind == view.EntryMenu || e.Kind == view.EntryAction:
scr = append(scr, go3270.Field{Row: row, Col: 0, Write: true, Name: "s" + id,
Color: go3270.Green, Highlighting: go3270.Underscore})
scr = append(scr, go3270.Field{Row: row, Col: 2, Autoskip: true})
case e.Kind == view.EntryText && len([]rune(e.Value)) > vw:
long[i] = true
scr = append(scr, go3270.Field{Row: row, Col: 0, Write: true, Name: "s" + id,
Color: go3270.Green, Highlighting: go3270.Underscore})
scr = append(scr, go3270.Field{Row: row, Col: 2, Autoskip: true})
scr = append(scr, u.text(row, vcol, bbs.Trunc(e.Value, vw-4)+" ...", go3270.White, false))
default:
scr = append(scr, go3270.Field{Row: row, Col: vcol, Write: true, Name: "v" + id,
Hidden: e.Secret, Color: go3270.Turquoise, Highlighting: go3270.Underscore})
if !e.Secret {
vals["v"+id] = e.Value
}
scr = append(scr, go3270.Field{Row: row, Col: vcol + 1 + vw, Autoskip: true})
}
}
resp, v, err := u.show(scr, vals)
if err != nil {
return view.SheetResult{}, err
}
switch resp.AID {
case go3270.AIDPF3:
return view.SheetResult{Action: view.Back, Entry: top}, nil
case go3270.AIDPF1:
// the help of the entry the cursor is on
i := top + resp.Row - 2
if resp.Row >= 2 && i < len(sh.Entries) && i >= top {
return view.SheetResult{Action: view.SheetHelp, Entry: i}, nil
}
msg = "Put the cursor on a line for its help."
continue
case go3270.AIDPF9:
return view.SheetResult{Action: view.SheetQuit, Entry: top}, nil
case go3270.AIDPF10:
return view.SheetResult{Action: view.SheetSave, Entry: top}, nil
case go3270.AIDPF7:
if top == 0 {
msg = "That is the top."
}
top = max(0, top-per)
continue
case go3270.AIDPF8:
if top+per >= len(sh.Entries) {
msg = "That is the end."
continue
}
top += per
continue
case go3270.AIDEnter:
for r := 0; r < per && top+r < len(sh.Entries); r++ {
i := top + r
if strings.TrimSpace(strings.Trim(v["s"+strconv.Itoa(i)], "\x00")) == "" {
continue
}
e := sh.Entries[i]
if !long[i] {
return view.SheetResult{Action: view.Pick, Entry: i}, nil
}
f, ok, err := u.Form(&view.Form{Title: e.Label, Intro: []view.Line{view.T(view.Dim, e.Help)},
Fields: []view.Field{{Name: "v", Label: e.Label, Width: max(e.Width, 255), Value: e.Value, Edit: true}},
Submit: "Set"})
if err != nil {
return view.SheetResult{}, err
}
if ok && f["v"] != e.Value {
return view.SheetResult{Action: view.SheetSet, Entry: i, Values: map[string]string{e.ID: f["v"]}}, nil
}
break
}
changed := map[string]string{}
first := -1
for r := 0; r < per && top+r < len(sh.Entries); r++ {
i := top + r
nv, sent := v["v"+strconv.Itoa(i)]
if !sent {
continue
}
e := sh.Entries[i]
nv = strings.TrimSpace(strings.Trim(nv, "\x00"))
if e.Secret && nv == "" || !e.Secret && nv == e.Value {
continue
}
changed[e.ID] = nv
if first < 0 {
first = i
}
}
if len(changed) > 0 {
return view.SheetResult{Action: view.SheetSet, Entry: first, Values: changed}, nil
}
continue
}
if id := pfAction(sh.Keys, resp.AID); id != "" {
return view.SheetResult{Action: id, Entry: top}, nil
}
}
}
+215
View File
@@ -0,0 +1,215 @@
package view
import (
"strconv"
"strings"
)
// Sheet is a full screen of entries to move among: menus to open, values
// to change, things to do. Changes are the screen's code's to keep; F10
// (PF10) asks it to save them all and leave, F9 (PF9) to leave without.
type Sheet struct {
Title string
Crumbs string // where it is: "Configuration > Services"
Note []Line // above the entries
Entries []Entry
Cursor int // the entry the cursor begins on
Keys []Action // more keys (A Add, D Delete ...), with PF keys on a 3270
Status string // the foot's left: "3 changes not saved"
}
// EntryKind is what an entry is.
type EntryKind int
// Entry kinds.
const (
EntryMenu EntryKind = iota // opens another sheet
EntryText // a value typed
EntryBool // yes or no: Enter or space turns it over
EntryChoice // one of Choices: Enter or space goes to the next
EntryAction // does something
EntryInfo // a value only shown
EntryHeading // a line between groups of entries
)
// Entry is a sheet's line.
type Entry struct {
ID string
Kind EntryKind
Label string
Value string // as it is now ("": not set)
Default string // shown, dim, when Value is ""
Choices []string // EntryChoice's
Secret bool // shown as stars, typed unseen
Changed bool // not saved yet: marked
Note string // at the line's end: "restart", "not available yet"
Help string // at the foot while the cursor is on it
Disabled bool // shown, not chosen
Width int // the most a value may be (0: 255)
}
// Sheet results' actions beyond Pick and Back, and the keys' own IDs.
const (
SheetSet = "set" // Values were changed
SheetSave = "save" // F10: save all and leave
SheetQuit = "quit" // F9: leave without saving
SheetHelp = "help" // F1 (or ?): the entry's whole help
)
// SheetResult is what was done on a sheet.
type SheetResult struct {
Action string // Pick (a Menu or Action entry chosen), SheetSet, SheetSave, SheetQuit, Back, a Keys ID
Entry int // the entry the cursor was on
Values map[string]string // SheetSet: entries' new values by ID (a 3270 sends all it changed at once)
}
// SheetUI is a front end that draws sheets full-screen.
type SheetUI interface {
Sheet(s *Sheet) (SheetResult, error)
}
// ShowSheet draws a sheet: full-screen where the front end can, else as a
// numbered table, a value at a time.
func ShowSheet(ui UI, s *Sheet) (SheetResult, error) {
if su, ok := ui.(SheetUI); ok {
return su.Sheet(s)
}
return LineSheet(ui, s)
}
// Shown is how an entry's value reads: the value, stars for a secret,
// its default in brackets, yes or no.
func (e Entry) Shown() string {
switch {
case e.Kind == EntryAction || e.Kind == EntryHeading:
return ""
case e.Kind == EntryMenu:
return e.Value // what is in it, in a word
case e.Value == "" && e.Default != "":
return "(" + e.Default + ")"
case e.Secret && e.Value != "":
return "********"
}
return e.Value
}
// Next is the value an EntryBool or EntryChoice turns to.
func (e Entry) Next() string {
cur := e.Value
if cur == "" {
cur = e.Default
}
if e.Kind == EntryBool {
if strings.EqualFold(cur, "yes") {
return "no"
}
return "yes"
}
for i, c := range e.Choices {
if c == cur {
return e.Choices[(i+1)%len(e.Choices)]
}
}
if len(e.Choices) > 0 {
return e.Choices[0]
}
return cur
}
// Choosable reports whether the cursor may rest on the entry.
func (e Entry) Choosable() bool {
return !e.Disabled && e.Kind != EntryHeading && e.Kind != EntryInfo
}
// LineSheet is a sheet on a terminal that cannot draw one: a numbered
// table, a number typed to open or change an entry, S to save and leave,
// X to leave without.
func LineSheet(ui UI, s *Sheet) (SheetResult, error) {
t := &Table{Title: s.Title, Note: s.Note, Pick: "Number",
Columns: []Column{{Title: "", Width: 26}, {Title: "", Width: 0}, {Title: "", Width: 10, Wide: true}}}
if s.Crumbs != "" {
t.Note = append([]Line{T(Dim, s.Crumbs)}, t.Note...)
}
if s.Status != "" {
t.Note = append(t.Note, T(Warn, s.Status))
}
var rows []int // the entry of each row (-1: a heading)
n := 0
for i, e := range s.Entries {
if e.Kind == EntryHeading {
h := ""
if e.Label != "" {
h = "-- " + e.Label
}
t.Rows = append(t.Rows, Row{Cells: []string{h, "", ""}})
rows = append(rows, -1)
continue
}
num := ""
if e.Choosable() {
n++
num = strconv.Itoa(n)
}
label := e.Label
if e.Kind == EntryMenu {
label += " >"
}
v := e.Shown()
if e.Changed {
v += " *"
}
t.Rows = append(t.Rows, Row{Num: num, Cells: []string{label, v, e.Note}, Hot: e.Changed})
rows = append(rows, i)
}
t.Actions = append(append([]Action{}, s.Keys...),
Action{ID: SheetSave, Label: "Save and exit", Key: 'S', PF: 10},
Action{ID: SheetQuit, Label: "Exit without saving", Key: 'X', PF: 9},
Action{ID: SheetHelp, Label: "Help", Key: '?', PF: 1})
for {
c, err := ui.Table(t)
if err != nil {
return SheetResult{}, err
}
switch c.Action {
case Back, SheetSave, SheetQuit:
return SheetResult{Action: c.Action}, nil
case SheetHelp:
// of which?
v, ok, err := ui.Form(&Form{Title: "Help", Fields: []Field{{Name: "n", Label: "Help on number", Width: 4}}})
if err != nil || !ok {
return SheetResult{}, err
}
for j, r := range t.Rows {
if r.Num == strings.TrimSpace(v["n"]) && rows[j] >= 0 {
return SheetResult{Action: SheetHelp, Entry: rows[j]}, nil
}
}
case Pick:
if c.Row < 0 || rows[c.Row] < 0 || !s.Entries[rows[c.Row]].Choosable() {
continue
}
i := rows[c.Row]
e := s.Entries[i]
switch e.Kind {
case EntryMenu, EntryAction:
return SheetResult{Action: Pick, Entry: i}, nil
case EntryBool, EntryChoice:
return SheetResult{Action: SheetSet, Entry: i, Values: map[string]string{e.ID: e.Next()}}, nil
case EntryText:
if e.Help != "" {
ui.Say(Dim, e.Help)
}
v, ok, err := ui.Form(&Form{Title: e.Label, Fields: []Field{{Name: "v", Label: e.Label,
Width: e.Width, Value: e.Value, Edit: true, Secret: e.Secret}}, Submit: "Set"})
if err != nil {
return SheetResult{}, err
}
if ok && v["v"] != e.Value {
return SheetResult{Action: SheetSet, Entry: i, Values: map[string]string{e.ID: v["v"]}}, nil
}
}
default:
return SheetResult{Action: c.Action, Entry: -1}, nil
}
}
}