Files
mesh-catalog/modules/i3/cmd/i3-tools/open.go
T
jochen 9a3149df88 i3: test the opener's no-kill run with pipes, never a real sleep
Code review round 2 (C-5 follow-up). openerRun's core is now runWithoutKilling(ctx,
*exec.Cmd), callable directly by a test with a command of its own. The test's child
blocks reading its stdin (a pipe held open past the bound); after confirming
TimedOut, the test closes the pipe to unblock it, then waits on the child's own
end (a byte written to an extra file just before it exits, read with a plain
blocking read) instead of sleeping and polling for a marker file. A kill at the
bound now leaves that read empty, which the test checked by reintroducing the old
signal and watching it fail.

Builds: design 08 sign-in-page §3, §29
2026-11-25 01:13:18 +01:00

301 lines
10 KiB
Go

// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https
// 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): 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"
)
// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a
// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener
// is left to go on and the answer says opening. A test shortens it with the i3's openBound field.
const defaultOpenTimeout = 10 * time.Second
// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3).
const openMaxAddress = 2048
// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter,
// ended by a colon.
var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`)
// openKept are the characters open's encoding never touches, beside the unreserved ones (letters,
// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is
// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9).
const openKept = "-._~:/?#[]@&=+%"
// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme
// other than http or https, no scheme (a file path), no host.
func checkAddressShape(address string) (scheme string, err error) {
m := schemePattern.FindStringSubmatch(address)
if m == nil {
return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address)
}
scheme = strings.ToLower(m[1])
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("a scheme other than http or https: %s", scheme)
}
afterScheme := address[len(m[0]):]
if !strings.HasPrefix(afterScheme, "//") {
return "", fmt.Errorf("no host: %s has no // after its scheme", scheme)
}
rest := afterScheme[2:]
end := strings.IndexAny(rest, "/?#")
authority := rest
if end >= 0 {
authority = rest[:end]
}
if at := strings.LastIndex(authority, "@"); at >= 0 {
authority = authority[at+1:]
}
if authority == "" {
return "", fmt.Errorf("no host")
}
return scheme, nil
}
// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs
// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form.
// Nothing is refused for a character, and the result is never read by a shell.
func encodeAddress(address string) string {
var b strings.Builder
for i := 0; i < len(address); i++ {
c := address[i]
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
b.WriteByte(c)
case strings.IndexByte(openKept, c) >= 0:
b.WriteByte(c)
default:
fmt.Fprintf(&b, "%%%02X", c)
}
}
return b.String()
}
// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason:
// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is
// none.
func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) {
res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme)
name := strings.TrimSpace(res.Stdout)
if !res.OK() || name == "" {
return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme)
}
return name, nil
}
// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data
// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes
// and arguments.
func entryCommand(entry string) string {
for _, dir := range xdgDataDirs() {
b, err := os.ReadFile(filepath.Join(dir, "applications", entry))
if err != nil {
continue
}
inEntry := false
for _, line := range strings.Split(string(b), "\n") {
line = strings.TrimSpace(line)
switch {
case strings.HasPrefix(line, "["):
inEntry = line == "[Desktop Entry]"
case inEntry:
if exec, ok := strings.CutPrefix(line, "Exec="); ok {
if fields := strings.Fields(exec); len(fields) > 0 {
return fields[0]
}
return ""
}
}
}
}
return ""
}
// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the
// system's (XDG_DATA_DIRS, or its default).
func xdgDataDirs() []string {
dirs := []string{os.Getenv("XDG_DATA_HOME")}
if dirs[0] == "" {
dirs[0] = filepath.Join(desktop.Home(), ".local", "share")
}
extra := os.Getenv("XDG_DATA_DIRS")
if extra == "" {
extra = "/usr/local/share:/usr/share"
}
for _, d := range strings.Split(extra, ":") {
if d != "" {
dirs = append(dirs, d)
}
}
return dirs
}
// openerRun runs the opener (systemd-run --wait -- xdg-open ...) through runWithoutKilling: 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 {
cmd := exec.Command(name, args...)
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if stdin != nil {
cmd.Stdin = bytes.NewReader(stdin)
}
return runWithoutKilling(ctx, cmd)
}
// runWithoutKilling starts cmd and waits for it, but stops waiting at ctx's deadline without
// sending cmd any signal (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5): left to go on,
// never torn down by the bound that only governs how long this call waits. A test calls this
// directly, with a command of its own whose Stdin and ExtraFiles it controls, to prove the started
// process is never killed, without a real sleep on either side.
func runWithoutKilling(ctx context.Context, cmd *exec.Cmd) desktop.Result {
res := desktop.Result{Command: append([]string{cmd.Path}, cmd.Args[1:]...)}
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) (ret any, err error) {
caller := stdio.CallerOf(map[string]any(a))
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 {
return nil, err
}
encoded = encodeAddress(address)
if len(encoded) > openMaxAddress {
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 {
return nil, err
}
env := s.Env(t.d.Base)
program, err = defaultProgram(ctx, t.d, env, scheme)
if err != nil {
return nil, err
}
bound := t.openBound
if bound == 0 {
bound = defaultOpenTimeout
}
runCtx, cancel := context.WithTimeout(ctx, bound)
defer cancel()
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 {
err = fmt.Errorf("the opener failed: %s", res.Err().Error())
return nil, err
}
started = nodedisplaysession.OpenAnswerStartedOpened
if res.TimedOut {
started = nodedisplaysession.OpenAnswerStartedOpening
}
command := entryCommand(program)
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):
// the address, opened or refused, and the program or the reason.
func (t *i3) journalOpen(address, outcome, programOrReason string) {
fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason)
}
// 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
}
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)
}
}
// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module
// (design 08 sign-in-page §29).
func liveHandAct(what, why string) error {
_, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"})
return err
}