sysd-manager-proxy 2.13.0

Simple lib used by sysd-manager to perform privileged operations via polkit over D-Bus.
Documentation
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use std::{
    collections::BTreeMap,
    env,
    error::Error,
    ffi::OsStr,
    path::{Path, PathBuf},
};

use base::{
    RunMode, args,
    consts::*,
    file::{commander, flatpak_host_file_path},
};

use tokio::{fs, process::Command};
use tracing::{debug, error, info, warn};

const SYSTEMD_DIR: &str = "/usr/share/dbus-1/system.d";
const ACTION_DIR: &str = "/usr/share/polkit-1/actions";
const SERVICE_DIR: &str = "/usr/lib/systemd/system";
const POLICY_FILE: &str = "io.github.plrigaux.SysDManager.policy";
const SERVICE_FILE: &str = "sysd-manager-proxy.service";
const DBUSCONF_FILE: &str = "io.github.plrigaux.SysDManager.conf";

pub async fn install(run_mode: RunMode) -> Result<(), Box<dyn Error>> {
    info!("Install proxy mode {:?}", run_mode);

    if run_mode == RunMode::Both {
        self::sub_install(RunMode::Development).await?;
        self::sub_install(RunMode::Normal).await?;
    } else {
        self::sub_install(run_mode).await?;
    }
    Ok(())
}

async fn sub_install(run_mode: RunMode) -> Result<(), Box<dyn Error>> {
    for (key, value) in std::env::vars() {
        println!("{}: {}", key, value);
    }

    if run_mode == RunMode::Both {
        error!("sub_install should not be called with RunMode::Both");
        return Err("Invalid RunMode::Both for sub_install".into());
    }
    let path = env::current_dir()?;
    info!("The current directory is {}", path.display());

    let mut normalized_path = PathBuf::new();
    for token in path.iter() {
        normalized_path.push(token);
        if token == "sysd-manager" {
            break;
        } else {
            debug!("{:?}", token)
        }
    }

    info!("The base directory is {}", normalized_path.display());

    let (interface, destination) = if run_mode == RunMode::Development {
        (DBUS_INTERFACE, DBUS_DESTINATION_DEV)
    } else {
        (DBUS_INTERFACE, DBUS_DESTINATION)
    };

    let mut base_path = normalized_path.join("sysd-manager-proxy");
    base_path.push("data");

    let mut map = BTreeMap::new();

    map.insert("BUS_NAME", run_mode.bus_name());
    map.insert("DESTINATION", destination);
    map.insert("INTERFACE", interface);
    map.insert("ENVIRONMENT", "");

    let exec = match run_mode {
        RunMode::Normal => {
            //  cmd = ["flatpak", "run", APP_ID]

            const BIN_DIR: &str = "/usr/bin";
            const BIN_NAME: &str = "sysd-manager-proxy";
            String::from_iter([BIN_DIR, "/", BIN_NAME])
        }
        RunMode::Development => {
            let exec = std::env::current_exe().expect("supposed to exist");
            let exec = exec.to_string_lossy();

            format!("{} -d", exec)
        }
        _ => {
            return Err("Invalid RunMode::Both for sub_install".into());
        }
    };

    let src = source_path(&base_path, DBUSCONF_FILE)?;
    let mut dst = PathBuf::from_iter(args!(
        flatpak_host_file_path(SYSTEMD_DIR),
        run_mode.bus_name()
    ));
    dst.add_extension("conf");

    let mut content = String::new();
    install_file(&src, &dst, false, &mut content).await?;
    install_edit_file(&map, dst, &mut content).await?;

    info!("Installing Polkit Policy");
    let src = source_path(&base_path, POLICY_FILE)?;
    let dst = flatpak_host_file_path(ACTION_DIR);
    install_file(&src, &dst, true, &mut content).await?;

    info!("Installing Service");

    let src = source_path(&base_path, SERVICE_FILE)?;
    let service_file_path = PathBuf::from_iter(args![
        flatpak_host_file_path(SERVICE_DIR),
        run_mode.proxy_service_name()
    ]);

    map.insert("EXECUTABLE", &exec);
    map.insert("SERVICE_ID", run_mode.proxy_service_id());
    install_file(&src, &service_file_path, false, &mut content).await?;
    install_edit_file(&map, service_file_path, &mut content).await?;

    let script_file = create_script(&content).await?;

    content.push_str("echo End of script");

    let output = commander(args!(sudo(), "sh", script_file), None)
        .output()
        .await?;

    ouput_to_screen(output);
    Ok(())
}

