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