From cd1397a3fc033f734bc187a8b333202d4b63956b Mon Sep 17 00:00:00 2001 From: Asahi Lina Date: Sat, 6 Jul 2024 17:28:26 +0900 Subject: [PATCH] Add dynamic UNIX socket forwarding Unconditionally forward a range of ports to sockets named `$XDG_RUNTIME_DIR/krun/socket/port-$PORT`. This allows applications to dynamically bind to sockets at those paths and have them forwarded to the guest as vsock ports, after the krun VM is already running. The port range is currently hardcoded as 50000..50200. Signed-off-by: Asahi Lina --- crates/krun/src/bin/krun.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/krun/src/bin/krun.rs b/crates/krun/src/bin/krun.rs index b5cf8d28..24a882b1 100644 --- a/crates/krun/src/bin/krun.rs +++ b/crates/krun/src/bin/krun.rs @@ -179,6 +179,25 @@ fn main() -> Result<()> { return Err(err).context("Failed to configure vsock for pulse socket"); } } + + let socket_dir = Path::new(&run_path).join("krun/socket"); + std::fs::create_dir_all(&socket_dir)?; + // Dynamic ports: Applications may listen on these sockets as neeeded. + for port in 50000..50200 { + let socket_path = socket_dir.join(format!("port-{}", port)); + let socket_path = CString::new( + socket_path + .to_str() + .expect("socket_path should not contain invalid UTF-8"), + ) + .context("Failed to process dynamic socket path as it contains NUL character")?; + // SAFETY: `socket_path` is a pointer to a `CString` with long enough lifetime. + let err = unsafe { krun_add_vsock_port(ctx_id, port, socket_path.as_ptr()) }; + if err < 0 { + let err = Errno::from_raw_os_error(-err); + return Err(err).context("Failed to configure vsock for dynamic socket"); + } + } } let username = env::var("USER").context("Failed to get username from environment")?;