fn source_path(base_path: &Path, file_name: &str) -> Result<PathBuf, Box<dyn Error>> {
    let src_path = base_path.join(file_name);

    /*     #[cfg(feature = "flatpak")]
    {
        use base::file::inside_flatpak;

        let stream = gio::functions::resources_open_stream(
            &src_path.to_string_lossy(),
            ResourceLookupFlags::NONE,
        )?;

        let path = PathBuf::from(format!("XXXXXX{}", POLICY_FILE));
        let (file, ios_stream) = gio::File::new_tmp(Some(&path)).unwrap();

        let mut tmp_path = file.path().ok_or(Box::<dyn Error>::from("No file path"))?;
        info!("temp file path {:?}", tmp_path);

        let os_strem = ios_stream.output_stream();
        os_strem
            .splice(
                &stream,
                OutputStreamSpliceFlags::NONE,
                None::<&gio::Cancellable>,
            )
            .unwrap();

        /*         /run/user/1000/.flatpak/io.github.plrigaux.sysd-manager/tmp
        /run/user/USERID/.flatpak/FLATPAK_ID/tmp/ */

        if inside_flatpak()
            && let Ok(run_time_dir) = env::var("XDG_RUNTIME_DIR")
            && let Ok(flatpak_id) = env::var("FLATPAK_ID")
        {
            tmp_path = PathBuf::from_iter(args![
                run_time_dir,
                ".flatpak",
                flatpak_id,
                tmp_path.strip_prefix("/").expect("tmp_path not empty")
            ]);
            debug!("flatpack tmp dir {}", tmp_path.display());
        }

        Ok(tmp_path)
    } */

    Ok(src_path)
}

async fn install_edit_file(
    map: &BTreeMap<&str, &str>,
    dst: PathBuf,
    content: &mut String,
) -> Result<(), Box<dyn Error + 'static>> {
    info!("Edit file -- {}", dst.display());

    let mut s = vec!["sed".to_string(), "-i".to_string()];

    //let mut command = commander(args!(sudo(), "sed", "-i"), None);

    for (k, v) in map {
        s.push("-e".to_string());
        s.push(format!(
            "s/{{{k}}}/{}/",
            v.replace("/", r"\\/").replace(" ", r"\ ")
        ));
        // command.args(args!("-e", );
    }
    s.push(dst.to_string_lossy().to_string());

    //command.arg(dst);

    content.push_str(&s.join(" "));
    content.push('\n');
    /*  let output = command.output().await?;

    ouput_to_screen(output); */
    Ok(())
}

async fn install_file(
    src: &Path,
    dst: &Path,
    dst_is_dir: bool,
    content: &mut String,
) -> Result<(), Box<dyn Error + 'static>> {
    install_file_mode(src, dst, dst_is_dir, "644", content).await
}

fn sudo() -> &'static str {
    "sudo"
}

