use super::super::unix::service::{self, Control};
use super::bus;
use crate::context::Context;
use crate::error::{Error, Result};
use crate::host::Scheduler;
use crate::permit::Permit;
use crate::schedule::{Elsewhere, Job, Location, RESTART_AFTER_SECONDS};
use std::path::{Path, PathBuf};
use std::sync::Arc;
const SYSTEMCTL: &str = "systemctl";
const TIMER: &str = "pitboard-renew.timer";
const SERVICE: &str = "pitboard-renew.service";
const WATCH: &str = "pitboard-watch.service";
const RELOAD: [&str; 2] = ["--user", "daemon-reload"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Reads {
pub(super) unit_path: Vec<PathBuf>,
pub(super) home: Option<PathBuf>,
}
impl Reads {
fn reads_from(&self, units: &Path) -> bool {
self.unit_path.iter().any(|folder| folder == units)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Answer {
Reads(Reads),
Unreached(String),
}
pub(super) trait Manager: Send + Sync + std::fmt::Debug {
fn reads(&self, ctx: &Context) -> Result<Answer>;
}
#[derive(Debug)]
pub(super) struct UserManager;
impl Manager for UserManager {
fn reads(&self, ctx: &Context) -> Result<Answer> {
if cfg!(any(test, feature = "test-support")) {
return Err(Error::ScheduleRefused {
detail: "a build for tests asked the user manager itself".into(),
});
}
Ok(asked(ctx).map_or_else(Answer::Unreached, Answer::Reads))
}
}
#[zbus::proxy(
interface = "org.freedesktop.systemd1.Manager",
default_service = "org.freedesktop.systemd1",
default_path = "/org/freedesktop/systemd1",
gen_async = false
)]
trait SystemdManager {
#[zbus(property)]
fn unit_path(&self) -> zbus::Result<Vec<String>>;
#[zbus(property)]
fn environment(&self) -> zbus::Result<Vec<String>>;
}
fn asked(ctx: &Context) -> std::result::Result<Reads, String> {
let connection = bus::user_manager(ctx)?;
let manager = SystemdManagerProxy::builder(&connection)
.cache_properties(zbus::proxy::CacheProperties::No)
.build()
.map_err(|e| e.to_string())?;
let unit_path = manager.unit_path().map_err(|e| e.to_string())?;
let environment = manager.environment().map_err(|e| e.to_string())?;
Ok(Reads {
unit_path: unit_path.into_iter().map(PathBuf::from).collect(),
home: environment
.iter()
.find_map(|given| given.strip_prefix("HOME="))
.map(PathBuf::from),
})
}
#[cfg(any(test, feature = "test-support"))]
#[derive(Debug)]
pub(super) struct Pretend;
#[cfg(any(test, feature = "test-support"))]
impl Manager for Pretend {
fn reads(&self, ctx: &Context) -> Result<Answer> {
Ok(Answer::Reads(Reads {
unit_path: vec![Systemd::units(ctx)],
home: Some(ctx.home().to_path_buf()),
}))
}
}
#[derive(Debug)]
pub(super) struct Systemd {
control: Arc<dyn Control>,
manager: Arc<dyn Manager>,
}
impl Systemd {
pub(super) fn new(control: Arc<dyn Control>, manager: Arc<dyn Manager>) -> Systemd {
Systemd { control, manager }
}
fn units(ctx: &Context) -> PathBuf {
ctx.config_home()
.map_or_else(|| ctx.home().join(".config"), Path::to_path_buf)
.join("systemd/user")
}
fn written_before(ctx: &Context) -> PathBuf {
ctx.home().join(".config/systemd/user")
}
fn folders(ctx: &Context) -> Vec<PathBuf> {
let (units, before) = (Self::units(ctx), Self::written_before(ctx));
if units == before {
vec![units]
} else {
vec![units, before]
}
}
fn holding(ctx: &Context, job: Job) -> Option<PathBuf> {
Self::folders(ctx)
.into_iter()
.find(|folder| folder.join(Self::installed_by(job)).is_file())
}
fn service(job: Job) -> &'static str {
match job {
Job::Renew => SERVICE,
Job::Watch => WATCH,
}
}
fn installed_by(job: Job) -> &'static str {
match job {
Job::Renew => TIMER,
Job::Watch => WATCH,
}
}
fn links(job: Job) -> &'static [(&'static str, &'static str)] {
match job {
Job::Renew => &[
("timers.target.wants", TIMER),
("graphical-session.target.wants", SERVICE),
],
Job::Watch => &[("default.target.wants", WATCH)],
}
}
fn read(ctx: &Context, job: Job) -> Option<String> {
std::fs::read_to_string(Self::holding(ctx, job)?.join(Self::service(job))).ok()
}
fn starts(job: Job) -> &'static [&'static [&'static str]] {
match job {
Job::Renew => &[
&["--user", "enable", SERVICE],
&["--user", "enable", "--now", TIMER],
],
Job::Watch => &[&["--user", "enable", WATCH], &["--user", "restart", WATCH]],
}
}
fn takes_back(job: Job, was_there: bool) -> &'static [&'static [&'static str]] {
match (job, was_there) {
(Job::Renew, false) => &[
&["--user", "disable", "--now", TIMER],
&["--user", "disable", SERVICE],
],
(Job::Renew, true) => &[&["--user", "disable", SERVICE]],
(Job::Watch, false) => &[&["--user", "disable", WATCH]],
(Job::Watch, true) => &[],
}
}
fn start(&self, permit: Permit, job: Job) -> Result<()> {
Self::starts(job)
.iter()
.try_for_each(|args| self.control.start(permit, SYSTEMCTL, args))
}
fn stop(&self, permit: Permit, job: Job) -> Result<()> {
let stopped = self.control.run(
permit,
SYSTEMCTL,
&["--user", "disable", "--now", Self::installed_by(job)],
);
match job {
Job::Watch => stopped,
Job::Renew => {
let _ = self
.control
.run(permit, SYSTEMCTL, &["--user", "disable", SERVICE]);
let _ = self.control.run(
permit,
SYSTEMCTL,
&["--user", "clean", "--what=state", TIMER],
);
Ok(())
}
}
}
fn manager_of_this_home(&self, ctx: &Context, job: Job) -> Result<Answer> {
match self.manager.reads(ctx)? {
Answer::Reads(reads) if reads.home.as_deref() != Some(ctx.home()) => {
Err(Error::ScheduleManagerElsewhere {
elsewhere: Elsewhere::Home {
home: ctx.home().to_path_buf(),
theirs: reads.home,
},
job,
})
}
answer => Ok(answer),
}
}
}
fn unreached(why: &str) -> Error {
Error::ScheduleRefused {
detail: format!("your user's systemd could not be asked where it reads units: {why}"),
}
}
pub(super) fn started_by_systemd(root: &Path) -> bool {
root.join("run/systemd/system").is_dir()
}
impl Scheduler for Systemd {
fn location(&self, ctx: &Context, job: Job) -> Location {
let folder = Self::holding(ctx, job).unwrap_or_else(|| Self::units(ctx));
Location::File(folder.join(Self::installed_by(job)))
}
fn installed(&self, ctx: &Context, job: Job) -> bool {
Self::holding(ctx, job).is_some()
}
fn program(&self, ctx: &Context, job: Job) -> Option<PathBuf> {
command(&Self::read(ctx, job)?, job).map(|(program, _)| program)
}
fn options(&self, ctx: &Context, job: Job) -> Vec<String> {
Self::read(ctx, job)
.and_then(|body| command(&body, job))
.map(|(_, options)| options)
.unwrap_or_default()
}
fn environment(&self, ctx: &Context, job: Job) -> Vec<(String, String)> {
Self::read(ctx, job)
.map(|body| given(&body))
.unwrap_or_default()
}
fn put(
&self,
ctx: &Context,
permit: Permit,
job: Job,
program: &Path,
options: &[String],
environment: &[(String, String)],
) -> Result<()> {
let program = spelled(program)?;
let units = Self::units(ctx);
match self.manager_of_this_home(ctx, job)? {
Answer::Reads(reads) if reads.reads_from(&units) => {}
Answer::Reads(_) => {
return Err(Error::ScheduleManagerElsewhere {
elsewhere: Elsewhere::Folder { units },
job,
});
}
Answer::Unreached(why) => return Err(unreached(&why)),
}
let unit = units.join(Self::service(job));
let timer_path = units.join(TIMER);
let before = (
std::fs::read_to_string(&unit).ok(),
std::fs::read_to_string(&timer_path).ok(),
);
service::write(
permit,
&unit,
&unit_file(job, &program, options, environment),
)?;
if job == Job::Renew {
service::write(permit, &timer_path, &timer())?;
}
let _ = self.control.run(permit, SYSTEMCTL, &RELOAD);
let Err(refused) = self.start(permit, job) else {
return Ok(());
};
let was_there = match job {
Job::Renew => before.1.is_some(),
Job::Watch => before.0.is_some(),
};
for args in Self::takes_back(job, was_there) {
let _ = self.control.run(permit, SYSTEMCTL, args);
}
service::restore(permit, &unit, before.0.as_deref());
if job == Job::Renew {
service::restore(permit, &timer_path, before.1.as_deref());
}
let _ = self.control.run(permit, SYSTEMCTL, &RELOAD);
if was_there {
let _ = self.start(permit, job);
}
Err(refused)
}
fn remove(&self, ctx: &Context, permit: Permit, job: Job) -> Result<bool> {
let holding: Vec<PathBuf> = Self::folders(ctx)
.into_iter()
.filter(|folder| folder.join(Self::installed_by(job)).is_file())
.collect();
if holding.is_empty() {
return Ok(false);
}
let answer = self.manager_of_this_home(ctx, job)?;
let loads = |folder: &Path| match &answer {
Answer::Reads(reads) => Some(reads.reads_from(folder)),
Answer::Unreached(_) => None,
};
let asks = holding.iter().any(|folder| loads(folder) != Some(false));
if asks {
self.stop(permit, job)?;
}
for folder in &holding {
if loads(folder) != Some(true) {
for (wants, unit) in Self::links(job) {
service::remove(permit, &folder.join(wants).join(unit))?;
}
}
service::remove(permit, &folder.join(Self::installed_by(job)))?;
service::remove(permit, &folder.join(Self::service(job)))?;
}
if asks {
let _ = self.control.run(permit, SYSTEMCTL, &RELOAD);
}
Ok(true)
}
fn started_this_process(&self, job: Job, said: Option<&str>) -> bool {
said == Some(Self::service(job))
}
fn outdated(&self, ctx: &Context, job: Job) -> bool {
let Some(folder) = Self::holding(ctx, job) else {
return false;
};
let lacks = |file: &str, setting: &str| {
!std::fs::read_to_string(folder.join(file))
.is_ok_and(|body| body.lines().any(|line| line.starts_with(setting)))
};
lacks(Self::service(job), "ConditionFileIsExecutable=")
|| (job == Job::Renew && lacks(TIMER, "OnCalendar="))
}
}
struct Spelled {
run: String,
condition: String,
}
fn spelled(program: &Path) -> Result<Spelled> {
let refused = |what: &str| Error::ScheduleRefused {
detail: format!(
"a systemd unit cannot run a program whose path holds {what}, so nothing was \
written. Install Pitboard where its path holds none, then try again."
),
};
let path = program
.to_str()
.ok_or_else(|| refused("bytes that are not UTF-8"))?;
if let Some(c) = path.chars().find(char::is_ascii_control) {
return Err(refused(&format!("the character U+{:04X}", u32::from(c))));
}
if path.contains('\\') {
return Err(refused("a backslash"));
}
if path.contains(['"', '\'']) {
return Err(refused("a quote"));
}
if path.ends_with(' ') {
return Err(refused("a space at its end"));
}
let condition = path.replace('%', "%%");
let run = if condition.contains(' ') {
format!("\"{condition}\"")
} else {
condition.clone()
};
Ok(Spelled { run, condition })
}
fn command(body: &str, job: Job) -> Option<(PathBuf, Vec<String>)> {
let run = body
.lines()
.find_map(|line| line.strip_prefix("ExecStart="))?;
let marked = format!(" {}", job.marked().join(" "));
let quoted = run
.strip_prefix('"')
.and_then(|quoted| quoted.split_once('"'));
let (program, options) = match quoted {
Some((program, after)) => (program, after.strip_prefix(marked.as_str())?),
None => run.rsplit_once(marked.as_str()).or_else(|| match job {
Job::Renew => run.strip_suffix(" renew").map(|program| (program, "")),
Job::Watch => None,
})?,
};
let options = options.split_whitespace().map(str::to_owned).collect();
Some((PathBuf::from(program.replace("%%", "%")), options))
}
fn unit_file(
job: Job,
program: &Spelled,
options: &[String],
environment: &[(String, String)],
) -> String {
let environment = environment
.iter()
.map(|(name, value)| assignment(name, value))
.collect::<String>();
let run = [job.marked().join(" "), options.join(" ")].join(" ");
let run = format!("{} {}", program.run, run.trim_end());
let condition = &program.condition;
match job {
Job::Renew => format!(
"[Unit]\n\
Description=Renew Pitboard's parked logins\n\
Documentation=https://docs.usepitboard.com\n\
After=graphical-session.target\n\
ConditionFileIsExecutable={condition}\n\
\n\
[Service]\n\
Type=oneshot\n\
{environment}\
ExecStart={run}\n\
\n\
[Install]\n\
WantedBy=graphical-session.target\n"
),
Job::Watch => format!(
"[Unit]\n\
Description=Switch Claude Code before an account runs out, and warm up accounts\n\
Documentation=https://docs.usepitboard.com\n\
ConditionFileIsExecutable={condition}\n\
\n\
[Service]\n\
{environment}\
ExecStart={run}\n\
Restart=on-failure\n\
RestartSec={RESTART_AFTER_SECONDS}\n\
\n\
[Install]\n\
WantedBy=default.target\n"
),
}
}
fn plain(text: &str) -> bool {
text.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_.:/@,".contains(c))
}
fn assignment(name: &str, value: &str) -> String {
if plain(name) && plain(value) {
return format!("Environment={name}={value}\n");
}
let mut quoted = String::new();
for c in format!("{name}={value}").chars() {
match c {
'\\' | '"' => {
quoted.push('\\');
quoted.push(c);
}
'%' => quoted.push_str("%%"),
c if c.is_control() && c.is_ascii() => quoted.push_str(&format!("\\x{:02x}", c as u32)),
c if c.is_control() => quoted.push_str(&format!("\\u{:04x}", c as u32)),
c => quoted.push(c),
}
}
format!("Environment=\"{quoted}\"\n")
}
fn given(body: &str) -> Vec<(String, String)> {
body.lines()
.filter_map(|line| {
let written = line.strip_prefix("Environment=")?;
let assigned = match written
.strip_prefix('"')
.and_then(|quoted| quoted.strip_suffix('"'))
{
Some(quoted) => unquoted(quoted),
None => written.to_string(),
};
let (name, value) = assigned.split_once('=')?;
Some((name.to_string(), value.to_string()))
})
.collect()
}
fn unquoted(quoted: &str) -> String {
let mut text = String::with_capacity(quoted.len());
let mut chars = quoted.chars();
while let Some(c) = chars.next() {
let escaped = match c {
'\\' | '%' => chars.next().unwrap_or(c),
c => {
text.push(c);
continue;
}
};
let digits = match (c, escaped) {
('\\', 'x') => 2,
('\\', 'u') => 4,
_ => {
text.push(escaped);
continue;
}
};
let number: String = chars.by_ref().take(digits).collect();
text.extend(
u32::from_str_radix(&number, 16)
.ok()
.and_then(char::from_u32),
);
}
text
}
fn timer() -> String {
"[Unit]\n\
Description=Renew Pitboard's parked logins daily\n\
\n\
[Timer]\n\
OnCalendar=daily\n\
Persistent=true\n\
RandomizedDelaySec=1h\n\
\n\
[Install]\n\
WantedBy=timers.target\n"
.to_string()
}
#[cfg(test)]
#[allow(
clippy::disallowed_methods,
reason = "a test sets up its scratch files as a person or a tool would"
)]
mod tests {
use super::*;
use crate::host::memory::MemoryHost;
use crate::schedule::{install, installed_program};
use std::os::unix::fs::PermissionsExt;
#[test]
fn only_a_system_systemd_started_offers_its_scheduler() {
let root = tempfile::tempdir().expect("a scratch root");
assert!(!started_by_systemd(root.path()));
std::fs::create_dir_all(root.path().join("run/systemd")).expect("made");
std::fs::write(root.path().join("run/systemd/system"), "").expect("a file");
assert!(
!started_by_systemd(root.path()),
"a file is not the directory"
);
std::fs::remove_file(root.path().join("run/systemd/system")).expect("gone");
std::fs::create_dir(root.path().join("run/systemd/system")).expect("made");
assert!(started_by_systemd(root.path()));
}
fn pairs(given: &[(&str, &str)]) -> Vec<(String, String)> {
given
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect()
}
fn unit(job: Job, path: &str, options: &[String], environment: &[(String, String)]) -> String {
let program = spelled(Path::new(path)).expect("a path a unit holds");
unit_file(job, &program, options, environment)
}
#[test]
fn the_unit_gives_its_service_the_variables_it_is_handed_and_reads_them_back() {
let program = "/usr/local/bin/pitboard";
let handed = pairs(&[
("PITBOARD_NO_ARGV", "1"),
("ALL_PROXY", "socks5h://alice:p%40ss\"w\\rd@127.0.0.1:1080"),
("HTTPS_PROXY", "http://proxy.example.com:3128"),
("no_proxy", ""),
("NO_PROXY", "*.anthropic.com, localhost"),
]);
let written = unit(Job::Renew, program, &[], &handed);
assert!(
written.contains(
"Type=oneshot\n\
Environment=PITBOARD_NO_ARGV=1\n\
Environment=\"ALL_PROXY=socks5h://alice:p%%40ss\\\"w\\\\rd@127.0.0.1:1080\"\n\
Environment=HTTPS_PROXY=http://proxy.example.com:3128\n\
Environment=no_proxy=\n\
Environment=\"NO_PROXY=*.anthropic.com, localhost\"\n\
ExecStart=/usr/local/bin/pitboard renew --scheduled\n"
),
"{written}"
);
assert_eq!(given(&written), handed);
assert!(!unit(Job::Renew, program, &[], &[]).contains("Environment="));
assert_eq!(given(&unit(Job::Renew, program, &[], &[])), Vec::new());
let broken = pairs(&[("NO_PROXY", "a\nExecStart=/bin/false\u{85}")]);
let written = unit(Job::Renew, program, &[], &broken);
assert!(
written.contains("Environment=\"NO_PROXY=a\\x0aExecStart=/bin/false\\u0085\"\n"),
"{written}"
);
assert_eq!(
written
.lines()
.filter(|l| l.starts_with("ExecStart="))
.count(),
1,
"{written}"
);
assert_eq!(given(&written), broken);
}
#[test]
fn the_watch_service_starts_with_the_users_systemd_and_reads_back_its_share() {
let at = ["--at".to_string(), "90".to_string()];
let written = unit(Job::Watch, "/usr/local/bin/pitboard", &at, &[]);
assert!(
written.contains(
"[Service]\n\
ExecStart=/usr/local/bin/pitboard watch --scheduled --at 90\n\
Restart=on-failure\n\
RestartSec=60\n\
\n\
[Install]\n\
WantedBy=default.target\n"
),
"{written}"
);
assert!(!written.contains("Type=oneshot"), "{written}");
assert_eq!(
command(&written, Job::Watch),
Some((PathBuf::from("/usr/local/bin/pitboard"), at.to_vec()))
);
assert_eq!(command(&written, Job::Renew), None, "not renewal's");
}
#[test]
fn the_timer_runs_on_each_calendar_day_and_catches_up_after_sleep() {
let written = unit(Job::Renew, "/usr/local/bin/pitboard", &[], &[]);
assert!(
written.contains("ExecStart=/usr/local/bin/pitboard renew --scheduled\n"),
"{written}"
);
assert!(!written.contains("status"));
let timer = timer();
assert!(
timer.contains(
"[Timer]\n\
OnCalendar=daily\n\
Persistent=true\n\
RandomizedDelaySec=1h\n\
\n\
[Install]\n\
WantedBy=timers.target\n"
),
"{timer}"
);
for monotonic in ["OnUnitActiveSec", "OnStartupSec", "OnBootSec"] {
assert!(!timer.contains(monotonic), "{timer}");
}
}
#[test]
fn the_renewal_service_also_runs_at_each_graphical_sign_in() {
let written = unit(Job::Renew, "/usr/bin/pitboard", &[], &[]);
assert!(
written.contains(
"Documentation=https://docs.usepitboard.com\n\
After=graphical-session.target\n"
),
"{written}"
);
assert!(
written.ends_with(
"ExecStart=/usr/bin/pitboard renew --scheduled\n\
\n\
[Install]\n\
WantedBy=graphical-session.target\n"
),
"{written}"
);
let (_home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let systemd = Systemd::new(asked.clone(), Arc::new(Pretend));
let program = Path::new("/usr/bin/pitboard");
systemd
.put(&ctx, Permit::for_a_test(), Job::Renew, program, &[], &[])
.expect("installed");
assert_eq!(
asked.taken(),
[
"--user daemon-reload".to_string(),
format!("--user enable {SERVICE}"),
format!("--user enable --now {TIMER}"),
]
);
assert!(
systemd
.remove(&ctx, Permit::for_a_test(), Job::Renew)
.expect("taken away")
);
assert_eq!(
asked.taken(),
[
format!("--user disable --now {TIMER}"),
format!("--user disable {SERVICE}"),
format!("--user clean --what=state {TIMER}"),
"--user daemon-reload".to_string(),
]
);
}
#[test]
fn a_refused_start_takes_back_both_enables() {
let (_home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let systemd = Systemd::new(asked.clone(), Arc::new(Pretend));
let program = Path::new("/usr/bin/pitboard");
let units = Systemd::units(&ctx);
let reload = "--user daemon-reload".to_string();
let enable = format!("--user enable {SERVICE}");
let start = format!("--user enable --now {TIMER}");
let disable = format!("--user disable {SERVICE}");
let stop = format!("--user disable --now {TIMER}");
for (refusing, asked_for) in [
(
SERVICE,
vec![
reload.clone(),
enable.clone(),
stop.clone(),
disable.clone(),
reload.clone(),
],
),
(
TIMER,
vec![
reload.clone(),
enable.clone(),
start.clone(),
stop.clone(),
disable.clone(),
reload.clone(),
],
),
] {
asked.refuse(refusing);
let refused = systemd
.put(&ctx, Permit::for_a_test(), Job::Renew, program, &[], &[])
.expect_err("refused");
assert_eq!(refused.code(), "schedule_refused", "{refusing}");
assert_eq!(asked.taken(), asked_for, "{refusing}");
assert!(!systemd.installed(&ctx, Job::Renew), "{refusing}");
assert!(!units.join(SERVICE).exists(), "{refusing}");
}
std::fs::create_dir_all(&units).expect("made");
let earlier = (
"[Service]\nType=oneshot\nExecStart=/usr/bin/pitboard renew --scheduled\n",
"[Timer]\nOnUnitActiveSec=86400\nOnStartupSec=900\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n",
);
std::fs::write(units.join(SERVICE), earlier.0).expect("written");
std::fs::write(units.join(TIMER), earlier.1).expect("written");
asked.refuse(TIMER);
systemd
.put(&ctx, Permit::for_a_test(), Job::Renew, program, &[], &[])
.expect_err("refused");
assert_eq!(
asked.taken(),
[
reload.clone(),
enable.clone(),
start.clone(),
disable,
reload,
enable,
start
]
);
assert_eq!(
(
std::fs::read_to_string(units.join(SERVICE)).expect("put back"),
std::fs::read_to_string(units.join(TIMER)).expect("put back"),
),
(earlier.0.to_string(), earlier.1.to_string())
);
}
#[test]
fn a_service_whose_pitboard_is_gone_is_skipped() {
for (job, description, ordered) in [
(
Job::Renew,
"Renew Pitboard's parked logins",
"After=graphical-session.target\n",
),
(
Job::Watch,
"Switch Claude Code before an account runs out, and warm up accounts",
"",
),
] {
let written = unit(job, "/usr/bin/pitboard", &[], &[]);
assert!(
written.starts_with(&format!(
"[Unit]\n\
Description={description}\n\
Documentation=https://docs.usepitboard.com\n\
{ordered}\
ConditionFileIsExecutable=/usr/bin/pitboard\n\
\n\
[Service]\n"
)),
"{written}"
);
}
}
#[test]
fn a_program_path_with_a_space_or_a_percent_reads_back_as_written() {
let path = "/home/x/100% sure/bin/pitboard";
let at = ["--at".to_string(), "90".to_string()];
for (job, options, run) in [
(Job::Renew, &[][..], "renew --scheduled"),
(Job::Watch, &at[..], "watch --scheduled --at 90"),
] {
let written = unit(job, path, options, &[]);
assert!(
written.contains("ConditionFileIsExecutable=/home/x/100%% sure/bin/pitboard\n"),
"{written}"
);
assert!(
written.contains(&format!(
"ExecStart=\"/home/x/100%% sure/bin/pitboard\" {run}\n"
)),
"{written}"
);
assert_eq!(
command(&written, job),
Some((PathBuf::from(path), options.to_vec())),
"{written}"
);
}
let dollar = unit(Job::Renew, "/opt/$x/pitboard", &[], &[]);
assert!(dollar.contains("ExecStart=/opt/$x/pitboard renew --scheduled\n"));
assert_eq!(
command(&dollar, Job::Renew).map(|(program, _)| program),
Some(PathBuf::from("/opt/$x/pitboard"))
);
let scratch = tempfile::tempdir().expect("a scratch folder");
let home = scratch.path().join("home");
let program = home.join("100% sure").join("pitboard");
std::fs::create_dir_all(program.parent().expect("its folder")).expect("made");
std::fs::write(&program, "").expect("a program");
let ctx = Context::new(home)
.with_memory_stores(MemoryHost::new())
.with_schedule_program(program.clone());
install(&ctx, Permit::for_a_test()).expect("installed");
assert_eq!(installed_program(&ctx), Some(program));
}
#[test]
fn a_program_path_no_unit_can_run_is_refused_before_anything_is_written() {
let (_home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let systemd = Systemd::new(asked.clone(), Arc::new(Pretend));
for (path, named) in [
("/opt/a\"b/pitboard", "a quote"),
("/opt/it's/pitboard", "a quote"),
("/opt/a\\b/pitboard", "a backslash"),
("/opt/a\nb/pitboard", "the character U+000A"),
("/opt/a\tb/pitboard", "the character U+0009"),
("/opt/pitboard ", "a space at its end"),
] {
let refused = systemd
.put(
&ctx,
Permit::for_a_test(),
Job::Renew,
Path::new(path),
&[],
&[],
)
.expect_err("refused");
assert_eq!(refused.code(), "schedule_refused", "{path:?}");
assert!(refused.to_string().contains(named), "{refused}");
}
assert!(!Systemd::units(&ctx).exists(), "nothing was written");
assert_eq!(asked.taken(), Vec::<String>::new());
}
#[test]
fn a_unit_written_without_the_marker_still_names_its_program_and_install_adds_it() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let home = scratch.path().join("home");
let program = home.join("bin/pitboard");
std::fs::create_dir_all(program.parent().expect("its directory")).expect("made");
std::fs::write(&program, "").expect("a program");
let ctx = Context::new(home.clone())
.with_memory_stores(MemoryHost::new())
.with_schedule_program(program.clone());
let units = Systemd::units(&ctx);
std::fs::create_dir_all(&units).expect("made");
std::fs::write(units.join(TIMER), timer()).expect("written");
std::fs::write(
units.join(SERVICE),
format!(
"[Service]\nType=oneshot\nExecStart={} renew\n",
program.display()
),
)
.expect("written");
assert_eq!(installed_program(&ctx), Some(program.clone()), "as before");
install(&ctx, Permit::for_a_test()).expect("installed again");
let written = std::fs::read_to_string(units.join(SERVICE)).expect("the service");
assert!(
written.contains(&format!(
"ExecStart={} renew --scheduled\n",
program.display()
)),
"{written}"
);
assert_eq!(installed_program(&ctx), Some(program));
let systemd = Systemd::new(
Arc::new(service::Pretend {
refuse_start: Arc::default(),
}),
Arc::new(Pretend),
);
assert!(systemd.started_this_process(Job::Renew, Some(SERVICE)));
assert!(!systemd.started_this_process(Job::Renew, Some(TIMER)));
assert!(
!systemd.started_this_process(Job::Renew, None),
"what systemd passes is not read"
);
}
#[derive(Debug, Default)]
struct Asked {
refusing: std::sync::Mutex<Option<&'static str>>,
calls: std::sync::Mutex<Vec<String>>,
}
impl Asked {
fn refuse(&self, word: &'static str) {
*self
.refusing
.lock()
.expect("a poisoned test is a failed test") = Some(word);
}
fn taken(&self) -> Vec<String> {
std::mem::take(&mut self.calls.lock().expect("a poisoned test is a failed test"))
}
}
impl Control for Asked {
fn run(&self, _: Permit, _program: &str, args: &[&str]) -> Result<()> {
let call = args.join(" ");
self.calls
.lock()
.expect("a poisoned test is a failed test")
.push(call.clone());
let mut refusing = self
.refusing
.lock()
.expect("a poisoned test is a failed test");
if refusing.is_some_and(|word| args.contains(&word)) {
*refusing = None;
return Err(Error::ScheduleRefused {
detail: format!("systemctl refused {call} in a test"),
});
}
Ok(())
}
}
#[derive(Debug)]
struct Says(Reads);
impl Manager for Says {
fn reads(&self, _ctx: &Context) -> Result<Answer> {
Ok(Answer::Reads(self.0.clone()))
}
}
fn says(unit_path: &[&Path], home: Option<&Path>) -> Arc<Says> {
Arc::new(Says(Reads {
unit_path: unit_path
.iter()
.map(|folder| folder.to_path_buf())
.collect(),
home: home.map(Path::to_path_buf),
}))
}
fn scratch_home() -> (tempfile::TempDir, Context) {
let home = tempfile::tempdir().expect("a scratch home");
let ctx = Context::new(home.path().to_path_buf()).with_memory_stores(MemoryHost::new());
(home, ctx)
}
fn configured_in(home: &Path, config: &Path) -> Context {
let named = |path: &Path| path.to_string_lossy().into_owned();
let env: crate::context::Environment =
[("HOME", named(home)), ("XDG_CONFIG_HOME", named(config))]
.into_iter()
.collect();
Context::for_command_line(&env).with_memory_stores(MemoryHost::new())
}
#[test]
fn a_unit_is_written_only_where_the_user_manager_reads_its_folder() {
let (home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let program = Path::new("/usr/local/bin/pitboard");
let units = Systemd::units(&ctx);
let elsewhere = home.path().join("elsewhere/systemd/user");
let systemd = Systemd::new(asked.clone(), says(&[&elsewhere], Some(home.path())));
for job in [Job::Renew, Job::Watch] {
let refused = systemd
.put(&ctx, Permit::for_a_test(), job, program, &[], &[])
.expect_err("refused");
assert_eq!(refused.code(), "schedule_manager_elsewhere");
assert!(
refused.to_string().contains(&units.display().to_string()),
"{refused}"
);
}
assert!(!units.exists(), "nothing was written");
assert_eq!(asked.taken(), Vec::<String>::new(), "nor asked");
let systemd = Systemd::new(
asked.clone(),
says(&[&elsewhere, &units], Some(home.path())),
);
systemd
.put(&ctx, Permit::for_a_test(), Job::Renew, program, &[], &[])
.expect("installed where it is read");
assert!(systemd.installed(&ctx, Job::Renew));
}
#[test]
fn a_unit_is_written_only_for_the_home_the_user_manager_runs_with() {
let (home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let program = Path::new("/usr/local/bin/pitboard");
let units = Systemd::units(&ctx);
let other = home.path().join("other");
for theirs in [Some(other.as_path()), None] {
let systemd = Systemd::new(asked.clone(), says(&[&units], theirs));
for job in [Job::Renew, Job::Watch] {
let refused = systemd
.put(&ctx, Permit::for_a_test(), job, program, &[], &[])
.expect_err("refused");
assert_eq!(refused.code(), "schedule_manager_elsewhere");
let said = refused.to_string();
assert!(said.contains(&home.path().display().to_string()), "{said}");
if let Some(theirs) = theirs {
assert!(said.contains(&theirs.display().to_string()), "{said}");
}
}
}
assert!(!units.exists(), "nothing was written");
assert_eq!(asked.taken(), Vec::<String>::new());
let ours = Systemd::new(asked.clone(), says(&[&units], Some(home.path())));
ours.put(&ctx, Permit::for_a_test(), Job::Watch, program, &[], &[])
.expect("installed for this home");
asked.taken();
let theirs = Systemd::new(asked.clone(), says(&[&units], Some(&other)));
let refused = theirs
.remove(&ctx, Permit::for_a_test(), Job::Watch)
.expect_err("another home's manager");
assert_eq!(refused.code(), "schedule_manager_elsewhere");
assert!(units.join(WATCH).is_file(), "still there");
assert_eq!(asked.taken(), Vec::<String>::new());
}
#[test]
fn nothing_is_asked_of_systemctl_where_the_manager_does_not_read_the_units() {
let (home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let program = Path::new("/usr/local/bin/pitboard");
let units = Systemd::units(&ctx);
let reading = Systemd::new(asked.clone(), says(&[&units], Some(home.path())));
let not_reading = Systemd::new(asked.clone(), says(&[], Some(home.path())));
for job in [Job::Renew, Job::Watch] {
reading
.put(&ctx, Permit::for_a_test(), job, program, &[], &[])
.expect("installed");
let links = enabled(&units, job);
asked.taken();
assert!(
not_reading
.remove(&ctx, Permit::for_a_test(), job)
.expect("taken away")
);
assert_eq!(asked.taken(), Vec::<String>::new(), "{job:?}");
assert!(!reading.installed(&ctx, job));
for gone in [Systemd::service(job), Systemd::installed_by(job)] {
assert!(!units.join(gone).exists(), "{gone}");
}
for link in &links {
assert!(
std::fs::symlink_metadata(link).is_err(),
"{}",
link.display()
);
}
}
for job in [Job::Renew, Job::Watch] {
reading
.put(&ctx, Permit::for_a_test(), job, program, &[], &[])
.expect("installed");
}
asked.taken();
for job in [Job::Renew, Job::Watch] {
assert!(
reading
.remove(&ctx, Permit::for_a_test(), job)
.expect("taken away")
);
}
assert_eq!(
asked.taken(),
[
format!("--user disable --now {TIMER}"),
format!("--user disable {SERVICE}"),
format!("--user clean --what=state {TIMER}"),
"--user daemon-reload".to_string(),
format!("--user disable --now {WATCH}"),
"--user daemon-reload".to_string(),
]
);
}
fn enabled(units: &Path, job: Job) -> Vec<PathBuf> {
Systemd::links(job)
.iter()
.map(|(wants, unit)| {
let link = units.join(wants).join(unit);
std::fs::create_dir_all(link.parent().expect("its folder")).expect("made");
crate::host::fs::testing::link(&units.join(unit), &link)
.expect("enabled, as systemctl links it");
link
})
.collect()
}
#[derive(Debug)]
struct Unreached;
impl Manager for Unreached {
fn reads(&self, _ctx: &Context) -> Result<Answer> {
Ok(Answer::Unreached(
"neither XDG_RUNTIME_DIR nor DBUS_SESSION_BUS_ADDRESS is set".into(),
))
}
}
#[test]
fn a_job_is_taken_away_where_nothing_reaches_the_user_manager() {
let (home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let program = Path::new("/usr/local/bin/pitboard");
let units = Systemd::units(&ctx);
let reading = Systemd::new(asked.clone(), says(&[&units], Some(home.path())));
let unreached = Systemd::new(asked.clone(), Arc::new(Unreached));
let mut links = Vec::new();
for job in [Job::Renew, Job::Watch] {
reading
.put(&ctx, Permit::for_a_test(), job, program, &[], &[])
.expect("installed");
links.push(enabled(&units, job));
}
asked.taken();
let gone = |job: Job, links: &[PathBuf]| {
assert!(!reading.installed(&ctx, job), "{job:?}");
for gone in [Systemd::service(job), Systemd::installed_by(job)] {
assert!(!units.join(gone).exists(), "{gone}");
}
for link in links {
assert!(
std::fs::symlink_metadata(link).is_err(),
"{}",
link.display()
);
}
};
asked.refuse("disable");
assert!(
unreached
.remove(&ctx, Permit::for_a_test(), Job::Renew)
.expect("taken away")
);
assert_eq!(
asked.taken(),
[
format!("--user disable --now {TIMER}"),
format!("--user disable {SERVICE}"),
format!("--user clean --what=state {TIMER}"),
"--user daemon-reload".to_string(),
]
);
gone(Job::Renew, &links[0]);
asked.refuse("disable");
let refused = unreached
.remove(&ctx, Permit::for_a_test(), Job::Watch)
.expect_err("it may still be running");
assert_eq!(refused.code(), "schedule_refused");
assert!(units.join(WATCH).is_file(), "still there");
asked.taken();
assert!(
unreached
.remove(&ctx, Permit::for_a_test(), Job::Watch)
.expect("stopped, then taken away")
);
assert_eq!(
asked.taken(),
[
format!("--user disable --now {WATCH}"),
"--user daemon-reload".to_string(),
]
);
gone(Job::Watch, &links[1]);
let refused = unreached
.put(&ctx, Permit::for_a_test(), Job::Renew, program, &[], &[])
.expect_err("nothing to tell where it would run");
assert_eq!(refused.code(), "schedule_refused");
assert!(
refused.to_string().contains("could not be asked"),
"{refused}"
);
assert!(!units.join(TIMER).exists());
assert_eq!(asked.taken(), Vec::<String>::new());
}
#[test]
fn the_units_go_where_xdg_config_home_says() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let (home, config) = (scratch.path().join("home"), scratch.path().join("config"));
let program = home.join("bin/pitboard");
std::fs::create_dir_all(program.parent().expect("its folder")).expect("made");
std::fs::write(&program, "").expect("a program");
let ctx = configured_in(&home, &config).with_schedule_program(program.clone());
let units = config.join("systemd/user");
let location = install(&ctx, Permit::for_a_test()).expect("installed");
assert_eq!(location, Location::File(units.join(TIMER)));
for file in [TIMER, SERVICE] {
assert!(units.join(file).is_file(), "{file}");
}
assert!(!home.join(".config").exists(), "nothing in ~/.config");
assert_eq!(installed_program(&ctx), Some(program));
}
#[test]
fn a_unit_an_earlier_pitboard_wrote_in_dot_config_is_still_found_and_taken_away() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let (home, config) = (scratch.path().join("home"), scratch.path().join("config"));
let ctx = configured_in(&home, &config);
let before = home.join(".config/systemd/user");
let program = "/usr/local/bin/pitboard";
let earlier = || {
std::fs::create_dir_all(before.join("timers.target.wants")).expect("made");
std::fs::write(
before.join(TIMER),
"[Timer]\nOnUnitActiveSec=86400\nOnStartupSec=900\nPersistent=true\n",
)
.expect("written");
std::fs::write(
before.join(SERVICE),
format!("[Service]\nType=oneshot\nExecStart={program} renew --scheduled\n"),
)
.expect("written");
crate::host::fs::testing::link(
&before.join(TIMER),
&before.join("timers.target.wants").join(TIMER),
)
.expect("enabled");
};
let asked = Arc::new(Asked::default());
earlier();
let systemd = Systemd::new(
asked.clone(),
says(&[&config.join("systemd/user")], Some(&home)),
);
assert!(systemd.installed(&ctx, Job::Renew));
assert_eq!(
systemd.location(&ctx, Job::Renew),
Location::File(before.join(TIMER))
);
assert_eq!(
systemd.program(&ctx, Job::Renew),
Some(PathBuf::from(program))
);
assert!(systemd.outdated(&ctx, Job::Renew));
assert!(
systemd
.remove(&ctx, Permit::for_a_test(), Job::Renew)
.expect("taken away")
);
assert_eq!(asked.taken(), Vec::<String>::new(), "never loaded");
assert!(!systemd.installed(&ctx, Job::Renew));
for gone in [TIMER, SERVICE, "timers.target.wants/pitboard-renew.timer"] {
assert!(
std::fs::symlink_metadata(before.join(gone)).is_err(),
"{gone}"
);
}
earlier();
let systemd = Systemd::new(asked.clone(), says(&[&before], Some(&home)));
assert!(
systemd
.remove(&ctx, Permit::for_a_test(), Job::Renew)
.expect("taken away")
);
assert_eq!(
asked.taken(),
[
format!("--user disable --now {TIMER}"),
format!("--user disable {SERVICE}"),
format!("--user clean --what=state {TIMER}"),
"--user daemon-reload".to_string(),
]
);
assert!(!before.join(TIMER).exists());
}
struct Plays {
unit_path: Vec<String>,
environment: Vec<String>,
}
#[zbus::interface(name = "org.freedesktop.systemd1.Manager")]
impl Plays {
#[zbus(property)]
fn unit_path(&self) -> Vec<String> {
self.unit_path.clone()
}
#[zbus(property)]
fn environment(&self) -> Vec<String> {
self.environment.clone()
}
}
const FOLDERS: [&str; 2] = ["/home/x/.config/systemd/user", "/usr/lib/systemd/user"];
const ENVIRONMENT: [&str; 3] = ["LANG=C.UTF-8", "HOME=/home/x", "PATH=/usr/bin"];
fn plays() -> Plays {
Plays {
unit_path: FOLDERS.map(String::from).to_vec(),
environment: ENVIRONMENT.map(String::from).to_vec(),
}
}
fn as_played() -> Reads {
Reads {
unit_path: FOLDERS.map(PathBuf::from).to_vec(),
home: Some(PathBuf::from("/home/x")),
}
}
fn joins(bus: &str) -> zbus::blocking::Connection {
zbus::blocking::connection::Builder::address(bus)
.and_then(|builder| builder.name("org.freedesktop.systemd1"))
.and_then(|builder| builder.serve_at("/org/freedesktop/systemd1", plays()))
.and_then(zbus::blocking::connection::Builder::build)
.expect("the manager's stand-in on the test's bus")
}
fn in_a_session(runtime: &Path, bus: &str) -> Context {
let runtime = runtime.to_string_lossy().into_owned();
let env = crate::context::Environment::on(
crate::host::Os::Linux,
[
("HOME", "/home/x"),
("XDG_RUNTIME_DIR", runtime.as_str()),
("DBUS_SESSION_BUS_ADDRESS", bus),
],
);
Context::read(&env, "cli").with_test_bus(bus.to_owned())
}
struct Private {
done: Arc<std::sync::atomic::AtomicBool>,
serving: std::thread::JoinHandle<usize>,
}
impl Private {
fn serve(socket: &Path) -> Private {
std::fs::create_dir_all(socket.parent().expect("a folder")).expect("made");
let listener = std::os::unix::net::UnixListener::bind(socket).expect("listening");
listener.set_nonblocking(true).expect("polled");
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let stop = Arc::clone(&done);
let serving = std::thread::spawn(move || {
let mut taken = 0;
while !stop.load(std::sync::atomic::Ordering::SeqCst) {
match listener.accept() {
Ok((stream, _)) => {
taken += 1;
let _ = Private::answer(stream);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(e) => panic!("the private socket stopped listening: {e}"),
}
}
taken
});
Private { done, serving }
}
fn connections(self) -> usize {
self.done.store(true, std::sync::atomic::Ordering::SeqCst);
self.serving.join().expect("served")
}
fn answer(stream: std::os::unix::net::UnixStream) -> std::io::Result<()> {
use std::io::{BufRead, Read, Write};
stream.set_nonblocking(false)?;
let mut out = stream.try_clone()?;
let mut from = std::io::BufReader::new(stream);
from.read_exact(&mut [0; 1])?;
loop {
let mut line = String::new();
if from.read_line(&mut line)? == 0 {
return Ok(());
}
match line.split_whitespace().next() {
Some("AUTH") => out.write_all(b"OK 0123456789abcdef0123456789abcdef\r\n")?,
Some("NEGOTIATE_UNIX_FD") => out.write_all(b"AGREE_UNIX_FD\r\n")?,
Some("BEGIN") => break,
_ => out.write_all(b"ERROR\r\n")?,
}
}
let ctxt = zbus::zvariant::serialized::Context::new_dbus(zbus::zvariant::LE, 0);
let mut serial = 0;
loop {
let mut fixed = [0; 16];
if from.read_exact(&mut fixed).is_err() {
return Ok(());
}
assert_eq!(fixed[0], b'l', "zbus writes in this machine's order");
let at = |i: usize| {
u32::from_le_bytes([fixed[i], fixed[i + 1], fixed[i + 2], fixed[i + 3]])
};
let (body, asked, fields) = (at(4) as usize, at(8), at(12) as usize);
let mut rest = vec![0; (16 + fields).next_multiple_of(8) - 16 + body];
from.read_exact(&mut rest)?;
let property =
zbus::zvariant::serialized::Data::new(&rest[rest.len() - body..], ctxt)
.deserialize::<(String, String)>()
.map(|((_, property), _)| property)
.unwrap_or_default();
let value = match property.as_str() {
"UnitPath" => FOLDERS.to_vec(),
"Environment" => ENVIRONMENT.to_vec(),
_ => Vec::new(),
};
serial += 1;
out.write_all(&Private::reply(ctxt, serial, asked, value))?;
}
}
fn reply(
ctxt: zbus::zvariant::serialized::Context,
serial: u32,
asked: u32,
value: Vec<&str>,
) -> Vec<u8> {
use zbus::zvariant::{Signature, Value};
let body = zbus::zvariant::to_bytes(ctxt, &Value::from(value)).expect("a body");
let fields = vec![
(5_u8, Value::U32(asked)),
(7, Value::from("org.freedesktop.systemd1")),
(8, Value::Signature(Signature::Variant)),
];
let length = u32::try_from(body.len()).expect("a short body");
let header = (b'l', 2_u8, 1_u8, 1_u8, length, serial, fields);
let mut message = zbus::zvariant::to_bytes(ctxt, &header)
.expect("a header")
.to_vec();
message.resize(message.len().next_multiple_of(8), 0);
message.extend_from_slice(&body);
message
}
}
#[test]
fn the_user_manager_is_asked_on_the_session_bus_for_its_folders_and_home() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let runtime = scratch.path().join("runtime");
let private = Private::serve(&runtime.join("systemd/private"));
let bus = crate::secret_service_testing::SecretService::without_a_provider(
&scratch.path().join("bus"),
)
.unwrap_or_else(|missing| panic!("{missing}"));
let _manager = joins(bus.address());
let reads = asked(&in_a_session(&runtime, bus.address())).expect("answered");
assert_eq!(reads, as_played());
assert_eq!(
private.connections(),
0,
"the private socket is never asked"
);
}
#[test]
fn a_user_manager_that_joins_the_bus_late_is_waited_for() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let runtime = scratch.path().join("runtime");
let bus = crate::secret_service_testing::SecretService::without_a_provider(
&scratch.path().join("bus"),
)
.unwrap_or_else(|missing| panic!("{missing}"));
let ctx = in_a_session(&runtime, bus.address());
let refused = asked(&ctx).expect_err("nothing owns the name");
assert!(refused.contains("org.freedesktop.systemd1"), "{refused}");
let address = bus.address().to_owned();
let joining = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(500));
joins(&address)
});
assert_eq!(asked(&ctx).expect("answered once it joined"), as_played());
drop(joining.join().expect("joined"));
}
#[test]
fn the_systems_user_manager_is_never_asked_from_a_build_for_tests() {
let (_home, ctx) = scratch_home();
let refused = UserManager.reads(&ctx).expect_err("refused");
assert_eq!(refused.code(), "schedule_refused");
let systemd = Systemd::new(service::system(), Arc::new(UserManager));
for job in [Job::Renew, Job::Watch] {
let refused = systemd
.put(
&ctx,
Permit::for_a_test(),
job,
Path::new("/usr/local/bin/pitboard"),
&[],
&[],
)
.expect_err("refused");
assert!(refused.to_string().contains("user manager"), "{refused}");
}
assert!(!Systemd::units(&ctx).exists());
}
#[test]
fn a_watch_service_systemd_will_not_restart_is_taken_away_or_put_back() {
let (_home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let systemd = Systemd::new(asked.clone(), Arc::new(Pretend));
let program = Path::new("/usr/local/bin/pitboard");
let at = |percent: &str| vec!["--at".to_string(), percent.to_string()];
let reload = "--user daemon-reload".to_string();
let enable = format!("--user enable {WATCH}");
let restart = format!("--user restart {WATCH}");
asked.refuse("restart");
let refused = systemd
.put(
&ctx,
Permit::for_a_test(),
Job::Watch,
program,
&at("90"),
&[],
)
.expect_err("refused");
assert_eq!(refused.code(), "schedule_refused");
assert!(!systemd.installed(&ctx, Job::Watch));
assert_eq!(
asked.taken(),
[
reload.clone(),
enable.clone(),
restart.clone(),
format!("--user disable {WATCH}"),
reload.clone()
]
);
systemd
.put(
&ctx,
Permit::for_a_test(),
Job::Watch,
program,
&at("90"),
&[],
)
.expect("installed");
asked.taken();
asked.refuse("restart");
systemd
.put(
&ctx,
Permit::for_a_test(),
Job::Watch,
program,
&at("70"),
&[],
)
.expect_err("refused");
assert_eq!(systemd.options(&ctx, Job::Watch), at("90"));
assert_eq!(
asked.taken(),
[
reload.clone(),
enable.clone(),
restart.clone(),
reload,
enable,
restart
]
);
}
#[test]
fn a_watch_service_systemd_will_not_stop_stays_installed() {
let (_home, ctx) = scratch_home();
let asked = Arc::new(Asked::default());
let systemd = Systemd::new(asked.clone(), Arc::new(Pretend));
let program = Path::new("/usr/local/bin/pitboard");
for job in [Job::Renew, Job::Watch] {
systemd
.put(&ctx, Permit::for_a_test(), job, program, &[], &[])
.expect("installed");
}
asked.refuse("disable");
let refused = systemd
.remove(&ctx, Permit::for_a_test(), Job::Watch)
.expect_err("still running");
assert_eq!(refused.code(), "schedule_refused");
assert!(systemd.installed(&ctx, Job::Watch));
assert!(Systemd::units(&ctx).join(WATCH).is_file());
asked.refuse("disable");
assert!(
systemd
.remove(&ctx, Permit::for_a_test(), Job::Renew)
.expect("taken away")
);
assert!(!systemd.installed(&ctx, Job::Renew));
assert!(!Systemd::units(&ctx).join(SERVICE).exists());
}
#[test]
fn an_installed_unit_carries_the_proxy_and_only_its_owner_can_read_it() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let home = scratch.path().join("home");
let program = home.join("bin/pitboard");
std::fs::create_dir_all(program.parent().expect("its directory")).expect("made");
std::fs::write(&program, "").expect("a program");
let home_text = home.to_string_lossy().into_owned();
let env: crate::context::Environment = [
("HOME", home_text.as_str()),
("ALL_PROXY", "socks5h://alice:s3cret@127.0.0.1:1080"),
("no_proxy", "localhost"),
]
.into_iter()
.collect();
let ctx = Context::for_command_line(&env)
.with_memory_stores(MemoryHost::new())
.with_schedule_program(program.clone());
let units = Systemd::units(&ctx);
std::fs::create_dir_all(&units).expect("made");
std::fs::write(units.join(SERVICE), "a service open to others\n").expect("written");
std::fs::set_permissions(units.join(SERVICE), std::fs::Permissions::from_mode(0o644))
.expect("opened to others");
install(&ctx, Permit::for_a_test()).expect("installed");
let written = std::fs::read_to_string(units.join(SERVICE)).expect("the service");
assert!(
written.contains(
"Environment=ALL_PROXY=socks5h://alice:s3cret@127.0.0.1:1080\n\
Environment=no_proxy=localhost\n"
),
"{written}"
);
for file in [SERVICE, TIMER] {
assert_eq!(
crate::host::fs::access(&units.join(file)).map(|access| access.described),
Some("mode 600".to_string()),
"{file}"
);
}
assert_eq!(installed_program(&ctx), Some(program));
}
}