Use common v0.8.0 UI, transport, and translation APIs

This commit is contained in:
Storm Dragon committed 2026-11-16 20:10:47 -05:00
1 parent 317303adb7
commit 92fd479336
344 files changed
+4102 -4973

No files matched your search

+16 -16
View File
@@ -14,7 +14,7 @@ import (
"syscall"
)
func (s *Server) endpoint_snapshot() []endpoint {
func (s *Server) endpointSnapshot() []endpoint {
s.endpointsMu.RLock()
defer s.endpointsMu.RUnlock()
return slices.Clone(s.endpoints)
@@ -22,18 +22,18 @@ func (s *Server) endpoint_snapshot() []endpoint {
// Every default instance has a private endpoint. The first available instance
// also serves the shared path, and a survivor claims it after that owner exits.
func (s *Server) claim_main() bool {
func (s *Server) claimMain() bool {
if s.options.SocketFile != "" || s.ctx.Err() != nil {
return false
}
s.endpointsMu.Lock()
defer s.endpointsMu.Unlock()
for _, endpoint := range s.endpoints {
if endpoint.path == s.main_path() {
if endpoint.path == s.mainPath() {
return false
}
}
endpoint, err := listen(s.main_path())
endpoint, err := listen(s.mainPath())
if err != nil {
return false // Active readers and unrelated paths are preserved.
}
@@ -49,8 +49,8 @@ func (s *Server) claim_main() bool {
return true
}
func (s *Server) private_path(data instance) string {
path := filepath.Join(filepath.Dir(s.main_path()), fmt.Sprintf("fenrirscreenreader-%d.sock", data.PID))
func (s *Server) privatePath(data instance) string {
path := filepath.Join(filepath.Dir(s.mainPath()), fmt.Sprintf("fenrirscreenreader-%d.sock", data.PID))
if slices.Contains(data.SocketFiles, path) {
return path
}
@@ -60,11 +60,11 @@ func (s *Server) private_path(data instance) string {
// Ancestry identifies ordinary PTY children. Reattached Screen sessions and
// detached helpers can lose that ancestry, so also use the caller's own X11
// identity. Neither a single terminal nor a console is a safe default.
func (s *Server) route_target(pid, uid int) (string, error) {
func (s *Server) routeTarget(pid, uid int) (string, error) {
instances := s.instances()
var terminals, consoles []instance
for _, data := range instances {
if s.private_path(data) == "" {
if s.privatePath(data) == "" {
continue
}
if data.ScreenDriver == "vcsaDriver" && (data.uid == 0 || data.uid == uid) {
@@ -77,7 +77,7 @@ func (s *Server) route_target(pid, uid int) (string, error) {
var ancestors []int
var ancestorReader *instance
ancestry:
for ancestor := pid; ancestor > 1 && !seen[ancestor]; ancestor = parent_pid(ancestor) {
for ancestor := pid; ancestor > 1 && !seen[ancestor]; ancestor = parentPid(ancestor) {
seen[ancestor] = true
ancestors = append(ancestors, ancestor)
for _, data := range terminals {
@@ -97,7 +97,7 @@ ancestry:
lookup := s.screenReader
if lookup == nil {
lookup = func(ancestors []int, uid int, readers []instance) (instance, bool, error) {
return attached_screen_reader("/proc", ancestors, uid, readers)
return attachedScreenReader("/proc", ancestors, uid, readers)
}
}
if reader, handled, err := lookup(ancestors, uid, readers); handled {
@@ -109,8 +109,8 @@ ancestry:
if ancestorReader != nil {
return s.destination(*ancestorReader)
}
identity := process_identity(pid, uid)
return s.route_identity(identity, uid, terminals, consoles)
identity := lookupProcessIdentity(pid, uid)
return s.routeIdentity(identity, uid, terminals, consoles)
}
type processIdentity struct {
@@ -121,7 +121,7 @@ type processIdentity struct {
// Read only identity fields from the credentialed process, never a supplied PID
// or environment in the request text. Environment is a routing hint, not an
// authorization grant; the destination still checks the original SO_PEERCRED.
func process_identity(pid, uid int) processIdentity {
func lookupProcessIdentity(pid, uid int) processIdentity {
var identity processIdentity
info, err := os.Stat(fmt.Sprintf("/proc/%d", pid))
if err != nil {
@@ -164,7 +164,7 @@ func process_identity(pid, uid int) processIdentity {
return identity
}
func (s *Server) route_identity(identity processIdentity, uid int, terminals, consoles []instance) (string, error) {
func (s *Server) routeIdentity(identity processIdentity, uid int, terminals, consoles []instance) (string, error) {
var matches []instance
if identity.console {
// A real controlling VT takes precedence over inherited X11 variables.
@@ -174,7 +174,7 @@ func (s *Server) route_identity(identity processIdentity, uid int, terminals, co
if data.uid != uid || data.WindowID != identity.window {
continue
}
target := process_identity(data.PID, data.uid)
target := lookupProcessIdentity(data.PID, data.uid)
if target.display == identity.display {
matches = append(matches, data)
}
@@ -193,7 +193,7 @@ func (s *Server) destination(data instance) (string, error) {
if !data.ConnectionHandoff {
return "", fmt.Errorf("reader %d cannot accept a connection handoff", data.PID)
}
path := s.private_path(data)
path := s.privatePath(data)
info, err := os.Lstat(path)
if err != nil || info.Mode()&os.ModeSocket == 0 {
return "", fmt.Errorf("reader %d private socket is unavailable", data.PID)
+57 -57
View File
@@ -60,11 +60,11 @@ func TestControlProcess(t *testing.T) {
_ = json.NewEncoder(os.Stdout).Encode(reply)
os.Exit(0)
}
run_reader_process(mode)
runReaderProcess(mode)
os.Exit(0)
}
func child_command(mode string) *exec.Cmd {
func childCommand(mode string) *exec.Cmd {
command := exec.Command(os.Args[0], "-test.run=^TestControlProcess$")
command.Env = append(os.Environ(), "FENRIR_CONTROL_PROCESS="+mode)
// A fixture must not inherit the developer's real VT as its controlling TTY.
@@ -74,7 +74,7 @@ func child_command(mode string) *exec.Cmd {
// Screen daemons launched by a fixture may be reparented to PID 1 and never
// reach the coordinator; their full ancestry still belongs to that fixture.
func fixture_ancestors(ancestors []int, coordinator int) []int {
func fixtureAncestors(ancestors []int, coordinator int) []int {
for i, pid := range ancestors {
if pid == coordinator {
return ancestors[:i]
@@ -95,9 +95,9 @@ func TestFixtureScreenInspectionExcludesHostAndKeepsPrivateSessions(t *testing.T
{"coordinator caller", []int{300, 100}, false},
} {
t.Run(trial.name, func(t *testing.T) {
f := new_screen_fixture(t)
f := newScreenFixture(t)
f.attach(200, 300, "/dev/null", true)
reader, handled, err := attached_screen_reader(f.root, fixture_ancestors(trial.ancestors, 300), os.Geteuid(), []instance{{PID: 300}})
reader, handled, err := attachedScreenReader(f.root, fixtureAncestors(trial.ancestors, 300), os.Geteuid(), []instance{{PID: 300}})
if err != nil || handled != trial.handled || handled && reader.PID != 300 {
t.Fatalf("reader=%+v handled=%v err=%v; want handled=%v", reader, handled, err, trial.handled)
}
@@ -105,16 +105,16 @@ func TestFixtureScreenInspectionExcludesHostAndKeepsPrivateSessions(t *testing.T
}
}
func run_reader_process(mode string) {
func runReaderProcess(mode string) {
encoder := json.NewEncoder(os.Stdout)
directory := os.Getenv("FENRIR_CONTROL_DIRECTORY")
// Processes above the test coordinator belong to the host, not this fixture.
// Screen sessions created by the native test remain inside the inspected tree.
coordinator := os.Getppid()
lookup := func(ancestors []int, uid int, readers []instance) (instance, bool, error) {
return attached_screen_reader("/proc", fixture_ancestors(ancestors, coordinator), uid, readers)
return attachedScreenReader("/proc", fixtureAncestors(ancestors, coordinator), uid, readers)
}
server, err := open_server(context.Background(), Options{Directory: directory, RegistryDirectory: filepath.Join(directory, "registry"), TerminalMode: mode == "terminal", WindowID: os.Getenv("WINDOWID")}, lookup)
server, err := openServer(context.Background(), Options{Directory: directory, RegistryDirectory: filepath.Join(directory, "registry"), TerminalMode: mode == "terminal", WindowID: os.Getenv("WINDOWID")}, lookup)
if err != nil {
_ = encoder.Encode(processReply{Error: err.Error()})
return
@@ -138,7 +138,7 @@ func run_reader_process(mode string) {
if json.Unmarshal(scanner.Bytes(), &request) != nil || request.Stop {
return
}
command := child_command("client")
command := childCommand("client")
command.Env = append(command.Env, "FENRIR_CONTROL_PATH="+request.Path, "FENRIR_CONTROL_TEXT="+request.Text)
data, err := command.Output()
var reply processReply
@@ -159,9 +159,9 @@ type readerProcess struct {
stopped bool
}
func start_reader_process(t *testing.T, directory, mode string) *readerProcess {
func startReaderProcess(t *testing.T, directory, mode string) *readerProcess {
t.Helper()
command := child_command(mode)
command := childCommand(mode)
command.Env = append(command.Env, "FENRIR_CONTROL_DIRECTORY="+directory)
command.Stderr = os.Stderr
input, err := command.StdinPipe()
@@ -218,7 +218,7 @@ func (p *readerProcess) send(t *testing.T, path, text string) processReply {
return reply
}
func check_receipt(t *testing.T, reply processReply, instancePID int, text string) {
func checkReceipt(t *testing.T, reply processReply, instancePID int, text string) {
t.Helper()
var receipt requestReceipt
if err := json.Unmarshal([]byte(reply.Response), &receipt); err != nil {
@@ -229,7 +229,7 @@ func check_receipt(t *testing.T, reply processReply, instancePID int, text strin
}
}
func wait_main_owner(t *testing.T, observer *Server, expectedCount int, excludedPID int) int {
func waitMainOwner(t *testing.T, observer *Server, expectedCount int, excludedPID int) int {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
@@ -253,21 +253,21 @@ func wait_main_owner(t *testing.T, observer *Server, expectedCount int, excluded
func TestReadersCoexistInBothStartupOrdersAndSurviveOwnerExit(t *testing.T) {
for _, order := range []string{"tty-first", "terminal-first"} {
t.Run(order, func(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
observer := &Server{ctx: context.Background(), options: options}
mainPath := observer.main_path()
mainPath := observer.mainPath()
var tty, first, second, owner *readerProcess
if order == "tty-first" {
tty = start_reader_process(t, options.Directory, "tty")
tty = startReaderProcess(t, options.Directory, "tty")
owner = tty
first = start_reader_process(t, options.Directory, "terminal")
first = startReaderProcess(t, options.Directory, "terminal")
} else {
first = start_reader_process(t, options.Directory, "terminal")
first = startReaderProcess(t, options.Directory, "terminal")
owner = first
tty = start_reader_process(t, options.Directory, "tty")
tty = startReaderProcess(t, options.Directory, "tty")
}
second = start_reader_process(t, options.Directory, "terminal")
if got := wait_main_owner(t, observer, 3, 0); got != owner.pid {
second = startReaderProcess(t, options.Directory, "terminal")
if got := waitMainOwner(t, observer, 3, 0); got != owner.pid {
t.Fatal("startup replaced the shared owner", got, owner.pid)
}
listing := first.send(t, mainPath, "COMMAND LS").Response
@@ -277,12 +277,12 @@ func TestReadersCoexistInBothStartupOrdersAndSurviveOwnerExit(t *testing.T) {
}
}
for _, reader := range []*readerProcess{tty, first, second} {
check_receipt(t, reader.send(t, mainPath, "COMMAND SAY shared"), reader.pid, "COMMAND SAY shared")
checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY shared"), reader.pid, "COMMAND SAY shared")
privatePath := filepath.Join(options.Directory, fmt.Sprintf("fenrirscreenreader-%d.sock", reader.pid))
check_receipt(t, second.send(t, privatePath, "COMMAND SAY private"), reader.pid, "COMMAND SAY private")
checkReceipt(t, second.send(t, privatePath, "COMMAND SAY private"), reader.pid, "COMMAND SAY private")
}
// An unrelated caller must not fall through to the console reader.
client := child_command("client")
client := childCommand("client")
client.Env = append(client.Env, "FENRIR_CONTROL_PATH="+mainPath, "FENRIR_CONTROL_TEXT=COMMAND SAY legacy")
data, err := client.Output()
if err != nil {
@@ -296,19 +296,19 @@ func TestReadersCoexistInBothStartupOrdersAndSurviveOwnerExit(t *testing.T) {
t.Fatal("unidentified caller reached a reader", reply)
}
owner.stop(t)
wait_main_owner(t, observer, 2, owner.pid)
waitMainOwner(t, observer, 2, owner.pid)
for _, reader := range []*readerProcess{tty, first, second} {
if reader != owner {
check_receipt(t, reader.send(t, mainPath, "COMMAND SAY survivor"), reader.pid, "COMMAND SAY survivor")
checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY survivor"), reader.pid, "COMMAND SAY survivor")
}
}
})
}
}
func external_request(t *testing.T, path, text string) processReply {
func externalRequest(t *testing.T, path, text string) processReply {
t.Helper()
client := child_command("client")
client := childCommand("client")
client.Env = append(client.Env, "FENRIR_CONTROL_PATH="+path, "FENRIR_CONTROL_TEXT="+text)
data, err := client.Output()
if err != nil {
@@ -322,20 +322,20 @@ func external_request(t *testing.T, path, text string) processReply {
}
func TestTerminalReadersRejectAmbiguityAndRecoverAfterOwnerFailure(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
observer := &Server{ctx: context.Background(), options: options}
mainPath := observer.main_path()
first := start_reader_process(t, options.Directory, "terminal")
second := start_reader_process(t, options.Directory, "terminal")
third := start_reader_process(t, options.Directory, "terminal")
wait_main_owner(t, observer, 3, 0)
mainPath := observer.mainPath()
first := startReaderProcess(t, options.Directory, "terminal")
second := startReaderProcess(t, options.Directory, "terminal")
third := startReaderProcess(t, options.Directory, "terminal")
waitMainOwner(t, observer, 3, 0)
for _, reader := range []*readerProcess{first, second, third} {
check_receipt(t, reader.send(t, mainPath, "COMMAND SAY terminal"), reader.pid, "COMMAND SAY terminal")
checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY terminal"), reader.pid, "COMMAND SAY terminal")
}
if reply := external_request(t, mainPath, "COMMAND SAY ambiguous"); !strings.Contains(reply.Response, "unique reader") {
if reply := externalRequest(t, mainPath, "COMMAND SAY ambiguous"); !strings.Contains(reply.Response, "unique reader") {
t.Fatal("arbitrary terminal selected", reply)
}
if reply := external_request(t, mainPath, "LIST"); strings.Count(reply.Response, "pid=") != 6 {
if reply := externalRequest(t, mainPath, "LIST"); strings.Count(reply.Response, "pid=") != 6 {
// Each record contains both pid= and ppid=.
t.Fatal("ambiguous caller could not discover instances", reply)
}
@@ -367,9 +367,9 @@ func TestTerminalReadersRejectAmbiguityAndRecoverAfterOwnerFailure(t *testing.T)
t.Fatal(err)
}
_ = first.command.Wait()
wait_main_owner(t, observer, 2, first.pid)
waitMainOwner(t, observer, 2, first.pid)
for _, reader := range []*readerProcess{second, third} {
check_receipt(t, reader.send(t, mainPath, "COMMAND SAY recovered"), reader.pid, "COMMAND SAY recovered")
checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY recovered"), reader.pid, "COMMAND SAY recovered")
}
}
@@ -382,48 +382,48 @@ func TestWindowRoutingWithoutReaderAncestor(t *testing.T) {
name = "console-first"
}
t.Run(name, func(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
observer := &Server{ctx: context.Background(), options: options}
mainPath := observer.main_path()
mainPath := observer.mainPath()
t.Setenv("DISPLAY", ":fixture")
t.Setenv("WINDOWID", "42")
var terminal *readerProcess
if consoleFirst {
start_reader_process(t, options.Directory, "tty")
startReaderProcess(t, options.Directory, "tty")
}
terminal = start_reader_process(t, options.Directory, "terminal")
terminal = startReaderProcess(t, options.Directory, "terminal")
if !consoleFirst {
start_reader_process(t, options.Directory, "tty")
startReaderProcess(t, options.Directory, "tty")
}
// This client is a sibling, not a child, of the terminal reader.
text := "command application codex"
check_receipt(t, external_request(t, mainPath, text), terminal.pid, text)
checkReceipt(t, externalRequest(t, mainPath, text), terminal.pid, text)
t.Setenv("WINDOWID", "43")
second := start_reader_process(t, options.Directory, "terminal")
check_receipt(t, external_request(t, mainPath, text), second.pid, text)
second := startReaderProcess(t, options.Directory, "terminal")
checkReceipt(t, externalRequest(t, mainPath, text), second.pid, text)
t.Setenv("WINDOWID", "42")
check_receipt(t, external_request(t, mainPath, text), terminal.pid, text)
checkReceipt(t, externalRequest(t, mainPath, text), terminal.pid, text)
// Even a sole terminal on a different display is not a match.
t.Setenv("DISPLAY", ":other")
if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
t.Fatal("cross-display routing", reply)
}
t.Setenv("DISPLAY", ":fixture")
t.Setenv("WINDOWID", "unknown")
if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
t.Fatal("unknown window routed", reply)
}
t.Setenv("WINDOWID", "")
if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
t.Fatal("unidentified background caller routed", reply)
}
t.Setenv("WINDOWID", "42")
start_reader_process(t, options.Directory, "terminal")
if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
startReaderProcess(t, options.Directory, "terminal")
if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") {
t.Fatal("duplicate window routed arbitrarily", reply)
}
// Discovery remains usable when routing is ambiguous.
if reply := external_request(t, mainPath, "ls"); !strings.Contains(reply.Response, "pid=") {
if reply := externalRequest(t, mainPath, "ls"); !strings.Contains(reply.Response, "pid=") {
t.Fatal("discovery failed", reply)
}
})
@@ -431,7 +431,7 @@ func TestWindowRoutingWithoutReaderAncestor(t *testing.T) {
}
func TestConsoleIdentityAndUnknownCallers(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
console := instance{PID: os.Getpid(), uid: os.Geteuid(), ScreenDriver: "vcsaDriver"}
server := &Server{ctx: context.Background(), options: options}
for _, trial := range []struct {
@@ -448,13 +448,13 @@ func TestConsoleIdentityAndUnknownCallers(t *testing.T) {
{"unknown window", processIdentity{window: "42", display: ":fixture"}, []instance{console}, false},
} {
t.Run(trial.name, func(t *testing.T) {
_, err := server.route_identity(trial.identity, os.Geteuid(), nil, trial.consoles)
_, err := server.routeIdentity(trial.identity, os.Geteuid(), nil, trial.consoles)
if (err == nil) != trial.valid {
t.Fatal("unexpected routing", err)
}
})
}
if got := process_identity(os.Getpid(), os.Geteuid()+1); got != (processIdentity{}) {
if got := lookupProcessIdentity(os.Getpid(), os.Geteuid()+1); got != (processIdentity{}) {
t.Fatal("read identity of a different UID", got)
}
}
+2 -2
View File
@@ -55,7 +55,7 @@ func handoff(caller *net.UnixConn, path string) error {
return sendErr
}
func receive_request(connection *net.UnixConn) (string, *net.UnixConn, error) {
func receiveRequest(connection *net.UnixConn) (string, *net.UnixConn, error) {
_ = connection.SetReadDeadline(time.Now().Add(250 * time.Millisecond))
var buffer [8192]byte
control := make([]byte, syscall.CmsgSpace(4))
@@ -108,6 +108,6 @@ func receive_request(connection *net.UnixConn) (string, *net.UnixConn, error) {
}
return "", unix, nil
}
text, err := read_request(connection, buffer[:count])
text, err := readRequest(connection, buffer[:count])
return text, nil, err
}
+7 -7
View File
@@ -12,14 +12,14 @@ import (
"testing"
)
func socket_pair(t *testing.T, path string) (*net.UnixConn, *net.UnixConn) {
func socketPair(t *testing.T, path string) (*net.UnixConn, *net.UnixConn) {
t.Helper()
listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { listener.Close() })
client := connect_remote(t, path)
client := connectRemote(t, path)
server, err := listener.AcceptUnix()
if err != nil {
t.Fatal(err)
@@ -29,8 +29,8 @@ func socket_pair(t *testing.T, path string) (*net.UnixConn, *net.UnixConn) {
}
func TestHandoffReadsOriginalCallerBytesAndRejectsInvalidDescriptors(t *testing.T) {
options := private_options(t)
caller, original := socket_pair(t, filepath.Join(options.Directory, "caller.sock"))
options := privateOptions(t)
caller, original := socketPair(t, filepath.Join(options.Directory, "caller.sock"))
if _, err := io.WriteString(caller, "COMMAND SAY original\n"); err != nil {
t.Fatal(err)
}
@@ -55,12 +55,12 @@ func TestHandoffReadsOriginalCallerBytesAndRejectsInvalidDescriptors(t *testing.
{"header", "INVALID\n", []int{int(file.Fd())}, false},
} {
t.Run(trial.name, func(t *testing.T) {
sender, receiver := socket_pair(t, filepath.Join(options.Directory, trial.name+".sock"))
sender, receiver := socketPair(t, filepath.Join(options.Directory, trial.name+".sock"))
if _, _, err := sender.WriteMsgUnix([]byte(trial.header), syscall.UnixRights(trial.fds...), nil); err != nil {
t.Fatal(err)
}
_ = sender.CloseWrite()
_, forwarded, err := receive_request(receiver)
_, forwarded, err := receiveRequest(receiver)
if !trial.valid {
if forwarded != nil {
forwarded.Close()
@@ -78,7 +78,7 @@ func TestHandoffReadsOriginalCallerBytesAndRejectsInvalidDescriptors(t *testing.
if err != nil || pid != os.Getpid() || uid != os.Geteuid() {
t.Fatal("caller credentials changed", pid, uid, err)
}
text, err := read_request(forwarded, nil)
text, err := readRequest(forwarded, nil)
if err != nil || text != "COMMAND SAY original" {
t.Fatal("handoff substituted caller bytes", text, err)
}
+11 -10
View File
@@ -44,7 +44,7 @@ type instance struct {
uid int
}
func (s *Server) registry_dir() string {
func (s *Server) registryDir() string {
if s.options.RegistryDirectory != "" {
return s.options.RegistryDirectory
}
@@ -52,7 +52,7 @@ func (s *Server) registry_dir() string {
}
func (s *Server) register() error {
dir := s.registry_dir()
dir := s.registryDir()
if err := os.Mkdir(dir, os.ModeSticky|0777); err != nil && !os.IsExist(err) {
return err
}
@@ -81,9 +81,9 @@ func (s *Server) register() error {
if s.options.TerminalMode {
data.ScreenDriver, data.KeyboardDriver, data.WindowID = "ptyDriver", "x11Driver", s.options.WindowID
}
for _, endpoint := range s.endpoint_snapshot() {
for _, endpoint := range s.endpointSnapshot() {
data.SocketFiles = append(data.SocketFiles, endpoint.path)
data.MainSocket = data.MainSocket || endpoint.path == s.main_path()
data.MainSocket = data.MainSocket || endpoint.path == s.mainPath()
}
encoded, err := json.Marshal(data)
if err != nil {
@@ -93,7 +93,8 @@ func (s *Server) register() error {
if err != nil {
return err
}
defer os.Remove(file.Name())
// After a successful rename the temporary name no longer exists.
defer func() { _ = os.Remove(file.Name()) }()
if _, err := file.Write(append(encoded, '\n')); err != nil {
file.Close()
return err
@@ -113,7 +114,7 @@ func (s *Server) register() error {
return nil
}
func (s *Server) refresh_registry() {
func (s *Server) refreshRegistry() {
ticker := time.NewTicker(200 * time.Millisecond)
lastRefresh := time.Now()
defer ticker.Stop()
@@ -122,7 +123,7 @@ func (s *Server) refresh_registry() {
case <-s.ctx.Done():
return
case <-ticker.C:
if s.claim_main() || time.Since(lastRefresh) >= 10*time.Second {
if s.claimMain() || time.Since(lastRefresh) >= 10*time.Second {
_ = s.register()
lastRefresh = time.Now()
}
@@ -131,7 +132,7 @@ func (s *Server) refresh_registry() {
}
func (s *Server) instances() []instance {
entries, _ := os.ReadDir(s.registry_dir())
entries, _ := os.ReadDir(s.registryDir())
var instances []instance
for _, entry := range entries {
if s.ctx.Err() != nil {
@@ -140,7 +141,7 @@ func (s *Server) instances() []instance {
if !strings.HasSuffix(entry.Name(), ".json") {
continue
}
path := filepath.Join(s.registry_dir(), entry.Name())
path := filepath.Join(s.registryDir(), entry.Name())
file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
if err != nil {
continue
@@ -185,7 +186,7 @@ func (s *Server) list() string {
return strings.Join(lines, "\n")
}
func parent_pid(pid int) int {
func parentPid(pid int) int {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
if err != nil {
return 0
+9 -9
View File
@@ -17,11 +17,11 @@ import (
// its current display processes through the server's open terminal devices,
// then use their reader ancestry. No Screen commands or init services are used.
// procRoot is explicit so device, ownership and ambiguity cases can be tested.
func attached_screen_reader(procRoot string, ancestors []int, uid int, readers []instance) (instance, bool, error) {
func attachedScreenReader(procRoot string, ancestors []int, uid int, readers []instance) (instance, bool, error) {
for _, pid := range ancestors {
processPath := filepath.Join(procRoot, strconv.Itoa(pid))
info, err := os.Stat(processPath)
if err != nil || !owned_by(info, uid) {
if err != nil || !ownedBy(info, uid) {
continue
}
command, err := os.ReadFile(filepath.Join(processPath, "cmdline"))
@@ -37,18 +37,18 @@ func attached_screen_reader(procRoot string, ancestors []int, uid int, readers [
if err != nil {
continue
}
reader, err := screen_display_reader(procRoot, processPath, uid, executable, readers)
reader, err := screenDisplayReader(procRoot, processPath, uid, executable, readers)
return reader, true, err
}
return instance{}, false, nil
}
func owned_by(info os.FileInfo, uid int) bool {
func ownedBy(info os.FileInfo, uid int) bool {
stat, ok := info.Sys().(*syscall.Stat_t)
return ok && int(stat.Uid) == uid
}
func screen_display_reader(procRoot, serverPath string, uid int, executable os.FileInfo, readers []instance) (instance, error) {
func screenDisplayReader(procRoot, serverPath string, uid int, executable os.FileInfo, readers []instance) (instance, error) {
fdPath := filepath.Join(serverPath, "fd")
files, err := os.ReadDir(fdPath)
if err != nil {
@@ -79,14 +79,14 @@ func screen_display_reader(procRoot, serverPath string, uid int, executable os.F
}
path := filepath.Join(procRoot, process.Name())
info, err := os.Stat(path)
if err != nil || !owned_by(info, uid) {
if err != nil || !ownedBy(info, uid) {
continue
}
data, err := os.ReadFile(filepath.Join(path, "stat"))
if err != nil {
continue
}
_, tty := process_parent_tty(data)
_, tty := processParentTty(data)
if tty == 0 || !displays[tty] {
continue
}
@@ -113,7 +113,7 @@ func screen_display_reader(procRoot, serverPath string, uid int, executable os.F
if err != nil {
break
}
ancestor, _ = process_parent_tty(data)
ancestor, _ = processParentTty(data)
}
}
if len(matches) == 1 {
@@ -124,7 +124,7 @@ func screen_display_reader(procRoot, serverPath string, uid int, executable os.F
return instance{}, fmt.Errorf("Screen session does not identify a unique attached reader; use its private socket")
}
func process_parent_tty(data []byte) (int, uint32) {
func processParentTty(data []byte) (int, uint32) {
end := bytes.LastIndexByte(data, ')')
if end < 0 {
return 0, 0
+7 -7
View File
@@ -66,13 +66,13 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) {
if err != nil {
t.Skip("GNU Screen not installed")
}
options := private_options(t)
options := privateOptions(t)
// The shared owner and an unrelated old-window reader must never receive
// messages intended for the terminal displaying the reattached session.
t.Setenv("DISPLAY", ":fixture")
t.Setenv("WINDOWID", "old")
start_reader_process(t, options.Directory, "tty")
start_reader_process(t, options.Directory, "terminal")
startReaderProcess(t, options.Directory, "tty")
startReaderProcess(t, options.Directory, "terminal")
options.TerminalMode, options.WindowID = true, "current"
server, err := Open(context.Background(), options)
if err != nil {
@@ -117,7 +117,7 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) {
}
defer connection.Close()
connection.SetDeadline(time.Now().Add(3 * time.Second))
if err := json.NewEncoder(connection).Encode(processCommand{Path: server.main_path(), Text: text}); err != nil {
if err := json.NewEncoder(connection).Encode(processCommand{Path: server.mainPath(), Text: text}); err != nil {
t.Fatal(err)
}
var reply processReply
@@ -137,7 +137,7 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) {
time.Sleep(10 * time.Millisecond)
}
if reply := send("COMMAND SAY detached"); !strings.Contains(reply.Response, "unique attached reader") {
for pid := reply.PID; pid > 1; pid = parent_pid(pid) {
for pid := reply.PID; pid > 1; pid = parentPid(pid) {
command, _ := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
executable, _ := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid))
t.Logf("ancestor %d command %q executable %q", pid, command, executable)
@@ -175,7 +175,7 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) {
for {
reply := send("COMMAND SAY attached")
if !strings.HasPrefix(reply.Response, "Remote routing failed:") {
check_receipt(t, reply, os.Getpid(), "COMMAND SAY attached")
checkReceipt(t, reply, os.Getpid(), "COMMAND SAY attached")
break
}
if time.Now().After(deadline) {
@@ -183,5 +183,5 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) {
}
time.Sleep(10 * time.Millisecond)
}
check_receipt(t, send("COMMAND NOTIFY notification"), os.Getpid(), "COMMAND NOTIFY notification")
checkReceipt(t, send("COMMAND NOTIFY notification"), os.Getpid(), "COMMAND NOTIFY notification")
}
+6 -6
View File
@@ -17,7 +17,7 @@ type screenFixture struct {
t *testing.T
}
func new_screen_fixture(t *testing.T) screenFixture {
func newScreenFixture(t *testing.T) screenFixture {
t.Helper()
f := screenFixture{root: t.TempDir(), t: t}
f.executable = filepath.Join(f.root, "screen")
@@ -72,7 +72,7 @@ func (f screenFixture) attach(pid, reader int, device string, sameExecutable boo
func TestScreenAttachmentRouting(t *testing.T) {
for _, scenario := range []string{"attached", "detached", "other executable", "ambiguous", "duplicate displays", "reattached", "no reader", "wrong uid"} {
t.Run(scenario, func(t *testing.T) {
f := new_screen_fixture(t)
f := newScreenFixture(t)
uid := os.Geteuid()
readers := []instance{{PID: 300}, {PID: 400}}
if scenario != "detached" {
@@ -98,7 +98,7 @@ func TestScreenAttachmentRouting(t *testing.T) {
f.process(400, 1, 0, "reader", "")
f.attach(201, 400, "/dev/zero", true)
}
reader, handled, err := attached_screen_reader(f.root, []int{120, 100}, uid, readers)
reader, handled, err := attachedScreenReader(f.root, []int{120, 100}, uid, readers)
valid := scenario == "attached" || scenario == "duplicate displays" || scenario == "reattached"
if handled != (scenario != "wrong uid") || (err == nil && handled) != valid {
t.Fatal(reader, handled, err)
@@ -117,17 +117,17 @@ func TestScreenAttachmentRouting(t *testing.T) {
}
func TestScreenRoutingIgnoresEnvironmentWithoutServerAncestor(t *testing.T) {
f := new_screen_fixture(t)
f := newScreenFixture(t)
f.attach(200, 300, "/dev/null", true)
t.Setenv("STY", "100.session")
if _, handled, err := attached_screen_reader(f.root, []int{120}, os.Geteuid(), []instance{{PID: 300}}); handled || err != nil {
if _, handled, err := attachedScreenReader(f.root, []int{120}, os.Geteuid(), []instance{{PID: 300}}); handled || err != nil {
t.Fatal("environment selected an unrelated Screen session", handled, err)
}
// A broken ancestry cycle must terminate without choosing an unrelated reader.
f.process(301, 302, 0, "cycle", "")
f.process(302, 301, 0, "cycle", "")
f.attach(201, 301, "/dev/zero", true)
reader, handled, err := attached_screen_reader(f.root, []int{120, 100}, os.Geteuid(), []instance{{PID: 300}})
reader, handled, err := attachedScreenReader(f.root, []int{120, 100}, os.Geteuid(), []instance{{PID: 300}})
if !handled || err != nil || reader.PID != 300 {
t.Fatal(reader, handled, err)
}
+15 -15
View File
@@ -76,7 +76,7 @@ type Server struct {
done chan struct{}
}
func (s *Server) main_path() string {
func (s *Server) mainPath() string {
if s.options.Directory != "" {
return filepath.Join(s.options.Directory, filepath.Base(MainSocket))
}
@@ -84,15 +84,15 @@ func (s *Server) main_path() string {
}
func Open(ctx context.Context, options Options) (*Server, error) {
return open_server(ctx, options, nil)
return openServer(ctx, options, nil)
}
// Keep process inspection injectable so fixture readers can exclude the host's
// terminal ancestry while retaining real sockets, credentials and handoffs.
func open_server(ctx context.Context, options Options, lookup screenLookup) (*Server, error) {
func openServer(ctx context.Context, options Options, lookup screenLookup) (*Server, error) {
ctx, cancel := context.WithCancel(ctx)
s := &Server{ctx: ctx, cancel: cancel, options: options, screenReader: lookup, requests: make(chan Request, 32), clients: make(chan struct{}, 8), done: make(chan struct{})}
paths := []string{filepath.Join(filepath.Dir(s.main_path()), fmt.Sprintf("fenrirscreenreader-%d.sock", os.Getpid())), s.main_path()}
paths := []string{filepath.Join(filepath.Dir(s.mainPath()), fmt.Sprintf("fenrirscreenreader-%d.sock", os.Getpid())), s.mainPath()}
if options.SocketFile != "" {
paths = []string{options.SocketFile}
}
@@ -114,7 +114,7 @@ func open_server(ctx context.Context, options Options, lookup screenLookup) (*Se
for _, endpoint := range s.endpoints {
s.workers.Go(func() { s.accept(endpoint) })
}
s.workers.Go(s.refresh_registry)
s.workers.Go(s.refreshRegistry)
return s, nil
}
@@ -132,7 +132,7 @@ func listen(path string) (endpoint, error) {
return endpoint{}, fmt.Errorf("%w %s", errSocketBusy, path)
}
if errors.Is(dialErr, syscall.EACCES) {
return endpoint{}, fmt.Errorf("%w %s: %v", errSocketBusy, path, dialErr)
return endpoint{}, fmt.Errorf("%w %s: %w", errSocketBusy, path, dialErr)
}
if !errors.Is(dialErr, syscall.ECONNREFUSED) {
return endpoint{}, fmt.Errorf("cannot establish remote socket is stale: %s: %w", path, dialErr)
@@ -165,7 +165,7 @@ func listen(path string) (endpoint, error) {
// checked by the application before any request may mutate reader state.
if err := os.Chmod(path, 0666); err != nil {
listener.Close()
os.Remove(path)
_ = os.Remove(path) // Best effort; the chmod error is reported.
return endpoint{}, err
}
info, err := os.Lstat(path)
@@ -239,7 +239,7 @@ func peer(connection *net.UnixConn) (int, int, error) {
return int(credentials.Pid), int(credentials.Uid), nil
}
func read_request(connection *net.UnixConn, data []byte) (string, error) {
func readRequest(connection *net.UnixConn, data []byte) (string, error) {
_ = connection.SetReadDeadline(time.Now().Add(250 * time.Millisecond))
var buffer [8130]byte
if len(data) > 8129 {
@@ -253,7 +253,7 @@ func read_request(connection *net.UnixConn, data []byte) (string, error) {
}
if err != nil {
var timeout net.Error
if err != io.EOF && !(errors.As(err, &timeout) && timeout.Timeout() && len(data) > 0) {
if !errors.Is(err, io.EOF) && !(errors.As(err, &timeout) && timeout.Timeout() && len(data) > 0) {
return "", err
}
break
@@ -276,9 +276,9 @@ func (s *Server) handle(connection *net.UnixConn, path string) {
// Route before consuming request bytes. A handed-off descriptor carries
// both the caller's kernel credentials and the caller's original request.
var routingErr error
if path == s.main_path() {
if path == s.mainPath() {
var target string
target, routingErr = s.route_target(pid, uid)
target, routingErr = s.routeTarget(pid, uid)
if routingErr == nil && target != "" {
routingErr = handoff(connection, target)
if routingErr == nil {
@@ -286,20 +286,20 @@ func (s *Server) handle(connection *net.UnixConn, path string) {
}
}
}
text, forwarded, err := receive_request(connection)
text, forwarded, err := receiveRequest(connection)
if forwarded != nil {
defer forwarded.Close()
connection = forwarded
pid, uid, err = peer(connection)
if err == nil {
// Handoffs never nest and never supply replacement request text.
text, err = read_request(connection, nil)
text, err = readRequest(connection, nil)
}
}
if err != nil || text == "" {
return
}
if is_list(text) {
if isList(text) {
_ = connection.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
_, _ = io.WriteString(connection, s.list()+"\n")
return
@@ -332,7 +332,7 @@ func (s *Server) handle(connection *net.UnixConn, path string) {
}
}
func is_list(text string) bool {
func isList(text string) bool {
switch strings.ToUpper(text) {
case "LS", "LIST", "COMMAND LS", "COMMAND LIST":
return true
+22 -22
View File
@@ -30,7 +30,7 @@ import (
"time"
)
func private_options(t *testing.T) Options {
func privateOptions(t *testing.T) Options {
t.Helper()
directory, err := os.MkdirTemp("/tmp", "fenrir-remote-")
if err != nil {
@@ -40,7 +40,7 @@ func private_options(t *testing.T) Options {
return Options{Directory: directory, RegistryDirectory: filepath.Join(directory, "registry")}
}
func connect_remote(t *testing.T, path string) *net.UnixConn {
func connectRemote(t *testing.T, path string) *net.UnixConn {
t.Helper()
connection, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
@@ -52,13 +52,13 @@ func connect_remote(t *testing.T, path string) *net.UnixConn {
}
func TestPythonSocketProtocolAndRegistry(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
server, err := Open(context.Background(), options)
if err != nil {
t.Fatal(err)
}
defer server.Close()
connection := connect_remote(t, server.main_path())
connection := connectRemote(t, server.mainPath())
if _, err := io.WriteString(connection, "command say Existing Bash script\n"); err != nil {
t.Fatal(err)
}
@@ -72,14 +72,14 @@ func TestPythonSocketProtocolAndRegistry(t *testing.T) {
t.Fatal("command was not delivered")
}
for _, command := range []string{"LIST", "command ls"} {
connection := connect_remote(t, server.main_path())
connection := connectRemote(t, server.mainPath())
io.WriteString(connection, command+"\n")
response, err := io.ReadAll(connection)
if err != nil || !strings.Contains(string(response), "screen=vcsaDriver keyboard=evdevDriver main_socket=yes") {
t.Fatal(string(response), err)
}
}
info, err := os.Stat(server.main_path())
info, err := os.Stat(server.mainPath())
if err != nil || info.Mode().Perm() != 0666 {
t.Fatal(info, err)
}
@@ -90,12 +90,12 @@ func TestPythonSocketProtocolAndRegistry(t *testing.T) {
}
func TestRequestTimeoutReturnsErrorInsteadOfSilentSuccess(t *testing.T) {
server, err := Open(context.Background(), private_options(t))
server, err := Open(context.Background(), privateOptions(t))
if err != nil {
t.Fatal(err)
}
defer server.Close()
connection := connect_remote(t, server.main_path())
connection := connectRemote(t, server.mainPath())
if _, err := io.WriteString(connection, "SETTING SAVE\n"); err != nil {
t.Fatal(err)
}
@@ -111,7 +111,7 @@ func TestRequestTimeoutReturnsErrorInsteadOfSilentSuccess(t *testing.T) {
}
func TestFullRequestQueueReturnsErrorInsteadOfSilentSuccess(t *testing.T) {
server, err := Open(context.Background(), private_options(t))
server, err := Open(context.Background(), privateOptions(t))
if err != nil {
t.Fatal(err)
}
@@ -119,7 +119,7 @@ func TestFullRequestQueueReturnsErrorInsteadOfSilentSuccess(t *testing.T) {
for range cap(server.requests) {
server.requests <- Request{}
}
connection := connect_remote(t, server.main_path())
connection := connectRemote(t, server.mainPath())
if _, err := io.WriteString(connection, "SETTING SAVE\n"); err != nil {
t.Fatal(err)
}
@@ -132,12 +132,12 @@ func TestFullRequestQueueReturnsErrorInsteadOfSilentSuccess(t *testing.T) {
func TestCancelledRequestReturnsUnknownCompletion(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
server, err := Open(ctx, private_options(t))
server, err := Open(ctx, privateOptions(t))
if err != nil {
t.Fatal(err)
}
defer server.Close()
connection := connect_remote(t, server.main_path())
connection := connectRemote(t, server.mainPath())
if _, err := io.WriteString(connection, "SETTING SAVE\n"); err != nil {
t.Fatal(err)
}
@@ -154,7 +154,7 @@ func TestCancelledRequestReturnsUnknownCompletion(t *testing.T) {
}
func TestSocketCoexistenceAndCleanupNeverReplaceActiveReader(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
server, err := Open(context.Background(), options)
if err != nil {
t.Fatal(err)
@@ -168,7 +168,7 @@ func TestSocketCoexistenceAndCleanupNeverReplaceActiveReader(t *testing.T) {
if len(server.instances()) != 1 {
t.Fatal("active registry entry removed")
}
if connection, err := net.Dial("unix", server.main_path()); err != nil {
if connection, err := net.Dial("unix", server.mainPath()); err != nil {
t.Fatal("main socket lost", err)
} else {
connection.Close()
@@ -177,7 +177,7 @@ func TestSocketCoexistenceAndCleanupNeverReplaceActiveReader(t *testing.T) {
func TestSocketRejectsSymlinksAndUnrelatedFiles(t *testing.T) {
for _, symlink := range []bool{false, true} {
options := private_options(t)
options := privateOptions(t)
path := filepath.Join(options.Directory, "fenrirscreenreader-daemon.sock")
if symlink {
if err := os.Symlink("/dev/null", path); err != nil {
@@ -197,16 +197,16 @@ func TestSocketRejectsSymlinksAndUnrelatedFiles(t *testing.T) {
}
func TestSilentAndOversizedClientsDoNotBlockOtherRequests(t *testing.T) {
server, err := Open(context.Background(), private_options(t))
server, err := Open(context.Background(), privateOptions(t))
if err != nil {
t.Fatal(err)
}
defer server.Close()
silent := connect_remote(t, server.main_path())
silent := connectRemote(t, server.mainPath())
defer silent.Close()
oversized := connect_remote(t, server.main_path())
oversized := connectRemote(t, server.mainPath())
io.WriteString(oversized, strings.Repeat("x", 9000))
good := connect_remote(t, server.main_path())
good := connectRemote(t, server.mainPath())
io.WriteString(good, "COMMAND INTERRUPT\n")
select {
case request := <-server.Requests():
@@ -225,7 +225,7 @@ func TestSilentAndOversizedClientsDoNotBlockOtherRequests(t *testing.T) {
}
func TestStaleSocketReplacementAndPrivateInstanceSelection(t *testing.T) {
options := private_options(t)
options := privateOptions(t)
path := filepath.Join(options.Directory, "stale.sock")
old, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
@@ -257,11 +257,11 @@ func TestStaleSocketReplacementAndPrivateInstanceSelection(t *testing.T) {
}
options.TerminalMode = true
server := &Server{ctx: context.Background(), options: options}
target, err := server.route_target(pid, os.Geteuid())
target, err := server.routeTarget(pid, os.Geteuid())
if err != nil || target != privatePath {
t.Fatal("registered ancestor instance not selected", target, err)
}
target, err = server.route_target(pid, os.Geteuid()+1)
target, err = server.routeTarget(pid, os.Geteuid()+1)
if err == nil || target != "" {
t.Fatal("forwarded to another user's instance", target, err)
}