mirror of
https://github.com/D-Modem/login.git
synced 2026-11-28 20:38:06 -08:00
handoff: the caller's line itself, from app_dmodem and on to a BBS
A header that comes with a descriptor (SCM_RIGHTS; app_dmodem's handoff = yes passes the modem's pty terminal) gives -serve the line itself: the session runs on that terminal as its controlling tty, so the menu, shells and pppd are on the modem's line and nothing is copied. The connection then only marks the session's life: the caller gone closes it (SIGHUP to the session), the session ending closes it (app_dmodem hangs up). An item with handoff = yes (mode = unix, header = yes) hands the session's line to its server the same way, the item's send and what the menu read and did not use right after the header, and has it back when the server closes the connection (after = menu shows the menu again). The time limit still holds: at the deadline the menu closes the connection. Tests: eight callers at once on handed-over lines, each session on a terminal, each handed on to a BBS that takes the terminal and gives it back; PPP on a handed-over line ended at its time limit, the call hung up; handoff without mode = unix and header = yes refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRRxseyEuLRFbFaBoX3
This commit is contained in:
9 files changed
+665
-28
No files matched your search
@@ -0,0 +1,160 @@
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
// The handoff: the caller's line itself, a terminal, passed from one
|
||||
// program to the next over a unix socket (SCM_RIGHTS) instead of its
|
||||
// bytes copied. The descriptor comes with the session header; the
|
||||
// connection then carries nothing more of the caller's (but for what the
|
||||
// sender had read of the line and not used, right after the header) and
|
||||
// stays open for as long as the receiver has the line. The receiver
|
||||
// closing it gives the line back; the sender closing it takes it away.
|
||||
//
|
||||
// app_dmodem (handoff = yes) hands modemmenu -serve the modem's line, on
|
||||
// which the caller's session runs as on a serial port; an item with
|
||||
// handoff = yes hands the session's line to a server (the BBS) and has
|
||||
// it back when the server is done.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/menu/internal/config"
|
||||
"github.com/D-Modem/menu/internal/term"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// readHeaderFD: readHeader on a unix socket, and the descriptor that came
|
||||
// with it (nil: none came); a second descriptor is an error
|
||||
func readHeaderFD(conn *net.UnixConn, timeout time.Duration) (map[string]string, *os.File, error) {
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
defer conn.SetReadDeadline(time.Time{})
|
||||
var got *os.File
|
||||
fail := func(err error) (map[string]string, *os.File, error) {
|
||||
if got != nil {
|
||||
got.Close()
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
h := map[string]string{}
|
||||
var line []byte
|
||||
total := 0
|
||||
b := make([]byte, 1)
|
||||
oob := make([]byte, unix.CmsgSpace(4*4))
|
||||
for {
|
||||
n, oobn, _, _, err := conn.ReadMsgUnix(b, oob)
|
||||
if oobn > 0 {
|
||||
fds, perr := rightsIn(oob[:oobn])
|
||||
if perr != nil {
|
||||
return fail(perr)
|
||||
}
|
||||
for _, fd := range fds {
|
||||
if got != nil {
|
||||
unix.Close(fd)
|
||||
return fail(errors.New("header: more than one descriptor"))
|
||||
}
|
||||
unix.CloseOnExec(fd)
|
||||
got = os.NewFile(uintptr(fd), "handoff")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fail(fmt.Errorf("header: %v", err))
|
||||
}
|
||||
if n == 0 {
|
||||
return fail(errors.New("header: end of file"))
|
||||
}
|
||||
if total++; total > headerMaxBytes {
|
||||
return fail(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, got, nil
|
||||
}
|
||||
if len(h) >= headerMaxLines {
|
||||
return fail(errors.New("header: too many lines"))
|
||||
}
|
||||
k, v, ok := strings.Cut(s, "=")
|
||||
if !ok {
|
||||
return fail(fmt.Errorf("header: no = in %q", s))
|
||||
}
|
||||
h[strings.ToUpper(strings.TrimSpace(k))] = v
|
||||
}
|
||||
}
|
||||
|
||||
// rightsIn: the descriptors of SCM_RIGHTS messages in oob
|
||||
func rightsIn(oob []byte) ([]int, error) {
|
||||
msgs, err := unix.ParseSocketControlMessage(oob)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var fds []int
|
||||
for i := range msgs {
|
||||
f, err := unix.ParseUnixRights(&msgs[i])
|
||||
if err == nil {
|
||||
fds = append(fds, f...)
|
||||
}
|
||||
}
|
||||
return fds, nil
|
||||
}
|
||||
|
||||
// sendWithFD: b on conn, the descriptor fd attached to it
|
||||
func sendWithFD(conn *net.UnixConn, b []byte, fd int) error {
|
||||
n, _, err := conn.WriteMsgUnix(b, unix.UnixRights(fd), nil)
|
||||
if err == nil && n < len(b) {
|
||||
_, err = conn.Write(b[n:])
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// runHandoff: the caller's line (the session's terminal) to the item's
|
||||
// server on its unix socket, with the session header, until the server
|
||||
// gives it back (closes the connection) or the deadline takes it away
|
||||
func runHandoff(t *term.Term, it *menuItem, s *session, deadline time.Time) error {
|
||||
c, err := net.DialTimeout("unix", it.path, it.timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn := c.(*net.UnixConn)
|
||||
defer conn.Close()
|
||||
var b bytes.Buffer
|
||||
writeHeader(&b, s, it.password)
|
||||
// what the server is to have first: the item's send, then what the
|
||||
// caller typed that the menu read and did not take
|
||||
if it.send != "" {
|
||||
v := s.vars(it.password)
|
||||
b.WriteString(config.Expand(config.Unescape(it.send), v, nil))
|
||||
}
|
||||
b.Write(t.TakePending())
|
||||
// the server may change the line's flags (non-blocking, for one): the
|
||||
// menu's again once it is back
|
||||
flags, ferr := unix.FcntlInt(uintptr(t.In), unix.F_GETFL, 0)
|
||||
if err := sendWithFD(conn, b.Bytes(), t.In); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if ferr == nil {
|
||||
unix.FcntlInt(uintptr(t.In), unix.F_SETFL, flags)
|
||||
}
|
||||
}()
|
||||
conn.SetReadDeadline(deadline)
|
||||
// nothing comes but the end
|
||||
// (nothing comes but the end; the line gone meanwhile, the caller
|
||||
// hung up, is the menu's to find on its next read)
|
||||
io.Copy(io.Discard, conn)
|
||||
if !deadline.IsZero() && !time.Now().Before(deadline) {
|
||||
return errTimeLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// handLine: a caller as app_dmodem's handoff = yes makes one: a pty, the
|
||||
// modem on its master (the caller's end here), its terminal handed to
|
||||
// modemmenu -serve at sock with the header
|
||||
func handLine(sock, header string) (*line, error) {
|
||||
m, sl, err := openPty()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err := net.Dial("unix", sock)
|
||||
if err != nil {
|
||||
m.Close()
|
||||
sl.Close()
|
||||
return nil, err
|
||||
}
|
||||
err = sendWithFD(c.(*net.UnixConn), []byte(header+"\n"), int(sl.Fd()))
|
||||
sl.Close()
|
||||
if err != nil {
|
||||
m.Close()
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
l := newLine(m)
|
||||
l.ctl = c
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// handoffBBS: a BBS that takes the line itself (the bbs's handoff
|
||||
// listener): the header and the terminal, a greeting naming the user on
|
||||
// the terminal, each line back with the user in front, until "quit":
|
||||
// then "bye", and the line given back (the connection closed)
|
||||
type handoffBBS struct {
|
||||
active, max, total atomic.Int32
|
||||
mu sync.Mutex
|
||||
failures []string
|
||||
}
|
||||
|
||||
// serveHandoffBBS: a handoffBBS listening at path
|
||||
func serveHandoffBBS(t *testing.T, path string) *handoffBBS {
|
||||
ln, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { ln.Close() })
|
||||
b := &handoffBBS{}
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go b.serve(c.(*net.UnixConn))
|
||||
}
|
||||
}()
|
||||
return b
|
||||
}
|
||||
|
||||
// fail: a failure, for the test
|
||||
func (b *handoffBBS) fail(f string, a ...any) {
|
||||
b.mu.Lock()
|
||||
b.failures = append(b.failures, fmt.Sprintf(f, a...))
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
// serve: one handed-over line, until "quit"
|
||||
func (b *handoffBBS) serve(c *net.UnixConn) {
|
||||
defer c.Close()
|
||||
h, tty, err := readHeaderFD(c, 5*time.Second)
|
||||
if err != nil {
|
||||
b.fail("header: %v", err)
|
||||
return
|
||||
}
|
||||
if tty == nil {
|
||||
b.fail("%s: no line came with the header", h["MODEM_USER"])
|
||||
return
|
||||
}
|
||||
defer tty.Close()
|
||||
if _, err := unix.IoctlGetTermios(int(tty.Fd()), unix.TCGETS); err != nil {
|
||||
b.fail("%s: the line is not a terminal", h["MODEM_USER"])
|
||||
return
|
||||
}
|
||||
b.total.Add(1)
|
||||
n := b.active.Add(1)
|
||||
defer b.active.Add(-1)
|
||||
for m := b.max.Load(); n > m && !b.max.CompareAndSwap(m, n); m = b.max.Load() {
|
||||
}
|
||||
user := h["MODEM_USER"]
|
||||
fmt.Fprintf(tty, "bbs: welcome %s\r\n", user)
|
||||
r := bufio.NewReader(tty)
|
||||
for {
|
||||
s, err := r.ReadString('\r')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if s == "quit\r" {
|
||||
fmt.Fprintf(tty, "bye %s\r\n", user)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(tty, "%s:%s\n", user, s)
|
||||
}
|
||||
}
|
||||
|
||||
// the handoff both ways, many callers at once: each caller's line (a
|
||||
// pty's terminal) handed to modemmenu -serve with the header, the session
|
||||
// on it; an item with handoff = yes hands it on to the BBS, which has the
|
||||
// terminal itself, and gives it back (the menu again); the caller hanging
|
||||
// up ends the session and closes the connection
|
||||
func TestServeHandoff(t *testing.T) {
|
||||
const callers = 8
|
||||
if _, _, err := openPty(); err != nil {
|
||||
t.Skip("no pty:", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
sock := filepath.Join(dir, "menu.sock")
|
||||
bbsSock := filepath.Join(dir, "bbs.sock")
|
||||
var users strings.Builder
|
||||
for i := 0; i < callers; i++ {
|
||||
fmt.Fprintf(&users, "user%d:{PLAIN}pw%d\n", i, i)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "users"), []byte(users.String()), 0o600)
|
||||
conf := filepath.Join(dir, "server.conf")
|
||||
os.WriteFile(conf, []byte(fmt.Sprintf(`
|
||||
[general]
|
||||
log = %s
|
||||
auth = file
|
||||
fail_delay = 0
|
||||
[file]
|
||||
path = %s
|
||||
[server]
|
||||
listen = %s
|
||||
max_sessions = %d
|
||||
[item bbs]
|
||||
key = B
|
||||
label = The BBS
|
||||
mode = unix
|
||||
path = %s
|
||||
header = yes
|
||||
handoff = yes
|
||||
after = menu
|
||||
[item tty]
|
||||
key = T
|
||||
label = The line
|
||||
command = case "$(tty)" in /dev/pts/*) echo "on a terminal";; *) echo "not a terminal";; esac
|
||||
after = menu
|
||||
`, filepath.Join(dir, "server.log"), filepath.Join(dir, "users"), sock, callers, bbsSock)), 0o600)
|
||||
bbs := serveHandoffBBS(t, bbsSock)
|
||||
startServe(t, dir, conf, sock)
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
inBBS sync.WaitGroup
|
||||
errs = make(chan error, callers)
|
||||
lines = make([]*line, callers)
|
||||
)
|
||||
inBBS.Add(callers)
|
||||
for i := 0; i < callers; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
arrived := false
|
||||
defer func() {
|
||||
if !arrived {
|
||||
inBBS.Done()
|
||||
}
|
||||
}()
|
||||
fail := func(err error) { errs <- fmt.Errorf("caller %d: %v", i, err) }
|
||||
l, err := handLine(sock, fmt.Sprintf("DMODEM_CALLERID=555000%d\nDMODEM_RATE=33600/33600\n", i))
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
lines[i] = l
|
||||
defer l.conn.Close()
|
||||
defer l.ctl.Close()
|
||||
user := fmt.Sprintf("user%d", i)
|
||||
steps := func(st []struct{ want, send string }) bool {
|
||||
for _, step := range st {
|
||||
if err := l.expect(step.want); err != nil {
|
||||
fail(err)
|
||||
return false
|
||||
}
|
||||
if step.send != "" {
|
||||
l.send(step.send)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if !steps([]struct{ want, send string }{
|
||||
{"login: ", user + "\r"},
|
||||
{"Password: ", fmt.Sprintf("pw%d\r", i)},
|
||||
{"Selection: ", "t\r"},
|
||||
{"on a terminal", ""},
|
||||
{"Selection: ", "b\r"},
|
||||
{"bbs: welcome " + user + "\r\n", fmt.Sprintf("ping %d\r", i)},
|
||||
{fmt.Sprintf("%s:ping %d\r", user, i), ""},
|
||||
}) {
|
||||
return
|
||||
}
|
||||
arrived = true
|
||||
inBBS.Done()
|
||||
inBBS.Wait()
|
||||
// the BBS gives the line back: the menu again
|
||||
mark := len(l.text())
|
||||
l.send("quit\r")
|
||||
if !steps([]struct{ want, send string }{{"bye " + user + "\r\n", ""}}) {
|
||||
return
|
||||
}
|
||||
until := time.Now().Add(15 * time.Second)
|
||||
for !strings.Contains(l.text()[mark:], "Selection: ") {
|
||||
if time.Now().After(until) {
|
||||
fail(fmt.Errorf("no menu after the BBS: %q", l.text()[mark:]))
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
// the caller hangs up: the session ends, the connection
|
||||
// closes
|
||||
l.conn.Close()
|
||||
l.ctl.SetReadDeadline(time.Now().Add(15 * time.Second))
|
||||
if _, err := io.Copy(io.Discard, l.ctl); err != nil {
|
||||
fail(fmt.Errorf("the connection after the hangup: %v", err))
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Error(err)
|
||||
}
|
||||
for _, f := range bbs.failures {
|
||||
t.Error("bbs:", f)
|
||||
}
|
||||
for i, l := range lines {
|
||||
if l == nil {
|
||||
continue
|
||||
}
|
||||
for j := 0; j < callers; j++ {
|
||||
if j != i && strings.Contains(l.text(), fmt.Sprintf("user%d:", j)) {
|
||||
t.Errorf("caller %d got caller %d's bytes", i, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n := bbs.total.Load(); n != callers {
|
||||
t.Errorf("%d lines handed to the BBS, want %d", n, callers)
|
||||
}
|
||||
if n := bbs.max.Load(); n != callers {
|
||||
t.Errorf("%d callers in the BBS at once, want %d", n, callers)
|
||||
}
|
||||
log, _ := os.ReadFile(filepath.Join(dir, "server.log"))
|
||||
if n := strings.Count(string(log), "on the line handed over"); n != callers {
|
||||
t.Errorf("%d sessions on handed-over lines, want %d:\n%s", n, callers, log)
|
||||
}
|
||||
}
|
||||
|
||||
// handoff = yes needs mode = unix and header = yes
|
||||
func TestHandoffSettings(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, item := range []string{
|
||||
"mode = tcp\nport = 23\nheader = yes",
|
||||
"mode = unix\npath = /x",
|
||||
} {
|
||||
conf := filepath.Join(dir, "m.conf")
|
||||
os.WriteFile(conf, []byte("[general]\nlog = none\nauth = file\n[file]\npath = /dev/null\n[item a]\nkey = A\nhandoff = yes\n"+item+"\n"), 0o600)
|
||||
if _, err := loadSettings(conf); err == nil || !strings.Contains(err.Error(), "handoff") {
|
||||
t.Errorf("%q: %v", item, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// a PPP session (a stand-in for pppd that would run for ever) on a
|
||||
// handed-over line, past its time: modemmenu ends it at the deadline, the
|
||||
// session ends and the connection closes, which hangs the call up
|
||||
func TestHandoffTimeLimit(t *testing.T) {
|
||||
if _, _, err := openPty(); err != nil {
|
||||
t.Skip("no pty:", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
sock := filepath.Join(dir, "menu.sock")
|
||||
os.WriteFile(filepath.Join(dir, "users"), []byte("alice:{PLAIN}secret\n"), 0o600)
|
||||
conf := filepath.Join(dir, "server.conf")
|
||||
os.WriteFile(conf, []byte(fmt.Sprintf(`
|
||||
[general]
|
||||
log = %s
|
||||
auth = file
|
||||
fail_delay = 0
|
||||
[file]
|
||||
path = %s
|
||||
[server]
|
||||
listen = %s
|
||||
[item ppp]
|
||||
key = P
|
||||
label = PPP
|
||||
command = echo "pppd up"; exec sleep 1000
|
||||
`, filepath.Join(dir, "server.log"), filepath.Join(dir, "users"), sock)), 0o600)
|
||||
startServe(t, dir, conf, sock)
|
||||
|
||||
// the call has 4 seconds (an upstream's MODEM_SECONDS_LEFT)
|
||||
l, err := handLine(sock, "DMODEM_CALLERID=5550000\nMODEM_SECONDS_LEFT=4\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.conn.Close()
|
||||
defer l.ctl.Close()
|
||||
for _, step := range []struct{ want, send string }{
|
||||
{"login: ", "alice\r"},
|
||||
{"Password: ", "secret\r"},
|
||||
{"Selection: ", "p\r"},
|
||||
{"pppd up", ""},
|
||||
} {
|
||||
if err := l.expect(step.want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if step.send != "" {
|
||||
l.send(step.send)
|
||||
}
|
||||
}
|
||||
start := time.Now()
|
||||
l.ctl.SetReadDeadline(time.Now().Add(30 * time.Second))
|
||||
if _, err := io.Copy(io.Discard, l.ctl); err != nil {
|
||||
t.Fatalf("the connection still open past the time limit: %v", err)
|
||||
}
|
||||
if d := time.Since(start); d > 20*time.Second {
|
||||
t.Errorf("hung up %v after PPP started", d)
|
||||
}
|
||||
log, _ := os.ReadFile(filepath.Join(dir, "server.log"))
|
||||
if !strings.Contains(string(log), "on the line handed over") || !strings.Contains(string(log), "ended") {
|
||||
t.Errorf("log:\n%s", log)
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,9 @@ func launch(t *term.Term, cfg *settings, it *menuItem, s *session, deadline time
|
||||
case "exec":
|
||||
return runExec(t, cfg, it, s, deadline, logf)
|
||||
default:
|
||||
if it.handoff {
|
||||
return runHandoff(t, it, s, deadline)
|
||||
}
|
||||
return runTCP(t, it, s, deadline)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ package main
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -51,32 +52,29 @@ func startServe(t *testing.T, dir, conf, sock string) {
|
||||
t.Fatalf("%s: modemmenu -serve is not listening: %s", sock, b)
|
||||
}
|
||||
|
||||
// line: a caller on a connection, for a goroutine (no t.Fatal there):
|
||||
// what came so far, and waits that fail with an error
|
||||
// line: a caller on a connection (or a pty's master), for a goroutine
|
||||
// (no t.Fatal there): what came so far, and waits that fail with an
|
||||
// error
|
||||
type line struct {
|
||||
conn net.Conn
|
||||
conn io.ReadWriteCloser
|
||||
ctl net.Conn // a handed-over line's connection to the server
|
||||
mu sync.Mutex
|
||||
got strings.Builder
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// dialLine: a caller connected to sock, the session header sent
|
||||
func dialLine(sock, header string) (*line, error) {
|
||||
c, err := net.Dial("unix", sock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := &line{conn: c, done: make(chan struct{})}
|
||||
// newLine: a caller on rw, what comes read as it comes
|
||||
func newLine(rw io.ReadWriteCloser) *line {
|
||||
l := &line{conn: rw, done: make(chan struct{})}
|
||||
go func() {
|
||||
defer close(l.done)
|
||||
r := bufio.NewReader(c)
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
n, err := r.Read(buf)
|
||||
n, err := rw.Read(buf)
|
||||
if n > 0 {
|
||||
// the terminal asked where its cursor is: 24x80
|
||||
if strings.Contains(string(buf[:n]), "\x1b[6n") {
|
||||
c.Write([]byte("\x1b[24;80R"))
|
||||
rw.Write([]byte("\x1b[24;80R"))
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.got.Write(buf[:n])
|
||||
@@ -87,6 +85,16 @@ func dialLine(sock, header string) (*line, error) {
|
||||
}
|
||||
}
|
||||
}()
|
||||
return l
|
||||
}
|
||||
|
||||
// dialLine: a caller connected to sock, the session header sent
|
||||
func dialLine(sock, header string) (*line, error) {
|
||||
c, err := net.Dial("unix", sock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := newLine(c)
|
||||
_, err = c.Write([]byte(header + "\n"))
|
||||
return l, err
|
||||
}
|
||||
|
||||
+58
-5
@@ -156,7 +156,7 @@ func serve(s *settings, config string) int {
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
sessions = map[*os.File]bool{} // the pty masters
|
||||
sessions = map[io.Closer]bool{} // what hangs each session up
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
ch := make(chan os.Signal, 1)
|
||||
@@ -192,7 +192,7 @@ func serve(s *settings, config string) int {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer func() { <-slots; wg.Done() }()
|
||||
serveConn(conn, srv, self, config, func(m *os.File, add bool) {
|
||||
serveConn(conn, srv, self, config, func(m io.Closer, add bool) {
|
||||
mu.Lock()
|
||||
if add {
|
||||
sessions[m] = true
|
||||
@@ -203,7 +203,8 @@ func serve(s *settings, config string) int {
|
||||
})
|
||||
}()
|
||||
}
|
||||
// hang up every session: closing a master hangs up its pty
|
||||
// hang up every session: closing a master hangs up its pty (a
|
||||
// handed-over line's session gets SIGHUP)
|
||||
mu.Lock()
|
||||
for m := range sessions {
|
||||
m.Close()
|
||||
@@ -278,7 +279,7 @@ func peer(conn net.Conn) string {
|
||||
|
||||
// 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)) {
|
||||
func serveConn(conn net.Conn, srv *serverSettings, self, config string, track func(io.Closer, bool)) {
|
||||
defer conn.Close()
|
||||
who := peer(conn)
|
||||
env := os.Environ()
|
||||
@@ -290,12 +291,23 @@ func serveConn(conn net.Conn, srv *serverSettings, self, config string, track fu
|
||||
}
|
||||
env = keep
|
||||
if srv.header {
|
||||
h, err := readHeader(conn, srv.headerTimeout)
|
||||
var h map[string]string
|
||||
var line *os.File
|
||||
var err error
|
||||
if uc, ok := conn.(*net.UnixConn); ok {
|
||||
h, line, err = readHeaderFD(uc, srv.headerTimeout)
|
||||
} else {
|
||||
h, err = readHeader(conn, srv.headerTimeout)
|
||||
}
|
||||
if err != nil {
|
||||
logf("%s: %v", who, err)
|
||||
return
|
||||
}
|
||||
env = append(env, headerEnv(h, srv.trustUser)...)
|
||||
if line != nil {
|
||||
serveLine(conn, line, who, env, self, config, srv, track)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
master, slave, err := openPty()
|
||||
@@ -333,6 +345,47 @@ func serveConn(conn net.Conn, srv *serverSettings, self, config string, track fu
|
||||
logf("%s: session pid %d ended", who, cmd.Process.Pid)
|
||||
}
|
||||
|
||||
// serveLine: the session on a line handed over with the header (the
|
||||
// modem's terminal, app_dmodem's handoff = yes): modemmenu on it as its
|
||||
// controlling tty, nothing copied; the connection closing (the call
|
||||
// gone) hangs the session up, the session ending closes it (the call
|
||||
// hangs up)
|
||||
func serveLine(conn net.Conn, line *os.File, who string, env []string, self, config string, srv *serverSettings, track func(io.Closer, bool)) {
|
||||
defer line.Close()
|
||||
if _, err := unix.IoctlGetTermios(int(line.Fd()), unix.TCGETS); err != nil {
|
||||
logf("%s: the line handed over is not a terminal", who)
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(self, "-config", config, "-upstream="+strconv.FormatBool(srv.trustUser))
|
||||
cmd.Env = env
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = line, line, line
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
|
||||
if err := cmd.Start(); err != nil {
|
||||
logf("%s: %v", who, err)
|
||||
return
|
||||
}
|
||||
line.Close()
|
||||
logf("%s: session pid %d on the line handed over", who, cmd.Process.Pid)
|
||||
hup := &hangup{pid: cmd.Process.Pid}
|
||||
track(hup, true)
|
||||
// nothing comes on the connection but its end
|
||||
go func() {
|
||||
io.Copy(io.Discard, conn)
|
||||
hup.Close()
|
||||
}()
|
||||
cmd.Wait()
|
||||
conn.Close()
|
||||
track(hup, false)
|
||||
logf("%s: session pid %d ended", who, cmd.Process.Pid)
|
||||
}
|
||||
|
||||
// hangup: a session on a handed-over line, hung up by Close (SIGHUP to
|
||||
// its process group)
|
||||
type hangup struct{ pid int }
|
||||
|
||||
// Close: SIGHUP to the session
|
||||
func (h *hangup) Close() error { return syscall.Kill(-h.pid, syscall.SIGHUP) }
|
||||
|
||||
// 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
|
||||
|
||||
@@ -47,6 +47,7 @@ type menuItem struct {
|
||||
port int
|
||||
path string // a unix socket instead of host and port
|
||||
header bool // the session header first
|
||||
handoff bool // mode unix: the line itself to the server
|
||||
send string
|
||||
rloginLocal string
|
||||
rloginUser string
|
||||
@@ -289,6 +290,12 @@ func loadItem(name string, sec *config.Section) (*menuItem, error) {
|
||||
if it.header, err = sec.Bool("header", false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if it.handoff, err = sec.Bool("handoff", false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if it.handoff && (strings.ToLower(sec.Get("mode", "")) != "unix" || !it.header) {
|
||||
return nil, fmt.Errorf("[item %s] handoff = yes needs mode = unix and header = yes", name)
|
||||
}
|
||||
it.rloginLocal = sec.Get("rlogin_client_user", "{password}")
|
||||
it.rloginUser = sec.Get("rlogin_server_user", "{user}")
|
||||
it.rloginTerm = sec.Get("rlogin_terminal", "ansi/{baud}")
|
||||
|
||||
+5
-4
@@ -184,8 +184,8 @@ modemmenu -serve: one modemmenu for all calls, on a unix socket (or tcp:host:por
|
||||
| `listen` | `/run/modemmenu/modemmenu.sock` | See the section above. |
|
||||
| `socket_mode` | `0660` | the socket's permissions: who may connect (app_dmodem: Asterisk's group) |
|
||||
| `socket_group` | `asterisk` | the socket's permissions: who may connect (app_dmodem: Asterisk's group) |
|
||||
| `header` | `yes` | 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_timeout` | `10` | 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` | 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. A header from app_dmodem's handoff = yes brings the modem's line with it (SCM_RIGHTS): the session runs on that terminal itself, nothing copied. |
|
||||
| `header_timeout` | `10` | 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. A header from app_dmodem's handoff = yes brings the modem's line with it (SCM_RIGHTS): the session runs on that terminal itself, nothing copied. |
|
||||
| `trust_user` | `no` | 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. |
|
||||
| `max_sessions` | `32` | connections at once; more are told the lines are busy. |
|
||||
|
||||
@@ -261,7 +261,7 @@ There may be any number of these, each with its own NAME.
|
||||
|---|---|---|
|
||||
| `key` | `B` | its key in the menu, one or more characters (default: its name's first letter) Also: `P`, `PW`, `S`, `M`, `L`, `LC`, `U`, `K`, `W`, `N`, `C`, `GO`. |
|
||||
| `aliases` | `...` | more words that select it (its name always does) Also: `dialup net`. |
|
||||
| `label` | `...` | its line in the menu. Also: `Bulletin board`, `PPP (dial-up networking)`, `Change your password`, `Shell`, `More services`, `Legend of the Red Dragon`, `Last callers`, `Upload a file (ZMODEM)`, `Kermit file server`, `The web (lynx)`, `Mail`, `Usenet news`, `Chat (IRC)`, `Gopherspace`. |
|
||||
| `label` | `...` | its line in the menu. Also: `Bulletin board`, `PPP (dial-up networking)`, `Change your password`, `Shell`, `More services`, `The BBS`, `Legend of the Red Dragon`, `Last callers`, `Upload a file (ZMODEM)`, `Kermit file server`, `The web (lynx)`, `Mail`, `Usenet news`, `Chat (IRC)`, `Gopherspace`. |
|
||||
| `mode` | `exec` | a program on the line: command (by /bin/sh -c); `passwd`: built in: the caller changes their password (min_password = 8 characters); `callers`: built in: the last callers (count = 10), the time, user and rate of each login (state_dir/callers, the latest 200; kept only with such an item); `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 ({user}), rlogin_terminal (ansi/{baud}) Also: `rlogin`, `tcp`, `passwd`, `unix`, `callers`. |
|
||||
| `run_as` | `{user}` | exec as this system user (modemmenu must be root) |
|
||||
| `tty` | `raw` | the line as app_dmodem has it; sane: cooked, echo, CR to LF, for programs that want a terminal. Also: `sane`. |
|
||||
@@ -271,6 +271,7 @@ There may be any number of these, each with its own NAME.
|
||||
| `connect_timeout` | `10` | seconds to reach a server. |
|
||||
| `terminal` | `ANSI` | telnet: the terminal type it tells the server ({term} and the other placeholders work) |
|
||||
| `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. Also: `yes`. |
|
||||
| `handoff` | `no` | unix with header = yes: yes hands the server the caller's line itself (SCM_RIGHTS, with the header) instead of copying bytes to it; the server gives it back by closing the connection (the bbs's listen with handoff = yes takes it) Also: `yes`. |
|
||||
| `users` | `alice` | bob these users ... |
|
||||
| `groups` | `sysops` | ... or members of these groups ([groups], or the system's for auth = system) Also: `dialup`. |
|
||||
| `min_baud` | `9600` | the connect rate at least this (unknown: no) |
|
||||
@@ -289,7 +290,7 @@ There may be any number of these, each with its own NAME.
|
||||
| `time_warning` | `no` | no time warning in the middle of PPP's frames. |
|
||||
| `command` | `exec /usr/sbin/pppd nodetach noauth local lock passive {ppp_local}:{ppp_remote} ms-dns {ppp_dns} ms-dns {ppp_dns2} ipparam {user}` | no time warning in the middle of PPP's frames. Also: `exec "$SHELL" -l`, `cd /srv/doors/lord && exec dosemu -dumb -E "lord.bat $MODEM_NODE"`, `cd "$HOME/uploads" && exec rz -b -R -E`, `cd "$HOME" && exec kermit -Y -x`, `exec lynx -anonymous https://example.org/`, `exec mutt`, `exec tin -r`, `exec irssi -c 127.0.0.1 -n {user}`, `exec lynx -anonymous gopher://gopher.floodgap.com/`. |
|
||||
| `min_password` | `8` | See the section above. |
|
||||
| `path` | `/run/modemmenu/more.sock` | See the section above. |
|
||||
| `path` | `/run/modemmenu/more.sock` | See the section above. Also: `/run/bbs/handoff.sock`. |
|
||||
| `dropfile_dir` | `/srv/doors/lord/node{node}` | See the section above. |
|
||||
| `count` | `10` | See the section above. |
|
||||
|
||||
|
||||
+43
-5
@@ -66,11 +66,49 @@ the connection, which hangs up the call.
|
||||
Many callers at once are many connections: app_dmodem connects each
|
||||
call by itself, and the server serves each connection in its own
|
||||
session, up to `max_sessions`. An item that hands the caller on to a
|
||||
server (`mode = unix`, `tcp`, `telnet`, `rlogin`), a BBS for one,
|
||||
opens a connection of its own for that caller from their session and
|
||||
copies the bytes between it and the session's pty. Nothing passes a
|
||||
descriptor (`SCM_RIGHTS`) from one process to the next: each hop copies,
|
||||
so each caller's bytes stay on their own connection all the way through.
|
||||
server (`mode = unix`, `tcp`, `telnet`, `rlogin`), a BBS for one, opens
|
||||
a connection of its own for that caller from their session and copies
|
||||
the bytes between it and the session's line.
|
||||
|
||||
### The handoff: the line itself, nothing copied
|
||||
|
||||
With app_dmodem's `handoff = yes` the modem's line is a pty, and its
|
||||
terminal comes with the header (`SCM_RIGHTS`). The session then runs on
|
||||
that terminal as on a serial port: the menu, a shell and pppd (which
|
||||
needs a tty) are on the modem's line itself, and `-serve` copies nothing.
|
||||
The connection carries nothing more; it stays open while the session
|
||||
lasts. The caller hanging up closes it and hangs the session up
|
||||
(`SIGHUP`); the session ending closes it, and app_dmodem hangs up once
|
||||
the last bytes are out.
|
||||
|
||||
An item with `handoff = yes` (`mode = unix`, `header = yes`) does the
|
||||
same towards its server: the session's line goes to the server with the
|
||||
header, the menu waits, and when the server closes the connection the
|
||||
line is back (`after = menu` shows the menu again). The BBS's
|
||||
`[listen]` with `handoff = yes` takes it. Bytes the menu had read and
|
||||
not used, and the item's `send`, come on the connection right after the
|
||||
header. The time limit still holds: at the deadline the menu closes the
|
||||
connection, which takes the line back.
|
||||
|
||||
```
|
||||
; dmodem.conf
|
||||
[menu]
|
||||
mode = unix
|
||||
path = /run/modemmenu/modemmenu.sock
|
||||
header = yes
|
||||
handoff = yes
|
||||
|
||||
; modemmenu.conf
|
||||
[item bbs]
|
||||
key = B
|
||||
mode = unix
|
||||
path = /run/bbs/handoff.sock
|
||||
header = yes
|
||||
handoff = yes
|
||||
after = menu
|
||||
```
|
||||
|
||||
Without `handoff`, or over TCP, the bytes are copied as before.
|
||||
|
||||
| `[server]` option | default | |
|
||||
|---|---|---|
|
||||
|
||||
@@ -230,7 +230,9 @@ 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 (MODEM_*). no: the caller's bytes from the start. A
|
||||
; header from app_dmodem's handoff = yes brings the modem's line with it
|
||||
; (SCM_RIGHTS): the session runs on that terminal itself, nothing copied
|
||||
header = yes
|
||||
header_timeout = 10
|
||||
; yes: a header with MODEM_USER (another modemmenu's item, header = yes)
|
||||
@@ -356,6 +358,11 @@ hotkeys = no
|
||||
; first, MODEM_* NAME=value lines and an empty line
|
||||
; (the password only with pass_password), for
|
||||
; modemmenu -serve or any program that reads it
|
||||
; handoff = no unix with header = yes: yes hands the server the
|
||||
; caller's line itself (SCM_RIGHTS, with the header)
|
||||
; instead of copying bytes to it; the server gives
|
||||
; it back by closing the connection (the bbs's
|
||||
; listen with handoff = yes takes it)
|
||||
;
|
||||
; Who sees an item (all that are set must pass; the others neither see nor
|
||||
; can choose it):
|
||||
@@ -443,6 +450,17 @@ after = menu
|
||||
;header = yes
|
||||
;after = menu
|
||||
|
||||
; the BBS with the caller's line itself (the bbs's [listen] handoff = yes):
|
||||
; nothing copied between them
|
||||
;[item bbs]
|
||||
;key = B
|
||||
;label = The BBS
|
||||
;mode = unix
|
||||
;path = /run/bbs/handoff.sock
|
||||
;header = yes
|
||||
;handoff = yes
|
||||
;after = menu
|
||||
|
||||
; More items, to copy into items = above. Each needs its program installed;
|
||||
; run_as = {user} (modemmenu as root) keeps callers in their own accounts.
|
||||
|
||||
|
||||
Reference in new issue
Block a user