devices/
serial_device.rs

1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::fmt;
6use std::fmt::Display;
7use std::fs::File;
8use std::fs::OpenOptions;
9use std::io;
10use std::io::stdin;
11use std::io::stdout;
12#[cfg(unix)]
13use std::os::unix::net::UnixStream;
14use std::path::PathBuf;
15
16use base::error;
17use base::open_file_or_duplicate;
18use base::syslog;
19#[cfg(windows)]
20use base::windows::Console as WinConsole;
21use base::AsRawDescriptor;
22use base::Event;
23use base::FileSync;
24use base::RawDescriptor;
25use base::ReadNotifier;
26use hypervisor::ProtectionType;
27use remain::sorted;
28use serde::Deserialize;
29use serde::Serialize;
30use serde_keyvalue::FromKeyValues;
31use thiserror::Error as ThisError;
32
33pub use crate::sys::serial_device::SerialDevice;
34use crate::sys::serial_device::*;
35use crate::PciAddress;
36
37#[sorted]
38#[derive(ThisError, Debug)]
39pub enum Error {
40    #[error("Unable to clone an Event: {0}")]
41    CloneEvent(base::Error),
42    #[error("Unable to clone a Unix Stream: {0}")]
43    CloneUnixStream(std::io::Error),
44    #[error("Unable to clone file: {0}")]
45    FileClone(std::io::Error),
46    #[error("Unable to create file '{1}': {0}")]
47    FileCreate(std::io::Error, PathBuf),
48    #[error("Unable to open file '{1}': {0}")]
49    FileOpen(std::io::Error, PathBuf),
50    #[error("Invalid serial config specified: {0}")]
51    InvalidConfig(String),
52    #[error("Serial device path '{0} is invalid")]
53    InvalidPath(PathBuf),
54    #[error("Invalid serial hardware: {0}")]
55    InvalidSerialHardware(String),
56    #[error("Invalid serial type: {0}")]
57    InvalidSerialType(String),
58    #[error("Serial device type file requires a path")]
59    PathRequired,
60    #[error("Failed to connect to socket: {0}")]
61    SocketConnect(std::io::Error),
62    #[error("Failed to create unbound socket: {0}")]
63    SocketCreate(std::io::Error),
64    #[error("Unable to open system type serial: {0}")]
65    SystemTypeError(std::io::Error),
66    #[error("Serial device type {0} not implemented")]
67    Unimplemented(SerialType),
68}
69
70/// Trait for types that can be used as input for a serial device.
71pub trait SerialInput: io::Read + ReadNotifier + Send {}
72impl SerialInput for File {}
73#[cfg(unix)]
74impl SerialInput for UnixStream {}
75#[cfg(windows)]
76impl SerialInput for WinConsole {}
77
78/// Enum for possible type of serial devices
79#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
80#[serde(rename_all = "kebab-case")]
81pub enum SerialType {
82    File,
83    Stdout,
84    Sink,
85    Syslog,
86    #[cfg_attr(unix, serde(rename = "unix"))]
87    #[cfg_attr(windows, serde(rename = "namedpipe"))]
88    SystemSerialType,
89    // Use the same Unix domain socket for input and output.
90    #[cfg(unix)]
91    UnixStream,
92}
93
94impl Default for SerialType {
95    fn default() -> Self {
96        Self::Sink
97    }
98}
99
100impl Display for SerialType {
101    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102        let s = match &self {
103            SerialType::File => "File".to_string(),
104            SerialType::Stdout => "Stdout".to_string(),
105            SerialType::Sink => "Sink".to_string(),
106            SerialType::Syslog => "Syslog".to_string(),
107            SerialType::SystemSerialType => SYSTEM_SERIAL_TYPE_NAME.to_string(),
108            #[cfg(unix)]
109            SerialType::UnixStream => "UnixStream".to_string(),
110        };
111
112        write!(f, "{s}")
113    }
114}
115
116/// Serial device hardware types
117#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
118#[serde(rename_all = "kebab-case")]
119pub enum SerialHardware {
120    /// Standard PC-style (8250/16550 compatible) UART
121    Serial,
122
123    /// virtio-console device
124    #[serde(alias = "legacy-virtio-console")]
125    VirtioConsole,
126
127    /// Bochs style debug port
128    Debugcon,
129}
130
131impl Default for SerialHardware {
132    fn default() -> Self {
133        Self::Serial
134    }
135}
136
137impl Display for SerialHardware {
138    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139        let s = match &self {
140            SerialHardware::Serial => "serial".to_string(),
141            SerialHardware::VirtioConsole => "virtio-console".to_string(),
142            SerialHardware::Debugcon => "debugcon".to_string(),
143        };
144
145        write!(f, "{s}")
146    }
147}
148
149fn serial_parameters_default_num() -> u8 {
150    1
151}
152
153fn serial_parameters_default_debugcon_port() -> u16 {
154    // Default to the port OVMF expects.
155    0x402
156}
157
158#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
159#[serde(deny_unknown_fields, rename_all = "kebab-case", default)]
160pub struct SerialParameters {
161    #[serde(rename = "type")]
162    pub type_: SerialType,
163    pub hardware: SerialHardware,
164    pub name: Option<String>,
165    pub path: Option<PathBuf>,
166    pub input: Option<PathBuf>,
167    /// Use the given `UnixStream` as input as well as output.
168    /// This flag can be used only when `type_` is `UnixStream`.
169    #[cfg(unix)]
170    pub input_unix_stream: bool,
171    #[serde(default = "serial_parameters_default_num")]
172    pub num: u8,
173    pub console: bool,
174    pub earlycon: bool,
175    pub stdin: bool,
176    #[serde(alias = "out_timestamp")]
177    pub out_timestamp: bool,
178    #[serde(
179        alias = "debugcon_port",
180        default = "serial_parameters_default_debugcon_port"
181    )]
182    pub debugcon_port: u16,
183    pub pci_address: Option<PciAddress>,
184    pub max_queue_sizes: Option<Vec<u16>>,
185}
186
187/// Temporary structure containing the parameters of a serial port for easy passing to
188/// `SerialDevice::new`.
189#[derive(Default)]
190pub struct SerialOptions {
191    pub name: Option<String>,
192    pub out_timestamp: bool,
193    pub console: bool,
194    pub pci_address: Option<PciAddress>,
195    pub max_queue_sizes: Option<Vec<u16>>,
196}
197
198impl SerialParameters {
199    pub(crate) fn serial_options(&self) -> SerialOptions {
200        SerialOptions {
201            name: self.name.clone(),
202            out_timestamp: self.out_timestamp,
203            console: self.console,
204            pci_address: self.pci_address,
205            max_queue_sizes: self.max_queue_sizes.clone(),
206        }
207    }
208
209    /// Helper function to create a serial device from the defined parameters.
210    ///
211    /// # Arguments
212    /// * `evt` - event used for interrupt events
213    /// * `keep_rds` - Vector of FDs required by this device if it were sandboxed in a child
214    ///   process. `evt` will always be added to this vector by this function.
215    pub fn create_serial_device<T: SerialDevice>(
216        &self,
217        protection_type: ProtectionType,
218        evt: &Event,
219        keep_rds: &mut Vec<RawDescriptor>,
220    ) -> std::result::Result<T, Error> {
221        let evt = evt.try_clone().map_err(Error::CloneEvent)?;
222        keep_rds.push(evt.as_raw_descriptor());
223        cros_tracing::push_descriptors!(keep_rds);
224        metrics::push_descriptors(keep_rds);
225
226        // When `self.input_unix_stream` is specified, use `self.path` for both output and input.
227        #[cfg(unix)]
228        if self.input_unix_stream {
229            if self.input.is_some() {
230                return Err(Error::InvalidConfig(
231                    "input-unix-stream can't be passed when input is specified".to_string(),
232                ));
233            }
234            if self.type_ != SerialType::UnixStream {
235                return Err(Error::InvalidConfig(
236                    "input-unix-stream must be used with type=unix-stream".to_string(),
237                ));
238            }
239
240            return create_unix_stream_serial_device(self, protection_type, evt, keep_rds);
241        }
242
243        let input: Option<Box<dyn SerialInput>> = if let Some(input_path) = &self.input {
244            let input_path = input_path.as_path();
245
246            let input_file = open_file_or_duplicate(input_path, OpenOptions::new().read(true))
247                .map_err(|e| Error::FileOpen(e.into(), input_path.into()))?;
248
249            keep_rds.push(input_file.as_raw_descriptor());
250            Some(Box::new(input_file))
251        } else if self.stdin {
252            keep_rds.push(stdin().as_raw_descriptor());
253            Some(Box::new(ConsoleInput::new()))
254        } else {
255            None
256        };
257        let (output, sync): (
258            Option<Box<dyn io::Write + Send>>,
259            Option<Box<dyn FileSync + Send>>,
260        ) = match self.type_ {
261            SerialType::Stdout => {
262                keep_rds.push(stdout().as_raw_descriptor());
263                (Some(Box::new(stdout())), None)
264            }
265            SerialType::Sink => (None, None),
266            SerialType::Syslog => {
267                syslog::push_descriptors(keep_rds);
268                (
269                    Some(Box::new(syslog::Syslogger::new(base::syslog::Level::Info))),
270                    None,
271                )
272            }
273            SerialType::File => match &self.path {
274                Some(path) => {
275                    let file =
276                        open_file_or_duplicate(path, OpenOptions::new().append(true).create(true))
277                            .map_err(|e| Error::FileCreate(e.into(), path.clone()))?;
278                    let sync = file.try_clone().map_err(Error::FileClone)?;
279
280                    keep_rds.push(file.as_raw_descriptor());
281                    keep_rds.push(sync.as_raw_descriptor());
282
283                    (Some(Box::new(file)), Some(Box::new(sync)))
284                }
285                None => return Err(Error::PathRequired),
286            },
287            SerialType::SystemSerialType => {
288                return create_system_type_serial_device(
289                    self,
290                    protection_type,
291                    evt,
292                    input,
293                    keep_rds,
294                );
295            }
296            #[cfg(unix)]
297            SerialType::UnixStream => {
298                let path = self.path.as_ref().ok_or(Error::PathRequired)?;
299                let output = UnixStream::connect(path).map_err(Error::SocketConnect)?;
300                keep_rds.push(output.as_raw_descriptor());
301                (Some(Box::new(output)), None)
302            }
303        };
304        Ok(T::new(
305            protection_type,
306            evt,
307            input,
308            output,
309            sync,
310            self.serial_options(),
311            keep_rds.to_vec(),
312        ))
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use serde_keyvalue::*;
319
320    use super::*;
321
322    fn from_serial_arg(options: &str) -> Result<SerialParameters, ParseError> {
323        from_key_values(options)
324    }
325
326    #[test]
327    fn params_from_key_values() {
328        // Defaults
329        let params = from_serial_arg("").unwrap();
330        assert_eq!(
331            params,
332            SerialParameters {
333                type_: SerialType::Sink,
334                hardware: SerialHardware::Serial,
335                name: None,
336                path: None,
337                input: None,
338                #[cfg(unix)]
339                input_unix_stream: false,
340                num: 1,
341                console: false,
342                earlycon: false,
343                stdin: false,
344                out_timestamp: false,
345                debugcon_port: 0x402,
346                pci_address: None,
347                max_queue_sizes: None,
348            }
349        );
350
351        // type parameter
352        let params = from_serial_arg("type=file").unwrap();
353        assert_eq!(params.type_, SerialType::File);
354        let params = from_serial_arg("type=stdout").unwrap();
355        assert_eq!(params.type_, SerialType::Stdout);
356        let params = from_serial_arg("type=sink").unwrap();
357        assert_eq!(params.type_, SerialType::Sink);
358        let params = from_serial_arg("type=syslog").unwrap();
359        assert_eq!(params.type_, SerialType::Syslog);
360        #[cfg(any(target_os = "android", target_os = "linux"))]
361        let opt = "type=unix";
362        #[cfg(windows)]
363        let opt = "type=namedpipe";
364        let params = from_serial_arg(opt).unwrap();
365        assert_eq!(params.type_, SerialType::SystemSerialType);
366        #[cfg(unix)]
367        {
368            let params = from_serial_arg("type=unix-stream").unwrap();
369            assert_eq!(params.type_, SerialType::UnixStream);
370        }
371        let params = from_serial_arg("type=foobar");
372        assert!(params.is_err());
373
374        // hardware parameter
375        let params = from_serial_arg("hardware=serial").unwrap();
376        assert_eq!(params.hardware, SerialHardware::Serial);
377        let params = from_serial_arg("hardware=virtio-console").unwrap();
378        assert_eq!(params.hardware, SerialHardware::VirtioConsole);
379        let params = from_serial_arg("hardware=debugcon").unwrap();
380        assert_eq!(params.hardware, SerialHardware::Debugcon);
381        let params = from_serial_arg("hardware=foobar");
382        assert!(params.is_err());
383
384        // path parameter
385        let params = from_serial_arg("path=/test/path").unwrap();
386        assert_eq!(params.path, Some("/test/path".into()));
387        let params = from_serial_arg("path");
388        assert!(params.is_err());
389
390        // input parameter
391        let params = from_serial_arg("input=/path/to/input").unwrap();
392        assert_eq!(params.input, Some("/path/to/input".into()));
393        let params = from_serial_arg("input");
394        assert!(params.is_err());
395
396        #[cfg(unix)]
397        {
398            // input-unix-stream parameter
399            let params = from_serial_arg("input-unix-stream").unwrap();
400            assert!(params.input_unix_stream);
401            let params = from_serial_arg("input-unix-stream=true").unwrap();
402            assert!(params.input_unix_stream);
403            let params = from_serial_arg("input-unix-stream=false").unwrap();
404            assert!(!params.input_unix_stream);
405            let params = from_serial_arg("input-unix-stream=foobar");
406            assert!(params.is_err());
407        }
408
409        // console parameter
410        let params = from_serial_arg("console").unwrap();
411        assert!(params.console);
412        let params = from_serial_arg("console=true").unwrap();
413        assert!(params.console);
414        let params = from_serial_arg("console=false").unwrap();
415        assert!(!params.console);
416        let params = from_serial_arg("console=foobar");
417        assert!(params.is_err());
418
419        // earlycon parameter
420        let params = from_serial_arg("earlycon").unwrap();
421        assert!(params.earlycon);
422        let params = from_serial_arg("earlycon=true").unwrap();
423        assert!(params.earlycon);
424        let params = from_serial_arg("earlycon=false").unwrap();
425        assert!(!params.earlycon);
426        let params = from_serial_arg("earlycon=foobar");
427        assert!(params.is_err());
428
429        // stdin parameter
430        let params = from_serial_arg("stdin").unwrap();
431        assert!(params.stdin);
432        let params = from_serial_arg("stdin=true").unwrap();
433        assert!(params.stdin);
434        let params = from_serial_arg("stdin=false").unwrap();
435        assert!(!params.stdin);
436        let params = from_serial_arg("stdin=foobar");
437        assert!(params.is_err());
438
439        // out-timestamp parameter
440        let params = from_serial_arg("out-timestamp").unwrap();
441        assert!(params.out_timestamp);
442        let params = from_serial_arg("out-timestamp=true").unwrap();
443        assert!(params.out_timestamp);
444        let params = from_serial_arg("out-timestamp=false").unwrap();
445        assert!(!params.out_timestamp);
446        let params = from_serial_arg("out-timestamp=foobar");
447        assert!(params.is_err());
448        // backward compatibility
449        let params = from_serial_arg("out_timestamp=true").unwrap();
450        assert!(params.out_timestamp);
451
452        // debugcon-port parameter
453        let params = from_serial_arg("debugcon-port=1026").unwrap();
454        assert_eq!(params.debugcon_port, 1026);
455        // backward compatibility
456        let params = from_serial_arg("debugcon_port=1026").unwrap();
457        assert_eq!(params.debugcon_port, 1026);
458
459        // all together
460        let params = from_serial_arg("type=stdout,path=/some/path,hardware=virtio-console,num=5,earlycon,console,stdin,input=/some/input,out_timestamp,debugcon_port=12,pci-address=00:0e.0,max-queue-sizes=[1,2]").unwrap();
461        assert_eq!(
462            params,
463            SerialParameters {
464                type_: SerialType::Stdout,
465                hardware: SerialHardware::VirtioConsole,
466                name: None,
467                path: Some("/some/path".into()),
468                input: Some("/some/input".into()),
469                #[cfg(unix)]
470                input_unix_stream: false,
471                num: 5,
472                console: true,
473                earlycon: true,
474                stdin: true,
475                out_timestamp: true,
476                debugcon_port: 12,
477                pci_address: Some(PciAddress {
478                    bus: 0,
479                    dev: 14,
480                    func: 0
481                }),
482                max_queue_sizes: Some(vec![1, 2]),
483            }
484        );
485
486        // invalid field
487        let params = from_serial_arg("type=stdout,foo=bar");
488        assert!(params.is_err());
489    }
490}