summaryrefslogtreecommitdiff
path: root/init/src/host/set.rs
blob: 9550b2910f69f10c8832a466dbe33093827d205f (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
use crate::log::log_warning;
use libc::{c_char, sethostname, size_t};
use std::{ffi::CString, fs, io};

pub fn set_hostname() -> Result<(), Box<dyn std::error::Error>> {
    let content = fs::read_to_string("/etc/hostname")
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|_| "localhost".to_string());

    if let Err(e) = perform_set_hostname(&content) {
        match perform_set_hostname("localhost") {
            Ok(_) => Err(format!(
                "Failed to set hostname: \"{}\": {}. Fell back to localhost successfully.",
                content, e
            )
            .into()),

            Err(fallback_error) => {
                log_warning(&format!(
                    "Failed to set hostname to '{}': {}. Also failed to set localhost: {}.",
                    content, e, fallback_error
                ));
                Err(format!(
                    "Failed to set hostname '{}' and failed to fall back to localhost: {}.",
                    content, e
                )
                .into())
            }
        }
    } else {
        Ok(())
    }
}

fn perform_set_hostname(name: &str) -> io::Result<()> {
    if name.len() > 64 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Hostname too long",
        ));
    }

    let c_str = CString::new(name)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "Hostname contains null byte"))?;

    let res = unsafe { sethostname(c_str.as_ptr() as *const c_char, name.len() as size_t) };

    if res != 0 {
        return Err(io::Error::last_os_error());
    }

    Ok(())
}