microsandbox_agentd/serial.rs
1//! Virtio serial port discovery.
2
3use std::{fs, path::PathBuf};
4
5use crate::error::{AgentdError, AgentdResult};
6
7//--------------------------------------------------------------------------------------------------
8// Constants
9//--------------------------------------------------------------------------------------------------
10
11/// The sysfs path where virtio ports are listed.
12const VIRTIO_PORTS_PATH: &str = "/sys/class/virtio-ports";
13
14/// Re-export the canonical agent port name from the protocol crate.
15pub use microsandbox_protocol::AGENT_PORT_NAME;
16
17//--------------------------------------------------------------------------------------------------
18// Functions
19//--------------------------------------------------------------------------------------------------
20
21/// Discovers the device path for a virtio serial port by its name.
22///
23/// Scans `/sys/class/virtio-ports/` entries, reads each `name` file,
24/// and returns `/dev/{port_id}` for the matching port.
25pub fn find_serial_port(name: &str) -> AgentdResult<PathBuf> {
26 let ports_dir = PathBuf::from(VIRTIO_PORTS_PATH);
27
28 let entries = fs::read_dir(&ports_dir).map_err(|e| {
29 AgentdError::SerialPortNotFound(format!("cannot read {VIRTIO_PORTS_PATH}: {e}"))
30 })?;
31
32 for entry in entries {
33 let entry = entry?;
34 let name_file = entry.path().join("name");
35
36 if let Ok(port_name) = fs::read_to_string(&name_file)
37 && port_name.trim() == name
38 {
39 let port_id = entry.file_name();
40 return Ok(PathBuf::from("/dev").join(port_id));
41 }
42 }
43
44 Err(AgentdError::SerialPortNotFound(format!(
45 "no virtio port with name '{name}' found"
46 )))
47}