Unix sockets: modemmenu -serve, and items that connect to one

modemmenu -serve listens on [server] listen, a unix socket (or
tcp:host:port), for app_dmodem's mode = unix profiles: each connection
gets a session of its own, modemmenu on a new pty as mode = exec would
give it, so pppd, shells and ^C work the same.  A socket has no
environment: the call's details come first as a header, NAME=value
lines and an empty line (app_dmodem's header = yes).  socket_mode and
socket_group decide who may connect, max_sessions caps them, SIGTERM
hangs them all up and removes the socket.

Menu items reach other menu applications on unix sockets: mode = unix
(raw), or a path on tcp, telnet and rlogin items, and header = yes sends
the session ahead.  A modemmenu -serve with trust_user takes the user of
such a header as logged in, so a caller moves from one menu to another
without a second login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RvtV8Dg9kqRaakbTEfyH3f
This commit is contained in:
Claude committed 2026-10-10 16:25:46 +00:00
1 parent 23b70c6a9a
commit a5a55575af
9 files changed
+826 -34

No files matched your search

+102 -4
View File
@@ -35,8 +35,15 @@ and time of the connection.
## Running it from app_dmodem
`app_dmodem`, the Asterisk module of
[D-Modem-RE](https://github.com/Neo-Desktop/D-Modem-RE) (`asterisk/`), runs
it as a `mode = exec` program on the caller's line:
[D-Modem-RE](https://github.com/Neo-Desktop/D-Modem-RE) (`asterisk/`),
hands it the caller's line in one of two ways: it starts modemmenu for
each call (`mode = exec`), or connects each call to one `modemmenu
-serve` on a unix socket (`mode = unix`, below).
### A program for each call
app_dmodem runs modemmenu as a `mode = exec` program on the caller's
line:
```
; dmodem.conf
@@ -58,6 +65,54 @@ set these instead, e.g. under a getty on another modem.
The line is raw (app_dmodem's pty): modemmenu echoes and edits what the
caller types itself. Its exit, like the selection's, hangs up the call.
### One server on a unix socket
`modemmenu -serve` listens on `[server] listen` (a unix socket, or
`tcp:host:port`) and app_dmodem connects each call to it:
```
; dmodem.conf
[menu]
mode = unix
path = /run/modemmenu/modemmenu.sock
header = yes
; modemmenu.conf
[server]
listen = /run/modemmenu/modemmenu.sock
socket_mode = 0660
socket_group = asterisk
```
A socket has no environment, so app_dmodem's `header = yes` sends the
call's details first: `DMODEM_CHANNEL`, `DMODEM_PROFILE`, `DMODEM_RATE`,
`DMODEM_CALLERID`, `DMODEM_DIALED` and `DMODEM_CONNECTED` (Unix time),
one `NAME=value` per line, then an empty line, then the caller's bytes.
`[server] header = yes` (the default) reads it; with `header = no` the
caller's bytes come from the start and the details are unknown.
Each connection gets a session of its own: a new pty with modemmenu on
it, as `mode = exec` would give it, so pppd, shells and `^C` work the
same. The caller hanging up hangs up the pty; the session ending closes
the connection, which hangs up the call.
| `[server]` option | default | |
|---|---|---|
| `listen` | `/run/modemmenu/modemmenu.sock` | a unix socket's path, or `tcp:host:port` |
| `socket_mode` | `0660` | the socket's permissions: who may connect |
| `socket_group` | | the socket's group, e.g. Asterisk's |
| `header` | `yes` | read the session header first |
| `header_timeout` | `10` | seconds for the header to come |
| `trust_user` | `no` | a header's `MODEM_USER` is logged in already (below) |
| `max_sessions` | `32` | sessions at once; more callers hear the lines are busy |
`-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
systemd, which also makes `/run/modemmenu`. Each connection is logged
with its peer's pid and uid.
## Building
Go 1.22 or later:
@@ -235,10 +290,46 @@ How it reaches each kind of selection:
- **tcp** and **telnet**: `send`, e.g. `send = "{user}\r{password}\r"`,
is sent once connected; telnet negotiates binary, echo and the
terminal type.
- **unix**: like **tcp**, raw, to a server on the unix socket `path`.
`tcp`, `telnet` and `rlogin` items take a `path` too, for their
protocol on a unix socket.
- **header** (`header = yes`, on any of the socket kinds): the session
first, `MODEM_*` `NAME=value` lines and an empty line (the password
only with `pass_password`), before `send` or the protocol.
`after = menu` returns to the menu when the selection ends, `after =
hangup` (the default) hangs up.
### Handing a caller to another menu
An item can hand the caller to another menu application on a unix
socket. To another `modemmenu -serve`, with the session header and that
server's `trust_user = yes`, the caller stays logged in: it shows its own
banner, welcome and menu, with the user, the password (with
`pass_password`), `MODEM_AUTH` as `upstream:<backend>`, and the call's
rate, number and time from the header.
```
; the front menu
[item more]
key = M
label = More services
mode = unix
path = /run/modemmenu/more.sock
header = yes
after = menu
; the other menu's modemmenu.conf
[server]
listen = /run/modemmenu/more.sock
trust_user = yes
socket_mode = 0600
```
`trust_user` believes whoever can connect: keep that socket to the front
menu's user (`socket_mode`, `socket_group`). Without it, the other menu
asks the caller to log in again.
## Security notes
- Asterisk usually runs as its own user: the users file (and
@@ -252,6 +343,10 @@ hangup` (the default) hangs up.
if the program reads the file instead.
- Never put `{password}` in a command line: other users see the
arguments of every process. Use `MODEM_PASSWORD` or the session file.
- A server's socket is only as safe as its permissions: anyone who can
connect gets a login prompt, and with `trust_user` a login as whoever
they name. Keep `socket_mode` and `socket_group` to Asterisk or the
front menu.
- The log (syslog's auth facility by default) gets logins, failures and
selections, never passwords. It is never the line: the caller would
see it.
@@ -263,8 +358,11 @@ the menu's choices and the telnet client, and runs modemmenu on a pty as
app_dmodem does: a wrong and a right login, the message of the day,
choices by key, name and alias, an unknown choice and `?`, an rlogin BBS
and back to the menu, a cooked shell, and an exec selection's
environment and session file. The system backend's uid, root and group
rules are tested with PAM replaced.
environment and session file. It also runs `modemmenu -serve` on a unix
socket: a session from an app_dmodem header (on a pty of its own), a
caller hanging up, another modemmenu handing a logged-in caller over by
a `mode = unix` item, and `SIGTERM`. The system backend's uid, root and
group rules are tested with PAM replaced.
Two more tests run when their servers are given:
+8 -23
View File
@@ -3,6 +3,7 @@ package main
import (
"bytes"
"fmt"
"io"
"net"
"os"
"os/exec"
@@ -11,42 +12,26 @@ import (
"syscall"
"testing"
"time"
"golang.org/x/sys/unix"
)
// openPty: master and slave of a new pty, raw as app_dmodem makes it
func openPty(t *testing.T) (*os.File, *os.File) {
m, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY, 0)
// testPty: master and slave of a new pty, raw as app_dmodem makes it
func testPty(t *testing.T) (*os.File, *os.File) {
m, s, err := openPty()
if err != nil {
t.Skip("no pty:", err)
}
if err := unix.IoctlSetPointerInt(int(m.Fd()), unix.TIOCSPTLCK, 0); err != nil {
t.Fatal(err)
}
n, err := unix.IoctlGetInt(int(m.Fd()), unix.TIOCGPTN)
if err != nil {
t.Fatal(err)
}
s, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR|syscall.O_NOCTTY, 0)
if err != nil {
t.Fatal(err)
}
tio, _ := unix.IoctlGetTermios(int(s.Fd()), unix.TCGETS)
makeRaw(tio)
unix.IoctlSetTermios(int(s.Fd()), unix.TCSETS, tio)
return m, s
}
// caller: the remote end of the line
type caller struct {
t *testing.T
m *os.File
m io.ReadWriter
in chan []byte
buf bytes.Buffer
}
func newCaller(t *testing.T, m *os.File) *caller {
func newCaller(t *testing.T, m io.ReadWriter) *caller {
c := &caller{t: t, m: m, in: make(chan []byte, 64)}
go func() {
for {
@@ -170,7 +155,7 @@ tty = sane
command = env > %s; cat "$MODEM_SESSION_FILE" >> %s; echo args: {user} {baud} {dialed}; read x; echo "read $x"
`, filepath.Join(dir, "log"), filepath.Join(dir, "motd"), users, ln.Addr().(*net.TCPAddr).Port, envOut, envOut)), 0o600)
m, s := openPty(t)
m, s := testPty(t)
defer m.Close()
cmd := exec.Command(bin, "-config", conf)
cmd.Stdin, cmd.Stdout, cmd.Stderr = s, s, s
@@ -271,7 +256,7 @@ func TestHangup(t *testing.T) {
conf := filepath.Join(dir, "modemmenu.conf")
os.WriteFile(conf, []byte("[general]\nlog = none\n[file]\npath = "+users+
"\n[item ppp]\ncommand = exec true\n"), 0o600)
m, s := openPty(t)
m, s := testPty(t)
cmd := exec.Command(bin, "-config", conf)
cmd.Stdin, cmd.Stdout, cmd.Stderr = s, s, s
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
+14 -3
View File
@@ -150,15 +150,26 @@ func running(p *os.Process) {
childMu.Unlock()
}
// runTCP: the caller's line to a server: raw TCP, telnet or rlogin
// 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) error {
v := s.vars(it.password)
addr := net.JoinHostPort(it.host, strconv.Itoa(it.port))
conn, err := net.DialTimeout("tcp", addr, it.timeout)
network, addr := "tcp", net.JoinHostPort(it.host, strconv.Itoa(it.port))
if it.path != "" {
network, addr = "unix", it.path
}
conn, err := net.DialTimeout(network, addr, it.timeout)
if err != nil {
return err
}
defer conn.Close()
if it.header {
// the session ahead of the protocol: for a modemmenu -serve, or
// any program that reads it
if err := writeHeader(conn, s, it.password); err != nil {
return err
}
}
var tn *telnet
switch it.mode {
+26 -3
View File
@@ -17,6 +17,7 @@ import (
"log/syslog"
"os"
"os/signal"
"strconv"
"strings"
"sync/atomic"
"syscall"
@@ -37,6 +38,9 @@ func main() {
callerID := flag.String("callerid", os.Getenv("DMODEM_CALLERID"), "the caller's `number` (default $DMODEM_CALLERID)")
check := flag.Bool("check", false, "check the configuration and exit")
hash := flag.Bool("hash", false, "read a password, print its bcrypt hash for the users file and exit")
serveFlag := flag.Bool("serve", false, "serve sessions on the [server] listen socket")
listenAt := flag.String("listen", "", "with -serve: listen on this unix socket `path` (or tcp:host:port) instead of [server] listen")
upstreamFlag := flag.Bool("upstream", false, "a session of -serve with trust_user (internal)")
flag.Parse()
if *hash {
@@ -54,7 +58,22 @@ func main() {
if err := openLog(s.log); err != nil {
fmt.Fprintln(os.Stderr, "modemmenu: log:", err)
}
sess := newSession(*rate, *dialed, *callerID, time.Now())
if *serveFlag {
if *listenAt != "" {
s.server.listen = *listenAt
}
os.Exit(serve(s, *config))
}
handleSignals()
connected := time.Now()
if e, err := strconv.ParseInt(os.Getenv("DMODEM_CONNECTED"), 10, 64); err == nil && e > 0 {
connected = time.Unix(e, 0)
}
sess := newSession(*rate, *dialed, *callerID, connected)
if upstream(sess, *upstreamFlag) && !s.userPattern.MatchString(sess.User) {
logf("upstream user %q: not a name we take", sess.User)
sess.User, sess.Password, sess.Auth = "", "", ""
}
t := newTerm(os.Stdin, os.Stdout)
code := run(t, s, sess)
t.close()
@@ -64,7 +83,7 @@ func main() {
// terminated: SIGTERM or SIGHUP came
var terminated atomic.Bool
func init() {
func handleSignals() {
// a selection on a cooked line gets ^C and ^\ from the terminal, and
// so would we: caught (not ignored, which the selection would inherit)
// and dropped. A shell that took the terminal for a job of its own
@@ -82,6 +101,7 @@ func init() {
p := child
childMu.Unlock()
if p == nil {
logf("%v: hung up", sig)
os.Exit(1)
}
// the program ends, its session file is removed, then us
@@ -149,7 +169,10 @@ func run(t *term, s *settings, sess *session) int {
if t.write(expand(s.banner, sess.vars(false), nil)) != nil {
return 1
}
if err := login(t, s, sess); err != nil {
if sess.User != "" {
// an upstream menu logged the caller in
logf("login user=%s auth=%s %v", sess.User, sess.Auth, sess)
} else if err := login(t, s, sess); err != nil {
if !errors.Is(err, errHangup) {
t.write("\r\n")
}
+44
View File
@@ -7,6 +7,13 @@
; mode = exec
; command = exec /usr/local/bin/modemmenu -config /etc/asterisk/modemmenu.conf
;
; or one modemmenu -serve serves every call on a unix socket ([server]):
;
; [menu]
; mode = unix
; path = /run/modemmenu/modemmenu.sock
; header = yes
;
; Values may be "quoted" to keep spaces at their ends; \r \n \t \e and \xHH
; are those bytes in the texts of [general] and [menu] and in send.
;
@@ -121,6 +128,26 @@ hash = auto
;dsn = /var/lib/asterisk/users.db
;query = SELECT password FROM users WHERE username = ?
; modemmenu -serve: one modemmenu for all calls, on a unix socket (or
; tcp:host:port). Each connection gets a session of its own on a new pty,
; as app_dmodem's mode = exec would give it
[server]
listen = /run/modemmenu/modemmenu.sock
; the socket's permissions: who may connect (app_dmodem: Asterisk's group)
socket_mode = 0660
;socket_group = asterisk
; the call's details come first on each connection, NAME=value lines and an
; empty line: app_dmodem's header = yes (DMODEM_*), or a menu item's
; header = yes (MODEM_*). no: the caller's bytes from the start
header = yes
header_timeout = 10
; yes: a header with MODEM_USER (another modemmenu's item, header = yes)
; logs the caller in without asking again. Only for a socket that nothing
; but trusted menus can connect to
trust_user = no
; connections at once; more are told the lines are busy
max_sessions = 32
[menu]
title = "\r\nMain menu\r\n"
prompt = "\r\nSelection: "
@@ -140,6 +167,9 @@ hotkeys = no
; label = ... its line in the menu
; mode = exec a program on the line: command (by /bin/sh -c)
; tcp a TCP server, raw: host, port; send is sent first
; unix a server on a unix socket, raw: path; send too
; (tcp, telnet and rlogin take a path as well, for
; their protocol on a unix socket)
; telnet a telnet server: host, port (23), terminal (ANSI)
; rlogin an rlogin server: host, port (513), and
; rlogin_client_user ({password}), rlogin_server_user
@@ -152,6 +182,10 @@ hotkeys = no
; in MODEM_SESSION_FILE (removed after)
; after = hangup when the item ends: hang up, or back to the menu
; connect_timeout = 10 seconds to reach a server
; header = no tcp, unix, telnet, rlogin: yes sends the session
; first, MODEM_* NAME=value lines and an empty line
; (the password only with pass_password), for
; modemmenu -serve or any program that reads it
; A BBS by rlogin: Synchronet and Mystic log the caller in with the user
; name as the server user and the password as the client user
@@ -189,3 +223,13 @@ tty = sane
pass_password = no
command = exec "$SHELL" -l
after = menu
; another menu: a modemmenu -serve with trust_user, which takes the caller
; as logged in here
;[item more]
;key = M
;label = More services
;mode = unix
;path = /run/modemmenu/more.sock
;header = yes
;after = menu
+18
View File
@@ -0,0 +1,18 @@
# /etc/systemd/system/modemmenu.service - modemmenu -serve for app_dmodem's
# mode = unix profiles (dmodem.conf: path = /run/modemmenu/modemmenu.sock,
# header = yes); [server] socket_group = asterisk lets Asterisk connect
[Unit]
Description=modemmenu: login and menu for dial-up callers
Before=asterisk.service
[Service]
ExecStart=/usr/local/bin/modemmenu -config /etc/asterisk/modemmenu.conf -serve
RuntimeDirectory=modemmenu
RuntimeDirectoryMode=0755
Restart=on-failure
# root for auth = system (PAM's pam_unix) and run_as; otherwise a user of
# its own, e.g. User=modemmenu
User=root
[Install]
WantedBy=multi-user.target
+356
View File
@@ -0,0 +1,356 @@
package main
import (
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/signal"
"os/user"
"strconv"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// The session header: the details of a call, ahead of the caller's bytes
// on a socket (which has no environment to carry them). KEY=value lines
// ending in an empty line; app_dmodem (header = yes) sends DMODEM_* keys,
// a modemmenu item (header = yes) MODEM_* keys.
const (
headerMaxLines = 64
headerMaxBytes = 8192
)
// writeHeader: the header of the session, MODEM_* (with the password when
// withPassword)
func writeHeader(w io.Writer, s *session, withPassword bool) error {
var b strings.Builder
for _, kv := range s.environ(withPassword) {
k, v, _ := strings.Cut(kv, "=")
b.WriteString(k + "=" + headerValue(v) + "\n")
}
b.WriteString("\n")
_, err := io.WriteString(w, b.String())
return err
}
// headerValue: a value on one line
func headerValue(v string) string {
return strings.Map(func(r rune) rune {
if r == '\r' || r == '\n' || r == 0 {
return ' '
}
return r
}, v)
}
// readHeader from r one byte at a time (what follows it is the caller's),
// until the empty line or the deadline
func readHeader(conn net.Conn, timeout time.Duration) (map[string]string, error) {
conn.SetReadDeadline(time.Now().Add(timeout))
defer conn.SetReadDeadline(time.Time{})
h := map[string]string{}
var line []byte
total := 0
b := make([]byte, 1)
for {
if _, err := conn.Read(b); err != nil {
return nil, fmt.Errorf("header: %v", err)
}
if total++; total > headerMaxBytes {
return nil, errors.New("header: too long")
}
if b[0] != '\n' {
line = append(line, b[0])
continue
}
s := strings.TrimSuffix(string(line), "\r")
line = line[:0]
if s == "" {
return h, nil
}
if len(h) >= headerMaxLines {
return nil, errors.New("header: too many lines")
}
k, v, ok := strings.Cut(s, "=")
if !ok {
return nil, fmt.Errorf("header: no = in %q", s)
}
h[strings.ToUpper(strings.TrimSpace(k))] = v
}
}
// headerEnv: the environment of a session from a header: the call's
// details as app_dmodem's DMODEM_*, and with trust the caller an
// upstream menu logged in already
func headerEnv(h map[string]string, trust bool) []string {
call := map[string]string{
"DMODEM_CHANNEL": "MODEM_CHANNEL", "DMODEM_PROFILE": "MODEM_PROFILE",
"DMODEM_RATE": "MODEM_RATE", "DMODEM_CALLERID": "MODEM_CALLERID",
"DMODEM_DIALED": "MODEM_DIALED", "DMODEM_CONNECTED": "MODEM_EPOCH",
}
var env []string
for d, m := range call {
if v, ok := h[d]; ok {
env = append(env, d+"="+v)
} else if v, ok := h[m]; ok {
env = append(env, d+"="+v)
}
}
if trust && h["MODEM_USER"] != "" {
env = append(env, "MODEMMENU_UPSTREAM_USER="+h["MODEM_USER"],
"MODEMMENU_UPSTREAM_PASSWORD="+h["MODEM_PASSWORD"],
"MODEMMENU_UPSTREAM_AUTH="+h["MODEM_AUTH"])
}
return env
}
// serve: sessions for the connections to listen, each modemmenu on a pty
// of its own as under app_dmodem
func serve(s *settings, config string) int {
srv := s.server
ln, err := listen(srv)
if err != nil {
fmt.Fprintln(os.Stderr, "modemmenu:", err)
return 1
}
self, err := os.Executable()
if err != nil {
fmt.Fprintln(os.Stderr, "modemmenu:", err)
return 1
}
logf("serving on %s", srv.listen)
var (
mu sync.Mutex
sessions = map[*os.File]bool{} // the pty masters
wg sync.WaitGroup
)
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
go func() {
sig := <-ch
logf("%v: stopping", sig)
ln.Close()
}()
slots := make(chan struct{}, srv.maxSessions)
for {
conn, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
break
}
logf("accept: %v", err)
time.Sleep(100 * time.Millisecond)
continue
}
select {
case slots <- struct{}{}:
default:
logf("%s: %d sessions already, refused", peer(conn), srv.maxSessions)
io.WriteString(conn, "\r\nAll lines are busy, call again later.\r\n")
conn.Close()
continue
}
wg.Add(1)
go func() {
defer func() { <-slots; wg.Done() }()
serveConn(conn, srv, self, config, func(m *os.File, add bool) {
mu.Lock()
if add {
sessions[m] = true
} else {
delete(sessions, m)
}
mu.Unlock()
})
}()
}
// hang up every session: closing a master hangs up its pty
mu.Lock()
for m := range sessions {
m.Close()
}
mu.Unlock()
wg.Wait()
if strings.HasPrefix(srv.listen, "/") {
os.Remove(srv.listen)
}
return 0
}
// listen on a unix socket (a path) or tcp:host:port
func listen(srv *serverSettings) (net.Listener, error) {
if addr, ok := strings.CutPrefix(srv.listen, "tcp:"); ok {
return net.Listen("tcp", addr)
}
path := srv.listen
// a socket left by a modemmenu that died; not anything else
if fi, err := os.Lstat(path); err == nil && fi.Mode()&os.ModeSocket != 0 {
if c, err := net.Dial("unix", path); err == nil {
c.Close()
return nil, fmt.Errorf("%s: another modemmenu is serving there", path)
}
os.Remove(path)
}
old := unix.Umask(0o077)
ln, err := net.Listen("unix", path)
unix.Umask(old)
if err != nil {
return nil, err
}
ln.(*net.UnixListener).SetUnlinkOnClose(true)
if srv.socketGroup != "" {
g, err := user.LookupGroup(srv.socketGroup)
if err != nil {
ln.Close()
return nil, fmt.Errorf("[server] socket_group: %v", err)
}
gid, _ := strconv.Atoi(g.Gid)
if err := os.Chown(path, -1, gid); err != nil {
ln.Close()
return nil, err
}
}
if err := os.Chmod(path, srv.socketMode); err != nil {
ln.Close()
return nil, err
}
return ln, nil
}
// peer: who connected, for the log
func peer(conn net.Conn) string {
uc, ok := conn.(*net.UnixConn)
if !ok {
return conn.RemoteAddr().String()
}
raw, err := uc.SyscallConn()
if err != nil {
return "unix"
}
var cred *unix.Ucred
raw.Control(func(fd uintptr) {
cred, _ = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED)
})
if cred == nil {
return "unix"
}
return fmt.Sprintf("pid %d uid %d", cred.Pid, cred.Uid)
}
// serveConn: the header, then modemmenu on a new pty, its bytes to and from
// the connection until either ends
func serveConn(conn net.Conn, srv *serverSettings, self, config string, track func(*os.File, bool)) {
defer conn.Close()
who := peer(conn)
env := os.Environ()
keep := env[:0]
for _, e := range env {
if !strings.HasPrefix(e, "DMODEM_") && !strings.HasPrefix(e, "MODEM") {
keep = append(keep, e)
}
}
env = keep
if srv.header {
h, err := readHeader(conn, srv.headerTimeout)
if err != nil {
logf("%s: %v", who, err)
return
}
env = append(env, headerEnv(h, srv.trustUser)...)
}
master, slave, err := openPty()
if err != nil {
logf("%s: %v", who, err)
return
}
cmd := exec.Command(self, "-config", config, "-upstream="+strconv.FormatBool(srv.trustUser))
cmd.Env = env
cmd.Stdin, cmd.Stdout, cmd.Stderr = slave, slave, slave
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
err = cmd.Start()
slave.Close()
if err != nil {
master.Close()
logf("%s: %v", who, err)
return
}
logf("%s: session pid %d", who, cmd.Process.Pid)
track(master, true)
var once sync.Once
hangup := func() { once.Do(func() { master.Close() }) }
// the caller to the session; the caller gone hangs it up
go func() {
io.Copy(master, conn)
hangup()
}()
// the session to the caller, until the pty is hung up or the session
// has ended and its last bytes are out (EIO)
io.Copy(conn, master)
cmd.Wait()
hangup()
track(master, false)
logf("%s: session pid %d ended", who, cmd.Process.Pid)
}
// openPty: a new pty, raw as app_dmodem makes it, master and slave
func openPty() (*os.File, *os.File, error) {
// nonblocking, so that the runtime polls it: a Close then ends a Read
// in progress (and hangs up the pty) instead of waiting for it
fd, err := unix.Open("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC|unix.O_NONBLOCK, 0)
if err != nil {
return nil, nil, err
}
m := os.NewFile(uintptr(fd), "/dev/ptmx")
if err := unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil {
m.Close()
return nil, nil, err
}
n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN)
if err != nil {
m.Close()
return nil, nil, err
}
s, err := os.OpenFile("/dev/pts/"+strconv.Itoa(n), os.O_RDWR|syscall.O_NOCTTY, 0)
if err != nil {
m.Close()
return nil, nil, err
}
if tio, err := unix.IoctlGetTermios(int(s.Fd()), unix.TCGETS); err == nil {
makeRaw(tio)
unix.IoctlSetTermios(int(s.Fd()), unix.TCSETS, tio)
}
return m, s, nil
}
// upstream: the caller as an upstream menu logged them in, from the
// environment of a session of modemmenu -serve with trust_user (trusted
// only then); the variables are removed either way, so that no selection
// sees them
func upstream(sess *session, trusted bool) bool {
u := os.Getenv("MODEMMENU_UPSTREAM_USER")
pw := os.Getenv("MODEMMENU_UPSTREAM_PASSWORD")
auth := os.Getenv("MODEMMENU_UPSTREAM_AUTH")
for _, k := range []string{"MODEMMENU_UPSTREAM_USER", "MODEMMENU_UPSTREAM_PASSWORD", "MODEMMENU_UPSTREAM_AUTH"} {
os.Unsetenv(k)
}
if !trusted || u == "" {
return false
}
sess.User, sess.Password, sess.Auth = u, pw, "upstream"
if auth != "" {
sess.Auth = "upstream:" + auth
}
return true
}
+189
View File
@@ -0,0 +1,189 @@
package main
import (
"bytes"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
func TestHeader(t *testing.T) {
a, b := net.Pipe()
s := newSession("33600/31200", "555\n1000", "", time.Unix(1791666309, 0))
s.User, s.Password = "alice", "secret"
go func() {
writeHeader(a, s, false)
a.Write([]byte("data"))
}()
h, err := readHeader(b, time.Second)
if err != nil {
t.Fatal(err)
}
if h["MODEM_USER"] != "alice" || h["MODEM_DIALED"] != "555 1000" || h["MODEM_PASSWORD"] != "" {
t.Errorf("header %v", h)
}
rest := make([]byte, 4)
b.Read(rest)
if string(rest) != "data" {
t.Errorf("after the header: %q", rest)
}
env := strings.Join(headerEnv(h, false), "\n")
if !strings.Contains(env, "DMODEM_RATE=33600/31200") || !strings.Contains(env, "DMODEM_CONNECTED=1791666309") ||
strings.Contains(env, "UPSTREAM") {
t.Errorf("env %s", env)
}
if env := strings.Join(headerEnv(h, true), "\n"); !strings.Contains(env, "MODEMMENU_UPSTREAM_USER=alice") {
t.Errorf("trusted env %s", env)
}
}
// modemmenu -serve on a unix socket: a session from app_dmodem's header,
// a hangup, and a chain from another modemmenu that logged the caller in
func TestServe(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, "modemmenu")
if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil {
t.Fatalf("build: %v\n%s", err, out)
}
if _, _, err := openPty(); err != nil {
t.Skip("no pty:", err)
}
sock := filepath.Join(dir, "menu.sock")
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("alice:{PLAIN}secret\n"), 0o600)
// the served menu: trusts the user of a header
conf := filepath.Join(dir, "server.conf")
os.WriteFile(conf, []byte(fmt.Sprintf(`
[general]
log = %s
auth = file
fail_delay = 0
banner = "Served line\r\n"
[file]
path = %s
[server]
listen = %s
trust_user = yes
socket_mode = 0600
[item info]
key = I
label = Info
command = echo "on $(tty | cut -c1-8) dialed=$MODEM_DIALED rate=$MODEM_RATE date=$MODEM_DATE auth=$MODEM_AUTH user=$MODEM_USER pw=$MODEM_PASSWORD up=$MODEMMENU_UPSTREAM_USER"
`, filepath.Join(dir, "server.log"), users, sock)), 0o600)
srv := exec.Command(bin, "-config", conf, "-serve")
if err := srv.Start(); err != nil {
t.Fatal(err)
}
defer srv.Process.Kill()
for i := 0; i < 100; i++ {
if _, err := os.Stat(sock); err == nil {
break
}
time.Sleep(50 * time.Millisecond)
}
if fi, err := os.Stat(sock); err != nil || fi.Mode().Perm() != 0o600 {
t.Fatalf("socket: %v %v", fi, err)
}
// as app_dmodem with header = yes: the call's details, then a login
conn, err := net.Dial("unix", sock)
if err != nil {
t.Fatal(err)
}
conn.Write([]byte("DMODEM_RATE=31200/26400\nDMODEM_CALLERID=5559999\nDMODEM_DIALED=5551000\n" +
"DMODEM_CONNECTED=1791666309\nDMODEM_CHANNEL=PJSIP/trunk-1\n\n"))
c := newCaller(t, conn)
c.expect("Served line")
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("secret\r")
c.expect("Selection: ")
c.send("info\r")
c.expect("on /dev/pts dialed=5551000 rate=31200/26400 date=2026-10-10 auth=file user=alice pw=secret up=\n")
c.expect("Goodbye")
conn.Close()
// a caller that hangs up at the login: the session ends
conn, err = net.Dial("unix", sock)
if err != nil {
t.Fatal(err)
}
conn.Write([]byte("\n"))
c = newCaller(t, conn)
c.expect("login: ")
conn.Close()
// another menu (on app_dmodem's pty) logs the caller in and hands
// them over: no second login
front := filepath.Join(dir, "front.conf")
os.WriteFile(front, []byte(fmt.Sprintf(`
[general]
log = none
auth = file
[file]
path = %s
[item more]
key = M
label = More services
mode = unix
path = %s
header = yes
`, users, sock)), 0o600)
m, s := testPty(t)
defer m.Close()
cmd := exec.Command(bin, "-config", front)
cmd.Stdin, cmd.Stdout, cmd.Stderr = s, s, s
cmd.Env = append(os.Environ(), "DMODEM_RATE=26400/26400", "DMODEM_DIALED=5552000")
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
s.Close()
defer cmd.Process.Kill()
c = newCaller(t, m)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("secret\r")
c.expect("Selection: ")
c.send("more\r")
c.expect("Served line")
c.expect("Welcome, alice.")
c.expect("Selection: ")
c.send("i\r")
c.expect("dialed=5552000 rate=26400/26400 date=")
c.expect("auth=upstream:file user=alice pw=secret up=\n")
c.expect("Goodbye")
cmd.Wait()
// SIGTERM: the socket goes
srv.Process.Signal(syscall.SIGTERM)
done := make(chan error, 1)
go func() { done <- srv.Wait() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("the server is still running after SIGTERM")
}
if _, err := os.Stat(sock); err == nil {
t.Error("the socket is still there")
}
log, _ := os.ReadFile(filepath.Join(dir, "server.log"))
for _, w := range []string{"serving on", "login user=alice auth=file", "login user=alice auth=upstream:file",
"callerid=\"5559999\" dialed=\"5551000\""} {
if !bytes.Contains(log, []byte(w)) {
t.Errorf("no %q in the log:\n%s", w, log)
}
}
if n := bytes.Count(log, []byte("ended")); n != 3 {
t.Errorf("%d sessions ended, want 3:\n%s", n, log)
}
}
+69 -1
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
)
@@ -36,6 +37,8 @@ type menuItem struct {
command string
host string
port int
path string // a unix socket instead of host and port
header bool // the session header first
send string
rloginLocal string
rloginUser string
@@ -49,8 +52,20 @@ type menuItem struct {
timeout time.Duration
}
// serverSettings: [server], for modemmenu -serve
type serverSettings struct {
listen string // a unix socket's path, or tcp:host:port
socketMode os.FileMode
socketGroup string
header bool
headerTimeout time.Duration
trustUser bool
maxSessions int
}
type settings struct {
general
server *serverSettings
menuTitle string
menuPrompt string
hangup []string // what hangs up, upper case; the first one shown
@@ -128,6 +143,10 @@ func loadSettings(path string) (*settings, error) {
s.backends = append(s.backends, a)
}
if s.server, err = loadServer(c.section("server")); 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: `))
@@ -205,6 +224,10 @@ func loadItem(name string, sec *section) (*menuItem, error) {
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}")
@@ -221,6 +244,13 @@ func loadItem(name string, sec *section) (*menuItem, error) {
if it.timeout, err = sec.duration("connect_timeout", 10*time.Second); err != nil {
return nil, err
}
if it.mode == "unix" {
// raw bytes over a unix socket: tcp with a path
it.mode = "tcp"
if it.path == "" {
return nil, fmt.Errorf("[item %s] mode = unix needs a path", name)
}
}
defPort := map[string]int{"tcp": 23, "telnet": 23, "rlogin": 513}[it.mode]
if it.port, err = sec.int("port", defPort); err != nil {
return nil, err
@@ -237,8 +267,11 @@ func loadItem(name string, sec *section) (*menuItem, error) {
if it.runAs != "" {
return nil, fmt.Errorf("[item %s] run_as is for mode = exec", name)
}
if it.path != "" && !strings.HasPrefix(it.path, "/") {
return nil, fmt.Errorf("[item %s] path: %q (an absolute path)", name, it.path)
}
default:
return nil, fmt.Errorf("[item %s] mode: %q (exec, tcp, telnet or rlogin)", name, it.mode)
return nil, fmt.Errorf("[item %s] mode: %q (exec, tcp, unix, telnet or rlogin)", name, it.mode)
}
if it.tty != "raw" && it.tty != "sane" {
return nil, fmt.Errorf("[item %s] tty: %q (raw or sane)", name, it.tty)
@@ -263,3 +296,38 @@ func contains(list []string, s string) bool {
}
return false
}
func loadServer(sec *section) (*serverSettings, error) {
var err error
srv := &serverSettings{
listen: sec.get("listen", "/run/modemmenu/modemmenu.sock"),
socketGroup: sec.get("socket_group", ""),
}
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", ""))
}
srv.socketMode = os.FileMode(mode)
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 {
return nil, err
}
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 {
return nil, err
}
if srv.maxSessions < 1 {
return nil, fmt.Errorf("[server] max_sessions: %d", srv.maxSessions)
}
if !strings.HasPrefix(srv.listen, "/") && !strings.HasPrefix(srv.listen, "tcp:") {
return nil, fmt.Errorf("[server] listen: %q (an absolute path, or tcp:host:port)", srv.listen)
}
return srv, nil
}