e13cb99ade
A headless xterm-compatible emulator (internal/termstate) follows each machine terminal's PTY output under the same lock as the 1 MiB tail. A terminal_output from before the retained tail (new page, reload, gap) now gets output_snapshot: an escape stream that resets the client and restores scrollback (1000 lines), main screen, the alternate screen when in use (via ?1049h so the program's exit brings the shell back), saved cursors, tabs, scroll region, cursor incl. pending wrap, modes (mouse tracking/encoding, bracketed paste, DECCKM, keypad, autowrap, origin, focus, ...), charsets, pen and title, as of output_end; frames continue there. Reads inside the tail stay raw. No Go library was adequate: charmbracelet/x/vt and vito/midterm scroll at 0.2-4 MB/s and hide modes/pen/region; vt10x is unmaintained. termstate runs at 160-200 MB/s. The app treats a snapshot reply as a replay without the dropped-output line, and every replay now starts with RIS so stale modes end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
393 lines
12 KiB
Go
393 lines
12 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"os/exec"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
)
|
|
|
|
// terminalStore persists the machine's terminal list; *pipeline.Store
|
|
// implements it.
|
|
type terminalStore interface {
|
|
SaveTerminal(ctx context.Context, terminal protocol.TerminalRecord, keep int) error
|
|
DeleteTerminal(ctx context.Context, id string) error
|
|
Terminals(ctx context.Context) ([]protocol.TerminalRecord, error)
|
|
}
|
|
|
|
// terminalManager owns the machine's terminals (terminal.go in protocol).
|
|
type terminalManager struct {
|
|
base context.Context
|
|
store terminalStore
|
|
clients *terminalClients
|
|
// login is the login command of a terminal starting in a directory.
|
|
login func(dir string) (*exec.Cmd, error)
|
|
promptWait time.Duration
|
|
home func() (string, error)
|
|
now func() time.Time
|
|
|
|
mu sync.Mutex
|
|
terms map[string]*terminalProcess
|
|
wg sync.WaitGroup
|
|
}
|
|
|
|
func newTerminalManager(base context.Context, store terminalStore) *terminalManager {
|
|
return &terminalManager{
|
|
base: base, store: store, clients: &terminalClients{},
|
|
login: terminalLoginCommand, promptWait: terminalPromptWait, home: OperatorHomeDirectory, now: time.Now,
|
|
terms: map[string]*terminalProcess{},
|
|
}
|
|
}
|
|
|
|
func newTerminalID() (string, error) {
|
|
var b [8]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
return "", err
|
|
}
|
|
return "term_" + hex.EncodeToString(b[:]), nil
|
|
}
|
|
|
|
// Open starts a terminal in cwd at cols x rows at the machine's login prompt
|
|
// and returns its record once the prompt shows. clientID (when set) is
|
|
// subscribed to its output before the login writes (flow: acknowledged, and
|
|
// the record carries the window). A login that cannot ask for the password
|
|
// is refused.
|
|
func (m *terminalManager) Open(ctx context.Context, clientID, cwd string, cols, rows int, flow bool) (protocol.TerminalRecord, error) {
|
|
if m.store == nil {
|
|
return protocol.TerminalRecord{}, errors.New("terminals need the server's store, which is not configured")
|
|
}
|
|
if !chatShellTerminals {
|
|
return protocol.TerminalRecord{}, errors.New(protocol.ChatShellTerminalUnsupported)
|
|
}
|
|
home, err := m.home()
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
dir, err := resolveTerminalCwd(home, cwd)
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
id, err := newTerminalID()
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
cmd, err := m.login(dir)
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
p, err := m.start(clientID, id, dir, cmd, cols, rows, flow)
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
if err := m.awaitPrompt(p); err != nil {
|
|
m.refuse(p)
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
record := p.snapshot(false, 0)
|
|
if err := m.store.SaveTerminal(ctx, record, protocol.TerminalEndedKept); err != nil {
|
|
m.refuse(p)
|
|
return protocol.TerminalRecord{}, fmt.Errorf("could not start the terminal: %v", err)
|
|
}
|
|
record = p.snapshot(false, 0)
|
|
m.publishRecord(record)
|
|
if flow && clientID != "" && m.clients.view(clientID, id) != nil {
|
|
record.Window = protocol.TerminalFlowWindow
|
|
}
|
|
return record, nil
|
|
}
|
|
|
|
// start runs cmd in a new terminal's PTY and supervises it; the terminal
|
|
// counts against the limit from here on.
|
|
func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, rows int, flow bool) (*terminalProcess, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.base.Err() != nil {
|
|
return nil, errors.New("the server is stopping")
|
|
}
|
|
if running := m.runningLocked(); running >= protocol.TerminalOpenLimit {
|
|
return nil, fmt.Errorf("this machine already has %d open terminals; close one first", running)
|
|
}
|
|
cols, rows = chatShellTerminalSize(cols, rows)
|
|
shell := strings.Join(cmd.Args[:min(len(cmd.Args), 3)], " ")
|
|
record := protocol.TerminalRecord{ID: id, Cwd: dir, Shell: shell, CreatedAt: m.now().UnixMilli(), Status: protocol.TerminalRunning, Cols: cols, Rows: rows}
|
|
p := newTerminalProcess(record)
|
|
terminal, err := p.startAttachment(cmd)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("could not start the terminal: %v", err)
|
|
}
|
|
m.terms[id] = p
|
|
if clientID != "" {
|
|
// Its frames follow the open reply (the handler releases them).
|
|
if v := m.clients.subscribe(clientID, p, flow); v != nil {
|
|
p.mu.Lock()
|
|
v.paused = true
|
|
p.mu.Unlock()
|
|
}
|
|
// The opener draws it first: it is the active client.
|
|
p.viewers.resize(clientID, cols, rows, true)
|
|
}
|
|
m.wg.Add(1)
|
|
go m.supervise(p, cmd, terminal)
|
|
go p.pumpInput()
|
|
return p, nil
|
|
}
|
|
|
|
// awaitPrompt waits for the login's password prompt: a login that ends,
|
|
// opens a shell without asking, or stays silent is refused.
|
|
func (m *terminalManager) awaitPrompt(p *terminalProcess) error {
|
|
timer := time.NewTimer(m.promptWait)
|
|
defer timer.Stop()
|
|
for {
|
|
login, _ := p.loginState()
|
|
switch {
|
|
case login.unprompted:
|
|
return errors.New("su opened a shell without asking for a password (does the account have none?); terminals are refused")
|
|
case login.prompted:
|
|
return nil
|
|
}
|
|
select {
|
|
case <-p.loginChanged:
|
|
case <-p.done:
|
|
login, output := p.loginState()
|
|
if login.prompted && !login.unprompted {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("the login prompt (su) ended before asking for a password: %s", terminalLastLine(output))
|
|
case <-timer.C:
|
|
return fmt.Errorf("the login prompt (su) did not ask for a password within %s; terminals are refused", m.promptWait)
|
|
}
|
|
}
|
|
}
|
|
|
|
// refuse ends a terminal that never showed its prompt, without listing it.
|
|
func (m *terminalManager) refuse(p *terminalProcess) {
|
|
p.mu.Lock()
|
|
p.closing, p.refused = true, true
|
|
p.mu.Unlock()
|
|
p.signal(syscall.SIGKILL)
|
|
<-p.done
|
|
p.mu.Lock()
|
|
views := make([]*terminalView, 0, len(p.views))
|
|
for v := range p.views {
|
|
views = append(views, v)
|
|
}
|
|
id := p.record.ID
|
|
p.mu.Unlock()
|
|
for _, v := range views {
|
|
v.client.unsubscribe(id)
|
|
}
|
|
}
|
|
|
|
// terminalLastLine is the last non-empty line of a terminal's output, for a
|
|
// refusal message.
|
|
func terminalLastLine(output string) string {
|
|
lines := strings.Split(strings.ReplaceAll(output, "\r", ""), "\n")
|
|
for i := len(lines) - 1; i >= 0; i-- {
|
|
if line := strings.TrimSpace(lines[i]); line != "" {
|
|
return line
|
|
}
|
|
}
|
|
return "it printed nothing"
|
|
}
|
|
|
|
func (m *terminalManager) runningLocked() int {
|
|
running := 0
|
|
for _, p := range m.terms {
|
|
if p.running() {
|
|
running++
|
|
}
|
|
}
|
|
return running
|
|
}
|
|
|
|
// List is every recorded terminal, oldest first, with the live state of the
|
|
// ones this process holds.
|
|
func (m *terminalManager) List(ctx context.Context) ([]protocol.TerminalRecord, error) {
|
|
if m.store == nil {
|
|
return nil, errors.New("terminals need the server's store, which is not configured")
|
|
}
|
|
records, err := m.store.Terminals(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i, record := range records {
|
|
if p := m.process(record.ID); p != nil {
|
|
records[i] = p.snapshot(false, 0)
|
|
}
|
|
}
|
|
return records, nil
|
|
}
|
|
|
|
func (m *terminalManager) process(id string) *terminalProcess {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return m.terms[id]
|
|
}
|
|
|
|
func (m *terminalManager) live(id string) (*terminalProcess, error) {
|
|
p := m.process(id)
|
|
if p == nil || !p.running() {
|
|
return nil, errors.New("this terminal is not running")
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// Input queues data for a running terminal, in arrival order. It is kept
|
|
// nowhere else: what the shell echoes is output.
|
|
func (m *terminalManager) Input(id, data string) error {
|
|
switch {
|
|
case data == "":
|
|
return errors.New("input is required")
|
|
case len(data) > protocol.ChatShellInputLimit:
|
|
return errors.New("the input exceeds 16 KiB; send it in parts")
|
|
case !utf8.ValidString(data):
|
|
return errors.New("input must be UTF-8 text")
|
|
}
|
|
p, err := m.live(id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
select {
|
|
case <-p.done:
|
|
return errors.New("this terminal is not running")
|
|
case p.input <- []byte(data):
|
|
return nil
|
|
default:
|
|
return errors.New("the terminal is not reading its input; wait for it or press Ctrl-C")
|
|
}
|
|
}
|
|
|
|
// Resize sets a running terminal's size and returns its record.
|
|
func (m *terminalManager) Resize(id string, cols, rows int) (protocol.TerminalRecord, error) {
|
|
if cols <= 0 || rows <= 0 {
|
|
return protocol.TerminalRecord{}, errors.New("positive cols and rows are required")
|
|
}
|
|
p, err := m.live(id)
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
if err := p.applySize(cols, rows); err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
return p.snapshot(false, 0), nil
|
|
}
|
|
|
|
// applySize sets the terminal's PTY to cols x rows (clamped).
|
|
func (p *terminalProcess) applySize(cols, rows int) error {
|
|
cols, rows = chatShellTerminalSize(cols, rows)
|
|
p.mu.Lock()
|
|
p.record.Cols, p.record.Rows = cols, rows
|
|
p.screen.Resize(cols, rows)
|
|
terminal := p.pty
|
|
p.mu.Unlock()
|
|
if terminal != nil {
|
|
return resizeChatShellTerminal(terminal, cols, rows)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Output is one terminal with its retained output from byte after on,
|
|
// subscribing clientID (when set) to the output that follows it (flow:
|
|
// acknowledged); the caller releases that subscription once the reply is
|
|
// written (m.clients.view(...).release). A terminal ended before this
|
|
// process started has no output.
|
|
func (m *terminalManager) Output(ctx context.Context, clientID, id string, after int64, flow bool) (protocol.TerminalRecord, error) {
|
|
if p := m.process(id); p != nil {
|
|
var v *terminalView
|
|
if clientID != "" {
|
|
v = m.clients.subscribe(clientID, p, flow)
|
|
}
|
|
return p.readFor(after, v), nil
|
|
}
|
|
records, err := m.List(ctx)
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
for _, record := range records {
|
|
if record.ID == id {
|
|
return record, nil
|
|
}
|
|
}
|
|
return protocol.TerminalRecord{}, errors.New("this machine has no such terminal")
|
|
}
|
|
|
|
// Ack records that clientID consumed terminal id's output up to end.
|
|
func (m *terminalManager) Ack(clientID, id string, end int64) error {
|
|
v := m.clients.view(clientID, id)
|
|
if v == nil {
|
|
return errors.New("this connection does not read that terminal")
|
|
}
|
|
v.ack(end)
|
|
return nil
|
|
}
|
|
|
|
// Close ends a terminal (killing its login and shell) and forgets
|
|
// it. It waits briefly for the shell to go and returns the closed record.
|
|
func (m *terminalManager) Close(ctx context.Context, id string) (protocol.TerminalRecord, error) {
|
|
if m.store == nil {
|
|
return protocol.TerminalRecord{}, errors.New("terminals need the server's store, which is not configured")
|
|
}
|
|
p := m.process(id)
|
|
if p != nil && p.running() {
|
|
p.mu.Lock()
|
|
p.closing = true
|
|
p.mu.Unlock()
|
|
p.signal(syscall.SIGHUP)
|
|
select {
|
|
case <-p.done:
|
|
case <-time.After(3 * time.Second):
|
|
p.signal(syscall.SIGKILL)
|
|
<-p.done
|
|
}
|
|
return p.snapshot(false, 0), nil
|
|
}
|
|
record, err := m.Output(ctx, "", id, 0, false)
|
|
if err != nil {
|
|
return protocol.TerminalRecord{}, err
|
|
}
|
|
m.forget(id)
|
|
record.Output, record.OutputStart = "", 0
|
|
record.Status = protocol.TerminalClosed
|
|
m.publishRecord(record)
|
|
return record, nil
|
|
}
|
|
|
|
// forget drops a terminal's record and retained output.
|
|
func (m *terminalManager) forget(id string) {
|
|
m.mu.Lock()
|
|
delete(m.terms, id)
|
|
m.mu.Unlock()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := m.store.DeleteTerminal(ctx, id); err != nil {
|
|
log.Printf("terminal delete %s: %v", id, err)
|
|
}
|
|
}
|
|
|
|
func (m *terminalManager) save(record protocol.TerminalRecord) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := m.store.SaveTerminal(ctx, record, protocol.TerminalEndedKept); err != nil {
|
|
log.Printf("terminal save %s: %v", record.ID, err)
|
|
}
|
|
}
|
|
|
|
func (m *terminalManager) publishRecord(record protocol.TerminalRecord) {
|
|
record.Output, record.OutputStart = "", 0
|
|
m.clients.publish(protocol.TerminalEventFrame{TerminalID: record.ID, Terminal: &record})
|
|
}
|
|
|
|
// Wait blocks until every supervised terminal has been released (tests,
|
|
// shutdown).
|
|
func (m *terminalManager) Wait() { m.wg.Wait() }
|