Merge pull request #20 from D-Modem/claude/project-thread-n7yldm

Setup: describe every setting, pick values from lists
This commit is contained in:
Neo authored and GitHub committed 2026-11-12 10:09:06 -08:00
commit b027f777bc
11 files changed
+1454 -47

No files matched your search

+8 -1
View File
@@ -366,7 +366,14 @@ command = echo info
for try := 0; try < 50; try++ {
l, err := dialLine(sock, "")
if err != nil {
t.Fatal(err)
// still busy: the server told it so and hung up before the
// header was written (broken pipe); try again
last = err
if l != nil {
l.conn.Close()
}
time.Sleep(100 * time.Millisecond)
continue
}
last = l.expect("login: ")
l.conn.Close()
+261 -39
View File
@@ -15,6 +15,7 @@ import (
"github.com/D-Modem/menu/internal/confdoc"
"github.com/D-Modem/menu/internal/confedit"
"github.com/D-Modem/menu/internal/config"
"github.com/D-Modem/menu/internal/term"
"github.com/D-Modem/menu/internal/tui"
"github.com/D-Modem/menu/samples"
@@ -174,7 +175,7 @@ func (u *setupUI) fill(p *page) {
if kd == nil {
continue
}
e := tui.Entry{ID: "kind:" + k, Label: u.title(k), Help: kd.Help, Mark: "►"}
e := tui.Entry{ID: "kind:" + k, Label: u.title(k), Help: kindHelp(kd), Mark: "►"}
switch {
case kd.Named:
n := len(u.named(k))
@@ -202,8 +203,15 @@ func (u *setupUI) fill(p *page) {
items = append(items, tui.Entry{ID: "sec:" + s, Label: name, Value: v, Mark: "►",
Changed: u.changed(s, ""), Help: "Enter opens it; Del deletes it."})
}
items = append(items, tui.Entry{Heading: true}, tui.Entry{ID: "add", Label: "Add a new one…",
Help: "A new [" + p.kind.Name + " NAME]: its name first."})
add := tui.Entry{ID: "add", Label: "Add a new one…", Help: "A new [" + p.kind.Name + " NAME]: its name first."}
if p.kind.Name == "item" {
add.Label = "Add a menu item…"
add.Help = "A new item for the menu: start from one of the sample's (the BBS, PPP, a door, change password, last callers...) or an empty one, then give it a name. It is added to the menu's items."
}
if p.kind.Name == "number" {
add.Help = "Settings for one more phone number: type the caller's number as its name."
}
items = append(items, tui.Entry{Heading: true}, add)
case "section":
kd := p.kind
if kd.Free != "" {
@@ -218,12 +226,7 @@ func (u *setupUI) fill(p *page) {
known := map[string]bool{}
for _, k := range kd.Keys {
known[k.Name] = true
e := u.keyEntry(p.sec, k)
if strings.TrimSpace(k.Help) == "" && kd.Help != "" {
// the section's comment is the key's
e.Help = capFirst(strings.TrimSpace(kd.Help))
}
items = append(items, e)
items = append(items, u.keyEntry(p.sec, kd, k))
}
for _, k := range u.doc.Keys(p.sec) {
if !known[k] {
@@ -242,10 +245,19 @@ func (u *setupUI) fill(p *page) {
p.l.Fix()
}
// kindHelp: what a section is for
func kindHelp(kd *confdoc.Kind) string {
if d := setupDesc(kd.Name, ""); d != "" {
return d
}
return capFirst(strings.TrimSpace(kd.Help))
}
// keyEntry: a key's line in its section's window
func (u *setupUI) keyEntry(sec string, k *confdoc.Key) tui.Entry {
func (u *setupUI) keyEntry(sec string, kd *confdoc.Kind, k *confdoc.Key) tui.Entry {
e := tui.Entry{ID: "key:" + k.Name, Label: k.Name, Changed: u.changed(sec, k.Name)}
if v, ok := u.doc.Get(sec, k.Name); ok {
v, set := u.doc.Get(sec, k.Name)
if set {
e.Value = v
if v == "" {
e.Value = `""`
@@ -256,8 +268,11 @@ func (u *setupUI) keyEntry(sec string, k *confdoc.Key) tui.Entry {
e.Note = "sample: " + k.Value
}
}
e.Help = keyHelp(k)
if len(choices(k)) > 1 {
e.Help = setupDesc(kd.Name, k.Name)
if e.Help == "" {
e.Help = keyHelp(k)
}
if cs := u.choicesFor(sec, kd, k); cs != nil && len(cs.list) > 0 {
e.Mark = "↕"
}
return e
@@ -544,7 +559,8 @@ func (u *setupUI) command(id string) (bool, error) {
// setupKeys: Help > Keys
const setupKeys = "↑ ↓ PgUp PgDn Home End, or a letter: move the bar.\n" +
"Enter: open a window, change a value (typed, or picked from a list).\n" +
"Space: the next of a value's choices. Del: back to the default.\n" +
"Space: the next of a value's choices (in a list of checkboxes: check one).\n" +
"Del: back to the default.\n" +
"Esc: back a window. / or F12 or Alt and a letter: the menus.\n" +
"F1: the help of the line. F10: save. F9: quit. ^L: draw again."
@@ -582,8 +598,29 @@ func (u *setupUI) pick(p *page, space bool) error {
l: &tui.List{Title: "[" + s + "]", MinW: 56}})
}
case e.ID == "add":
var tpl *itemTemplate
suggestName := ""
if p.kind.Name == "item" {
tpls := itemTemplates(samples.Conf)
values, notes := []string{"An empty item"}, []string{"set it up from scratch"}
for _, t := range tpls {
values = append(values, t.get("label"))
notes = append(notes, firstSentence(t.about))
}
i, ok, err := d.Choose(u.frame(-1), "Add a menu item: start from", values, notes, 0)
if err != nil || !ok {
return err
}
if i > 0 {
tpl = &tpls[i-1]
suggestName = tpl.name
for n := 2; u.doc.Has("item " + suggestName); n++ {
suggestName = fmt.Sprintf("%s%d", tpl.name, n)
}
}
}
name, ok, err := d.Input(u.frame(-1), "New ["+p.kind.Name+" NAME]", "Its name (one word: letters, digits, - and _"+
map[bool]string{true: "; for a number, the caller's number", false: ""}[p.kind.Name == "number"]+"):", "", 32, false)
map[bool]string{true: "; for a number, the caller's number", false: ""}[p.kind.Name == "number"]+"):", suggestName, 32, false)
if err != nil || !ok || name == "" {
return err
}
@@ -594,7 +631,11 @@ func (u *setupUI) pick(p *page, space bool) error {
sec := p.kind.Name + " " + name
u.doc.AddSection(sec)
if p.kind.Name == "item" {
u.doc.Set(sec, "label", name)
if tpl != nil {
u.fromTemplate(sec, tpl)
} else {
u.doc.Set(sec, "label", name)
}
if v, ok := u.doc.Get(menuSection, "items"); ok {
u.doc.Set(menuSection, "items", strings.TrimSpace(v+" "+name))
}
@@ -670,7 +711,8 @@ func (u *setupUI) renameInItems(old, name string) {
u.doc.Set(menuSection, "items", strings.Join(out, " "))
}
// edit: a key's value: picked from its choices, or typed
// edit: a key's value: picked from its choices (or checked off, for a
// list of some at once), or typed
func (u *setupUI) edit(p *page, key string, space bool) error {
d := u.d
var k *confdoc.Key
@@ -681,53 +723,148 @@ func (u *setupUI) edit(p *page, key string, space bool) error {
k = &confdoc.Key{Name: key}
}
cur, set := u.doc.Get(p.sec, key)
cs := choices(k)
if len(cs) > 1 {
var cs *choiceSet
if p.kind != nil {
cs = u.choicesFor(p.sec, p.kind, k)
}
if cs != nil && len(cs.list) == 0 {
cs = nil
}
switch {
case cs != nil && cs.multi:
if space {
return nil
}
return u.editMulti(p, key, cs, cur, set)
case cs != nil:
if set && !cs.has(cur) {
cs.list = append(cs.list, choice{cur, "set now"})
}
at := -1
for i, c := range cs {
if strings.EqualFold(c, cur) {
for i, c := range cs.list {
if strings.EqualFold(c.value, cur) {
at = i
}
}
if space {
u.doc.Set(p.sec, key, cs[(at+1)%len(cs)])
u.doc.Set(p.sec, key, cs.list[(at+1)%len(cs.list)].value)
return nil
}
def := "(not set: the default)"
list := append(append([]string{}, cs...), def, "Type a value…")
values, notes := cs.values(), cs.notes()
values = append(values, "(not set)")
notes = append(notes, defaultNote(k))
if cs.open {
values = append(values, "Type another value…")
notes = append(notes, "")
}
start := at
if !set {
start = len(cs)
start = len(cs.list)
}
i, ok, err := d.Choose(u.frame(-1), key, list, nil, max(start, 0))
i, ok, err := d.Choose(u.frame(-1), key, values, notes, max(start, 0))
if err != nil || !ok {
return err
}
switch {
case i < len(cs):
u.doc.Set(p.sec, key, cs[i])
case i < len(cs.list):
u.doc.Set(p.sec, key, cs.list[i].value)
return nil
case i == len(cs):
case i == len(cs.list):
u.doc.Unset(p.sec, key)
return nil
}
} else if space {
case space:
return nil
}
prompt := strings.TrimSpace(k.Help)
if prompt != "" {
prompt = strings.ToUpper(prompt[:1]) + prompt[1:]
return u.typeValue(p, k, cur, set)
}
// defaultNote: what a key is when it is not set
func defaultNote(k *confdoc.Key) string {
if k.Value != "" {
return "the default (sample: " + k.Value + ")"
}
return "the default"
}
// editMulti: a list's values checked off; those set that the list does
// not have stay, after them
func (u *setupUI) editMulti(p *page, key string, cs *choiceSet, cur string, set bool) error {
have := config.Fields(cur)
// the ones set first, in their order (the order counts for some:
// [general] auth, [menu] items), then the rest
var list []choice
for _, v := range have {
note := "set now"
for _, c := range cs.list {
if strings.EqualFold(c.value, v) {
note = c.note
}
}
list = append(list, choice{v, note})
}
for _, c := range cs.list {
if !contains(have, c.value) {
list = append(list, c)
}
}
on := make([]bool, len(list))
for i := range have {
on[i] = true
}
all := &choiceSet{list: list}
extra := ""
if cs.open {
extra = "Type the list…"
}
out, typed, ok, err := u.d.ChooseMulti(u.frame(-1), key+": check the ones to have", all.values(), all.notes(), on, extra)
if err != nil || !ok {
return err
}
if typed {
var k *confdoc.Key
if p.kind != nil {
k = p.kind.ByKey[key]
}
if k == nil {
k = &confdoc.Key{Name: key}
}
return u.typeValue(p, k, cur, set)
}
var vs []string
for i, c := range list {
if out[i] {
vs = append(vs, c.value)
}
}
if len(vs) == 0 {
u.doc.Unset(p.sec, key)
return nil
}
u.doc.Set(p.sec, key, strings.Join(vs, " "))
return nil
}
// typeValue: a key's value typed in a box
func (u *setupUI) typeValue(p *page, k *confdoc.Key, cur string, set bool) error {
key := k.Name
prompt := ""
if p.kind != nil {
prompt = setupDesc(p.kind.Name, key)
}
if prompt == "" {
prompt = capFirst(strings.TrimSpace(k.Help))
}
if len(prompt) > 230 {
prompt = prompt[:229] + "…"
}
if !strings.HasSuffix(prompt, ".") && prompt != "" {
if !strings.HasSuffix(prompt, ".") && !strings.HasSuffix(prompt, ")") && prompt != "" {
prompt += "."
}
if !set && k.Value != "" {
prompt += " Sample: " + k.Value
}
v, ok, err := d.Input(u.frame(-1), "["+p.sec+"] "+key, prompt+" (Empty: not set, the default; \"\" for nothing.)", cur, 1024, false)
v, ok, err := u.d.Input(u.frame(-1), "["+p.sec+"] "+key, prompt+" (Empty: not set, the default; \"\" for nothing.)", cur, 1024, false)
if err != nil || !ok {
return err
}
@@ -765,7 +902,8 @@ func (u *setupUI) remove(p *page) error {
return nil
}
// help: F1, the whole help of the bar's line
// help: F1, the whole help of the bar's line: what it does, the
// sample's notes, and the values it may be picked from
func (u *setupUI) help(p *page) error {
e := p.l.Selected()
if e == nil {
@@ -774,9 +912,14 @@ func (u *setupUI) help(p *page) error {
text := e.Help
if strings.HasPrefix(e.ID, "key:") && p.kind != nil {
if k := p.kind.ByKey[strings.TrimPrefix(e.ID, "key:")]; k != nil {
text = keyHelp(k)
if len(k.Examples) > 0 {
text += "\n\nAlso: " + strings.Join(k.Examples, ", ")
text = keyFullHelp(setupDesc(p.kind.Name, k.Name), k, u.choicesFor(p.sec, p.kind, k))
}
}
if strings.HasPrefix(e.ID, "kind:") {
if kd := u.byKind[strings.TrimPrefix(e.ID, "kind:")]; kd != nil {
text = kindHelp(kd)
if h := capFirst(strings.TrimSpace(kd.Help)); h != "" && h != text {
text += "\n\nFrom the sample: " + h
}
}
}
@@ -784,6 +927,45 @@ func (u *setupUI) help(p *page) error {
return err
}
// keyFullHelp: a key's description, the sample's notes, its choices
func keyFullHelp(desc string, k *confdoc.Key, cs *choiceSet) string {
text := desc
sample := keyHelp(k)
closedNotes := cs != nil && !cs.open && len(cs.list) > 2
switch {
case text == "":
text = sample
case closedNotes:
// the list below says what the sample's help does
case strings.TrimSpace(k.Help) != "":
text += "\n\nFrom the sample: " + sample
case k.Value != "":
text += " Sample: " + k.Value
}
if cs != nil && len(cs.list) > 0 {
var b strings.Builder
switch {
case cs.multi:
b.WriteString("\n\nCheck any of:")
case cs.open:
b.WriteString("\n\nSuggested (or type your own):")
default:
b.WriteString("\n\nOne of:")
}
for _, c := range cs.list {
b.WriteString("\n " + c.value)
if c.note != "" {
b.WriteString(": " + c.note)
}
}
text += b.String()
}
if len(k.Examples) > 0 && (cs == nil || cs.open) {
text += "\n\nAlso in the sample: " + strings.Join(k.Examples, ", ")
}
return text
}
// summary: what the file sets up, for a check that passed
func (u *setupUI) summary() string {
items := len(u.named("item"))
@@ -1001,3 +1183,43 @@ func capFirst(s string) string {
// menuSection: [menu], whose items = the setup keeps up with the items'
const menuSection = "menu"
// fromTemplate: a new [item NAME] given a sample item's keys; its key a
// free one when the sample's is taken
func (u *setupUI) fromTemplate(sec string, t *itemTemplate) {
for _, kv := range t.keys {
u.doc.Set(sec, kv[0], kv[1])
}
key := strings.ToUpper(t.get("key"))
by, taken := u.takenKeys(sec)[key]
if key == "" || !taken {
return
}
for _, c := range u.keyChoices(sec).list {
if c.note == "free" {
u.doc.Set(sec, "key", c.value)
u.flash = "The sample's key " + key + " is " + by + ", so this item has " + c.value + "."
return
}
}
}
// firstSentence: s up to its first stop (". ", ": " or " ("), where
// that leaves a few words
func firstSentence(s string) string {
cut := len(s)
for _, sep := range []string{". ", ": ", " ("} {
for from := 0; ; {
i := strings.Index(s[from:], sep)
if i < 0 {
break
}
if from+i >= 12 {
cut = min(cut, from+i)
break
}
from += i + len(sep)
}
}
return s[:cut]
}
+517
View File
@@ -0,0 +1,517 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bufio"
"net"
"os"
"sort"
"strconv"
"strings"
"github.com/D-Modem/menu/internal/confdoc"
"github.com/D-Modem/menu/internal/config"
)
// The setup's pick lists: for a key whose values are a few known words,
// or are things the file or the machine already has (the items, the
// groups, the users, the system's accounts), the values to pick from,
// each with a note of what it is. A closed list takes nothing else; an
// open one is suggestions, and a value of one's own may still be typed; a
// multi one is checked off, some at once.
// choice is a value to pick, and its note.
type choice struct{ value, note string }
// choiceSet is what a key may be picked from.
type choiceSet struct {
list []choice
open bool // a value of one's own may be typed
multi bool // several at once, joined by spaces
}
func (c *choiceSet) values() []string {
out := make([]string, len(c.list))
for i, x := range c.list {
out[i] = x.value
}
return out
}
func (c *choiceSet) notes() []string {
out := make([]string, len(c.list))
for i, x := range c.list {
out[i] = x.note
}
return out
}
// has: whether v is one of the list's values (case aside)
func (c *choiceSet) has(v string) bool {
for _, x := range c.list {
if strings.EqualFold(x.value, v) {
return true
}
}
return false
}
// closed is a list of value, note pairs that takes nothing else.
func closed(kv ...string) *choiceSet { return pairs(false, false, kv) }
// suggest is a list of value, note pairs, a value of one's own allowed.
func suggest(kv ...string) *choiceSet { return pairs(true, false, kv) }
func pairs(open, multi bool, kv []string) *choiceSet {
c := &choiceSet{open: open, multi: multi}
for i := 0; i+1 < len(kv); i += 2 {
c.list = append(c.list, choice{kv[i], kv[i+1]})
}
return c
}
// add: a value not in the list yet
func (c *choiceSet) add(v, note string) {
if v != "" && !c.has(v) {
c.list = append(c.list, choice{v, note})
}
}
// choicesFor: what [sec] key is picked from; nil: it is typed
func (u *setupUI) choicesFor(sec string, kd *confdoc.Kind, k *confdoc.Key) *choiceSet {
kind := ""
if kd != nil {
kind = kd.Name
}
switch kind + "." + k.Name {
case "general.log":
return suggest("syslog", "the system log (auth facility)", "none", "no log",
"/var/log/modemmenu.log", "a file of its own")
case "general.auth":
c := pairs(false, true, []string{
"file", "the users file ([file])", "ldap", "an LDAP directory ([ldap])",
"sql", "an SQL database ([sql])", "system", "this machine's accounts by PAM ([system])"})
return c
case "general.password_echo":
return suggest("*", "a star for each character", "#", "a hash for each character", "none", "nothing at all")
case "general.time_limit", "general.daily_limit", "guest.time_limit":
return suggest("0", "no limit", "15m", "15 minutes", "30m", "half an hour", "1h", "an hour", "2h", "two hours")
case "general.time_warning":
return suggest("5m 1m", "at 5 minutes and at 1 minute left", "2m", "at 2 minutes left",
"10m 5m 1m", "at 10, 5 and 1 minutes left", "0", "no warnings")
case "general.state_dir":
return suggest("/var/lib/modemmenu", "the usual place")
case "terminal.petscii":
return closed("auto", "watch the login for a Commodore's keys", "yes", "every caller is a Commodore", "no", "never")
case "terminal.charset":
return closed("auto", "by the terminal", "utf8", "UTF-8", "cp437", "the IBM PC's (SyncTERM, BBS terminals)",
"dec", "a DEC VT's line drawing", "ascii", "plain + - | only")
case "file.hash":
return closed("auto", "by each line's prefix ($2b$, {SHA256}...)", "plain", "the rest of the line is the password")
case "file.path", "signup.file":
c := suggest("/etc/asterisk/modemmenu.users", "the usual place")
if p, ok := u.val("file", "path"); ok {
c.add(p, "[file] path")
}
return c
case "ldap.password_change":
return closed("exop", "Password Modify (OpenLDAP, 389 DS and most)", "ad", "Active Directory (ldaps or starttls only)")
case "ldap.url":
return suggest("ldaps://ldap.example.com", "TLS from the start", "ldap://ldap.example.com:389", "plain (use starttls)")
case "sql.driver":
return closed("mysql", "MySQL", "mariadb", "MariaDB", "postgres", "PostgreSQL", "sqlite", "an SQLite file")
case "sql.hash":
return closed("auto", "by the stored password's prefix", "bcrypt", "bcrypt hashes", "sha256", "SHA-256, hex",
"sha512", "SHA-512, hex", "ssha256", "salted SHA-256", "ssha512", "salted SHA-512",
"plain", "the password as it is", "none", "the query checks it: any row is a yes")
case "sql.update_hash":
return closed("bcrypt", "store a bcrypt hash", "none", "the password as typed (the query hashes it)")
case "sql.args":
return closed("user", "the query has one placeholder: the user", "user password", "user, then password",
"password user", "password, then user")
case "sql.update_args":
return suggest("password user", "new password, then user", "user password", "user, then new password",
"password user old_password", "new password, user, old password")
case "system.groups":
return u.groupChoices(true, false)
case "system.min_uid":
return suggest("1000", "most Linux systems' first user", "500", "older systems' first user", "0", "every account")
case "system.pam_service":
return suggest("modemmenu", "/etc/pam.d/modemmenu (modemmenu.pam.sample)", "login", "the console's", "sshd", "SSH's")
case "server.listen":
return u.listenChoices(sec, "/run/modemmenu/modemmenu.sock", "tcp:127.0.0.1:2323")
case "authd.listen":
return u.listenChoices(sec, "/run/modemmenu/auth.sock", "")
case "server.socket_mode", "authd.socket_mode":
return suggest("0660", "the owner and the group", "0600", "the owner only", "0666", "anyone on the machine")
case "server.socket_group", "authd.socket_group":
return u.systemGroupChoices()
case "authd.allow_users":
c := u.systemUserChoices()
c.multi = true
return c
case "ppp_pool.dns":
c := suggest()
c.multi = true
if v, ok := u.val("ppp_pool", "local"); ok {
c.add(v, "this server's PPP address (its resolver)")
}
for _, ns := range resolvConf() {
c.add(ns, "this machine's DNS server")
}
c.add("1.1.1.1", "Cloudflare")
c.add("8.8.8.8", "Google")
c.add("9.9.9.9", "Quad9")
return c
case "ppp_pool.local":
c := suggest("100.120.224.1", "the sample's subnet")
return c
case "autoppp.item", "number.item":
return u.itemChoices(false)
case "number.user":
return u.userChoices(false)
case "aol.networks":
return pairs(false, true, []string{"aolnet", "AOLnet", "sprintnet", "SprintNet", "tymnet", "Tymnet",
"p3", "a CCL script that starts P3 at once"})
case "aol.sprintnet_speed":
return suggest("11:14", "9600 bps and up (high-speed settings)", "11:12", "2400 bps")
case "aol.host":
return suggest("localhost:5190", "the BBS's AOL front end on this machine")
case "dropfile.emulation":
return closed("auto", "by the terminal detected", "ansi", "always ANSI", "ascii", "always plain text")
case "dropfile.comm_type":
return closed("0", "local: the door on its own input and output", "1", "serial", "2", "telnet")
case "dropfile.com_port":
return suggest("COM0:", "local", "COM1:", "the first port", "COM2:", "the second port")
case "dropfile.rate":
return suggest("38400", "a FOSSIL's usual rate", "19200", "", "57600", "", "115200", "", "connect", "the modem's real rate")
case "dropfile.security", "item.security":
c := suggest("10", "a caller", "50", "a trusted caller", "100", "a co-sysop", "255", "the sysop")
if kind == "item" {
c.list = append([]choice{{"0", "[dropfile]'s"}}, c.list...)
}
return c
case "menu.items":
return u.itemChoices(true)
case "menu.fullscreen":
return closed("auto", "a window for terminals that can have it", "no", "lines of text for everyone")
case "menu.hangup":
return suggest("G goodbye bye logoff", "the sample's", "G", "only G", "Q quit bye", "Q for quit")
case "item.mode":
return closed("exec", "a program on the line (command)",
"telnet", "a telnet server (host, port)",
"rlogin", "an rlogin server (host, port)",
"tcp", "a TCP server, raw (host, port)",
"unix", "a unix socket, raw (path)",
"passwd", "built in: change your password",
"callers", "built in: the last callers",
"setup", "built in: this setup (sysops only)")
case "item.tty":
return closed("raw", "the line as it is", "sane", "a normal terminal: echo, CR to LF")
case "item.after":
return closed("hangup", "hang up", "menu", "back to the menu")
case "item.door_sys_lines":
return closed("52", "the full DOOR.SYS", "31", "the old short one")
case "item.dropfile":
return pairs(false, true, []string{"door32.sys", "DOOR32.SYS (most newer doors)", "door.sys", "DOOR.SYS",
"dorinfo1.def", "DORINFO1.DEF", "dorinfo#.def", "DORINFOn.DEF by the node"})
case "item.terminal":
return suggest("ANSI", "", "{term}", "what the caller's terminal said", "VT100", "", "VT220", "", "xterm", "")
case "item.rlogin_terminal":
return suggest("ansi/{baud}", "ANSI at the connect rate", "{term}/{baud}", "the caller's terminal type")
case "item.run_as":
c := u.systemUserChoices()
c.list = append([]choice{{"{user}", "the caller's own account"}}, c.list...)
return c
case "item.users":
return u.userChoices(true)
case "item.groups":
return u.groupChoices(true, true)
case "item.min_baud":
return suggest("2400", "", "9600", "", "14400", "", "28800", "", "33600", "V.34 at its best")
case "item.host":
return suggest("127.0.0.1", "this machine", "localhost", "this machine, by name", "::1", "this machine, IPv6")
case "item.port":
return suggest("23", "telnet", "513", "rlogin", "2323", "a BBS's telnet")
case "item.path":
c := suggest()
for _, p := range sockets() {
c.add(p, "a socket on this machine")
}
return c
case "item.key":
return u.keyChoices(sec)
}
// the sample's own: yes or no, or the values its help names
if isBool(k.Value) {
return closed("yes", "", "no", "")
}
if cs := choices(k); len(cs) > 1 {
return &choiceSet{list: choiceNotes(k, cs)}
}
return nil
}
// choiceNotes: the notes the sample's help gives each value ("`passwd`:
// built in: ...; `callers`: ...")
func choiceNotes(k *confdoc.Key, cs []string) []choice {
var out []choice
for _, v := range cs {
note := ""
if i := strings.Index(k.Help, "`"+v+"`:"); i >= 0 {
note = strings.TrimSpace(k.Help[i+len(v)+3:])
if j := strings.Index(note, ";"); j >= 0 {
note = note[:j]
}
}
out = append(out, choice{v, note})
}
return out
}
// itemChoices: the [item NAME]s (multi: some, in the menu's order)
func (u *setupUI) itemChoices(multi bool) *choiceSet {
c := &choiceSet{multi: multi}
for _, s := range u.named("item") {
name := strings.TrimPrefix(s, "item ")
label, _ := u.val(s, "label")
mode, _ := u.val(s, "mode")
note := label
if mode != "" && mode != "exec" {
note += " (" + mode + ")"
}
c.list = append(c.list, choice{name, note})
}
return c
}
// takenKeys: what selects another item than [sec], or hangs up, and by
// what
func (u *setupUI) takenKeys(sec string) map[string]string {
taken := map[string]string{}
hangup, ok := u.val(menuSection, "hangup")
if !ok {
hangup = "G goodbye bye logoff"
}
for _, h := range config.Fields(strings.ToUpper(hangup)) {
taken[h] = "the hangup"
}
for _, s := range u.named("item") {
if s == sec {
continue
}
name := strings.TrimPrefix(s, "item ")
k, ok := u.val(s, "key")
if !ok {
k = name[:1]
}
taken[strings.ToUpper(k)] = "taken by [" + s + "]"
taken[strings.ToUpper(name)] = "taken by [" + s + "]"
v, _ := u.val(s, "aliases")
for _, a := range config.Fields(strings.ToUpper(v)) {
taken[a] = "taken by [" + s + "]"
}
}
return taken
}
// keyChoices: keys for [item NAME]: the letters of its name and label,
// each free or what has it already
func (u *setupUI) keyChoices(sec string) *choiceSet {
c := suggest()
taken := u.takenKeys(sec)
name := strings.TrimPrefix(sec, "item ")
label, _ := u.val(sec, "label")
for _, r := range strings.ToUpper(name + label) {
if !(r >= 'A' && r <= 'Z') && !(r >= '0' && r <= '9') {
continue
}
k := string(r)
if t, ok := taken[k]; ok {
c.add(k, t)
} else {
c.add(k, "free")
}
}
return c
}
// listenChoices: the socket's usual path, a TCP address, and the others'
// listen marked taken
func (u *setupUI) listenChoices(sec, path, tcp string) *choiceSet {
c := suggest(path, "the usual place")
if tcp != "" {
c.add(tcp, "TCP on this machine only")
}
for _, other := range []string{"server", "authd"} {
if other == sec {
continue
}
if v, ok := u.val(other, "listen"); ok {
for i := range c.list {
if c.list[i].value == v {
c.list[i].note = "taken by [" + other + "] listen"
}
}
}
}
return c
}
// userChoices: the users file's users (multi: some at once)
func (u *setupUI) userChoices(multi bool) *choiceSet {
c := &choiceSet{open: true, multi: multi}
path, ok := u.val("file", "path")
if !ok {
path = "/etc/asterisk/modemmenu.users"
}
for _, name := range usersIn(path) {
c.add(name, "in the users file")
}
return c
}
// groupChoices: [groups]'s, and with system the system's groups
func (u *setupUI) groupChoices(system, multi bool) *choiceSet {
c := &choiceSet{open: true, multi: multi}
if !system || multi {
for _, g := range u.doc.Keys("groups") {
v, _ := u.val("groups", g)
c.add(g, "[groups]: "+v)
}
}
if system {
for _, g := range systemGroups() {
c.add(g, "a system group")
}
}
return c
}
func (u *setupUI) systemGroupChoices() *choiceSet {
c := &choiceSet{open: true}
for _, g := range systemGroups() {
c.add(g, "")
}
return c
}
func (u *setupUI) systemUserChoices() *choiceSet {
c := &choiceSet{open: true}
for _, n := range systemUsers() {
c.add(n, "a system account")
}
return c
}
// usersIn: the names in a users file (user:hash lines)
func usersIn(path string) []string {
f, err := os.Open(path)
if err != nil {
return nil
}
defer f.Close()
var out []string
sc := bufio.NewScanner(f)
for sc.Scan() {
l := strings.TrimSpace(sc.Text())
if l == "" || l[0] == '#' {
continue
}
if name, _, ok := strings.Cut(l, ":"); ok && name != "" {
out = append(out, name)
}
}
return out
}
// etcFiles: where the system's accounts are read from (tests change them)
var etcPasswd, etcGroup, etcResolv = "/etc/passwd", "/etc/group", "/etc/resolv.conf"
// systemUsers: /etc/passwd's accounts that log in (uid 1000 and up), and
// the services' few that a BBS uses
func systemUsers() []string {
var out []string
for _, f := range colonFile(etcPasswd) {
if len(f) < 3 {
continue
}
uid, _ := strconv.Atoi(f[2])
if (uid >= 1000 && uid < 65534) || f[0] == "bbs" || f[0] == "asterisk" || f[0] == "nobody" {
out = append(out, f[0])
}
}
return out
}
// systemGroups: /etc/group's names
func systemGroups() []string {
var out []string
for _, f := range colonFile(etcGroup) {
out = append(out, f[0])
}
sort.Strings(out)
return out
}
func colonFile(path string) [][]string {
b, err := os.ReadFile(path)
if err != nil {
return nil
}
var out [][]string
for _, l := range strings.Split(string(b), "\n") {
if l = strings.TrimSpace(l); l == "" || l[0] == '#' {
continue
}
out = append(out, strings.Split(l, ":"))
}
return out
}
// resolvConf: the machine's DNS servers
func resolvConf() []string {
b, err := os.ReadFile(etcResolv)
if err != nil {
return nil
}
var out []string
for _, l := range strings.Split(string(b), "\n") {
f := strings.Fields(l)
if len(f) >= 2 && f[0] == "nameserver" && net.ParseIP(f[1]) != nil && !strings.HasPrefix(f[1], "127.") {
out = append(out, f[1])
}
}
return out
}
// sockets: the unix sockets of /run/modemmenu and /run/bbs
func sockets() []string {
var out []string
for _, dir := range []string{"/run/modemmenu", "/run/bbs"} {
es, _ := os.ReadDir(dir)
for _, e := range es {
if e.Type()&os.ModeSocket != 0 {
out = append(out, dir+"/"+e.Name())
}
}
}
return out
}
// val: a key's value in the file as it is now, and whether it is set
func (u *setupUI) val(sec, key string) (string, bool) { return u.doc.Get(sec, key) }
+230
View File
@@ -0,0 +1,230 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/D-Modem/menu/internal/confdoc"
"github.com/D-Modem/menu/internal/tui"
"github.com/D-Modem/menu/samples"
)
// TestEverySettingDescribed: each section and key of the sample, which
// is what the setup shows, has a description of what it does; and no
// description is left for a key the sample does not have
func TestEverySettingDescribed(t *testing.T) {
have := map[string]bool{}
for _, kd := range confdoc.Parse(samples.Conf) {
have[kd.Name] = true
if setupDesc(kd.Name, "") == "" {
t.Errorf("[%s]: no description", kd.Name)
}
for _, k := range kd.Keys {
have[kd.Name+"."+k.Name] = true
if setupDesc(kd.Name, k.Name) == "" {
t.Errorf("[%s] %s: no description", kd.Name, k.Name)
}
}
}
for k := range setupDescs {
if !have[k] {
t.Errorf("%s: described, but not in the sample", k)
}
}
}
// setupFor: a setup of a small file, with keys to type at it
func setupFor(t *testing.T, conf string) (*setupUI, *keyLine) {
t.Helper()
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("alice:{PLAIN}secret\nbob:{PLAIN}x\n"), 0o600)
path := filepath.Join(dir, "modemmenu.conf")
os.WriteFile(path, []byte(fmt.Sprintf(conf, users)), 0o640)
f := &keyLine{}
d := &tui.Desk{Line: f, Rows: 25, Cols: 80, Charset: tui.UTF8}
u, err := newSetup(d, path)
if err != nil {
t.Fatal(err)
}
return u, f
}
const choicesConf = `[general]
log = none
auth = file
[file]
path = %s
[groups]
sysops = alice
[menu]
items = bbs passwd
[item bbs]
key = B
label = Board
command = true
[item passwd]
key = PW
label = Password
mode = passwd
`
const (
kDown, kEnter, kEsc = "\x1b[B", "\r", "\x1b\x00"
)
// TestSetupChoices: the lists a key is picked from, with their notes
func TestSetupChoices(t *testing.T) {
u, _ := setupFor(t, choicesConf)
kd := func(n string) *confdoc.Kind { return u.byKind[n] }
get := func(kind, sec, key string) *choiceSet {
return u.choicesFor(sec, kd(kind), kd(kind).ByKey[key])
}
// closed, with notes: nothing else is typed
m := get("item", "item bbs", "mode")
if m.open || m.multi || !m.has("passwd") || !m.has("setup") {
t.Errorf("mode: %+v", m)
}
// the items, for [menu] items: checked off, with their labels
it := get("menu", "menu", "items")
if !it.multi || len(it.list) != 2 || it.list[0] != (choice{"bbs", "Board"}) || it.list[1].note != "Password (passwd)" {
t.Errorf("items: %+v", it)
}
// the users file's users; [groups]'s groups
if us := get("item", "item bbs", "users"); !us.has("alice") || !us.has("bob") || !us.multi {
t.Errorf("users: %+v", us)
}
if gs := get("item", "item bbs", "groups"); !gs.has("sysops") || gs.list[0].note != "[groups]: alice" {
t.Errorf("groups: %+v", gs)
}
// keys: what is taken says by what
keys := get("item", "item passwd", "key")
notes := map[string]string{}
for _, c := range keys.list {
notes[c.value] = c.note
}
if notes["P"] != "free" || notes["S"] != "free" || notes["B"] != "" {
t.Errorf("passwd's keys: %v", notes)
}
keys = get("item", "item bbs", "key")
for _, c := range keys.list {
notes[c.value] = c.note
}
if notes["B"] != "free" || notes["O"] != "free" {
t.Errorf("bbs's keys: %v", notes)
}
u.doc.Set("item bbs", "label", "Go play")
for _, c := range get("item", "item bbs", "key").list {
if c.value == "G" && c.note != "the hangup" {
t.Errorf("G: %q", c.note)
}
}
// a yes-or-no
if b := get("guest", "guest", "enabled"); b.open || len(b.list) != 2 {
t.Errorf("enabled: %+v", b)
}
// F1 lists them
h := keyFullHelp(setupDesc("item", "mode"), kd("item").ByKey["mode"], m)
if !strings.Contains(h, "One of:") || !strings.Contains(h, "passwd: built in: change your password") || !strings.HasPrefix(h, "What the item does") {
t.Errorf("help:\n%s", h)
}
}
// TestSetupMulti: [menu] items checked off: one unchecked, the order kept
func TestSetupMulti(t *testing.T) {
u, f := setupFor(t, choicesConf)
u.open("menu")
p := u.stack[len(u.stack)-1]
u.fill(p)
f.in = []byte(" " + kEnter) // bbs off
if err := u.edit(p, "items", false); err != nil {
t.Fatal(err)
}
if v, _ := u.doc.Get("menu", "items"); v != "passwd" {
t.Errorf("items = %q", v)
}
f.in = []byte(kDown + " " + kEnter) // bbs back on, after passwd
u.edit(p, "items", false)
if v, _ := u.doc.Get("menu", "items"); v != "passwd bbs" {
t.Errorf("items = %q", v)
}
}
// TestSetupAddItem: a menu item from the sample's: its keys, a free key
// when the sample's is taken, in the menu's items
func TestSetupAddItem(t *testing.T) {
u, f := setupFor(t, choicesConf)
u.open("item")
p := u.stack[len(u.stack)-1]
u.fill(p)
add := func(label string) {
t.Helper()
p.l.Cur = len(p.l.Items) - 1
if p.l.Items[p.l.Cur].ID != "add" {
t.Fatalf("not the add line: %+v", p.l.Items[p.l.Cur])
}
at := -1
for i, tp := range itemTemplates(samples.Conf) {
if tp.get("label") == label {
at = i + 1
}
}
if at < 0 {
t.Fatalf("no %q in the sample", label)
}
f.in = []byte(strings.Repeat(kDown, at) + kEnter + kEnter) // the template; its name as offered
if err := u.pick(p, false); err != nil {
t.Fatal(err)
}
u.stack = u.stack[:len(u.stack)-1]
u.fill(p)
}
add("Last callers")
if v, _ := u.doc.Get("item callers", "mode"); v != "callers" {
t.Errorf("callers' mode %q", v)
}
if v, _ := u.doc.Get("item callers", "key"); v != "LC" {
t.Errorf("callers' key %q", v)
}
add("Bulletin board") // B is bbs's
if v, _ := u.doc.Get("item bbs2", "key"); v != "S" {
t.Errorf("bbs2's key %q", v)
}
if v, _ := u.doc.Get("item bbs2", "mode"); v != "rlogin" {
t.Errorf("bbs2's mode %q", v)
}
if _, ok := u.doc.Get("item bbs2", "send"); ok {
t.Errorf("the sample's other way (send) taken as its own")
}
if v, _ := u.doc.Get("menu", "items"); v != "bbs passwd callers bbs2" {
t.Errorf("items = %q", v)
}
if err := checkConf(u.path, u.doc.String()); err != nil {
t.Errorf("does not check: %v", err)
}
}
// TestItemTemplates: the sample's items, each with its own keys
func TestItemTemplates(t *testing.T) {
ts := itemTemplates(samples.Conf)
by := map[string]itemTemplate{}
for _, x := range ts {
by[x.get("label")] = x
}
if p := by["PPP (dial-up networking)"]; p.get("time_warning") != "no" || !strings.HasPrefix(p.get("command"), "exec /usr/sbin/pppd") {
t.Errorf("ppp: %+v", p)
}
if s := by["Setup"]; s.get("mode") != "setup" || s.get("groups") != "sysops" {
t.Errorf("setup: %+v", s)
}
if len(ts) < 10 {
t.Errorf("%d templates", len(ts))
}
}
+225
View File
@@ -0,0 +1,225 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
// What each section and key of modemmenu.conf does, in a sentence or two
// for the sysop: the setup's help box shows it under the bar, and F1 adds
// the sample's own notes and the choices. The sample's comments are
// written for someone reading the file; these say what the setting is
// for. TestEverySettingDescribed keeps one for every section and key the
// sample has.
// setupDescs: "kind" for a section, "kind.key" for a key
var setupDescs = map[string]string{
// [general]
"general": "How callers log in: where modemmenu logs, which user databases it asks, what the caller sees before and after the menu, and how long a call may last.",
"general.log": "Where modemmenu writes its log: syslog, a file's path, or none. It never goes to the caller's line.",
"general.auth": "Which user databases check a login, in the order they are asked. A database that does not know the user passes to the next one; a wrong password stops at the first one that knows them.",
"general.banner": "The text every caller sees first, before the login prompt.",
"general.banner_file": "A file shown instead of the banner (it may hold ANSI colors). Read at every call.",
"general.login_prompt": "The prompt that asks the caller for their user name.",
"general.password_prompt": "The prompt that asks the caller for their password.",
"general.connect_message": "Shown after the banner when the connect rate is known: {speed} is the rate. \"\" shows nothing.",
"general.welcome": "Shown once a caller has logged in, before the message of the day. {user}, {date} and the other placeholders work here.",
"general.motd": "The message of the day: shown after the welcome, before the menu.",
"general.motd_file": "A file shown after motd as part of the message of the day, read at every login.",
"general.goodbye": "Shown at the end of the call, just before modemmenu hangs up.",
"general.password_echo": "What the caller sees for each password character they type: a character such as *, or none for nothing at all.",
"general.attempts": "How many wrong logins a caller gets before modemmenu hangs up.",
"general.fail_delay": "Seconds modemmenu waits after a wrong login before asking again, to slow down guessing.",
"general.login_timeout": "Seconds a caller has to log in before modemmenu hangs up.",
"general.idle_timeout": "Seconds the menu waits for a choice before it hangs up.",
"general.user_pattern": "A regular expression user names must match. Names that do not are refused before any user database is asked.",
"general.max_input": "The longest line a caller may type at a prompt (a password may be twice as long).",
"general.time_limit": "The longest a single call may last after login (0: no limit). Whatever is running is hung up when time runs out.",
"general.daily_limit": "The total time a user may spend on the line in a day, over all their calls (0: no limit).",
"general.state_dir": "The directory where modemmenu keeps what it remembers between calls: daily usage, the last callers, door nodes and PPP addresses.",
"general.time_warning": "When to warn the caller that their time is running out, as times before the limit (5m 1m). 0 turns the warnings off.",
"general.time_warning_message": "The warning written on the line when time is running out. {time_left} is in minutes, {seconds_left} in seconds; \\a beeps.",
// [terminal]
"terminal": "How modemmenu works out what kind of terminal the caller has (ANSI, VT52, a Commodore...) before the banner, so the menu and doors can use it.",
"terminal.detect": "Whether to ask the caller's terminal what it is before the banner. no: every caller is taken as a plain ANSI terminal.",
"terminal.petscii": "Whether to recognise Commodore (PETSCII) callers: auto watches the login for a Commodore's keys, yes treats every caller as one, no never does.",
"terminal.timeout": "How long to wait for each answer from the caller's terminal while detecting it.",
"terminal.charset": "Which characters the full-screen menu draws its boxes and shading with. auto picks by the terminal.",
// [groups]
"groups": "Your own groups of users, used by the menu items' groups setting to decide who sees an item. Each line is a group's name and its members.",
// [guest]
"guest": "A guest account: callers who log in with its name need no password, and only see the items marked for guests.",
"guest.enabled": "Turns the guest account on or off.",
"guest.name": "The user name a caller types to log in as a guest.",
"guest.time_limit": "How long a guest may stay on (never more than the general time_limit).",
// [signup]
"signup": "Lets callers create their own account from the login prompt. New accounts are added to the users file.",
"signup.enabled": "Turns sign-up on or off.",
"signup.name": "The user name a caller types at the login prompt to sign up.",
"signup.pending": "yes: new accounts are locked until the sysop unlocks them in the users file. no: they can log in at once.",
"signup.min_password": "The shortest password a new account may have.",
"signup.file": "The users file new accounts are written to. The [file] path by default.",
"signup.message": "Shown to a caller who starts signing up.",
// [callerid]
"callerid": "Which phone numbers may call: an allow list, a deny list, and whether callers without caller ID get in.",
"callerid.allow": "If set, only these numbers may call (* and ? match like file names).",
"callerid.deny": "These numbers are refused (* and ? match like file names).",
"callerid.anonymous": "Whether callers who withhold their number (no caller ID) are let in.",
"callerid.deny_message": "Shown to a caller who is refused by caller ID, before modemmenu hangs up.",
// [number NAME]
"number": "Settings for one caller's phone number: log them in as a user without a password, refuse them, or start an item for them at once.",
"number.user": "Logs this number in as this user without asking for a password. Caller ID can be forged, so only where your phone network vouches for it.",
"number.item": "The menu item started for this number right after login.",
"number.deny": "yes refuses calls from this number.",
// [file]
"file": "Users kept in a text file of user:password-hash lines.",
"file.path": "The users file.",
"file.hash": "How the passwords in the file are stored. auto tells by each line's prefix; plain takes the rest of the line as the password.",
// [ldap]
"ldap": "Users checked against an LDAP directory, by logging in to it as the user.",
"ldap.url": "The LDAP server: ldaps://host, or ldap://host:389.",
"ldap.starttls": "Whether to switch an ldap:// connection to TLS before sending passwords.",
"ldap.ca_file": "The certificate authority that signed the LDAP server's certificate, if it is not one the system trusts.",
"ldap.insecure_skip_verify": "yes skips checking the server's certificate. For testing only: anyone in between could read passwords.",
"ldap.timeout": "Seconds to wait for the LDAP server.",
"ldap.bind_dn": "The user's entry, with {user} in it, to log in as directly. Leave it out to search for the entry instead.",
"ldap.search_base": "Where in the directory to search for the user's entry.",
"ldap.search_filter": "The filter that finds the user's entry ({user} is their name). It can also restrict who may log in.",
"ldap.search_bind_dn": "The account the search runs as (empty: anonymously).",
"ldap.search_bind_password": "The password of search_bind_dn.",
"ldap.group_base": "Where groups are looked for, so items' groups can name LDAP groups. Not set: LDAP groups are not used.",
"ldap.group_filter": "The filter that finds a group the caller is a member of ({group}, {dn} and {user}).",
"ldap.password_change": "How the Change password item changes an LDAP password: exop for most servers, ad for Active Directory.",
// [system]
"system": "Logins checked against this machine's own accounts through PAM (local users, sssd, Kerberos...).",
"system.pam_service": "The PAM service name: the file in /etc/pam.d that says how to check the password.",
"system.min_uid": "Accounts with a lower user id (system accounts) may not log in.",
"system.allow_root": "Whether root may log in.",
"system.groups": "If set, only members of these system groups may log in.",
// [sql]
"sql": "Users checked against an SQL database (MySQL or MariaDB, PostgreSQL, SQLite).",
"sql.driver": "The kind of database.",
"sql.dsn": "How to connect to the database: its address, name and login, in the driver's own form.",
"sql.query": "The query that returns the user's stored password (or any row, with hash = none).",
"sql.args": "What fills the query's placeholders, in order: user, password.",
"sql.hash": "How the stored passwords are hashed. none: the query checks the password itself and any row means yes.",
"sql.timeout": "Seconds to wait for the database.",
"sql.update_query": "The query the Change password item runs. Without it, SQL passwords cannot be changed from the menu.",
"sql.update_args": "What fills update_query's placeholders, in order: user, password, old_password.",
"sql.update_hash": "How a changed password is stored: bcrypt, or none for a query that hashes it itself.",
// [server]
"server": "modemmenu -serve: one modemmenu answering every call on a socket, instead of one started for each call.",
"server.listen": "Where -serve listens: a unix socket's path, or tcp:host:port.",
"server.socket_mode": "The unix socket's permissions (octal): who may connect to it.",
"server.socket_group": "The group that owns the unix socket (Asterisk's, for app_dmodem).",
"server.header": "Whether each connection starts with the call's details (caller ID, rate...). app_dmodem and modemmenu items with header = yes send them.",
"server.header_timeout": "Seconds to wait for those details on a new connection.",
"server.trust_user": "yes: a caller already logged in by another modemmenu is not asked to log in again. Only for a socket that nothing else can reach.",
"server.max_sessions": "How many calls -serve takes at once; more callers are told the lines are busy.",
// [authd]
"authd": "The auth socket: lets the BBS's other logins (telnet, SSH, the web) check passwords against the same user databases as the dial-up login.",
"authd.listen": "The auth socket's path.",
"authd.socket_mode": "The socket's permissions (octal): who may connect to it.",
"authd.socket_group": "The group that owns the socket.",
"authd.allow_users": "The system users whose programs may ask the socket (the BBS's user).",
"authd.max_clients": "How many requests the socket answers at once.",
// [ppp_pool]
"ppp_pool": "The addresses PPP (dial-up networking) callers get, so several lines can run PPP at once, each with its own.",
"ppp_pool.local": "This server's own address on every PPP link.",
"ppp_pool.range": "The addresses handed out to callers, first-last. Pick a subnet none of the host's networks use.",
"ppp_pool.dns": "The DNS servers offered to PPP callers (one or two). This server's PPP address by default.",
// [autoppp]
"autoppp": "Starts PPP straight away for dialers that send PPP instead of logging in (Windows Dial-Up Networking and most others). The login is checked by PAP.",
"autoppp.enabled": "Turns AutoPPP on or off.",
"autoppp.command": "The command run on the line for such a caller: pppd with the modemmenu.so plugin.",
"autoppp.item": "The menu item whose access rules (groups, minimum speed, caller IDs...) a PPP caller must pass.",
// [aol]
"aol": "Lets the classic AOL client (2.5 to 4.0) dial in: modemmenu plays the network it expects, then connects it to the BBS's AOL front end.",
"aol.enabled": "Turns AOL dial-in on or off.",
"aol.host": "The BBS's AOL front end, host:port.",
"aol.networks": "Which networks modemmenu pretends to be for the AOL client.",
"aol.aolnet_prompt": "The greeting AOLnet's script waits for. Every caller sees it before the login prompt.",
"aol.sprintnet_speed": "The answer to SprintNet's speed question. 11:14 makes the client use its high-speed settings.",
// [dropfile]
"dropfile": "The door drop files (DOOR32.SYS, DOOR.SYS, DORINFO) written for door games: what they say about the BBS and how the door reaches the caller.",
"dropfile.bbs_name": "The BBS's name, as doors show it.",
"dropfile.sysop": "The sysop's name, as doors show it.",
"dropfile.security": "The security level callers get in the drop files (an item's own security overrides it).",
"dropfile.emulation": "What the drop files say the caller's terminal is: auto by the terminal detected, or always ansi or ascii.",
"dropfile.comm_type": "How the door talks to the caller, in DOOR32.SYS: 0 on its own input and output (the usual), 1 serial, 2 telnet.",
"dropfile.comm_handle": "The handle DOOR32.SYS gives with comm_type (-1 with 0).",
"dropfile.com_port": "The COM port DOOR.SYS and DORINFO name (COM0: is local). Under DOSEMU, the one DOSEMU gives the door.",
"dropfile.fossil": "Whether the drop files say a FOSSIL driver is there (DOS doors under DOSEMU).",
"dropfile.rate": "The speed the drop files give: a fixed rate doors accept, or connect for the modem's real rate.",
"dropfile.four_digit_years": "Write dates with four-digit years in DOOR.SYS, for newer doors that want them.",
"dropfile.max_nodes": "How many doors may run at once, each on its own node (15 at most with dorinfo#.def).",
// [menu]
"menu": "The menu callers see after they log in: its title, prompt, items, and the words that hang up.",
"menu.title": "The menu's title.",
"menu.prompt": "The prompt under the menu. {time_left} shows the minutes left.",
"menu.items": "Which items the menu shows, in order. Not set: every [item] in the file, in file order.",
"menu.hangup": "What the caller types to hang up; the first one is shown in the menu.",
"menu.hotkeys": "yes: one key picks an item at once, without Enter (every item's key must then be one character).",
"menu.fullscreen": "auto: callers whose terminal can do it get the menu in a window, picked with the cursor keys. no: everyone gets the menu as lines of text.",
// [item NAME]
"item": "A menu item: a program run on the line, a server the caller is connected to, or one of modemmenu's own (change password, last callers, setup).",
"item.key": "The key the caller types to pick this item (by default the first letter of its name).",
"item.aliases": "More words the caller can type to pick it (its name always works).",
"item.label": "The item's line in the menu.",
"item.help": "A line saying what the item is, shown under the full-screen menu.",
"item.mode": "What the item does: run a program, connect to a server, or one of modemmenu's own.",
"item.command": "The program run on the line (by /bin/sh), for mode = exec. {user} and the other placeholders work here.",
"item.run_as": "The system user the program runs as (modemmenu must run as root).",
"item.tty": "How the line is set up for the program: raw as it comes, or sane for programs that expect a normal terminal.",
"item.pass_password": "Whether the program gets the caller's password ({password}, MODEM_PASSWORD).",
"item.session_file": "yes: the call's details go in a JSON file the program can read (MODEM_SESSION_FILE).",
"item.after": "What happens when the item ends: hang up, or back to the menu.",
"item.connect_timeout": "Seconds to wait for the server to answer.",
"item.terminal": "The terminal type telnet tells the server.",
"item.header": "yes: sends the call's details to the server first, for modemmenu -serve or the BBS.",
"item.handoff": "yes: hands the caller's line itself to the server (unix socket and header = yes), instead of copying it through modemmenu.",
"item.users": "If set, only these users see the item (or members of its groups).",
"item.groups": "If set, only members of these groups see the item (or its users).",
"item.min_baud": "Only callers connected at least this fast see the item.",
"item.callerids": "Only callers whose number matches one of these see the item.",
"item.guest": "Whether the guest account sees the item.",
"item.dropfile": "Door drop files written for the program before it starts and removed after.",
"item.dropfile_lowercase": "Names the drop files in lower case, for doors on Linux.",
"item.dropfile_dir": "Where the drop files are written ({node} is the door's node). Not set: a new directory each time.",
"item.door_sys_lines": "52 for the full DOOR.SYS, or 31 for the old short one some doors want.",
"item.security": "The security level this door's drop files give (0: the one in [dropfile]).",
"item.host": "The server to connect to.",
"item.port": "The server's port.",
"item.path": "A unix socket to connect to instead of a host and port.",
"item.send": "Sent to the server as soon as it answers, such as a login: {user}\\r{password}\\r.",
"item.rlogin_client_user": "rlogin's client user name ({password} for BBSes that take the password there).",
"item.rlogin_server_user": "rlogin's server user name: the caller's user name on the server.",
"item.rlogin_terminal": "The terminal type and speed rlogin tells the server.",
"item.time_warning": "Whether time warnings are written on the line while this item runs (no for PPP, where they would break the link).",
"item.min_password": "The shortest new password the Change password item accepts.",
"item.count": "How many callers the Last callers item shows.",
}
// setupDesc: a section's (key "") or key's description, "" none
func setupDesc(kind, key string) string {
if key == "" {
return setupDescs[kind]
}
return setupDescs[kind+"."+key]
}
+94
View File
@@ -0,0 +1,94 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"regexp"
"strings"
"github.com/D-Modem/menu/internal/confdoc"
)
// itemTemplate is a menu item of the sample's (set or commented out), to
// start a new [item] from: "Add a menu item" offers each.
type itemTemplate struct {
name string
about string // the sample's comment before it, or its label
keys [][2]string // its keys, in order
}
var (
tplHeaderRE = regexp.MustCompile(`^;?\[item (\S+)\]$`)
tplKeyRE = regexp.MustCompile(`^;?([a-z][a-z0-9_]*) = (.*)$`)
)
// itemTemplates: the sample's items, each once (by its label)
func itemTemplates(sample string) []itemTemplate {
var out []itemTemplate
var prose []string
var cur *itemTemplate
alt := false
seen := map[string]bool{}
flush := func() {
if cur != nil && len(cur.keys) > 0 {
label := cur.get("label")
if !seen[label] {
seen[label] = true
if cur.about == "" {
cur.about = label
}
out = append(out, *cur)
}
}
cur = nil
}
for _, raw := range strings.Split(sample, "\n") {
line := strings.TrimRight(raw, " \t\r")
if line == "" {
flush()
prose = nil
continue
}
if m := tplHeaderRE.FindStringSubmatch(line); m != nil {
flush()
cur, alt = &itemTemplate{name: m[1]}, false
if len(prose) > 0 {
cur.about = capFirst(strings.Join(prose, " "))
}
prose = nil
continue
}
if strings.HasPrefix(line, "[") {
flush()
prose = nil
continue
}
if cur != nil {
if m := tplKeyRE.FindStringSubmatch(line); m != nil {
// after a comment in an item, the commented keys are its
// alternatives ("; or a BBS that ..."), not its own
if !(alt && strings.HasPrefix(line, ";")) {
cur.keys = append(cur.keys, [2]string{m[1], confdoc.Unquote(m[2])})
}
continue
}
alt = true
continue
}
if strings.HasPrefix(line, ";") {
prose = append(prose, strings.TrimSpace(strings.TrimLeft(line, ";")))
}
}
flush()
return out
}
func (t *itemTemplate) get(key string) string {
for _, kv := range t.keys {
if kv[0] == key {
return kv[1]
}
}
return ""
}
+2
View File
@@ -121,6 +121,7 @@ There may be any number of these, each with its own NAME.
|---|---|---|
| `user` | `alice` | See the section above. |
| `item` | `ppp` | See the section above. |
| `deny` | `no` | See the section above. |
## `[file]`
@@ -173,6 +174,7 @@ SQL: query gets args (user, password, in that order of placeholders) and returns
| `query` | `SELECT password FROM users WHERE username = ? AND enabled = 1` | mysql (or mariadb), postgres, sqlite. Also: `SELECT 1 FROM users WHERE username = $1 AND password = crypt($2, password)`, `SELECT password FROM users WHERE username = ?`. |
| `args` | `user` | mysql (or mariadb), postgres, sqlite. Also: `user password`. |
| `hash` | `auto` | mysql (or mariadb), postgres, sqlite. Also: `none`. |
| `timeout` | `10` | seconds to wait for the database. |
| `update_query` | `UPDATE users SET password = ? WHERE username = ?` | mode = passwd items: update_query sets the password, with update_args (user, password, old_password, in the order of its placeholders); update_hash = bcrypt stores a bcrypt hash, none the password as typed (for a query that hashes it). Without update_query, SQL passwords cannot be changed from the menu. Also: `UPDATE users SET password = crypt($1, gen_salt('bf')) WHERE username = $2`. |
| `update_args` | `password user` | mode = passwd items: update_query sets the password, with update_args (user, password, old_password, in the order of its placeholders); update_hash = bcrypt stores a bcrypt hash, none the password as typed (for a query that hashes it). Without update_query, SQL passwords cannot be changed from the menu. |
| `update_hash` | `bcrypt` | mode = passwd items: update_query sets the password, with update_args (user, password, old_password, in the order of its placeholders); update_hash = bcrypt stores a bcrypt hash, none the password as typed (for a query that hashes it). Without update_query, SQL passwords cannot be changed from the menu. Also: `none`. |
+41 -6
View File
@@ -16,19 +16,54 @@ modemmenu -setup -config /etc/asterisk/modemmenu.conf
Dial-up and Server (the same as the bar's menus). Enter opens one: its
keys and their values, `(not set)` and the sample's value for those the
file leaves out.
- Every section and key has a line under the bar saying what it does,
written for the sysop; **F1** adds the sample's own notes and the values
it can be picked from.
- **Enter** changes the value under the bar: typed in a box (cursor keys,
Home, End, Del, ^U), or picked from a list for a key the sample gives
the choices of (`yes`/`no`, `petscii = auto|yes|no`...). **Space** steps
through the choices; **Del** takes the key out (its default again). An
empty box is "not set"; type `""` for an empty value.
Home, End, Del, ^U), or picked from a list (a `↕` at the right of the
line). **Space** steps through the choices; **Del** takes the key out
(its default again). An empty box is "not set"; type `""` for an empty
value.
- `[item NAME]` and `[number NAME]` are lists: add one, open it, rename
it or delete it. An item renamed or deleted is renamed or taken out of
`[menu] items` too. `[groups]` takes groups of the sysop's own names.
- **Add a menu item** starts from one of the sample's items (the BBS by
rlogin or by handoff, PPP, change password, last callers, a door, a
shell, ZMODEM...) or an empty one. Its keys are filled in, it goes on
`[menu] items`, and when the sample's key is taken by another item it
gets a free one.
### Values picked from what there is
Most keys are picked from a list rather than typed, each value with a
note of what it is. Some lists are the only values a key takes (`mode`,
`tty`, `after`, `charset`, `petscii`, `driver`, `hash`, `emulation`,
`comm_type`, `fullscreen`, `password_change`, every `yes`/`no`); the
rest are suggestions, with "Type another value…" for one's own. Lists of
several values have checkboxes (Space checks one, Enter is done):
| Key | Offered |
|---|---|
| `[general] auth` | file, ldap, sql, system, checked in the order they are asked |
| `[menu] items` | each `[item]` with its label and mode, in the menu's order |
| `[item] key` | the letters of the item's name and label, each "free" or "taken by [item x]" / "the hangup" |
| `[item] users`, `[number] user` | the users file's users |
| `[item] groups`, `[system] groups` | `[groups]`' groups with their members, and the system's groups |
| `[item] run_as`, `[authd] allow_users` | `{user}`, and the system's login accounts |
| `[item] dropfile` | door32.sys, door.sys, dorinfo1.def, dorinfo#.def |
| `[item] path` | the sockets in /run/modemmenu and /run/bbs |
| `[autoppp] item`, `[number] item` | the menu's items |
| `[server]`/`[authd] listen` | the usual socket, marked "taken by" when the other uses it |
| `socket_group`, `socket_mode` | the system's groups; 0660, 0600, 0666 |
| `[ppp_pool] dns` | this server's PPP address, resolv.conf's servers, Cloudflare, Google, Quad9 |
| `[aol] networks` | aolnet, sprintnet, tymnet, p3 |
| time limits, `time_warning`, `min_baud`, `rate`, `security`, `log`... | common values |
- **F1** shows the whole help of the line, **/** (or F12, or Alt and a
letter) the menus, **Esc** goes back a window, **F10** saves, **F9**
quits (asking to save what changed). `^L` draws the screen again.
- The help of every key is the sample's ([reference](reference.md)), built
into the program.
- The descriptions are built into the program; the sample's notes are
those of the [reference](reference.md).
Saving checks the file first, as `modemmenu -check` does; a file that
does not check is saved only when asked again ("Save anyway"). The file
+55
View File
@@ -243,3 +243,58 @@ func itoa(n int) string {
}
return string(b)
}
// ChooseMulti is a list over base of choices to check some of: [x] before
// each checked one, Space checks or unchecks the bar's, Enter is done.
// extra, when not "", is a last line that ends the list another way (such
// as "Type the list…"): picked, extraPicked is true. on is what is
// checked at first; the result, what is checked at the end.
func (d *Desk) ChooseMulti(base *Screen, title string, choices, notes []string, on []bool, extra string) (out []bool, extraPicked, ok bool, err error) {
out = make([]bool, len(choices))
copy(out, on)
l := &List{Title: title, Center: true}
build := func() {
l.Items = l.Items[:0]
for i, c := range choices {
box := "[ ] "
if out[i] {
box = "[x] "
}
e := Entry{Label: box + c}
if i < len(notes) && notes[i] != "" {
e.Value, e.Unset = notes[i], true
}
l.Items = append(l.Items, e)
}
if extra != "" {
l.Items = append(l.Items, Entry{Heading: true}, Entry{Label: extra})
}
}
build()
l.Fix()
for {
build()
scr := base.Clone()
l.Draw(d, scr, true)
d.KeyBar(scr, Hints("Space", "Check", "Enter", "Done", "Esc", "Cancel"), "")
if err := d.Show(scr); err != nil {
return on, false, false, err
}
k, _, err := d.Key(-1)
if err != nil {
return on, false, false, err
}
switch {
case k == KeyEnter && l.Cur >= len(choices):
return out, true, true, nil
case k == KeyEnter:
return out, false, true, nil
case k == ' ' && l.Cur < len(choices):
out[l.Cur] = !out[l.Cur]
case k == KeyEsc || k == KeyLeft:
return on, false, false, nil
default:
l.Move(d, k)
}
}
}
+17
View File
@@ -151,6 +151,23 @@ func TestDialogs(t *testing.T) {
if i, ok, _ := d.Choose(base, "Pick", []string{"a", "b", "c"}, nil, 0); !ok || i != 2 {
t.Errorf("choice %d %v", i, ok)
}
// checkboxes: the first off, the third on; the extra line
f.in = []byte(" \x1b[B\x1b[B \r")
on, extra, ok, _ := d.ChooseMulti(base, "Some", []string{"a", "b", "c"}, nil, []bool{true, true, false}, "Type…")
if !ok || extra || on[0] || !on[1] || !on[2] {
t.Errorf("checked %v %v %v", on, extra, ok)
}
if txt := d.Screen().Text(); !strings.Contains(txt, "[x] c") || !strings.Contains(txt, "[ ] a") {
t.Errorf("boxes not drawn:\n%s", txt)
}
f.in = []byte("\x1b[F\r")
if _, extra, ok, _ := d.ChooseMulti(base, "Some", []string{"a"}, nil, nil, "Type…"); !ok || !extra {
t.Errorf("extra %v %v", extra, ok)
}
f.in = []byte(" \x1b")
if on, _, ok, _ := d.ChooseMulti(base, "Some", []string{"a"}, nil, []bool{false}, ""); ok || on[0] {
t.Errorf("Esc: %v %v", on, ok)
}
}
// TestPullDown: a menu pulled down, moved across, an item picked
+4 -1
View File
@@ -154,6 +154,7 @@ deny_message = "\r\nThis line does not take your call.\r\n"
;[number 5551234]
;user = alice
;item = ppp
;deny = no
; users in a text file: user:hash, # comments. hash: bcrypt ($2b$...,
; modemmenu -hash makes one), {SHA256}hex, {SHA512}hex, {SSHA256}base64,
@@ -212,6 +213,8 @@ dsn = modem:secret@tcp(127.0.0.1:3306)/bbs
query = SELECT password FROM users WHERE username = ? AND enabled = 1
args = user
hash = auto
; seconds to wait for the database
;timeout = 10
; mode = passwd items: update_query sets the password, with update_args
; (user, password, old_password, in the order of its placeholders);
; update_hash = bcrypt stores a bcrypt hash, none the password as typed
@@ -508,7 +511,6 @@ after = menu
; More items, to copy into items = above. Each needs its program installed;
; run_as = {user} (modemmenu as root) keeps callers in their own accounts.
; who called last
; a DOS door under DOSEMU (its command line depends on your DOSEMU's
; version and setup: an example to adapt)
;[item lord]
@@ -520,6 +522,7 @@ after = menu
;command = cd /srv/doors/lord && exec dosemu -dumb -E "lord.bat $MODEM_NODE"
;after = menu
; who called last
;[item callers]
;key = LC
;label = Last callers