Split the code into packages: cmd/modemmenu, internal/*, authd

All of modemmenu was one package main in the repository's root.  It is
now one module with the program and the pieces it is made of apart:

  cmd/modemmenu/     the program (the login, the menu, access, limits,
                     the selections, -serve, AutoPPP, drop files, the
                     auth socket's server)
  internal/config/   modemmenu.conf's sections and keys, {name} templates
  internal/term/     the caller's line, terminal detection, PETSCII
  internal/auth/     the backends and password changes
  internal/telnet/   the telnet client of mode = telnet items
  authd/             the auth socket's protocol and a client, for a BBS
                     to import (bbs's internal/menuauth is a copy of it)
  samples/           the .conf, .users, .pam and .service samples

make builds ./cmd/modemmenu and installs the samples from samples/; the
docs, confref and the site's reference follow.  The tests are where
their code is, none lost.  TestSampleHasEveryKey now reads the keys of
internal/ too (and the exported Get, Bool...: it would have found none).
.gitignore's "modemmenu" ignored cmd/modemmenu/ as well: it is
/modemmenu now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRRbjf74j8oq9R3PXhA
This commit is contained in:
Claude committed 2026-11-06 03:12:02 +00:00
1 parent ab86caaf50
commit 80d0fda167
77 files changed
+2653 -2283

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
# modemmenu's site, https://d-modem.github.io/menu/: docs/ and the README
# with brand's shared theme and workflow (brand's docs/sites.md). A pull
# request builds it, main deploys it. It fails if docs/reference.md isn't
# what modemmenu.conf.sample makes now (go run ./tools/confref).
# what samples/modemmenu.conf.sample makes now (go run ./tools/confref).
name: Pages
on:
push:
+1 -1
View File
@@ -1,4 +1,4 @@
modemmenu
/modemmenu
pbx-modem
/menu
*.so
+4 -4
View File
@@ -30,7 +30,7 @@ pppd/modemmenu.so: pppd/modemmenu.c
# -buildvcs=false: nothing reads the VCS stamp, and git refuses a checkout
# owned by another user (sudo make in your own clone), which fails the build
modemmenu: FORCE
$(GO) build -buildvcs=false $(TAGS) -o $@ .
$(GO) build -buildvcs=false $(TAGS) -o $@ ./cmd/modemmenu
test:
$(GO) vet $(TAGS) ./...
@@ -39,11 +39,11 @@ test:
install: all
install -D -m 755 modemmenu $(DESTDIR)$(BINDIR)/modemmenu
[ -e $(DESTDIR)$(CONF_DIR)/modemmenu.conf ] || \
install -D -m 640 modemmenu.conf.sample $(DESTDIR)$(CONF_DIR)/modemmenu.conf
install -D -m 640 samples/modemmenu.conf.sample $(DESTDIR)$(CONF_DIR)/modemmenu.conf
[ -e $(DESTDIR)$(CONF_DIR)/modemmenu.users ] || \
install -D -m 600 modemmenu.users.sample $(DESTDIR)$(CONF_DIR)/modemmenu.users
install -D -m 600 samples/modemmenu.users.sample $(DESTDIR)$(CONF_DIR)/modemmenu.users
[ $(PAM) != 1 ] || [ -e $(DESTDIR)/etc/pam.d/modemmenu ] || \
install -D -m 644 modemmenu.pam.sample $(DESTDIR)/etc/pam.d/modemmenu
install -D -m 644 samples/modemmenu.pam.sample $(DESTDIR)/etc/pam.d/modemmenu
[ $(PPPD) != 1 ] || \
install -D -m 644 pppd/modemmenu.so $(DESTDIR)$(PPPD_PLUGIN_DIR)/modemmenu.so
+1 -1
View File
@@ -58,7 +58,7 @@ The documentation is also a website, [d-modem.github.io/menu](https://d-modem.gi
[docs/](docs/README.md) has building, running, configuration,
authentication, PPP, security and the tests.
[modemmenu.conf.sample](modemmenu.conf.sample) has every option.
[samples/modemmenu.conf.sample](samples/modemmenu.conf.sample) has every option.
## The D-Modem suite
+29
View File
@@ -0,0 +1,29 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
// Package authd is modemmenu's auth socket ([authd] in modemmenu.conf),
// for the programs that ask it: modemmenu's backends (its users file,
// LDAP, SQL, the system's accounts by PAM) answer whether a password is a
// user's, so that a BBS's other logins (telnet, SSH, the web) take the
// same one as the dial-up line. One request a connection, a JSON line
// each way:
//
// {"user": "alice", "password": "..."}
// {"ok": true, "auth": "ldap"} or {"ok": false, "error": "denied"}
package authd
// Request is what a client sends.
type Request struct {
User string `json:"user"`
Password string `json:"password"`
}
// Reply is modemmenu's answer.
type Reply struct {
OK bool `json:"ok"`
Auth string `json:"auth,omitempty"` // the backend that took it
Error string `json:"error,omitempty"` // denied, refused, bad request
}
// MaxRequest is the longest request line modemmenu reads.
const MaxRequest = 4096
+56
View File
@@ -0,0 +1,56 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package authd
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"net"
"time"
)
// Client asks the socket at Socket.
type Client struct {
Socket string
Timeout time.Duration // for an answer (modemmenu waits fail_delay before a no); 0: 15s
}
// Check asks whether pw is user's password: true and the backend that
// said so, false if it is not; an error if modemmenu could not be asked
// or would not answer (refused: not a client it answers).
func (c *Client) Check(user, pw string) (bool, string, error) {
timeout := c.Timeout
if timeout <= 0 {
timeout = 15 * time.Second
}
conn, err := net.DialTimeout("unix", c.Socket, timeout)
if err != nil {
return false, "", err
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(timeout))
b, _ := json.Marshal(Request{User: user, Password: pw})
if _, err := conn.Write(append(b, '\n')); err != nil {
return false, "", err
}
line, err := bufio.NewReader(conn).ReadSlice('\n')
if err != nil {
return false, "", fmt.Errorf("no answer: %w", err)
}
var r Reply
if err := json.Unmarshal(line, &r); err != nil {
return false, "", fmt.Errorf("an answer not understood: %q", line)
}
switch {
case r.OK:
return true, r.Auth, nil
case r.Error == "denied":
return false, "", nil
case r.Error != "":
return false, "", errors.New(r.Error)
}
return false, "", fmt.Errorf("an answer not understood: %q", line)
}
+67
View File
@@ -0,0 +1,67 @@
package authd
import (
"bufio"
"encoding/json"
"net"
"path/filepath"
"testing"
"time"
)
// serve answers as modemmenu's [authd] would: alice/secret, then a
// refusal for "eve", and silence for "slow".
func serve(t *testing.T) string {
sock := filepath.Join(t.TempDir(), "auth.sock")
ln, err := net.Listen("unix", sock)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func() {
defer c.Close()
line, _ := bufio.NewReader(c).ReadBytes('\n')
var r Request
json.Unmarshal(line, &r)
switch {
case r.User == "slow":
time.Sleep(time.Second)
case r.User == "eve":
c.Write([]byte(`{"ok":false,"error":"refused"}` + "\n"))
case r.User == "alice" && r.Password == "secret":
c.Write([]byte(`{"ok":true,"auth":"file"}` + "\n"))
default:
c.Write([]byte(`{"ok":false,"error":"denied"}` + "\n"))
}
}()
}
}()
return sock
}
// TestCheck: the helper's yes (with how), its no, its refusal (an error),
// a helper too slow, and no helper at all.
func TestCheck(t *testing.T) {
c := &Client{Socket: serve(t), Timeout: 300 * time.Millisecond}
if ok, auth, err := c.Check("alice", "secret"); !ok || auth != "file" || err != nil {
t.Errorf("alice: %v %q %v", ok, auth, err)
}
if ok, _, err := c.Check("alice", "wrong"); ok || err != nil {
t.Errorf("wrong: %v %v", ok, err)
}
if _, _, err := c.Check("eve", "x"); err == nil || err.Error() != "refused" {
t.Errorf("eve: %v", err)
}
if _, _, err := c.Check("slow", "x"); err == nil {
t.Error("slow: no time out")
}
if _, _, err := (&Client{Socket: "/nonexistent/auth.sock"}).Check("alice", "secret"); err == nil {
t.Error("no socket")
}
}
+50 -47
View File
@@ -10,6 +10,9 @@ import (
"strconv"
"strings"
"time"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/config"
)
// Who may use what: groups of users, the access rules of the items, the
@@ -26,16 +29,16 @@ type itemAccess struct {
// loadItemAccess: an item's access rules (users, groups, callerids,
// min_baud, guest), its caller ID patterns checked
func loadItemAccess(name string, sec *section) (itemAccess, error) {
func loadItemAccess(name string, sec *config.Section) (itemAccess, error) {
var a itemAccess
var err error
a.users = fields(sec.get("users", ""))
a.groups = fields(sec.get("groups", ""))
a.callerIDs = fields(sec.get("callerids", ""))
if a.minBaud, err = sec.int("min_baud", 0); err != nil {
a.users = config.Fields(sec.Get("users", ""))
a.groups = config.Fields(sec.Get("groups", ""))
a.callerIDs = config.Fields(sec.Get("callerids", ""))
if a.minBaud, err = sec.Int("min_baud", 0); err != nil {
return a, err
}
if a.guest, err = sec.bool("guest", false); err != nil {
if a.guest, err = sec.Bool("guest", false); err != nil {
return a, err
}
for _, p := range a.callerIDs {
@@ -93,20 +96,20 @@ type limitSettings struct {
// loadAccess: the time limits and warnings of [general], [groups],
// [guest], [signup] and [callerid] and its [number ...] sections
func loadAccess(c *ini, s *settings) error {
func loadAccess(c *config.File, s *settings) error {
var err error
g := c.section("general")
if s.limits.timeLimit, err = g.duration("time_limit", 0); err != nil {
g := c.Section("general")
if s.limits.timeLimit, err = g.Duration("time_limit", 0); err != nil {
return err
}
if s.limits.dailyLimit, err = g.duration("daily_limit", 0); err != nil {
if s.limits.dailyLimit, err = g.Duration("daily_limit", 0); err != nil {
return err
}
s.limits.stateDir = g.get("state_dir", "/var/lib/modemmenu")
if s.limits.warnings, err = g.durations("time_warning", "2m"); err != nil {
s.limits.stateDir = g.Get("state_dir", "/var/lib/modemmenu")
if s.limits.warnings, err = g.Durations("time_warning", "2m"); err != nil {
return err
}
s.limits.warningMessage = unescape(g.get("time_warning_message",
s.limits.warningMessage = config.Unescape(g.Get("time_warning_message",
`\r\n\r\n*** {time_left} minute(s) left in this call ***\r\n`))
if s.limits.dailyLimit > 0 && !strings.HasPrefix(s.limits.stateDir, "/") {
return fmt.Errorf("[general] state_dir: %q (an absolute path)", s.limits.stateDir)
@@ -114,33 +117,33 @@ func loadAccess(c *ini, s *settings) error {
// [groups]: name = its members
s.groups = map[string][]string{}
gs := c.section("groups")
for _, k := range gs.keys {
s.groups[k] = fields(gs.get(k, ""))
gs := c.Section("groups")
for _, k := range gs.Keys {
s.groups[k] = config.Fields(gs.Get(k, ""))
}
gu := c.section("guest")
if s.guest.enabled, err = gu.bool("enabled", false); err != nil {
gu := c.Section("guest")
if s.guest.enabled, err = gu.Bool("enabled", false); err != nil {
return err
}
s.guest.name = gu.get("name", "guest")
if s.guest.timeLimit, err = gu.duration("time_limit", 15*time.Minute); err != nil {
s.guest.name = gu.Get("name", "guest")
if s.guest.timeLimit, err = gu.Duration("time_limit", 15*time.Minute); err != nil {
return err
}
su := c.section("signup")
if s.signup.enabled, err = su.bool("enabled", false); err != nil {
su := c.Section("signup")
if s.signup.enabled, err = su.Bool("enabled", false); err != nil {
return err
}
s.signup.name = su.get("name", "new")
s.signup.file = su.get("file", c.section("file").get("path", "/etc/asterisk/modemmenu.users"))
if s.signup.pending, err = su.bool("pending", true); err != nil {
s.signup.name = su.Get("name", "new")
s.signup.file = su.Get("file", c.Section("file").Get("path", "/etc/asterisk/modemmenu.users"))
if s.signup.pending, err = su.Bool("pending", true); err != nil {
return err
}
if s.signup.minPassword, err = su.int("min_password", 8); err != nil {
if s.signup.minPassword, err = su.Int("min_password", 8); err != nil {
return err
}
s.signup.message = unescape(su.get("message", `\r\nNew account. Choose a user name and a password.\r\n`))
s.signup.message = config.Unescape(su.Get("message", `\r\nNew account. Choose a user name and a password.\r\n`))
if s.signup.enabled && !contains(s.auth, "file") {
return fmt.Errorf("[signup] enabled: new accounts go in the users file, and [general] auth has no file")
}
@@ -148,28 +151,28 @@ func loadAccess(c *ini, s *settings) error {
return fmt.Errorf("[guest] name and [signup] name are both %q", s.guest.name)
}
cs := c.section("callerid")
s.callerID.allow = fields(cs.get("allow", ""))
s.callerID.deny = fields(cs.get("deny", ""))
if s.callerID.anonymous, err = cs.bool("anonymous", true); err != nil {
cs := c.Section("callerid")
s.callerID.allow = config.Fields(cs.Get("allow", ""))
s.callerID.deny = config.Fields(cs.Get("deny", ""))
if s.callerID.anonymous, err = cs.Bool("anonymous", true); err != nil {
return err
}
s.callerID.denyMessage = unescape(cs.get("deny_message", `\r\nThis line does not take your call.\r\n`))
s.callerID.denyMessage = config.Unescape(cs.Get("deny_message", `\r\nThis line does not take your call.\r\n`))
for _, p := range append(append([]string{}, s.callerID.allow...), s.callerID.deny...) {
if _, err := path.Match(p, ""); err != nil {
return fmt.Errorf("[callerid] %q: %v", p, err)
}
}
for _, sec := range c.sections {
p, ok := strings.CutPrefix(sec.name, "number ")
for _, sec := range c.Sections {
p, ok := strings.CutPrefix(sec.Name, "number ")
if !ok {
continue
}
if _, err := path.Match(p, ""); err != nil {
return fmt.Errorf("[%s]: %v", sec.name, err)
return fmt.Errorf("[%s]: %v", sec.Name, err)
}
r := numberRule{pattern: p, user: sec.get("user", ""), item: sec.get("item", "")}
if r.deny, err = sec.bool("deny", false); err != nil {
r := numberRule{pattern: p, user: sec.Get("user", ""), item: sec.Get("item", "")}
if r.deny, err = sec.Bool("deny", false); err != nil {
return err
}
s.callerID.numbers = append(s.callerID.numbers, r)
@@ -254,8 +257,8 @@ func (s *settings) inGroup(sess *session, group string) bool {
if contains(s.groups[group], sess.User) {
return true
}
auth := strings.TrimPrefix(sess.Auth, "upstream:")
if auth != "system" && auth != "ldap" {
via := strings.TrimPrefix(sess.Auth, "upstream:")
if via != "system" && via != "ldap" {
return false
}
if in, ok := sess.groupCache[group]; ok {
@@ -263,19 +266,19 @@ func (s *settings) inGroup(sess *session, group string) bool {
}
var in bool
var err error
if auth == "system" {
var acct *account
if acct, err = lookupNSS(sess.User); err == nil {
in, err = inGroupsNSS(acct, []string{group})
if via == "system" {
var acct *auth.Account
if acct, err = auth.LookupNSS(sess.User); err == nil {
in, err = auth.InGroupsNSS(acct, []string{group})
}
} else {
for _, b := range s.backends {
if la, ok := b.(*ldapAuth); ok {
in, err = la.memberOf(sess.User, sess.Password, group)
if la, ok := b.(*auth.LDAP); ok {
in, err = la.MemberOf(sess.User, sess.Password, group)
}
}
}
if err != nil && !errors.Is(err, errNoUser) {
if err != nil && !errors.Is(err, auth.ErrNoUser) {
logf("groups: %s in %s: %v", sess.User, group, err)
}
if sess.groupCache == nil {
@@ -327,7 +330,7 @@ func (s *settings) visible(sess *session) []*menuItem {
// ldapGroups: whether the LDAP backend has groups ([ldap] group_base)
func (s *settings) ldapGroups() bool {
for _, b := range s.backends {
if la, ok := b.(*ldapAuth); ok && la.groupBase != "" {
if la, ok := b.(*auth.LDAP); ok && la.HasGroups() {
return true
}
}
@@ -14,28 +14,10 @@ import (
"syscall"
"testing"
"time"
)
// TestStripComment: inline comments end a value after whitespace, not
// inside quotes or a word; \; and \# are kept as text
func TestStripComment(t *testing.T) {
for in, want := range map[string]string{
"P ; PPP": "P ",
"P # PPP": "P ",
"a;b": "a;b",
"echo a; echo b": "echo a; echo b",
`"a ; b" ; c`: `"a ; b" `,
`x \; y`: "x ; y",
`x \# y`: "x # y",
"; all comment": "",
"(&(uid={user})(#x))": "(&(uid={user})(#x))",
"exec pppd ipparam {user}": "exec pppd ipparam {user}",
} {
if got := stripComment(in); got != want {
t.Errorf("%q: %q, want %q", in, got, want)
}
}
}
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/config"
)
// accessConf: a configuration with groups, item rules, guest, signup and
// caller ID rules
@@ -151,8 +133,8 @@ func TestAccessRules(t *testing.T) {
}
// the users file: a locked account
fa, _ := newFileAuth(&section{name: "file", vals: map[string]string{"path": filepath.Join(dir, "users")}})
if err := fa.authenticate(context.Background(), "locked", "secret"); !errors.Is(err, errBadPassword) {
fa, _ := auth.NewFile(&config.Section{Name: "file", Vals: map[string]string{"path": filepath.Join(dir, "users")}})
if err := fa.Authenticate(context.Background(), "locked", "secret"); !errors.Is(err, auth.ErrBadPassword) {
t.Errorf("locked: %v", err)
}
@@ -448,32 +430,3 @@ command = exec sleep 30
waitExit(t, cmd)
}
}
// TestDurations: time_warning's list of durations, longest first, and
// none for 0 or none
func TestDurations(t *testing.T) {
for in, want := range map[string]string{
"5m 1m": "[5m0s 1m0s]",
"60, 300": "[5m0s 1m0s]",
"1m 5m 1m": "[5m0s 1m0s]",
"90s": "[1m30s]",
"0": "[]",
"none": "[]",
"": "[]",
} {
s := &section{name: "general", vals: map[string]string{"time_warning": in}}
got, err := s.durations("time_warning", "2m")
if err != nil || fmt.Sprint(got) != want {
t.Errorf("%q: %v %v, want %s", in, got, err, want)
}
}
for _, bad := range []string{"5m soon", "-1m", "1m 0"} {
s := &section{name: "general", vals: map[string]string{"time_warning": bad}}
if _, err := s.durations("time_warning", "2m"); err == nil {
t.Errorf("%q: no error", bad)
}
}
if got, _ := (&section{name: "general", vals: map[string]string{}}).durations("time_warning", "2m"); fmt.Sprint(got) != "[2m0s]" {
t.Errorf("the default: %v", got)
}
}
+24 -35
View File
@@ -19,6 +19,9 @@ import (
"syscall"
"time"
"github.com/D-Modem/menu/authd"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/config"
"golang.org/x/sys/unix"
)
@@ -43,38 +46,24 @@ type authdSettings struct {
maxClients int
}
// authRequest and authReply are the socket's JSON.
type authRequest struct {
User string `json:"user"`
Password string `json:"password"`
}
type authReply struct {
OK bool `json:"ok"`
Auth string `json:"auth,omitempty"` // the backend that took it
Error string `json:"error,omitempty"` // denied, refused, bad request
}
const maxAuthRequest = 4096
// loadAuthd: [authd], the auth socket; nil when it has no listen
func loadAuthd(sec *section) (*authdSettings, error) {
if sec.get("listen", "") == "" {
func loadAuthd(sec *config.Section) (*authdSettings, error) {
if sec.Get("listen", "") == "" {
return nil, nil
}
a := &authdSettings{listen: sec.get("listen", ""), socketGroup: sec.get("socket_group", "")}
a := &authdSettings{listen: sec.Get("listen", ""), socketGroup: sec.Get("socket_group", "")}
if !strings.HasPrefix(a.listen, "/") {
return nil, fmt.Errorf("[authd] listen: %q (an absolute path: a unix socket only, passwords cross it)", a.listen)
}
mode, err := strconv.ParseUint(sec.get("socket_mode", "0660"), 8, 32)
mode, err := strconv.ParseUint(sec.Get("socket_mode", "0660"), 8, 32)
if err != nil || mode > 0o777 {
return nil, fmt.Errorf("[authd] socket_mode: %q (octal, e.g. 0660)", sec.get("socket_mode", ""))
return nil, fmt.Errorf("[authd] socket_mode: %q (octal, e.g. 0660)", sec.Get("socket_mode", ""))
}
if mode&0o007 != 0 {
return nil, fmt.Errorf("[authd] socket_mode: %04o lets anyone ask for passwords", mode)
}
a.socketMode = os.FileMode(mode)
if names := fields(sec.get("allow_users", "")); len(names) > 0 {
if names := config.Fields(sec.Get("allow_users", "")); len(names) > 0 {
a.allowUIDs = map[uint32]bool{}
for _, n := range names {
u, err := user.Lookup(n)
@@ -85,7 +74,7 @@ func loadAuthd(sec *section) (*authdSettings, error) {
a.allowUIDs[uint32(uid)] = true
}
}
if a.maxClients, err = sec.int("max_clients", 16); err != nil {
if a.maxClients, err = sec.Int("max_clients", 16); err != nil {
return nil, err
}
if a.maxClients < 1 {
@@ -94,8 +83,8 @@ func loadAuthd(sec *section) (*authdSettings, error) {
return a, nil
}
// authd: modemmenu -authd, the auth socket alone, until SIGTERM.
func authd(s *settings) int {
// runAuthd: modemmenu -authd, the auth socket alone, until SIGTERM.
func runAuthd(s *settings) int {
if s.authd == nil {
fmt.Fprintln(os.Stderr, "modemmenu: -authd: no [authd] listen")
return 2
@@ -178,43 +167,43 @@ func peerUID(conn net.Conn) (uint32, bool) {
func answerAuth(s *settings, conn net.Conn) {
defer conn.Close()
who := peer(conn)
reply := func(r authReply) {
reply := func(r authd.Reply) {
b, _ := json.Marshal(r)
conn.Write(append(b, '\n'))
}
if s.authd.allowUIDs != nil {
if uid, ok := peerUID(conn); !ok || !s.authd.allowUIDs[uid] {
logf("auth request from %s: not an allowed user", who)
reply(authReply{Error: "refused"})
reply(authd.Reply{Error: "refused"})
return
}
}
// one line, soon: a client that says less is not waited for
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
line, err := bufio.NewReaderSize(io.LimitReader(conn, maxAuthRequest), maxAuthRequest).ReadSlice('\n')
line, err := bufio.NewReaderSize(io.LimitReader(conn, authd.MaxRequest), authd.MaxRequest).ReadSlice('\n')
conn.SetDeadline(time.Now().Add(time.Minute))
var req authRequest
var req authd.Request
if err != nil || json.Unmarshal(line, &req) != nil || req.User == "" {
logf("auth request from %s: bad request", who)
reply(authReply{Error: "bad request"})
reply(authd.Reply{Error: "bad request"})
return
}
var auth string
var via string
if s.userPattern.MatchString(req.User) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
auth, err = authenticate(ctx, s.backends, req.User, req.Password, logf)
via, err = auth.Authenticate(ctx, s.backends, req.User, req.Password, logf)
cancel()
} else {
// not a name we take: the same answer, after the same time
burn(req.Password)
err = errNoUser
auth.Burn(req.Password)
err = auth.ErrNoUser
}
if err != nil {
logf("auth request from %s: user=%q denied (%v)", who, req.User, err)
time.Sleep(s.failDelay)
reply(authReply{Error: "denied"})
reply(authd.Reply{Error: "denied"})
return
}
logf("auth request from %s: user=%s auth=%s", who, req.User, auth)
reply(authReply{OK: true, Auth: auth})
logf("auth request from %s: user=%s auth=%s", who, req.User, via)
reply(authd.Reply{OK: true, Auth: via})
}
@@ -11,6 +11,8 @@ import (
"path/filepath"
"strings"
"testing"
"github.com/D-Modem/menu/authd"
)
// authSettings: settings with an auth socket in a test directory, and
@@ -33,7 +35,7 @@ func authSettings(t *testing.T, extra string) (*settings, string) {
}
// ask: one request on the auth socket, its answer
func ask(t *testing.T, sock, body string) authReply {
func ask(t *testing.T, sock, body string) authd.Reply {
t.Helper()
c, err := net.Dial("unix", sock)
if err != nil {
@@ -41,7 +43,7 @@ func ask(t *testing.T, sock, body string) authReply {
}
defer c.Close()
c.Write([]byte(body + "\n"))
var r authReply
var r authd.Reply
if err := json.NewDecoder(c).Decode(&r); err != nil {
t.Fatalf("%s: %v", body, err)
}
@@ -60,7 +62,7 @@ func TestAuthd(t *testing.T) {
if fi, err := os.Stat(sock); err != nil || fi.Mode().Perm() != 0o600 {
t.Fatalf("socket %v %v", fi, err)
}
for body, want := range map[string]authReply{
for body, want := range map[string]authd.Reply{
`{"user":"alice","password":"secret"}`: {OK: true, Auth: "file"},
`{"user":"alice","password":"wrong"}`: {Error: "denied"},
`{"user":"bob","password":"secret"}`: {Error: "denied"},
+26 -40
View File
@@ -19,6 +19,10 @@ import (
"syscall"
"time"
"github.com/D-Modem/menu/authd"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/config"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/sys/unix"
)
@@ -41,10 +45,10 @@ type autopppSettings struct {
}
// loadAutoPPP: [autoppp]; enabled needs a command
func loadAutoPPP(sec *section) (autopppSettings, error) {
func loadAutoPPP(sec *config.Section) (autopppSettings, error) {
var err error
a := autopppSettings{command: sec.get("command", ""), item: sec.get("item", "")}
if a.enabled, err = sec.bool("enabled", false); err != nil {
a := autopppSettings{command: sec.Get("command", ""), item: sec.Get("item", "")}
if a.enabled, err = sec.Bool("enabled", false); err != nil {
return a, err
}
if a.enabled && a.command == "" {
@@ -53,28 +57,10 @@ func loadAutoPPP(sec *section) (autopppSettings, error) {
return a, nil
}
// pppFrame: whether what starts with the flag 0x7E is a PPP frame: the
// address and control (0xFF 0x03, the 0x03 escaped as 0x7D 0x23), the
// address escaped (0x7D 0xDF), or both compressed away (LCP's 0xC0 0x21)
func pppFrame(b []byte) bool {
if len(b) < 3 || b[0] != 0x7E {
return false
}
switch {
case b[1] == 0xFF && (b[2] == 0x03 || b[2] == 0x7D):
return true
case b[1] == 0x7D && b[2] == 0xDF:
return true
case b[1] == 0xC0 && b[2] == 0x21:
return true
}
return false
}
// sniffPPP: at the login prompt, whether a PPP frame comes; what is not
// one is put back for the name
func sniffPPP(t *term, deadline time.Time) (bool, error) {
c, err := t.readByte(time.Until(deadline))
func sniffPPP(t *term.Term, deadline time.Time) (bool, error) {
c, err := t.ReadOne(time.Until(deadline))
if err != nil {
return false, err
}
@@ -82,17 +68,17 @@ func sniffPPP(t *term, deadline time.Time) (bool, error) {
if c == 0x7E {
// the rest of the frame's start, which follows at once
for len(got) < 3 {
c, err := t.readByte(time.Second)
c, err := t.ReadOne(time.Second)
if err != nil {
break
}
got = append(got, c)
}
if pppFrame(got) {
if term.IsPPPFrame(got) {
return true, nil
}
}
t.unread(got...)
t.Unread(got...)
return false, nil
}
@@ -161,8 +147,8 @@ func (a *pppAuth) answer(conn net.Conn) {
conn.Write(append(b, '\n'))
}
conn.SetDeadline(time.Now().Add(time.Minute))
line, err := bufio.NewReaderSize(io.LimitReader(conn, maxAuthRequest), maxAuthRequest).ReadSlice('\n')
var req authRequest
line, err := bufio.NewReaderSize(io.LimitReader(conn, authd.MaxRequest), authd.MaxRequest).ReadSlice('\n')
var req authd.Request
if err != nil || json.Unmarshal(line, &req) != nil || req.User == "" {
reply(pppReply{Error: "bad request"})
return
@@ -178,14 +164,14 @@ func (a *pppAuth) answer(conn net.Conn) {
reply(pppReply{Error: "too many attempts"})
return
}
var auth string
var via string
if s.userPattern.MatchString(req.User) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
auth, err = authenticate(ctx, s.backends, req.User, req.Password, logf)
via, err = auth.Authenticate(ctx, s.backends, req.User, req.Password, logf)
cancel()
} else {
burn(req.Password)
err = errNoUser
auth.Burn(req.Password)
err = auth.ErrNoUser
}
if err != nil {
a.fails++
@@ -194,7 +180,7 @@ func (a *pppAuth) answer(conn net.Conn) {
reply(pppReply{Error: "denied"})
return
}
sess.User, sess.Password, sess.Auth = req.User, req.Password, auth
sess.User, sess.Password, sess.Auth = req.User, req.Password, via
if name := s.autoppp.item; name != "" {
if it := s.selects(strings.ToUpper(name)); it == nil || !s.allows(it, sess) {
a.fails++
@@ -219,18 +205,18 @@ func (a *pppAuth) answer(conn net.Conn) {
logf("callers: %v", err)
}
}
logf("login user=%s auth=%s via PPP %v", sess.User, auth, sess)
logf("login user=%s auth=%s via PPP %v", sess.User, via, sess)
secs := -1
if left, ok := lim.left(time.Now()); ok {
secs = int(left / time.Second)
}
close(a.login)
reply(pppReply{OK: true, Auth: auth, SecondsLeft: secs})
reply(pppReply{OK: true, Auth: via, SecondsLeft: secs})
}
// autoPPP: the [autoppp] command on the line, with the call's auth
// socket, until it ends; the exit status
func autoPPP(t *term, s *settings, sess *session) int {
func autoPPP(t *term.Term, s *settings, sess *session) int {
logf("PPP frame at the login prompt: %s %v", s.autoppp.command, sess)
a, err := startPPPAuth(s, sess)
if err != nil {
@@ -241,7 +227,7 @@ func autoPPP(t *term, s *settings, sess *session) int {
v := sess.vars(false)
v["auth_socket"] = a.path()
cmd := exec.Command("/bin/sh", "-c", expand(s.autoppp.command, v, shellQuote))
cmd := exec.Command("/bin/sh", "-c", config.Expand(s.autoppp.command, v, shellQuote))
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stdout
env := make([]string, 0, 32)
for _, e := range os.Environ() {
@@ -252,8 +238,8 @@ func autoPPP(t *term, s *settings, sess *session) int {
env = append(env, sess.environ(false)...)
env = append(env, "MODEMMENU_AUTH_SOCKET="+a.path())
cmd.Env = env
before := t.setMode("raw")
defer t.restoreMode(before)
before := t.SetMode("raw")
defer t.RestoreMode(before)
if err := cmd.Start(); err != nil {
logf("autoppp: %v", err)
return 1
@@ -283,7 +269,7 @@ func autoPPP(t *term, s *settings, sess *session) int {
err = cmd.Wait()
close(done)
running(nil)
unix.IoctlSetPointerInt(t.in, unix.TIOCSPGRP, unix.Getpgrp())
unix.IoctlSetPointerInt(t.In, unix.TIOCSPGRP, unix.Getpgrp())
a.mu.Lock()
lim := a.lim
a.mu.Unlock()
@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"
"github.com/D-Modem/menu/internal/term"
)
// TestPPPFrame: what starts a PPP frame, and what does not
@@ -23,7 +25,7 @@ func TestPPPFrame(t *testing.T) {
"\x7e\xff": false,
"alice": false,
} {
if got := pppFrame([]byte(in)); got != want {
if got := term.IsPPPFrame([]byte(in)); got != want {
t.Errorf("% x: %v, want %v", in, got, want)
}
}
@@ -41,8 +43,8 @@ func buildPlugin(t *testing.T, dir string) (plugin, host string) {
}
plugin, host = filepath.Join(dir, "modemmenu.so"), filepath.Join(dir, "host")
for _, args := range [][]string{
{"-Wall", "-Werror", "-Wno-unused-parameter", "-fPIC", "-shared", "-o", plugin, "pppd/modemmenu.c"},
{"-Wall", "-Werror", "-rdynamic", "-o", host, "pppd/test/host.c", "-ldl"},
{"-Wall", "-Werror", "-Wno-unused-parameter", "-fPIC", "-shared", "-o", plugin, "../../pppd/modemmenu.c"},
{"-Wall", "-Werror", "-rdynamic", "-o", host, "../../pppd/test/host.c", "-ldl"},
} {
if out, err := exec.Command("cc", args...).CombinedOutput(); err != nil {
t.Fatalf("cc %v: %v\n%s", args, err, out)
+3 -2
View File
@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/sys/unix"
)
@@ -85,7 +86,7 @@ func lastCallers(dir string, n int) ([][3]string, error) {
}
// callersItem: mode = callers, the last count callers on the line
func callersItem(t *term, s *settings, it *menuItem) error {
func callersItem(t *term.Term, s *settings, it *menuItem) error {
list, err := lastCallers(s.limits.stateDir, it.count)
if err != nil {
logf("callers: %v", err)
@@ -106,7 +107,7 @@ func callersItem(t *term, s *settings, it *menuItem) error {
}
fmt.Fprintf(&b, " %s %-16s %s\r\n", when, c[1], rate)
}
return t.write(b.String())
return t.Write(b.String())
}
// hasCallers: whether an item shows the last callers (logins are only
File renamed without changes.
+16 -15
View File
@@ -13,6 +13,7 @@ import (
"strings"
"time"
"github.com/D-Modem/menu/internal/config"
"golang.org/x/sys/unix"
)
@@ -48,35 +49,35 @@ type dropfileSettings struct {
}
// loadDropfile: [dropfile], checked
func loadDropfile(sec *section) (dropfileSettings, error) {
func loadDropfile(sec *config.Section) (dropfileSettings, error) {
var err error
d := dropfileSettings{
bbsName: sec.get("bbs_name", "modemmenu"),
sysop: sec.get("sysop", "Sysop"),
emulation: strings.ToLower(sec.get("emulation", "auto")),
comPort: strings.ToUpper(sec.get("com_port", "COM1:")),
rate: strings.ToLower(sec.get("rate", "38400")),
bbsName: sec.Get("bbs_name", "modemmenu"),
sysop: sec.Get("sysop", "Sysop"),
emulation: strings.ToLower(sec.Get("emulation", "auto")),
comPort: strings.ToUpper(sec.Get("com_port", "COM1:")),
rate: strings.ToLower(sec.Get("rate", "38400")),
}
if d.security, err = sec.int("security", 10); err != nil {
if d.security, err = sec.Int("security", 10); err != nil {
return d, err
}
if d.comType, err = sec.int("comm_type", 0); err != nil {
if d.comType, err = sec.Int("comm_type", 0); err != nil {
return d, err
}
defHandle := 0
if d.comType == 0 {
defHandle = -1
}
if d.comHandle, err = sec.int("comm_handle", defHandle); err != nil {
if d.comHandle, err = sec.Int("comm_handle", defHandle); err != nil {
return d, err
}
if d.fossil, err = sec.bool("fossil", true); err != nil {
if d.fossil, err = sec.Bool("fossil", true); err != nil {
return d, err
}
if d.fourDigitYears, err = sec.bool("four_digit_years", false); err != nil {
if d.fourDigitYears, err = sec.Bool("four_digit_years", false); err != nil {
return d, err
}
if d.maxNodes, err = sec.int("max_nodes", 64); err != nil {
if d.maxNodes, err = sec.Int("max_nodes", 64); err != nil {
return d, err
}
if d.emulation != "auto" && d.emulation != "ansi" && d.emulation != "ascii" {
@@ -104,9 +105,9 @@ var dropfileNames = map[string]string{
}
// loadItemDropfiles: an item's dropfile = names, as the files' names
func loadItemDropfiles(name string, sec *section) ([]string, error) {
func loadItemDropfiles(name string, sec *config.Section) ([]string, error) {
var out []string
for _, f := range fields(strings.ToLower(sec.get("dropfile", ""))) {
for _, f := range config.Fields(strings.ToLower(sec.Get("dropfile", ""))) {
n, ok := dropfileNames[f]
if !ok {
return nil, fmt.Errorf("[item %s] dropfile: %q (door32.sys, door.sys, dorinfo1.def or dorinfo#.def)", name, f)
@@ -166,7 +167,7 @@ func writeDropfiles(cfg *settings, it *menuItem, s *session, deadline time.Time,
if it.dropfileDir != "" {
v := s.vars(false)
v["node"] = strconv.Itoa(node)
d.dir = expand(it.dropfileDir, v, nil)
d.dir = config.Expand(it.dropfileDir, v, nil)
if err := os.MkdirAll(d.dir, 0o755); err != nil {
d.close()
return nil, err
@@ -13,12 +13,14 @@ import (
"syscall"
"testing"
"time"
"github.com/D-Modem/menu/internal/config"
)
// TestDropfileFormats: DOOR32.SYS, DOOR.SYS (52 and 31 lines) and
// DORINFO1.DEF, line by line
func TestDropfileFormats(t *testing.T) {
sec := &section{name: "dropfile", vals: map[string]string{"bbs_name": "Test BBS", "sysop": "Ada Lovelace"}}
sec := &config.Section{Name: "dropfile", Vals: map[string]string{"bbs_name": "Test BBS", "sysop": "Ada Lovelace"}}
df, err := loadDropfile(sec)
if err != nil {
t.Fatal(err)
@@ -61,8 +63,8 @@ func TestDropfileFormats(t *testing.T) {
in.s = s
// the modems' rate, ASCII, four-digit years, no FOSSIL, local port
sec.vals["rate"], sec.vals["emulation"], sec.vals["four_digit_years"] = "connect", "ascii", "yes"
sec.vals["fossil"], sec.vals["com_port"], sec.vals["comm_type"] = "no", "com0:", "2"
sec.Vals["rate"], sec.Vals["emulation"], sec.Vals["four_digit_years"] = "connect", "ascii", "yes"
sec.Vals["fossil"], sec.Vals["com_port"], sec.Vals["comm_type"] = "no", "com0:", "2"
if in.df, err = loadDropfile(sec); err != nil {
t.Fatal(err)
}
@@ -78,7 +80,7 @@ func TestDropfileFormats(t *testing.T) {
}
for k, v := range map[string]string{"comm_type": "3", "com_port": "LPT1", "rate": "fast", "emulation": "rip", "max_nodes": "0"} {
bad := &section{name: "dropfile", vals: map[string]string{k: v}}
bad := &config.Section{Name: "dropfile", Vals: map[string]string{k: v}}
if _, err := loadDropfile(bad); err == nil {
t.Errorf("%s = %s: no error", k, v)
}
@@ -318,7 +320,7 @@ func TestDropfileLowercase(t *testing.T) {
dir := t.TempDir()
cfg := &settings{}
cfg.limits.stateDir = dir
cfg.dropfile, _ = loadDropfile(&section{name: "dropfile", vals: map[string]string{}})
cfg.dropfile, _ = loadDropfile(&config.Section{Name: "dropfile", Vals: map[string]string{}})
it := &menuItem{name: "d", dropfiles: []string{"DOOR32.SYS", "DORINFO1.DEF"}, dropfileLower: true, doorSysLines: 52}
df, err := writeDropfiles(cfg, it, &session{User: "alice"}, time.Time{}, -1, -1)
if err != nil {
File renamed without changes.
@@ -13,12 +13,12 @@ import (
// users file alone and serves FreePBX's "menu" profile on its socket
func TestFreePBXSample(t *testing.T) {
dir := t.TempDir()
conf, err := os.ReadFile("freepbx/modemmenu.conf")
conf, err := os.ReadFile("../../freepbx/modemmenu.conf")
if err != nil {
t.Fatal(err)
}
users := filepath.Join(dir, "modemmenu.users")
sample, err := os.ReadFile("freepbx/modemmenu.users")
sample, err := os.ReadFile("../../freepbx/modemmenu.users")
if err != nil {
t.Fatal(err)
}
@@ -51,10 +51,10 @@ func TestFreePBXSample(t *testing.T) {
t.Errorf("items %v", names)
}
ctx := context.Background()
if err := s.backends[0].authenticate(ctx, "test", "changeme"); err != nil {
if err := s.backends[0].Authenticate(ctx, "test", "changeme"); err != nil {
t.Errorf("test's login: %v", err)
}
if err := s.backends[0].authenticate(ctx, "test", "wrong"); err == nil {
if err := s.backends[0].Authenticate(ctx, "test", "wrong"); err == nil {
t.Error("a wrong password let in")
}
+30 -184
View File
@@ -18,12 +18,15 @@ import (
"syscall"
"time"
"github.com/D-Modem/menu/internal/config"
"github.com/D-Modem/menu/internal/telnet"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/sys/unix"
)
// launch the selection: its error, or nil when it ended by itself;
// errTimeLimit when deadline (if not zero) ended it
func launch(t *term, cfg *settings, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error {
func launch(t *term.Term, cfg *settings, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error {
// each time_warning before the deadline (those still ahead), on the
// line in the middle of what the selection says
for _, warn := range cfg.limits.warnings {
@@ -35,7 +38,7 @@ func launch(t *term, cfg *settings, it *menuItem, s *session, deadline time.Time
v := s.vars(false)
v["time_left"] = strconv.Itoa(int((left + 30*time.Second) / time.Minute))
v["seconds_left"] = strconv.Itoa(int((left + 500*time.Millisecond) / time.Second))
t.write(expand(cfg.limits.warningMessage, v, nil))
t.Write(config.Expand(cfg.limits.warningMessage, v, nil))
logf("%s: time warning user=%s left=%v", it.name, s.User, left.Round(time.Second))
})
defer timer.Stop()
@@ -55,7 +58,7 @@ func launch(t *term, cfg *settings, it *menuItem, s *session, deadline time.Time
// runExec: the command under /bin/sh -c on the caller's line, the
// session in MODEM_* of its environment, {placeholders} of the command
// as quoted shell words
func runExec(t *term, cfg *settings, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error {
func runExec(t *term.Term, cfg *settings, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error {
v := s.vars(it.password)
env := make([]string, 0, 32)
for _, e := range os.Environ() {
@@ -73,7 +76,7 @@ func runExec(t *term, cfg *settings, it *menuItem, s *session, deadline time.Tim
var cred *syscall.Credential
var home string
if it.runAs != "" {
name := expand(it.runAs, v, nil)
name := config.Expand(it.runAs, v, nil)
u, err := user.Lookup(name)
if err != nil {
return fmt.Errorf("run_as %s: %v", name, err)
@@ -105,7 +108,7 @@ func runExec(t *term, cfg *settings, it *menuItem, s *session, deadline time.Tim
"MODEM_DROPFILE="+df.files[0])
}
cmd := exec.Command("/bin/sh", "-c", expand(it.command, v, shellQuote))
cmd := exec.Command("/bin/sh", "-c", config.Expand(it.command, v, shellQuote))
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stdout
if cred != nil {
cmd.SysProcAttr = &syscall.SysProcAttr{Credential: cred}
@@ -121,8 +124,8 @@ func runExec(t *term, cfg *settings, it *menuItem, s *session, deadline time.Tim
}
cmd.Env = env
before := t.setMode(it.tty)
defer t.restoreMode(before)
before := t.SetMode(it.tty)
defer t.RestoreMode(before)
if err := cmd.Start(); err != nil {
return err
}
@@ -144,7 +147,7 @@ func runExec(t *term, cfg *settings, it *menuItem, s *session, deadline time.Tim
return errTimeLimit
}
// the line's foreground is ours again, whatever a shell did with it
unix.IoctlSetPointerInt(t.in, unix.TIOCSPGRP, unix.Getpgrp())
unix.IoctlSetPointerInt(t.In, unix.TIOCSPGRP, unix.Getpgrp())
if ee, ok := err.(*exec.ExitError); ok {
logf("%s: %s", it.name, ee.ProcessState)
return nil
@@ -217,7 +220,7 @@ func running(p *os.Process) {
// runTCP: the caller's line to a server, by TCP or a unix socket: raw,
// telnet or rlogin
func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
func runTCP(t *term.Term, it *menuItem, s *session, deadline time.Time) error {
v := s.vars(it.password)
network, addr := "tcp", net.JoinHostPort(it.host, strconv.Itoa(it.port))
if it.path != "" {
@@ -236,15 +239,15 @@ func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
}
}
var tn *telnet
var tn *telnet.Client
switch it.mode {
case "rlogin":
// RFC 1282: \0 client-user \0 server-user \0 terminal/speed \0;
// BBSs (Synchronet, Mystic) take the password as the client
// user and log the caller in at once
hello := "\x00" + expand(it.rloginLocal, v, nil) + "\x00" +
expand(it.rloginUser, v, nil) + "\x00" +
expand(it.rloginTerm, v, nil) + "\x00"
hello := "\x00" + config.Expand(it.rloginLocal, v, nil) + "\x00" +
config.Expand(it.rloginUser, v, nil) + "\x00" +
config.Expand(it.rloginTerm, v, nil) + "\x00"
conn.SetDeadline(time.Now().Add(it.timeout))
if _, err := io.WriteString(conn, hello); err != nil {
return err
@@ -256,11 +259,10 @@ func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
conn.SetDeadline(time.Time{})
if ack[0] != 0 {
// not the ack: the server's first byte of output
t.writeRaw(string(ack[:]))
t.WriteRaw(string(ack[:]))
}
case "telnet":
tn = &telnet{conn: conn, term: expand(it.terminal, v, nil),
local: map[byte]bool{}, remote: map[byte]bool{}}
tn = telnet.New(conn, config.Expand(it.terminal, v, nil))
}
// at the deadline the connection's reads and writes fail: the end
conn.SetDeadline(deadline)
@@ -271,9 +273,9 @@ func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
return err
}
if it.send != "" {
b := []byte(expand(unescape(it.send), v, nil))
b := []byte(config.Expand(config.Unescape(it.send), v, nil))
if tn != nil {
b = tn.encode(b)
b = tn.Encode(b)
}
if _, err := conn.Write(b); err != nil {
return err
@@ -281,11 +283,9 @@ func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
}
// what the caller sent that the menu read and did not take
if len(t.pending) > 0 {
b := t.pending
t.pending = nil
if b := t.TakePending(); len(b) > 0 {
if tn != nil {
b = tn.encode(b)
b = tn.Encode(b)
}
if _, err := conn.Write(b); err != nil {
return timeUp(err)
@@ -301,9 +301,9 @@ func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
if n > 0 {
out := buf[:n]
if tn != nil {
out = tn.decode(out)
out = tn.Decode(out)
}
if werr := t.writeRaw(string(out)); werr != nil {
if werr := t.WriteRaw(string(out)); werr != nil {
done <- werr
return
}
@@ -324,181 +324,27 @@ func runTCP(t *term, it *menuItem, s *session, deadline time.Time) error {
return timeUp(err)
default:
}
ok, err := pollOne(t.in, unix.POLLIN, 200*time.Millisecond)
ok, err := term.PollOne(t.In, unix.POLLIN, 200*time.Millisecond)
if err != nil {
return errHangup
return term.ErrHangup
}
if !ok {
continue
}
n, err := unix.Read(t.in, buf)
n, err := unix.Read(t.In, buf)
if err == unix.EINTR || err == unix.EAGAIN {
continue
}
if n <= 0 || err != nil {
return errHangup
return term.ErrHangup
}
b := buf[:n]
if tn != nil {
b = tn.encode(b)
b = tn.Encode(b)
}
if _, err := tn.writeTo(conn, b); err != nil {
if _, err := tn.Pass(conn, b); err != nil {
<-done
return timeUp(nil)
}
}
}
// telnet: just enough of a telnet client for a BBS: binary, suppress go
// ahead and the server's echo, and the terminal type
type telnet struct {
mu sync.Mutex
conn io.Writer
term string
state int
cmd byte
sb []byte
local map[byte]bool // options we do
remote map[byte]bool // options the server does
}
const (
iac = 255
dont = 254
do = 253
wont = 252
will = 251
sb = 250
se = 240
optBinary = 0
optEcho = 1
optSGA = 3
optTType = 24
)
// writeTo: b written to w, not in the middle of a reply to the server
// (a nil telnet writes as is)
func (tn *telnet) writeTo(w io.Writer, b []byte) (int, error) {
if tn == nil {
return w.Write(b)
}
tn.mu.Lock()
defer tn.mu.Unlock()
return w.Write(b)
}
// send: bytes to the server
func (tn *telnet) send(b ...byte) {
tn.writeTo(tn.conn, b)
}
// encode the caller's bytes: IAC doubled, CR as CR NUL unless binary
func (tn *telnet) encode(b []byte) []byte {
tn.mu.Lock()
bin := tn.local[optBinary]
tn.mu.Unlock()
out := make([]byte, 0, len(b)+8)
for _, c := range b {
out = append(out, c)
if c == iac {
out = append(out, iac)
} else if c == '\r' && !bin {
out = append(out, 0)
}
}
return out
}
// decode the server's bytes: its data, the commands answered
func (tn *telnet) decode(b []byte) []byte {
out := b[:0:0]
for _, c := range b {
switch tn.state {
case 0:
if c == iac {
tn.state = 1
} else {
out = append(out, c)
}
case 1:
switch c {
case iac:
out = append(out, iac)
tn.state = 0
case will, wont, do, dont:
tn.cmd, tn.state = c, 2
case sb:
tn.sb, tn.state = tn.sb[:0], 3
default:
tn.state = 0
}
case 2:
tn.option(tn.cmd, c)
tn.state = 0
case 3:
if c == iac {
tn.state = 4
} else if len(tn.sb) < 256 {
tn.sb = append(tn.sb, c)
}
case 4:
if c == se {
tn.subneg()
tn.state = 0
} else {
if c == iac && len(tn.sb) < 256 {
tn.sb = append(tn.sb, iac)
}
tn.state = 3
}
}
}
return out
}
// option: the answer to the server's WILL, WONT, DO or DONT
func (tn *telnet) option(cmd, opt byte) {
switch cmd {
case will:
ok := opt == optEcho || opt == optSGA || opt == optBinary
if ok && !tn.remote[opt] {
tn.remote[opt] = true
tn.send(iac, do, opt)
} else if !ok {
tn.send(iac, dont, opt)
}
case wont:
if tn.remote[opt] {
tn.remote[opt] = false
tn.send(iac, dont, opt)
}
case do:
ok := opt == optSGA || opt == optBinary || opt == optTType
if ok && !tn.local[opt] {
tn.mu.Lock()
tn.local[opt] = true
tn.mu.Unlock()
tn.send(iac, will, opt)
} else if !ok {
tn.send(iac, wont, opt)
}
case dont:
if tn.local[opt] {
tn.mu.Lock()
tn.local[opt] = false
tn.mu.Unlock()
tn.send(iac, wont, opt)
}
}
}
// subneg: the answer to a subnegotiation: the terminal type when asked
func (tn *telnet) subneg() {
// TTYPE SEND: TTYPE IS <terminal>
if len(tn.sb) >= 2 && tn.sb[0] == optTType && tn.sb[1] == 1 {
msg := []byte{iac, sb, optTType, 0}
msg = append(msg, []byte(tn.term)...)
tn.send(append(msg, iac, se)...)
}
}
+37
View File
@@ -0,0 +1,37 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// MODEMMENU_TEST_LDAP, groups as in internal/auth's TestLDAPGroups: an
// item for sysops, through settings, a login by ldap
func TestLDAPItemGroups(t *testing.T) {
url := os.Getenv("MODEMMENU_TEST_LDAP")
if url == "" {
t.Skip("MODEMMENU_TEST_LDAP is not set")
}
dir := t.TempDir()
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("[general]\nauth = ldap\n[ldap]\nurl = "+url+
"\nsearch_base = ou=people,dc=example,dc=com\ngroup_base = ou=groups,dc=example,dc=com\n"+
"[item ops]\ngroups = sysops\ncommand = true\n[item away]\ngroups = other\ncommand = true\n"), 0o600)
s, err := loadSettings(p)
if err != nil {
t.Fatal(err)
}
sess := &session{User: "lduser", Password: "ldpass", Auth: "ldap"}
var names []string
for _, it := range s.visible(sess) {
names = append(names, it.name)
}
if strings.Join(names, " ") != "ops" {
t.Errorf("lduser sees %v", names)
}
}
File renamed without changes.
+49 -46
View File
@@ -26,6 +26,9 @@ import (
"syscall"
"time"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/config"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/crypto/bcrypt"
xterm "golang.org/x/term"
)
@@ -66,7 +69,7 @@ func main() {
fmt.Fprintln(os.Stderr, "modemmenu: log:", err)
}
if *authdFlag {
os.Exit(authd(s))
os.Exit(runAuthd(s))
}
if *serveFlag {
if *listenAt != "" {
@@ -84,9 +87,9 @@ func main() {
logf("upstream user %q: not a name we take", sess.User)
sess.User, sess.Password, sess.Auth = "", "", ""
}
t := newTerm(os.Stdin, os.Stdout)
t := term.New(os.Stdin, os.Stdout)
code := run(t, s, sess)
t.close()
t.Close()
os.Exit(code)
}
@@ -180,11 +183,11 @@ func (s *session) String() string {
}
// run the login and the menu: the exit status
func run(t *term, s *settings, sess *session) int {
func run(t *term.Term, s *settings, sess *session) int {
logf("connect %v", sess)
if !s.callerAllowed(sess.CallerID) {
logf("refused by caller ID %v", sess)
t.write(s.callerID.denyMessage)
t.Write(s.callerID.denyMessage)
return 1
}
// what the terminal is, before anything is written for it
@@ -195,13 +198,13 @@ func run(t *term, s *settings, sess *session) int {
if sess.Terminal != "" {
logf("terminal %s %v", sess.describeTerminal(), sess)
}
if t.write(expand(s.banner, sess.vars(false), nil)) != nil {
if t.Write(config.Expand(s.banner, sess.vars(false), nil)) != nil {
return 1
}
// the connect rate, as BBSs greeted their callers (not when it is
// not known: no "Connected at ." on a getty without -rate)
if s.connectMessage != "" && sess.Speed() != "" {
t.write(expand(s.connectMessage, sess.vars(false), nil))
t.Write(config.Expand(s.connectMessage, sess.vars(false), nil))
}
rule := s.numberRule(sess.CallerID)
switch {
@@ -218,8 +221,8 @@ func run(t *term, s *settings, sess *session) int {
return autoPPP(t, s, sess)
}
if err != nil {
if !errors.Is(err, errHangup) {
t.write("\r\n")
if !errors.Is(err, term.ErrHangup) {
t.Write("\r\n")
}
logf("no login: %v (%v)", err, sess)
return 1
@@ -229,7 +232,7 @@ func run(t *term, s *settings, sess *session) int {
lim, err := newLimiter(s, sess, time.Now())
if err != nil {
logf("user=%s: no time left today", sess.User)
t.write("\r\nYou have used your time for today. Call again tomorrow.\r\n")
t.Write("\r\nYou have used your time for today. Call again tomorrow.\r\n")
return 0
}
setAtExit(lim.done)
@@ -241,8 +244,8 @@ func run(t *term, s *settings, sess *session) int {
}
lim.mark(sess, time.Now())
t.write(expand(s.welcome, sess.vars(false), nil))
t.write(motd(s, sess))
t.Write(config.Expand(s.welcome, sess.vars(false), nil))
t.Write(motd(s, sess))
var first *menuItem
if rule != nil && rule.item != "" {
first = s.selects(strings.ToUpper(rule.item))
@@ -253,11 +256,11 @@ func run(t *term, s *settings, sess *session) int {
err = menu(t, s, sess, lim, first)
switch {
case err == nil:
t.write(expand(s.goodbye, sess.vars(false), nil))
t.Write(config.Expand(s.goodbye, sess.vars(false), nil))
case errors.Is(err, errTimeLimit):
t.write("\r\n\r\nYour time is up." + expand(s.goodbye, sess.vars(false), nil))
case errors.Is(err, errTimeout):
t.write("\r\nIdle too long.\r\n")
t.Write("\r\n\r\nYour time is up." + config.Expand(s.goodbye, sess.vars(false), nil))
case errors.Is(err, term.ErrTimeout):
t.Write("\r\nIdle too long.\r\n")
}
logf("logout user=%s: %v", sess.User, describe(err))
return 0
@@ -273,12 +276,12 @@ func describe(err error) string {
// login: the user name and password until one is right, attempts tries
// or the login timeout
func login(t *term, s *settings, sess *session) error {
func login(t *term.Term, s *settings, sess *session) error {
deadline := time.Now().Add(s.loginTimeout)
// a terminal not known by the end is not a Commodore
defer func() { t.watchPETSCII = false }()
defer func() { t.WatchPETSCII = false }()
for try := 1; try <= s.attempts; try++ {
if err := t.write(s.loginPrompt); err != nil {
if err := t.Write(s.loginPrompt); err != nil {
return err
}
if s.autoppp.enabled {
@@ -291,8 +294,8 @@ func login(t *term, s *settings, sess *session) error {
return errAutoPPP
}
}
name, err := t.readLine(deadline, s.maxInput, true, "")
if errors.Is(err, errPETSCII) {
name, err := t.ReadLine(deadline, s.maxInput, true, "")
if errors.Is(err, term.ErrPETSCII) {
// a Commodore's key: the prompt again, for it
becomePETSCII(t, sess)
try--
@@ -301,7 +304,7 @@ func login(t *term, s *settings, sess *session) error {
if err != nil {
return err
}
if t.watchPETSCII && name != "" {
if t.WatchPETSCII && name != "" {
if name, err = settlePETSCII(t, s, sess, name, deadline); err != nil {
return err
}
@@ -320,35 +323,35 @@ func login(t *term, s *settings, sess *session) error {
if s.signup.enabled && strings.EqualFold(name, s.signup.name) {
return signup(t, s, sess, deadline)
}
if err := t.write(s.passwordPrompt); err != nil {
if err := t.Write(s.passwordPrompt); err != nil {
return err
}
pw, err := t.readLine(deadline, s.maxInput*2, false, s.mask)
pw, err := t.ReadLine(deadline, s.maxInput*2, false, s.mask)
if err != nil {
return err
}
auth := ""
via := ""
if s.userPattern.MatchString(name) {
ctx, cancel := context.WithDeadline(context.Background(), deadline.Add(10*time.Second))
auth, err = authenticate(ctx, s.backends, name, pw, logf)
via, err = auth.Authenticate(ctx, s.backends, name, pw, logf)
cancel()
} else {
// not a name we take: the same answer, after the same time
burn(pw)
err = errNoUser
auth.Burn(pw)
err = auth.ErrNoUser
}
if err == nil {
sess.User, sess.Password, sess.Auth = name, pw, auth
logf("login user=%s auth=%s %v", name, auth, sess)
sess.User, sess.Password, sess.Auth = name, pw, via
logf("login user=%s auth=%s %v", name, via, sess)
return nil
}
logf("failed login user=%q (%v) %v", name, err, sess)
time.Sleep(s.failDelay)
if err := t.write("\r\nLogin incorrect\r\n"); err != nil {
if err := t.Write("\r\nLogin incorrect\r\n"); err != nil {
return err
}
if terminated.Load() {
return errHangup
return term.ErrHangup
}
}
return errors.New("too many attempts")
@@ -363,15 +366,15 @@ func motd(s *settings, sess *session) string {
if err != nil {
logf("motd_file: %v", err)
} else {
m += crlf(string(b))
m += term.CRLF(string(b))
}
}
return expand(m, sess.vars(false), nil)
return config.Expand(m, sess.vars(false), nil)
}
// menu until the caller hangs up, says goodbye, the time is up or a
// selection ends with after = hangup; first (if not nil) starts at once
func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) error {
func menu(t *term.Term, s *settings, sess *session, lim *limiter, first *menuItem) error {
items := s.visible(sess)
redraw := first == nil
for {
@@ -386,7 +389,7 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
}
if redraw && first == nil {
var b strings.Builder
b.WriteString(expand(s.menuTitle, sess.vars(false), nil))
b.WriteString(config.Expand(s.menuTitle, sess.vars(false), nil))
width := len(s.hangup[0])
for _, it := range items {
width = max(width, len(it.key))
@@ -395,14 +398,14 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
fmt.Fprintf(&b, "\r\n [%s]%*s %s", it.key, width-len(it.key), "", it.label)
}
fmt.Fprintf(&b, "\r\n [%s]%*s Goodbye (hang up)\r\n", s.hangup[0], width-len(s.hangup[0]), "")
if err := t.write(b.String()); err != nil {
if err := t.Write(b.String()); err != nil {
return err
}
}
it := first
first = nil
if it == nil {
if err := t.write(expand(s.menuPrompt, sess.vars(false), nil)); err != nil {
if err := t.Write(config.Expand(s.menuPrompt, sess.vars(false), nil)); err != nil {
return err
}
@@ -411,17 +414,17 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
var choice string
var err error
if s.hotkeys {
if choice, err = t.readKey(idle); err == nil {
t.write(choice + "\r\n")
if choice, err = t.ReadKey(idle); err == nil {
t.Write(choice + "\r\n")
}
} else {
choice, err = t.readLine(idle, s.maxInput, true, "")
choice, err = t.ReadLine(idle, s.maxInput, true, "")
}
choice = strings.ToUpper(strings.TrimSpace(choice))
if err == io.EOF || contains(s.hangup, choice) {
return nil
}
if errors.Is(err, errTimeout) && limited && !time.Now().Before(lim.deadline) {
if errors.Is(err, term.ErrTimeout) && limited && !time.Now().Before(lim.deadline) {
return errTimeLimit
}
if err != nil {
@@ -438,7 +441,7 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
// what the caller may not use, it cannot tell from what is
// not there
if it = selectFrom(items, choice); it == nil {
t.write("Unknown selection; ? shows the menu.\r\n")
t.Write("Unknown selection; ? shows the menu.\r\n")
continue
}
}
@@ -449,8 +452,8 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
lim.mark(sess, time.Now())
logf("start %s user=%s mode=%s", it.name, sess.User, it.mode)
err := launch(t, s, it, sess, lim.deadline, logf)
if errors.Is(err, errHangup) || terminated.Load() {
return errHangup
if errors.Is(err, term.ErrHangup) || terminated.Load() {
return term.ErrHangup
}
if errors.Is(err, errTimeLimit) {
logf("%s: time limit", it.name)
@@ -459,7 +462,7 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
redraw = true
if err != nil {
logf("%s: %v", it.name, err)
t.write("\r\n\r\n" + it.label + " is not available now.\r\n")
t.Write("\r\n\r\n" + it.label + " is not available now.\r\n")
continue
}
logf("end %s user=%s", it.name, sess.User)
+94
View File
@@ -0,0 +1,94 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/D-Modem/menu/internal/config"
)
// TestExpand: {placeholders} replaced and shell-quoted; unknown ones
// kept
func TestExpand(t *testing.T) {
v := map[string]string{"user": "o'neil; rm -rf /", "baud": "33600"}
got := config.Expand("login {user} {baud} {unknown} {", v, shellQuote)
want := `login 'o'\''neil; rm -rf /' '33600' {unknown} {`
if got != want {
t.Errorf("got %q, want %q", got, want)
}
if got := config.Expand("{USER}/{baud}", v, nil); got != v["user"]+"/33600" {
t.Errorf("got %q", got)
}
if got := config.Unescape(`a\r\n\x41\\b`); got != "a\r\nA\\b" {
t.Errorf("unescape: %q", got)
}
}
// TestSession: the call's details in the environment
func TestSession(t *testing.T) {
now := time.Date(2026, 10, 10, 21, 5, 9, 0, time.UTC)
s := newSession("50666/31200", "5551000", "5559999", now)
s.User, s.Password = "alice", "secret"
env := strings.Join(s.environ(true), "\n")
for _, w := range []string{"MODEM_USER=alice", "MODEM_PASSWORD=secret", "MODEM_BAUD=50666",
"MODEM_RX_RATE=31200", "MODEM_DIALED=5551000", "MODEM_CALLERID=5559999",
"MODEM_DATE=2026-10-10", "MODEM_TIME=21:05:09", "MODEM_EPOCH=" + "1791666309"} {
if !strings.Contains(env, w+"\n") && !strings.HasSuffix(env, w) {
t.Errorf("no %s in\n%s", w, env)
}
}
if strings.Contains(strings.Join(s.environ(false), "\n"), "secret") {
t.Error("the password without pass_password")
}
}
// TestMenuSettings: what keys, names and aliases select, and the menu
// settings that are refused
func TestMenuSettings(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, nil, 0o600)
load := func(menu, items string) (*settings, error) {
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("[general]\nauth = file\n[file]\npath = "+users+"\n[menu]\n"+menu+"\n"+items), 0o600)
return loadSettings(p)
}
ppp := "[item ppp]\nkey = P\naliases = dialup net\ncommand = true\n"
s, err := load("", ppp+"[item bbs]\nkey = BBS\ncommand = true\n")
if err != nil {
t.Fatal(err)
}
for choice, want := range map[string]string{"P": "ppp", "PPP": "ppp", "NET": "ppp", "BBS": "bbs", "B": ""} {
it := s.selects(choice)
if want == "" && it != nil || want != "" && (it == nil || it.name != want) {
t.Errorf("%s selects %v, want %q", choice, it, want)
}
}
if !contains(s.hangup, "GOODBYE") {
t.Errorf("hangup %v", s.hangup)
}
for _, c := range []struct{ menu, items string }{
{"", ppp + "[item net]\ncommand = true\n"}, // net: an alias of ppp
{"hangup = P", ppp}, // P hangs up and selects ppp
{"hotkeys = yes", ppp + "[item bbs]\nkey = BBS\ncommand = true\n"},
} {
if _, err := load(c.menu, c.items); err == nil {
t.Errorf("%q %q: no error", c.menu, c.items)
}
}
if _, err := load("hotkeys = yes", ppp); err != nil {
t.Errorf("hotkeys with one-character keys: %v", err)
}
}
// runGo: the go command with args, its output
func runGo(args ...string) ([]byte, error) {
return exec.Command("go", args...).CombinedOutput()
}
+115
View File
@@ -0,0 +1,115 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/term"
)
// changePasswordItem: mode = passwd, the caller's password changed in
// the backend that holds their account
func changePasswordItem(t *term.Term, s *settings, it *menuItem, sess *session, deadline time.Time) error {
if sess.Auth == "guest" {
return t.Write("\r\nA guest has no password to change.\r\n")
}
end := time.Now().Add(s.loginTimeout)
if !deadline.IsZero() && deadline.Before(end) {
end = deadline
}
timeUp := func(err error) error {
if errors.Is(err, term.ErrTimeout) && !deadline.IsZero() && !time.Now().Before(deadline) {
return errTimeLimit
}
if errors.Is(err, term.ErrTimeout) || errors.Is(err, io.EOF) {
t.Write("\r\nYour password is as it was.\r\n")
return nil
}
return err
}
if err := t.Write("\r\nCurrent password: "); err != nil {
return err
}
old, err := t.ReadLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
// which backend holds the account: the one that takes the password
// (a login by caller ID or an upstream menu did not say)
ctx, cancel := context.WithDeadline(context.Background(), end.Add(10*time.Second))
defer cancel()
name, err := auth.Authenticate(ctx, s.backends, sess.User, old, logf)
if err != nil {
logf("passwd user=%s: current password wrong (%v)", sess.User, err)
time.Sleep(s.failDelay)
return t.Write("That is not your password.\r\n")
}
var changer auth.PasswordChanger
for _, b := range s.backends {
if b.Name() == name {
if c, ok := b.(auth.PasswordChanger); ok && c.CanChangePassword() {
changer = c
}
}
}
if changer == nil {
logf("passwd user=%s: %s cannot change passwords", sess.User, name)
return t.Write("Your password cannot be changed here. Ask the sysop.\r\n")
}
var pw string
for try := 0; ; try++ {
if try == 3 {
return t.Write("Your password is as it was.\r\n")
}
if err := t.Write("New password: "); err != nil {
return err
}
p, err := t.ReadLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
switch {
case p == "":
return t.Write("Your password is as it was.\r\n")
case len(p) < it.minPassword:
t.Write(fmt.Sprintf("At least %d characters, please.\r\n", it.minPassword))
continue
case p == old:
t.Write("That is your password now; another one, please.\r\n")
continue
}
if err := t.Write("Again: "); err != nil {
return err
}
again, err := t.ReadLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
if again != p {
t.Write("They differ.\r\n")
continue
}
pw = p
break
}
if err := changer.ChangePassword(ctx, t, sess.User, old, pw); err != nil {
logf("passwd user=%s auth=%s: %v", sess.User, name, err)
if errors.Is(err, auth.ErrRefused) {
return t.Write("The new password was not accepted. Your password is as it was.\r\n")
}
return t.Write("Sorry, your password cannot be changed now.\r\n")
}
sess.Password = pw
logf("passwd user=%s auth=%s: changed", sess.User, name)
return t.Write("Your password is changed.\r\n")
}
+119
View File
@@ -0,0 +1,119 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// TestPasswdLine: on a line, a mode = passwd item changes the password
func TestPasswdLine(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, "modemmenu")
if out, err := runGo("build", "-o", bin, "."); err != nil {
t.Fatalf("build: %v\n%s", err, out)
}
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("alice:{PLAIN}old-password\n"), 0o600)
conf := filepath.Join(dir, "c.conf")
os.WriteFile(conf, []byte(fmt.Sprintf(`
[general]
log = %s
auth = file
fail_delay = 0
[file]
path = %s
[guest]
enabled = yes
[item passwd]
key = PW
label = Change your password
mode = passwd
guest = yes
[item info]
command = echo "PW=$MODEM_PASSWORD"
after = menu
`, filepath.Join(dir, "log"), users)), 0o600)
c, cmd := callAs(t, bin, conf)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("old-password\r")
c.expect("Selection: ")
c.send("pw\r")
c.expect("Current password: ")
c.send("wrong\r")
c.expect("That is not your password.")
c.expect("Selection: ")
c.send("passwd\r")
c.expect("Current password: ")
c.send("old-password\r")
c.expect("New password: ")
c.send("short\r")
c.expect("At least 8")
c.expect("New password: ")
c.send("old-password\r")
c.expect("another one")
c.expect("New password: ")
c.send("new-password\r")
c.expect("Again: ")
c.send("new-passwork\r")
c.expect("They differ.")
// three tries
c.expect("Your password is as it was.")
c.expect("Selection: ")
c.send("pw\r")
c.expect("Current password: ")
c.send("old-password\r")
c.expect("New password: ")
c.send("new-password\r")
c.expect("Again: ")
c.send("new-password\r")
c.expect("Your password is changed.")
c.expect("Selection: ")
// the selections after it get the new one
c.send("info\r")
c.expect("PW=new-password")
c.send("g\r")
waitExit(t, cmd)
c, cmd = callAs(t, bin, conf)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("old-password\r")
c.expect("Login incorrect")
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("new-password\r")
c.expect("Selection: ")
c.send("g\r")
waitExit(t, cmd)
// a guest has none
c, cmd = callAs(t, bin, conf)
c.expect("login: ")
c.send("guest\r")
c.expect("Selection: ")
c.send("pw\r")
c.expect("A guest has no password")
c.send("g\r")
waitExit(t, cmd)
log, _ := os.ReadFile(filepath.Join(dir, "log"))
for _, w := range []string{"passwd user=alice: current password wrong", "passwd user=alice auth=file: changed"} {
if !strings.Contains(string(log), w) {
t.Errorf("no %q in the log:\n%s", w, log)
}
}
if strings.Contains(string(log), "new-password") {
t.Errorf("a password in the log:\n%s", log)
}
}
@@ -13,11 +13,11 @@ import (
)
// TestSampleHasEveryKey: each key the code reads is in
// modemmenu.conf.sample, so it has help there and a line in the
// samples/modemmenu.conf.sample, so it has help there and a line in the
// configuration reference (go run ./tools/confref makes docs/reference.md
// from the sample).
func TestSampleHasEveryKey(t *testing.T) {
sample, err := os.ReadFile("modemmenu.conf.sample")
sample, err := os.ReadFile("../../samples/modemmenu.conf.sample")
if err != nil {
t.Fatal(err)
}
@@ -25,8 +25,11 @@ func TestSampleHasEveryKey(t *testing.T) {
for _, m := range regexp.MustCompile(`(?m)^;?\s*([a-z][a-z0-9_]*)\s*=`).FindAllSubmatch(sample, -1) {
inSample[string(m[1])] = true
}
re := regexp.MustCompile(`\.(?:get|has|bool|int|duration|durations)\("([a-z0-9_]+)"`)
re := regexp.MustCompile(`(\w+)\.(?:Get|Has|Bool|Int|Duration|Durations)\("([a-z0-9_]+)"`)
// this command's and its packages' (internal/auth reads [file], [ldap]...)
files, _ := filepath.Glob("*.go")
more, _ := filepath.Glob("../../internal/*/*.go")
files = append(files, more...)
var missing []string
for _, f := range files {
if strings.HasSuffix(f, "_test.go") {
@@ -37,9 +40,12 @@ func TestSampleHasEveryKey(t *testing.T) {
t.Fatal(err)
}
for _, m := range re.FindAllStringSubmatch(string(src), -1) {
if !inSample[m[1]] {
missing = append(missing, f+": "+m[1])
inSample[m[1]] = true
if m[1] == "flag" {
continue // the command line's
}
if !inSample[m[2]] {
missing = append(missing, f+": "+m[2])
inSample[m[2]] = true
}
}
}
+2 -1
View File
@@ -18,6 +18,7 @@ import (
"syscall"
"time"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/sys/unix"
)
@@ -356,7 +357,7 @@ func openPty() (*os.File, *os.File, error) {
return nil, nil, err
}
if tio, err := unix.IoctlGetTermios(int(s.Fd()), unix.TCGETS); err == nil {
makeRaw(tio)
term.MakeRaw(tio)
unix.IoctlSetTermios(int(s.Fd()), unix.TCSETS, tio)
}
return m, s, nil
File renamed without changes.
-30
View File
@@ -172,36 +172,6 @@ func (s *session) writeFile(withPassword bool, uid, gid int) (string, error) {
return f.Name(), nil
}
// expand replaces {name} by its value, quote() of it (nil: as is);
// unknown names stay as they are
func expand(t string, v map[string]string, quote func(string) string) string {
var b strings.Builder
for {
i := strings.IndexByte(t, '{')
if i < 0 {
break
}
j := strings.IndexByte(t[i:], '}')
if j < 0 {
break
}
name := t[i+1 : i+j]
val, ok := v[strings.ToLower(name)]
b.WriteString(t[:i])
switch {
case !ok:
b.WriteString(t[i : i+j+1])
case quote != nil:
b.WriteString(quote(val))
default:
b.WriteString(val)
}
t = t[i+j+1:]
}
b.WriteString(t)
return b.String()
}
// shellQuote: a value as one word of /bin/sh
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+86 -88
View File
@@ -10,6 +10,10 @@ import (
"strconv"
"strings"
"time"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/config"
"github.com/D-Modem/menu/internal/term"
)
type general struct {
@@ -93,72 +97,72 @@ type settings struct {
hangup []string // what hangs up, upper case; the first one shown
hotkeys bool // one key selects, without a line end
items []*menuItem
backends []authenticator
backends []auth.Authenticator
}
// loadSettings: the configuration file, every section loaded and
// checked
func loadSettings(path string) (*settings, error) {
c, err := parseINI(path)
c, err := config.Parse(path)
if err != nil {
return nil, err
}
s := &settings{}
g := c.section("general")
s.log = g.get("log", "syslog")
s.banner = unescape(g.get("banner", `\r\nD-Modem\r\n`))
if f := g.get("banner_file", ""); f != "" {
g := c.Section("general")
s.log = g.Get("log", "syslog")
s.banner = config.Unescape(g.Get("banner", `\r\nD-Modem\r\n`))
if f := g.Get("banner_file", ""); f != "" {
b, err := os.ReadFile(f)
if err != nil {
return nil, fmt.Errorf("[general] banner_file: %v", err)
}
s.banner = crlf(string(b))
s.banner = term.CRLF(string(b))
}
s.loginPrompt = unescape(g.get("login_prompt", `\r\nlogin: `))
s.passwordPrompt = unescape(g.get("password_prompt", "Password: "))
s.welcome = unescape(g.get("welcome", `\r\nWelcome, {user}.\r\n`))
s.connectMessage = unescape(g.get("connect_message", `\r\nConnected at {speed}.\r\n`))
s.motd = unescape(g.get("motd", ""))
s.motdFile = g.get("motd_file", "")
s.goodbye = unescape(g.get("goodbye", `\r\nGoodbye.\r\n`))
s.mask = g.get("password_echo", "*")
s.loginPrompt = config.Unescape(g.Get("login_prompt", `\r\nlogin: `))
s.passwordPrompt = config.Unescape(g.Get("password_prompt", "Password: "))
s.welcome = config.Unescape(g.Get("welcome", `\r\nWelcome, {user}.\r\n`))
s.connectMessage = config.Unescape(g.Get("connect_message", `\r\nConnected at {speed}.\r\n`))
s.motd = config.Unescape(g.Get("motd", ""))
s.motdFile = g.Get("motd_file", "")
s.goodbye = config.Unescape(g.Get("goodbye", `\r\nGoodbye.\r\n`))
s.mask = g.Get("password_echo", "*")
if s.mask == "none" {
s.mask = ""
}
if s.attempts, err = g.int("attempts", 3); err != nil {
if s.attempts, err = g.Int("attempts", 3); err != nil {
return nil, err
}
if s.maxInput, err = g.int("max_input", 64); err != nil {
if s.maxInput, err = g.Int("max_input", 64); err != nil {
return nil, err
}
if s.failDelay, err = g.duration("fail_delay", 3*time.Second); err != nil {
if s.failDelay, err = g.Duration("fail_delay", 3*time.Second); err != nil {
return nil, err
}
if s.loginTimeout, err = g.duration("login_timeout", 90*time.Second); err != nil {
if s.loginTimeout, err = g.Duration("login_timeout", 90*time.Second); err != nil {
return nil, err
}
if s.idleTimeout, err = g.duration("idle_timeout", 5*time.Minute); err != nil {
if s.idleTimeout, err = g.Duration("idle_timeout", 5*time.Minute); err != nil {
return nil, err
}
pat := g.get("user_pattern", `^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$`)
pat := g.Get("user_pattern", `^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$`)
if s.userPattern, err = regexp.Compile(pat); err != nil {
return nil, fmt.Errorf("[general] user_pattern: %v", err)
}
s.auth = fields(strings.ToLower(g.get("auth", "file")))
s.auth = config.Fields(strings.ToLower(g.Get("auth", "file")))
if len(s.auth) == 0 {
return nil, fmt.Errorf("[general] auth: no authentication backend")
}
for _, name := range s.auth {
var a authenticator
var a auth.Authenticator
switch name {
case "file":
a, err = newFileAuth(c.section("file"))
a, err = auth.NewFile(c.Section("file"))
case "ldap":
a, err = newLDAPAuth(c.section("ldap"))
a, err = auth.NewLDAP(c.Section("ldap"))
case "sql":
a, err = newSQLAuth(c.section("sql"))
a, err = auth.NewSQL(c.Section("sql"))
case "system", "pam":
a, err = newSystemAuth(c.section("system"))
a, err = auth.NewSystem(c.Section("system"))
default:
err = fmt.Errorf("[general] auth: unknown backend %q (file, ldap, sql, system)", name)
}
@@ -168,43 +172,43 @@ func loadSettings(path string) (*settings, error) {
s.backends = append(s.backends, a)
}
if s.server, err = loadServer(c.section("server")); err != nil {
if s.server, err = loadServer(c.Section("server")); err != nil {
return nil, err
}
if err := loadAccess(c, s); err != nil {
return nil, err
}
if s.dropfile, err = loadDropfile(c.section("dropfile")); err != nil {
if s.dropfile, err = loadDropfile(c.Section("dropfile")); err != nil {
return nil, err
}
if s.autoppp, err = loadAutoPPP(c.section("autoppp")); err != nil {
if s.autoppp, err = loadAutoPPP(c.Section("autoppp")); err != nil {
return nil, err
}
if s.terminal, err = loadTerminal(c.section("terminal")); err != nil {
if s.terminal, err = loadTerminal(c.Section("terminal")); err != nil {
return nil, err
}
if s.authd, err = loadAuthd(c.section("authd")); err != nil {
if s.authd, err = loadAuthd(c.Section("authd")); err != nil {
return nil, err
}
m := c.section("menu")
s.menuTitle = unescape(m.get("title", `\r\nMain menu\r\n`))
s.menuPrompt = unescape(m.get("prompt", `\r\nSelection: `))
s.hangup = fields(strings.ToUpper(m.get("hangup", "G goodbye bye logoff")))
m := c.Section("menu")
s.menuTitle = config.Unescape(m.Get("title", `\r\nMain menu\r\n`))
s.menuPrompt = config.Unescape(m.Get("prompt", `\r\nSelection: `))
s.hangup = config.Fields(strings.ToUpper(m.Get("hangup", "G goodbye bye logoff")))
if len(s.hangup) == 0 {
return nil, fmt.Errorf("[menu] hangup: nothing to hang up with")
}
var names []string
if m.has("items") {
names = fields(m.get("items", ""))
if m.Has("items") {
names = config.Fields(m.Get("items", ""))
} else {
for _, sec := range c.sections {
if strings.HasPrefix(sec.name, "item ") {
names = append(names, strings.TrimPrefix(sec.name, "item "))
for _, sec := range c.Sections {
if strings.HasPrefix(sec.Name, "item ") {
names = append(names, strings.TrimPrefix(sec.Name, "item "))
}
}
}
if s.hotkeys, err = m.bool("hotkeys", false); err != nil {
if s.hotkeys, err = m.Bool("hotkeys", false); err != nil {
return nil, err
}
keys := map[string]string{}
@@ -212,7 +216,7 @@ func loadSettings(path string) (*settings, error) {
keys[h] = "[menu] hangup"
}
for _, name := range names {
sec, ok := c.byName["item "+name]
sec, ok := c.ByName["item "+name]
if !ok {
return nil, fmt.Errorf("[menu] items: no [item %s]", name)
}
@@ -254,77 +258,77 @@ func loadSettings(path string) (*settings, error) {
}
// loadItem: an [item ...] section, checked
func loadItem(name string, sec *section) (*menuItem, error) {
func loadItem(name string, sec *config.Section) (*menuItem, error) {
var err error
it := &menuItem{name: name}
it.key = strings.ToUpper(sec.get("key", name[:1]))
it.key = strings.ToUpper(sec.Get("key", name[:1]))
if it.key == "" || strings.ContainsAny(it.key, " \t,") {
return nil, fmt.Errorf("[item %s] key: %q (one word)", name, it.key)
}
// the key, the item's name and its aliases all select it
it.choices = []string{it.key}
for _, c := range append([]string{name}, fields(sec.get("aliases", ""))...) {
for _, c := range append([]string{name}, config.Fields(sec.Get("aliases", ""))...) {
c = strings.ToUpper(c)
if c != it.key && !contains(it.choices, c) {
it.choices = append(it.choices, c)
}
}
it.label = sec.get("label", name)
it.mode = strings.ToLower(sec.get("mode", "exec"))
it.command = sec.get("command", "")
it.host = sec.get("host", "127.0.0.1")
it.send = sec.get("send", "")
it.path = sec.get("path", "")
if it.header, err = sec.bool("header", false); err != nil {
it.label = sec.Get("label", name)
it.mode = strings.ToLower(sec.Get("mode", "exec"))
it.command = sec.Get("command", "")
it.host = sec.Get("host", "127.0.0.1")
it.send = sec.Get("send", "")
it.path = sec.Get("path", "")
if it.header, err = sec.Bool("header", false); err != nil {
return nil, err
}
it.rloginLocal = sec.get("rlogin_client_user", "{password}")
it.rloginUser = sec.get("rlogin_server_user", "{user}")
it.rloginTerm = sec.get("rlogin_terminal", "ansi/{baud}")
it.terminal = sec.get("terminal", "ANSI")
it.runAs = sec.get("run_as", "")
it.tty = strings.ToLower(sec.get("tty", "raw"))
it.rloginLocal = sec.Get("rlogin_client_user", "{password}")
it.rloginUser = sec.Get("rlogin_server_user", "{user}")
it.rloginTerm = sec.Get("rlogin_terminal", "ansi/{baud}")
it.terminal = sec.Get("terminal", "ANSI")
it.runAs = sec.Get("run_as", "")
it.tty = strings.ToLower(sec.Get("tty", "raw"))
defAfter := "hangup"
if m := strings.ToLower(sec.get("mode", "")); m == "passwd" || m == "callers" {
if m := strings.ToLower(sec.Get("mode", "")); m == "passwd" || m == "callers" {
// a password changed is no reason to hang up
defAfter = "menu"
}
it.after = strings.ToLower(sec.get("after", defAfter))
if it.minPassword, err = sec.int("min_password", 8); err != nil {
it.after = strings.ToLower(sec.Get("after", defAfter))
if it.minPassword, err = sec.Int("min_password", 8); err != nil {
return nil, err
}
if it.timeWarning, err = sec.bool("time_warning", true); err != nil {
if it.timeWarning, err = sec.Bool("time_warning", true); err != nil {
return nil, err
}
if it.count, err = sec.int("count", 10); err != nil {
if it.count, err = sec.Int("count", 10); err != nil {
return nil, err
}
if it.dropfiles, err = loadItemDropfiles(name, sec); err != nil {
return nil, err
}
it.dropfileDir = sec.get("dropfile_dir", "")
if it.security, err = sec.int("security", 0); err != nil {
it.dropfileDir = sec.Get("dropfile_dir", "")
if it.security, err = sec.Int("security", 0); err != nil {
return nil, err
}
if it.doorSysLines, err = sec.int("door_sys_lines", 52); err != nil {
if it.doorSysLines, err = sec.Int("door_sys_lines", 52); err != nil {
return nil, err
}
if it.doorSysLines != 52 && it.doorSysLines != 31 {
return nil, fmt.Errorf("[item %s] door_sys_lines: %d (52 or 31)", name, it.doorSysLines)
}
if it.dropfileLower, err = sec.bool("dropfile_lowercase", false); err != nil {
if it.dropfileLower, err = sec.Bool("dropfile_lowercase", false); err != nil {
return nil, err
}
if len(it.dropfiles) > 0 && strings.ToLower(sec.get("mode", "exec")) != "exec" {
if len(it.dropfiles) > 0 && strings.ToLower(sec.Get("mode", "exec")) != "exec" {
return nil, fmt.Errorf("[item %s] dropfile is for mode = exec", name)
}
if it.password, err = sec.bool("pass_password", true); err != nil {
if it.password, err = sec.Bool("pass_password", true); err != nil {
return nil, err
}
if it.sessionFile, err = sec.bool("session_file", false); err != nil {
if it.sessionFile, err = sec.Bool("session_file", false); err != nil {
return nil, err
}
if it.timeout, err = sec.duration("connect_timeout", 10*time.Second); err != nil {
if it.timeout, err = sec.Duration("connect_timeout", 10*time.Second); err != nil {
return nil, err
}
if it.access, err = loadItemAccess(name, sec); err != nil {
@@ -338,7 +342,7 @@ func loadItem(name string, sec *section) (*menuItem, error) {
}
}
defPort := map[string]int{"tcp": 23, "telnet": 23, "rlogin": 513}[it.mode]
if it.port, err = sec.int("port", defPort); err != nil {
if it.port, err = sec.Int("port", defPort); err != nil {
return nil, err
}
switch it.mode {
@@ -370,12 +374,6 @@ func loadItem(name string, sec *section) (*menuItem, error) {
return it, nil
}
// crlf: the line ends of a text file as the terminal wants them
func crlf(s string) string {
s = strings.ReplaceAll(s, "\r\n", "\n")
return strings.ReplaceAll(s, "\n", "\r\n")
}
// contains: whether s is in list
func contains(list []string, s string) bool {
for _, v := range list {
@@ -387,30 +385,30 @@ func contains(list []string, s string) bool {
}
// loadServer: [server], for modemmenu -serve
func loadServer(sec *section) (*serverSettings, error) {
func loadServer(sec *config.Section) (*serverSettings, error) {
var err error
srv := &serverSettings{
listen: sec.get("listen", "/run/modemmenu/modemmenu.sock"),
socketGroup: sec.get("socket_group", ""),
listen: sec.Get("listen", "/run/modemmenu/modemmenu.sock"),
socketGroup: sec.Get("socket_group", ""),
}
mode, err := strconv.ParseUint(sec.get("socket_mode", "0660"), 8, 32)
mode, err := strconv.ParseUint(sec.Get("socket_mode", "0660"), 8, 32)
if err != nil || mode > 0o777 {
return nil, fmt.Errorf("[server] socket_mode: %q (octal, e.g. 0660)", sec.get("socket_mode", ""))
return nil, fmt.Errorf("[server] socket_mode: %q (octal, e.g. 0660)", sec.Get("socket_mode", ""))
}
srv.socketMode = os.FileMode(mode)
if srv.header, err = sec.bool("header", true); err != nil {
if srv.header, err = sec.Bool("header", true); err != nil {
return nil, err
}
if srv.headerTimeout, err = sec.duration("header_timeout", 10*time.Second); err != nil {
if srv.headerTimeout, err = sec.Duration("header_timeout", 10*time.Second); err != nil {
return nil, err
}
if srv.trustUser, err = sec.bool("trust_user", false); err != nil {
if srv.trustUser, err = sec.Bool("trust_user", false); err != nil {
return nil, err
}
if srv.trustUser && !srv.header {
return nil, fmt.Errorf("[server] trust_user needs header = yes")
}
if srv.maxSessions, err = sec.int("max_sessions", 32); err != nil {
if srv.maxSessions, err = sec.Int("max_sessions", 32); err != nil {
return nil, err
}
if srv.maxSessions < 1 {
+16 -14
View File
@@ -11,6 +11,8 @@ import (
"strings"
"time"
"github.com/D-Modem/menu/internal/auth"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/crypto/bcrypt"
"golang.org/x/sys/unix"
)
@@ -20,9 +22,9 @@ var errPending = errors.New("account pending approval")
// signup: a new account in the users file, the caller logged in with it
// (or errPending with signup's pending = yes)
func signup(t *term, s *settings, sess *session, deadline time.Time) error {
func signup(t *term.Term, s *settings, sess *session, deadline time.Time) error {
su := s.signup
if err := t.write(su.message); err != nil {
if err := t.Write(su.message); err != nil {
return err
}
var name string
@@ -30,16 +32,16 @@ func signup(t *term, s *settings, sess *session, deadline time.Time) error {
if try == 3 {
return errors.New("signup: no name taken")
}
if err := t.write("\r\nUser name: "); err != nil {
if err := t.Write("\r\nUser name: "); err != nil {
return err
}
n, err := t.readLine(deadline, s.maxInput, true, "")
n, err := t.ReadLine(deadline, s.maxInput, true, "")
if err != nil {
return err
}
n = strings.TrimSpace(n)
if why := s.nameTaken(n); why != "" {
t.write(why + "\r\n")
t.Write(why + "\r\n")
continue
}
name = n
@@ -50,26 +52,26 @@ func signup(t *term, s *settings, sess *session, deadline time.Time) error {
if try == 3 {
return errors.New("signup: no password")
}
if err := t.write("Password: "); err != nil {
if err := t.Write("Password: "); err != nil {
return err
}
p, err := t.readLine(deadline, s.maxInput*2, false, s.mask)
p, err := t.ReadLine(deadline, s.maxInput*2, false, s.mask)
if err != nil {
return err
}
if len(p) < su.minPassword {
t.write(fmt.Sprintf("At least %d characters, please.\r\n", su.minPassword))
t.Write(fmt.Sprintf("At least %d characters, please.\r\n", su.minPassword))
continue
}
if err := t.write("Again: "); err != nil {
if err := t.Write("Again: "); err != nil {
return err
}
again, err := t.readLine(deadline, s.maxInput*2, false, s.mask)
again, err := t.ReadLine(deadline, s.maxInput*2, false, s.mask)
if err != nil {
return err
}
if again != p {
t.write("They differ.\r\n")
t.Write("They differ.\r\n")
continue
}
pw = p
@@ -92,12 +94,12 @@ func signup(t *term, s *settings, sess *session, deadline time.Time) error {
}, note)
if err := appendUser(su.file, name, name+":"+lock+string(hash)+":"+note+"\n"); err != nil {
logf("signup %s: %v", name, err)
t.write("\r\nSorry, no new accounts now.\r\n")
t.Write("\r\nSorry, no new accounts now.\r\n")
return err
}
logf("signup user=%s pending=%v %v", name, su.pending, sess)
if su.pending {
t.write("\r\nThank you. Your account waits for the sysop's approval.\r\n")
t.Write("\r\nThank you. Your account waits for the sysop's approval.\r\n")
return errPending
}
sess.User, sess.Password, sess.Auth = name, pw, "file"
@@ -118,7 +120,7 @@ func (s *settings) nameTaken(name string) string {
}
// a system account's name would let the new user log in to a
// selection run_as that account
if _, err := lookupNSS(name); err == nil {
if _, err := auth.LookupNSS(name); err == nil {
return "That name is taken."
}
return ""
File renamed without changes.
+158
View File
@@ -0,0 +1,158 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/D-Modem/menu/internal/config"
"github.com/D-Modem/menu/internal/term"
"golang.org/x/sys/unix"
)
// terminalSettings: [terminal]
type terminalSettings struct {
detect bool // ask: ANSI, VT52, an ANSI terminal's identity
petscii string // auto (a terminal that is not ANSI may be one), yes (every caller), no
timeout time.Duration
}
// loadTerminal: [terminal], checked
func loadTerminal(sec *config.Section) (terminalSettings, error) {
var err error
ts := terminalSettings{
petscii: strings.ToLower(sec.Get("petscii", "auto")),
}
if ts.detect, err = sec.Bool("detect", true); err != nil {
return ts, err
}
if ts.timeout, err = sec.Duration("timeout", 2*time.Second); err != nil {
return ts, err
}
switch ts.petscii {
case "auto", "yes", "no":
default:
return ts, fmt.Errorf("[terminal] petscii: %q (auto, yes or no)", ts.petscii)
}
return ts, nil
}
// detectTerminal: what the caller's terminal is, in sess (Terminal, Term,
// TermName, Rows, Cols), the line set for it
func detectTerminal(t *term.Term, s *settings, sess *session) error {
ts := s.terminal
defer func() {
if sess.Terminal == "petscii" {
t.SetPETSCII()
}
if sess.Rows != "" && sess.Cols != "" {
rows, _ := strconv.Atoi(sess.Rows)
cols, _ := strconv.Atoi(sess.Cols)
// the line's size, for what a selection runs on it
unix.IoctlSetWinsize(t.In, unix.TIOCSWINSZ, &unix.Winsize{Row: uint16(rows), Col: uint16(cols)})
}
}()
switch {
case sess.Terminal != "":
// an upstream menu said
return nil
case ts.petscii == "yes":
sess.Terminal, sess.Term, sess.Rows, sess.Cols = "petscii", "dumb", "25", "40"
return nil
}
p := &term.Prober{T: t}
defer p.Done()
if !ts.detect || p.PPP {
// not asked: perhaps a Commodore, whose keys will tell
t.WatchPETSCII = ts.petscii == "auto" && !p.PPP
return nil
}
ansi, rows, cols, err := p.ANSI(ts.timeout)
if err != nil || p.PPP {
return err
}
if !ansi {
is52, err := p.VT52(ts.timeout / 2)
if err != nil || p.PPP {
return err
}
if is52 {
sess.Terminal, sess.Term, sess.TermName, sess.Rows, sess.Cols = "vt52", "vt52", "VT52", "24", "80"
return nil
}
sess.Terminal, sess.Term = "ascii", "dumb"
// perhaps a Commodore: its keys will tell
t.WatchPETSCII = ts.petscii == "auto"
return nil
}
sess.Terminal, sess.Term = "ansi", "ansi"
if rows > 0 && cols > 0 {
sess.Rows, sess.Cols = strconv.Itoa(rows), strconv.Itoa(cols)
}
in, err := p.Identify(ts.timeout)
if err != nil {
return err
}
if n := in.Name(); n != "" {
sess.TermName = n
}
sess.Term = in.Term()
if in.Level() > 0 || in.Emulator() {
sess.Terminal = "vt"
}
return nil
}
// becomePETSCII: the caller has a Commodore after all
func becomePETSCII(t *term.Term, sess *session) {
t.WatchPETSCII = false
sess.Terminal, sess.Term, sess.Rows, sess.Cols = "petscii", "dumb", "25", "40"
unix.IoctlSetWinsize(t.In, unix.TIOCSWINSZ, &unix.Winsize{Row: 25, Col: 40})
t.SetPETSCII()
logf("terminal: a Commodore (PETSCII) %v", sess)
}
// settlePETSCII: a name typed all in capitals, while it is not known
// whether the terminal is a Commodore: a Commodore's unshifted keys, or
// ASCII in capitals, and DEL tells which. The name as the caller meant
// it.
func settlePETSCII(t *term.Term, s *settings, sess *session, name string, deadline time.Time) (string, error) {
t.WatchPETSCII = false
if strings.ToUpper(name) != name || strings.ToLower(name) == name {
return name, nil // lower case, or no letters
}
if err := t.Write("PRESS DEL (OR BACKSPACE): "); err != nil {
return "", err
}
wait := min(30*time.Second, time.Until(deadline))
c, err := t.ReadOne(wait)
if err != nil && !errors.Is(err, term.ErrTimeout) {
return "", err
}
t.Write("\r\n")
if c != 0x14 {
return name, nil
}
becomePETSCII(t, sess)
// its unshifted letters are lower case
name = strings.ToLower(name)
t.Write(s.loginPrompt + name + "\r\n")
return name, nil
}
// describeTerminal: for the log
func (s *session) describeTerminal() string {
d := s.Terminal
if s.TermName != "" {
d += " (" + s.TermName + ")"
}
if s.Rows != "" {
d += " " + s.Cols + "x" + s.Rows
}
return d
}
@@ -14,45 +14,6 @@ import (
"testing"
)
// TestParseVT: names, TERMs and levels from real terminals' answers
func TestParseVT(t *testing.T) {
for _, c := range []struct {
what, reply, name, term string
level int
}{
{"xterm", "\x1b[?64;1;2;6;9;15;18;21;22c\x1b[>41;390;0c\x1bP>|XTerm(390)\x1b\\\x1b[50;132R", "XTerm(390)", "xterm", 4},
{"xterm without XTVERSION", "\x1b[?65;1;9c\x1b[>41;390;0c\x1b[24;80R", "xterm (patch 390)", "xterm", 5},
{"a VT220", "\x1b[?62;1;2;6;8;9;15c\x1b[>1;10;0c\x1b[24;80R", "VT220", "vt220", 2},
{"a VT520", "\x1b[?65;1;2;6;7;8;9;12;18;19;21;22;23;24;42;44;45;46c\x1b[>64;20;0c\x1b[24;80R", "VT520", "vt520", 5},
{"a VT100", "\x1b[?1;2c\x1b[24;80R", "VT100", "vt100", 1},
{"a VT102", "\x1b[?6c\x1b[24;80R", "VT102", "vt102", 1},
{"SyncTERM", "\x1b[=67;84;101;114;109;1;316c\x1b[24;80R", "SyncTERM (CTerm 1.316)", "syncterm", 0},
{"VTE", "\x1b[?65;1;9c\x1b[>65;6800;1c\x1b[24;80R", "VTE", "xterm", 5},
{"an answerback", "MYTERM\x1b[?62;1c\x1b[24;80R", "MYTERM", "vt220", 2},
{"nothing said", "\x1b[24;80R", "", "ansi", 0},
} {
in := parseVT([]byte(c.reply))
if in.name() != c.name || in.term() != c.term || in.level() != c.level {
t.Errorf("%s: %q %q level %d, want %q %q %d", c.what, in.name(), in.term(), in.level(), c.name, c.term, c.level)
}
}
}
// TestPETSCIIText: the menu's text as PETSCII, and a Commodore's keys
// as ASCII
func TestPETSCIIText(t *testing.T) {
if got := string(petsciiOut("Hi you\r\n\x1b[1;33mX\b \b\n")); got != "\xc8I YOU\r\xd8\x9d \x9d\r" {
t.Errorf("out %q", got)
}
var in []byte
for _, c := range []byte("HI\xc8\x14\r") {
in = append(in, petsciiIn(c))
}
if string(in) != "hiH\x7f\r" {
t.Errorf("in %q", in)
}
}
// the terminal's details from an upstream menu's header, not asked again
func TestTerminalHeader(t *testing.T) {
env := strings.Join(headerEnv(map[string]string{"MODEM_TERMINAL": "vt", "MODEM_TERM": "vt220",
+1 -1
View File
@@ -9,4 +9,4 @@
- [Security notes](security.md)
- [Tests](testing.md)
The samples: [modemmenu.conf.sample](../modemmenu.conf.sample), [modemmenu.users.sample](../modemmenu.users.sample), [modemmenu.pam.sample](../modemmenu.pam.sample), [modemmenu.service.sample](../modemmenu.service.sample), [modemmenu-authd.service.sample](../modemmenu-authd.service.sample).
The samples: [modemmenu.conf.sample](../samples/modemmenu.conf.sample), [modemmenu.users.sample](../samples/modemmenu.users.sample), [modemmenu.pam.sample](../samples/modemmenu.pam.sample), [modemmenu.service.sample](../samples/modemmenu.service.sample), [modemmenu-authd.service.sample](../samples/modemmenu-authd.service.sample).
+3 -3
View File
@@ -40,7 +40,7 @@ checks for expired and locked accounts. It needs a build with PAM
(above). To set it up:
1. Install the PAM service: `make install` puts
[modemmenu.pam.sample](../modemmenu.pam.sample) in `/etc/pam.d/modemmenu`
[modemmenu.pam.sample](../samples/modemmenu.pam.sample) in `/etc/pam.d/modemmenu`
(the distribution's `common-auth`, `common-account` and, for password
changes, `common-password`).
2. Run Asterisk, and so modemmenu, as root for local accounts:
@@ -84,7 +84,7 @@ password where, never the password.
Run as root, `pam_unix` applies no quality checks (its `minlen` and
the like are not for root): for a policy, put `pam_pwquality` before it
with `enforce_for_root`, as
[modemmenu.pam.sample](../modemmenu.pam.sample) shows.
[modemmenu.pam.sample](../samples/modemmenu.pam.sample) shows.
## The same password elsewhere: the auth socket
@@ -104,7 +104,7 @@ allow_users = bbs
```
`modemmenu -serve` answers it as well as its sessions; `modemmenu -authd`
answers it alone (modemmenu-authd.service.sample). One request a
answers it alone ([modemmenu-authd.service.sample](../samples/modemmenu-authd.service.sample)). One request a
connection, a JSON line each way:
```
+19 -1
View File
@@ -4,7 +4,7 @@
Go 1.22 or later:
```
make # or: go build (-tags pam for PAM)
make # or: go build ./cmd/modemmenu (-tags pam for PAM)
make PAM=0 # without PAM, when libpam's headers are there
make test
make install # /usr/local/bin/modemmenu, and the samples into
@@ -15,3 +15,21 @@ make install # /usr/local/bin/modemmenu, and the samples into
(`libpam0g-dev` on Debian and Ubuntu, `pam-devel` on Fedora). Without
them modemmenu builds with the other backends, and `auth = system` is a
configuration error.
## The source
One Go module, one program:
| Where | What |
| --- | --- |
| `cmd/modemmenu/` | the program: the login, the menu, access rules and time limits, the selections, `-serve`, AutoPPP, drop files, the auth socket's server |
| `internal/config/` | modemmenu.conf's sections and keys, and the `{name}` templates |
| `internal/term/` | the caller's line: reads, writes and line editing, terminal detection, PETSCII |
| `internal/auth/` | the backends (users file, LDAP, SQL, system by PAM) and password changes |
| `internal/telnet/` | the telnet client of `mode = telnet` items |
| `authd/` | the auth socket's protocol and a client, for other programs (a BBS) to import |
| `pppd/` | pppd's `modemmenu.so` plugin, in C |
| `samples/` | modemmenu.conf, the users file, PAM and systemd samples |
| `freepbx/` | the FreePBX setup |
| `tools/confref/` | makes docs/reference.md from samples/modemmenu.conf.sample |
+2 -2
View File
@@ -1,6 +1,6 @@
# Configuration
[modemmenu.conf.sample](../modemmenu.conf.sample) has every option, and the
[modemmenu.conf.sample](../samples/modemmenu.conf.sample) has every option, and the
[configuration reference](reference.md) lists them all, section by section. In
short:
@@ -345,7 +345,7 @@ such an item, each login is recorded in `state_dir/callers` (the latest
## More items
The end of [modemmenu.conf.sample](../modemmenu.conf.sample) has items to
The end of [modemmenu.conf.sample](../samples/modemmenu.conf.sample) has items to
copy, each needing its program:
| item | program |
+2 -2
View File
@@ -1,9 +1,9 @@
<!-- Made by go run ./tools/confref from modemmenu.conf.sample: edit the sample, not this page. -->
<!-- Made by go run ./tools/confref from samples/modemmenu.conf.sample: edit the sample, not this page. -->
# Configuration reference
Every section and key of modemmenu.conf, from the comments in
[modemmenu.conf.sample](https://github.com/D-Modem/menu/blob/main/modemmenu.conf.sample).
[modemmenu.conf.sample](https://github.com/D-Modem/menu/blob/main/samples/modemmenu.conf.sample).
**Sample** is the value the sample sets (or shows, commented out);
[Configuration](configuration.md) explains the file and its sections in
full.
+1 -1
View File
@@ -76,7 +76,7 @@ the connection, which hangs up the call.
`-listen PATH` overrides `listen`. `SIGTERM` hangs up every session,
removes the socket and ends the server; a stale socket left by a server
that died is replaced at start, a live one is not.
[modemmenu.service.sample](../modemmenu.service.sample) runs it under
[modemmenu.service.sample](../samples/modemmenu.service.sample) runs it under
systemd, which also makes `/run/modemmenu`. Each connection is logged
with its peer's pid and uid.
+1 -1
View File
@@ -17,7 +17,7 @@
;
; modemmenu -check -config /etc/modemmenu/modemmenu.conf
;
; Every option is in modemmenu.conf.sample at the top of the repository.
; Every option is in samples/modemmenu.conf.sample in the repository.
[general]
; the journal (journalctl -t modemmenu), never the caller's line
+26 -23
View File
@@ -1,7 +1,10 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
// Package auth checks a user's password with modemmenu's backends (a
// users file, LDAP, SQL, the system's accounts by PAM), in turn, and
// changes it in the backend that holds the account.
package auth
import (
"context"
@@ -17,30 +20,30 @@ import (
"golang.org/x/crypto/bcrypt"
)
// errNoUser: the backend does not know the user (the next one is asked);
// errBadPassword: it knows the user, the password is wrong (no other
// ErrNoUser: the backend does not know the user (the next one is asked);
// ErrBadPassword: it knows the user, the password is wrong (no other
// backend is asked)
var (
errNoUser = errors.New("no such user")
errBadPassword = errors.New("wrong password")
ErrNoUser = errors.New("no such user")
ErrBadPassword = errors.New("wrong password")
)
type authenticator interface {
name() string
authenticate(ctx context.Context, user, password string) error
type Authenticator interface {
Name() string
Authenticate(ctx context.Context, user, password string) error
}
// a hash compared against when the user is unknown, so that the answer
// takes as long either way
var dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy password"), bcrypt.DefaultCost)
// checkPassword against a stored password, in the scheme its prefix or
// CheckPassword against a stored password, in the scheme its prefix or
// scheme (auto: by prefix) names:
//
// $2a$, $2b$, $2y$ ... bcrypt
// {SHA256}hex, {SHA512}hex (or base64), {SSHA256}/{SSHA512}base64(hash+salt)
// {PLAIN}text, or text with scheme = plain
func checkPassword(stored, password, scheme string) (bool, error) {
func CheckPassword(stored, password, scheme string) (bool, error) {
if scheme == "" || scheme == "auto" {
scheme = "plain"
switch {
@@ -108,32 +111,32 @@ func equalDigest(stored string, sum []byte) bool {
return false
}
// burn: the time a password check takes, for an unknown user
func burn(password string) {
// Burn: the time a password check takes, for an unknown user
func Burn(password string) {
bcrypt.CompareHashAndPassword(dummyHash, []byte(password))
}
// authenticate with each backend in turn: the name of the one that
// Authenticate with each backend in turn: the name of the one that
// accepted the user, or why none did
func authenticate(ctx context.Context, backends []authenticator, user, password string, logf func(string, ...any)) (string, error) {
func Authenticate(ctx context.Context, backends []Authenticator, user, password string, logf func(string, ...any)) (string, error) {
for _, a := range backends {
err := a.authenticate(ctx, user, password)
err := a.Authenticate(ctx, user, password)
switch {
case err == nil:
return a.name(), nil
case errors.Is(err, errBadPassword):
return a.Name(), nil
case errors.Is(err, ErrBadPassword):
return "", err
case errors.Is(err, errNoUser):
if err != errNoUser {
case errors.Is(err, ErrNoUser):
if err != ErrNoUser {
// known, but not one this backend lets in: why
logf("auth %s: %v", a.name(), err)
logf("auth %s: %v", a.Name(), err)
}
continue
default:
// a backend that is down does not stop the others
logf("auth %s: %v", a.name(), err)
logf("auth %s: %v", a.Name(), err)
}
}
burn(password)
return "", errNoUser
Burn(password)
return "", ErrNoUser
}
+119
View File
@@ -0,0 +1,119 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package auth
import (
"context"
"crypto/sha256"
"crypto/sha512"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"os"
"path/filepath"
"testing"
"github.com/D-Modem/menu/internal/config"
"golang.org/x/crypto/bcrypt"
)
// TestCheckPassword: each stored hash scheme accepts the right password
// and refuses others
func TestCheckPassword(t *testing.T) {
bc, _ := bcrypt.GenerateFromPassword([]byte("pw"), bcrypt.MinCost)
s256 := sha256.Sum256([]byte("pw"))
s512 := sha512.Sum512([]byte("pw"))
salted := sha256.Sum256([]byte("pwSALT"))
ssha := base64.StdEncoding.EncodeToString(append(salted[:], "SALT"...))
for _, c := range []struct {
stored, scheme string
ok bool
}{
{string(bc), "auto", true},
{string(bc), "bcrypt", true},
{"{SHA256}" + hex.EncodeToString(s256[:]), "auto", true},
{"{SHA256}" + base64.StdEncoding.EncodeToString(s256[:]), "auto", true},
{"{SHA512}" + hex.EncodeToString(s512[:]), "auto", true},
{"{SSHA256}" + ssha, "auto", true},
{"{PLAIN}pw", "auto", true},
{"{PLAIN}px", "auto", false},
{"pw", "plain", true},
{hex.EncodeToString(s256[:]), "sha256", true},
} {
for _, pw := range []string{"pw", "wrong"} {
ok, err := CheckPassword(c.stored, pw, c.scheme)
if err != nil {
t.Errorf("%s (%s): %v", c.stored, c.scheme, err)
}
if want := c.ok && pw == "pw"; ok != want {
t.Errorf("%s (%s) %s: %v, want %v", c.stored, c.scheme, pw, ok, want)
}
}
}
if _, err := CheckPassword("pw", "pw", "auto"); err == nil {
t.Error("a bare password with hash = auto: no error")
}
}
// TestBackends: the file and SQL backends, in order, accept and refuse
// as they should
func TestBackends(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
bc, _ := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
os.WriteFile(users, []byte("# users\nalice:"+string(bc)+":Alice\nbob:{PLAIN}a:b\n"), 0o600)
fa, err := NewFile(&config.Section{Name: "file", Vals: map[string]string{"path": users}})
if err != nil {
t.Fatal(err)
}
dbPath := filepath.Join(dir, "users.db")
db, err := sql.Open("sqlite", dbPath)
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`CREATE TABLE users (username TEXT, password TEXT);
INSERT INTO users VALUES ('carol', '{PLAIN}pw'), ('alice', '{PLAIN}other');`); err != nil {
t.Fatal(err)
}
db.Close()
sa, err := NewSQL(&config.Section{Name: "sql", Vals: map[string]string{
"driver": "sqlite", "dsn": dbPath,
"query": "SELECT password FROM users WHERE username = ?"}})
if err != nil {
t.Fatal(err)
}
sn, err := NewSQL(&config.Section{Name: "sql", Vals: map[string]string{
"driver": "sqlite", "dsn": dbPath, "args": "user password", "hash": "none",
"query": "SELECT 1 FROM users WHERE username = ? AND password = '{PLAIN}' || ?"}})
if err != nil {
t.Fatal(err)
}
backends := []Authenticator{fa, sa}
nolog := func(string, ...any) {}
for _, c := range []struct {
user, pw, auth string
err error
}{
{"alice", "secret", "file", nil},
{"alice", "other", "", ErrBadPassword}, // the file knows alice: not asked further
{"bob", "a:b", "file", nil},
{"carol", "pw", "sql", nil},
{"carol", "px", "", ErrBadPassword},
{"dave", "pw", "", ErrNoUser},
} {
auth, err := Authenticate(context.Background(), backends, c.user, c.pw, nolog)
if auth != c.auth || !errors.Is(err, c.err) && !(err == nil && c.err == nil) {
t.Errorf("%s/%s: %q %v, want %q %v", c.user, c.pw, auth, err, c.auth, c.err)
}
}
if err := sn.Authenticate(context.Background(), "carol", "pw"); err != nil {
t.Errorf("hash = none: %v", err)
}
if err := sn.Authenticate(context.Background(), "carol", "px"); !errors.Is(err, ErrNoUser) {
t.Errorf("hash = none, wrong password: %v", err)
}
}
+19 -17
View File
@@ -1,7 +1,7 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"bufio"
@@ -9,21 +9,23 @@ import (
"fmt"
"os"
"strings"
"github.com/D-Modem/menu/internal/config"
)
// fileAuth: a text file of user:password lines (the password hashed as
// File: a text file of user:password lines (the password hashed as
// checkPassword reads it, ! before it for a locked account; # comments),
// read at each login so that edits take effect at once
type fileAuth struct {
type File struct {
path string
scheme string
}
// newFileAuth: the [file] backend, its users file checked to exist
func newFileAuth(s *section) (authenticator, error) {
a := &fileAuth{
path: s.get("path", "/etc/asterisk/modemmenu.users"),
scheme: strings.ToLower(s.get("hash", "auto")),
// NewFile: the [file] backend, its users file checked to exist
func NewFile(s *config.Section) (Authenticator, error) {
a := &File{
path: s.Get("path", "/etc/asterisk/modemmenu.users"),
scheme: strings.ToLower(s.Get("hash", "auto")),
}
if _, err := os.Stat(a.path); err != nil {
return nil, fmt.Errorf("[file] path: %v", err)
@@ -31,12 +33,12 @@ func newFileAuth(s *section) (authenticator, error) {
return a, nil
}
// name: the backend's name, for {auth} and the log
func (a *fileAuth) name() string { return "file" }
// Name: the backend's Name, for {auth} and the log
func (a *File) Name() string { return "file" }
// authenticate: the user's line in the users file and its hash
// Authenticate: the user's line in the users file and its hash
// checked; a locked entry (!) is refused
func (a *fileAuth) authenticate(_ context.Context, user, password string) error {
func (a *File) Authenticate(_ context.Context, user, password string) error {
f, err := os.Open(a.path)
if err != nil {
return err
@@ -54,24 +56,24 @@ func (a *fileAuth) authenticate(_ context.Context, user, password string) error
}
// a locked account (signup's pending ones): !hash
if strings.HasPrefix(stored, "!") {
burn(password)
return fmt.Errorf("%w: %s is locked", errBadPassword, user)
Burn(password)
return fmt.Errorf("%w: %s is locked", ErrBadPassword, user)
}
// user:hash[:anything else, e.g. a full name]
if a.scheme != "plain" && !strings.HasPrefix(stored, "{") {
stored, _, _ = strings.Cut(stored, ":")
}
ok, err := checkPassword(stored, password, a.scheme)
ok, err := CheckPassword(stored, password, a.scheme)
if err != nil {
return fmt.Errorf("%s: user %s: %v", a.path, user, err)
}
if !ok {
return errBadPassword
return ErrBadPassword
}
return nil
}
if err := sc.Err(); err != nil {
return err
}
return errNoUser
return ErrNoUser
}
+46 -39
View File
@@ -1,7 +1,7 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"context"
@@ -15,13 +15,14 @@ import (
"time"
"unicode/utf16"
"github.com/D-Modem/menu/internal/config"
"github.com/go-ldap/ldap/v3"
)
// ldapAuth: a bind as the user, to bind_dn with {user} in it, or to the
// LDAP: a bind as the user, to bind_dn with {user} in it, or to the
// DN that search_filter finds under search_base (searched as
// search_bind_dn, anonymously if none)
type ldapAuth struct {
type LDAP struct {
url string
startTLS bool
tls *tls.Config
@@ -40,36 +41,36 @@ type ldapAuth struct {
passwordChange string
}
// newLDAPAuth: the [ldap] backend from its section, checked
func newLDAPAuth(s *section) (authenticator, error) {
// NewLDAP: the [ldap] backend from its section, checked
func NewLDAP(s *config.Section) (Authenticator, error) {
var err error
a := &ldapAuth{
url: s.get("url", "ldap://127.0.0.1:389"),
bindDN: s.get("bind_dn", ""),
base: s.get("search_base", ""),
filter: s.get("search_filter", "(uid={user})"),
searchDN: s.get("search_bind_dn", ""),
searchPass: s.get("search_bind_password", ""),
groupBase: s.get("group_base", ""),
groupFilter: s.get("group_filter",
a := &LDAP{
url: s.Get("url", "ldap://127.0.0.1:389"),
bindDN: s.Get("bind_dn", ""),
base: s.Get("search_base", ""),
filter: s.Get("search_filter", "(uid={user})"),
searchDN: s.Get("search_bind_dn", ""),
searchPass: s.Get("search_bind_password", ""),
groupBase: s.Get("group_base", ""),
groupFilter: s.Get("group_filter",
"(&(cn={group})(|(member={dn})(uniqueMember={dn})(memberUid={user})))"),
passwordChange: strings.ToLower(s.get("password_change", "exop")),
passwordChange: strings.ToLower(s.Get("password_change", "exop")),
}
if a.passwordChange != "exop" && a.passwordChange != "ad" {
return nil, fmt.Errorf("[ldap] password_change: %q (exop or ad)", a.passwordChange)
}
if a.startTLS, err = s.bool("starttls", false); err != nil {
if a.startTLS, err = s.Bool("starttls", false); err != nil {
return nil, err
}
if a.timeout, err = s.duration("timeout", 10*time.Second); err != nil {
if a.timeout, err = s.Duration("timeout", 10*time.Second); err != nil {
return nil, err
}
skip, err := s.bool("insecure_skip_verify", false)
skip, err := s.Bool("insecure_skip_verify", false)
if err != nil {
return nil, err
}
a.tls = &tls.Config{InsecureSkipVerify: skip}
if ca := s.get("ca_file", ""); ca != "" {
if ca := s.Get("ca_file", ""); ca != "" {
pem, err := os.ReadFile(ca)
if err != nil {
return nil, fmt.Errorf("[ldap] ca_file: %v", err)
@@ -89,11 +90,11 @@ func newLDAPAuth(s *section) (authenticator, error) {
return a, nil
}
// name: the backend's name, for {auth} and the log
func (a *ldapAuth) name() string { return "ldap" }
// Name: the backend's Name, for {auth} and the log
func (a *LDAP) Name() string { return "ldap" }
// authenticate: a bind as the user (found by search, or by bind_dn)
func (a *ldapAuth) authenticate(ctx context.Context, user, password string) error {
// Authenticate: a bind as the user (found by search, or by bind_dn)
func (a *LDAP) Authenticate(ctx context.Context, user, password string) error {
conn, _, err := a.bindUser(user, password)
if conn != nil {
conn.Close()
@@ -102,11 +103,11 @@ func (a *ldapAuth) authenticate(ctx context.Context, user, password string) erro
}
// bindUser: a connection bound as the user, and the user's DN
func (a *ldapAuth) bindUser(user, password string) (*ldap.Conn, string, error) {
func (a *LDAP) bindUser(user, password string) (*ldap.Conn, string, error) {
// an empty password would be an unauthenticated bind, which servers
// accept for any DN
if password == "" {
return nil, "", errBadPassword
return nil, "", ErrBadPassword
}
conn, err := a.dial()
if err != nil {
@@ -124,9 +125,9 @@ func (a *ldapAuth) bindUser(user, password string) (*ldap.Conn, string, error) {
if a.bindDN != "" {
// a direct bind cannot tell an unknown DN from a wrong
// password: let the other backends try
return nil, "", errNoUser
return nil, "", ErrNoUser
}
return nil, "", errBadPassword
return nil, "", ErrBadPassword
}
if err != nil {
conn.Close()
@@ -136,7 +137,7 @@ func (a *ldapAuth) bindUser(user, password string) (*ldap.Conn, string, error) {
}
// dial the server, with StartTLS if configured
func (a *ldapAuth) dial() (*ldap.Conn, error) {
func (a *LDAP) dial() (*ldap.Conn, error) {
d := &net.Dialer{Timeout: a.timeout}
host := a.url
if i := strings.Index(host, "://"); i >= 0 {
@@ -162,16 +163,16 @@ func (a *ldapAuth) dial() (*ldap.Conn, error) {
}
// userDN: the user's DN, from bind_dn or by the search
func (a *ldapAuth) userDN(conn *ldap.Conn, user string) (string, error) {
func (a *LDAP) userDN(conn *ldap.Conn, user string) (string, error) {
if a.bindDN != "" {
return expand(a.bindDN, map[string]string{"user": user}, ldap.EscapeDN), nil
return config.Expand(a.bindDN, map[string]string{"user": user}, ldap.EscapeDN), nil
}
if a.searchDN != "" {
if err := conn.Bind(a.searchDN, a.searchPass); err != nil {
return "", fmt.Errorf("bind %s: %v", a.searchDN, err)
}
}
filter := expand(a.filter, map[string]string{"user": user}, ldap.EscapeFilter)
filter := config.Expand(a.filter, map[string]string{"user": user}, ldap.EscapeFilter)
res, err := conn.Search(ldap.NewSearchRequest(a.base, ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases, 2, int(a.timeout/time.Second), false,
filter, []string{"dn"}, nil))
@@ -180,19 +181,25 @@ func (a *ldapAuth) userDN(conn *ldap.Conn, user string) (string, error) {
}
switch len(res.Entries) {
case 0:
return "", errNoUser
return "", ErrNoUser
case 1:
return res.Entries[0].DN, nil
}
return "", fmt.Errorf("search %s: more than one entry", filter)
}
// changePassword bound as the user, so that the server applies its own
// HasGroups: whether groups are looked up here (group_base is set)
func (a *LDAP) HasGroups() bool { return a.groupBase != "" }
// CanChangePassword: always (exop or ad)
func (a *LDAP) CanChangePassword() bool { return true }
// ChangePassword bound as the user, so that the server applies its own
// password policy: by the Password Modify extended operation (RFC 3062),
// or for Active Directory (password_change = ad, which does not have it)
// by replacing unicodePwd, the old value deleted and the new one added
// (which AD takes only over TLS: ldaps:// or starttls)
func (a *ldapAuth) changePassword(_ context.Context, _ *term, user, old, new string) error {
func (a *LDAP) ChangePassword(_ context.Context, _ Messenger, user, old, new string) error {
conn, dn, err := a.bindUser(user, old)
if err != nil {
return err
@@ -204,7 +211,7 @@ func (a *ldapAuth) changePassword(_ context.Context, _ *term, user, old, new str
_, err = conn.PasswordModify(ldap.NewPasswordModifyRequest(dn, old, new))
}
if err != nil {
return fmt.Errorf("%w: %v", errRefused, err)
return fmt.Errorf("%w: %v", ErrRefused, err)
}
return nil
}
@@ -230,13 +237,13 @@ func adPassword(pw string) string {
return string(b)
}
// memberOf: whether user is in group, an entry under group_base that
// MemberOf: whether user is in group, an entry under group_base that
// group_filter ({group}, the user's {dn} and {user}) finds; searched as
// search_bind_dn, else as the user (with their password), else
// anonymously. errNoUser without group_base: LDAP has no groups here.
func (a *ldapAuth) memberOf(user, password, group string) (bool, error) {
func (a *LDAP) MemberOf(user, password, group string) (bool, error) {
if a.groupBase == "" {
return false, errNoUser
return false, ErrNoUser
}
var conn *ldap.Conn
var dn string
@@ -255,7 +262,7 @@ func (a *ldapAuth) memberOf(user, password, group string) (bool, error) {
return false, err
}
defer conn.Close()
filter := expand(a.groupFilter, map[string]string{"group": group, "dn": dn, "user": user}, ldap.EscapeFilter)
filter := config.Expand(a.groupFilter, map[string]string{"group": group, "dn": dn, "user": user}, ldap.EscapeFilter)
res, err := conn.Search(ldap.NewSearchRequest(a.groupBase, ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases, 1, int(a.timeout/time.Second), false,
filter, []string{"dn"}, nil))
+12 -32
View File
@@ -1,16 +1,15 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/D-Modem/menu/internal/config"
"github.com/go-ldap/ldap/v3"
)
@@ -25,21 +24,21 @@ func TestLDAP(t *testing.T) {
{"url": url, "search_base": "ou=people,dc=example,dc=com"},
{"url": url, "bind_dn": "uid={user},ou=people,dc=example,dc=com"},
} {
a, err := newLDAPAuth(&section{name: "ldap", vals: vals})
a, err := NewLDAP(&config.Section{Name: "ldap", Vals: vals})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := a.authenticate(ctx, "lduser", "ldpass"); err != nil {
if err := a.Authenticate(ctx, "lduser", "ldpass"); err != nil {
t.Errorf("%v: right password: %v", vals, err)
}
if err := a.authenticate(ctx, "lduser", "wrong"); err == nil {
if err := a.Authenticate(ctx, "lduser", "wrong"); err == nil {
t.Errorf("%v: wrong password accepted", vals)
}
if err := a.authenticate(ctx, "lduser", ""); err == nil {
if err := a.Authenticate(ctx, "lduser", ""); err == nil {
t.Errorf("%v: empty password accepted", vals)
}
if err := a.authenticate(ctx, "nobody*)(uid=*", "ldpass"); !errors.Is(err, errNoUser) {
if err := a.Authenticate(ctx, "nobody*)(uid=*", "ldpass"); !errors.Is(err, ErrNoUser) {
t.Errorf("%v: unknown user: %v", vals, err)
}
}
@@ -74,38 +73,19 @@ func TestLDAPGroups(t *testing.T) {
{"url": url, "search_base": "ou=people,dc=example,dc=com", "group_base": "ou=groups,dc=example,dc=com"},
{"url": url, "bind_dn": "uid={user},ou=people,dc=example,dc=com", "group_base": "ou=groups,dc=example,dc=com"},
} {
a, err := newLDAPAuth(&section{name: "ldap", vals: vals})
a, err := NewLDAP(&config.Section{Name: "ldap", Vals: vals})
if err != nil {
t.Fatal(err)
}
la := a.(*ldapAuth)
la := a.(*LDAP)
for group, want := range map[string]bool{"sysops": true, "dialup": true, "other": false, "nothere": false} {
if in, err := la.memberOf("lduser", "ldpass", group); err != nil || in != want {
if in, err := la.MemberOf("lduser", "ldpass", group); err != nil || in != want {
t.Errorf("%v: lduser in %s: %v %v, want %v", vals, group, in, err, want)
}
}
}
a, _ := newLDAPAuth(&section{name: "ldap", vals: map[string]string{"url": url, "search_base": "ou=people,dc=example,dc=com"}})
if _, err := a.(*ldapAuth).memberOf("lduser", "ldpass", "sysops"); !errors.Is(err, errNoUser) {
a, _ := NewLDAP(&config.Section{Name: "ldap", Vals: map[string]string{"url": url, "search_base": "ou=people,dc=example,dc=com"}})
if _, err := a.(*LDAP).MemberOf("lduser", "ldpass", "sysops"); !errors.Is(err, ErrNoUser) {
t.Errorf("without group_base: %v", err)
}
// an item for sysops, through settings, a login by ldap
dir := t.TempDir()
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("[general]\nauth = ldap\n[ldap]\nurl = "+url+
"\nsearch_base = ou=people,dc=example,dc=com\ngroup_base = ou=groups,dc=example,dc=com\n"+
"[item ops]\ngroups = sysops\ncommand = true\n[item away]\ngroups = other\ncommand = true\n"), 0o600)
s, err := loadSettings(p)
if err != nil {
t.Fatal(err)
}
sess := &session{User: "lduser", Password: "ldpass", Auth: "ldap"}
var names []string
for _, it := range s.visible(sess) {
names = append(names, it.name)
}
if strings.Join(names, " ") != "ops" {
t.Errorf("lduser sees %v", names)
}
}
+2 -2
View File
@@ -3,7 +3,7 @@
//go:build !pam
package main
package auth
import "errors"
@@ -15,6 +15,6 @@ func pamAuthenticate(service, user, password string) error {
}
// pamChangePassword: without PAM, no password change
func pamChangePassword(service, user, old, new string, line *term) error {
func pamChangePassword(service, user, old, new string, line Messenger) error {
return errors.New("built without PAM")
}
+7 -7
View File
@@ -1,7 +1,7 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"errors"
@@ -9,12 +9,12 @@ import (
"strconv"
)
// lookupNSS: the account from the name service (getpwnam with cgo)
func lookupNSS(name string) (*account, error) {
// LookupNSS: the account from the name service (getpwnam with cgo)
func LookupNSS(name string) (*Account, error) {
u, err := user.Lookup(name)
var unknown user.UnknownUserError
if errors.As(err, &unknown) {
return nil, errNoUser
return nil, ErrNoUser
}
if err != nil {
return nil, err
@@ -27,12 +27,12 @@ func lookupNSS(name string) (*account, error) {
if err != nil {
return nil, err
}
return &account{name: u.Username, uid: uid, gid: gid}, nil
return &Account{name: u.Username, uid: uid, gid: gid}, nil
}
// inGroupsNSS: whether the account is in any of the groups, by the
// InGroupsNSS: whether the account is in any of the groups, by the
// name service (/etc/group, LDAP via NSS...)
func inGroupsNSS(acct *account, groups []string) (bool, error) {
func InGroupsNSS(acct *Account, groups []string) (bool, error) {
u, err := user.Lookup(acct.name)
if err != nil {
return false, err
+14 -7
View File
@@ -3,7 +3,7 @@
//go:build pam
package main
package auth
import (
"errors"
@@ -36,17 +36,17 @@ func pamAuthenticate(service, user, password string) error {
t.SetItem(pam.Tty, "modem")
if err := t.Authenticate(pam.DisallowNullAuthtok); err != nil {
if errors.Is(err, pam.ErrUserUnknown) {
return errNoUser
return ErrNoUser
}
if errors.Is(err, pam.ErrAuth) || errors.Is(err, pam.ErrPermDenied) ||
errors.Is(err, pam.ErrMaxtries) || errors.Is(err, pam.ErrCredInsufficient) {
return errBadPassword
return ErrBadPassword
}
return fmt.Errorf("pam %s: %v", service, err)
}
if err := t.AcctMgmt(pam.DisallowNullAuthtok); err != nil {
// expired, locked, outside its hours...: refused, and why logged
return fmt.Errorf("%w: pam account %s: %v", errBadPassword, user, err)
return fmt.Errorf("%w: pam account %s: %v", ErrBadPassword, user, err)
}
return nil
}
@@ -55,7 +55,7 @@ func pamAuthenticate(service, user, password string) error {
// hidden prompts get the current password (asked for "current" or "old")
// or the new one; what it has to say goes to the caller (a quality
// module's reasons).
func pamChangePassword(service, user, old, new string, line *term) error {
func pamChangePassword(service, user, old, new string, line Messenger) error {
t, err := pam.StartFunc(service, user, func(s pam.Style, msg string) (string, error) {
switch s {
case pam.PromptEchoOff:
@@ -68,7 +68,7 @@ func pamChangePassword(service, user, old, new string, line *term) error {
return user, nil
case pam.ErrorMsg, pam.TextInfo:
if line != nil && msg != "" {
line.write(crlf(strings.TrimRight(msg, "\n")) + "\r\n")
line.Write(pamCRLF(strings.TrimRight(msg, "\n")) + "\r\n")
}
return "", nil
}
@@ -82,9 +82,16 @@ func pamChangePassword(service, user, old, new string, line *term) error {
if err := t.ChangeAuthTok(0); err != nil {
if errors.Is(err, pam.ErrAuthtok) || errors.Is(err, pam.ErrPermDenied) ||
errors.Is(err, pam.ErrAuthtokRecovery) || errors.Is(err, pam.ErrAuth) {
return fmt.Errorf("%w: pam %s: %v", errRefused, service, err)
return fmt.Errorf("%w: pam %s: %v", ErrRefused, service, err)
}
return fmt.Errorf("pam %s: %v", service, err)
}
return nil
}
// pamCRLF: a PAM module's message with its line ends as the terminal
// wants them
func pamCRLF(s string) string {
s = strings.ReplaceAll(s, "\r\n", "\n")
return strings.ReplaceAll(s, "\n", "\r\n")
}
+14 -12
View File
@@ -3,7 +3,7 @@
//go:build pam
package main
package auth
import (
"context"
@@ -11,6 +11,8 @@ import (
"os"
"strings"
"testing"
"github.com/D-Modem/menu/internal/config"
)
// MODEMMENU_TEST_PAM=user:password of an account the PAM service
@@ -21,21 +23,21 @@ func TestPAM(t *testing.T) {
t.Skip("MODEMMENU_TEST_PAM is not set")
}
user, pw, _ := strings.Cut(cred, ":")
a, err := newSystemAuth(&section{name: "system", vals: map[string]string{}})
a, err := NewSystem(&config.Section{Name: "system", Vals: map[string]string{}})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := a.authenticate(ctx, user, pw); err != nil {
if err := a.Authenticate(ctx, user, pw); err != nil {
t.Errorf("right password: %v", err)
}
if err := a.authenticate(ctx, user, pw+"x"); !errors.Is(err, errBadPassword) {
if err := a.Authenticate(ctx, user, pw+"x"); !errors.Is(err, ErrBadPassword) {
t.Errorf("wrong password: %v", err)
}
if err := a.authenticate(ctx, "no-such-user-here", pw); !errors.Is(err, errNoUser) {
if err := a.Authenticate(ctx, "no-such-user-here", pw); !errors.Is(err, ErrNoUser) {
t.Errorf("unknown user: %v", err)
}
if err := a.authenticate(ctx, "root", pw); !errors.Is(err, errNoUser) {
if err := a.Authenticate(ctx, "root", pw); !errors.Is(err, ErrNoUser) {
t.Errorf("root: %v", err)
}
}
@@ -48,22 +50,22 @@ func TestPAMChangePassword(t *testing.T) {
t.Skip("MODEMMENU_TEST_PAM is not set")
}
user, pw, _ := strings.Cut(cred, ":")
a, err := newSystemAuth(&section{name: "system", vals: map[string]string{}})
a, err := NewSystem(&config.Section{Name: "system", Vals: map[string]string{}})
if err != nil {
t.Fatal(err)
}
sa := a.(*systemAuth)
sa := a.(*System)
ctx := context.Background()
if err := sa.changePassword(ctx, nil, user, pw, pw+"-2"); err != nil {
if err := sa.ChangePassword(ctx, nil, user, pw, pw+"-2"); err != nil {
t.Fatal(err)
}
if err := a.authenticate(ctx, user, pw+"-2"); err != nil {
if err := a.Authenticate(ctx, user, pw+"-2"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.authenticate(ctx, user, pw); err == nil {
if err := a.Authenticate(ctx, user, pw); err == nil {
t.Error("the old password still works")
}
if err := sa.changePassword(ctx, nil, user, pw+"-2", pw); err != nil {
if err := sa.ChangePassword(ctx, nil, user, pw+"-2", pw); err != nil {
t.Errorf("back: %v", err)
}
}
+143
View File
@@ -0,0 +1,143 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package auth
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"golang.org/x/crypto/bcrypt"
"golang.org/x/sys/unix"
)
// ErrRefused: the backend did not take the new password (its policy)
var ErrRefused = errors.New("new password refused")
// PasswordChanger: a backend that can change a user's password; old has
// been checked already. t is the caller's line, for a backend (PAM) that
// has something to tell them.
type PasswordChanger interface {
ChangePassword(ctx context.Context, t Messenger, user, old, new string) error
// CanChangePassword: whether this backend is set up to (sql: an
// update_query)
CanChangePassword() bool
}
// Messenger: the caller's line, for what a backend has to tell them
type Messenger interface {
Write(s string) error
}
func (a *File) CanChangePassword() bool { return true }
func (a *SQL) CanChangePassword() bool { return a.updateQuery != "" }
func (a *System) CanChangePassword() bool { return true }
// ChangePassword in the users file: the user's line rewritten in place
// (other lines as they are) under the lock signups take, the password as
// bcrypt (as text with hash = plain), a note after it kept
func (a *File) ChangePassword(_ context.Context, _ Messenger, user, old, new string) error {
f, err := os.OpenFile(a.path, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
st, err := f.Stat()
if err != nil {
return err
}
b := make([]byte, st.Size())
if _, err := f.ReadAt(b, 0); err != nil && err != io.EOF {
return err
}
stored := ""
if a.scheme == "plain" {
stored = new
} else {
h, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost)
if err != nil {
return err
}
stored = string(h)
}
lines := strings.Split(string(b), "\n")
found := false
for i, line := range lines {
t := strings.TrimSpace(line)
if t == "" || t[0] == '#' {
continue
}
name, rest, ok := strings.Cut(t, ":")
if !ok || name != user {
continue
}
// what follows the hash: user:hash:note (not after {SCHEME}text
// or with hash = plain, where the rest is the password)
note := ""
if a.scheme != "plain" && !strings.HasPrefix(rest, "{") {
if _, n, ok := strings.Cut(rest, ":"); ok {
note = ":" + n
}
}
lines[i] = name + ":" + stored + note
found = true
break
}
if !found {
return ErrNoUser
}
out := []byte(strings.Join(lines, "\n"))
if _, err := f.WriteAt(out, 0); err != nil {
return err
}
if err := f.Truncate(int64(len(out))); err != nil {
return err
}
return f.Sync()
}
// ChangePassword in the database: update_query with update_args, the
// password as update_hash says
func (a *SQL) ChangePassword(ctx context.Context, _ Messenger, user, old, new string) error {
stored := new
if a.updateHash == "bcrypt" {
h, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost)
if err != nil {
return err
}
stored = string(h)
}
args := make([]any, len(a.updateArgs))
for i, arg := range a.updateArgs {
switch arg {
case "user":
args[i] = user
case "password":
args[i] = stored
case "old_password":
args[i] = old
}
}
ctx, cancel := context.WithTimeout(ctx, a.timeout)
defer cancel()
res, err := a.db.ExecContext(ctx, a.updateQuery, args...)
if err != nil {
return err
}
if n, err := res.RowsAffected(); err == nil && n != 1 {
return fmt.Errorf("update_query changed %d rows, not 1", n)
}
return nil
}
// ChangePassword by PAM: the service's password stack
func (a *System) ChangePassword(_ context.Context, t Messenger, user, old, new string) error {
return pamChangePassword(a.service, user, old, new, t)
}
+130
View File
@@ -0,0 +1,130 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package auth
import (
"context"
"database/sql"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/D-Modem/menu/internal/config"
)
// TestFileChangePassword: the users file's line of the user changed,
// the others and the notes after the hash kept
func TestFileChangePassword(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("# users\nalice:{PLAIN}old-pw\nbob:{PLAIN}bob-pw\ncarol:$2a$04$abcdefghijklmnopqrstuuJ8Jq7QF7mHNXgNnrBX3/7uJpH9fC2T6:signup 2026-10-12 5551234\n"), 0o600)
fa, err := NewFile(&config.Section{Name: "file", Vals: map[string]string{"path": users}})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := fa.(*File).ChangePassword(ctx, nil, "alice", "old-pw", "new-pw-1"); err != nil {
t.Fatal(err)
}
if err := fa.Authenticate(ctx, "alice", "new-pw-1"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := fa.Authenticate(ctx, "alice", "old-pw"); !errors.Is(err, ErrBadPassword) {
t.Errorf("the old password: %v", err)
}
if err := fa.Authenticate(ctx, "bob", "bob-pw"); err != nil {
t.Errorf("bob, untouched: %v", err)
}
// a note after the hash stays
if err := fa.(*File).ChangePassword(ctx, nil, "carol", "", "carol-new"); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(users)
lines := strings.Split(string(b), "\n")
if len(lines) != 5 || lines[0] != "# users" || !strings.HasPrefix(lines[1], "alice:$2a$") ||
lines[2] != "bob:{PLAIN}bob-pw" || !strings.HasSuffix(lines[3], ":signup 2026-10-12 5551234") || lines[4] != "" {
t.Errorf("users file:\n%s", b)
}
if err := fa.(*File).ChangePassword(ctx, nil, "dave", "", "x"); !errors.Is(err, ErrNoUser) {
t.Errorf("dave: %v", err)
}
// hash = plain: the password as text
os.WriteFile(users, []byte("erin:old:x\n"), 0o600)
fp, _ := NewFile(&config.Section{Name: "file", Vals: map[string]string{"path": users, "hash": "plain"}})
fp.(*File).ChangePassword(ctx, nil, "erin", "old:x", "new")
if b, _ := os.ReadFile(users); string(b) != "erin:new\n" {
t.Errorf("plain: %q", b)
}
}
// TestSQLChangePassword: update_query changes the user's row only
func TestSQLChangePassword(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "users.db")
db, _ := sql.Open("sqlite", dbPath)
if _, err := db.Exec(`CREATE TABLE users (username TEXT, password TEXT);
INSERT INTO users VALUES ('carol', '{PLAIN}pw'), ('dave', '{PLAIN}pw');`); err != nil {
t.Fatal(err)
}
db.Close()
vals := map[string]string{"driver": "sqlite", "dsn": dbPath,
"query": "SELECT password FROM users WHERE username = ?"}
a, err := NewSQL(&config.Section{Name: "sql", Vals: vals})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
vals["update_query"] = "UPDATE users SET password = ? WHERE username = ?"
a, _ = NewSQL(&config.Section{Name: "sql", Vals: vals})
if err := a.(*SQL).ChangePassword(ctx, nil, "carol", "pw", "carol-new"); err != nil {
t.Fatal(err)
}
if err := a.Authenticate(ctx, "carol", "carol-new"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.Authenticate(ctx, "dave", "pw"); err != nil {
t.Errorf("dave, untouched: %v", err)
}
if err := a.(*SQL).ChangePassword(ctx, nil, "nobody", "pw", "x"); err == nil {
t.Error("no row: no error")
}
vals["update_args"] = "user nonsense"
if _, err := NewSQL(&config.Section{Name: "sql", Vals: vals}); err == nil {
t.Error("update_args nonsense: no error")
}
}
// MODEMMENU_TEST_LDAP (see ldap_test.go), the server letting users write
// their own userPassword: lduser's password changed and back
func TestLDAPChangePassword(t *testing.T) {
url := os.Getenv("MODEMMENU_TEST_LDAP")
if url == "" {
t.Skip("MODEMMENU_TEST_LDAP is not set")
}
a, err := NewLDAP(&config.Section{Name: "ldap", Vals: map[string]string{
"url": url, "search_base": "ou=people,dc=example,dc=com"}})
if err != nil {
t.Fatal(err)
}
la := a.(*LDAP)
ctx := context.Background()
if err := la.ChangePassword(ctx, nil, "lduser", "wrong", "x"); !errors.Is(err, ErrBadPassword) {
t.Errorf("a wrong current password: %v", err)
}
if err := la.ChangePassword(ctx, nil, "lduser", "ldpass", "ldpass-2"); err != nil {
t.Fatal(err)
}
if err := a.Authenticate(ctx, "lduser", "ldpass-2"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.Authenticate(ctx, "lduser", "ldpass"); err == nil {
t.Error("the old password still works")
}
if err := la.ChangePassword(ctx, nil, "lduser", "ldpass-2", "ldpass"); err != nil {
t.Errorf("back: %v", err)
}
}
+24 -23
View File
@@ -1,7 +1,7 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"context"
@@ -11,15 +11,16 @@ import (
"strings"
"time"
"github.com/D-Modem/menu/internal/config"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "modernc.org/sqlite"
)
// sqlAuth: query, with the user (and the password, for args = user
// SQL: query, with the user (and the password, for args = user
// password) as its arguments, returns the stored password of the user
// (checked as hash says), or with hash = none any row for a valid login
type sqlAuth struct {
type SQL struct {
driver string
dsn string
query string
@@ -43,17 +44,17 @@ var sqlDrivers = map[string]string{
"sqlite3": "sqlite",
}
// newSQLAuth: the [sql] backend, its database opened (not yet
// NewSQL: the [sql] backend, its database opened (not yet
// connected); args names the query's parameters (user, password)
func newSQLAuth(s *section) (authenticator, error) {
func NewSQL(s *config.Section) (Authenticator, error) {
var err error
a := &sqlAuth{
dsn: s.get("dsn", ""),
query: s.get("query", ""),
args: fields(strings.ToLower(s.get("args", "user"))),
scheme: strings.ToLower(s.get("hash", "auto")),
a := &SQL{
dsn: s.Get("dsn", ""),
query: s.Get("query", ""),
args: config.Fields(strings.ToLower(s.Get("args", "user"))),
scheme: strings.ToLower(s.Get("hash", "auto")),
}
drv := strings.ToLower(s.get("driver", ""))
drv := strings.ToLower(s.Get("driver", ""))
if a.driver = sqlDrivers[drv]; a.driver == "" {
return nil, fmt.Errorf("[sql] driver: %q (mysql, postgres or sqlite)", drv)
}
@@ -65,12 +66,12 @@ func newSQLAuth(s *section) (authenticator, error) {
return nil, fmt.Errorf("[sql] args: %q (user, password)", arg)
}
}
if a.timeout, err = s.duration("timeout", 10*time.Second); err != nil {
if a.timeout, err = s.Duration("timeout", 10*time.Second); err != nil {
return nil, err
}
a.updateQuery = s.get("update_query", "")
a.updateArgs = fields(strings.ToLower(s.get("update_args", "password user")))
a.updateHash = strings.ToLower(s.get("update_hash", "bcrypt"))
a.updateQuery = s.Get("update_query", "")
a.updateArgs = config.Fields(strings.ToLower(s.Get("update_args", "password user")))
a.updateHash = strings.ToLower(s.Get("update_hash", "bcrypt"))
for _, arg := range a.updateArgs {
if arg != "user" && arg != "password" && arg != "old_password" {
return nil, fmt.Errorf("[sql] update_args: %q (user, password, old_password)", arg)
@@ -88,12 +89,12 @@ func newSQLAuth(s *section) (authenticator, error) {
return a, nil
}
// name: the backend's name, for {auth} and the log
func (a *sqlAuth) name() string { return "sql" }
// Name: the backend's Name, for {auth} and the log
func (a *SQL) Name() string { return "sql" }
// authenticate: the query's row for the user, its first column the
// Authenticate: the query's row for the user, its first column the
// stored hash checked against the password (hash = none: a row is enough)
func (a *sqlAuth) authenticate(ctx context.Context, user, password string) error {
func (a *SQL) Authenticate(ctx context.Context, user, password string) error {
ctx, cancel := context.WithTimeout(ctx, a.timeout)
defer cancel()
args := make([]any, len(a.args))
@@ -113,7 +114,7 @@ func (a *sqlAuth) authenticate(ctx context.Context, user, password string) error
err = row.Scan(&stored)
}
if errors.Is(err, sql.ErrNoRows) {
return errNoUser
return ErrNoUser
}
if err != nil {
return err
@@ -122,14 +123,14 @@ func (a *sqlAuth) authenticate(ctx context.Context, user, password string) error
return nil
}
if !stored.Valid {
return errBadPassword
return ErrBadPassword
}
ok, err := checkPassword(stored.String, password, a.scheme)
ok, err := CheckPassword(stored.String, password, a.scheme)
if err != nil {
return fmt.Errorf("user %s: %v", user, err)
}
if !ok {
return errBadPassword
return ErrBadPassword
}
return nil
}
+26 -24
View File
@@ -1,50 +1,52 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"context"
"fmt"
"strings"
"github.com/D-Modem/menu/internal/config"
)
// systemAuth: the accounts of the system, by PAM: the auth and account
// System: the accounts of the system, by PAM: the auth and account
// stacks of pam_service, in a build with -tags pam. Only accounts with a
// uid of at least min_uid (not root, unless allow_root), in one of groups
// if it is set, may log in.
type systemAuth struct {
type System struct {
service string
minUID int
allowRoot bool
groups []string
// the name service and PAM, replaced in tests
lookup func(string) (*account, error)
inGroups func(*account, []string) (bool, error)
lookup func(string) (*Account, error)
inGroups func(*Account, []string) (bool, error)
pam func(service, user, password string) error
}
// account: a user of the name service
type account struct {
// Account: a user of the name service
type Account struct {
name string
uid, gid int
}
// newSystemAuth: the [system] backend (PAM and the name service);
// NewSystem: the [system] backend (PAM and the name service);
// an error when this modemmenu is built without PAM
func newSystemAuth(s *section) (authenticator, error) {
func NewSystem(s *config.Section) (Authenticator, error) {
var err error
a := &systemAuth{
service: s.get("pam_service", "modemmenu"),
groups: fields(s.get("groups", "")),
lookup: lookupNSS,
inGroups: inGroupsNSS,
a := &System{
service: s.Get("pam_service", "modemmenu"),
groups: config.Fields(s.Get("groups", "")),
lookup: LookupNSS,
inGroups: InGroupsNSS,
pam: pamAuthenticate,
}
if a.minUID, err = s.int("min_uid", 1000); err != nil {
if a.minUID, err = s.Int("min_uid", 1000); err != nil {
return nil, err
}
if a.allowRoot, err = s.bool("allow_root", false); err != nil {
if a.allowRoot, err = s.Bool("allow_root", false); err != nil {
return nil, err
}
if !havePAM {
@@ -53,12 +55,12 @@ func newSystemAuth(s *section) (authenticator, error) {
return a, nil
}
// name: the backend's name, for {auth} and the log
func (a *systemAuth) name() string { return "system" }
// Name: the backend's Name, for {auth} and the log
func (a *System) Name() string { return "system" }
// authenticate: the account looked up, min_uid, root and groups
// Authenticate: the account looked up, min_uid, root and groups
// checked, then the password by PAM
func (a *systemAuth) authenticate(_ context.Context, user, password string) error {
func (a *System) Authenticate(_ context.Context, user, password string) error {
acct, err := a.lookup(user)
if err != nil {
return err
@@ -71,12 +73,12 @@ func (a *systemAuth) authenticate(_ context.Context, user, password string) erro
// allowed: an account that may dial in. The others are not this
// backend's users: the next one is asked
func (a *systemAuth) allowed(acct *account) error {
func (a *System) allowed(acct *Account) error {
if acct.uid == 0 && !a.allowRoot {
return fmt.Errorf("%w: %s is root", errNoUser, acct.name)
return fmt.Errorf("%w: %s is root", ErrNoUser, acct.name)
}
if acct.uid != 0 && acct.uid < a.minUID {
return fmt.Errorf("%w: %s has uid %d < min_uid %d", errNoUser, acct.name, acct.uid, a.minUID)
return fmt.Errorf("%w: %s has uid %d < min_uid %d", ErrNoUser, acct.name, acct.uid, a.minUID)
}
if len(a.groups) == 0 {
return nil
@@ -86,7 +88,7 @@ func (a *systemAuth) allowed(acct *account) error {
return err
}
if !in {
return fmt.Errorf("%w: %s is in none of %s", errNoUser, acct.name, strings.Join(a.groups, ", "))
return fmt.Errorf("%w: %s is in none of %s", ErrNoUser, acct.name, strings.Join(a.groups, ", "))
}
return nil
}
@@ -1,36 +1,38 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
package auth
import (
"context"
"errors"
"testing"
"github.com/D-Modem/menu/internal/config"
)
// the account rules of the system backend, PAM replaced by a stub
func TestSystemRules(t *testing.T) {
accounts := map[string]*account{
accounts := map[string]*Account{
"root": {name: "root", uid: 0},
"daemon": {name: "daemon", uid: 1, gid: 1},
"alice": {name: "alice", uid: 1000, gid: 1000},
"bob": {name: "bob", uid: 1001, gid: 20},
}
dialup := map[string]bool{"bob": true}
newAuth := func(minUID int, root bool, groups []string) *systemAuth {
return &systemAuth{
newAuth := func(minUID int, root bool, groups []string) *System {
return &System{
service: "modemmenu", minUID: minUID, allowRoot: root, groups: groups,
lookup: func(u string) (*account, error) {
lookup: func(u string) (*Account, error) {
if a, ok := accounts[u]; ok {
return a, nil
}
return nil, errNoUser
return nil, ErrNoUser
},
inGroups: func(a *account, g []string) (bool, error) { return dialup[a.name], nil },
inGroups: func(a *Account, g []string) (bool, error) { return dialup[a.name], nil },
pam: func(service, user, password string) error {
if password != "pw" {
return errBadPassword
return ErrBadPassword
}
return nil
},
@@ -38,28 +40,28 @@ func TestSystemRules(t *testing.T) {
}
ctx := context.Background()
for _, c := range []struct {
a *systemAuth
a *System
user, pw string
want error
}{
{newAuth(1000, false, nil), "alice", "pw", nil},
{newAuth(1000, false, nil), "alice", "px", errBadPassword},
{newAuth(1000, false, nil), "nobody", "pw", errNoUser},
{newAuth(1000, false, nil), "daemon", "pw", errNoUser},
{newAuth(1000, false, nil), "root", "pw", errNoUser},
{newAuth(1000, false, nil), "alice", "px", ErrBadPassword},
{newAuth(1000, false, nil), "nobody", "pw", ErrNoUser},
{newAuth(1000, false, nil), "daemon", "pw", ErrNoUser},
{newAuth(1000, false, nil), "root", "pw", ErrNoUser},
{newAuth(1000, true, nil), "root", "pw", nil},
{newAuth(1, false, nil), "daemon", "pw", nil},
{newAuth(1000, false, []string{"dialup"}), "alice", "pw", errNoUser},
{newAuth(1000, false, []string{"dialup"}), "alice", "pw", ErrNoUser},
{newAuth(1000, false, []string{"dialup"}), "bob", "pw", nil},
} {
err := c.a.authenticate(ctx, c.user, c.pw)
err := c.a.Authenticate(ctx, c.user, c.pw)
if c.want == nil && err != nil || c.want != nil && !errors.Is(err, c.want) {
t.Errorf("%s/%s (min_uid %d, root %v, groups %v): %v, want %v",
c.user, c.pw, c.a.minUID, c.a.allowRoot, c.a.groups, err, c.want)
}
}
if !havePAM {
if _, err := newSystemAuth(&section{name: "system", vals: map[string]string{}}); err == nil {
if _, err := NewSystem(&config.Section{Name: "system", Vals: map[string]string{}}); err == nil {
t.Error("auth = system without PAM: no error")
}
}
+63 -60
View File
@@ -1,7 +1,10 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
// Package config reads modemmenu.conf: [sections] of key = value, the
// values as strings, yes/no, numbers and durations, and the {name}
// templates of its strings.
package config
import (
"bufio"
@@ -13,31 +16,31 @@ import (
"time"
)
// section is one [name] of the configuration, its keys in file order
type section struct {
name string
keys []string
vals map[string]string
line map[string]int
// Section is one [name] of the configuration, its keys in file order
type Section struct {
Name string
Keys []string
Vals map[string]string
Line map[string]int
}
// get: key's value, or def when it is not set
func (s *section) get(key, def string) string {
if v, ok := s.vals[key]; ok {
// Get: key's value, or def when it is not set
func (s *Section) Get(key, def string) string {
if v, ok := s.Vals[key]; ok {
return v
}
return def
}
// has: whether key is set
func (s *section) has(key string) bool {
_, ok := s.vals[key]
// Has: whether key is set
func (s *Section) Has(key string) bool {
_, ok := s.Vals[key]
return ok
}
// bool: key as yes/no (true/false, on/off, 1/0), or def
func (s *section) bool(key string, def bool) (bool, error) {
v, ok := s.vals[key]
// Bool: key as yes/no (true/false, on/off, 1/0), or def
func (s *Section) Bool(key string, def bool) (bool, error) {
v, ok := s.Vals[key]
if !ok {
return def, nil
}
@@ -47,25 +50,25 @@ func (s *section) bool(key string, def bool) (bool, error) {
case "no", "false", "off", "0":
return false, nil
}
return def, fmt.Errorf("[%s] %s: %q is not yes or no", s.name, key, v)
return def, fmt.Errorf("[%s] %s: %q is not yes or no", s.Name, key, v)
}
// int: key as a number, or def
func (s *section) int(key string, def int) (int, error) {
v, ok := s.vals[key]
// Int: key as a number, or def
func (s *Section) Int(key string, def int) (int, error) {
v, ok := s.Vals[key]
if !ok {
return def, nil
}
n, err := strconv.Atoi(v)
if err != nil {
return def, fmt.Errorf("[%s] %s: %q is not a number", s.name, key, v)
return def, fmt.Errorf("[%s] %s: %q is not a number", s.Name, key, v)
}
return n, nil
}
// seconds: a plain number of seconds, or a Go duration (90s, 5m)
func (s *section) duration(key string, def time.Duration) (time.Duration, error) {
v, ok := s.vals[key]
// seconds: a plain number of seconds, or a Go Duration (90s, 5m)
func (s *Section) Duration(key string, def time.Duration) (time.Duration, error) {
v, ok := s.Vals[key]
if !ok {
return def, nil
}
@@ -74,37 +77,37 @@ func (s *section) duration(key string, def time.Duration) (time.Duration, error)
}
d, err := time.ParseDuration(v)
if err != nil {
return def, fmt.Errorf("[%s] %s: %q is not a duration", s.name, key, v)
return def, fmt.Errorf("[%s] %s: %q is not a duration", s.Name, key, v)
}
return d, nil
}
// ini is a dmodem.conf-style file: [sections] of key = value, ';' or '#'
// File is a dmodem.conf-style file: [sections] of key = value, ';' or '#'
// comments on lines of their own or after a value (following a space)
type ini struct {
path string
sections []*section
byName map[string]*section
type File struct {
Path string
Sections []*Section
ByName map[string]*Section
}
// section: the section by name; an empty one if there is none
func (c *ini) section(name string) *section {
if s, ok := c.byName[name]; ok {
// Section: the Section by name; an empty one if there is none
func (c *File) Section(name string) *Section {
if s, ok := c.ByName[name]; ok {
return s
}
return &section{name: name, vals: map[string]string{}, line: map[string]int{}}
return &Section{Name: name, Vals: map[string]string{}, Line: map[string]int{}}
}
// parseINI: the configuration file's sections and keys (keys in lower
// Parse: the configuration file's sections and keys (keys in lower
// case, inline comments and surrounding quotes taken off values)
func parseINI(path string) (*ini, error) {
func Parse(path string) (*File, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
c := &ini{path: path, byName: map[string]*section{}}
var cur *section
c := &File{Path: path, ByName: map[string]*Section{}}
var cur *Section
sc := bufio.NewScanner(f)
for n := 1; sc.Scan(); n++ {
line := strings.TrimSpace(sc.Text())
@@ -117,13 +120,13 @@ func parseINI(path string) (*ini, error) {
return nil, fmt.Errorf("%s:%d: no ] in %q", path, n, line)
}
name := strings.Join(strings.Fields(line[1:end]), " ")
if s, ok := c.byName[name]; ok {
if s, ok := c.ByName[name]; ok {
cur = s
continue
}
cur = &section{name: name, vals: map[string]string{}, line: map[string]int{}}
c.sections = append(c.sections, cur)
c.byName[name] = cur
cur = &Section{Name: name, Vals: map[string]string{}, Line: map[string]int{}}
c.Sections = append(c.Sections, cur)
c.ByName[name] = cur
continue
}
eq := strings.IndexByte(line, '=')
@@ -134,23 +137,23 @@ func parseINI(path string) (*ini, error) {
return nil, fmt.Errorf("%s:%d: %q is before any [section]", path, n, line)
}
key := strings.ToLower(strings.TrimSpace(line[:eq]))
val := strings.TrimSpace(stripComment(line[eq+1:]))
val := strings.TrimSpace(StripComment(line[eq+1:]))
if len(val) >= 2 && val[0] == '"' && val[len(val)-1] == '"' {
val = val[1 : len(val)-1]
}
if _, ok := cur.vals[key]; !ok {
cur.keys = append(cur.keys, key)
if _, ok := cur.Vals[key]; !ok {
cur.Keys = append(cur.Keys, key)
}
cur.vals[key] = val
cur.line[key] = n
cur.Vals[key] = val
cur.Line[key] = n
}
return c, sc.Err()
}
// stripComment: a value without the comment after it: from a ; or # that
// StripComment: a value without the comment after it: from a ; or # that
// follows a space or tab, outside "quotes". \; and \# are the characters
// themselves.
func stripComment(v string) string {
func StripComment(v string) string {
var b strings.Builder
quoted := false
for i := 0; i < len(v); i++ {
@@ -170,22 +173,22 @@ func stripComment(v string) string {
return b.String()
}
// durations: a list of durations ("5m 1m", "300, 60"), the longest
// Durations: a list of Durations ("5m 1m", "300, 60"), the longest
// first, each once; "0" or "none" for none
func (s *section) durations(key, def string) ([]time.Duration, error) {
v := strings.TrimSpace(s.get(key, def))
func (s *Section) Durations(key, def string) ([]time.Duration, error) {
v := strings.TrimSpace(s.Get(key, def))
if v == "" || v == "0" || strings.EqualFold(v, "none") {
return nil, nil
}
var out []time.Duration
for _, f := range fields(v) {
one := &section{name: s.name, vals: map[string]string{key: f}}
d, err := one.duration(key, 0)
for _, f := range Fields(v) {
one := &Section{Name: s.Name, Vals: map[string]string{key: f}}
d, err := one.Duration(key, 0)
if err != nil {
return nil, err
}
if d <= 0 {
return nil, fmt.Errorf("[%s] %s: %q is not a time before the limit", s.name, key, f)
return nil, fmt.Errorf("[%s] %s: %q is not a time before the limit", s.Name, key, f)
}
dup := false
for _, o := range out {
@@ -199,9 +202,9 @@ func (s *section) durations(key, def string) ([]time.Duration, error) {
return out, nil
}
// unescape turns \r \n \t \e \\ and \xHH of a configured string into
// Unescape turns \r \n \t \e \\ and \xHH of a configured string into
// their bytes
func unescape(s string) string {
func Unescape(s string) string {
var b strings.Builder
for i := 0; i < len(s); i++ {
if s[i] != '\\' || i+1 == len(s) {
@@ -234,8 +237,8 @@ func unescape(s string) string {
return b.String()
}
// fields: a list split at commas and whitespace
func fields(s string) []string {
// Fields: a list split at commas and whitespace
func Fields(s string) []string {
return strings.FieldsFunc(s, func(r rune) bool {
return r == ',' || r == ' ' || r == '\t'
})
+79
View File
@@ -0,0 +1,79 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package config
import (
"fmt"
"os"
"path/filepath"
"testing"
)
// TestINI: the configuration file's sections, keys in lower case and
// quoted values
func TestINI(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("; comment\n[general]\nauth = file, sql\nbanner = \" hi \"\n[item bbs]\nKey = b\n"), 0o600)
c, err := Parse(p)
if err != nil {
t.Fatal(err)
}
if g := c.Section("general"); g.Get("banner", "") != " hi " || len(Fields(g.Get("auth", ""))) != 2 {
t.Errorf("general: %v", g.Vals)
}
if c.Section("item bbs").Get("key", "") != "b" {
t.Errorf("item: %v", c.Section("item bbs").Vals)
}
}
// TestStripComment: inline comments end a value after whitespace, not
// inside quotes or a word; \; and \# are kept as text
func TestStripComment(t *testing.T) {
for in, want := range map[string]string{
"P ; PPP": "P ",
"P # PPP": "P ",
"a;b": "a;b",
"echo a; echo b": "echo a; echo b",
`"a ; b" ; c`: `"a ; b" `,
`x \; y`: "x ; y",
`x \# y`: "x # y",
"; all comment": "",
"(&(uid={user})(#x))": "(&(uid={user})(#x))",
"exec pppd ipparam {user}": "exec pppd ipparam {user}",
} {
if got := StripComment(in); got != want {
t.Errorf("%q: %q, want %q", in, got, want)
}
}
}
// TestDurations: time_warning's list of durations, longest first, and
// none for 0 or none
func TestDurations(t *testing.T) {
for in, want := range map[string]string{
"5m 1m": "[5m0s 1m0s]",
"60, 300": "[5m0s 1m0s]",
"1m 5m 1m": "[5m0s 1m0s]",
"90s": "[1m30s]",
"0": "[]",
"none": "[]",
"": "[]",
} {
s := &Section{Name: "general", Vals: map[string]string{"time_warning": in}}
got, err := s.Durations("time_warning", "2m")
if err != nil || fmt.Sprint(got) != want {
t.Errorf("%q: %v %v, want %s", in, got, err, want)
}
}
for _, bad := range []string{"5m soon", "-1m", "1m 0"} {
s := &Section{Name: "general", Vals: map[string]string{"time_warning": bad}}
if _, err := s.Durations("time_warning", "2m"); err == nil {
t.Errorf("%q: no error", bad)
}
}
if got, _ := (&Section{Name: "general", Vals: map[string]string{}}).Durations("time_warning", "2m"); fmt.Sprint(got) != "[2m0s]" {
t.Errorf("the default: %v", got)
}
}
+36
View File
@@ -0,0 +1,36 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package config
import "strings"
// Expand replaces {name} by its value, quote() of it (nil: as is);
// unknown names stay as they are
func Expand(t string, v map[string]string, quote func(string) string) string {
var b strings.Builder
for {
i := strings.IndexByte(t, '{')
if i < 0 {
break
}
j := strings.IndexByte(t[i:], '}')
if j < 0 {
break
}
name := t[i+1 : i+j]
val, ok := v[strings.ToLower(name)]
b.WriteString(t[:i])
switch {
case !ok:
b.WriteString(t[i : i+j+1])
case quote != nil:
b.WriteString(quote(val))
default:
b.WriteString(val)
}
t = t[i+j+1:]
}
b.WriteString(t)
return b.String()
}
+170
View File
@@ -0,0 +1,170 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
// Package telnet is just enough of a telnet client for a BBS: binary,
// suppress go ahead and the server's echo, and the terminal type.
package telnet
import (
"io"
"sync"
)
// Client: just enough of a Client client for a BBS: binary, suppress go
// ahead and the server's echo, and the terminal type
type Client struct {
mu sync.Mutex
conn io.Writer
term string
state int
cmd byte
sb []byte
local map[byte]bool // options we do
remote map[byte]bool // options the server does
}
const (
iac = 255
dont = 254
do = 253
wont = 252
will = 251
sb = 250
se = 240
optBinary = 0
optEcho = 1
optSGA = 3
optTType = 24
)
// Pass: b written to w, not in the middle of a reply to the server
// (a nil telnet writes as is)
func (tn *Client) Pass(w io.Writer, b []byte) (int, error) {
if tn == nil {
return w.Write(b)
}
tn.mu.Lock()
defer tn.mu.Unlock()
return w.Write(b)
}
// send: bytes to the server
func (tn *Client) send(b ...byte) {
tn.Pass(tn.conn, b)
}
// Encode the caller's bytes: IAC doubled, CR as CR NUL unless binary
func (tn *Client) Encode(b []byte) []byte {
tn.mu.Lock()
bin := tn.local[optBinary]
tn.mu.Unlock()
out := make([]byte, 0, len(b)+8)
for _, c := range b {
out = append(out, c)
if c == iac {
out = append(out, iac)
} else if c == '\r' && !bin {
out = append(out, 0)
}
}
return out
}
// Decode the server's bytes: its data, the commands answered
func (tn *Client) Decode(b []byte) []byte {
out := b[:0:0]
for _, c := range b {
switch tn.state {
case 0:
if c == iac {
tn.state = 1
} else {
out = append(out, c)
}
case 1:
switch c {
case iac:
out = append(out, iac)
tn.state = 0
case will, wont, do, dont:
tn.cmd, tn.state = c, 2
case sb:
tn.sb, tn.state = tn.sb[:0], 3
default:
tn.state = 0
}
case 2:
tn.option(tn.cmd, c)
tn.state = 0
case 3:
if c == iac {
tn.state = 4
} else if len(tn.sb) < 256 {
tn.sb = append(tn.sb, c)
}
case 4:
if c == se {
tn.subneg()
tn.state = 0
} else {
if c == iac && len(tn.sb) < 256 {
tn.sb = append(tn.sb, iac)
}
tn.state = 3
}
}
}
return out
}
// option: the answer to the server's WILL, WONT, DO or DONT
func (tn *Client) option(cmd, opt byte) {
switch cmd {
case will:
ok := opt == optEcho || opt == optSGA || opt == optBinary
if ok && !tn.remote[opt] {
tn.remote[opt] = true
tn.send(iac, do, opt)
} else if !ok {
tn.send(iac, dont, opt)
}
case wont:
if tn.remote[opt] {
tn.remote[opt] = false
tn.send(iac, dont, opt)
}
case do:
ok := opt == optSGA || opt == optBinary || opt == optTType
if ok && !tn.local[opt] {
tn.mu.Lock()
tn.local[opt] = true
tn.mu.Unlock()
tn.send(iac, will, opt)
} else if !ok {
tn.send(iac, wont, opt)
}
case dont:
if tn.local[opt] {
tn.mu.Lock()
tn.local[opt] = false
tn.mu.Unlock()
tn.send(iac, wont, opt)
}
}
}
// subneg: the answer to a subnegotiation: the terminal type when asked
func (tn *Client) subneg() {
// TTYPE SEND: TTYPE IS <terminal>
if len(tn.sb) >= 2 && tn.sb[0] == optTType && tn.sb[1] == 1 {
msg := []byte{iac, sb, optTType, 0}
msg = append(msg, []byte(tn.term)...)
tn.send(append(msg, iac, se)...)
}
}
// New: a client on conn that says it is a term terminal
func New(conn io.Writer, term string) *Client {
return &Client{conn: conn, term: term, local: map[byte]bool{}, remote: map[byte]bool{}}
}
+35
View File
@@ -0,0 +1,35 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package telnet
import "testing"
// TestTelnetDecode: the telnet client's data, its replies to the
// server, and the caller's bytes encoded
func TestTelnetDecode(t *testing.T) {
var sent []byte
tn := &Client{conn: nil, term: "ANSI", local: map[byte]bool{}, remote: map[byte]bool{}}
tn.conn = &recorder{b: &sent}
in := []byte{'h', iac, will, optEcho, 'i', iac, iac, iac, do, optTType,
iac, sb, optTType, 1, iac, se, iac, do, 31, '!'}
out := tn.Decode(in)
if string(out) != "hi\xff!" {
t.Errorf("data %q", out)
}
want := []byte{iac, do, optEcho, iac, will, optTType, iac, sb, optTType, 0, 'A', 'N', 'S', 'I', iac, se, iac, wont, 31}
if string(sent) != string(want) {
t.Errorf("replies % x, want % x", sent, want)
}
if got := tn.Encode([]byte{'a', '\r', iac}); string(got) != "a\r\x00\xff\xff" {
t.Errorf("encode % x", got)
}
}
type recorder struct{ b *[]byte }
// Write: p kept
func (r *recorder) Write(p []byte) (int, error) {
*r.b = append(*r.b, p...)
return len(p), nil
}
+367
View File
@@ -0,0 +1,367 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package term
import (
"bytes"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// What the caller's terminal is, asked as bbs-sec asks it, before the
// banner:
//
// - ANSI: the cursor moved as far as it goes and its position asked for
// (CSI 6n). An ANSI terminal answers, and the answer is its size.
// - VT52, when not ANSI: ESC Z, which a VT52 answers with ESC / and a
// letter.
// - What an ANSI terminal is: DEC's questions (the answerback, DA1, DA2),
// xterm's version (XTVERSION) and SyncTERM's CTerm attributes.
// - PETSCII, when not ANSI: a Commodore asks nothing and answers nothing;
// its keys tell (DEL, the cursor keys, its shifted letters), or a name
// typed all in capitals and the DEL key pressed when asked.
// the questions, and the patterns of their answers
const (
// the cursor saved, as far down and right as it goes, its position
// asked, restored: the answer is the screen's size
queryANSI = "\x1b7\x1b[999;999H\x1b[6n\x1b8"
// the answerback (ENQ), DA1, DA2, XTVERSION, and last the cursor's
// position, which every ANSI terminal answers: once it comes, whatever
// else would has
queryVT = "\x05\x1b[c\x1b[>c\x1b[>0q\x1b[6n"
queryVT52 = "\x1bZ"
)
var (
da1Pattern = regexp.MustCompile(`\x1b\[\?([0-9;]*)c`)
da2Pattern = regexp.MustCompile(`\x1b\[>([0-9;]*)c`)
ctermPat = regexp.MustCompile(`\x1b\[=([0-9;]*)c`)
xtverPat = regexp.MustCompile(`\x1bP>\|([^\x1b\x07]{0,80})\x1b\\`)
cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`)
vt52Pattern = regexp.MustCompile(`\x1b/([A-Za-z])`)
// all the answers, to take them out of what the caller typed
answers = []*regexp.Regexp{da1Pattern, da2Pattern, ctermPat, xtverPat, cprPattern, vt52Pattern}
)
// VTInfo: what an ANSI terminal said of itself
type VTInfo struct {
answerback string // ENQ's answer
da1 []int // the class (1, 6, 62-65) and options
da2 []int // the model, its firmware version, options
version string // XTVERSION's "name(version)"
cterm string // SyncTERM's CTerm version
}
// ParseVT: what an ANSI terminal answered to queryVT
func ParseVT(reply []byte) VTInfo {
var in VTInfo
// the answerback is what came before the first escape sequence
ab := reply
if i := bytes.IndexByte(ab, 0x1b); i >= 0 {
ab = ab[:i]
}
in.answerback = printable(string(ab), 40)
if m := da1Pattern.FindSubmatch(reply); m != nil {
in.da1 = numbers(string(m[1]))
}
if m := da2Pattern.FindSubmatch(reply); m != nil {
in.da2 = numbers(string(m[1]))
}
if m := xtverPat.FindSubmatch(reply); m != nil {
in.version = printable(string(m[1]), 60)
}
if m := ctermPat.FindSubmatch(reply); m != nil {
// "CTerm" in decimal character codes, then the version
ns := numbers(string(m[1]))
if len(ns) >= 5 && string([]byte{byte(ns[0]), byte(ns[1]), byte(ns[2]), byte(ns[3]), byte(ns[4])}) == "CTerm" {
var v []string
for _, n := range ns[5:] {
v = append(v, strconv.Itoa(n))
}
if in.cterm = strings.Join(v, "."); in.cterm == "" {
in.cterm = "?"
}
}
}
return in
}
// numbers: a sequence's ;-separated parameters (32 at most)
func numbers(s string) []int {
var out []int
for _, f := range strings.Split(s, ";") {
n, err := strconv.Atoi(f)
if err != nil || n < 0 || n > 1<<20 {
continue
}
if out = append(out, n); len(out) == 32 {
break
}
}
return out
}
// printable: s's printable ASCII, at most max bytes, trimmed
func printable(s string, max int) string {
var b strings.Builder
for _, r := range s {
if r >= 0x20 && r < 0x7f && b.Len() < max {
b.WriteRune(r)
}
}
return strings.TrimSpace(b.String())
}
// Level: the VT Level: 1 a VT100 or VT102, 2 a VT220, 3 VT320, 4 VT420,
// 5 VT510 and later; 0 if it did not say
func (in VTInfo) Level() int {
if len(in.da1) == 0 {
return 0
}
switch c := in.da1[0]; {
case c >= 61 && c <= 69:
return c - 60
case c == 1 || c == 6 || c == 4 || c == 7 || c == 12:
return 1
}
return 0
}
// DA2's model numbers of DEC's own terminals, and those emulators give
var (
decModels = map[int]string{
0: "VT100", 1: "VT220", 2: "VT240", 18: "VT330", 19: "VT340", 24: "VT320",
28: "DECterm", 32: "VT382", 41: "VT420", 61: "VT510", 64: "VT520", 65: "VT525",
}
emulators = map[int]string{77: "mintty", 82: "rxvt", 83: "screen", 84: "tmux", 85: "rxvt-unicode"}
)
// Hardware: a DEC terminal by its DA2 (a model of DEC's, a small firmware
// version), not an emulator that says its name otherwise
func (in VTInfo) Hardware() bool {
if in.version != "" || in.cterm != "" || len(in.da2) < 2 {
return false
}
_, dec := decModels[in.da2[0]]
return dec && in.da2[1] < 95
}
// Emulator: a program on a computer (xterm, VTE, SyncTERM...), not a VT
func (in VTInfo) Emulator() bool {
if in.version != "" || in.cterm != "" {
return true
}
if len(in.da2) >= 2 && !in.Hardware() {
p, v := in.da2[0], in.da2[1]
return emulators[p] != "" || p == 41 && v >= 95 || (p == 1 || p == 65) && v >= 1000
}
return false
}
// Name: what the terminal is, as best it said
func (in VTInfo) Name() string {
switch {
case in.version != "":
return in.version
case in.cterm != "":
return "SyncTERM (CTerm " + in.cterm + ")"
case in.Hardware():
return decModels[in.da2[0]]
}
if len(in.da2) >= 2 {
p, v := in.da2[0], in.da2[1]
switch {
case emulators[p] != "":
return emulators[p]
case p == 41 && v >= 95:
return fmt.Sprintf("xterm (patch %d)", v)
case (p == 1 || p == 65) && v >= 1000:
return "VTE"
}
}
if in.answerback != "" {
return in.answerback
}
switch l := in.Level(); {
case l == 1 && in.da1[0] == 6:
return "VT102"
case l == 1:
return "VT100"
case l >= 2:
return fmt.Sprintf("VT%d00 class", l)
}
return ""
}
// Term: a TERM for it: syncterm, xterm for the other emulators, a VT's
// own (vt100, vt220...), ansi when it did not say
func (in VTInfo) Term() string {
switch {
case in.cterm != "":
return "syncterm"
case in.Emulator():
return "xterm"
case in.Hardware():
switch m := in.da2[0]; {
case m == 0:
return "vt100"
case m == 1 || m == 2:
return "vt220"
case m >= 18 && m <= 32:
return "vt320"
case m == 41:
return "vt420"
default:
return "vt520"
}
}
switch l := in.Level(); {
case l == 1 && in.da1[0] == 6:
return "vt102"
case l == 1:
return "vt100"
case l == 2:
return "vt220"
case l == 3:
return "vt320"
case l == 4:
return "vt420"
case l >= 5:
return "vt520"
}
return "ansi"
}
// PETSCIITelltale: a byte only a Commodore's keys send: DEL, the cursor
// keys, CLR, the function keys, a shifted letter
func PETSCIITelltale(b byte) bool {
switch {
case b == 0x14, b == 0x91, b == 0x1D, b == 0x9D, b == 0x93:
return true
case b >= 0x85 && b <= 0x8C:
return true
case b >= 0xC1 && b <= 0xDA:
return true
}
return false
}
// Prober: the questions of one call, and what came that was no answer
// (what the caller typed, a PPP frame) to be read again after
type Prober struct {
T *Term
extra []byte
PPP bool // a PPP frame came: ask nothing more
}
// collect what comes until done, max bytes or timeout
func (p *Prober) collect(timeout time.Duration, max int, done func([]byte) bool) ([]byte, error) {
var got []byte
end := time.Now().Add(timeout)
for len(got) < max {
left := time.Until(end)
if left <= 0 {
break
}
c, err := p.T.ReadOne(left)
if errors.Is(err, ErrTimeout) {
break
}
if err != nil {
return got, err
}
got = append(got, c)
if done(got) {
break
}
if n := len(got); n >= 3 && IsPPPFrame(got[n-3:]) {
break // a dialer's PPP: no answer will come
}
}
return got, nil
}
// keep what is no answer to the questions
func (p *Prober) keep(b []byte) {
for _, re := range answers {
b = re.ReplaceAll(b, nil)
}
p.extra = append(p.extra, b...)
for i := range p.extra {
if IsPPPFrame(p.extra[i:]) {
p.PPP = true
}
}
}
// Done: what was no answer, read again by the login
func (p *Prober) Done() { p.T.Unread(p.extra...) }
// ANSI: the position after the cursor went as far as it goes: whether the
// terminal answered, and its size
func (p *Prober) ANSI(timeout time.Duration) (bool, int, int, error) {
if err := p.T.WriteRaw(queryANSI); err != nil {
return false, 0, 0, err
}
got, err := p.collect(timeout, 64, cprPattern.Match)
if err != nil {
return false, 0, 0, err
}
m := cprPattern.FindSubmatch(got)
p.keep(got)
if m == nil {
// a plain terminal shows the question as text: wiped
return false, 0, 0, p.T.WriteRaw("\r" + strings.Repeat(" ", 20) + "\r")
}
rows, _ := strconv.Atoi(string(m[1]))
cols, _ := strconv.Atoi(string(m[2]))
if rows < 10 || rows > 200 {
rows = 0
}
if cols < 40 || cols > 300 {
cols = 0
}
return true, rows, cols, nil
}
// VT52: whether ESC Z is answered as a VT52 answers it; any other shows
// a Z, which is wiped
func (p *Prober) VT52(timeout time.Duration) (bool, error) {
if err := p.T.WriteRaw(queryVT52); err != nil {
return false, err
}
got, err := p.collect(timeout, 16, vt52Pattern.Match)
if err != nil {
return false, err
}
is := vt52Pattern.Match(got)
p.keep(got)
if !is {
return false, p.T.WriteRaw("\r \r")
}
return true, nil
}
// Identify: what an ANSI terminal says it is
func (p *Prober) Identify(timeout time.Duration) (VTInfo, error) {
if err := p.T.WriteRaw(queryVT); err != nil {
return VTInfo{}, err
}
got, err := p.collect(timeout, 1024, cprPattern.Match)
if err != nil {
return VTInfo{}, err
}
in := ParseVT(got)
// the answerback is no key the caller typed
if i := bytes.IndexByte(got, 0x1b); i > 0 && in.answerback != "" {
got = got[i:]
}
p.keep(got)
return in, nil
}
+77
View File
@@ -0,0 +1,77 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package term
// PETSCIIOut: what the menu writes, for a Commodore in its lower/upper
// case set: the letters' cases swapped as that set has them, a line end
// as RETURN, backspace as cursor left, escape sequences and what it has
// not dropped
func PETSCIIOut(s string) []byte {
out := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == 0x1b:
// an escape sequence: CSI's parameters to its final byte, or
// one character
if i+1 < len(s) && s[i+1] == '[' {
i += 2
for i < len(s) && (s[i] < 0x40 || s[i] > 0x7e) {
i++
}
} else {
i++
}
case c == '\r':
out = append(out, 0x0d)
if i+1 < len(s) && s[i+1] == '\n' {
i++
}
case c == '\n':
out = append(out, 0x0d)
case c == 0x08:
out = append(out, 0x9d)
case c >= 'a' && c <= 'z':
out = append(out, c-'a'+0x41)
case c >= 'A' && c <= 'Z':
out = append(out, c-'A'+0xc1)
case c == '{':
out = append(out, '(')
case c == '}':
out = append(out, ')')
case c == '|':
out = append(out, '!')
case c == '~':
out = append(out, '-')
case c == '`':
out = append(out, '\'')
case c == '\\':
out = append(out, '/')
case c == '_':
out = append(out, '-')
case c >= 0x20 && c < 0x7f:
out = append(out, c)
case c >= 0xc0:
// a rune of UTF-8: one character the C64 has not
out = append(out, '?')
}
}
return out
}
// PETSCIIIn: a Commodore's key as ASCII: its unshifted letters lower
// case, its shifted ones upper case, DEL as DEL
func PETSCIIIn(c byte) byte {
switch {
case c >= 0x41 && c <= 0x5a:
return c - 0x41 + 'a'
case c >= 0xc1 && c <= 0xda:
return c - 0xc1 + 'A'
case c >= 0x61 && c <= 0x7a:
return c - 0x61 + 'A'
case c == 0x14:
return 0x7f
}
return c
}
+22
View File
@@ -0,0 +1,22 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package term
// IsPPPFrame: whether what starts with the flag 0x7E is a PPP frame: the
// address and control (0xFF 0x03, the 0x03 escaped as 0x7D 0x23), the
// address escaped (0x7D 0xDF), or both compressed away (LCP's 0xC0 0x21)
func IsPPPFrame(b []byte) bool {
if len(b) < 3 || b[0] != 0x7E {
return false
}
switch {
case b[1] == 0xFF && (b[2] == 0x03 || b[2] == 0x7D):
return true
case b[1] == 0x7D && b[2] == 0xDF:
return true
case b[1] == 0xC0 && b[2] == 0x21:
return true
}
return false
}
+102 -83
View File
@@ -1,72 +1,85 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
// Package term is the caller's line: raw reads and writes with timeouts,
// line editing and echo, the questions that tell what terminal the caller
// has (ANSI, VT52, an ANSI terminal's identity), PETSCII for a Commodore,
// and a PPP frame told from typing.
package term
import (
"errors"
"io"
"os"
"strings"
"time"
"golang.org/x/sys/unix"
)
var (
errTimeout = errors.New("timeout")
errHangup = errors.New("hangup")
// while watchPETSCII: a key only a Commodore sends
errPETSCII = errors.New("a Commodore's key")
ErrTimeout = errors.New("timeout")
ErrHangup = errors.New("hangup")
// while WatchPETSCII: a key only a Commodore sends
ErrPETSCII = errors.New("a Commodore's key")
)
// term: the caller's line on stdin and stdout. app_dmodem's pty is raw
// Term: the caller's line on stdin and stdout. app_dmodem's pty is raw
// (no echo, no line editing, no CR/LF translation): the menu echoes and
// edits lines itself. Reads poll stdin and take no more than they need,
// so that what the caller types after the menu goes to the selection.
type term struct {
in, out int
type Term struct {
In, Out int
saved *unix.Termios
lastCR bool
pending []byte // read and put back (unread), read again first
// a Commodore: what the menu writes and reads is PETSCII
petscii bool
PETSCII bool
// the terminal may be a Commodore's: a key only one sends ends a line
// with errPETSCII
watchPETSCII bool
// with ErrPETSCII
WatchPETSCII bool
}
// setPETSCII: the line a Commodore's from here on, in its lower/upper
// SetPETSCII: the line a Commodore's from here on, in its lower/upper
// case set
func (t *term) setPETSCII() {
if !t.petscii {
t.petscii = true
t.writeRaw("\x0e")
func (t *Term) SetPETSCII() {
if !t.PETSCII {
t.PETSCII = true
t.WriteRaw("\x0e")
}
}
// unread: b read again, before what the line has
func (t *term) unread(b ...byte) {
// Unread: b read again, before what the line has
func (t *Term) Unread(b ...byte) {
t.pending = append(append([]byte{}, b...), t.pending...)
}
// newTerm: the line on in and out, made raw if it is a terminal (its
// mode before kept for close)
func newTerm(in, out *os.File) *term {
t := &term{in: int(in.Fd()), out: int(out.Fd())}
// TakePending: what was read and put back, taken off the line (for a
// selection to have it)
func (t *Term) TakePending() []byte {
b := t.pending
t.pending = nil
return b
}
// New: the line on in and out, made raw if it is a terminal (its
// mode before kept for Close)
func New(in, out *os.File) *Term {
t := &Term{In: int(in.Fd()), Out: int(out.Fd())}
// a terminal of our own (a getty, a test from a console): raw as the
// pty of app_dmodem is
if tio, err := unix.IoctlGetTermios(t.in, unix.TCGETS); err == nil {
if tio, err := unix.IoctlGetTermios(t.In, unix.TCGETS); err == nil {
saved := *tio
t.saved = &saved
makeRaw(tio)
unix.IoctlSetTermios(t.in, unix.TCSETS, tio)
MakeRaw(tio)
unix.IoctlSetTermios(t.In, unix.TCSETS, tio)
}
return t
}
// makeRaw: t as app_dmodem's pty is: no echo, no line editing, no
// MakeRaw: t as app_dmodem's pty is: no echo, no line editing, no
// translation, 8 bits
func makeRaw(t *unix.Termios) {
func MakeRaw(t *unix.Termios) {
t.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP |
unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
t.Oflag &^= unix.OPOST
@@ -77,8 +90,8 @@ func makeRaw(t *unix.Termios) {
t.Cc[unix.VTIME] = 0
}
// makeSane: a cooked line for programs that expect one (a shell, login)
func makeSane(t *unix.Termios) {
// MakeSane: a cooked line for programs that expect one (a shell, login)
func MakeSane(t *unix.Termios) {
t.Iflag |= unix.BRKINT | unix.ICRNL | unix.IXON
t.Iflag &^= unix.INLCR | unix.IGNCR
t.Oflag |= unix.OPOST | unix.ONLCR
@@ -90,64 +103,64 @@ func makeSane(t *unix.Termios) {
t.Cc[unix.VEOF] = 'D' & 0x1f
}
// setMode: the line raw or sane for a selection; the mode before, to
// SetMode: the line raw or sane for a selection; the mode before, to
// restore (nil when stdin is no terminal)
func (t *term) setMode(mode string) *unix.Termios {
tio, err := unix.IoctlGetTermios(t.in, unix.TCGETS)
func (t *Term) SetMode(mode string) *unix.Termios {
tio, err := unix.IoctlGetTermios(t.In, unix.TCGETS)
if err != nil {
return nil
}
before := *tio
if mode == "sane" {
makeSane(tio)
MakeSane(tio)
} else {
makeRaw(tio)
MakeRaw(tio)
}
unix.IoctlSetTermios(t.in, unix.TCSETS, tio)
unix.IoctlSetTermios(t.In, unix.TCSETS, tio)
return &before
}
// restoreMode: the line's mode as setMode found it
func (t *term) restoreMode(tio *unix.Termios) {
// RestoreMode: the line's mode as setMode found it
func (t *Term) RestoreMode(tio *unix.Termios) {
if tio != nil {
unix.IoctlSetTermios(t.in, unix.TCSETS, tio)
unix.IoctlSetTermios(t.In, unix.TCSETS, tio)
}
}
// close: the line's mode as newTerm found it
func (t *term) close() {
// Close: the line's mode as newTerm found it
func (t *Term) Close() {
if t.saved != nil {
unix.IoctlSetTermios(t.in, unix.TCSETSW, t.saved)
unix.IoctlSetTermios(t.In, unix.TCSETSW, t.saved)
}
}
// write what the menu says, as the terminal takes it
func (t *term) write(s string) error {
if t.petscii {
return t.writeRaw(string(petsciiOut(s)))
// Write what the menu says, as the terminal takes it
func (t *Term) Write(s string) error {
if t.PETSCII {
return t.WriteRaw(string(PETSCIIOut(s)))
}
return t.writeRaw(s)
return t.WriteRaw(s)
}
// writeRaw: bytes as they are (a selection's, the terminal's questions)
func (t *term) writeRaw(s string) error {
// WriteRaw: bytes as they are (a selection's, the terminal's questions)
func (t *Term) WriteRaw(s string) error {
b := []byte(s)
for len(b) > 0 {
n, err := unix.Write(t.out, b)
n, err := unix.Write(t.Out, b)
if err == unix.EINTR || err == unix.EAGAIN {
pollOne(t.out, unix.POLLOUT, time.Second)
PollOne(t.Out, unix.POLLOUT, time.Second)
continue
}
if err != nil {
return errHangup
return ErrHangup
}
b = b[n:]
}
return nil
}
// pollOne: whether fd is ready for ev within d (d < 0: no limit)
func pollOne(fd int, ev int16, d time.Duration) (bool, error) {
// PollOne: whether fd is ready for ev within d (d < 0: no limit)
func PollOne(fd int, ev int16, d time.Duration) (bool, error) {
ms := -1
if d >= 0 {
ms = int(d / time.Millisecond)
@@ -168,8 +181,8 @@ func pollOne(fd int, ev int16, d time.Duration) (bool, error) {
}
}
// readByte within d, or errTimeout; errHangup when the line is gone
func (t *term) readByte(d time.Duration) (byte, error) {
// ReadOne within d, or errTimeout; errHangup when the line is gone
func (t *Term) ReadOne(d time.Duration) (byte, error) {
if len(t.pending) > 0 {
b := t.pending[0]
t.pending = t.pending[1:]
@@ -180,44 +193,44 @@ func (t *term) readByte(d time.Duration) (byte, error) {
for {
left := time.Until(deadline)
if left <= 0 {
return 0, errTimeout
return 0, ErrTimeout
}
ok, err := pollOne(t.in, unix.POLLIN, left)
ok, err := PollOne(t.In, unix.POLLIN, left)
if err != nil {
return 0, errHangup
return 0, ErrHangup
}
if !ok {
return 0, errTimeout
return 0, ErrTimeout
}
n, err := unix.Read(t.in, b[:])
n, err := unix.Read(t.In, b[:])
if err == unix.EINTR || err == unix.EAGAIN {
continue
}
if n <= 0 || err != nil {
return 0, errHangup
return 0, ErrHangup
}
return b[0], nil
}
}
// readLine of at most max bytes until deadline, echoing it (or mask for
// ReadLine of at most max bytes until deadline, echoing it (or mask for
// each byte; "" for nothing). CR, LF or CR LF end it; BS and DEL erase,
// ^U the line, ^D or ^C on an empty line hang up.
func (t *term) readLine(deadline time.Time, max int, echo bool, mask string) (string, error) {
func (t *Term) ReadLine(deadline time.Time, max int, echo bool, mask string) (string, error) {
var line []byte
for {
c, err := t.readByte(time.Until(deadline))
c, err := t.ReadOne(time.Until(deadline))
if err != nil {
return "", err
}
if t.watchPETSCII && petsciiTelltale(c) {
if c < 0xc1 || !t.continuation() {
return "", errPETSCII
if t.WatchPETSCII && PETSCIITelltale(c) {
if c < 0xc1 || !t.Continuation() {
return "", ErrPETSCII
}
continue // a letter of UTF-8, not a shifted one
}
if t.petscii {
c = petsciiIn(c)
if t.PETSCII {
c = PETSCIIIn(c)
}
if c == '\n' && t.lastCR {
t.lastCR = false
@@ -226,18 +239,18 @@ func (t *term) readLine(deadline time.Time, max int, echo bool, mask string) (st
t.lastCR = c == '\r'
switch {
case c == '\r' || c == '\n':
return string(line), t.write("\r\n")
return string(line), t.Write("\r\n")
case c == 0x08 || c == 0x7f:
if len(line) > 0 {
line = line[:len(line)-1]
if echo || mask != "" {
t.write("\b \b")
t.Write("\b \b")
}
}
case c == 0x15:
for range line {
if echo || mask != "" {
t.write("\b \b")
t.Write("\b \b")
}
}
line = line[:0]
@@ -249,18 +262,18 @@ func (t *term) readLine(deadline time.Time, max int, echo bool, mask string) (st
line = append(line, c)
switch {
case echo:
t.write(string(c))
t.Write(string(c))
case mask != "":
t.write(mask)
t.Write(mask)
}
}
}
}
// readKey: one key, upper case, until deadline
func (t *term) readKey(deadline time.Time) (string, error) {
// ReadKey: one key, upper case, until deadline
func (t *Term) ReadKey(deadline time.Time) (string, error) {
for {
c, err := t.readByte(time.Until(deadline))
c, err := t.ReadOne(time.Until(deadline))
if err != nil {
return "", err
}
@@ -268,8 +281,8 @@ func (t *term) readKey(deadline time.Time) (string, error) {
t.lastCR = false
continue
}
if t.petscii {
c = petsciiIn(c)
if t.PETSCII {
c = PETSCIIIn(c)
}
t.lastCR = c == '\r'
if c == 0x04 {
@@ -284,16 +297,22 @@ func (t *term) readKey(deadline time.Time) (string, error) {
}
}
// continuation: whether a UTF-8 continuation byte follows at once (it is
// Continuation: whether a UTF-8 Continuation byte follows at once (it is
// taken)
func (t *term) continuation() bool {
c, err := t.readByte(200 * time.Millisecond)
func (t *Term) Continuation() bool {
c, err := t.ReadOne(200 * time.Millisecond)
if err != nil {
return false
}
if c >= 0x80 && c <= 0xbf {
return true
}
t.unread(c)
t.Unread(c)
return false
}
// CRLF: the line ends of a text file as the terminal wants them
func CRLF(s string) string {
s = strings.ReplaceAll(s, "\r\n", "\n")
return strings.ReplaceAll(s, "\n", "\r\n")
}
+45
View File
@@ -0,0 +1,45 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package term
import "testing"
// TestParseVT: names, TERMs and levels from real terminals' answers
func TestParseVT(t *testing.T) {
for _, c := range []struct {
what, reply, name, term string
level int
}{
{"xterm", "\x1b[?64;1;2;6;9;15;18;21;22c\x1b[>41;390;0c\x1bP>|XTerm(390)\x1b\\\x1b[50;132R", "XTerm(390)", "xterm", 4},
{"xterm without XTVERSION", "\x1b[?65;1;9c\x1b[>41;390;0c\x1b[24;80R", "xterm (patch 390)", "xterm", 5},
{"a VT220", "\x1b[?62;1;2;6;8;9;15c\x1b[>1;10;0c\x1b[24;80R", "VT220", "vt220", 2},
{"a VT520", "\x1b[?65;1;2;6;7;8;9;12;18;19;21;22;23;24;42;44;45;46c\x1b[>64;20;0c\x1b[24;80R", "VT520", "vt520", 5},
{"a VT100", "\x1b[?1;2c\x1b[24;80R", "VT100", "vt100", 1},
{"a VT102", "\x1b[?6c\x1b[24;80R", "VT102", "vt102", 1},
{"SyncTERM", "\x1b[=67;84;101;114;109;1;316c\x1b[24;80R", "SyncTERM (CTerm 1.316)", "syncterm", 0},
{"VTE", "\x1b[?65;1;9c\x1b[>65;6800;1c\x1b[24;80R", "VTE", "xterm", 5},
{"an answerback", "MYTERM\x1b[?62;1c\x1b[24;80R", "MYTERM", "vt220", 2},
{"nothing said", "\x1b[24;80R", "", "ansi", 0},
} {
in := ParseVT([]byte(c.reply))
if in.Name() != c.name || in.Term() != c.term || in.Level() != c.level {
t.Errorf("%s: %q %q level %d, want %q %q %d", c.what, in.Name(), in.Term(), in.Level(), c.name, c.term, c.level)
}
}
}
// TestPETSCIIText: the menu's text as PETSCII, and a Commodore's keys
// as ASCII
func TestPETSCIIText(t *testing.T) {
if got := string(PETSCIIOut("Hi you\r\n\x1b[1;33mX\b \b\n")); got != "\xc8I YOU\r\xd8\x9d \x9d\r" {
t.Errorf("out %q", got)
}
var in []byte
for _, c := range []byte("HI\xc8\x14\r") {
in = append(in, PETSCIIIn(c))
}
if string(in) != "hiH\x7f\r" {
t.Errorf("in %q", in)
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
INHERIT: .site/mkdocs-base.yml
# modemmenu's site, https://d-modem.github.io/menu/: docs/ and the README
# with brand's shared theme and workflow (brand's docs/sites.md).
# docs/reference.md is made from modemmenu.conf.sample (go run ./tools/confref).
# docs/reference.md is made from samples/modemmenu.conf.sample (go run ./tools/confref).
site_name: D-Modem menu
site_description: modemmenu, the login and menu dial-up callers reach
site_url: https://d-modem.github.io/menu/
-247
View File
@@ -1,247 +0,0 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"crypto/sha256"
"crypto/sha512"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
// TestCheckPassword: each stored hash scheme accepts the right password
// and refuses others
func TestCheckPassword(t *testing.T) {
bc, _ := bcrypt.GenerateFromPassword([]byte("pw"), bcrypt.MinCost)
s256 := sha256.Sum256([]byte("pw"))
s512 := sha512.Sum512([]byte("pw"))
salted := sha256.Sum256([]byte("pwSALT"))
ssha := base64.StdEncoding.EncodeToString(append(salted[:], "SALT"...))
for _, c := range []struct {
stored, scheme string
ok bool
}{
{string(bc), "auto", true},
{string(bc), "bcrypt", true},
{"{SHA256}" + hex.EncodeToString(s256[:]), "auto", true},
{"{SHA256}" + base64.StdEncoding.EncodeToString(s256[:]), "auto", true},
{"{SHA512}" + hex.EncodeToString(s512[:]), "auto", true},
{"{SSHA256}" + ssha, "auto", true},
{"{PLAIN}pw", "auto", true},
{"{PLAIN}px", "auto", false},
{"pw", "plain", true},
{hex.EncodeToString(s256[:]), "sha256", true},
} {
for _, pw := range []string{"pw", "wrong"} {
ok, err := checkPassword(c.stored, pw, c.scheme)
if err != nil {
t.Errorf("%s (%s): %v", c.stored, c.scheme, err)
}
if want := c.ok && pw == "pw"; ok != want {
t.Errorf("%s (%s) %s: %v, want %v", c.stored, c.scheme, pw, ok, want)
}
}
}
if _, err := checkPassword("pw", "pw", "auto"); err == nil {
t.Error("a bare password with hash = auto: no error")
}
}
// TestExpand: {placeholders} replaced and shell-quoted; unknown ones
// kept
func TestExpand(t *testing.T) {
v := map[string]string{"user": "o'neil; rm -rf /", "baud": "33600"}
got := expand("login {user} {baud} {unknown} {", v, shellQuote)
want := `login 'o'\''neil; rm -rf /' '33600' {unknown} {`
if got != want {
t.Errorf("got %q, want %q", got, want)
}
if got := expand("{USER}/{baud}", v, nil); got != v["user"]+"/33600" {
t.Errorf("got %q", got)
}
if got := unescape(`a\r\n\x41\\b`); got != "a\r\nA\\b" {
t.Errorf("unescape: %q", got)
}
}
// TestSession: the call's details in the environment
func TestSession(t *testing.T) {
now := time.Date(2026, 10, 10, 21, 5, 9, 0, time.UTC)
s := newSession("50666/31200", "5551000", "5559999", now)
s.User, s.Password = "alice", "secret"
env := strings.Join(s.environ(true), "\n")
for _, w := range []string{"MODEM_USER=alice", "MODEM_PASSWORD=secret", "MODEM_BAUD=50666",
"MODEM_RX_RATE=31200", "MODEM_DIALED=5551000", "MODEM_CALLERID=5559999",
"MODEM_DATE=2026-10-10", "MODEM_TIME=21:05:09", "MODEM_EPOCH=" + "1791666309"} {
if !strings.Contains(env, w+"\n") && !strings.HasSuffix(env, w) {
t.Errorf("no %s in\n%s", w, env)
}
}
if strings.Contains(strings.Join(s.environ(false), "\n"), "secret") {
t.Error("the password without pass_password")
}
}
// TestTelnetDecode: the telnet client's data, its replies to the
// server, and the caller's bytes encoded
func TestTelnetDecode(t *testing.T) {
var sent []byte
tn := &telnet{conn: nil, term: "ANSI", local: map[byte]bool{}, remote: map[byte]bool{}}
tn.conn = &recorder{b: &sent}
in := []byte{'h', iac, will, optEcho, 'i', iac, iac, iac, do, optTType,
iac, sb, optTType, 1, iac, se, iac, do, 31, '!'}
out := tn.decode(in)
if string(out) != "hi\xff!" {
t.Errorf("data %q", out)
}
want := []byte{iac, do, optEcho, iac, will, optTType, iac, sb, optTType, 0, 'A', 'N', 'S', 'I', iac, se, iac, wont, 31}
if string(sent) != string(want) {
t.Errorf("replies % x, want % x", sent, want)
}
if got := tn.encode([]byte{'a', '\r', iac}); string(got) != "a\r\x00\xff\xff" {
t.Errorf("encode % x", got)
}
}
// TestINI: the configuration file's sections, keys in lower case and
// quoted values
func TestINI(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("; comment\n[general]\nauth = file, sql\nbanner = \" hi \"\n[item bbs]\nKey = b\n"), 0o600)
c, err := parseINI(p)
if err != nil {
t.Fatal(err)
}
if g := c.section("general"); g.get("banner", "") != " hi " || len(fields(g.get("auth", ""))) != 2 {
t.Errorf("general: %v", g.vals)
}
if c.section("item bbs").get("key", "") != "b" {
t.Errorf("item: %v", c.section("item bbs").vals)
}
}
// TestBackends: the file and SQL backends, in order, accept and refuse
// as they should
func TestBackends(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
bc, _ := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
os.WriteFile(users, []byte("# users\nalice:"+string(bc)+":Alice\nbob:{PLAIN}a:b\n"), 0o600)
fa, err := newFileAuth(&section{name: "file", vals: map[string]string{"path": users}})
if err != nil {
t.Fatal(err)
}
dbPath := filepath.Join(dir, "users.db")
db, err := sql.Open("sqlite", dbPath)
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`CREATE TABLE users (username TEXT, password TEXT);
INSERT INTO users VALUES ('carol', '{PLAIN}pw'), ('alice', '{PLAIN}other');`); err != nil {
t.Fatal(err)
}
db.Close()
sa, err := newSQLAuth(&section{name: "sql", vals: map[string]string{
"driver": "sqlite", "dsn": dbPath,
"query": "SELECT password FROM users WHERE username = ?"}})
if err != nil {
t.Fatal(err)
}
sn, err := newSQLAuth(&section{name: "sql", vals: map[string]string{
"driver": "sqlite", "dsn": dbPath, "args": "user password", "hash": "none",
"query": "SELECT 1 FROM users WHERE username = ? AND password = '{PLAIN}' || ?"}})
if err != nil {
t.Fatal(err)
}
backends := []authenticator{fa, sa}
nolog := func(string, ...any) {}
for _, c := range []struct {
user, pw, auth string
err error
}{
{"alice", "secret", "file", nil},
{"alice", "other", "", errBadPassword}, // the file knows alice: not asked further
{"bob", "a:b", "file", nil},
{"carol", "pw", "sql", nil},
{"carol", "px", "", errBadPassword},
{"dave", "pw", "", errNoUser},
} {
auth, err := authenticate(context.Background(), backends, c.user, c.pw, nolog)
if auth != c.auth || !errors.Is(err, c.err) && !(err == nil && c.err == nil) {
t.Errorf("%s/%s: %q %v, want %q %v", c.user, c.pw, auth, err, c.auth, c.err)
}
}
if err := sn.authenticate(context.Background(), "carol", "pw"); err != nil {
t.Errorf("hash = none: %v", err)
}
if err := sn.authenticate(context.Background(), "carol", "px"); !errors.Is(err, errNoUser) {
t.Errorf("hash = none, wrong password: %v", err)
}
}
type recorder struct{ b *[]byte }
// Write: p kept
func (r *recorder) Write(p []byte) (int, error) {
*r.b = append(*r.b, p...)
return len(p), nil
}
// TestMenuSettings: what keys, names and aliases select, and the menu
// settings that are refused
func TestMenuSettings(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, nil, 0o600)
load := func(menu, items string) (*settings, error) {
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("[general]\nauth = file\n[file]\npath = "+users+"\n[menu]\n"+menu+"\n"+items), 0o600)
return loadSettings(p)
}
ppp := "[item ppp]\nkey = P\naliases = dialup net\ncommand = true\n"
s, err := load("", ppp+"[item bbs]\nkey = BBS\ncommand = true\n")
if err != nil {
t.Fatal(err)
}
for choice, want := range map[string]string{"P": "ppp", "PPP": "ppp", "NET": "ppp", "BBS": "bbs", "B": ""} {
it := s.selects(choice)
if want == "" && it != nil || want != "" && (it == nil || it.name != want) {
t.Errorf("%s selects %v, want %q", choice, it, want)
}
}
if !contains(s.hangup, "GOODBYE") {
t.Errorf("hangup %v", s.hangup)
}
for _, c := range []struct{ menu, items string }{
{"", ppp + "[item net]\ncommand = true\n"}, // net: an alias of ppp
{"hangup = P", ppp}, // P hangs up and selects ppp
{"hotkeys = yes", ppp + "[item bbs]\nkey = BBS\ncommand = true\n"},
} {
if _, err := load(c.menu, c.items); err == nil {
t.Errorf("%q %q: no error", c.menu, c.items)
}
}
if _, err := load("hotkeys = yes", ppp); err != nil {
t.Errorf("hotkeys with one-character keys: %v", err)
}
}
// runGo: the go command with args, its output
func runGo(args ...string) ([]byte, error) {
return exec.Command("go", args...).CombinedOutput()
}
-233
View File
@@ -1,233 +0,0 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"golang.org/x/sys/unix"
)
// errRefused: the backend did not take the new password (its policy)
var errRefused = errors.New("new password refused")
// passwordChanger: a backend that can change a user's password; old has
// been checked already. t is the caller's line, for a backend (PAM) that
// has something to tell them.
type passwordChanger interface {
changePassword(ctx context.Context, t *term, user, old, new string) error
}
// changePasswordItem: mode = passwd, the caller's password changed in
// the backend that holds their account
func changePasswordItem(t *term, s *settings, it *menuItem, sess *session, deadline time.Time) error {
if sess.Auth == "guest" {
return t.write("\r\nA guest has no password to change.\r\n")
}
end := time.Now().Add(s.loginTimeout)
if !deadline.IsZero() && deadline.Before(end) {
end = deadline
}
timeUp := func(err error) error {
if errors.Is(err, errTimeout) && !deadline.IsZero() && !time.Now().Before(deadline) {
return errTimeLimit
}
if errors.Is(err, errTimeout) || errors.Is(err, io.EOF) {
t.write("\r\nYour password is as it was.\r\n")
return nil
}
return err
}
if err := t.write("\r\nCurrent password: "); err != nil {
return err
}
old, err := t.readLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
// which backend holds the account: the one that takes the password
// (a login by caller ID or an upstream menu did not say)
ctx, cancel := context.WithDeadline(context.Background(), end.Add(10*time.Second))
defer cancel()
name, err := authenticate(ctx, s.backends, sess.User, old, logf)
if err != nil {
logf("passwd user=%s: current password wrong (%v)", sess.User, err)
time.Sleep(s.failDelay)
return t.write("That is not your password.\r\n")
}
var changer passwordChanger
for _, b := range s.backends {
if b.name() == name {
changer, _ = b.(passwordChanger)
if sa, ok := b.(*sqlAuth); ok && sa.updateQuery == "" {
changer = nil
}
}
}
if changer == nil {
logf("passwd user=%s: %s cannot change passwords", sess.User, name)
return t.write("Your password cannot be changed here. Ask the sysop.\r\n")
}
var pw string
for try := 0; ; try++ {
if try == 3 {
return t.write("Your password is as it was.\r\n")
}
if err := t.write("New password: "); err != nil {
return err
}
p, err := t.readLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
switch {
case p == "":
return t.write("Your password is as it was.\r\n")
case len(p) < it.minPassword:
t.write(fmt.Sprintf("At least %d characters, please.\r\n", it.minPassword))
continue
case p == old:
t.write("That is your password now; another one, please.\r\n")
continue
}
if err := t.write("Again: "); err != nil {
return err
}
again, err := t.readLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
if again != p {
t.write("They differ.\r\n")
continue
}
pw = p
break
}
if err := changer.changePassword(ctx, t, sess.User, old, pw); err != nil {
logf("passwd user=%s auth=%s: %v", sess.User, name, err)
if errors.Is(err, errRefused) {
return t.write("The new password was not accepted. Your password is as it was.\r\n")
}
return t.write("Sorry, your password cannot be changed now.\r\n")
}
sess.Password = pw
logf("passwd user=%s auth=%s: changed", sess.User, name)
return t.write("Your password is changed.\r\n")
}
// changePassword in the users file: the user's line rewritten in place
// (other lines as they are) under the lock signups take, the password as
// bcrypt (as text with hash = plain), a note after it kept
func (a *fileAuth) changePassword(_ context.Context, _ *term, user, old, new string) error {
f, err := os.OpenFile(a.path, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
st, err := f.Stat()
if err != nil {
return err
}
b := make([]byte, st.Size())
if _, err := f.ReadAt(b, 0); err != nil && err != io.EOF {
return err
}
stored := ""
if a.scheme == "plain" {
stored = new
} else {
h, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost)
if err != nil {
return err
}
stored = string(h)
}
lines := strings.Split(string(b), "\n")
found := false
for i, line := range lines {
t := strings.TrimSpace(line)
if t == "" || t[0] == '#' {
continue
}
name, rest, ok := strings.Cut(t, ":")
if !ok || name != user {
continue
}
// what follows the hash: user:hash:note (not after {SCHEME}text
// or with hash = plain, where the rest is the password)
note := ""
if a.scheme != "plain" && !strings.HasPrefix(rest, "{") {
if _, n, ok := strings.Cut(rest, ":"); ok {
note = ":" + n
}
}
lines[i] = name + ":" + stored + note
found = true
break
}
if !found {
return errNoUser
}
out := []byte(strings.Join(lines, "\n"))
if _, err := f.WriteAt(out, 0); err != nil {
return err
}
if err := f.Truncate(int64(len(out))); err != nil {
return err
}
return f.Sync()
}
// changePassword in the database: update_query with update_args, the
// password as update_hash says
func (a *sqlAuth) changePassword(ctx context.Context, _ *term, user, old, new string) error {
stored := new
if a.updateHash == "bcrypt" {
h, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost)
if err != nil {
return err
}
stored = string(h)
}
args := make([]any, len(a.updateArgs))
for i, arg := range a.updateArgs {
switch arg {
case "user":
args[i] = user
case "password":
args[i] = stored
case "old_password":
args[i] = old
}
}
ctx, cancel := context.WithTimeout(ctx, a.timeout)
defer cancel()
res, err := a.db.ExecContext(ctx, a.updateQuery, args...)
if err != nil {
return err
}
if n, err := res.RowsAffected(); err == nil && n != 1 {
return fmt.Errorf("update_query changed %d rows, not 1", n)
}
return nil
}
// changePassword by PAM: the service's password stack
func (a *systemAuth) changePassword(_ context.Context, t *term, user, old, new string) error {
return pamChangePassword(a.service, user, old, new, t)
}
-236
View File
@@ -1,236 +0,0 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// TestFileChangePassword: the users file's line of the user changed,
// the others and the notes after the hash kept
func TestFileChangePassword(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("# users\nalice:{PLAIN}old-pw\nbob:{PLAIN}bob-pw\ncarol:$2a$04$abcdefghijklmnopqrstuuJ8Jq7QF7mHNXgNnrBX3/7uJpH9fC2T6:signup 2026-10-12 5551234\n"), 0o600)
fa, err := newFileAuth(&section{name: "file", vals: map[string]string{"path": users}})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := fa.(*fileAuth).changePassword(ctx, nil, "alice", "old-pw", "new-pw-1"); err != nil {
t.Fatal(err)
}
if err := fa.authenticate(ctx, "alice", "new-pw-1"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := fa.authenticate(ctx, "alice", "old-pw"); !errors.Is(err, errBadPassword) {
t.Errorf("the old password: %v", err)
}
if err := fa.authenticate(ctx, "bob", "bob-pw"); err != nil {
t.Errorf("bob, untouched: %v", err)
}
// a note after the hash stays
if err := fa.(*fileAuth).changePassword(ctx, nil, "carol", "", "carol-new"); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(users)
lines := strings.Split(string(b), "\n")
if len(lines) != 5 || lines[0] != "# users" || !strings.HasPrefix(lines[1], "alice:$2a$") ||
lines[2] != "bob:{PLAIN}bob-pw" || !strings.HasSuffix(lines[3], ":signup 2026-10-12 5551234") || lines[4] != "" {
t.Errorf("users file:\n%s", b)
}
if err := fa.(*fileAuth).changePassword(ctx, nil, "dave", "", "x"); !errors.Is(err, errNoUser) {
t.Errorf("dave: %v", err)
}
// hash = plain: the password as text
os.WriteFile(users, []byte("erin:old:x\n"), 0o600)
fp, _ := newFileAuth(&section{name: "file", vals: map[string]string{"path": users, "hash": "plain"}})
fp.(*fileAuth).changePassword(ctx, nil, "erin", "old:x", "new")
if b, _ := os.ReadFile(users); string(b) != "erin:new\n" {
t.Errorf("plain: %q", b)
}
}
// TestSQLChangePassword: update_query changes the user's row only
func TestSQLChangePassword(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "users.db")
db, _ := sql.Open("sqlite", dbPath)
if _, err := db.Exec(`CREATE TABLE users (username TEXT, password TEXT);
INSERT INTO users VALUES ('carol', '{PLAIN}pw'), ('dave', '{PLAIN}pw');`); err != nil {
t.Fatal(err)
}
db.Close()
vals := map[string]string{"driver": "sqlite", "dsn": dbPath,
"query": "SELECT password FROM users WHERE username = ?"}
a, err := newSQLAuth(&section{name: "sql", vals: vals})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
vals["update_query"] = "UPDATE users SET password = ? WHERE username = ?"
a, _ = newSQLAuth(&section{name: "sql", vals: vals})
if err := a.(*sqlAuth).changePassword(ctx, nil, "carol", "pw", "carol-new"); err != nil {
t.Fatal(err)
}
if err := a.authenticate(ctx, "carol", "carol-new"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.authenticate(ctx, "dave", "pw"); err != nil {
t.Errorf("dave, untouched: %v", err)
}
if err := a.(*sqlAuth).changePassword(ctx, nil, "nobody", "pw", "x"); err == nil {
t.Error("no row: no error")
}
vals["update_args"] = "user nonsense"
if _, err := newSQLAuth(&section{name: "sql", vals: vals}); err == nil {
t.Error("update_args nonsense: no error")
}
}
// TestPasswdLine: on a line, a mode = passwd item changes the password
func TestPasswdLine(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, "modemmenu")
if out, err := runGo("build", "-o", bin, "."); err != nil {
t.Fatalf("build: %v\n%s", err, out)
}
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("alice:{PLAIN}old-password\n"), 0o600)
conf := filepath.Join(dir, "c.conf")
os.WriteFile(conf, []byte(fmt.Sprintf(`
[general]
log = %s
auth = file
fail_delay = 0
[file]
path = %s
[guest]
enabled = yes
[item passwd]
key = PW
label = Change your password
mode = passwd
guest = yes
[item info]
command = echo "PW=$MODEM_PASSWORD"
after = menu
`, filepath.Join(dir, "log"), users)), 0o600)
c, cmd := callAs(t, bin, conf)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("old-password\r")
c.expect("Selection: ")
c.send("pw\r")
c.expect("Current password: ")
c.send("wrong\r")
c.expect("That is not your password.")
c.expect("Selection: ")
c.send("passwd\r")
c.expect("Current password: ")
c.send("old-password\r")
c.expect("New password: ")
c.send("short\r")
c.expect("At least 8")
c.expect("New password: ")
c.send("old-password\r")
c.expect("another one")
c.expect("New password: ")
c.send("new-password\r")
c.expect("Again: ")
c.send("new-passwork\r")
c.expect("They differ.")
// three tries
c.expect("Your password is as it was.")
c.expect("Selection: ")
c.send("pw\r")
c.expect("Current password: ")
c.send("old-password\r")
c.expect("New password: ")
c.send("new-password\r")
c.expect("Again: ")
c.send("new-password\r")
c.expect("Your password is changed.")
c.expect("Selection: ")
// the selections after it get the new one
c.send("info\r")
c.expect("PW=new-password")
c.send("g\r")
waitExit(t, cmd)
c, cmd = callAs(t, bin, conf)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("old-password\r")
c.expect("Login incorrect")
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("new-password\r")
c.expect("Selection: ")
c.send("g\r")
waitExit(t, cmd)
// a guest has none
c, cmd = callAs(t, bin, conf)
c.expect("login: ")
c.send("guest\r")
c.expect("Selection: ")
c.send("pw\r")
c.expect("A guest has no password")
c.send("g\r")
waitExit(t, cmd)
log, _ := os.ReadFile(filepath.Join(dir, "log"))
for _, w := range []string{"passwd user=alice: current password wrong", "passwd user=alice auth=file: changed"} {
if !strings.Contains(string(log), w) {
t.Errorf("no %q in the log:\n%s", w, log)
}
}
if strings.Contains(string(log), "new-password") {
t.Errorf("a password in the log:\n%s", log)
}
}
// MODEMMENU_TEST_LDAP (see ldap_test.go), the server letting users write
// their own userPassword: lduser's password changed and back
func TestLDAPChangePassword(t *testing.T) {
url := os.Getenv("MODEMMENU_TEST_LDAP")
if url == "" {
t.Skip("MODEMMENU_TEST_LDAP is not set")
}
a, err := newLDAPAuth(&section{name: "ldap", vals: map[string]string{
"url": url, "search_base": "ou=people,dc=example,dc=com"}})
if err != nil {
t.Fatal(err)
}
la := a.(*ldapAuth)
ctx := context.Background()
if err := la.changePassword(ctx, nil, "lduser", "wrong", "x"); !errors.Is(err, errBadPassword) {
t.Errorf("a wrong current password: %v", err)
}
if err := la.changePassword(ctx, nil, "lduser", "ldpass", "ldpass-2"); err != nil {
t.Fatal(err)
}
if err := a.authenticate(ctx, "lduser", "ldpass-2"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.authenticate(ctx, "lduser", "ldpass"); err == nil {
t.Error("the old password still works")
}
if err := la.changePassword(ctx, nil, "lduser", "ldpass-2", "ldpass"); err != nil {
t.Errorf("back: %v", err)
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
-584
View File
@@ -1,584 +0,0 @@
// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bytes"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/sys/unix"
)
// What the caller's terminal is, asked as bbs-sec asks it, before the
// banner:
//
// - ANSI: the cursor moved as far as it goes and its position asked for
// (CSI 6n). An ANSI terminal answers, and the answer is its size.
// - VT52, when not ANSI: ESC Z, which a VT52 answers with ESC / and a
// letter.
// - What an ANSI terminal is: DEC's questions (the answerback, DA1, DA2),
// xterm's version (XTVERSION) and SyncTERM's CTerm attributes.
// - PETSCII, when not ANSI: a Commodore asks nothing and answers nothing;
// its keys tell (DEL, the cursor keys, its shifted letters), or a name
// typed all in capitals and the DEL key pressed when asked.
// terminalSettings: [terminal]
type terminalSettings struct {
detect bool // ask: ANSI, VT52, an ANSI terminal's identity
petscii string // auto (a terminal that is not ANSI may be one), yes (every caller), no
timeout time.Duration
}
// loadTerminal: [terminal], checked
func loadTerminal(sec *section) (terminalSettings, error) {
var err error
ts := terminalSettings{
petscii: strings.ToLower(sec.get("petscii", "auto")),
}
if ts.detect, err = sec.bool("detect", true); err != nil {
return ts, err
}
if ts.timeout, err = sec.duration("timeout", 2*time.Second); err != nil {
return ts, err
}
switch ts.petscii {
case "auto", "yes", "no":
default:
return ts, fmt.Errorf("[terminal] petscii: %q (auto, yes or no)", ts.petscii)
}
return ts, nil
}
// the questions, and the patterns of their answers
const (
// the cursor saved, as far down and right as it goes, its position
// asked, restored: the answer is the screen's size
queryANSI = "\x1b7\x1b[999;999H\x1b[6n\x1b8"
// the answerback (ENQ), DA1, DA2, XTVERSION, and last the cursor's
// position, which every ANSI terminal answers: once it comes, whatever
// else would has
queryVT = "\x05\x1b[c\x1b[>c\x1b[>0q\x1b[6n"
queryVT52 = "\x1bZ"
)
var (
da1Pattern = regexp.MustCompile(`\x1b\[\?([0-9;]*)c`)
da2Pattern = regexp.MustCompile(`\x1b\[>([0-9;]*)c`)
ctermPat = regexp.MustCompile(`\x1b\[=([0-9;]*)c`)
xtverPat = regexp.MustCompile(`\x1bP>\|([^\x1b\x07]{0,80})\x1b\\`)
cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`)
vt52Pattern = regexp.MustCompile(`\x1b/([A-Za-z])`)
// all the answers, to take them out of what the caller typed
answers = []*regexp.Regexp{da1Pattern, da2Pattern, ctermPat, xtverPat, cprPattern, vt52Pattern}
)
// vtInfo: what an ANSI terminal said of itself
type vtInfo struct {
answerback string // ENQ's answer
da1 []int // the class (1, 6, 62-65) and options
da2 []int // the model, its firmware version, options
version string // XTVERSION's "name(version)"
cterm string // SyncTERM's CTerm version
}
// parseVT: what an ANSI terminal answered to queryVT
func parseVT(reply []byte) vtInfo {
var in vtInfo
// the answerback is what came before the first escape sequence
ab := reply
if i := bytes.IndexByte(ab, 0x1b); i >= 0 {
ab = ab[:i]
}
in.answerback = printable(string(ab), 40)
if m := da1Pattern.FindSubmatch(reply); m != nil {
in.da1 = numbers(string(m[1]))
}
if m := da2Pattern.FindSubmatch(reply); m != nil {
in.da2 = numbers(string(m[1]))
}
if m := xtverPat.FindSubmatch(reply); m != nil {
in.version = printable(string(m[1]), 60)
}
if m := ctermPat.FindSubmatch(reply); m != nil {
// "CTerm" in decimal character codes, then the version
ns := numbers(string(m[1]))
if len(ns) >= 5 && string([]byte{byte(ns[0]), byte(ns[1]), byte(ns[2]), byte(ns[3]), byte(ns[4])}) == "CTerm" {
var v []string
for _, n := range ns[5:] {
v = append(v, strconv.Itoa(n))
}
if in.cterm = strings.Join(v, "."); in.cterm == "" {
in.cterm = "?"
}
}
}
return in
}
// numbers: a sequence's ;-separated parameters (32 at most)
func numbers(s string) []int {
var out []int
for _, f := range strings.Split(s, ";") {
n, err := strconv.Atoi(f)
if err != nil || n < 0 || n > 1<<20 {
continue
}
if out = append(out, n); len(out) == 32 {
break
}
}
return out
}
// printable: s's printable ASCII, at most max bytes, trimmed
func printable(s string, max int) string {
var b strings.Builder
for _, r := range s {
if r >= 0x20 && r < 0x7f && b.Len() < max {
b.WriteRune(r)
}
}
return strings.TrimSpace(b.String())
}
// level: the VT level: 1 a VT100 or VT102, 2 a VT220, 3 VT320, 4 VT420,
// 5 VT510 and later; 0 if it did not say
func (in vtInfo) level() int {
if len(in.da1) == 0 {
return 0
}
switch c := in.da1[0]; {
case c >= 61 && c <= 69:
return c - 60
case c == 1 || c == 6 || c == 4 || c == 7 || c == 12:
return 1
}
return 0
}
// DA2's model numbers of DEC's own terminals, and those emulators give
var (
decModels = map[int]string{
0: "VT100", 1: "VT220", 2: "VT240", 18: "VT330", 19: "VT340", 24: "VT320",
28: "DECterm", 32: "VT382", 41: "VT420", 61: "VT510", 64: "VT520", 65: "VT525",
}
emulators = map[int]string{77: "mintty", 82: "rxvt", 83: "screen", 84: "tmux", 85: "rxvt-unicode"}
)
// hardware: a DEC terminal by its DA2 (a model of DEC's, a small firmware
// version), not an emulator that says its name otherwise
func (in vtInfo) hardware() bool {
if in.version != "" || in.cterm != "" || len(in.da2) < 2 {
return false
}
_, dec := decModels[in.da2[0]]
return dec && in.da2[1] < 95
}
// emulator: a program on a computer (xterm, VTE, SyncTERM...), not a VT
func (in vtInfo) emulator() bool {
if in.version != "" || in.cterm != "" {
return true
}
if len(in.da2) >= 2 && !in.hardware() {
p, v := in.da2[0], in.da2[1]
return emulators[p] != "" || p == 41 && v >= 95 || (p == 1 || p == 65) && v >= 1000
}
return false
}
// name: what the terminal is, as best it said
func (in vtInfo) name() string {
switch {
case in.version != "":
return in.version
case in.cterm != "":
return "SyncTERM (CTerm " + in.cterm + ")"
case in.hardware():
return decModels[in.da2[0]]
}
if len(in.da2) >= 2 {
p, v := in.da2[0], in.da2[1]
switch {
case emulators[p] != "":
return emulators[p]
case p == 41 && v >= 95:
return fmt.Sprintf("xterm (patch %d)", v)
case (p == 1 || p == 65) && v >= 1000:
return "VTE"
}
}
if in.answerback != "" {
return in.answerback
}
switch l := in.level(); {
case l == 1 && in.da1[0] == 6:
return "VT102"
case l == 1:
return "VT100"
case l >= 2:
return fmt.Sprintf("VT%d00 class", l)
}
return ""
}
// term: a TERM for it: syncterm, xterm for the other emulators, a VT's
// own (vt100, vt220...), ansi when it did not say
func (in vtInfo) term() string {
switch {
case in.cterm != "":
return "syncterm"
case in.emulator():
return "xterm"
case in.hardware():
switch m := in.da2[0]; {
case m == 0:
return "vt100"
case m == 1 || m == 2:
return "vt220"
case m >= 18 && m <= 32:
return "vt320"
case m == 41:
return "vt420"
default:
return "vt520"
}
}
switch l := in.level(); {
case l == 1 && in.da1[0] == 6:
return "vt102"
case l == 1:
return "vt100"
case l == 2:
return "vt220"
case l == 3:
return "vt320"
case l == 4:
return "vt420"
case l >= 5:
return "vt520"
}
return "ansi"
}
// petsciiTelltale: a byte only a Commodore's keys send: DEL, the cursor
// keys, CLR, the function keys, a shifted letter
func petsciiTelltale(b byte) bool {
switch {
case b == 0x14, b == 0x91, b == 0x1D, b == 0x9D, b == 0x93:
return true
case b >= 0x85 && b <= 0x8C:
return true
case b >= 0xC1 && b <= 0xDA:
return true
}
return false
}
// prober: the questions of one call, and what came that was no answer
// (what the caller typed, a PPP frame) to be read again after
type prober struct {
t *term
extra []byte
ppp bool // a PPP frame came: ask nothing more
}
// collect what comes until done, max bytes or timeout
func (p *prober) collect(timeout time.Duration, max int, done func([]byte) bool) ([]byte, error) {
var got []byte
end := time.Now().Add(timeout)
for len(got) < max {
left := time.Until(end)
if left <= 0 {
break
}
c, err := p.t.readByte(left)
if errors.Is(err, errTimeout) {
break
}
if err != nil {
return got, err
}
got = append(got, c)
if done(got) {
break
}
if n := len(got); n >= 3 && pppFrame(got[n-3:]) {
break // a dialer's PPP: no answer will come
}
}
return got, nil
}
// keep what is no answer to the questions
func (p *prober) keep(b []byte) {
for _, re := range answers {
b = re.ReplaceAll(b, nil)
}
p.extra = append(p.extra, b...)
for i := range p.extra {
if pppFrame(p.extra[i:]) {
p.ppp = true
}
}
}
// done: what was no answer, read again by the login
func (p *prober) done() { p.t.unread(p.extra...) }
// ansi: the position after the cursor went as far as it goes: whether the
// terminal answered, and its size
func (p *prober) ansi(timeout time.Duration) (bool, int, int, error) {
if err := p.t.writeRaw(queryANSI); err != nil {
return false, 0, 0, err
}
got, err := p.collect(timeout, 64, cprPattern.Match)
if err != nil {
return false, 0, 0, err
}
m := cprPattern.FindSubmatch(got)
p.keep(got)
if m == nil {
// a plain terminal shows the question as text: wiped
return false, 0, 0, p.t.writeRaw("\r" + strings.Repeat(" ", 20) + "\r")
}
rows, _ := strconv.Atoi(string(m[1]))
cols, _ := strconv.Atoi(string(m[2]))
if rows < 10 || rows > 200 {
rows = 0
}
if cols < 40 || cols > 300 {
cols = 0
}
return true, rows, cols, nil
}
// vt52: whether ESC Z is answered as a VT52 answers it; any other shows
// a Z, which is wiped
func (p *prober) vt52(timeout time.Duration) (bool, error) {
if err := p.t.writeRaw(queryVT52); err != nil {
return false, err
}
got, err := p.collect(timeout, 16, vt52Pattern.Match)
if err != nil {
return false, err
}
is := vt52Pattern.Match(got)
p.keep(got)
if !is {
return false, p.t.writeRaw("\r \r")
}
return true, nil
}
// identify: what an ANSI terminal says it is
func (p *prober) identify(timeout time.Duration) (vtInfo, error) {
if err := p.t.writeRaw(queryVT); err != nil {
return vtInfo{}, err
}
got, err := p.collect(timeout, 1024, cprPattern.Match)
if err != nil {
return vtInfo{}, err
}
in := parseVT(got)
// the answerback is no key the caller typed
if i := bytes.IndexByte(got, 0x1b); i > 0 && in.answerback != "" {
got = got[i:]
}
p.keep(got)
return in, nil
}
// detectTerminal: what the caller's terminal is, in sess (Terminal, Term,
// TermName, Rows, Cols), the line set for it
func detectTerminal(t *term, s *settings, sess *session) error {
ts := s.terminal
defer func() {
if sess.Terminal == "petscii" {
t.setPETSCII()
}
if sess.Rows != "" && sess.Cols != "" {
rows, _ := strconv.Atoi(sess.Rows)
cols, _ := strconv.Atoi(sess.Cols)
// the line's size, for what a selection runs on it
unix.IoctlSetWinsize(t.in, unix.TIOCSWINSZ, &unix.Winsize{Row: uint16(rows), Col: uint16(cols)})
}
}()
switch {
case sess.Terminal != "":
// an upstream menu said
return nil
case ts.petscii == "yes":
sess.Terminal, sess.Term, sess.Rows, sess.Cols = "petscii", "dumb", "25", "40"
return nil
}
p := &prober{t: t}
defer p.done()
if !ts.detect || p.ppp {
// not asked: perhaps a Commodore, whose keys will tell
t.watchPETSCII = ts.petscii == "auto" && !p.ppp
return nil
}
ansi, rows, cols, err := p.ansi(ts.timeout)
if err != nil || p.ppp {
return err
}
if !ansi {
is52, err := p.vt52(ts.timeout / 2)
if err != nil || p.ppp {
return err
}
if is52 {
sess.Terminal, sess.Term, sess.TermName, sess.Rows, sess.Cols = "vt52", "vt52", "VT52", "24", "80"
return nil
}
sess.Terminal, sess.Term = "ascii", "dumb"
// perhaps a Commodore: its keys will tell
t.watchPETSCII = ts.petscii == "auto"
return nil
}
sess.Terminal, sess.Term = "ansi", "ansi"
if rows > 0 && cols > 0 {
sess.Rows, sess.Cols = strconv.Itoa(rows), strconv.Itoa(cols)
}
in, err := p.identify(ts.timeout)
if err != nil {
return err
}
if n := in.name(); n != "" {
sess.TermName = n
}
sess.Term = in.term()
if in.level() > 0 || in.emulator() {
sess.Terminal = "vt"
}
return nil
}
// becomePETSCII: the caller has a Commodore after all
func becomePETSCII(t *term, sess *session) {
t.watchPETSCII = false
sess.Terminal, sess.Term, sess.Rows, sess.Cols = "petscii", "dumb", "25", "40"
unix.IoctlSetWinsize(t.in, unix.TIOCSWINSZ, &unix.Winsize{Row: 25, Col: 40})
t.setPETSCII()
logf("terminal: a Commodore (PETSCII) %v", sess)
}
// settlePETSCII: a name typed all in capitals, while it is not known
// whether the terminal is a Commodore: a Commodore's unshifted keys, or
// ASCII in capitals, and DEL tells which. The name as the caller meant
// it.
func settlePETSCII(t *term, s *settings, sess *session, name string, deadline time.Time) (string, error) {
t.watchPETSCII = false
if strings.ToUpper(name) != name || strings.ToLower(name) == name {
return name, nil // lower case, or no letters
}
if err := t.write("PRESS DEL (OR BACKSPACE): "); err != nil {
return "", err
}
wait := min(30*time.Second, time.Until(deadline))
c, err := t.readByte(wait)
if err != nil && !errors.Is(err, errTimeout) {
return "", err
}
t.write("\r\n")
if c != 0x14 {
return name, nil
}
becomePETSCII(t, sess)
// its unshifted letters are lower case
name = strings.ToLower(name)
t.write(s.loginPrompt + name + "\r\n")
return name, nil
}
// describeTerminal: for the log
func (s *session) describeTerminal() string {
d := s.Terminal
if s.TermName != "" {
d += " (" + s.TermName + ")"
}
if s.Rows != "" {
d += " " + s.Cols + "x" + s.Rows
}
return d
}
// petsciiOut: what the menu writes, for a Commodore in its lower/upper
// case set: the letters' cases swapped as that set has them, a line end
// as RETURN, backspace as cursor left, escape sequences and what it has
// not dropped
func petsciiOut(s string) []byte {
out := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == 0x1b:
// an escape sequence: CSI's parameters to its final byte, or
// one character
if i+1 < len(s) && s[i+1] == '[' {
i += 2
for i < len(s) && (s[i] < 0x40 || s[i] > 0x7e) {
i++
}
} else {
i++
}
case c == '\r':
out = append(out, 0x0d)
if i+1 < len(s) && s[i+1] == '\n' {
i++
}
case c == '\n':
out = append(out, 0x0d)
case c == 0x08:
out = append(out, 0x9d)
case c >= 'a' && c <= 'z':
out = append(out, c-'a'+0x41)
case c >= 'A' && c <= 'Z':
out = append(out, c-'A'+0xc1)
case c == '{':
out = append(out, '(')
case c == '}':
out = append(out, ')')
case c == '|':
out = append(out, '!')
case c == '~':
out = append(out, '-')
case c == '`':
out = append(out, '\'')
case c == '\\':
out = append(out, '/')
case c == '_':
out = append(out, '-')
case c >= 0x20 && c < 0x7f:
out = append(out, c)
case c >= 0xc0:
// a rune of UTF-8: one character the C64 has not
out = append(out, '?')
}
}
return out
}
// petsciiIn: a Commodore's key as ASCII: its unshifted letters lower
// case, its shifted ones upper case, DEL as DEL
func petsciiIn(c byte) byte {
switch {
case c >= 0x41 && c <= 0x5a:
return c - 0x41 + 'a'
case c >= 0xc1 && c <= 0xda:
return c - 0xc1 + 'A'
case c >= 0x61 && c <= 0x7a:
return c - 0x61 + 'A'
case c == 0x14:
return 0x7f
}
return c
}
+5 -5
View File
@@ -4,11 +4,11 @@
// Command confref writes docs/reference.md, the configuration reference:
// every section and key of modemmenu.conf, with the help, the sample's
// value and the other values the sample shows, all read from the comments
// of modemmenu.conf.sample. From the repository's root:
// of samples/modemmenu.conf.sample. From the repository's root:
//
// go run ./tools/confref
//
// TestSampleHasEveryKey (config_test.go) keeps the sample complete: a key
// TestSampleHasEveryKey (cmd/modemmenu/reference_test.go) keeps the sample complete: a key
// the code reads that the sample doesn't show fails it.
package main
@@ -241,12 +241,12 @@ func prose(s string) string {
func reference(kinds []*kind) string {
var b strings.Builder
b.WriteString(`<!-- Made by go run ./tools/confref from modemmenu.conf.sample: edit the sample, not this page. -->
b.WriteString(`<!-- Made by go run ./tools/confref from samples/modemmenu.conf.sample: edit the sample, not this page. -->
# Configuration reference
Every section and key of modemmenu.conf, from the comments in
[modemmenu.conf.sample](https://github.com/D-Modem/menu/blob/main/modemmenu.conf.sample).
[modemmenu.conf.sample](https://github.com/D-Modem/menu/blob/main/samples/modemmenu.conf.sample).
**Sample** is the value the sample sets (or shows, commented out);
[Configuration](configuration.md) explains the file and its sections in
full.
@@ -300,7 +300,7 @@ full.
}
func main() {
sample, err := os.ReadFile("modemmenu.conf.sample")
sample, err := os.ReadFile("samples/modemmenu.conf.sample")
if err != nil {
log.Fatal(err)
}