allot_shared/
autostart.rs1use std::{
7 ffi::OsStr,
8 path::{Path, PathBuf},
9};
10
11pub const SYSTEMD_UNIT: &str = "allotd.service";
13pub const LAUNCHD_LABEL: &str = "tech.mehran.allotd";
15pub const CONFIG_HOME_VAR: &str = "XDG_CONFIG_HOME";
17
18const EXEC_START: &str = "ExecStart=";
19const PROGRAM_ARGUMENTS: &str = "<key>ProgramArguments</key>";
20
21pub 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
31pub fn launch_agent_file(home: &Path) -> PathBuf {
33 home.join("Library")
34 .join("LaunchAgents")
35 .join(format!("{LAUNCHD_LABEL}.plist"))
36}
37
38pub 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
57pub 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
71pub 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
93pub 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
102pub fn xml_escape(text: &str) -> String {
104 text.replace('&', "&")
105 .replace('<', "<")
106 .replace('>', ">")
107 .replace('"', """)
108 .replace('\'', "'")
109}
110
111pub fn xml_unescape(text: &str) -> String {
113 text.replace("<", "<")
114 .replace(">", ">")
115 .replace(""", "\"")
116 .replace("'", "'")
117 .replace("&", "&")
118}
119
120fn escape_exec(path: &str) -> String {
123 path.replace('\\', r"\\")
124 .replace('"', "\\\"")
125 .replace('%', "%%")
126 .replace('$', "$$")
127}
128
129fn 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&B <x>/.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}