// 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): each call that is acted on is written to the log of acts done by hand. package main import ( "context" "fmt" "os" "path/filepath" "regexp" "strings" "time" 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 } // 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) { caller := stdio.CallerOf(map[string]any(a)) 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) 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()) 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) if err != nil { t.journalOpen(address, "refused", err.Error()) return nil, err } bound := t.openBound if bound == 0 { bound = defaultOpenTimeout } runCtx, cancel := context.WithTimeout(ctx, bound) defer cancel() res := t.d.Run(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) } started := "opened" if res.TimedOut { started = "opening" } 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 } // 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 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) { 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) } } // 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 }