tilo_paths/machine.rs
1//! What a session reaches of the machine it draws on: the one answer every
2//! service that acts on the machine reads.
3//!
4//! A Tilo login owns the machine under it: its VPN kill switch configures the
5//! firewall, its Bluetooth and network services drive the radios, its power
6//! service holds logind. A session that runs *inside* another desktop — a
7//! nested session in a window, a test session beside a live one — owns none of
8//! that: those daemons belong to the person sitting at the machine, and a
9//! session they did not start must never change them. The answer is declared
10//! once, by the environment (`TILO_MACHINE`), and inherited by every process
11//! the session starts, so the shell, its services, the launcher and the
12//! programs it runs all read the same one.
13//!
14//! Services do not decide this themselves and do not guess it from a display:
15//! they ask here, and a [`Reach::Hosted`] session keeps its machine-acting
16//! services off rather than pointing them at a host's daemons.
17
18use std::ffi::OsString;
19
20/// The variable a session declares itself with: `owned` for a session that
21/// reaches the machine's own daemons, `hosted` for one that must not.
22pub const VAR: &str = "TILO_MACHINE";
23
24/// Where Tilo OS's system unit keeps the device daemon's sockets: its own runtime directory,
25/// which every account may enter, each connection admitted by the account it comes from.
26pub const DAEMON_SOCKETS: &str = "/run/tilo-runtime";
27/// The device daemon's native endpoint, in its sockets' directory: what apps, the system's own
28/// callers (the sign-in's session hooks) and `tilo-runtime --connect` reach.
29pub const DAEMON_NATIVE: &str = "native.sock";
30/// The variable naming a device daemon's profile when it is not the account's own: a test's, a VM
31/// host's.
32pub const DAEMON_PROFILE_VAR: &str = "TILO_RUNTIME_PROFILE";
33
34/// The profile an account's own device daemon keeps its state in, under its home: its store, its
35/// device's key and certificates, and the sockets of a profile named apart. Tilo OS's system unit
36/// keeps its profile outside every home instead.
37#[must_use]
38pub fn account_daemon_profile() -> Option<std::path::PathBuf> {
39 #[cfg(target_os = "macos")]
40 let suffix = "Library/Application Support/Tilo/runtime";
41 #[cfg(target_os = "windows")]
42 let suffix = "AppData/Local/Tilo/runtime";
43 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
44 let suffix = ".local/state/tilo/runtime";
45 Some(super::home()?.join(suffix))
46}
47
48/// The unit Tilo OS runs the device daemon from boot with, as the system's own account.
49pub const DAEMON_SYSTEM_UNIT: &str = "/usr/lib/systemd/system/tilo-runtime.service";
50/// The profile the system unit names for its daemon ([`DAEMON_PROFILE_VAR`]): its home and state
51/// on Tilo OS, outside every person's home.
52pub const DAEMON_SYSTEM_PROFILE: &str = "/var/lib/tilo/state";
53
54/// Whether the daemon serving the profile `named` ([`DAEMON_PROFILE_VAR`], when it is said) is the
55/// computer's own, on a computer whose daemon is the system's (`system`): the system unit names its
56/// own profile, and is the computer's; any other profile is served apart, as one account's (a
57/// test's, a VM host's, a stack's), even on Tilo OS.
58#[must_use]
59pub fn serves_the_computer(system: bool, named: Option<&std::path::Path>) -> bool {
60 system && named.is_none_or(|profile| profile == std::path::Path::new(DAEMON_SYSTEM_PROFILE))
61}
62
63/// Whether this computer's daemon is the system's: Tilo OS runs it from boot as its own
64/// account for every person of the computer, where other computers run it as the person.
65#[must_use]
66pub fn system_daemon() -> bool {
67 cfg!(target_os = "linux") && std::path::Path::new(DAEMON_SYSTEM_UNIT).is_file()
68}
69
70/// What Tilo's guest OS starts a workspace's VM with: only that image ships it.
71pub const HOSTED_GUEST_INIT: &str = "/usr/libexec/tilo/hosted-init";
72
73/// Whether this computer is a workspace's VM running Tilo's guest OS, whose daemon its keeper
74/// starts once the VM woke rather than a system unit at boot.
75#[must_use]
76pub fn hosted_guest() -> bool {
77 cfg!(target_os = "linux") && std::path::Path::new(HOSTED_GUEST_INIT).is_file()
78}
79
80/// Where this computer's daemon keeps its sockets: the system unit's runtime directory under
81/// Tilo OS; else, for the account `uid` runs it as, `$XDG_RUNTIME_DIR/tilo` (the one systemd
82/// names by the account when the variable is not said, over ssh or from cron) on Linux, and the
83/// account's temporary directory (`/var/folders/…/T/tilo`) on macOS. Neither made nor checked:
84/// the daemon makes it, private to the account.
85///
86/// # Errors
87/// macOS names no temporary directory for this account.
88#[cfg(unix)]
89pub fn daemon_sockets(uid: u32) -> Result<std::path::PathBuf, String> {
90 use std::path::PathBuf;
91 if system_daemon() {
92 return Ok(PathBuf::from(DAEMON_SOCKETS));
93 }
94 account_sockets(uid)
95}
96
97/// Where the account `uid` runs its own programs' sockets: `$XDG_RUNTIME_DIR/tilo` (the one
98/// systemd names by the account when the variable is not said, over ssh or from cron) on Linux,
99/// and the account's temporary directory (`/var/folders/…/T/tilo`) on macOS. Never the system
100/// unit's directory, which every account reaches. Neither made nor checked: the daemon makes
101/// it, private to the account.
102///
103/// # Errors
104/// macOS names no temporary directory for this account.
105#[cfg(unix)]
106pub fn account_sockets(uid: u32) -> Result<std::path::PathBuf, String> {
107 use std::path::PathBuf;
108 #[cfg(target_os = "macos")]
109 {
110 let _ = uid;
111 Ok(darwin_temp_dir()?.join("tilo"))
112 }
113 #[cfg(not(target_os = "macos"))]
114 Ok(crate::var("XDG_RUNTIME_DIR")
115 .map(PathBuf::from)
116 .filter(|runtime| runtime.is_absolute() && runtime.is_dir())
117 .or_else(|| Some(PathBuf::from(format!("/run/user/{uid}"))).filter(|run| run.is_dir()))
118 .map_or_else(
119 || std::env::temp_dir().join(format!("tilo-{uid}")),
120 |runtime| runtime.join("tilo"),
121 ))
122}
123
124/// The native endpoint of the daemon this account reaches ([`daemon_sockets`] of its own
125/// account).
126///
127/// # Errors
128/// As [`daemon_sockets`].
129#[cfg(unix)]
130pub fn daemon_native() -> Result<std::path::PathBuf, String> {
131 Ok(daemon_sockets(rustix::process::geteuid().as_raw())?.join(DAEMON_NATIVE))
132}
133
134/// Where this computer's daemon names its pipes on Windows: the `sockets` folder of the account's
135/// own daemon profile. A pipe lives in the system's pipe namespace, not in a folder; its name is
136/// made from this path, and the folder holds the daemon's lock beside them. Neither made nor
137/// checked: the daemon makes it, private to the account.
138///
139/// # Errors
140/// The account names no home.
141#[cfg(windows)]
142pub fn daemon_sockets() -> Result<std::path::PathBuf, String> {
143 account_daemon_profile()
144 .map(|profile| profile.join("sockets"))
145 .ok_or_else(|| "this account names no home folder (USERPROFILE)".to_owned())
146}
147
148/// The native endpoint of the daemon this account reaches ([`daemon_sockets`]).
149///
150/// # Errors
151/// As [`daemon_sockets`].
152#[cfg(windows)]
153pub fn daemon_native() -> Result<std::path::PathBuf, String> {
154 Ok(daemon_sockets()?.join(DAEMON_NATIVE))
155}
156
157/// This account's temporary directory on macOS (`/var/folders/…/T/`), as the system names it:
158/// private to the account, and short whatever the home folder is.
159#[cfg(target_os = "macos")]
160fn darwin_temp_dir() -> Result<std::path::PathBuf, String> {
161 use std::os::unix::ffi::OsStringExt as _;
162 let mut buf = vec![0_u8; 1024];
163 // SAFETY: `buf` is writable for `buf.len()` bytes; confstr writes at most that many, its
164 // NUL included.
165 let len = unsafe {
166 libc::confstr(
167 libc::_CS_DARWIN_USER_TEMP_DIR,
168 buf.as_mut_ptr().cast(),
169 buf.len(),
170 )
171 };
172 if len == 0 || len > buf.len() {
173 return Err(format!(
174 "this account has no temporary directory: {}",
175 std::io::Error::last_os_error()
176 ));
177 }
178 buf.truncate(len.saturating_sub(1));
179 Ok(std::path::PathBuf::from(std::ffi::OsString::from_vec(buf)))
180}
181
182/// Whether a session reaches the machine's own daemons.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum Reach {
185 /// This session is the login that owns the machine: its services drive the
186 /// machine's daemons.
187 Owned,
188 /// This session runs inside another desktop, or is a test beside one: the
189 /// machine's daemons are not its to change.
190 Hosted,
191}
192
193impl Reach {
194 /// The reach `TILO_MACHINE` names: `hosted` for a hosted session, else
195 /// [`Owned`](Self::Owned). A session that says nothing owns the machine it
196 /// was started on, so a login needs no declaration and only a session that
197 /// must keep away from the machine has to say so.
198 #[must_use]
199 pub fn named(value: Option<&OsString>) -> Self {
200 match value.and_then(|value| value.to_str()).map(str::trim) {
201 Some("hosted") => Self::Hosted,
202 _ => Self::Owned,
203 }
204 }
205
206 /// Whether the machine's own daemons are this session's to drive.
207 #[must_use]
208 pub const fn is_owned(self) -> bool {
209 matches!(self, Self::Owned)
210 }
211}
212
213/// What this process's session reaches of the machine.
214#[must_use]
215pub fn reach() -> Reach {
216 Reach::named(crate::var(VAR).as_ref())
217}
218
219/// Whether this session may drive the machine's own daemons: the one answer
220/// the services that act on the machine read.
221#[must_use]
222pub fn owns_the_machine() -> bool {
223 reach().is_owned()
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 fn value(text: &str) -> OsString {
231 OsString::from(text)
232 }
233
234 #[test]
235 fn a_session_that_says_nothing_owns_its_machine() {
236 assert_eq!(Reach::named(None), Reach::Owned);
237 assert_eq!(Reach::named(Some(&value(""))), Reach::Owned);
238 assert_eq!(Reach::named(Some(&value("owned"))), Reach::Owned);
239 assert_eq!(Reach::named(Some(&value("something else"))), Reach::Owned);
240 }
241
242 #[test]
243 fn a_hosted_session_reaches_no_machine_of_its_own() {
244 assert_eq!(Reach::named(Some(&value("hosted"))), Reach::Hosted);
245 assert_eq!(Reach::named(Some(&value(" hosted "))), Reach::Hosted);
246 assert!(!Reach::Hosted.is_owned());
247 assert!(Reach::Owned.is_owned());
248 }
249}