diff --git a/modules/i3/cmd/i3-tools/main.go b/modules/i3/cmd/i3-tools/main.go index 82de29aa6..cb9a4ba33 100644 --- a/modules/i3/cmd/i3-tools/main.go +++ b/modules/i3/cmd/i3-tools/main.go @@ -14,6 +14,7 @@ import ( "path/filepath" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" stdio "git.novox.be/novox/mesh-sdk/go" "i3/internal/desktop" @@ -53,7 +54,8 @@ func machine() *i3 { if state == "" { state = filepath.Join(home, ".local", "state") } - t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), handAct: liveHandAct} + t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), + handAct: liveHandAct, opener: openerRun} t.socket = func() (string, error) { runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid())) i3sock := "" @@ -84,7 +86,7 @@ func tools(t *i3) []stdio.Tool { Run: call(t.reload), }, { - Name: "node-display-session.open", + Name: nodedisplaysession.Seat + "." + nodedisplaysession.VerbOpen, Description: "Open an http or https address in the person's default browser, for any caller over the bus " + "(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " + "too long once encoded, no graphical session or no default program for the scheme; the opener's " + diff --git a/modules/i3/cmd/i3-tools/open.go b/modules/i3/cmd/i3-tools/open.go index b48939e68..491fb23d6 100644 --- a/modules/i3/cmd/i3-tools/open.go +++ b/modules/i3/cmd/i3-tools/open.go @@ -2,18 +2,24 @@ // address in the person's default browser, outside i3's own IPC (which hands a shell a command // line); this verb takes the address as one argument, through the account's own program chooser // (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act -// (ADR 0565 §10): each call that is acted on is written to the log of acts done by hand. +// (ADR 0565 §10): every call, refused or not, is written to the log of acts done by hand (lead +// answer note (b), DQ-7: "each call"). package main import ( + "bytes" "context" + "errors" "fmt" "os" + "os/exec" "path/filepath" "regexp" "strings" + "syscall" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" stdio "git.novox.be/novox/mesh-sdk/go" "i3/internal/desktop" @@ -144,36 +150,93 @@ func xdgDataDirs() []string { return dirs } +// openerRun runs the opener (systemd-run --wait -- xdg-open ...): it stops waiting at its bound +// without killing what it started (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5), unlike +// internal/desktop's Exec (run.go), which kills the command's process group at its deadline. A page +// still opening at the bound is left to open: the browser outlives this call either way, since it +// runs under the account's own service manager (systemd-run --user), not as this process's child. +func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + res := desktop.Result{Command: append([]string{name}, args...)} + cmd := exec.Command(name, args...) + cmd.Env = env + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if stdin != nil { + cmd.Stdin = bytes.NewReader(stdin) + } + var out, errb bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errb + if err := cmd.Start(); err != nil { + res.Code = 127 + res.Stderr = err.Error() + return res + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case err := <-done: + res.Stdout, res.Stderr = out.String(), errb.String() + var exit *exec.ExitError + switch { + case err == nil: + case errors.As(err, &exit): + res.Code = exit.ExitCode() + if res.Code < 0 { + res.Code = 128 + } + default: + res.Code = 1 + if res.Stderr == "" { + res.Stderr = err.Error() + } + } + case <-ctx.Done(): + // Left to go on (DMC-8, C-5): no signal is sent, so the process it started keeps running; + // the goroutine above still reads its exit, harmlessly, once it does. + res.TimedOut = true + } + return res +} + // open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's // default browser for the scheme, and answers once the opener has started. -func (t *i3) open(ctx context.Context, a desktop.Args) (any, error) { +func (t *i3) open(ctx context.Context, a desktop.Args) (ret any, err error) { caller := stdio.CallerOf(map[string]any(a)) - address, err := a.Text("address") + why := fmt.Sprintf("asked by %s", caller) + var address, encoded, program, started string + + defer func() { + switch { + case err != nil: + t.journalOpen(address, "refused", err.Error()) + t.recordHandAct(fmt.Sprintf("refused %s: %s", address, err), why) + default: + t.journalOpen(address, started, program) + t.recordHandAct(fmt.Sprintf("%s %s in %s", started, encoded, program), why) + } + }() + + address, err = a.Text("address") if err != nil { return nil, err } scheme, err := checkAddressShape(address) if err != nil { - t.journalOpen(address, "refused", err.Error()) return nil, err } - encoded := encodeAddress(address) + encoded = encodeAddress(address) if len(encoded) > openMaxAddress { - err := fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) - t.journalOpen(address, "refused", err.Error()) + err = fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) return nil, err } s, err := t.d.Find() if err != nil { - t.journalOpen(address, "refused", err.Error()) return nil, err } env := s.Env(t.d.Base) - program, err := defaultProgram(ctx, t.d, env, scheme) + program, err = defaultProgram(ctx, t.d, env, scheme) if err != nil { - t.journalOpen(address, "refused", err.Error()) return nil, err } @@ -183,22 +246,23 @@ func (t *i3) open(ctx context.Context, a desktop.Args) (any, error) { } runCtx, cancel := context.WithTimeout(ctx, bound) defer cancel() - res := t.d.Run(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) + runner := t.opener + if runner == nil { + runner = openerRun + } + res := runner(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) if !res.OK() && !res.TimedOut { - reason := res.Err().Error() - t.journalOpen(address, "refused", reason) - return nil, fmt.Errorf("the opener failed: %s", reason) + err = fmt.Errorf("the opener failed: %s", res.Err().Error()) + return nil, err } - started := "opened" + started = nodedisplaysession.OpenAnswerStartedOpened if res.TimedOut { - started = "opening" + started = nodedisplaysession.OpenAnswerStartedOpening } command := entryCommand(program) - t.journalOpen(address, started, program) - t.recordHandAct(caller, encoded, program, started) - return map[string]any{"address": encoded, "program": program, "command": command, "started": started}, nil + return nodedisplaysession.OpenAnswer{Address: encoded, Program: program, Command: command, Started: started}, nil } // journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14): @@ -207,15 +271,12 @@ func (t *i3) journalOpen(address, outcome, programOrReason string) { fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason) } -// recordHandAct writes open's call to the log of acts done by hand (design 08 sign-in-page §29; -// ADR 0565 §10): open is an act, so every call that is acted on (never a refusal before the -// opener ran) is recorded with its caller and why. -func (t *i3) recordHandAct(caller, address, program, started string) { +// recordHandAct writes one call of open to the log of acts done by hand (design 08 sign-in-page +// §29; ADR 0565 §10; lead answer note (b)): every call, refused or not, with its caller and why. +func (t *i3) recordHandAct(what, why string) { if t.handAct == nil { return } - what := fmt.Sprintf("%s %s in %s", started, address, program) - why := fmt.Sprintf("asked by %s", caller) if err := t.handAct(what, why); err != nil { fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err) } diff --git a/modules/i3/cmd/i3-tools/open_test.go b/modules/i3/cmd/i3-tools/open_test.go index f36f139b5..71c60e1d1 100644 --- a/modules/i3/cmd/i3-tools/open_test.go +++ b/modules/i3/cmd/i3-tools/open_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" + "i3/internal/desktop" ) @@ -18,25 +20,44 @@ type runCall struct { args []string } -// stubOpener builds an i3 whose session is found (unless find answers an error) and whose -// commands are answered from answers, keyed by the command's name ("xdg-mime", "systemd-run"); -// every call is recorded in calls. -func stubOpener(t *testing.T, find func() (*desktop.Session, error), answers map[string]desktop.Result) (*i3, *[]runCall) { +// stubOpener builds an i3 whose session is found (unless find answers an error), whose xdg-mime +// query answers xdgMime, and whose opener answers the systemd-run call with opener (nil runs it is +// never reached). Every call, to either, is recorded in calls. +func stubOpener(t *testing.T, find func() (*desktop.Session, error), xdgMime desktop.Result, opener desktop.Runner) (*i3, *[]runCall) { t.Helper() calls := &[]runCall{} run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { *calls = append(*calls, runCall{name, args}) - res, ok := answers[name] - if !ok { - t.Fatalf("unexpected command %s %v", name, args) + if name != "xdg-mime" { + t.Fatalf("unexpected command on the session's own run: %s %v", name, args) } + return xdgMime + } + var wrapped desktop.Runner + if opener != nil { + wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + *calls = append(*calls, runCall{name, args}) + return opener(ctx, env, stdin, name, args...) + } + } else { + wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + t.Fatalf("the opener never runs: %s %v", name, args) + return desktop.Result{} + } + } + return &i3{d: desktop.Desk{Find: find, Run: run}, opener: wrapped, openBound: 50 * time.Millisecond}, calls +} + +// resultOpener is an opener stub that answers res, blocking on ctx when res.TimedOut (as a real +// still-running opener would appear to this call). +func resultOpener(res desktop.Result) desktop.Runner { + return func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { if res.TimedOut { <-ctx.Done() return desktop.Result{TimedOut: true} } return res } - return &i3{d: desktop.Desk{Find: find, Run: run}, openBound: 50 * time.Millisecond}, calls } func foundSession() (*desktop.Session, error) { @@ -59,7 +80,7 @@ func writeDesktopEntry(t *testing.T, entry, execLine string) { // 935/I-1: every scheme but http and https, and a file path, is refused. func TestOpenRefusesEveryOtherScheme(t *testing.T) { - x, calls := stubOpener(t, foundSession, map[string]desktop.Result{}) + x, calls := stubOpener(t, foundSession, desktop.Result{}, nil) for _, address := range []string{ "/etc/passwd", // no scheme: a file path "file:///etc/passwd", // a scheme other than http or https @@ -73,13 +94,13 @@ func TestOpenRefusesEveryOtherScheme(t *testing.T) { } } if len(*calls) != 0 { - t.Fatalf("a refused address never reaches the opener: %v", *calls) + t.Fatalf("a refused address never reaches xdg-mime or the opener: %v", *calls) } } // 935/I-1: an address over 2048 bytes once encoded is refused. func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) { - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{}) + x, _ := stubOpener(t, foundSession, desktop.Result{}, nil) address := "https://example.net/" + strings.Repeat("a", 2048) if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil { t.Fatal("not refused") @@ -90,7 +111,7 @@ func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) { func TestOpenRefusesWithNoGraphicalSession(t *testing.T) { x, _ := stubOpener(t, func() (*desktop.Session, error) { return nil, &desktop.NoSession{Reason: "none"} - }, map[string]desktop.Result{}) + }, desktop.Result{}, nil) _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if !desktop.IsNoSession(err) { t.Fatalf("%v", err) @@ -99,36 +120,26 @@ func TestOpenRefusesWithNoGraphicalSession(t *testing.T) { // 935/I-1: no default program for the scheme is refused. func TestOpenRefusesWithNoDefaultProgram(t *testing.T) { - x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: ""}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: ""}, nil) if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil { t.Fatal("not refused") } - for _, c := range *calls { - if c.name == "systemd-run" { - t.Fatal("the opener never runs with no default program") - } - } } // 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its // UTF-8 form, and the address reaches the opener as one argument, never a shell command line. func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 0}, - }) + x, calls := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0})) address := `https://example.net/a'b;c d$(e),f"g` got, err := run(t, x, "node-display-session.open", map[string]any{"address": address}) if err != nil { t.Fatal(err) } want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g` - answer := got.(map[string]any) - if answer["address"] != want { - t.Fatalf("got %q, want %q", answer["address"], want) + answer := got.(nodedisplaysession.OpenAnswer) + if answer.Address != want { + t.Fatalf("got %q, want %q", answer.Address, want) } var last runCall for _, c := range *calls { @@ -149,10 +160,8 @@ func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) { // 935/I-3: an opener that fails is refused with its status and names no program. func TestOpenRefusesWhenTheOpenerFails(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 1, Stderr: "no such unit"}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, + resultOpener(desktop.Result{Code: 1, Stderr: "no such unit"})) _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if err == nil || !strings.Contains(err.Error(), "no such unit") { t.Fatalf("%v", err) @@ -162,16 +171,13 @@ func TestOpenRefusesWhenTheOpenerFails(t *testing.T) { // 935/I-3: an opener that ends well answers opened with the program. func TestOpenAnswersOpenedWithTheProgram(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 0}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0})) got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if err != nil { t.Fatal(err) } - answer := got.(map[string]any) - if answer["started"] != "opened" || answer["program"] != "browser.desktop" || answer["command"] != "firefox" { + answer := got.(nodedisplaysession.OpenAnswer) + if answer.Started != nodedisplaysession.OpenAnswerStartedOpened || answer.Program != "browser.desktop" || answer.Command != "firefox" { t.Fatalf("%+v", answer) } } @@ -180,28 +186,48 @@ func TestOpenAnswersOpenedWithTheProgram(t *testing.T) { // names the program only once the opener started). func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {TimedOut: true}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{TimedOut: true})) got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if err != nil { t.Fatal(err) } - answer := got.(map[string]any) - if answer["started"] != "opening" || answer["program"] != "browser.desktop" { + answer := got.(nodedisplaysession.OpenAnswer) + if answer.Started != nodedisplaysession.OpenAnswerStartedOpening || answer.Program != "browser.desktop" { t.Fatalf("%+v", answer) } } -// DQ-7: each call that is acted on writes one act to the log of acts done by hand, with its caller -// and why; a refusal before the opener ran writes none. -func TestOpenWritesOneActDoneByHand(t *testing.T) { +// C-5: cmd/i3-tools runs the opener with its own run (openerRun, not internal/desktop's Exec, which +// kills a command's process group at its deadline, run.go:82-86): it stops waiting at its bound +// without killing what it started, so an opener still running past the bound keeps running and +// finishes on its own. +func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) { + marker := filepath.Join(t.TempDir(), "ran") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + start := time.Now() + res := openerRun(ctx, os.Environ(), nil, "sh", "-c", "sleep 0.15; touch "+marker) + if !res.TimedOut { + t.Fatalf("expected TimedOut, got %+v", res) + } + if since := time.Since(start); since > 200*time.Millisecond { + t.Fatalf("openerRun waited past its own bound: %s", since) + } + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if _, err := os.Stat(marker); err == nil { + return // the process kept running after openerRun gave up waiting, and finished: not killed + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("the opener process was killed: it never finished past the bound") +} + +// DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its +// caller and why — a successful one and a refused one alike. +func TestOpenWritesOneActDoneByHandForEveryCall(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 0}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0})) var recorded []string x.handAct = func(what, why string) error { recorded = append(recorded, what+"|"+why) @@ -218,7 +244,7 @@ func TestOpenWritesOneActDoneByHand(t *testing.T) { if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil { t.Fatal("expected a refusal") } - if len(recorded) != 0 { - t.Fatalf("a refusal before the opener ran writes no act: %v", recorded) + if len(recorded) != 1 || !strings.Contains(recorded[0], "refused") || !strings.Contains(recorded[0], "ftp://example.net") { + t.Fatalf("a refusal writes an act too (note (b)): %v", recorded) } } diff --git a/modules/i3/cmd/i3-tools/tools.go b/modules/i3/cmd/i3-tools/tools.go index 5835985a5..73c812006 100644 --- a/modules/i3/cmd/i3-tools/tools.go +++ b/modules/i3/cmd/i3-tools/tools.go @@ -25,6 +25,9 @@ type i3 struct { // openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens // it so a still-running opener is seen without waiting out the real bound. openBound time.Duration + // opener runs the opener command: openerRun (design 08 sign-in-page §29; DMC-8, lead answer C-5) + // unless a test replaces it to control the opener's outcome directly. + opener desktop.Runner } func (t *i3) ask(kind uint32, payload string, out any) error { diff --git a/modules/i3/go.mod b/modules/i3/go.mod index 645d3fdbe..c5901cd6d 100644 --- a/modules/i3/go.mod +++ b/modules/i3/go.mod @@ -2,7 +2,10 @@ module i3 go 1.26.0 -require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +require ( + git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +) require ( github.com/klauspost/compress v1.20.1 // indirect