starnix_container_structured_config/
starnix_container_structured_config_rust_config_lib_source.rs

1use fidl::unpersist;
2use fidl_cf_sc_internal_starnixcontainerstructuredconfig::Config as FidlConfig;
3use fuchsia_inspect::{ArrayProperty, Node};
4use fuchsia_runtime::{take_startup_handle, HandleInfo, HandleType};
5use std::convert::TryInto;
6const EXPECTED_CHECKSUM: &[u8] = &[
7    0x7c, 0x13, 0x67, 0x3a, 0x47, 0x91, 0xa3, 0xd2, 0x95, 0x47, 0x32, 0x49, 0xce, 0x53, 0x85, 0x2b,
8    0x61, 0x41, 0xed, 0x90, 0x6b, 0xda, 0x09, 0x2e, 0xd0, 0xfe, 0xde, 0x3f, 0xa2, 0xfe, 0x98, 0x3b,
9];
10#[derive(Debug)]
11pub struct Config {
12    pub enable_utc_time_adjustment: bool,
13    pub extra_features: Vec<String>,
14    pub mlock_always_onfault: bool,
15    pub mlock_pin_flavor: String,
16    pub selinux_exceptions: Vec<String>,
17    pub ui_visual_debugging_level: u8,
18}
19impl Config {
20    #[doc = r" Take the config startup handle and parse its contents."]
21    #[doc = r""]
22    #[doc = r" # Panics"]
23    #[doc = r""]
24    #[doc = r" If the config startup handle was already taken or if it is not valid."]
25    pub fn take_from_startup_handle() -> Self {
26        let handle_info = HandleInfo::new(HandleType::ComponentConfigVmo, 0);
27        let config_vmo: zx::Vmo =
28            take_startup_handle(handle_info).expect("Config VMO handle must be present.").into();
29        Self::from_vmo(&config_vmo).expect("Config VMO handle must be valid.")
30    }
31    #[doc = r" Parse `Self` from `vmo`."]
32    pub fn from_vmo(vmo: &zx::Vmo) -> Result<Self, Error> {
33        let config_size = vmo.get_content_size().map_err(Error::GettingContentSize)?;
34        let config_bytes = vmo.read_to_vec(0, config_size).map_err(Error::ReadingConfigBytes)?;
35        Self::from_bytes(&config_bytes)
36    }
37    #[doc = r" Parse `Self` from `bytes`."]
38    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
39        let (checksum_len_bytes, bytes) = bytes.split_at_checked(2).ok_or(Error::TooFewBytes)?;
40        let checksum_len_bytes: [u8; 2] =
41            checksum_len_bytes.try_into().expect("previous call guaranteed 2 element slice");
42        let checksum_length = u16::from_le_bytes(checksum_len_bytes) as usize;
43        let (observed_checksum, bytes) =
44            bytes.split_at_checked(checksum_length).ok_or(Error::TooFewBytes)?;
45        if observed_checksum != EXPECTED_CHECKSUM {
46            return Err(Error::ChecksumMismatch { observed_checksum: observed_checksum.to_vec() });
47        }
48        let fidl_config: FidlConfig = unpersist(bytes).map_err(Error::Unpersist)?;
49        Ok(Self {
50            enable_utc_time_adjustment: fidl_config.enable_utc_time_adjustment,
51            extra_features: fidl_config.extra_features,
52            mlock_always_onfault: fidl_config.mlock_always_onfault,
53            mlock_pin_flavor: fidl_config.mlock_pin_flavor,
54            selinux_exceptions: fidl_config.selinux_exceptions,
55            ui_visual_debugging_level: fidl_config.ui_visual_debugging_level,
56        })
57    }
58    pub fn record_inspect(&self, inspector_node: &Node) {
59        inspector_node.record_bool("enable_utc_time_adjustment", self.enable_utc_time_adjustment);
60        let arr = inspector_node.create_string_array("extra_features", self.extra_features.len());
61        for i in 0..self.extra_features.len() {
62            arr.set(i, &self.extra_features[i]);
63        }
64        inspector_node.record(arr);
65        inspector_node.record_bool("mlock_always_onfault", self.mlock_always_onfault);
66        inspector_node.record_string("mlock_pin_flavor", &self.mlock_pin_flavor);
67        let arr =
68            inspector_node.create_string_array("selinux_exceptions", self.selinux_exceptions.len());
69        for i in 0..self.selinux_exceptions.len() {
70            arr.set(i, &self.selinux_exceptions[i]);
71        }
72        inspector_node.record(arr);
73        inspector_node
74            .record_uint("ui_visual_debugging_level", self.ui_visual_debugging_level as u64);
75    }
76}
77#[derive(Debug)]
78pub enum Error {
79    #[doc = r" Failed to read the content size of the VMO."]
80    GettingContentSize(zx::Status),
81    #[doc = r" Failed to read the content of the VMO."]
82    ReadingConfigBytes(zx::Status),
83    #[doc = r" The VMO was too small for this config library."]
84    TooFewBytes,
85    #[doc = r" The VMO's config ABI checksum did not match this library's."]
86    ChecksumMismatch { observed_checksum: Vec<u8> },
87    #[doc = r" Failed to parse the non-checksum bytes of the VMO as this library's FIDL type."]
88    Unpersist(fidl::Error),
89}
90impl std::fmt::Display for Error {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self {
93            Self::GettingContentSize(status) => {
94                write!(f, "Failed to get content size: {status}")
95            }
96            Self::ReadingConfigBytes(status) => {
97                write!(f, "Failed to read VMO content: {status}")
98            }
99            Self::TooFewBytes => {
100                write!(f, "VMO content is not large enough for this config library.")
101            }
102            Self::ChecksumMismatch { observed_checksum } => {
103                write!(
104                    f,
105                    "ABI checksum mismatch, expected {:?}, got {:?}",
106                    EXPECTED_CHECKSUM, observed_checksum,
107                )
108            }
109            Self::Unpersist(fidl_error) => {
110                write!(f, "Failed to parse contents of config VMO: {fidl_error}")
111            }
112        }
113    }
114}
115impl std::error::Error for Error {
116    #[allow(unused_parens, reason = "rustfmt errors without parens here")]
117    fn source(&self) -> Option<(&'_ (dyn std::error::Error + 'static))> {
118        match self {
119            Self::GettingContentSize(ref status) | Self::ReadingConfigBytes(ref status) => {
120                Some(status)
121            }
122            Self::TooFewBytes => None,
123            Self::ChecksumMismatch { .. } => None,
124            Self::Unpersist(ref fidl_error) => Some(fidl_error),
125        }
126    }
127    fn description(&self) -> &str {
128        match self {
129            Self::GettingContentSize(_) => "getting content size",
130            Self::ReadingConfigBytes(_) => "reading VMO contents",
131            Self::TooFewBytes => "VMO contents too small",
132            Self::ChecksumMismatch { .. } => "ABI checksum mismatch",
133            Self::Unpersist(_) => "FIDL parsing error",
134        }
135    }
136}