Files
LixenandClaude Opus 5.5 e9aeed0be0 v0.5.1 console key releases: Linux VT and FreeBSD vt(4), with a guard
* linux console source: releases from the console's own keyboard, typed by its keymap

SetKeyReport with KeySourceConsole, on a Linux virtual console the game runs
on, switches the keyboard to raw keycodes (K_MEDIUMRAW) while releases are
reported. The kernel allows the switch on the caller's controlling tty, so no
root is needed; a console that refuses is not asked again and the protocol is
next. Going back to presses, Fini and EmergencyReset switch it back.

Each keycode is typed as the console types it cooked, after
drivers/tty/vt/keyboard.c, by the console's own tables read at the switch
(KDGKBENT, KDGKBSENT, KDGKBDIACRUC, KDGKBMETA): modifiers and their left and
right groups, Caps and Num Lock with their lights kept in step (KDSKBLED),
sticky and locked modifiers, Unicode entries, dead keys and compose, the
keypad by Num Lock, function strings, Meta as ESC prefix or bit 7, console
switching by Alt+Fn and Alt+arrows to consoles in use, and from kernel 7.1
cursor and CSI keys with their modifiers. Translation starts from the
console's modifiers and locks (TIOCLINUX 6, KDGKBLED). Each key is held by
its keycode; a key typing several keys taps all but its last. Switching to
another console ends every hold Lost. Mouse reports are off while the
keyboard is raw, since the console types them into the same input, and come
back after it.

The guard: before the first switch the package runs the binary again, named
console-guard, holding the console and the read end of a pipe only the game
writes. If the pipe ends while the keyboard is raw (kill -9, the OOM killer, a
Go fatal error), the guard switches the keyboard back, restores the termios
the game found and shows the cursor, without a reset that would clear the
game's last words. A game leading its console's session takes the console
with it as it dies; its guard then leads a session of its own and opens the
console again once the kernel has hung it up, to restore it.

