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
// Copyright (C) 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use color_eyre::Result;
use sn_releases::ReleaseType;
use std::path::{Path, PathBuf};

#[cfg(unix)]
pub fn get_node_manager_path() -> Result<PathBuf> {
    // This needs to be a system-wide location rather than a user directory because the `install`
    // command will run as the root user. However, it should be readable by non-root users, because
    // other commands, e.g., requesting status, shouldn't require root.
    use std::os::unix::fs::PermissionsExt;

    let path = Path::new("/var/safenode-manager/");
    if is_running_as_root() && !path.exists() {
        std::fs::create_dir_all(path)?;
        let mut perm = std::fs::metadata(path)?.permissions();
        perm.set_mode(0o755); // set permissions to rwxr-xr-x
        std::fs::set_permissions(path, perm)?;
    }

    Ok(path.to_path_buf())
}

#[cfg(unix)]
pub fn get_node_registry_path() -> Result<PathBuf> {
    use std::os::unix::fs::PermissionsExt;

    let path = get_node_manager_path()?;
    let node_registry_path = path.join("node_registry.json");
    if is_running_as_root() && !node_registry_path.exists() {
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true) // Do not append to the file if it already exists.
            .open(node_registry_path.clone())?;
        // Set the permissions of /var/safenode-manager/node_registry.json to rwxrwxrwx. The
        // `status` command updates the registry with the latest information it has on the
        // services at the time it runs. It's normally the case that service management status
        // operations do not require elevated privileges. If we want that to be the case, we
        // need to give all users the ability to write to the registry file. Everything else in
        // the /var/safenode-manager directory and its subdirectories will still require
        // elevated privileges.
        let mut perm = std::fs::metadata(node_registry_path.clone())?.permissions();
        perm.set_mode(0o777);
        std::fs::set_permissions(node_registry_path.clone(), perm)?;
    }

    Ok(node_registry_path)
}

#[cfg(unix)]
pub fn get_service_data_dir_path(custom_path: Option<PathBuf>, owner: &str) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => p,
        None => PathBuf::from("/var/safenode-manager/services"),
    };
    create_owned_dir(path.clone(), owner)?;
    Ok(path)
}

#[cfg(windows)]
pub fn get_service_data_dir_path(custom_path: Option<PathBuf>, _owner: &str) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => p,
        None => PathBuf::from("C:\\ProgramData\\safenode\\data"),
    };
    std::fs::create_dir_all(&path)?;
    Ok(path)
}

#[cfg(unix)]
pub fn get_service_log_dir_path(
    bin_type: ReleaseType,
    custom_path: Option<PathBuf>,
    owner: &str,
) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => p,
        None => PathBuf::from("/var/log").join(bin_type.to_string()),
    };
    create_owned_dir(path.clone(), owner)?;
    Ok(path)
}

#[cfg(windows)]
pub fn get_service_log_dir_path(
    bin_type: ReleaseType,
    custom_path: Option<PathBuf>,
    _owner: &str,
) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => p,
        None => PathBuf::from("C:\\ProgramData")
            .join(bin_type.to_string())
            .join("logs"),
    };
    std::fs::create_dir_all(&path)?;
    Ok(path)
}

#[cfg(unix)]
pub fn create_owned_dir(path: PathBuf, owner: &str) -> Result<()> {
    use color_eyre::eyre::eyre;
    use nix::unistd::{chown, Gid, Uid};
    use std::os::unix::fs::PermissionsExt;
    use users::get_user_by_name;

    std::fs::create_dir_all(&path)?;
    let permissions = std::fs::Permissions::from_mode(0o755);
    std::fs::set_permissions(&path, permissions)?;

    let user = get_user_by_name(owner).ok_or_else(|| eyre!("User '{owner}' does not exist"))?;
    let uid = Uid::from_raw(user.uid());
    let gid = Gid::from_raw(user.primary_group_id());
    chown(&path, Some(uid), Some(gid))?;
    Ok(())
}

#[cfg(windows)]
pub fn create_owned_dir(path: PathBuf, _owner: &str) -> Result<()> {
    std::fs::create_dir_all(path)?;
    Ok(())
}

#[cfg(windows)]
pub fn get_node_registry_path() -> Result<PathBuf> {
    let path = Path::new("C:\\ProgramData\\safenode-manager");
    if !path.exists() {
        std::fs::create_dir_all(path)?;
    }
    Ok(path.join("node_registry.json"))
}

#[cfg(unix)]
pub fn is_running_as_root() -> bool {
    users::get_effective_uid() == 0
}

#[cfg(windows)]
pub fn is_running_as_root() -> bool {
    // The Windows implementation for this will be much more complex.
    true
}