async fn install_file_mode(
    src: &Path,
    dst: &Path,
    dst_is_dir: bool,
    mode: &str,
    //  map: Option<&BTreeMap<&str, &str>>,
    content: &mut String,
) -> Result<(), Box<dyn Error + 'static>> {
    info!(
        "Installing {} --> {} with mode {}",
        src.display(),
        dst.display(),
        mode
    );

    let dir_arg = if dst_is_dir { "-t" } else { "-T" };

    /*     let mut command = commander(
           args!(
               sudo(),
               "install",
               format!("-vDm{}", mode),
               src,
               dir_arg,
               dst
           ),
           None,
       );
    */
    let s = [
        //     sudo(),
        "install",
        &format!("-vDm{}", mode),
        &src.to_string_lossy(),
        dir_arg,
        &dst.to_string_lossy(),
    ]
    .join(" ");

    content.push_str(&s);
    content.push('\n');

    /*     if let Some(map) = map {
        command.args(["&&", "sed", "-i"]);
        for (k, v) in map {
            command.args(args!("-e", format!("s/{{{k}}}/{}/", v.replace("/", r"\/"))));
        }
        command.arg(dst);
    }

    let output = command.output().await?;
    ouput_to_screen(output); */
    Ok(())
}

enum Pattern {
    Equals(String),
    Start(String),
}

struct Clean {
    dir: String,
    patterns: Vec<Pattern>,
}

pub async fn clean(_run_mode: RunMode) -> Result<(), Box<dyn Error>> {
    info!("Clean proxy files");

    let mut to_clean = Vec::new();
    let clean = Clean {
        dir: SYSTEMD_DIR.to_string(),
        patterns: vec![Pattern::Start("io.github.plrigaux.SysDM".to_string())],
    };

    to_clean.push(clean);

    let clean = Clean {
        dir: ACTION_DIR.to_string(),
        patterns: vec![Pattern::Equals(
            "io.github.plrigaux.SysDManager.policy".to_string(),
        )],
    };

    to_clean.push(clean);

    let clean = Clean {
        dir: SERVICE_DIR.to_string(),
        patterns: vec![Pattern::Start("sysd-manager-proxy".to_string())],
    };
    to_clean.push(clean);

    let mut paths_to_clean = Vec::new();
    //TODO: use run_mode to clean only relevant files
    for clean in to_clean {
        let mut entries = fs::read_dir(clean.dir).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();

            for pattern in &clean.patterns {
                match pattern {
                    Pattern::Equals(s) => {
                        if let Some(file_name) = path.file_name() {
                            let fname = file_name.to_string_lossy();
                            if fname == *s {
                                paths_to_clean.push(path.clone());
                            }
                        }
                    }
                    Pattern::Start(s) => {
                        if let Some(file_name) = path.file_name() {
                            let fname = file_name.to_string_lossy();
                            if fname.starts_with(s) {
                                paths_to_clean.push(path.clone());
                            }
                        }
                    }
                }
            }
        }
    }

    info!("{} file to clean", paths_to_clean.len());
    for path in paths_to_clean {
        let output = Command::new("sudo")
            .arg("rm")
            .arg("-v")
            .arg(path)
            .output()
            .await?;

        ouput_to_screen(output);
    }
    Ok(())
}

use tokio::io::AsyncWriteExt;
async fn create_script(content: &str) -> Result<PathBuf, std::io::Error> {
    let mut file_path = env::temp_dir();

    file_path.push("sysd-manager-install.sh");

    let mut file = fs::OpenOptions::new()
        .write(true)
        .truncate(true)
        .create(true)
        .open(&file_path)
        .await?;

    file.write_all(b"#!/bin/bash\n\n").await?;

    file.write_all(content.as_bytes()).await?;

    info!("Script created to {}", file_path.display());

    Ok(file_path)
}

fn ouput_to_screen(output: std::process::Output) {
    if output.status.success() {
        for l in String::from_utf8_lossy(&output.stdout).lines() {
            info!("{l}");
        }
    } else {
        warn!("Exit code {:?}", output.status.code());
        for line in String::from_utf8_lossy(&output.stderr).lines() {
            warn!("{line}");
        }
    }
}

#[cfg(test)]
mod test {

    #[test]
    fn test_string() {
        let k = "A";
        let v = "B";
        let x = format!(r#"s/{{{k}}}/{}/"#, v.replace("/", r"\/"));

        assert_eq!(x, "s/{A}/B/")
    }
}