service_install/install/init/systemd/
disable_existing.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::{fs, io};

use itertools::Itertools;
use tracing::debug;

use crate::install::{InstallError, InstallStep, RollbackError, RollbackStep};
use crate::Tense;

use super::unit::{self, Unit};
use super::{system_path, user_path, FindExeError, Mode};

struct ReEnable {
    units: Vec<Unit>,
    mode: Mode,
}

impl RollbackStep for ReEnable {
    fn perform(&mut self) -> Result<(), RollbackError> {
        for unit in &self.units {
            super::enable(&unit.file_name, self.mode, true)?;
        }
        Ok(())
    }

    fn describe(&self, tense: Tense) -> String {
        let verb = match tense {
            Tense::Past => "Re-enabled",
            Tense::Active => "Re-enabling",
            Tense::Questioning => "Re-enable",
            Tense::Future => "Will re-enable",
        };
        format!(
            "{verb} the {} services that spawned the original file",
            self.mode
        )
    }
}

struct Disable {
    services: Vec<Unit>,
    timers: Vec<Unit>,
    mode: Mode,
}

impl InstallStep for Disable {
    fn describe(&self, tense: Tense) -> String {
        let verb = match tense {
            Tense::Past => "Disabled",
            Tense::Active => "Disabling",
            Tense::Questioning => "Disable",
            Tense::Future => "Will disable",
        };
        format!(
            "{verb} the {} services and/or timers running the file at the install location",
            self.mode
        )
    }

    fn describe_detailed(&self, tense: Tense) -> String {
        let verb = match tense {
            Tense::Past => "Disabled",
            Tense::Active => "Disabling",
            Tense::Questioning => "Disable",
            Tense::Future => "Will disable",
        };
        #[allow(clippy::format_collect)]
        let services: String = self
            .services
            .iter()
            .map(|unit| unit.file_name.to_string_lossy().to_string())
            .map(|unit| format!("\n|\t- {unit}"))
            .collect();
        #[allow(clippy::format_collect)]
        let timers: String = self
            .timers
            .iter()
            .map(|unit| unit.file_name.to_string_lossy().to_string())
            .map(|unit| format!("\n|\t- {unit}"))
            .collect();

        match (services.is_empty(), timers.is_empty()) {
            (false, false) => 
        format!(
            "{verb} the {} services and/or timers running the file at the install location\n| services:{services}\n| timers:{timers}",
            self.mode
        ) ,
            (false, true) => 
        format!(
            "{verb} the {} services running the file at the install location\n| services:{services}", self.mode),
            (true, false) => 
        format!(
            "{verb} the {} timers running the file at the install location\n| timers:{timers}",
            self.mode
        ),
            (true, true) => unreachable!("Would have triggered error while constructing the disable installstep.")
        }
    }

    fn perform(&mut self) -> Result<Option<Box<dyn RollbackStep>>, InstallError> {
        let mut rollback = Box::new(ReEnable {
            mode: self.mode,
            units: Vec::new(),
        });
        for unit in &self.services {
            super::disable(&unit.file_name, self.mode, true).map_err(super::Error::SystemCtl)?;
            rollback.units.push(unit.clone());
        }
        for unit in &self.timers {
            super::disable(&unit.file_name, self.mode, true).map_err(super::Error::SystemCtl)?;
            super::stop(&unit.name(), self.mode).map_err(super::Error::SystemCtl)?;
            rollback.units.push(unit.clone());
        }
        let rollback = rollback as Box<dyn RollbackStep>;
        Ok(Some(rollback))
    }
}

#[derive(Debug, thiserror::Error)]
pub enum DisableError {
    #[error("Could not find the service")]
    CouldNotFindIt(#[from] #[source] FindError),
    #[error("Could not open systemd unit")]
    CouldNotReadUnit(#[from] #[source] unit::Error),
    #[error("Could not find the service or (timer) that keeps the file in use")]
    NoServiceOrTimerFound,
}

pub(crate) fn disable_step(
    target: &Path,
    mode: Mode,
) -> Result<Vec<Box<dyn InstallStep>>, DisableError> {
    let path = match mode {
        Mode::User => user_path().unwrap(),
        Mode::System => system_path(),
    };
    let services: Vec<_> = collect_services(&path)
        .map_err(FindError::CouldNotReadDir)?
        .into_iter()
        .map(Unit::from_path)
        .collect::<Result<_, _>>()
        .map_err(DisableError::CouldNotReadUnit)?;
    let timers: Vec<_> = collect_timers(&path)
        .map_err(FindError::CouldNotReadDir)?
        .into_iter()
        .map(Unit::from_path)
        .collect::<Result<_, _>>()
        .map_err(DisableError::CouldNotReadUnit)?;

    let services = find_services_with_target_exe(services, target)?;
    let names: HashSet<_> = services.iter().map(Unit::name).collect();
    let mut timers: Vec<_> = timers
        .into_iter()
        .filter(|timer| names.contains(&timer.name()))
        .collect();
    timers.dedup_by_key(|u| u.name());
    timers.sort_by_key(Unit::name);

    let mut services: Vec<_> = services.into_iter().filter(Unit::has_install).collect();
    services.dedup_by_key(|u| u.name());
    services.sort_by_key(Unit::name);

    if services.is_empty() && timers.is_empty() {
        return Err(DisableError::NoServiceOrTimerFound);
    }
    let disable = Box::new(Disable {
        services,
        timers,
        mode,
    });
    let disable = disable as Box<dyn InstallStep>;
    Ok(vec![disable])
}

fn find_services_with_target_exe(units: Vec<Unit>, target: &Path) -> Result<Vec<Unit>, FindError> {
    let (units, errs): (Vec<_>, Vec<_>) = units
        .into_iter()
        .map(|unit| unit.exe_path().map(|exe| (exe, unit)))
        .filter_ok(|(exe, _)| exe == target)
        .map_ok(|(_, unit)| unit)
        .partition_result();

    if !errs.is_empty() {
        debug!("Some service files failed to parse: {errs:#?}")
    }

    Ok(units)
}

#[derive(Debug, thiserror::Error)]
pub enum FindError {
    #[error(
        "No service spawning the target file found, could not parse some services however: {0:#?}"
    )]
    NotFoundWithErrors(Vec<FindExeError>),
    #[error("Could not read directory")]
    CouldNotReadDir(#[from] #[source] std::io::Error),
}

fn walk_dir(dir: &Path, process_file: &mut impl FnMut(&Path)) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                walk_dir(&path, process_file)?;
            } else if path.is_file() {
                (process_file)(&path);
            }
        }
    }
    Ok(())
}
fn collect_services(dir: &Path) -> io::Result<Vec<PathBuf>> {
    let mut units = Vec::new();
    walk_dir(dir, &mut |path| {
        if path.extension().is_some_and(|e| e == "service") {
            units.push(path.to_owned());
        }
    })?;
    Ok(units)
}

fn collect_timers(dir: &Path) -> io::Result<Vec<PathBuf>> {
    let mut units = Vec::new();
    walk_dir(dir, &mut |path| {
        if path.extension().is_some_and(|e| e == "timer") {
            units.push(path.to_owned());
        }
    })?;
    Ok(units)
}