Checked in QEMU on a real VT, kernels 6.8 and 7.2, the game as uid 1000:
the same key strokes read identically raw and cooked (Shift released first,
Ctrl, Alt, AltGr, Caps and Num Lock, the keypad, function keys, modified
cursor keys on 7.2; dead grave and tilde, compose, a euro sign and Cyrillic
from a loaded keymap), Alt+F2 away ended the hold Lost and Alt+F1 came back,
and the keyboard came back to K_UNICODE with ICANON and ECHO after Fini, a
panic with EmergencyReset, kill -9, and kill -9 of a game leading its session
(left raw without the guard's own session).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zCVjspRDuEuMrDTumVhp

* freebsd console source: releases from vt(4)'s keyboard, typed by its keymap

On FreeBSD's vt(4) console the keyboard switches to keycodes (K_CODE),
which vt allows any process with the console open, no root needed. Each
keycode types what vt types for it cooked: the keyboard's keymap and
accent map (GIO_KEYMAP, GIO_DEADKEYMAP) run through a port of the
kernel's genkbd_keyaction, kbdmux's left Alt keypad codes, and
vt_processkey's xterm sequences, ESC for Alt and console switching. The
locks go back to the keyboard and its lights with KDSKBSTATE. Scroll Lock
is inert while raw; with the console's history mode on (Scroll Lock lit)
the keyboard stays as it is and the ask reports presses.

Shared with the Linux source now: the restore EmergencyReset runs, the
guard, which opens again a console revoked or hung up with its session's
leader, and what a key asks of the console. A console that can't go raw
just now (Scroll Lock on, its guard gone, output not drained) is tried
again at the next ask rather than never; a refusal at prepare still
holds for good.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zCVjspRDuEuMrDTumVhp

* example-keys: show each key event, for trying key releases

A viewer for the key events a terminal or console reports: F2 asks for
releases from the console or the terminal's protocol, or gives them
back, and the report each ask came to shows above the events.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zCVjspRDuEuMrDTumVhp

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-21 11:16:27 -04:00

171 lines
5.1 KiB
Go

//go:build linux || freebsd
package terminal
import (
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"unsafe"
"golang.org/x/sys/unix"
)
// The guard restores a console keyboard the game leaves raw by dying where no
// handler of its own runs: SIGKILL, the OOM killer, a Go fatal error. Before
// the first raw switch the package runs its program's binary again with
// guardEnv set, which the package's init catches before main. The guard keeps
// the console and the read end of a pipe whose write end only the game holds:
// the pipe's end is the game's, and if the keyboard is raw then, the guard
// switches it back, restores the termios and shows the cursor.
// guardEnv marks a run of the binary as a guard, which ps lists as guardName
const (
guardEnv = "LIXENWRAITH_TERMINAL_GUARD"
guardName = "console-guard"
)
// The guard's messages: armed with the keyboard mode and termios to restore,
// or disarmed
const (
guardArm = 'A'
guardDisarm = 'D'
)
func init() {
if os.Getenv(guardEnv) == "1" {
nameGuard()
os.Exit(runGuard(os.NewFile(3, "guard"), os.NewFile(4, "console")))
}
}
// keyGuard is the game's end of its guard
type keyGuard struct {
w *os.File // the pipe's write end, closed on exec in any other child
}
// startGuard runs the guard over tty
func startGuard(tty *os.File) (*keyGuard, error) {
exe, err := guardExecutable()
if err != nil {
return nil, err
}
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
defer r.Close()
// Named apart from the game, which on Linux spares it a kill by the
// game's name
cmd := exec.Command(exe)
cmd.Args = []string{guardName}
cmd.Env = append(os.Environ(), guardEnv+"=1")
cmd.ExtraFiles = []*os.File{r, tty}
// A group of its own, so a kill of the game's job leaves it to restore.
// A game leading its session takes the console with it as it dies, the
// kernel hanging the console up: its guard leads a session of its own, to
// take the console up again.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if sid, err := unix.Getsid(0); err == nil && sid == os.Getpid() {
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
}
if err := cmd.Start(); err != nil {
w.Close()
return nil, err
}
go cmd.Wait()
return &keyGuard{w: w}, nil
}
// termiosBytes is t as the guard reads it, the same binary on both ends
func termiosBytes(t *unix.Termios) []byte {
return unsafe.Slice((*byte)(unsafe.Pointer(t)), unsafe.Sizeof(*t))
}
// arm tells the guard the keyboard is about to go raw, and what restores it;
// false when the guard is gone. One write, under the pipe's atomic size.
func (g *keyGuard) arm(mode int, cooked *unix.Termios) bool {
_, err := g.w.Write(append([]byte{guardArm, byte(mode)}, termiosBytes(cooked)...))
return err == nil
}
// disarm tells the guard the keyboard is cooked again
func (g *keyGuard) disarm() { g.w.Write([]byte{guardDisarm}) }
// close ends the guard, which exits disarmed
func (g *keyGuard) close() { g.w.Close() }
// guardReset is what the guard writes after restoring the keyboard: mouse
// reports off, the cursor shown, attributes reset, but no RIS, which would
// clear the message the game died with
var guardReset = string(csiMouseMotionOff) + string(csiMouseDragOff) + string(csiMouseClickOff) +
string(csiMouseSGROff) + string(csiPasteOff) + string(csiCursorShow) + string(csiSGR0) + string(csiAutoWrapOn)
// runGuard waits on cmds until the game is gone, and restores the console
// tty if the keyboard was raw then
func runGuard(cmds, tty *os.File) int {
signal.Ignore(syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM,
syscall.SIGTSTP, syscall.SIGTTIN, syscall.SIGTTOU, syscall.SIGPIPE)
path := consolePath(tty)
armed, mode, cooked := guardWait(cmds)
if armed {
guardRestore(tty, path, mode, func(fd int) {
unix.IoctlSetTermios(fd, tcsets, &cooked)
unix.Write(fd, []byte(guardReset))
})
}
return 0
}
// guardReopenFor is how long the guard tries to open again a console its
// game took along
const guardReopenFor = 2 * time.Second
// guardReopen opens the console at path again, until its keyboard switches
// back to mode or guardReopenFor passes, and has rest restore the rest
// through it
func guardReopen(path string, mode int, rest func(fd int)) {
if path == "" {
return
}
for end := time.Now().Add(guardReopenFor); time.Now().Before(end); time.Sleep(10 * time.Millisecond) {
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
continue
}
ok := unix.IoctlSetInt(int(f.Fd()), kdSetKeyboardMode, mode) == nil
if ok {
rest(int(f.Fd()))
}
f.Close()
if ok {
return
}
}
}
// guardWait reads the game's messages to their end: whether the guard was
// armed then, and with what
func guardWait(cmds io.Reader) (armed bool, mode int, cooked unix.Termios) {
var msg [1]byte
arg := make([]byte, 1+len(termiosBytes(&cooked)))
for {
if _, err := io.ReadFull(cmds, msg[:]); err != nil {
return armed, mode, cooked
}
switch msg[0] {
case guardArm:
if _, err := io.ReadFull(cmds, arg); err != nil {
return armed, mode, cooked
}
armed, mode = true, int(arg[0])
copy(termiosBytes(&cooked), arg[1:])
case guardDisarm:
armed = false
}
}
}