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
// 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::{eyre::eyre, Result};
use sn_releases::ReleaseType;
use std::path::PathBuf;

#[cfg(unix)]
pub fn get_daemon_install_path() -> PathBuf {
    PathBuf::from("/usr/local/bin/safenodemand")
}

#[cfg(windows)]
pub fn get_daemon_install_path() -> PathBuf {
    PathBuf::from("C:\\ProgramData\\safenodemand\\safenodemand.exe")
}

#[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 = if is_running_as_root() {
        let path = PathBuf::from("/var/safenode-manager/");
        debug!("Running as root, creating node_manager_path and setting perms if path doesn't exists: {path:?}");
        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)?;
        path
    } else {
        let path = get_user_safenode_data_dir()?;
        debug!("Running as non-root, node_manager_path is: {path:?}");
        path
    };

    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)
}

#[cfg(windows)]
pub fn get_node_manager_path() -> Result<PathBuf> {
    use std::path::Path;
    let path = Path::new("C:\\ProgramData\\safenode-manager");
    debug!("Running as root, creating node_manager_path at: {path:?}");

    if !path.exists() {
        std::fs::create_dir_all(path)?;
    }
    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() {
        debug!("Running as root and node_registry_path doesn't exist, creating node_registry_path and setting perms at: {node_registry_path:?}");
        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)?;
    }
    debug!("Node registry path is: {node_registry_path:?}");

    Ok(node_registry_path)
}

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

    Ok(path.join("node_registry.json"))
}

/// Get the data directory for the service.
///
/// It's a little counter-intuitive, but the owner will be `None` in the case of a user-mode
/// service, because it will always run as the current user. The `owner` is really to specify the
/// non-root user for running a system-wide service.
#[cfg(unix)]
pub fn get_service_data_dir_path(
    custom_path: Option<PathBuf>,
    owner: Option<String>,
) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => {
            debug!("Using custom path for service data dir: {p:?}");
            p
        }
        None => {
            if owner.is_some() {
                let path = PathBuf::from("/var/safenode-manager/services");
                debug!("Using default path for service data dir: {path:?}");
                path
            } else {
                let path = get_user_safenode_data_dir()?;
                debug!("Using user mode service data dir: {path:?}");
                path
            }
        }
    };
    if let Some(owner) = owner {
        create_owned_dir(path.clone(), &owner)?;
    }
    Ok(path)
}

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

/// Get the logging directory for the service.
///
/// It's a little counter-intuitive, but the owner will be `None` in the case of a user-mode
/// service, because it will always run as the current user. The `owner` is really to specify the
/// non-root user for running a system-wide service.
#[cfg(unix)]
pub fn get_service_log_dir_path(
    bin_type: ReleaseType,
    custom_path: Option<PathBuf>,
    owner: Option<String>,
) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => {
            debug!("Using custom path for service log dir: {p:?}");
            p
        }
        None => {
            if owner.is_some() {
                let path = PathBuf::from("/var/log").join(bin_type.to_string());
                debug!("Using default path for service log dir: {path:?}");
                path
            } else {
                let path = get_user_safenode_data_dir()?;
                debug!("Using user mode service log dir: {path:?}");
                path
            }
        }
    };
    if let Some(owner) = owner {
        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: Option<String>,
) -> Result<PathBuf> {
    let path = match custom_path {
        Some(p) => {
            debug!("Using custom path for service log dir: {p:?}");
            p
        }
        None => {
            let path = PathBuf::from("C:\\ProgramData")
                .join(bin_type.to_string())
                .join("logs");
            debug!("Using default path for service log dir: {path:?}");
            path
        }
    };
    std::fs::create_dir_all(&path)?;
    Ok(path)
}

#[cfg(unix)]
pub fn create_owned_dir(path: PathBuf, owner: &str) -> Result<()> {
    debug!("Creating owned dir and setting permissions: {path:?} with owner: {owner}");
    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(|| {
        error!("User '{owner}' does not exist");
        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<()> {
    debug!("Creating owned dir: {path:?}");
    std::fs::create_dir_all(path)?;
    Ok(())
}

#[cfg(unix)]
pub fn is_running_as_root() -> bool {
    use nix::unistd::geteuid;
    geteuid().is_root()
}

#[cfg(windows)]
pub fn is_running_as_root() -> bool {
    // Example: Attempt to read from a typically restricted system directory
    std::fs::read_dir("C:\\Windows\\System32\\config").is_ok()
}

pub fn get_user_safenode_data_dir() -> Result<PathBuf> {
    Ok(dirs_next::data_dir()
        .ok_or_else(|| {
            error!("Failed to get data_dir");
            eyre!("Could not obtain user data directory")
        })?
        .join("safe")
        .join("node"))
}