//! The person's LOGIN-SHELL ENVIRONMENT, captured once at the start of a //! `serve` and used for everything this host runs. //! //! **Why this module exists.** Since CottonDB for Mac 0.6.1 the helper is a //! launchd agent (`SMAppService.agent`), and launchd hands a `gui/` job //! almost nothing: measured on all three host Macs with //! `launchctl print gui/$(id -u)/com.decemberfm.cotton.session-host`, the whole //! environment is `PATH=/usr/bin:/bin:/usr/sbin:/sbin` plus an inherited //! `SSH_AUTH_SOCK`. Two things broke at once: //! //! 1. **Every agent read as not installed.** `claude` lives in //! `~/.local/bin`, `codex` in a node prefix — neither is on that PATH, so //! `read.agentAccounts` answered `agents: {}` and every launch would have //! been refused as *no agent on this Mac*. //! 2. **A session would have run in launchd's environment, not the person's.** //! The rule the Code tool is built to is that Claude Code and Codex work //! exactly as they would in a terminal; a child with no `~/.local/bin`, no //! locale, no `LANG`, no toolchain shims is not that. //! //! Phase 6's proof ran the helper from a shell, which inherits all of it — //! which is why it passed and the packaged agent did not. //! //! **The fix is one capture, at the root.** At `serve` start the host runs the //! person's login shell once, non-interactively — `$SHELL -l -c 'env -0'` — //! and keeps its VARIABLES. Its PATH is not kept: a session's PATH is the //! declared one in [`crate::launch_env`], because a login shell never reads //! `.zshrc` and a PATH nobody declared is one nobody can rely on. That //! environment is the base for agent detection AND for every //! pseudo-terminal this host spawns, and a child gets it and nothing of this //! process's own ([`crate::pty`] clears what it inherited). //! //! - **`-l`, never `-i`.** A login shell sources the files that build a //! person's PATH (`.zprofile`, `.zshenv`, `.profile`). An INTERACTIVE shell //! also sources `.zshrc`, which on a real Mac starts completion systems, //! prompt frameworks and version managers, and can block on a terminal that //! is not there. A capture that hangs is a host that never serves. //! - **`env -0`**, because an environment value may contain a newline and a //! line-based read would silently split it into two half-variables. //! - **Bounded, and survivable.** The shell gets [`CAPTURE_TIMEOUT`]; a shell //! that fails, times out or prints nothing leaves the host with the process //! environment it already had, with the declared PATH. A //! login file that is broken today must not cost the person their sessions. //! //! **Nothing here is ever logged but [`LOGGABLE`]** — PATH, SHELL, HOME and //! LANG. An environment is where a person's tokens live; //! [`LoginEnv::summary`] is the one line this module produces and it reads //! those four names off the constant rather than spelling any of its own. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::time::Duration; /// How long the login shell gets to print its environment. /// /// Ten seconds is minutes more than a `.zprofile` takes and still a bound: the /// host serves with the process environment rather than waiting on a login /// file that is hung. pub const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10); /// The shell used when neither `SHELL` nor the directory record names one. /// /// macOS's own default since Catalina. pub const FALLBACK_SHELL: &str = "/bin/zsh"; /// The terminal type a hosted session gets when the login environment names /// none. /// /// A login shell run by launchd has no controlling terminal, so it usually /// exports no `TERM` — and both agents' interactive faces are terminal UIs /// that read it. Absent, a session would come up in the degraded rendering a /// person never sees in their own terminal, which is the same defect as the /// missing PATH wearing a different hat. Set only when nothing else said. pub const FALLBACK_TERM: &str = "xterm-256color"; /// What the capturing shell said about ITSELF, dropped on the way out. /// /// These four describe the shell that ran `env -0`, not the person's /// environment: `PWD`/`OLDPWD` are that shell's directory and a session runs in /// a repository's, `SHLVL` counts a nesting that ends with the capture, and `_` /// is the last command it ran. Carried through, `PWD` is the loudest — a child /// started in a checkout would carry a `PWD` naming the home directory, and /// anything inside it that trusts `$PWD` over `getcwd` reads the wrong tree. pub const SHELL_BOOKKEEPING: [&str; 4] = ["PWD", "OLDPWD", "SHLVL", "_"]; /// The only variables whose VALUE this crate ever writes down. /// /// Everything else in an environment is a person's own business, and some of /// it is a credential. pub const LOGGABLE: [&str; 4] = ["PATH", "SHELL", "HOME", "LANG"]; /// The environment this host runs everything in. /// /// A child gets THESE variables and nothing else ([`crate::pty`] clears what /// this process inherited). An empty one gives a child an empty environment /// and resolves a program by its bare name; [`LoginEnv::inherited`] is the /// explicit copy of this process's own, for a host run from a terminal or a /// test that is about something else. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct LoginEnv { vars: BTreeMap, } impl LoginEnv { /// This process's own environment, copied as it stands — a child of a /// host run from a terminal gets the terminal's, said here rather than /// left to inheritance. pub fn inherited() -> Self { Self::from_vars(std::env::vars().collect()) } /// Take a captured environment as it stands, without the PATH repair /// [`build`] does. pub fn from_vars(vars: BTreeMap) -> Self { Self { vars } } /// Is there nothing captured at all? pub fn is_empty(&self) -> bool { self.vars.is_empty() } /// Everything captured. pub fn vars(&self) -> &BTreeMap { &self.vars } /// One variable. pub fn get(&self, name: &str) -> Option<&str> { self.vars.get(name).map(String::as_str) } /// The PATH this host resolves programs against — empty when nothing was /// captured. pub fn path(&self) -> &str { self.get("PATH").unwrap_or("") } /// What to exec for `program`. /// /// An ABSOLUTE PATH whenever the captured PATH holds one, because the /// program lookup a `Command` does is not this PATH's, and a child that /// inherits the right `PATH` variable is still exec'd by name against the /// parent's. Resolving here is the one place that cannot drift. pub fn program_path(&self, program: &str) -> String { resolve_program(self.path(), program) .map(|found| found.display().to_string()) .unwrap_or_else(|| program.to_string()) } /// This environment with `on_top` over it — what a caller asked for always /// wins. pub fn merged(&self, on_top: BTreeMap) -> BTreeMap { let mut merged = self.vars.clone(); merged.extend(on_top); merged } /// The ONE line this module writes to the log. /// /// [`LOGGABLE`] AND NOTHING ELSE, read off the constant rather than /// spelled again here — so the rule about what may be written down has one /// declaration and this function cannot drift from it. Between them those /// four answer every "why does it say the agent is not installed" this /// module exists for. pub fn summary(&self) -> String { if self.is_empty() { return "no login environment captured — children inherit this process's own" .to_string(); } let named: Vec = LOGGABLE .iter() .filter_map(|name| self.get(name).map(|value| format!("{name}={value}"))) .collect(); format!("login environment — {}", named.join(" ")) } } /// Build the environment this host will use out of what a shell printed. /// /// `captured` is the shell's answer (or the process environment, when the /// shell had none to give); `home` is this person's home directory. The /// person's variables are kept; the PATH is NOT theirs but the declared one /// ([`crate::launch_env::path`]) — whatever PATH the shell printed is /// replaced, so a hosted session can rely on exactly the directories that /// module lists and no other. [`SHELL_BOOKKEEPING`] is dropped; `TERM` is set /// only when nothing named one. pub fn build(captured: BTreeMap, home: &str) -> LoginEnv { let mut vars = captured; for name in SHELL_BOOKKEEPING { vars.remove(name); } vars.insert("PATH".to_string(), crate::launch_env::path(home)); vars.entry("TERM".to_string()) .or_insert_with(|| FALLBACK_TERM.to_string()); LoginEnv { vars } } /// `NAME=VALUE` entries out of what `env -0` printed. /// /// NUL-separated, so a value holding a newline survives. An entry with no `=`, /// an empty name, or bytes that are not UTF-8 is skipped — never half-parsed /// into a variable nobody set. pub fn parse_env0(bytes: &[u8]) -> BTreeMap { let mut vars = BTreeMap::new(); for entry in bytes.split(|byte| *byte == 0) { if entry.is_empty() { continue; } let Ok(text) = std::str::from_utf8(entry) else { continue; }; let Some((name, value)) = text.split_once('=') else { continue; }; if name.is_empty() { continue; } vars.insert(name.to_string(), value.to_string()); } vars } /// Which shell to ask. /// /// `SHELL` first — it is the person's current choice and it is what every /// other tool on the Mac reads — then the login record's own shell, which is /// what answers under launchd where `SHELL` is not set at all, then /// [`FALLBACK_SHELL`]. A value that is not an absolute path is not a shell we /// will exec. pub fn choose_shell(shell_var: Option<&str>, directory_shell: Option<&str>) -> String { for said in [shell_var, directory_shell] { if let Some(shell) = said.map(str::trim).filter(|s| s.starts_with('/')) { return shell.to_string(); } } FALLBACK_SHELL.to_string() } /// The first executable called `program` on `path`. /// /// A name holding a `/` is a path already and is taken as one. A directory /// that happens to carry the name is not a program. pub fn resolve_program(path: &str, program: &str) -> Option { if program.is_empty() { return None; } if program.contains('/') { let candidate = PathBuf::from(program); return is_executable(&candidate).then_some(candidate); } path.split(':') .filter(|dir| !dir.is_empty()) .map(|dir| Path::new(dir).join(program)) .find(|candidate| is_executable(candidate)) } /// A file somebody may exec. fn is_executable(path: &Path) -> bool { use std::os::unix::fs::PermissionsExt as _; std::fs::metadata(path) .map(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0) .unwrap_or(false) } /// This login's shell, out of the password database. /// /// The same record `dscl . -read /Users/$USER UserShell` prints, read with the /// call `dscl` itself makes — no subprocess, and no dependence on `USER`, /// which launchd does not set either and which is the variable the whole /// problem is made of. pub fn directory_shell() -> Option { // SAFETY: `getpwuid(3)` returns a pointer into a static buffer this // process owns, or null when there is no record. Nothing here holds it // past the copy below, and this host reads it once at startup from one // thread. unsafe { let record = libc::getpwuid(libc::getuid()); if record.is_null() { return None; } let shell = (*record).pw_shell; if shell.is_null() { return None; } std::ffi::CStr::from_ptr(shell) .to_str() .ok() .map(str::to_string) .filter(|said| !said.is_empty()) } } /// Run `shell -l -c 'env -0'` and keep what it printed. /// /// `fallback` is what the host uses when the shell answers nothing — the /// process's own environment, which under launchd is thin and under a terminal /// is already right. Either way the answer goes through [`build`], so the /// declared PATH is the PATH whichever branch was taken. pub fn capture( shell: &str, home: &str, fallback: BTreeMap, timeout: Duration, ) -> LoginEnv { let mut vars = match ask_shell(shell, timeout) { Some(printed) if !printed.is_empty() => printed, _ => fallback, }; // A shell launchd started is not a login in the `login(1)` sense, so it // exports neither of these however faithfully it sourced the person's // files. Both are known here and neither is a guess. vars.entry("SHELL".to_string()) .or_insert_with(|| shell.to_string()); if !home.is_empty() { vars.entry("HOME".to_string()) .or_insert_with(|| home.to_string()); } build(vars, home) } /// The subprocess half of [`capture`], bounded. /// /// The child's stdout is drained by a thread so a shell that prints more than /// a pipe holds cannot deadlock the wait, and the wait itself is a /// `recv_timeout` — the descriptor closes when the shell exits, and a shell /// that is still running when the budget is gone is killed rather than waited /// on for ever. Its stdin is closed and its stderr thrown away: a login file /// that prints a warning is not this host's to relay, and one that reads from /// the terminal must see end-of-file rather than block. fn ask_shell(shell: &str, timeout: Duration) -> Option> { use std::io::Read as _; use std::process::{Command, Stdio}; let mut child = Command::new(shell) .arg("-l") .arg("-c") .arg("env -0") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .ok()?; let mut stdout = child.stdout.take()?; let (printed_to, printed) = std::sync::mpsc::channel(); std::thread::spawn(move || { let mut bytes = Vec::new(); let _ = stdout.read_to_end(&mut bytes); let _ = printed_to.send(bytes); }); let answer = printed.recv_timeout(timeout).ok(); if answer.is_none() { let _ = child.kill(); } let _ = child.wait(); answer.map(|bytes| parse_env0(&bytes)) } #[cfg(test)] #[path = "login_env_tests.rs"] mod login_env_tests;