package loginservice import ( "bytes" "context" "encoding/xml" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "slices" "strconv" "strings" "time" ) type LaunchdObservation struct { Definition Definition ExitCode, Signal *int State, Path string PID int Runs, ActiveCount uint64 Loaded, DomainAbsent, Disabled, NeverExited bool } func (s DaemonUnit) Target() string { return "gui/" + strconv.Itoa(os.Getuid()) + "/" + s.name } func (s DaemonUnit) Bootstrap(ctx context.Context) error { return s.launchdMutation(ctx, "bootstrap", "gui/"+strconv.Itoa(os.Getuid()), s.path) } func (s DaemonUnit) Kickstart(ctx context.Context) error { return s.launchdMutation(ctx, "kickstart", s.Target()) } func (s DaemonUnit) Bootout(ctx context.Context) error { return s.launchdMutation(ctx, "bootout", s.Target()) } func (s DaemonUnit) launchdMutation(ctx context.Context, args ...string) error { if err := ctx.Err(); err != nil { return err } _, diagnostic, err := launchdCommand(ctx, args...) if diagnostic = strings.TrimSpace(diagnostic); err != nil && diagnostic != "" { return fmt.Errorf("%w: %s", err, diagnostic) } return err } type cappedOutput struct { bytes.Buffer overflow bool } func (b *cappedOutput) Write(p []byte) (int, error) { n := len(p) if b.Len()+n > 1<<20 { b.overflow = true p = p[:max(0, (1<<20)-b.Len())] } _, _ = b.Buffer.Write(p) return n, nil } func launchdCommand(ctx context.Context, args ...string) (string, string, error) { name := os.Getenv("ALBEDO_LAUNCHCTL") if name == "" { name = "/bin/launchctl" } return boundedCommand(ctx, name, args...) } func boundedCommand(ctx context.Context, name string, args ...string) (string, string, error) { ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() var out, diagnostic cappedOutput command := exec.CommandContext(ctx, name, args...) command.Stdout = &out command.Stderr = &diagnostic err := command.Run() if out.overflow || diagnostic.overflow { return "", "", errors.New("manager output exceeds 1 MiB") } if ctx.Err() != nil { return "", "", ctx.Err() } return out.String(), diagnostic.String(), err } func launchdAbsent(err error, stdout, stderr, label string, uid int) (bool, bool) { var exit *exec.ExitError if !errors.As(err, &exit) || strings.TrimSpace(stdout) != "" { return false, false } diagnostic := strings.TrimSpace(stderr) absent := fmt.Sprintf("Could not find service %q in domain for user gui: %d", label, uid) if exit.ExitCode() == 113 && (diagnostic == absent || diagnostic == "Bad request.\n"+absent) { return true, false } domain := fmt.Sprintf("Bad request.\nCould not find domain for user gui: %d", uid) return false, exit.ExitCode() == 112 && diagnostic == domain } func ambiguousLaunchd(value string) bool { for _, r := range value { if r < 32 || r == 127 || r == '{' || r == '}' { return true } } return false } func (s DaemonUnit) validateLaunchdDefinition(definition Definition) error { if !filepath.IsAbs(definition.Executable) || ambiguousLaunchd(definition.Executable) || ambiguousLaunchd(s.home) || ambiguousLaunchd(s.path) { return errors.New("launchd requires absolute executable and unambiguous paths") } if definition.Environment["ALBEDO_HOME"] != s.home { return errors.New("service home does not match") } if definition.Environment["PATH"] == "" { return errors.New("launchd service requires a captured PATH") } for key, value := range definition.Environment { if !slices.Contains([]string{"PATH", "ALBEDO_HOME", "ALBEDO_DAEMON", "ALBEDO_ROOT"}, key) || ambiguousLaunchd(value) { return fmt.Errorf("unsupported launchd environment key or value for %s", key) } } return nil } func (s DaemonUnit) renderLaunchd(definition Definition) ([]byte, error) { if err := s.validateLaunchdDefinition(definition); err != nil { return nil, err } keys := make([]string, 0, len(definition.Environment)) for key := range definition.Environment { keys = append(keys, key) } slices.Sort(keys) var b strings.Builder b.WriteString("\n\n\n\n") fmt.Fprintf(&b, "Label%s\nProgramArguments%sdaemon--serve\nEnvironmentVariables", xmlText(s.name), xmlText(definition.Executable)) for _, key := range keys { fmt.Fprintf(&b, "%s%s", key, xmlText(definition.Environment[key])) } b.WriteString("\nRunAtLoad\nKeepAliveSuccessfulExit\nAbandonProcessGroup\nExitTimeOut45\n") fmt.Fprintf(&b, "StandardOutPath%s\nStandardErrorPath%s\n\n", xmlText(filepath.Join(s.home, "daemon.log")), xmlText(filepath.Join(s.home, "daemon.log"))) return []byte(b.String()), nil } // Exact re-rendering makes all edits, including duplicate keys, unowned. func (s DaemonUnit) parseLaunchdDefinition(data []byte) (Definition, error) { definition := Definition{Environment: map[string]string{}} decoder := xml.NewDecoder(bytes.NewReader(data)) var previous string environment := false arguments := false for { token, err := decoder.Token() if err == io.EOF { break } if err != nil { return definition, err } switch token := token.(type) { case xml.StartElement: switch token.Name.Local { case "key": if err := decoder.DecodeElement(&previous, &token); err != nil { return definition, err } case "dict": if previous == "EnvironmentVariables" { environment = true } case "array": arguments = previous == "ProgramArguments" case "string": var value string if err := decoder.DecodeElement(&value, &token); err != nil { return definition, err } if environment { definition.Environment[previous] = value } else if arguments && definition.Executable == "" { definition.Executable = value } } case xml.EndElement: if token.Name.Local == "dict" { environment = false } if token.Name.Local == "array" { arguments = false } } } expected, err := s.renderLaunchd(definition) if err != nil { return definition, err } if !bytes.Equal(expected, data) { return definition, errors.New("plist contains edits outside generated format") } return definition, nil } func parseDisabled(output, label string) (bool, error) { lines := strings.Split(strings.TrimSpace(output), "\n") if len(lines) < 2 || strings.TrimSpace(lines[0]) != "disabled services = {" || strings.TrimSpace(lines[len(lines)-1]) != "}" { return false, errors.New("invalid print-disabled block") } seen := map[string]bool{} disabled := false for _, line := range lines[1 : len(lines)-1] { line = strings.TrimSpace(line) if line == "" { continue } key, value, ok := strings.Cut(line, " => ") if !ok || !strings.HasPrefix(key, "\"") { return false, errors.New("invalid disabled entry") } decoded, err := strconv.Unquote(key) if err != nil || decoded == "" || ambiguousLaunchd(decoded) || seen[decoded] || (value != "enabled" && value != "disabled") { return false, errors.New("invalid or duplicate disabled entry") } seen[decoded] = true if decoded == label { disabled = value == "disabled" } } return disabled, nil } type launchdFields struct { scalars map[string]string blocks map[string][]string } func parseLaunchdFields(output, target string) (launchdFields, error) { fields := launchdFields{map[string]string{}, map[string][]string{}} lines := strings.Split(strings.TrimSpace(output), "\n") if len(output) > 1<<20 || len(lines) < 2 || lines[0] != target+" = {" || lines[len(lines)-1] != "}" { return fields, errors.New("invalid launchd root") } seen := map[string]bool{} for i := 1; i < len(lines)-1; i++ { line := lines[i] if line == "" { continue } if !strings.HasPrefix(line, "\t") || strings.HasPrefix(line, "\t\t") { return fields, errors.New("invalid launchd indentation") } key, value, ok := strings.Cut(line[1:], " = ") if !ok || seen[key] { return fields, errors.New("invalid or duplicate launchd field") } seen[key] = true if value != "{" { if strings.ContainsAny(value, "{}") { return fields, fmt.Errorf("invalid launchd field %s", key) } fields.scalars[key] = value continue } if key == "LWCR" { var entries []string closed := false for i++; i < len(lines)-1; i++ { if lines[i] == "\t}" { closed = true break } entries = append(entries, lines[i]) } if !closed || !validLaunchdLWCR(entries) { return fields, errors.New("unsupported LWCR metadata") } fields.blocks[key] = entries continue } var entries []string closed := false for i++; i < len(lines)-1; i++ { if lines[i] == "\t}" { closed = true break } if !strings.HasPrefix(lines[i], "\t\t") || strings.HasPrefix(lines[i], "\t\t\t") || strings.ContainsAny(lines[i], "{}") { return fields, fmt.Errorf("invalid launchd block %s", key) } entries = append(entries, lines[i][2:]) } if !closed { return fields, errors.New("unterminated launchd block") } fields.blocks[key] = entries } return fields, nil } func blockAssignments(lines []string, separator string) (map[string]string, error) { result := map[string]string{} for _, line := range lines { key, value, ok := strings.Cut(line, separator) if !ok || key == "" { return nil, errors.New("invalid block entry") } if _, exists := result[key]; exists { return nil, errors.New("duplicate block entry") } result[key] = value } return result, nil } func decimal(value string, bits int) (uint64, error) { if value == "" || strings.Trim(value, "0123456789") != "" { return 0, errors.New("invalid decimal") } return strconv.ParseUint(value, 10, bits) } func (s DaemonUnit) parseLaunchd(output string) (*LaunchdObservation, error) { fields, err := parseLaunchdFields(output, s.Target()) if err != nil { return nil, err } scalars := fields.scalars job := &LaunchdObservation{Loaded: true, Path: scalars["path"], State: scalars["state"]} invalid := func(key string) (*LaunchdObservation, error) { return nil, fmt.Errorf("unsupported loaded launchd field %s", key) } expected := map[string]string{ "path": s.path, "type": "LaunchAgent", "stdout path": filepath.Join(s.home, "daemon.log"), "stderr path": filepath.Join(s.home, "daemon.log"), "minimum runtime": "10", "exit timeout": "45", "spawn type": "daemon (3)", "jetsam priority": "40", "jetsam memory limit (active)": "(unlimited)", "jetsam memory limit (inactive)": "(unlimited)", "jetsamproperties category": "daemon", "jetsam thread limit": "32", "cpumon": "default", } for key, value := range expected { if scalars[key] != value { return invalid(key) } } allowed := map[string]bool{} for key := range expected { allowed[key] = true } // macOS 26 does not print sanitizer flags; later releases print 0x0. if value, ok := scalars["sanitizer flags"]; ok && value != "0x0" { return invalid("sanitizer flags") } for _, key := range []string{ "sanitizer flags", "program", "state", "runs", "pid", "active count", "last exit code", "last terminating signal", "immediate reason", "forks", "execs", "initialized", "trampolined", "started suspended", "proxy started suspended", "checked allocations", "checked allocations reason", "checked allocations flags", "domain", "asid", "properties", "job state", } { allowed[key] = true } for key := range scalars { if !allowed[key] { return invalid(key) } } if value, exists := scalars["job state"]; exists && value != "running" && value != "exited" { return invalid("job state") } properties := map[string]bool{} for property := range strings.SplitSeq(scalars["properties"], " | ") { if properties[property] || !slices.Contains([]string{"abandon process group", "inferred program", "runatload", "managed LWCR", "has LWCR"}, property) { return invalid("properties") } properties[property] = true } for _, required := range []string{"abandon process group", "inferred program", "runatload"} { if !properties[required] { return invalid("properties") } } asid, e := decimal(scalars["asid"], 64) if e != nil || asid == 0 || scalars["domain"] != "gui/"+strconv.Itoa(os.Getuid())+" ["+scalars["asid"]+"]" { return invalid("domain/asid") } for _, key := range []string{"runs", "active count", "forks", "execs", "initialized", "trampolined", "started suspended", "proxy started suspended"} { value, exists := scalars[key] if !exists && key != "runs" && key != "active count" { continue } number, e := decimal(value, 64) if e != nil { return invalid(key) } switch key { case "runs": job.Runs = number case "active count": job.ActiveCount = number case "initialized", "trampolined": if number > 1 { return invalid(key) } case "started suspended", "proxy started suspended": if number != 0 { return invalid(key) } } } if value, exists := scalars["pid"]; exists { pid, e := decimal(value, 31) if e != nil || pid == 0 { return invalid("pid") } job.PID = int(pid) } for key, value := range scalars { switch key { case "last exit code": if value == "(never exited)" { job.NeverExited = true continue } number, diagnostic, has := strings.Cut(value, ": ") code, e := decimal(number, 8) if e != nil || (has && (diagnostic == "" || ambiguousLaunchd(diagnostic))) { return invalid(key) } exit := int(code) job.ExitCode = &exit case "last terminating signal": description, number, ok := strings.Cut(value, ": ") signal, e := decimal(number, 8) if !ok || description == "" || ambiguousLaunchd(description) || e != nil || signal == 0 || signal > 31 { return invalid(key) } value := int(signal) job.Signal = &value case "immediate reason": if !slices.Contains([]string{"speculative", "non-ipc demand", "semaphore", "inefficient", "one-shot"}, value) { return invalid(key) } case "checked allocations": if !regexp.MustCompile(`^[0-9]+ \(queried = [0-9]+\)$`).MatchString(value) { return invalid(key) } case "checked allocations reason": if value != "no host" { return invalid(key) } case "checked allocations flags": if value != "0x0" { return invalid(key) } } } if job.Signal != nil && (job.ExitCode != nil || job.NeverExited) { return invalid("exit history") } if job.PID != 0 && job.Runs == 0 { return invalid("pid/runs") } switch job.State { // xpcproxy is the native state between spawn and exec of the job's program. case "running", "xpcproxy": if job.PID == 0 || job.Runs == 0 { return invalid("state/pid") } case "not running", "spawn scheduled": if job.PID != 0 { return invalid("state/pid") } case "SIGTERMed": default: return invalid("state") } if job.State == "not running" && job.ExitCode == nil && job.Signal == nil && job.Runs != 0 { return invalid("idle history") } for key, lines := range fields.blocks { switch key { case "LWCR": case "arguments": if len(lines) != 3 || lines[0] != scalars["program"] || !launchdServeArguments(lines) { return invalid(key) } job.Definition.Executable = lines[0] case "environment", "default environment", "inherited environment", "semaphores": values, e := blockAssignments(lines, " => ") if e != nil { return invalid(key) } switch key { case "environment": if values["OSLogRateLimit"] != "64" || values["XPC_SERVICE_NAME"] != s.name { return invalid(key) } delete(values, "OSLogRateLimit") delete(values, "XPC_SERVICE_NAME") for name := range values { if !slices.Contains([]string{"PATH", "ALBEDO_HOME", "ALBEDO_DAEMON", "ALBEDO_ROOT"}, name) { return invalid("environment " + name) } } job.Definition.Environment = values case "default environment": if len(values) != 1 || values["PATH"] != "/usr/bin:/bin:/usr/sbin:/sbin" { return invalid(key) } case "inherited environment": if len(values) > 1 || (len(values) == 1 && (values["SSH_AUTH_SOCK"] == "" || ambiguousLaunchd(values["SSH_AUTH_SOCK"]))) { return invalid(key) } case "semaphores": if len(values) != 1 || values["successful exit"] != "0" { return invalid(key) } } case "resource coalition", "jetsam coalition": values, e := blockAssignments(lines, " = ") if e != nil || len(values) != 5 { return invalid(key) } id, e := decimal(values["ID"], 64) if e != nil || id == 0 { return invalid(key) } if _, e := decimal(values["active count"], 64); e != nil { return invalid(key) } if values["type"] != strings.TrimSuffix(key, " coalition") || values["state"] != "active" || values["name"] != s.name { return invalid(key) } default: return invalid(key) } } for _, key := range []string{"arguments", "environment", "default environment", "semaphores"} { if _, ok := fields.blocks[key]; !ok { return invalid(key) } } if err = s.validateLaunchdDefinition(job.Definition); err != nil { return invalid("environment") } return job, nil } // Recognize direct arguments or the home-manager wrapper layout. The service // owner is responsible for the shell command; this is not shell validation. func launchdServeArguments(arguments []string) bool { program := arguments[0] if program == "/bin/sh" { command := arguments[2] return arguments[1] == "-c" && strings.HasPrefix(command, "/bin/wait4path /nix/store && exec ") && strings.HasSuffix(command, " daemon --serve") } return filepath.IsAbs(program) && slices.Equal(arguments[1:], []string{"daemon", "--serve"}) } // launchctl's observed shell requirement metadata has one fixed nested block. func validLaunchdLWCR(lines []string) bool { fields := map[string]string{} requirements := map[string]string{} inRequirements, closedRequirements := false, false for _, line := range lines { if line == "\t\t\"reqs\" => {" { if inRequirements || closedRequirements { return false } inRequirements = true continue } if line == "\t\t}" { if !inRequirements { return false } inRequirements = false closedRequirements = true continue } prefix := "\t\t" target := fields if inRequirements { prefix = "\t\t\t" target = requirements } if !strings.HasPrefix(line, prefix) || strings.HasPrefix(line, prefix+"\t") { return false } key, value, ok := strings.Cut(strings.TrimPrefix(line, prefix), " => ") if !ok { return false } if _, exists := target[key]; exists { return false } target[key] = value } return !inRequirements && closedRequirements && len(fields) == 3 && fields[`"vers"`] == "1" && fields[`"comp"`] == "1" && fields[`"ccat"`] == "0" && len(requirements) == 2 && requirements[`"signing-identifier"`] == `"com.apple.sh"` && requirements[`"validation-category"`] == "1" } func (s DaemonUnit) observeLaunchd(ctx context.Context) (Observation, error) { observation := Observation{File: AbsentFile, Properties: map[string]string{}, Launchd: &LaunchdObservation{}} info, err := os.Lstat(s.path) if err == nil { observation.Info = info switch { case s.declarative: observation.File = DeclaredFile case !info.Mode().IsRegular(): observation.File = ForeignFile observation.Problem = "service file is not a regular file" default: observation.Data, err = readServiceFile(s.path) if err != nil { return observation, err } definition, parseErr := s.parseLaunchdDefinition(observation.Data) if parseErr != nil { observation.File = ForeignFile observation.Problem = parseErr.Error() } else { observation.File = OwnedFile observation.Definition = definition } } } else if !errors.Is(err, os.ErrNotExist) { return observation, err } output, diagnostic, err := launchdCommand(ctx, "print", s.Target()) if err != nil { if (errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist)) && observation.File == AbsentFile { return observation, nil } absent, domainAbsent := launchdAbsent(err, output, diagnostic, s.name, os.Getuid()) if domainAbsent { observation.Launchd.DomainAbsent = true if observation.File != AbsentFile { return observation, errors.New("GUI domain unavailable with service file present") } return observation, nil } if !absent { return observation, fmt.Errorf("launchctl print unavailable: %w", err) } } else { if strings.TrimSpace(diagnostic) != "" { return observation, errors.New("unexpected launchctl print diagnostic") } loaded, e := s.parseLaunchd(output) if e != nil { return observation, e } observation.Launchd = loaded if s.declarative { observation.Definition = loaded.Definition } } observation.Available = true output, diagnostic, err = launchdCommand(ctx, "print-disabled", "gui/"+strconv.Itoa(os.Getuid())) if err != nil { return observation, fmt.Errorf("launchctl print-disabled unavailable: %w", err) } if strings.TrimSpace(diagnostic) != "" { return observation, errors.New("unexpected print-disabled diagnostic") } observation.Launchd.Disabled, err = parseDisabled(output, s.name) return observation, err }