summaryrefslogtreecommitdiff
path: root/init/src/mounts/rescue.rs
blob: 2238297576c88fa0f362bc542d3b45d4d1c68cec (plain)
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
use crate::log::{log_success, log_warning};
use std::ffi::CString;
use std::fs::{create_dir, metadata};
use std::os::unix::fs::MetadataExt;

fn check_mount_point_permissions(path: &str) -> Result<(), Box<dyn std::error::Error>> {
    if !std::path::Path::new(path).exists() {
        create_dir(path)?;
    }

    let meta = metadata(path)?;

    if !meta.is_dir() {
        return Err(format!("Mount point {} is not a directory", path).into());
    }
    
    // TODO
    // let mode = meta.mode();
    
    let uid = meta.uid();
    if uid != 0 {
        log_warning(&format!("Warning: Mount point {} not owned by root", path));
    }

    Ok(())
}

pub fn mount_system() -> Result<(), Box<dyn std::error::Error>> {
    let mounts: &[(&str, &str, Option<&str>)] = &[
        ("/proc", "proc", None),
        ("/sys", "sysfs", None),
        ("/dev", "devtmpfs", Some("devtmpfs")),
        ("/tmp", "tmpfs", None),
        ("/run", "tmpfs", None),
    ];

    unsafe {
        for &(target, fstype, source) in mounts {
            if let Err(e) = check_mount_point_permissions(target) {
                log_warning(&format!("Permission check failed for {}: {}", target, e));
            }

            let target_c = CString::new(target)?;
            let fstype_c = CString::new(fstype)?;
            // let source_c = source.map(|s| CString::new(s).map_err(|e| ));
            let source_c = match source {
                Some(s) => match CString::new(s) {
                    Ok(c_string) => Some(c_string), 
                    Err(null_err) => {
                        log_warning(&format!("Source string contains NULL bytes (\\0), skipping: {}", null_err)); 
                        continue; 
                    } 
                }, 
                None => None
            }; 
                        

            let source_ptr = source_c.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());

            let ret = libc::syscall(
                libc::SYS_mount,
                source_ptr,
                target_c.as_ptr(),
                fstype_c.as_ptr(),
                0 as libc::c_ulong,
                std::ptr::null::<libc::c_void>(),
            );

            if ret != 0 {
                return Err(format!(
                    "Failed to mount {}: {}",
                    target,
                    std::io::Error::last_os_error()
                )
                .into());
            }
            log_success(&format!("Mounting {}...", target));
        }
    }

    Ok(())
}