1use crate::node::Node;
8use fidl::endpoints::ServerEnd;
9use fidl::prelude::*;
10use fidl_fuchsia_io as fio;
11use futures::StreamExt as _;
12use std::sync::Arc;
13use zx_status::Status;
14
15pub use vfs_macros::attribute_query;
16
17const FS_RIGHTS: fio::OpenFlags = fio::OPEN_RIGHTS;
19
20pub fn stricter_or_same_rights(parent_flags: fio::OpenFlags, flags: fio::OpenFlags) -> bool {
22 let parent_rights = parent_flags & FS_RIGHTS;
23 let rights = flags & FS_RIGHTS;
24 return !rights.intersects(!parent_rights);
25}
26
27pub fn inherit_rights_for_clone(
30 parent_flags: fio::OpenFlags,
31 mut flags: fio::OpenFlags,
32) -> Result<fio::OpenFlags, Status> {
33 if flags.intersects(fio::OpenFlags::CLONE_SAME_RIGHTS) && flags.intersects(FS_RIGHTS) {
34 return Err(Status::INVALID_ARGS);
35 }
36
37 flags |= parent_flags & (fio::OpenFlags::APPEND | fio::OpenFlags::NODE_REFERENCE);
41
42 if flags.intersects(fio::OpenFlags::CLONE_SAME_RIGHTS) {
46 flags &= !fio::OpenFlags::CLONE_SAME_RIGHTS;
47 flags |= parent_flags & FS_RIGHTS;
48 }
49
50 if !stricter_or_same_rights(parent_flags, flags) {
51 return Err(Status::ACCESS_DENIED);
52 }
53
54 flags &= !(fio::OpenFlags::POSIX_WRITABLE | fio::OpenFlags::POSIX_EXECUTABLE);
56
57 Ok(flags)
58}
59
60pub fn send_on_open_with_error(
73 describe: bool,
74 server_end: ServerEnd<fio::NodeMarker>,
75 status: Status,
76) {
77 if status == Status::OK {
78 panic!("send_on_open_with_error() should not be used to respond with Status::OK");
79 }
80
81 if !describe {
82 let _ = server_end.close_with_epitaph(status);
85 return;
86 }
87
88 let (_, control_handle) = server_end.into_stream_and_control_handle();
89 let _ = control_handle.send_on_open_(status.into_raw(), None);
91 control_handle.shutdown_with_epitaph(status);
92}
93
94pub trait IntoAny: std::any::Any {
100 fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync + 'static>;
102}
103
104impl<T: 'static + Send + Sync> IntoAny for T {
105 fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync + 'static> {
106 self as Arc<dyn std::any::Any + Send + Sync + 'static>
107 }
108}
109
110pub fn rights_to_posix_mode_bits(readable: bool, writable: bool, executable: bool) -> u32 {
114 return (if readable { libc::S_IRUSR } else { 0 }
115 | if writable { libc::S_IWUSR } else { 0 }
116 | if executable { libc::S_IXUSR } else { 0 })
117 .into();
118}
119
120pub async fn extended_attributes_sender(
121 iterator: ServerEnd<fio::ExtendedAttributeIteratorMarker>,
122 attributes: Vec<Vec<u8>>,
123) {
124 let mut stream = iterator.into_stream();
125
126 let mut chunks = attributes.chunks(fio::MAX_LIST_ATTRIBUTES_CHUNK as usize).peekable();
127
128 while let Some(Ok(fio::ExtendedAttributeIteratorRequest::GetNext { responder })) =
129 stream.next().await
130 {
131 let (chunk, last) = match chunks.next() {
132 Some(chunk) => (chunk, chunks.peek().is_none()),
133 None => (&[][..], true),
134 };
135 responder.send(Ok((chunk, last))).unwrap_or_else(|_error| {
136 #[cfg(any(test, feature = "use_log"))]
137 log::error!(_error:?; "list extended attributes failed to send a chunk");
138 });
139 if last {
140 break;
141 }
142 }
143}
144
145pub fn encode_extended_attribute_value(
146 value: Vec<u8>,
147) -> Result<fio::ExtendedAttributeValue, Status> {
148 let size = value.len() as u64;
149 if size > fio::MAX_INLINE_ATTRIBUTE_VALUE {
150 #[cfg(target_os = "fuchsia")]
151 {
152 let vmo = fidl::Vmo::create(size)?;
153 vmo.write(&value, 0)?;
154 Ok(fio::ExtendedAttributeValue::Buffer(vmo))
155 }
156 #[cfg(not(target_os = "fuchsia"))]
157 Err(Status::NOT_SUPPORTED)
158 } else {
159 Ok(fio::ExtendedAttributeValue::Bytes(value))
160 }
161}
162
163pub fn decode_extended_attribute_value(
164 value: fio::ExtendedAttributeValue,
165) -> Result<Vec<u8>, Status> {
166 match value {
167 fio::ExtendedAttributeValue::Bytes(val) => Ok(val),
168 #[cfg(target_os = "fuchsia")]
169 fio::ExtendedAttributeValue::Buffer(vmo) => {
170 let length = vmo.get_content_size()?;
171 vmo.read_to_vec(0, length)
172 }
173 #[cfg(not(target_os = "fuchsia"))]
174 fio::ExtendedAttributeValue::Buffer(_) => Err(Status::NOT_SUPPORTED),
175 fio::ExtendedAttributeValue::__SourceBreaking { .. } => Err(Status::NOT_SUPPORTED),
176 }
177}
178
179#[macro_export]
191macro_rules! attributes {
192 ($requested:expr,
193 Mutable {$($mut_a:ident: $mut_v:expr),* $(,)?},
194 Immutable {$($immut_a:ident: $immut_v:expr),* $(,)?}) => (
195 {
196 use $crate::common::attribute_query;
197 fio::NodeAttributes2 {
198 mutable_attributes: fio::MutableNodeAttributes {
199 $($mut_a: if $requested.contains(attribute_query!($mut_a)) {
200 Option::from($mut_v)
201 } else {
202 None
203 }),*,
204 ..Default::default()
205 },
206 immutable_attributes: fio::ImmutableNodeAttributes {
207 $($immut_a: if $requested.contains(attribute_query!($immut_a)) {
208 Option::from($immut_v)
209 } else {
210 None
211 }),*,
212 ..Default::default()
213 }
214 }
215 }
216 )
217}
218
219#[macro_export]
230macro_rules! immutable_attributes {
231 ($requested:expr,
232 Immutable {$($immut_a:ident: $immut_v:expr),* $(,)?}) => (
233 {
234 use $crate::common::attribute_query;
235 fio::NodeAttributes2 {
236 mutable_attributes: Default::default(),
237 immutable_attributes: fio::ImmutableNodeAttributes {
238 $($immut_a: if $requested.contains(attribute_query!($immut_a)) {
239 Option::from($immut_v)
240 } else {
241 None
242 }),*,
243 ..Default::default()
244 },
245 }
246 }
247 )
248}
249
250#[derive(PartialEq, Eq)]
252pub enum CreationMode {
253 Never,
255 AllowExisting,
257 Always,
259 UnnamedTemporary,
261 UnlinkableUnnamedTemporary,
263}
264
265pub(crate) fn io1_to_io2_attrs(
267 flags: fio::NodeAttributeFlags,
268 attrs: fio::NodeAttributes,
269) -> fio::MutableNodeAttributes {
270 fio::MutableNodeAttributes {
271 creation_time: flags
272 .contains(fio::NodeAttributeFlags::CREATION_TIME)
273 .then_some(attrs.creation_time),
274 modification_time: flags
275 .contains(fio::NodeAttributeFlags::MODIFICATION_TIME)
276 .then_some(attrs.modification_time),
277 ..Default::default()
278 }
279}
280
281const ALL_IO1_ATTRIBUTES: fio::NodeAttributesQuery = fio::NodeAttributesQuery::PROTOCOLS
283 .union(fio::NodeAttributesQuery::ABILITIES)
284 .union(fio::NodeAttributesQuery::ID)
285 .union(fio::NodeAttributesQuery::CONTENT_SIZE)
286 .union(fio::NodeAttributesQuery::STORAGE_SIZE)
287 .union(fio::NodeAttributesQuery::LINK_COUNT)
288 .union(fio::NodeAttributesQuery::CREATION_TIME)
289 .union(fio::NodeAttributesQuery::MODIFICATION_TIME);
290
291const DEFAULT_IO1_ATTRIBUTES: fio::NodeAttributes = fio::NodeAttributes {
293 mode: 0,
294 id: fio::INO_UNKNOWN,
295 content_size: 0,
296 storage_size: 0,
297 link_count: 0,
298 creation_time: 0,
299 modification_time: 0,
300};
301
302const DEFAULT_LINK_COUNT: u64 = 1;
303
304const fn approximate_posix_mode(
308 protocols: Option<fio::NodeProtocolKinds>,
309 abilities: fio::Abilities,
310) -> u32 {
311 let Some(protocols) = protocols else {
312 return 0;
313 };
314 match protocols {
315 fio::NodeProtocolKinds::DIRECTORY => {
316 let mut mode = libc::S_IFDIR;
317 if abilities.contains(fio::Abilities::ENUMERATE) {
318 mode |= libc::S_IRUSR;
319 }
320 if abilities.contains(fio::Abilities::MODIFY_DIRECTORY) {
321 mode |= libc::S_IWUSR;
322 }
323 if abilities.contains(fio::Abilities::TRAVERSE) {
324 mode |= libc::S_IXUSR;
325 }
326 mode
327 }
328 fio::NodeProtocolKinds::FILE => {
329 let mut mode = libc::S_IFREG;
330 if abilities.contains(fio::Abilities::READ_BYTES) {
331 mode |= libc::S_IRUSR;
332 }
333 if abilities.contains(fio::Abilities::WRITE_BYTES) {
334 mode |= libc::S_IWUSR;
335 }
336 if abilities.contains(fio::Abilities::EXECUTE) {
337 mode |= libc::S_IXUSR;
338 }
339 mode
340 }
341 fio::NodeProtocolKinds::CONNECTOR => fio::MODE_TYPE_SERVICE | libc::S_IRUSR | libc::S_IWUSR,
342 #[cfg(fuchsia_api_level_at_least = "HEAD")]
343 fio::NodeProtocolKinds::SYMLINK => libc::S_IFLNK | libc::S_IRUSR,
344 _ => 0,
345 }
346}
347
348pub async fn io2_to_io1_attrs<T: Node>(
352 node: &T,
353 rights: fio::Rights,
354) -> (Status, fio::NodeAttributes) {
355 if !rights.contains(fio::Rights::GET_ATTRIBUTES) {
356 return (Status::BAD_HANDLE, DEFAULT_IO1_ATTRIBUTES);
357 }
358
359 let attributes = node.get_attributes(ALL_IO1_ATTRIBUTES).await;
360 let Ok(fio::NodeAttributes2 {
361 mutable_attributes: mut_attrs,
362 immutable_attributes: immut_attrs,
363 }) = attributes
364 else {
365 return (attributes.unwrap_err(), DEFAULT_IO1_ATTRIBUTES);
366 };
367
368 (
369 Status::OK,
370 fio::NodeAttributes {
371 mode: mut_attrs.mode.unwrap_or_else(|| {
374 approximate_posix_mode(
375 immut_attrs.protocols,
376 immut_attrs.abilities.unwrap_or_default(),
377 )
378 }),
379 id: immut_attrs.id.unwrap_or(fio::INO_UNKNOWN),
380 content_size: immut_attrs.content_size.unwrap_or_default(),
381 storage_size: immut_attrs.storage_size.unwrap_or_default(),
382 link_count: immut_attrs.link_count.unwrap_or(DEFAULT_LINK_COUNT),
383 creation_time: mut_attrs.creation_time.unwrap_or_default(),
384 modification_time: mut_attrs.modification_time.unwrap_or_default(),
385 },
386 )
387}
388
389pub fn mutable_node_attributes_to_query(
390 attributes: &fio::MutableNodeAttributes,
391) -> fio::NodeAttributesQuery {
392 let mut query = fio::NodeAttributesQuery::empty();
393
394 if attributes.creation_time.is_some() {
395 query |= fio::NodeAttributesQuery::CREATION_TIME;
396 }
397 if attributes.modification_time.is_some() {
398 query |= fio::NodeAttributesQuery::MODIFICATION_TIME;
399 }
400 if attributes.access_time.is_some() {
401 query |= fio::NodeAttributesQuery::ACCESS_TIME;
402 }
403 if attributes.mode.is_some() {
404 query |= fio::NodeAttributesQuery::MODE;
405 }
406 if attributes.uid.is_some() {
407 query |= fio::NodeAttributesQuery::UID;
408 }
409 if attributes.gid.is_some() {
410 query |= fio::NodeAttributesQuery::GID;
411 }
412 if attributes.rdev.is_some() {
413 query |= fio::NodeAttributesQuery::RDEV;
414 }
415 query
416}
417
418#[cfg(test)]
419mod tests {
420 use super::inherit_rights_for_clone;
421
422 use fidl_fuchsia_io as fio;
423
424 macro_rules! irfc_ok {
428 ($parent_flags:expr, $flags:expr, $expected_new_flags:expr $(,)*) => {{
429 let res = inherit_rights_for_clone($parent_flags, $flags);
430 match res {
431 Ok(new_flags) => assert_eq!(
432 $expected_new_flags, new_flags,
433 "`inherit_rights_for_clone` returned unexpected set of flags.\n\
434 Expected: {:X}\n\
435 Actual: {:X}",
436 $expected_new_flags, new_flags
437 ),
438 Err(status) => panic!("`inherit_rights_for_clone` failed. Status: {status}"),
439 }
440 }};
441 }
442
443 #[test]
444 fn node_reference_is_inherited() {
445 irfc_ok!(
446 fio::OpenFlags::NODE_REFERENCE,
447 fio::OpenFlags::empty(),
448 fio::OpenFlags::NODE_REFERENCE
449 );
450 }
451}