triage_detect_config/
triage-detect-config_rust_config_lib_source.rs

1use fidl::unpersist;
2use fidl_cf_sc_internal_triagedetectconfig::Config as FidlConfig;
3use fuchsia_inspect::Node;
4use fuchsia_runtime::{take_startup_handle, HandleInfo, HandleType};
5use std::convert::TryInto;
6const EXPECTED_CHECKSUM: &[u8] = &[
7    0x95, 0xdf, 0xc8, 0xef, 0xf2, 0x38, 0x46, 0xa6, 0xd1, 0x34, 0x38, 0xc3, 0xdb, 0xde, 0xff, 0x88,
8    0x0d, 0x4c, 0xdf, 0xc9, 0x16, 0xb7, 0xc3, 0xb5, 0x06, 0x06, 0xa0, 0xd3, 0x46, 0x84, 0x86, 0x45,
9];
10#[derive(Debug)]
11pub struct Config {
12    pub check_every: String,
13    pub test_only: bool,
14}
15impl Config {
16    #[doc = r" Take the config startup handle and parse its contents."]
17    #[doc = r""]
18    #[doc = r" # Panics"]
19    #[doc = r""]
20    #[doc = r" If the config startup handle was already taken or if it is not valid."]
21    pub fn take_from_startup_handle() -> Self {
22        let handle_info = HandleInfo::new(HandleType::ComponentConfigVmo, 0);
23        let config_vmo: zx::Vmo =
24            take_startup_handle(handle_info).expect("Config VMO handle must be present.").into();
25        Self::from_vmo(&config_vmo).expect("Config VMO handle must be valid.")
26    }
27    #[doc = r" Parse `Self` from `vmo`."]
28    pub fn from_vmo(vmo: &zx::Vmo) -> Result<Self, Error> {
29        let config_size = vmo.get_content_size().map_err(Error::GettingContentSize)?;
30        let config_bytes = vmo.read_to_vec(0, config_size).map_err(Error::ReadingConfigBytes)?;
31        Self::from_bytes(&config_bytes)
32    }
33    #[doc = r" Parse `Self` from `bytes`."]
34    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
35        let (checksum_len_bytes, bytes) = bytes.split_at_checked(2).ok_or(Error::TooFewBytes)?;
36        let checksum_len_bytes: [u8; 2] =
37            checksum_len_bytes.try_into().expect("previous call guaranteed 2 element slice");
38        let checksum_length = u16::from_le_bytes(checksum_len_bytes) as usize;
39        let (observed_checksum, bytes) =
40            bytes.split_at_checked(checksum_length).ok_or(Error::TooFewBytes)?;
41        if observed_checksum != EXPECTED_CHECKSUM {
42            return Err(Error::ChecksumMismatch { observed_checksum: observed_checksum.to_vec() });
43        }
44        let fidl_config: FidlConfig = unpersist(bytes).map_err(Error::Unpersist)?;
45        Ok(Self { check_every: fidl_config.check_every, test_only: fidl_config.test_only })
46    }
47    pub fn record_inspect(&self, inspector_node: &Node) {
48        inspector_node.record_string("check_every", &self.check_every);
49        inspector_node.record_bool("test_only", self.test_only);
50    }
51}
52#[derive(Debug)]
53pub enum Error {
54    #[doc = r" Failed to read the content size of the VMO."]
55    GettingContentSize(zx::Status),
56    #[doc = r" Failed to read the content of the VMO."]
57    ReadingConfigBytes(zx::Status),
58    #[doc = r" The VMO was too small for this config library."]
59    TooFewBytes,
60    #[doc = r" The VMO's config ABI checksum did not match this library's."]
61    ChecksumMismatch { observed_checksum: Vec<u8> },
62    #[doc = r" Failed to parse the non-checksum bytes of the VMO as this library's FIDL type."]
63    Unpersist(fidl::Error),
64}
65impl std::fmt::Display for Error {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        match self {
68            Self::GettingContentSize(status) => {
69                write!(f, "Failed to get content size: {status}")
70            }
71            Self::ReadingConfigBytes(status) => {
72                write!(f, "Failed to read VMO content: {status}")
73            }
74            Self::TooFewBytes => {
75                write!(f, "VMO content is not large enough for this config library.")
76            }
77            Self::ChecksumMismatch { observed_checksum } => {
78                write!(
79                    f,
80                    "ABI checksum mismatch, expected {:?}, got {:?}",
81                    EXPECTED_CHECKSUM, observed_checksum,
82                )
83            }
84            Self::Unpersist(fidl_error) => {
85                write!(f, "Failed to parse contents of config VMO: {fidl_error}")
86            }
87        }
88    }
89}
90impl std::error::Error for Error {
91    #[allow(unused_parens, reason = "rustfmt errors without parens here")]
92    fn source(&self) -> Option<(&'_ (dyn std::error::Error + 'static))> {
93        match self {
94            Self::GettingContentSize(ref status) | Self::ReadingConfigBytes(ref status) => {
95                Some(status)
96            }
97            Self::TooFewBytes => None,
98            Self::ChecksumMismatch { .. } => None,
99            Self::Unpersist(ref fidl_error) => Some(fidl_error),
100        }
101    }
102    fn description(&self) -> &str {
103        match self {
104            Self::GettingContentSize(_) => "getting content size",
105            Self::ReadingConfigBytes(_) => "reading VMO contents",
106            Self::TooFewBytes => "VMO contents too small",
107            Self::ChecksumMismatch { .. } => "ABI checksum mismatch",
108            Self::Unpersist(_) => "FIDL parsing error",
109        }
110    }
111}