@@ -50,7 +50,8 @@ extern "C" {
5050 disk_format : u32 ,
5151 read_only : bool ,
5252 ) -> i32 ;
53- fn krun_add_vsock_port ( ctx_id : u32 , port : u32 , c_filepath : * const c_char ) -> i32 ;
53+ fn krun_add_vsock_port2 ( ctx_id : u32 , port : u32 , c_filepath : * const c_char , listen : bool )
54+ -> i32 ;
5455 fn krun_add_virtiofs ( ctx_id : u32 , c_tag : * const c_char , c_path : * const c_char ) -> i32 ;
5556 fn krun_set_console_output ( ctx_id : u32 , c_filepath : * const c_char ) -> i32 ;
5657 fn krun_add_net_unixgram (
@@ -286,12 +287,25 @@ impl FromStr for VsockConfig {
286287 vsock_config. socket_url = PathBuf :: from_str ( socket_url. as_str ( ) )
287288 . context ( "socketURL argument not a valid path" ) ?;
288289
290+ if let Some ( v) = args. remove ( "connect" ) {
291+ if !v. is_empty ( ) {
292+ return Err ( anyhow ! ( format!(
293+ "unexpected value for virtio-vsock argument: connect={v}"
294+ ) ) ) ;
295+ }
296+ vsock_config. action = VsockAction :: from_str ( "connect" ) ?
297+ }
289298 if let Some ( v) = args. remove ( "listen" ) {
290299 if !v. is_empty ( ) {
291300 return Err ( anyhow ! ( format!(
292301 "unexpected value for virtio-vsock argument: listen={v}"
293302 ) ) ) ;
294303 }
304+ if vsock_config. action == VsockAction :: Connect {
305+ return Err ( anyhow ! (
306+ "virtio-vsock argument \" listen\" and \" connect\" are mutually exclusive and cannot be used together."
307+ ) ) ;
308+ }
295309 vsock_config. action = VsockAction :: from_str ( "listen" ) ?
296310 }
297311
@@ -307,7 +321,14 @@ impl KrunContextSet for VsockConfig {
307321 unsafe fn krun_ctx_set ( & self , id : u32 ) -> Result < ( ) , anyhow:: Error > {
308322 let path_cstr = path_to_cstring ( & self . socket_url ) ?;
309323
310- if krun_add_vsock_port ( id, self . port , path_cstr. as_ptr ( ) ) < 0 {
324+ // libkrun's `listen` parameter means "guest expects connections from host" which is true when VsockAction::Connect.
325+ if krun_add_vsock_port2 (
326+ id,
327+ self . port ,
328+ path_cstr. as_ptr ( ) ,
329+ self . action == VsockAction :: Connect ,
330+ ) < 0
331+ {
311332 return Err ( anyhow ! ( format!(
312333 "unable to add vsock port {} for path {}" ,
313334 self . port,
@@ -322,8 +343,11 @@ impl KrunContextSet for VsockConfig {
322343/// virtio-vsock action.
323344#[ derive( Clone , Debug , Default , PartialEq ) ]
324345pub enum VsockAction {
346+ /// Host listens for guest-initiated connections (default).
325347 #[ default]
326348 Listen ,
349+ /// Host connects to guest; guest listens for host-initiated connections.
350+ Connect ,
327351}
328352
329353impl FromStr for VsockAction {
@@ -334,6 +358,7 @@ impl FromStr for VsockAction {
334358
335359 match & s[ ..] {
336360 "listen" => Ok ( Self :: Listen ) ,
361+ "connect" => Ok ( Self :: Connect ) ,
337362 _ => Err ( anyhow ! ( "invalid vsock action" ) ) ,
338363 }
339364 }
0 commit comments