Skip to main content

allot_shared/
autostart.rs

1//! The files that start allotd at login on Linux and macOS: a systemd user unit and a launchd
2//! LaunchAgent. `allot install` writes them, and on Linux the client starts allotd through the
3//! unit, so both read them the same way. Neither restarts allotd when it exits: the next
4//! session that needs it starts it again, as on Windows.
5
6use std::{
7    ffi::OsStr,
8    path::{Path, PathBuf},
9};
10
11/// The systemd user unit's name.
12pub const SYSTEMD_UNIT: &str = "allotd.service";
13/// The LaunchAgent's label, which also names its plist.
14pub const LAUNCHD_LABEL: &str = "tech.mehran.allotd";
15/// Overrides `~/.config` as the base of systemd's user unit directory.
16pub const CONFIG_HOME_VAR: &str = "XDG_CONFIG_HOME";
17
18const EXEC_START: &str = "ExecStart=";
19const PROGRAM_ARGUMENTS: &str = "<key>ProgramArguments</key>";
20
21/// The user unit file under `home`, in `config_home` (the value of [`CONFIG_HOME_VAR`]) when it
22/// is an absolute path, as the XDG spec requires, and in `~/.config` otherwise.
23pub fn systemd_unit_file(home: &Path, config_home: Option<&OsStr>) -> PathBuf {
24    let base = config_home
25        .map(Path::new)
26        .filter(|path| path.is_absolute())
27        .map_or_else(|| home.join(".config"), Path::to_owned);
28    base.join("systemd").join("user").join(SYSTEMD_UNIT)
29}
30
31/// The LaunchAgent's plist under `home`.
32pub fn launch_agent_file(home: &Path) -> PathBuf {
33    home.join("Library")
34        .join("LaunchAgents")
35        .join(format!("{LAUNCHD_LABEL}.plist"))
36}
37
38/// The user unit that starts `allotd` when the user manager starts, at login. `Type=exec`
39/// makes `systemctl start` fail when the file cannot be run, so the client can fall back.
40pub fn systemd_unit(allotd: &Path) -> String {
41    let exec = escape_exec(&allotd.to_string_lossy());
42    format!(
43        "# Written by allot install; allot uninstall removes it.\n\
44         [Unit]\n\
45         Description=Allot daemon (allotd)\n\
46         Documentation=https://github.com/meh7an/allot\n\
47         \n\
48         [Service]\n\
49         Type=exec\n\
50         {EXEC_START}\"{exec}\"\n\
51         \n\
52         [Install]\n\
53         WantedBy=default.target\n"
54    )
55}
56
57/// The executable a user unit starts, from its first `ExecStart=` line, or `None` when it has
58/// none.
59pub fn systemd_unit_exec(unit: &str) -> Option<String> {
60    let value = unit
61        .lines()
62        .find_map(|line| line.trim().strip_prefix(EXEC_START))?
63        .trim();
64    let raw = match value.strip_prefix('"') {
65        Some(quoted) => unquote_exec(quoted)?,
66        None => value.split_whitespace().next()?.to_owned(),
67    };
68    Some(raw.replace("%%", "%").replace("$$", "$"))
69}
70
71/// The LaunchAgent that starts `allotd` when it is loaded, which launchd does at login.
72pub fn launch_agent(allotd: &Path) -> String {
73    let program = xml_escape(&allotd.to_string_lossy());
74    format!(
75        r#"<?xml version="1.0" encoding="UTF-8"?>
76<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
77<plist version="1.0">
78<dict>
79	<key>Label</key>
80	<string>{LAUNCHD_LABEL}</string>
81	{PROGRAM_ARGUMENTS}
82	<array>
83		<string>{program}</string>
84	</array>
85	<key>RunAtLoad</key>
86	<true/>
87</dict>
88</plist>
89"#
90    )
91}
92
93/// The executable a LaunchAgent's plist starts, from the first of its `ProgramArguments`, or
94/// `None` when it has none (a binary plist included).
95pub fn launch_agent_program(plist: &str) -> Option<String> {
96    let after = &plist[plist.find(PROGRAM_ARGUMENTS)? + PROGRAM_ARGUMENTS.len()..];
97    let start = after.find("<string>")? + "<string>".len();
98    let end = start + after[start..].find("</string>")?;
99    Some(xml_unescape(&after[start..end]))
100}
101
102/// `text` with the five XML special characters escaped.
103pub fn xml_escape(text: &str) -> String {
104    text.replace('&', "&amp;")
105        .replace('<', "&lt;")
106        .replace('>', "&gt;")
107        .replace('"', "&quot;")
108        .replace('\'', "&apos;")
109}
110
111/// Undoes [`xml_escape`].
112pub fn xml_unescape(text: &str) -> String {
113    text.replace("&lt;", "<")
114        .replace("&gt;", ">")
115        .replace("&quot;", "\"")
116        .replace("&apos;", "'")
117        .replace("&amp;", "&")
118}
119
120/// A path for a double-quoted `ExecStart=` word: C escapes for `\` and `"`, and the `%`
121/// specifiers and `$` variables systemd would otherwise expand doubled.
122fn escape_exec(path: &str) -> String {
123    path.replace('\\', r"\\")
124        .replace('"', "\\\"")
125        .replace('%', "%%")
126        .replace('$', "$$")
127}
128
129/// The word up to the closing quote of a double-quoted `ExecStart=` value, with `\\` and `\"`
130/// unescaped; `None` when the quote is not closed.
131fn unquote_exec(quoted: &str) -> Option<String> {
132    let mut word = String::new();
133    let mut chars = quoted.chars();
134    while let Some(char) = chars.next() {
135        match char {
136            '"' => return Some(word),
137            '\\' => word.push(chars.next()?),
138            other => word.push(other),
139        }
140    }
141    None
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn test_systemd_unit_file_uses_an_absolute_config_home_only() {
150        let home = Path::new("/home/someone");
151        let default = home.join(".config/systemd/user/allotd.service");
152        assert_eq!(systemd_unit_file(home, None), default);
153        assert_eq!(
154            systemd_unit_file(home, Some(OsStr::new("relative/config"))),
155            default
156        );
157        let xdg = std::env::temp_dir().join("xdg");
158        assert_eq!(
159            systemd_unit_file(home, Some(xdg.as_os_str())),
160            xdg.join("systemd/user/allotd.service")
161        );
162    }
163
164    #[test]
165    fn test_launch_agent_file_is_named_after_the_label() {
166        assert_eq!(
167            launch_agent_file(Path::new("/Users/someone")),
168            Path::new("/Users/someone/Library/LaunchAgents/tech.mehran.allotd.plist")
169        );
170    }
171
172    #[test]
173    fn test_systemd_unit_quotes_and_reads_back_an_awkward_path() {
174        let allotd = r#"/home/a b/100% "$HOME"\x/.allot/bin/allotd"#;
175        let unit = systemd_unit(Path::new(allotd));
176
177        assert!(
178            unit.contains(r#"ExecStart="/home/a b/100%% \"$$HOME\"\\x/.allot/bin/allotd""#),
179            "{unit}"
180        );
181        assert!(unit.contains("Type=exec\n"));
182        assert!(unit.contains("WantedBy=default.target\n"));
183        assert!(!unit.contains("Restart="), "allotd is not restarted");
184        assert_eq!(systemd_unit_exec(&unit).as_deref(), Some(allotd));
185    }
186
187    #[test]
188    fn test_systemd_unit_exec_reads_unquoted_and_rejects_missing_or_unclosed() {
189        let unquoted = "[Service]\nExecStart=/opt/allotd --flag\n";
190        assert_eq!(systemd_unit_exec(unquoted).as_deref(), Some("/opt/allotd"));
191        assert_eq!(systemd_unit_exec("[Service]\nType=exec\n"), None);
192        assert_eq!(systemd_unit_exec("ExecStart=\"/opt/allotd\n"), None);
193    }
194
195    #[test]
196    fn test_launch_agent_escapes_and_reads_back_its_program() {
197        let allotd = "/Users/A&B <x>/.allot/bin/allotd";
198        let plist = launch_agent(Path::new(allotd));
199
200        assert!(
201            plist.contains("<string>/Users/A&amp;B &lt;x&gt;/.allot/bin/allotd</string>"),
202            "{plist}"
203        );
204        assert!(plist.contains("<string>tech.mehran.allotd</string>"));
205        assert!(plist.contains("<key>RunAtLoad</key>\n\t<true/>"));
206        assert!(!plist.contains("KeepAlive"), "allotd is not restarted");
207        assert_eq!(launch_agent_program(&plist).as_deref(), Some(allotd));
208        assert_eq!(launch_agent_program("bplist00"), None);
209    }
210}