1use crate::common::{
8 decode_extended_attribute_value, encode_extended_attribute_value, extended_attributes_sender,
9 inherit_rights_for_clone, send_on_open_with_error,
10};
11use crate::execution_scope::ExecutionScope;
12use crate::name::parse_name;
13use crate::node::Node;
14use crate::object_request::{run_synchronous_future_or_spawn, ConnectionCreator, Representation};
15use crate::request_handler::{RequestHandler, RequestListener};
16use crate::{ObjectRequest, ObjectRequestRef, ProtocolsExt, ToObjectRequest};
17use fidl::endpoints::{ControlHandle as _, Responder, ServerEnd};
18use fidl_fuchsia_io as fio;
19use std::future::{ready, Future};
20use std::ops::ControlFlow;
21use std::pin::Pin;
22use std::sync::Arc;
23use zx_status::Status;
24
25pub trait Symlink: Node {
26 fn read_target(&self) -> impl Future<Output = Result<Vec<u8>, Status>> + Send;
27
28 fn list_extended_attributes(
30 &self,
31 ) -> impl Future<Output = Result<Vec<Vec<u8>>, Status>> + Send {
32 ready(Err(Status::NOT_SUPPORTED))
33 }
34 fn get_extended_attribute(
35 &self,
36 _name: Vec<u8>,
37 ) -> impl Future<Output = Result<Vec<u8>, Status>> + Send {
38 ready(Err(Status::NOT_SUPPORTED))
39 }
40 fn set_extended_attribute(
41 &self,
42 _name: Vec<u8>,
43 _value: Vec<u8>,
44 _mode: fio::SetExtendedAttributeMode,
45 ) -> impl Future<Output = Result<(), Status>> + Send {
46 ready(Err(Status::NOT_SUPPORTED))
47 }
48 fn remove_extended_attribute(
49 &self,
50 _name: Vec<u8>,
51 ) -> impl Future<Output = Result<(), Status>> + Send {
52 ready(Err(Status::NOT_SUPPORTED))
53 }
54}
55
56pub struct Connection<T> {
57 scope: ExecutionScope,
58 symlink: Arc<T>,
59}
60
61pub struct SymlinkOptions;
62
63impl<T: Symlink> Connection<T> {
64 pub async fn create(
70 scope: ExecutionScope,
71 symlink: Arc<T>,
72 protocols: impl ProtocolsExt,
73 object_request: ObjectRequestRef<'_>,
74 ) -> Result<(), Status> {
75 let _options = protocols.to_symlink_options()?;
76 let connection = Self { scope: scope.clone(), symlink };
77 if let Ok(requests) = object_request.take().into_request_stream(&connection).await {
78 scope.spawn(RequestListener::new(requests, connection));
79 }
80 Ok(())
81 }
82
83 pub fn create_sync(
86 scope: ExecutionScope,
87 symlink: Arc<T>,
88 options: impl ProtocolsExt,
89 object_request: ObjectRequest,
90 ) {
91 run_synchronous_future_or_spawn(
92 scope.clone(),
93 object_request.handle_async(async |object_request| {
94 Self::create(scope, symlink, options, object_request).await
95 }),
96 )
97 }
98
99 async fn handle_request(&mut self, req: fio::SymlinkRequest) -> Result<bool, fidl::Error> {
101 match req {
102 #[cfg(fuchsia_api_level_at_least = "26")]
103 fio::SymlinkRequest::DeprecatedClone { flags, object, control_handle: _ } => {
104 self.handle_deprecated_clone(flags, object).await;
105 }
106 #[cfg(not(fuchsia_api_level_at_least = "26"))]
107 fio::SymlinkRequest::Clone { flags, object, control_handle: _ } => {
108 self.handle_deprecated_clone(flags, object).await;
109 }
110 #[cfg(fuchsia_api_level_at_least = "26")]
111 fio::SymlinkRequest::Clone { request, control_handle: _ } => {
112 self.handle_clone(ServerEnd::new(request.into_channel())).await;
113 }
114 #[cfg(not(fuchsia_api_level_at_least = "26"))]
115 fio::SymlinkRequest::Clone2 { request, control_handle: _ } => {
116 self.handle_clone(ServerEnd::new(request.into_channel())).await;
117 }
118 fio::SymlinkRequest::Close { responder } => {
119 responder.send(Ok(()))?;
120 return Ok(true);
121 }
122 fio::SymlinkRequest::LinkInto { dst_parent_token, dst, responder } => {
123 responder.send(
124 self.handle_link_into(dst_parent_token, dst).await.map_err(|s| s.into_raw()),
125 )?;
126 }
127 fio::SymlinkRequest::GetConnectionInfo { responder } => {
128 let rights = fio::Operations::GET_ATTRIBUTES;
130 responder
131 .send(fio::ConnectionInfo { rights: Some(rights), ..Default::default() })?;
132 }
133 fio::SymlinkRequest::Sync { responder } => {
134 responder.send(Ok(()))?;
135 }
136 fio::SymlinkRequest::GetAttr { responder } => {
137 let (status, attrs) = crate::common::io2_to_io1_attrs(
139 self.symlink.as_ref(),
140 fio::Rights::GET_ATTRIBUTES,
141 )
142 .await;
143 responder.send(status.into_raw(), &attrs)?;
144 }
145 fio::SymlinkRequest::SetAttr { responder, .. } => {
146 responder.send(Status::ACCESS_DENIED.into_raw())?;
147 }
148 fio::SymlinkRequest::GetAttributes { query, responder } => {
149 let attrs = self.symlink.get_attributes(query).await;
151 responder.send(
152 attrs
153 .as_ref()
154 .map(|attrs| (&attrs.mutable_attributes, &attrs.immutable_attributes))
155 .map_err(|status| status.into_raw()),
156 )?;
157 }
158 fio::SymlinkRequest::UpdateAttributes { payload: _, responder } => {
159 responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
160 }
161 fio::SymlinkRequest::ListExtendedAttributes { iterator, control_handle: _ } => {
162 self.handle_list_extended_attribute(iterator).await;
163 }
164 fio::SymlinkRequest::GetExtendedAttribute { responder, name } => {
165 let res = self.handle_get_extended_attribute(name).await.map_err(|s| s.into_raw());
166 responder.send(res)?;
167 }
168 fio::SymlinkRequest::SetExtendedAttribute { responder, name, value, mode } => {
169 let res = self
170 .handle_set_extended_attribute(name, value, mode)
171 .await
172 .map_err(|s| s.into_raw());
173 responder.send(res)?;
174 }
175 fio::SymlinkRequest::RemoveExtendedAttribute { responder, name } => {
176 let res =
177 self.handle_remove_extended_attribute(name).await.map_err(|s| s.into_raw());
178 responder.send(res)?;
179 }
180 fio::SymlinkRequest::Describe { responder } => match self.symlink.read_target().await {
181 Ok(target) => responder
182 .send(&fio::SymlinkInfo { target: Some(target), ..Default::default() })?,
183 Err(status) => {
184 responder.control_handle().shutdown_with_epitaph(status);
185 return Ok(true);
186 }
187 },
188 #[cfg(fuchsia_api_level_at_least = "NEXT")]
189 fio::SymlinkRequest::GetFlags { responder } => {
190 responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
191 }
192 #[cfg(fuchsia_api_level_at_least = "NEXT")]
193 fio::SymlinkRequest::SetFlags { flags: _, responder } => {
194 responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
195 }
196 #[cfg(fuchsia_api_level_at_least = "NEXT")]
197 fio::SymlinkRequest::DeprecatedGetFlags { responder } => {
198 responder.send(Status::NOT_SUPPORTED.into_raw(), fio::OpenFlags::empty())?;
199 }
200 #[cfg(fuchsia_api_level_at_least = "NEXT")]
201 fio::SymlinkRequest::DeprecatedSetFlags { responder, .. } => {
202 responder.send(Status::ACCESS_DENIED.into_raw())?;
203 }
204 #[cfg(not(fuchsia_api_level_at_least = "NEXT"))]
205 fio::SymlinkRequest::GetFlags { responder } => {
206 responder.send(Status::NOT_SUPPORTED.into_raw(), fio::OpenFlags::empty())?;
207 }
208 #[cfg(not(fuchsia_api_level_at_least = "NEXT"))]
209 fio::SymlinkRequest::SetFlags { responder, .. } => {
210 responder.send(Status::ACCESS_DENIED.into_raw())?;
211 }
212 fio::SymlinkRequest::Query { responder } => {
213 responder.send(fio::SYMLINK_PROTOCOL_NAME.as_bytes())?;
214 }
215 fio::SymlinkRequest::QueryFilesystem { responder } => {
216 match self.symlink.query_filesystem() {
217 Err(status) => responder.send(status.into_raw(), None)?,
218 Ok(info) => responder.send(0, Some(&info))?,
219 }
220 }
221 fio::SymlinkRequest::_UnknownMethod { ordinal: _ordinal, .. } => {
222 #[cfg(any(test, feature = "use_log"))]
223 log::warn!(_ordinal; "Received unknown method")
224 }
225 }
226 Ok(false)
227 }
228
229 async fn handle_deprecated_clone(
230 &mut self,
231 flags: fio::OpenFlags,
232 server_end: ServerEnd<fio::NodeMarker>,
233 ) {
234 let flags = match inherit_rights_for_clone(fio::OpenFlags::RIGHT_READABLE, flags) {
235 Ok(updated) => updated,
236 Err(status) => {
237 send_on_open_with_error(
238 flags.contains(fio::OpenFlags::DESCRIBE),
239 server_end,
240 status,
241 );
242 return;
243 }
244 };
245 flags
246 .to_object_request(server_end)
247 .handle_async(async |object_request| {
248 Self::create(self.scope.clone(), self.symlink.clone(), flags, object_request).await
249 })
250 .await;
251 }
252
253 async fn handle_clone(&mut self, server_end: ServerEnd<fio::SymlinkMarker>) {
254 let flags = fio::Flags::PROTOCOL_SYMLINK | fio::Flags::PERM_GET_ATTRIBUTES;
255 flags
256 .to_object_request(server_end)
257 .handle_async(async |object_request| {
258 Self::create(self.scope.clone(), self.symlink.clone(), flags, object_request).await
259 })
260 .await;
261 }
262
263 async fn handle_link_into(
264 &mut self,
265 target_parent_token: fidl::Event,
266 target_name: String,
267 ) -> Result<(), Status> {
268 let target_name = parse_name(target_name).map_err(|_| Status::INVALID_ARGS)?;
269
270 let target_parent = self
271 .scope
272 .token_registry()
273 .get_owner(target_parent_token.into())?
274 .ok_or(Err(Status::NOT_FOUND))?;
275
276 self.symlink.clone().link_into(target_parent, target_name).await
277 }
278
279 async fn handle_list_extended_attribute(
280 &self,
281 iterator: ServerEnd<fio::ExtendedAttributeIteratorMarker>,
282 ) {
283 let attributes = match self.symlink.list_extended_attributes().await {
284 Ok(attributes) => attributes,
285 Err(status) => {
286 #[cfg(any(test, feature = "use_log"))]
287 log::error!(status:?; "list extended attributes failed");
288 iterator.close_with_epitaph(status).unwrap_or_else(|_error| {
289 #[cfg(any(test, feature = "use_log"))]
290 log::error!(_error:?; "failed to send epitaph")
291 });
292 return;
293 }
294 };
295 self.scope.spawn(extended_attributes_sender(iterator, attributes));
296 }
297
298 async fn handle_get_extended_attribute(
299 &self,
300 name: Vec<u8>,
301 ) -> Result<fio::ExtendedAttributeValue, Status> {
302 let value = self.symlink.get_extended_attribute(name).await?;
303 encode_extended_attribute_value(value)
304 }
305
306 async fn handle_set_extended_attribute(
307 &self,
308 name: Vec<u8>,
309 value: fio::ExtendedAttributeValue,
310 mode: fio::SetExtendedAttributeMode,
311 ) -> Result<(), Status> {
312 if name.contains(&0) {
313 return Err(Status::INVALID_ARGS);
314 }
315 let val = decode_extended_attribute_value(value)?;
316 self.symlink.set_extended_attribute(name, val, mode).await
317 }
318
319 async fn handle_remove_extended_attribute(&self, name: Vec<u8>) -> Result<(), Status> {
320 self.symlink.remove_extended_attribute(name).await
321 }
322}
323
324impl<T: Symlink> RequestHandler for Connection<T> {
325 type Request = Result<fio::SymlinkRequest, fidl::Error>;
326
327 async fn handle_request(self: Pin<&mut Self>, request: Self::Request) -> ControlFlow<()> {
328 let this = self.get_mut();
329 let _guard = this.scope.active_guard();
330 match request {
331 Ok(request) => match this.handle_request(request).await {
332 Ok(false) => ControlFlow::Continue(()),
333 Ok(true) | Err(_) => ControlFlow::Break(()),
334 },
335 Err(_) => ControlFlow::Break(()),
336 }
337 }
338}
339
340impl<T: Symlink> Representation for Connection<T> {
341 type Protocol = fio::SymlinkMarker;
342
343 async fn get_representation(
344 &self,
345 requested_attributes: fio::NodeAttributesQuery,
346 ) -> Result<fio::Representation, Status> {
347 Ok(fio::Representation::Symlink(fio::SymlinkInfo {
348 attributes: if requested_attributes.is_empty() {
349 None
350 } else {
351 Some(self.symlink.get_attributes(requested_attributes).await?)
352 },
353 target: Some(self.symlink.read_target().await?),
354 ..Default::default()
355 }))
356 }
357
358 async fn node_info(&self) -> Result<fio::NodeInfoDeprecated, Status> {
359 Ok(fio::NodeInfoDeprecated::Symlink(fio::SymlinkObject {
360 target: self.symlink.read_target().await?,
361 }))
362 }
363}
364
365impl<T: Symlink> ConnectionCreator<T> for Connection<T> {
366 async fn create<'a>(
367 scope: ExecutionScope,
368 node: Arc<T>,
369 protocols: impl ProtocolsExt,
370 object_request: ObjectRequestRef<'a>,
371 ) -> Result<(), Status> {
372 Self::create(scope, node, protocols, object_request).await
373 }
374}
375
376pub fn serve(
378 link: Arc<impl Symlink>,
379 scope: ExecutionScope,
380 protocols: impl ProtocolsExt,
381 object_request: ObjectRequestRef<'_>,
382) -> Result<(), Status> {
383 if protocols.is_node() {
384 let options = protocols.to_node_options(link.entry_info().type_())?;
385 link.open_as_node(scope, options, object_request)
386 } else {
387 Connection::create_sync(scope, link, protocols, object_request.take());
388 Ok(())
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::{Connection, Symlink};
395 use crate::common::rights_to_posix_mode_bits;
396 use crate::directory::entry::{EntryInfo, GetEntryInfo};
397 use crate::execution_scope::ExecutionScope;
398 use crate::node::Node;
399 use crate::{immutable_attributes, ToObjectRequest};
400 use assert_matches::assert_matches;
401 use fidl::endpoints::{create_proxy, ServerEnd};
402 use fidl_fuchsia_io as fio;
403 use fuchsia_sync::Mutex;
404 use futures::StreamExt;
405 use std::collections::HashMap;
406 use std::sync::Arc;
407 use zx_status::Status;
408
409 const TARGET: &[u8] = b"target";
410
411 struct TestSymlink {
412 xattrs: Mutex<HashMap<Vec<u8>, Vec<u8>>>,
413 }
414
415 impl TestSymlink {
416 fn new() -> Self {
417 TestSymlink { xattrs: Mutex::new(HashMap::new()) }
418 }
419 }
420
421 impl Symlink for TestSymlink {
422 async fn read_target(&self) -> Result<Vec<u8>, Status> {
423 Ok(TARGET.to_vec())
424 }
425 async fn list_extended_attributes(&self) -> Result<Vec<Vec<u8>>, Status> {
426 let map = self.xattrs.lock();
427 Ok(map.values().map(|x| x.clone()).collect())
428 }
429 async fn get_extended_attribute(&self, name: Vec<u8>) -> Result<Vec<u8>, Status> {
430 let map = self.xattrs.lock();
431 map.get(&name).map(|x| x.clone()).ok_or(Status::NOT_FOUND)
432 }
433 async fn set_extended_attribute(
434 &self,
435 name: Vec<u8>,
436 value: Vec<u8>,
437 _mode: fio::SetExtendedAttributeMode,
438 ) -> Result<(), Status> {
439 let mut map = self.xattrs.lock();
440 map.insert(name, value);
443 Ok(())
444 }
445 async fn remove_extended_attribute(&self, name: Vec<u8>) -> Result<(), Status> {
446 let mut map = self.xattrs.lock();
447 map.remove(&name);
448 Ok(())
449 }
450 }
451
452 impl Node for TestSymlink {
453 async fn get_attributes(
454 &self,
455 requested_attributes: fio::NodeAttributesQuery,
456 ) -> Result<fio::NodeAttributes2, Status> {
457 Ok(immutable_attributes!(
458 requested_attributes,
459 Immutable {
460 content_size: TARGET.len() as u64,
461 storage_size: TARGET.len() as u64,
462 protocols: fio::NodeProtocolKinds::SYMLINK,
463 abilities: fio::Abilities::GET_ATTRIBUTES,
464 }
465 ))
466 }
467 }
468
469 impl GetEntryInfo for TestSymlink {
470 fn entry_info(&self) -> EntryInfo {
471 EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::Symlink)
472 }
473 }
474
475 async fn serve_test_symlink() -> fio::SymlinkProxy {
476 let (client_end, server_end) = create_proxy::<fio::SymlinkMarker>();
477 let flags = fio::PERM_READABLE | fio::Flags::PROTOCOL_SYMLINK;
478
479 Connection::create_sync(
480 ExecutionScope::new(),
481 Arc::new(TestSymlink::new()),
482 flags,
483 flags.to_object_request(server_end),
484 );
485
486 client_end
487 }
488
489 #[fuchsia::test]
490 async fn test_read_target() {
491 let client_end = serve_test_symlink().await;
492
493 assert_eq!(
494 client_end.describe().await.expect("fidl failed").target.expect("missing target"),
495 b"target"
496 );
497 }
498
499 #[fuchsia::test]
500 async fn test_validate_flags() {
501 let scope = ExecutionScope::new();
502
503 let check = |mut flags: fio::OpenFlags| {
504 let (client_end, server_end) = create_proxy::<fio::SymlinkMarker>();
505 flags |= fio::OpenFlags::DESCRIBE;
506 flags.to_object_request(server_end).create_connection_sync::<Connection<_>, _>(
507 scope.clone(),
508 Arc::new(TestSymlink::new()),
509 flags,
510 );
511
512 async move {
513 Status::from_raw(
514 client_end
515 .take_event_stream()
516 .next()
517 .await
518 .expect("no event")
519 .expect("next failed")
520 .into_on_open_()
521 .expect("expected OnOpen")
522 .0,
523 )
524 }
525 };
526
527 for flags in [
528 fio::OpenFlags::RIGHT_WRITABLE,
529 fio::OpenFlags::RIGHT_EXECUTABLE,
530 fio::OpenFlags::CREATE,
531 fio::OpenFlags::CREATE_IF_ABSENT,
532 fio::OpenFlags::TRUNCATE,
533 fio::OpenFlags::APPEND,
534 fio::OpenFlags::POSIX_WRITABLE,
535 fio::OpenFlags::POSIX_EXECUTABLE,
536 fio::OpenFlags::CLONE_SAME_RIGHTS,
537 fio::OpenFlags::BLOCK_DEVICE,
538 ] {
539 assert_eq!(check(flags).await, Status::INVALID_ARGS, "{flags:?}");
540 }
541
542 assert_eq!(
543 check(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::NOT_DIRECTORY).await,
544 Status::OK
545 );
546 }
547
548 #[fuchsia::test]
549 async fn test_get_attr() {
550 let client_end = serve_test_symlink().await;
551
552 assert_matches!(
553 client_end.get_attr().await.expect("fidl failed"),
554 (
555 0,
556 fio::NodeAttributes {
557 mode,
558 id: fio::INO_UNKNOWN,
559 content_size: 6,
560 storage_size: 6,
561 link_count: 1,
562 creation_time: 0,
563 modification_time: 0,
564 }
565 ) if mode == fio::MODE_TYPE_SYMLINK
566 | rights_to_posix_mode_bits(true, false, false)
567 );
568 }
569
570 #[fuchsia::test]
571 async fn test_clone() {
572 let client_end = serve_test_symlink().await;
573
574 let orig_attrs = client_end
575 .get_attributes(fio::NodeAttributesQuery::all())
576 .await
577 .expect("fidl failed")
578 .unwrap();
579 let (cloned_client, cloned_server) = create_proxy::<fio::SymlinkMarker>();
581 client_end.clone(ServerEnd::new(cloned_server.into_channel())).unwrap();
582 let cloned_attrs = cloned_client
583 .get_attributes(fio::NodeAttributesQuery::all())
584 .await
585 .expect("fidl failed")
586 .unwrap();
587 assert_eq!(orig_attrs, cloned_attrs);
588 }
589
590 #[fuchsia::test]
591 async fn test_describe() {
592 let client_end = serve_test_symlink().await;
593
594 assert_matches!(
595 client_end.describe().await.expect("fidl failed"),
596 fio::SymlinkInfo {
597 target: Some(target),
598 ..
599 } if target == b"target"
600 );
601 }
602
603 #[fuchsia::test]
604 async fn test_xattrs() {
605 let client_end = serve_test_symlink().await;
606
607 client_end
608 .set_extended_attribute(
609 b"foo",
610 fio::ExtendedAttributeValue::Bytes(b"bar".to_vec()),
611 fio::SetExtendedAttributeMode::Set,
612 )
613 .await
614 .unwrap()
615 .unwrap();
616 assert_eq!(
617 client_end.get_extended_attribute(b"foo").await.unwrap().unwrap(),
618 fio::ExtendedAttributeValue::Bytes(b"bar".to_vec()),
619 );
620 let (iterator_client_end, iterator_server_end) =
621 create_proxy::<fio::ExtendedAttributeIteratorMarker>();
622 client_end.list_extended_attributes(iterator_server_end).unwrap();
623 assert_eq!(
624 iterator_client_end.get_next().await.unwrap().unwrap(),
625 (vec![b"bar".to_vec()], true)
626 );
627 client_end.remove_extended_attribute(b"foo").await.unwrap().unwrap();
628 assert_eq!(
629 client_end.get_extended_attribute(b"foo").await.unwrap().unwrap_err(),
630 Status::NOT_FOUND.into_raw(),
631 );
632 }
633}