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 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 return 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 return 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 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 file_path: &Path,
263 create_file: bool,
264 content: &str,
265) -> Result<u64, SysdBaseError> {
266 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
280async fn create_dir_all_with_priviledge(dir_path: &Path) -> Result<(), SysdBaseError> {
281 let prog_n_args = args!["pkexec", "mkdir", "-p", dir_path];
282 execute_command(None, &prog_n_args).await?;
283 Ok(())
284}
285
286pub async fn write_with_priviledge(file_path: &Path, text: &str) -> Result<u64, SysdBaseError> {
287 let prog_n_args = args!["pkexec", "tee", file_path];
288 let input = text.as_bytes();
289 execute_command(Some(input), &prog_n_args).await?;
290 Ok(input.len() as u64)
291}
292
293pub async fn execute_command(
294 input: Option<&[u8]>,
295 prog_n_args: &[&OsStr],
296) -> Result<(), SysdBaseError> {
297 let mut cmd = commander(prog_n_args, None);
298
299 let mut child = cmd
300 .stdin(Stdio::piped())
301 .stdout(Stdio::piped())
302 .stderr(Stdio::piped())
303 .spawn()
304 .map_err(|error: std::io::Error| SysdBaseError::create_command_error(&cmd, error))?;
305
306 let stdout = child
307 .stdout
308 .take()
309 .ok_or("Child did not have a handle to stdout")?;
310 let stderr = child
313 .stderr
314 .take()
315 .ok_or("Child did not have a handle to stderr")?;
316
317 if let Some(input) = input {
318 let mut child_stdin = child
319 .stdin
320 .take()
321 .ok_or("Unable to pass stdin to command")?;
322 child_stdin.write_all(input).await?;
323 drop(child_stdin);
324 }
325
326 let handle = tokio::spawn(async move {
327 let exit_status = child.wait().await?;
328 if exit_status.success() {
329 info!("Script executed with success");
330 return Ok(());
331 }
332
333 let code = exit_status
334 .code()
335 .inspect(|code| warn!("Subprocess exit code: {code:?}"))
336 .ok_or("Subprocess exit code: None")?;
337
338 let err = match code {
339 1 => {
340 #[cfg(feature = "flatpak")]
341 {
342 SysdBaseError::CmdNoFreedesktopFlatpakPermission
343 }
344 #[cfg(not(feature = "flatpak"))]
345 {
346 Err(format!("Subprocess exit code: {code}"))?
347 }
348 }
349 126 => SysdBaseError::NotAuthorized,
350 127 => SysdBaseError::NotAuthorizedAuthentificationDismissed,
351 _ => Err(format!("Subprocess exit code: {code}"))?,
352 };
353 Err(err)
354 });
355
356 let mut reader_out = BufReader::new(stdout).lines();
357 let mut reader_err = BufReader::new(stderr).lines();
358 debug!("Going to read out");
359
360 while let Some(line) = reader_out.next_line().await? {
361 debug!("Script line: {}", line);
362 }
363
364 debug!("Going to read err");
365
366 while let Some(line) = reader_err.next_line().await? {
367 error!("Script line: {}", line);
368 }
369
370 debug!("Going to wait");
371
372 handle.await?
373}
374
375pub async fn save_io(
376 file_path: impl AsRef<Path>,
377 create: bool,
378 content: &str,
379) -> Result<u64, std::io::Error> {
380 if create
381 && let Some(dir_path) = file_path.as_ref().parent()
382 && !dir_path.exists()
383 && let Err(err) = fs::create_dir_all(dir_path).await
384 {
385 error!("Can't create path {}, {err:?}", dir_path.display());
386 }
387
388 let mut file = fs::OpenOptions::new()
389 .write(true)
390 .truncate(true)
391 .create(create)
392 .open(file_path)
393 .await?;
394
395 let test_bytes = content.as_bytes();
396
397 file.write_all(test_bytes).await?;
398 file.flush().await?;
399
400 let bytes_written = test_bytes.len();
401
402 Ok(bytes_written as u64)
403}
404
405pub const FLATPAK_SPAWN: &str = "flatpak-spawn";
406
407pub static INSIDE_FLATPAK: OnceLock<bool> = OnceLock::new();
408
409#[macro_export]
410macro_rules! inside_flatpak {
411 () => {
412 *INSIDE_FLATPAK.get_or_init(|| {
413 #[cfg(not(feature = "flatpak"))]
414 warn!("Not supposed to be called");
415
416 let in_flatpak = std::env::var("FLATPAK_ID").is_ok();
417
418 #[cfg(feature = "flatpak")]
419 if !in_flatpak {
420 warn!("Your run the flatpak compilation, but you aren't running inside a Flatpak");
421 }
422
423 in_flatpak
424 })
425 };
426}
427
428pub fn inside_flatpak() -> bool {
429 inside_flatpak!()
430}
431
432#[cfg(feature = "flatpak")]
438pub fn commander<I, S>(prog_n_args: I, environment_variables: Option<&[(&str, &str)]>) -> Command
439where
440 I: IntoIterator<Item = S>,
441 S: AsRef<OsStr>,
442{
443 if !inside_flatpak!() {
444 error!("Command call might not work because you are not running inside a Flatpak")
445 }
446
447 let mut cmd = Command::new(FLATPAK_SPAWN);
448 cmd.arg("--host");
449 cmd.args(prog_n_args);
450
451 if let Some(envs) = environment_variables {
452 for env in envs {
453 cmd.arg(format!("--env={}={}", env.0, env.1));
454 }
455 }
456
457 cmd
458}
459
460#[cfg(not(feature = "flatpak"))]
461pub fn commander<I, S>(prog_n_args: I, environment_variables: Option<&[(&str, &str)]>) -> Command
462where
463 I: IntoIterator<Item = S>,
464 S: AsRef<OsStr>,
465{
466 let mut it = prog_n_args.into_iter();
467 let mut cmd = Command::new(it.next().unwrap());
468
469 for arg in it {
470 cmd.arg(arg);
471 }
472
473 if let Some(envs) = environment_variables {
474 for env in envs {
475 cmd.env(env.0, env.1);
476 }
477 }
478
479 cmd
480}
481
482pub fn commander_blocking<I, S>(
483 prog_n_args: I,
484 environment_variables: Option<&[(&str, &str)]>,
485) -> std::process::Command
486where
487 I: IntoIterator<Item = S>,
488 S: AsRef<OsStr>,
489{
490 commander(prog_n_args, environment_variables).into_std()
491}
492
493pub fn test_flatpak_spawn() -> Result<(), io::Error> {
494 #[cfg(feature = "flatpak")]
495 {
496 info!("test_flatpak_spawn");
497 std::process::Command::new(FLATPAK_SPAWN)
498 .arg("--help")
499 .output()
500 .map(|_o| ())
501 }
502
503 #[cfg(not(feature = "flatpak"))]
504 Ok(())
505}
506
507pub fn flatpak_host_file_path(file_path: &str) -> PathBuf {
510 #[cfg(feature = "flatpak")]
511 {
512 if inside_flatpak!() && (file_path.starts_with("/usr") || file_path.starts_with("/etc")) {
513 let file_path = file_path.strip_prefix('/').unwrap_or(file_path);
514 PathBuf::from_iter(["/run/host", file_path])
515 } else {
516 PathBuf::from(&file_path)
517 }
518 }
519
520 #[cfg(not(feature = "flatpak"))]
521 PathBuf::from(file_path)
522}
523
524#[cfg(test)]
525mod test {
526 use super::*;
527 use test_base::init_logs;
528
529 pub fn flatpak_host_file_path_t(file_path: &str) -> PathBuf {
530 let file_path = if let Some(stripped) = file_path.strip_prefix('/') {
531 stripped
532 } else {
533 file_path
534 };
535 PathBuf::from_iter(["/run/host", file_path])
536 }
537
538 pub fn flatpak_host_file_path_t2(file_path: &str) -> PathBuf {
539 PathBuf::from("/run/host").join(file_path)
540 }
541
542 #[test]
543 fn test_fp() {
544 init_logs();
545
546 let src = PathBuf::from("/tmp");
547 let a = flatpak_host_file_path(&src.to_string_lossy());
548 warn!("{} exists {}", a.display(), a.exists());
549 warn!("{} exists {}", src.display(), src.exists());
550 }
551
552 #[test]
553 fn test_fp2() {
554 init_logs();
555
556 let src = PathBuf::from("/tmp");
557 let a = flatpak_host_file_path_t(&src.to_string_lossy());
558 warn!("{} exists {}", a.display(), a.exists());
559 warn!("{} exists {}", src.display(), src.exists());
560
561 let b = flatpak_host_file_path_t("test");
562 warn!("{} exists {}", b.display(), b.exists());
563
564 let b = flatpak_host_file_path_t("/test");
565 warn!("{} exists {}", b.display(), b.exists());
566
567 let b = flatpak_host_file_path_t2("/test");
568 warn!("{} exists {}", b.display(), b.exists());
569 }
570}