Skip to main content

tilo_paths/
login.rs

1//! Whether this process runs inside a Tilo login, and where that login's compositor
2//! publishes its endpoints: the private [`SESSION_DIR`] under the login's runtime
3//! directory.
4
5use std::ffi::{OsStr, OsString};
6use std::path::{Path, PathBuf};
7
8pub const TILO_DESKTOP: &str = "tilo";
9pub const SESSION_DIR: &str = "tilo-session";
10pub const AGENT_SOCKET_FILE: &str = "agent.sock";
11/// The socket in [`SESSION_DIR`] where the desktop serves Tilo's API to its own person's
12/// programs (the REPL, the `tilo` command, scripts), as that person.
13pub const API_SOCKET_FILE: &str = "api.sock";
14pub const ENVIRONMENTS_DIR: &str = "environments";
15pub const GUEST_AGENT_SOCKET: &str = "/run/tilo/agent.sock";
16pub const AGENT_SOCKET_ENV: &str = "TILO_AGENT_SOCK";
17pub const ADMIN_CONTROL_SOCKET_FILE: &str = "admin-control.sock";
18/// The development test-control socket's file name in [`SESSION_DIR`]: what
19/// `tilo-control` and the tools that drive a desktop reach for unless they are
20/// told another path.
21pub const TEST_CONTROL_SOCKET_FILE: &str = "test-control.sock";
22pub const WORKSPACE_ID_FILE: &str = "workspace-id";
23/// File in [`SESSION_DIR`] holding the bare name of the running session's
24/// Wayland socket, so `WAYLAND_DISPLAY=$(cat …)` is exactly right. The
25/// session that bound the socket publishes it for the programs this login
26/// starts and the tools beside it, which find the display without reading
27/// the compositor's log.
28pub const WAYLAND_DISPLAY_FILE: &str = "wayland-display";
29/// File in [`SESSION_DIR`] a desktop publishes once a person can use it: the session process
30/// it names, with its kernel start time, is drawing on every output it has on and has begun
31/// restoring the windows of this device. A reader that waits for a restarted desktop reads
32/// this, never the mere existence of a compositor process.
33pub const DESKTOP_READY_FILE: &str = "desktop-ready";
34/// File in [`SESSION_DIR`] the login keeps while it waits, after an asked restart whose desktop
35/// never became usable, for the restart to be asked again: whoever asked reads that the desktop
36/// did not come back without waiting for it.
37pub const DESKTOP_RESTART_FAILED_FILE: &str = "desktop-restart-failed";
38
39const SESSION_SOCKETS: [&str; 2] = [AGENT_SOCKET_FILE, ADMIN_CONTROL_SOCKET_FILE];
40
41#[must_use]
42pub fn session_dir(runtime_dir: Option<OsString>) -> Option<PathBuf> {
43    let runtime_dir = PathBuf::from(runtime_dir?);
44    runtime_dir
45        .is_absolute()
46        .then(|| runtime_dir.join(SESSION_DIR))
47}
48
49/// Whether an `XDG_CURRENT_DESKTOP` value names a Tilo login. The value is a
50/// colon list (a Tilo session exports `tilo:GNOME`), so Tilo is one entry of
51/// it, never necessarily the whole value.
52#[must_use]
53pub fn names_tilo(current_desktop: Option<&OsStr>) -> bool {
54    current_desktop
55        .and_then(OsStr::to_str)
56        .is_some_and(|value| {
57            value
58                .split(':')
59                .any(|part| part.eq_ignore_ascii_case(TILO_DESKTOP))
60        })
61}
62
63#[must_use]
64pub fn login_runtime_dir_from(
65    runtime_dir: Option<OsString>,
66    uid: u32,
67    exists: impl FnOnce(&Path) -> bool,
68) -> Option<PathBuf> {
69    let named = runtime_dir
70        .map(PathBuf::from)
71        .filter(|dir| dir.is_absolute());
72    named.or_else(|| {
73        let conventional = PathBuf::from(format!("/run/user/{uid}"));
74        exists(&conventional).then_some(conventional)
75    })
76}
77
78#[cfg(unix)]
79#[must_use]
80pub fn login_runtime_dir() -> Option<PathBuf> {
81    login_runtime_dir_from(
82        crate::var("XDG_RUNTIME_DIR"),
83        rustix::process::geteuid().as_raw(),
84        Path::is_dir,
85    )
86}
87
88#[cfg(not(unix))]
89#[must_use]
90pub fn login_runtime_dir() -> Option<PathBuf> {
91    None
92}
93
94/// Whether `runtime_dir` holds a Tilo session's marker: one of the
95/// compositor's own sockets in its private [`SESSION_DIR`]. Only a
96/// compositor of this account creates them, in a directory only this
97/// account can write, so they say "this login is a Tilo desktop" without any
98/// environment variable a launcher may have dropped on the way.
99#[cfg(unix)]
100#[must_use]
101pub fn has_session_marker(runtime_dir: &Path) -> bool {
102    use std::os::unix::fs::FileTypeExt as _;
103    let session = runtime_dir.join(SESSION_DIR);
104    SESSION_SOCKETS.iter().any(|name| {
105        std::fs::symlink_metadata(session.join(name))
106            .is_ok_and(|metadata| metadata.file_type().is_socket())
107    })
108}
109
110/// Whether `runtime_dir` holds a Tilo session's marker: never outside Unix.
111#[cfg(not(unix))]
112#[must_use]
113pub fn has_session_marker(_runtime_dir: &Path) -> bool {
114    let _ = SESSION_SOCKETS;
115    false
116}
117
118/// Whether a process with these facts runs inside a Tilo login: its environment names
119/// the desktop, or its account's runtime directory holds the session's own marker. The
120/// environment is a hint that can only add.
121#[must_use]
122pub fn in_tilo_login(
123    current_desktop: Option<&OsStr>,
124    runtime_dir: Option<&Path>,
125    marker: impl FnOnce(&Path) -> bool,
126) -> bool {
127    names_tilo(current_desktop) || runtime_dir.is_some_and(marker)
128}
129
130#[must_use]
131pub fn is_tilo_login() -> bool {
132    in_tilo_login(
133        crate::var("XDG_CURRENT_DESKTOP").as_deref(),
134        login_runtime_dir().as_deref(),
135        has_session_marker,
136    )
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn a_tilo_login_is_one_entry_of_the_colon_list() {
145        for value in ["tilo", "tilo:GNOME", "GNOME:tilo", "Tilo"] {
146            assert!(names_tilo(Some(OsStr::new(value))), "{value}");
147        }
148        for value in ["", "GNOME", "tilox:GNOME", "KDE"] {
149            assert!(!names_tilo(Some(OsStr::new(value))), "{value}");
150        }
151        assert!(!names_tilo(None));
152    }
153
154    #[test]
155    fn a_process_that_lost_its_environment_is_still_inside_its_login() {
156        let runtime = Path::new("/run/user/1000");
157        assert!(in_tilo_login(None, Some(runtime), |_| true));
158        assert!(in_tilo_login(Some(OsStr::new("")), Some(runtime), |_| true));
159        assert!(in_tilo_login(
160            Some(OsStr::new("GNOME")),
161            Some(runtime),
162            |_| true
163        ));
164        // The environment alone is enough too, and the marker never subtracts.
165        assert!(in_tilo_login(Some(OsStr::new("tilo:GNOME")), None, |_| {
166            false
167        }));
168        assert!(in_tilo_login(
169            Some(OsStr::new("tilo")),
170            Some(runtime),
171            |_| false
172        ));
173        assert!(!in_tilo_login(
174            Some(OsStr::new("GNOME")),
175            Some(runtime),
176            |_| false
177        ));
178        assert!(!in_tilo_login(None, None, |_| true));
179    }
180
181    #[test]
182    fn the_runtime_directory_falls_back_to_the_accounts_own() {
183        let present = |_: &Path| true;
184        assert_eq!(
185            login_runtime_dir_from(Some("/run/user/7".into()), 1000, present),
186            Some(PathBuf::from("/run/user/7"))
187        );
188        for lost in [None, Some(OsString::new()), Some("relative/run".into())] {
189            assert_eq!(
190                login_runtime_dir_from(lost.clone(), 1000, present),
191                Some(PathBuf::from("/run/user/1000")),
192                "{lost:?}"
193            );
194            assert_eq!(login_runtime_dir_from(lost, 1000, |_| false), None);
195        }
196    }
197
198    #[test]
199    fn the_session_directory_lives_under_an_absolute_runtime_dir_only() {
200        assert_eq!(
201            session_dir(Some("/run/user/1000".into())),
202            Some(PathBuf::from("/run/user/1000/tilo-session"))
203        );
204        assert_eq!(session_dir(Some("run/user".into())), None);
205        assert_eq!(session_dir(Some(OsString::new())), None);
206        assert_eq!(session_dir(None), None);
207    }
208
209    #[cfg(unix)]
210    #[test]
211    fn only_a_compositors_socket_is_the_session_marker() {
212        use std::os::unix::net::UnixListener;
213        let runtime = std::env::temp_dir().join(format!(
214            "tilo-paths-marker-{}-{:?}",
215            std::process::id(),
216            std::thread::current().id()
217        ));
218        let _ = std::fs::remove_dir_all(&runtime);
219        std::fs::create_dir(&runtime).unwrap();
220        assert!(!has_session_marker(&runtime), "no session directory");
221        let session = runtime.join(SESSION_DIR);
222        std::fs::create_dir(&session).unwrap();
223        assert!(!has_session_marker(&runtime), "an empty directory");
224        std::fs::write(session.join(AGENT_SOCKET_FILE), b"").unwrap();
225        assert!(!has_session_marker(&runtime), "a regular file");
226        std::fs::remove_file(session.join(AGENT_SOCKET_FILE)).unwrap();
227        let admin = UnixListener::bind(session.join(ADMIN_CONTROL_SOCKET_FILE)).unwrap();
228        assert!(has_session_marker(&runtime), "the admin socket");
229        drop(admin);
230        std::fs::remove_dir_all(&runtime).unwrap();
231    }
232}