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