package server import ( "crypto/rand" "encoding/hex" "errors" "os" "os/exec" "sync" "syscall" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // terminalProcess is one terminal this server process holds: running (its // attachment is the login, then the shell it becomes) or ended with its // output still retained. type terminalProcess struct { mu sync.Mutex record protocol.TerminalRecord out *chatShellOutput titles terminalTitles // login follows the output until the login completes; loginChanged is // signalled when it changes. login terminalLoginWatch loginChanged chan struct{} // cmd and pty are the running login or shell. cmd *exec.Cmd pty *os.File input chan []byte done chan struct{} // closing is set by terminal_close: the end is a close, not an exit. closing bool // refused: the login never asked for a password; the terminal is // forgotten without being listed. refused bool } func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess { var stream [6]byte _, _ = rand.Read(stream[:]) record.Stream = hex.EncodeToString(stream[:]) return &terminalProcess{ record: record, out: newChatShellOutput(protocol.TerminalRetained), input: make(chan []byte, protocol.ChatShellInputQueue), done: make(chan struct{}), loginChanged: make(chan struct{}, 1), } } // loginState is the login's progress and the output retained so far. func (p *terminalProcess) loginState() (terminalLoginWatch, string) { p.mu.Lock() defer p.mu.Unlock() text, _ := p.out.tail(terminalLoginScan) return p.login, text } func (p *terminalProcess) running() bool { p.mu.Lock() defer p.mu.Unlock() return p.record.Status == protocol.TerminalRunning } // snapshot is the current record; with output, the retained bytes from // absolute byte after on. func (p *terminalProcess) snapshot(output bool, after int64) protocol.TerminalRecord { p.mu.Lock() defer p.mu.Unlock() record := p.record record.OutputEnd = p.out.total if output { text, start := p.out.tail(protocol.TerminalRetained) if after > start { skip := min(after-start, int64(len(text))) cut := runeStartAfter([]byte(text), int(skip)) text, start = text[cut:], start+int64(cut) } record.Output, record.OutputStart = text, start } return record } // startAttachment starts cmd in a fresh pseudo-terminal at the record's // size and makes it the current attachment. func (p *terminalProcess) startAttachment(cmd *exec.Cmd) (*os.File, error) { if !chatShellTerminals { return nil, errors.New(protocol.ChatShellTerminalUnsupported) } p.mu.Lock() cols, rows := p.record.Cols, p.record.Rows p.mu.Unlock() terminal, err := startChatShellTerminal(cmd, cols, rows) if err != nil { return nil, err } p.mu.Lock() p.cmd, p.pty = cmd, terminal p.mu.Unlock() return terminal, nil } // read copies one attachment's stream into the retained output and follows // the window title; it returns when the attachment's terminal is closed. func (p *terminalProcess) read(terminal *os.File, titled func(string)) { buffer := make([]byte, 32<<10) for { n, err := terminal.Read(buffer) if n > 0 { p.mu.Lock() p.out.write(buffer[:n]) if p.login.feed(buffer[:n]) { select { case p.loginChanged <- struct{}{}: default: } } title, changed := p.titles.feed(buffer[:n]) changed = changed && title != p.record.Title if changed { p.record.Title = title } p.mu.Unlock() if changed { titled(title) } } if err != nil { return } } } // pumpInput writes queued input to the terminal until it ends. func (p *terminalProcess) pumpInput() { for { select { case <-p.done: return case data := <-p.input: p.mu.Lock() terminal := p.pty p.mu.Unlock() if terminal != nil { _, _ = terminal.Write(data) } } } } // signal sends sig to the current attachment's process group. func (p *terminalProcess) signal(sig syscall.Signal) { p.mu.Lock() cmd := p.cmd p.mu.Unlock() if cmd != nil && cmd.Process != nil { _ = syscall.Kill(-cmd.Process.Pid, sig) } } // waitAttachment waits for the attachment to exit and its stream to drain // (a descendant holding the terminal is read briefly, then cut off), then // kills its group and closes its terminal. It returns the exit error. func (p *terminalProcess) waitAttachment(cmd *exec.Cmd, terminal *os.File, readDone <-chan struct{}) error { err := cmd.Wait() _ = terminal.SetReadDeadline(time.Now().Add(chatShellDrain)) select { case <-readDone: case <-time.After(chatShellDrain + chatShellDrain/2): } _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) p.mu.Lock() terminal.Close() if p.pty == terminal { p.pty = nil } p.mu.Unlock() return err } // exitCode is the shell's exit status, when it exited by itself. func terminalExitCode(err error) *int { code := 0 var exitErr *exec.ExitError switch { case err == nil: case errors.As(err, &exitErr): if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() { return nil } code = exitErr.ExitCode() default: return nil } return &code }