patches and low-level development discussion
 help / color / mirror / code / Atom feed
adf99159b88d456973025cfa92c406d3cad3e5a2 blob 5483 bytes (raw)

  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
 
// SPDX-License-Identifier: EUPL-1.2+
// SPDX-FileCopyrightText: 2022-2023 Alyssa Ross <hi@alyssa.is>

mod ch;
mod net;
mod s6;
mod unix;

use std::borrow::Cow;
use std::env::args_os;
use std::ffi::{CString, OsStr, OsString};
use std::fs::remove_file;
use std::io::{self, ErrorKind};
use std::os::unix::net::UnixListener;
use std::os::unix::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command;

use net::{format_mac, net_setup, NetConfig};
use unix::clear_cloexec;

pub use s6::notify_readiness;

pub fn prog_name() -> String {
    args_os()
        .next()
        .as_ref()
        .map(Path::new)
        .and_then(Path::file_name)
        .map(OsStr::to_string_lossy)
        .unwrap_or(Cow::Borrowed("start-vm"))
        .into_owned()
}

pub fn create_api_socket() -> Result<UnixListener, String> {
    let _ = remove_file("env/cloud-hypervisor.sock");
    let api_socket = UnixListener::bind("env/cloud-hypervisor.sock")
        .map_err(|e| format!("creating API socket: {e}"))?;

    // Safe because we own api_socket.
    if unsafe { clear_cloexec(api_socket.as_fd()) } == -1 {
        let errno = io::Error::last_os_error();
        return Err(format!("clearing CLOEXEC on API socket fd: {}", errno));
    }

    Ok(api_socket)
}

pub fn vm_command(
    dir: PathBuf,
    config_root: &Path,
    api_socket_fd: RawFd,
) -> Result<Command, String> {
    let vm_name = dir
        .file_name()
        .ok_or_else(|| "directory has no name".to_string())?;

    if vm_name.as_bytes().contains(&b',') {
        return Err(format!("VM name may not contain a comma: {:?}", vm_name));
    }

    let config_dir = config_root.join(vm_name);

    let mut command = Command::new("cloud-hypervisor");
    command.args(["--api-socket", &format!("fd={api_socket_fd}")]);
    command.args(["--cmdline", "console=ttyS0 root=PARTLABEL=root"]);
    command.args(["--memory", "size=128M,shared=on"]);
    command.args(["--console", "pty"]);
    command.arg("--kernel");
    command.arg(config_dir.join("vmlinux"));

    let net_providers_dir = config_dir.join("providers/net");
    match net_providers_dir.read_dir() {
        Ok(entries) => {
            // TODO: to support multiple net providers, we'll need
            // a better naming scheme for tap and bridge devices.
            #[allow(clippy::never_loop)]
            for r in entries {
                let entry = r
                    .map_err(|e| format!("examining directory entry: {}", e))?
                    .file_name();

                // Safe because provider_name is the name of a directory entry, so
                // can't contain a null byte.
                let provider_name = unsafe { CString::from_vec_unchecked(entry.into_vec()) };

                // Safe because we pass a valid pointer and check the result.
                let NetConfig { fd, mac } = unsafe { net_setup(provider_name.as_ptr()) };
                if fd == -1 {
                    let e = io::Error::last_os_error();
                    return Err(format!("setting up networking failed: {}", e));
                }

                command
                    .arg("--net")
                    .arg(format!("fd={},mac={}", fd, format_mac(&mac)));

                break;
            }
        }
        Err(e) if e.kind() == ErrorKind::NotFound => {}
        Err(e) => return Err(format!("reading directory {:?}: {}", net_providers_dir, e)),
    }

    let blk_dir = config_dir.join("blk");
    match blk_dir.read_dir() {
        Ok(entries) => {
            for result in entries {
                let entry = result
                    .map_err(|e| format!("examining directory entry: {}", e))?
                    .path();

                if entry.extension() != Some(OsStr::new("img")) {
                    continue;
                }

                if entry.as_os_str().as_bytes().contains(&b',') {
                    return Err(format!("illegal ',' character in path {:?}", entry));
                }

                let mut arg = OsString::from("path=");
                arg.push(entry);
                arg.push(",readonly=on");
                command.arg("--disk").arg(arg);
            }
        }
        Err(e) => return Err(format!("reading directory {:?}: {}", blk_dir, e)),
    }

    let shared_dirs_dir = config_dir.join("shared-dirs");
    match shared_dirs_dir.read_dir() {
        Ok(entries) => {
            for result in entries {
                let entry = result
                    .map_err(|e| format!("examining directory entry: {}", e))?
                    .file_name();

                let mut arg = OsString::from("tag=");
                arg.push(&entry);
                arg.push(",socket=../");
                arg.push(vm_name);
                arg.push("-fs-");
                arg.push(&entry);
                arg.push("/env/virtiofsd.sock");
                command.arg("--fs").arg(arg);
            }
        }
        Err(e) if e.kind() == ErrorKind::NotFound => {}
        Err(e) => return Err(format!("reading directory {:?}: {}", shared_dirs_dir, e)),
    }

    command.arg("--serial").arg({
        let mut serial = OsString::from("file=/run/");
        serial.push(vm_name);
        serial.push(".log");
        serial
    });

    Ok(command)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_vm_name_comma() {
        assert!(vm_command("/v,m".into(), Path::new("/"), -1)
            .unwrap_err()
            .contains("comma"));
    }
}
debug log:

solving adf9915 ...
found adf9915 in https://spectrum-os.org/git/spectrum

Code repositories for project(s) associated with this public inbox

	https://spectrum-os.org/git/crosvm
	https://spectrum-os.org/git/doc
	https://spectrum-os.org/git/mktuntap
	https://spectrum-os.org/git/nixpkgs
	https://spectrum-os.org/git/spectrum
	https://spectrum-os.org/git/ucspi-vsock
	https://spectrum-os.org/git/www

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).