Skip to main content

sysd_manager_base/
file.rs

1use std::ffi::{OsStr, OsString};
2use std::path::Component;
3use std::process::Stdio;
4use std::{
5    error::Error,
6    io,
7    path::{Path, PathBuf},
8    sync::OnceLock,
9};
10use tokio::fs;
11use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
12use tokio::process::Command;
13
14use tokio::task::JoinError;
15use tracing::debug;
16#[allow(unused_imports)]
17use tracing::{error, info, warn};
18
19use crate::getuid;
20
21#[macro_export]
22macro_rules! args {
23    ($($a:expr),*) => {
24        [
25            $(AsRef::<OsStr>::as_ref(&$a),)*
26        ]
27    }
28}
29
30#[macro_export]
31macro_rules! vs {
32    ($($a:expr),*) => {
33        [
34            $(AsRef::<String>::as_ref(&$a),)*
35        ]
36    }
37}
38
39#[derive(Debug)]
40pub enum SysdBaseError {
41    CmdNoFreedesktopFlatpakPermission,
42    CommandCallError(
43        OsString,
44        Vec<OsString>,
45        Vec<(OsString, Option<OsString>)>,
46        io::Error,
47    ),
48    Custom(String),
49    IoError(io::Error),
50    NotAuthorizedAuthentificationDismissed,
51    NotAuthorized,
52    Tokio(JoinError),
53    InvalidPath(String),
54}
55
56impl SysdBaseError {
57    pub(crate) fn create_command_error(command: &Command, error: std::io::Error) -> Self {
58        let std_command = command.as_std();
59        let program = std_command.get_program().to_os_string();
60        let envs: Vec<(OsString, Option<OsString>)> = std_command
61            .get_envs()
62            .map(|(k, v)| (k.to_os_string(), v.map(|s| s.to_os_string())))
63            .collect();
64        let arg: Vec<OsString> = std_command.get_args().map(|s| s.to_os_string()).collect();
65
66        SysdBaseError::CommandCallError(program, arg, envs, error)
67    }
68}
69
70impl From<&str> for SysdBaseError {
71    fn from(value: &str) -> Self {
72        value.to_string().into()
73    }
74}
75
76impl From<String> for SysdBaseError {
77    fn from(value: String) -> Self {
78        SysdBaseError::Custom(value)
79    }
80}
81
82impl From<std::io::Error> for SysdBaseError {
83    fn from(value: std::io::Error) -> Self {
84        SysdBaseError::IoError(value)
85    }
86}
87
88impl From<JoinError> for SysdBaseError {
89    fn from(value: JoinError) -> Self {
90        SysdBaseError::Tokio(value)
91    }
92}
93
94pub fn determine_drop_in_path_dir(
95    unit_name: &str,
96    runtime: bool,
97    user_session: bool,
98) -> Result<String, Box<dyn Error + 'static>> {
99    let path = match (runtime, user_session) {
100        (true, false) => format!("/run/systemd/system/{}.d", unit_name),
101        (false, false) => format!("/etc/systemd/system/{}.d", unit_name),
102        (true, true) => {
103            let runtime_dir = std::env::var("XDG_RUNTIME_DIR")
104                .unwrap_or_else(|_| format!("/run/user/{}", getuid()));
105
106            format!("{runtime_dir}/systemd/user/{}.d", unit_name)
107        }
108        (false, true) => {
109            let home_dir = std::env::home_dir().ok_or(Box::<dyn Error>::from(
110                "No HOME found to create drop-in".to_string(),
111            ))?;
112            format!(
113                "{}/.config/systemd/user/{}.d",
114                home_dir.display(),
115                unit_name
116            )
117        }
118    };
119    Ok(path)
120}
121
122pub fn determine_unit_file_path_dir(
123    runtime: bool,
124    user_session: bool,
125) -> Result<PathBuf, Box<dyn Error + 'static>> {
126    let path = match (runtime, user_session) {
127        (true, false) => PathBuf::from("/run/systemd/system/"),
128        (false, false) => PathBuf::from("/etc/systemd/system/"),
129        (true, true) => {
130            let runtime_dir = std::env::var("XDG_RUNTIME_DIR")
131                .unwrap_or_else(|_| format!("/run/user/{}", getuid()));
132            let path = PathBuf::from(runtime_dir);
133
134            path.join("systemd/user/")
135        }
136        (false, true) => std::env::home_dir()
137            .unwrap_or_else(|| {
138                error!("Nome directory found!");
139                PathBuf::default()
140            })
141            .join(".config")
142            .join("systemd/user"),
143    };
144    Ok(path)
145}
146
147pub fn create_drop_in_path_file(
148    unit_name: &str,
149    runtime: bool,
150    user_session: bool,
151    file_name: &str,
152) -> Result<String, Box<dyn Error + 'static>> {
153    let path_dir = determine_drop_in_path_dir(unit_name, runtime, user_session)?;
154
155    let path = format!("{path_dir}/{file_name}.conf");
156
157    info!(
158        "Creating drop-in path for unit: {}, runtime: {}, user: {} -> path {}",
159        unit_name, runtime, user_session, path
160    );
161    Ok(path)
162}
163
164pub async fn create_drop_in_io(
165    file_path_str: &str,
166    content: &str,
167    user_session: bool,
168) -> Result<(), SysdBaseError> {
169    //FIXME add security
170    if file_path_str.contains("../") {
171        let err = std::io::Error::new(
172            std::io::ErrorKind::InvalidData,
173            r#"The "../" pattern is not supported""#,
174        );
175
176        return Err(err)?;
177    }
178
179    let file_path = PathBuf::from(file_path_str);
180
181    if file_path.components().any(|c| c == Component::ParentDir) {
182        let err = std::io::Error::new(
183            std::io::ErrorKind::InvalidData,
184            r#"The "../" pattern is not supported for file path"#,
185        );
186
187        return Err(err)?;
188    }
189
190    path_safe_guard(user_session, file_path_str)?;
191
192    let unit_drop_in_dir = file_path.parent().ok_or(std::io::Error::new(
193        std::io::ErrorKind::InvalidData,
194        format!("Parent dir of file {:?} is invalid", file_path_str),
195    ))?;
196
197    if !unit_drop_in_dir.exists() {
198        info!("Creating dir {}", unit_drop_in_dir.display());
199        match fs::create_dir_all(&unit_drop_in_dir).await {
200            Ok(_) => {}
201            Err(err) => {
202                if err.kind() == std::io::ErrorKind::PermissionDenied && getuid() != 0 {
203                    create_dir_all_with_priviledge(unit_drop_in_dir).await
204                } else {
205                    Err(err)?
206                }?
207            }
208        }
209    }
210
211    //Save content
212    info!("Creating file {}", file_path.display());
213    let bytes_written = write_on_disk(&file_path, true, content).await?;
214
215    info!(
216        "{bytes_written} bytes writen on File {}",
217        file_path.to_string_lossy()
218    );
219    Ok(())
220}
221
222pub fn path_safe_guard(user_session: bool, file_path_str: &str) -> Result<(), SysdBaseError> {
223    if file_path_str.contains("../") {
224        let err = SysdBaseError::InvalidPath(format!(
225            r#"The file path "{}" not absoluated"#,
226            file_path_str,
227        ));
228
229        return Err(err);
230    }
231
232    if !user_session {
233        let safe_loctions = [
234            "/usr/lib/systemd/system/",
235            "/lib/systemd/system/",
236            "/etc/systemd/system/",
237            "/run/systemd/system/",
238        ];
239
240        if !safe_loctions
241            .iter()
242            .any(|loc| file_path_str.starts_with(loc))
243        {
244            let err = SysdBaseError::InvalidPath(format!(
245                r#"The file "{}" not located in any of: {}"#,
246                file_path_str,
247                safe_loctions.join(" ")
248            ));
249
250            return Err(err);
251        }
252    }
253
254    info!("Valid path");
255
256    Ok(())
257}
258
259pub async fn write_on_disk(
260    //  user_session: bool,
261    file_path: &Path,
262    create_file: bool,
263    content: &str,
264) -> Result<u64, SysdBaseError> {
265    //safe_guard(&file_path.to_string_lossy(), user_session)?;
266    let bytes_written = match save_io(file_path, create_file, content).await {
267        Ok(b) => b,
268        Err(err) => {
269            if err.kind() == std::io::ErrorKind::PermissionDenied && getuid() != 0 {
270                write_with_priviledge(file_path, content).await
271            } else {
272                Err(err)?
273            }?
274        }
275    };
276    Ok(bytes_written)
277}
278
279async fn create_dir_all_with_priviledge(dir_path: &Path) -> Result<(), SysdBaseError> {
280    let prog_n_args = args!["pkexec", "mkdir", "-p", dir_path];
281    execute_command(None, &prog_n_args).await?;
282    Ok(())
283}
284
285pub async fn write_with_priviledge(file_path: &Path, text: &str) -> Result<u64, SysdBaseError> {
286    let prog_n_args = args!["pkexec", "tee", file_path];
287    let input = text.as_bytes();
288    execute_command(Some(input), &prog_n_args).await?;
289    Ok(input.len() as u64)
290}
291
292pub async fn execute_command(
293    input: Option<&[u8]>,
294    prog_n_args: &[&OsStr],
295) -> Result<(), SysdBaseError> {
296    let mut cmd = commander(prog_n_args, None);
297
298    let mut child = cmd
299        .stdin(Stdio::piped())
300        .stdout(Stdio::piped())
301        .stderr(Stdio::piped())
302        .spawn()
303        .map_err(|error: std::io::Error| SysdBaseError::create_command_error(&cmd, error))?;
304
305    let stdout = child
306        .stdout
307        .take()
308        .ok_or("Child did not have a handle to stdout")?;
309    //.expect("child did not have a handle to stdout");
310
311    let stderr = child
312        .stderr
313        .take()
314        .ok_or("Child did not have a handle to stderr")?;
315
316    if let Some(input) = input {
317        let mut child_stdin = child
318            .stdin
319            .take()
320            .ok_or("Unable to pass stdin to command")?;
321        child_stdin.write_all(input).await?;
322        drop(child_stdin);
323    }
324
325    let handle = tokio::spawn(async move {
326        let exit_status = child.wait().await?;
327        if exit_status.success() {
328            info!("Script executed with success");
329            return Ok(());
330        }
331
332        let code = exit_status
333            .code()
334            .inspect(|code| warn!("Subprocess exit code: {code:?}"))
335            .ok_or("Subprocess exit code: None")?;
336
337        let err = match code {
338            1 => {
339                #[cfg(feature = "flatpak")]
340                {
341                    SysdBaseError::CmdNoFreedesktopFlatpakPermission
342                }
343                #[cfg(not(feature = "flatpak"))]
344                {
345                    Err(format!("Subprocess exit code: {code}"))?
346                }
347            }
348            126 => SysdBaseError::NotAuthorized,
349            127 => SysdBaseError::NotAuthorizedAuthentificationDismissed,
350            _ => Err(format!("Subprocess exit code: {code}"))?,
351        };
352        Err(err)
353    });
354
355    let mut reader_out = BufReader::new(stdout).lines();
356    let mut reader_err = BufReader::new(stderr).lines();
357    debug!("Going to read out");
358
359    while let Some(line) = reader_out.next_line().await? {
360        debug!("Script line: {}", line);
361    }
362
363    debug!("Going to read err");
364
365    while let Some(line) = reader_err.next_line().await? {
366        error!("Script line: {}", line);
367    }
368
369    debug!("Going to wait");
370
371    handle.await?
372}
373
374pub async fn save_io(
375    file_path: impl AsRef<Path>,
376    create: bool,
377    content: &str,
378) -> Result<u64, std::io::Error> {
379    if create
380        && let Some(dir_path) = file_path.as_ref().parent()
381        && !dir_path.exists()
382        && let Err(err) = fs::create_dir_all(dir_path).await
383    {
384        error!("Can't create path {}, {err:?}", dir_path.display());
385    }
386
387    let mut file = fs::OpenOptions::new()
388        .write(true)
389        .truncate(true)
390        .create(create)
391        .open(file_path)
392        .await?;
393
394    let test_bytes = content.as_bytes();
395
396    file.write_all(test_bytes).await?;
397    file.flush().await?;
398
399    let bytes_written = test_bytes.len();
400
401    Ok(bytes_written as u64)
402}
403
404pub const FLATPAK_SPAWN: &str = "flatpak-spawn";
405
406pub static INSIDE_FLATPAK: OnceLock<bool> = OnceLock::new();
407
408#[macro_export]
409macro_rules! inside_flatpak {
410    () => {
411        *INSIDE_FLATPAK.get_or_init(|| {
412            #[cfg(not(feature = "flatpak"))]
413            warn!("Not supposed to be called");
414
415            let in_flatpak = std::env::var("FLATPAK_ID").is_ok();
416
417            #[cfg(feature = "flatpak")]
418            if !in_flatpak {
419                warn!("Your run the flatpak compilation, but you aren't running inside a Flatpak");
420            }
421
422            in_flatpak
423        })
424    };
425}
426
427pub fn inside_flatpak() -> bool {
428    inside_flatpak!()
429}
430
431/*     pub fn args<I, S>(&mut self, args: I) -> &mut Command
432where
433    I: IntoIterator<Item = S>,
434    S: AsRef<OsStr>, */
435
436#[cfg(feature = "flatpak")]
437pub fn commander<I, S>(prog_n_args: I, environment_variables: Option<&[(&str, &str)]>) -> Command
438where
439    I: IntoIterator<Item = S>,
440    S: AsRef<OsStr>,
441{
442    if !inside_flatpak!() {
443        error!("Command call might not work because you are not running inside a Flatpak")
444    }
445
446    let mut cmd = Command::new(FLATPAK_SPAWN);
447    cmd.arg("--host");
448    cmd.args(prog_n_args);
449
450    if let Some(envs) = environment_variables {
451        for env in envs {
452            cmd.arg(format!("--env={}={}", env.0, env.1));
453        }
454    }
455
456    cmd
457}
458
459#[cfg(not(feature = "flatpak"))]
460pub fn commander<I, S>(prog_n_args: I, environment_variables: Option<&[(&str, &str)]>) -> Command
461where
462    I: IntoIterator<Item = S>,
463    S: AsRef<OsStr>,
464{
465    let mut it = prog_n_args.into_iter();
466    let mut cmd = Command::new(it.next().unwrap());
467
468    for arg in it {
469        cmd.arg(arg);
470    }
471
472    if let Some(envs) = environment_variables {
473        for env in envs {
474            cmd.env(env.0, env.1);
475        }
476    }
477
478    cmd
479}
480
481pub fn commander_blocking<I, S>(
482    prog_n_args: I,
483    environment_variables: Option<&[(&str, &str)]>,
484) -> std::process::Command
485where
486    I: IntoIterator<Item = S>,
487    S: AsRef<OsStr>,
488{
489    commander(prog_n_args, environment_variables).into_std()
490}
491
492pub fn test_flatpak_spawn() -> Result<(), io::Error> {
493    #[cfg(feature = "flatpak")]
494    {
495        info!("test_flatpak_spawn");
496        std::process::Command::new(FLATPAK_SPAWN)
497            .arg("--help")
498            .output()
499            .map(|_o| ())
500    }
501
502    #[cfg(not(feature = "flatpak"))]
503    Ok(())
504}
505
506/// To be able to acces the Flatpack mounted files.
507/// Limit to /usr for the least access principle
508pub fn flatpak_host_file_path(file_path: &str) -> PathBuf {
509    #[cfg(feature = "flatpak")]
510    {
511        if inside_flatpak!() && (file_path.starts_with("/usr") || file_path.starts_with("/etc")) {
512            let file_path = file_path.strip_prefix('/').unwrap_or(file_path);
513            PathBuf::from_iter(["/run/host", file_path])
514        } else {
515            PathBuf::from(&file_path)
516        }
517    }
518
519    #[cfg(not(feature = "flatpak"))]
520    PathBuf::from(file_path)
521}
522
523#[cfg(test)]
524mod test {
525    use super::*;
526    use test_base::init_logs;
527
528    pub fn flatpak_host_file_path_t(file_path: &str) -> PathBuf {
529        let file_path = if let Some(stripped) = file_path.strip_prefix('/') {
530            stripped
531        } else {
532            file_path
533        };
534        PathBuf::from_iter(["/run/host", file_path])
535    }
536
537    pub fn flatpak_host_file_path_t2(file_path: &str) -> PathBuf {
538        PathBuf::from("/run/host").join(file_path)
539    }
540
541    #[test]
542    fn test_fp() {
543        init_logs();
544
545        let src = PathBuf::from("/tmp");
546        let a = flatpak_host_file_path(&src.to_string_lossy());
547        warn!("{} exists {}", a.display(), a.exists());
548        warn!("{} exists {}", src.display(), src.exists());
549    }
550
551    #[test]
552    fn test_fp2() {
553        init_logs();
554
555        let src = PathBuf::from("/tmp");
556        let a = flatpak_host_file_path_t(&src.to_string_lossy());
557        warn!("{} exists {}", a.display(), a.exists());
558        warn!("{} exists {}", src.display(), src.exists());
559
560        let b = flatpak_host_file_path_t("test");
561        warn!("{} exists {}", b.display(), b.exists());
562
563        let b = flatpak_host_file_path_t("/test");
564        warn!("{} exists {}", b.display(), b.exists());
565
566        let b = flatpak_host_file_path_t2("/test");
567        warn!("{} exists {}", b.display(), b.exists());
568    }
569}