vfs/
symlink.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Server support for symbolic links.
6
7use 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    // Extended attributes for symlinks.
29    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    /// Creates a new connection to serve the symlink. The symlink will be served from a new async
65    /// `Task`, not from the current `Task`. Errors in constructing the connection are not
66    /// guaranteed to be returned, they may be sent directly to the client end of the connection.
67    /// This method should be called from within an `ObjectRequest` handler to ensure that errors
68    /// are sent to the client end of the connection.
69    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    /// Similar to `create` but optimized for symlinks whose implementation is synchronous and
84    /// creating the connection is being done from a non-async context.
85    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    // Returns true if the connection should terminate.
100    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                // TODO(https://fxbug.dev/293947862): Restrict GET_ATTRIBUTES.
129                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                // TODO(https://fxbug.dev/293947862): Restrict GET_ATTRIBUTES.
138                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                // TODO(https://fxbug.dev/293947862): Restrict GET_ATTRIBUTES.
150                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, .. } => {
222                log::warn!(ordinal; "Received unknown method")
223            }
224        }
225        Ok(false)
226    }
227
228    async fn handle_deprecated_clone(
229        &mut self,
230        flags: fio::OpenFlags,
231        server_end: ServerEnd<fio::NodeMarker>,
232    ) {
233        let flags = match inherit_rights_for_clone(fio::OpenFlags::RIGHT_READABLE, flags) {
234            Ok(updated) => updated,
235            Err(status) => {
236                send_on_open_with_error(
237                    flags.contains(fio::OpenFlags::DESCRIBE),
238                    server_end,
239                    status,
240                );
241                return;
242            }
243        };
244        flags
245            .to_object_request(server_end)
246            .handle_async(async |object_request| {
247                Self::create(self.scope.clone(), self.symlink.clone(), flags, object_request).await
248            })
249            .await;
250    }
251
252    async fn handle_clone(&mut self, server_end: ServerEnd<fio::SymlinkMarker>) {
253        let flags = fio::Flags::PROTOCOL_SYMLINK | fio::Flags::PERM_GET_ATTRIBUTES;
254        flags
255            .to_object_request(server_end)
256            .handle_async(async |object_request| {
257                Self::create(self.scope.clone(), self.symlink.clone(), flags, object_request).await
258            })
259            .await;
260    }
261
262    async fn handle_link_into(
263        &mut self,
264        target_parent_token: fidl::Event,
265        target_name: String,
266    ) -> Result<(), Status> {
267        let target_name = parse_name(target_name).map_err(|_| Status::INVALID_ARGS)?;
268
269        let target_parent = self
270            .scope
271            .token_registry()
272            .get_owner(target_parent_token.into())?
273            .ok_or(Err(Status::NOT_FOUND))?;
274
275        self.symlink.clone().link_into(target_parent, target_name).await
276    }
277
278    async fn handle_list_extended_attribute(
279        &self,
280        iterator: ServerEnd<fio::ExtendedAttributeIteratorMarker>,
281    ) {
282        let attributes = match self.symlink.list_extended_attributes().await {
283            Ok(attributes) => attributes,
284            Err(status) => {
285                log::error!(status:?; "list extended attributes failed");
286                iterator
287                    .close_with_epitaph(status)
288                    .unwrap_or_else(|error| log::error!(error:?; "failed to send epitaph"));
289                return;
290            }
291        };
292        self.scope.spawn(extended_attributes_sender(iterator, attributes));
293    }
294
295    async fn handle_get_extended_attribute(
296        &self,
297        name: Vec<u8>,
298    ) -> Result<fio::ExtendedAttributeValue, Status> {
299        let value = self.symlink.get_extended_attribute(name).await?;
300        encode_extended_attribute_value(value)
301    }
302
303    async fn handle_set_extended_attribute(
304        &self,
305        name: Vec<u8>,
306        value: fio::ExtendedAttributeValue,
307        mode: fio::SetExtendedAttributeMode,
308    ) -> Result<(), Status> {
309        if name.contains(&0) {
310            return Err(Status::INVALID_ARGS);
311        }
312        let val = decode_extended_attribute_value(value)?;
313        self.symlink.set_extended_attribute(name, val, mode).await
314    }
315
316    async fn handle_remove_extended_attribute(&self, name: Vec<u8>) -> Result<(), Status> {
317        self.symlink.remove_extended_attribute(name).await
318    }
319}
320
321impl<T: Symlink> RequestHandler for Connection<T> {
322    type Request = Result<fio::SymlinkRequest, fidl::Error>;
323
324    async fn handle_request(self: Pin<&mut Self>, request: Self::Request) -> ControlFlow<()> {
325        let this = self.get_mut();
326        let _guard = this.scope.active_guard();
327        match request {
328            Ok(request) => match this.handle_request(request).await {
329                Ok(false) => ControlFlow::Continue(()),
330                Ok(true) | Err(_) => ControlFlow::Break(()),
331            },
332            Err(_) => ControlFlow::Break(()),
333        }
334    }
335}
336
337impl<T: Symlink> Representation for Connection<T> {
338    type Protocol = fio::SymlinkMarker;
339
340    async fn get_representation(
341        &self,
342        requested_attributes: fio::NodeAttributesQuery,
343    ) -> Result<fio::Representation, Status> {
344        Ok(fio::Representation::Symlink(fio::SymlinkInfo {
345            attributes: if requested_attributes.is_empty() {
346                None
347            } else {
348                Some(self.symlink.get_attributes(requested_attributes).await?)
349            },
350            target: Some(self.symlink.read_target().await?),
351            ..Default::default()
352        }))
353    }
354
355    async fn node_info(&self) -> Result<fio::NodeInfoDeprecated, Status> {
356        Ok(fio::NodeInfoDeprecated::Symlink(fio::SymlinkObject {
357            target: self.symlink.read_target().await?,
358        }))
359    }
360}
361
362impl<T: Symlink> ConnectionCreator<T> for Connection<T> {
363    async fn create<'a>(
364        scope: ExecutionScope,
365        node: Arc<T>,
366        protocols: impl ProtocolsExt,
367        object_request: ObjectRequestRef<'a>,
368    ) -> Result<(), Status> {
369        Self::create(scope, node, protocols, object_request).await
370    }
371}
372
373/// Helper to open a symlink or node as required.
374pub fn serve(
375    link: Arc<impl Symlink>,
376    scope: ExecutionScope,
377    protocols: impl ProtocolsExt,
378    object_request: ObjectRequestRef<'_>,
379) -> Result<(), Status> {
380    if protocols.is_node() {
381        let options = protocols.to_node_options(link.entry_info().type_())?;
382        link.open_as_node(scope, options, object_request)
383    } else {
384        Connection::create_sync(scope, link, protocols, object_request.take());
385        Ok(())
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::{Connection, Symlink};
392    use crate::common::rights_to_posix_mode_bits;
393    use crate::directory::entry::{EntryInfo, GetEntryInfo};
394    use crate::execution_scope::ExecutionScope;
395    use crate::node::Node;
396    use crate::{immutable_attributes, ToObjectRequest};
397    use assert_matches::assert_matches;
398    use fidl::endpoints::{create_proxy, ServerEnd};
399    use fidl_fuchsia_io as fio;
400    use futures::StreamExt;
401    use std::collections::HashMap;
402    use std::sync::{Arc, Mutex};
403    use zx_status::Status;
404
405    const TARGET: &[u8] = b"target";
406
407    struct TestSymlink {
408        xattrs: Mutex<HashMap<Vec<u8>, Vec<u8>>>,
409    }
410
411    impl TestSymlink {
412        fn new() -> Self {
413            TestSymlink { xattrs: Mutex::new(HashMap::new()) }
414        }
415    }
416
417    impl Symlink for TestSymlink {
418        async fn read_target(&self) -> Result<Vec<u8>, Status> {
419            Ok(TARGET.to_vec())
420        }
421        async fn list_extended_attributes(&self) -> Result<Vec<Vec<u8>>, Status> {
422            let map = self.xattrs.lock().unwrap();
423            Ok(map.values().map(|x| x.clone()).collect())
424        }
425        async fn get_extended_attribute(&self, name: Vec<u8>) -> Result<Vec<u8>, Status> {
426            let map = self.xattrs.lock().unwrap();
427            map.get(&name).map(|x| x.clone()).ok_or(Status::NOT_FOUND)
428        }
429        async fn set_extended_attribute(
430            &self,
431            name: Vec<u8>,
432            value: Vec<u8>,
433            _mode: fio::SetExtendedAttributeMode,
434        ) -> Result<(), Status> {
435            let mut map = self.xattrs.lock().unwrap();
436            // Don't bother replicating the mode behavior, we just care that this method is hooked
437            // up at all.
438            map.insert(name, value);
439            Ok(())
440        }
441        async fn remove_extended_attribute(&self, name: Vec<u8>) -> Result<(), Status> {
442            let mut map = self.xattrs.lock().unwrap();
443            map.remove(&name);
444            Ok(())
445        }
446    }
447
448    impl Node for TestSymlink {
449        async fn get_attributes(
450            &self,
451            requested_attributes: fio::NodeAttributesQuery,
452        ) -> Result<fio::NodeAttributes2, Status> {
453            Ok(immutable_attributes!(
454                requested_attributes,
455                Immutable {
456                    content_size: TARGET.len() as u64,
457                    storage_size: TARGET.len() as u64,
458                    protocols: fio::NodeProtocolKinds::SYMLINK,
459                    abilities: fio::Abilities::GET_ATTRIBUTES,
460                }
461            ))
462        }
463    }
464
465    impl GetEntryInfo for TestSymlink {
466        fn entry_info(&self) -> EntryInfo {
467            EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::Symlink)
468        }
469    }
470
471    async fn serve_test_symlink() -> fio::SymlinkProxy {
472        let (client_end, server_end) = create_proxy::<fio::SymlinkMarker>();
473        let flags = fio::PERM_READABLE | fio::Flags::PROTOCOL_SYMLINK;
474
475        Connection::create_sync(
476            ExecutionScope::new(),
477            Arc::new(TestSymlink::new()),
478            flags,
479            flags.to_object_request(server_end),
480        );
481
482        client_end
483    }
484
485    #[fuchsia::test]
486    async fn test_read_target() {
487        let client_end = serve_test_symlink().await;
488
489        assert_eq!(
490            client_end.describe().await.expect("fidl failed").target.expect("missing target"),
491            b"target"
492        );
493    }
494
495    #[fuchsia::test]
496    async fn test_validate_flags() {
497        let scope = ExecutionScope::new();
498
499        let check = |mut flags: fio::OpenFlags| {
500            let (client_end, server_end) = create_proxy::<fio::SymlinkMarker>();
501            flags |= fio::OpenFlags::DESCRIBE;
502            flags.to_object_request(server_end).create_connection_sync::<Connection<_>, _>(
503                scope.clone(),
504                Arc::new(TestSymlink::new()),
505                flags,
506            );
507
508            async move {
509                Status::from_raw(
510                    client_end
511                        .take_event_stream()
512                        .next()
513                        .await
514                        .expect("no event")
515                        .expect("next failed")
516                        .into_on_open_()
517                        .expect("expected OnOpen")
518                        .0,
519                )
520            }
521        };
522
523        for flags in [
524            fio::OpenFlags::RIGHT_WRITABLE,
525            fio::OpenFlags::RIGHT_EXECUTABLE,
526            fio::OpenFlags::CREATE,
527            fio::OpenFlags::CREATE_IF_ABSENT,
528            fio::OpenFlags::TRUNCATE,
529            fio::OpenFlags::APPEND,
530            fio::OpenFlags::POSIX_WRITABLE,
531            fio::OpenFlags::POSIX_EXECUTABLE,
532            fio::OpenFlags::CLONE_SAME_RIGHTS,
533            fio::OpenFlags::BLOCK_DEVICE,
534        ] {
535            assert_eq!(check(flags).await, Status::INVALID_ARGS, "{flags:?}");
536        }
537
538        assert_eq!(
539            check(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::NOT_DIRECTORY).await,
540            Status::OK
541        );
542    }
543
544    #[fuchsia::test]
545    async fn test_get_attr() {
546        let client_end = serve_test_symlink().await;
547
548        assert_matches!(
549            client_end.get_attr().await.expect("fidl failed"),
550            (
551                0,
552                fio::NodeAttributes {
553                    mode,
554                    id: fio::INO_UNKNOWN,
555                    content_size: 6,
556                    storage_size: 6,
557                    link_count: 1,
558                    creation_time: 0,
559                    modification_time: 0,
560                }
561            ) if mode == fio::MODE_TYPE_SYMLINK
562                | rights_to_posix_mode_bits(/*r*/ true, /*w*/ false, /*x*/ false)
563        );
564    }
565
566    #[fuchsia::test]
567    async fn test_clone() {
568        let client_end = serve_test_symlink().await;
569
570        let orig_attrs = client_end
571            .get_attributes(fio::NodeAttributesQuery::all())
572            .await
573            .expect("fidl failed")
574            .unwrap();
575        // Clone the original connection and query it's attributes, which should match the original.
576        let (cloned_client, cloned_server) = create_proxy::<fio::SymlinkMarker>();
577        client_end.clone(ServerEnd::new(cloned_server.into_channel())).unwrap();
578        let cloned_attrs = cloned_client
579            .get_attributes(fio::NodeAttributesQuery::all())
580            .await
581            .expect("fidl failed")
582            .unwrap();
583        assert_eq!(orig_attrs, cloned_attrs);
584    }
585
586    #[fuchsia::test]
587    async fn test_describe() {
588        let client_end = serve_test_symlink().await;
589
590        assert_matches!(
591            client_end.describe().await.expect("fidl failed"),
592            fio::SymlinkInfo {
593                target: Some(target),
594                ..
595            } if target == b"target"
596        );
597    }
598
599    #[fuchsia::test]
600    async fn test_xattrs() {
601        let client_end = serve_test_symlink().await;
602
603        client_end
604            .set_extended_attribute(
605                b"foo",
606                fio::ExtendedAttributeValue::Bytes(b"bar".to_vec()),
607                fio::SetExtendedAttributeMode::Set,
608            )
609            .await
610            .unwrap()
611            .unwrap();
612        assert_eq!(
613            client_end.get_extended_attribute(b"foo").await.unwrap().unwrap(),
614            fio::ExtendedAttributeValue::Bytes(b"bar".to_vec()),
615        );
616        let (iterator_client_end, iterator_server_end) =
617            create_proxy::<fio::ExtendedAttributeIteratorMarker>();
618        client_end.list_extended_attributes(iterator_server_end).unwrap();
619        assert_eq!(
620            iterator_client_end.get_next().await.unwrap().unwrap(),
621            (vec![b"bar".to_vec()], true)
622        );
623        client_end.remove_extended_attribute(b"foo").await.unwrap().unwrap();
624        assert_eq!(
625            client_end.get_extended_attribute(b"foo").await.unwrap().unwrap_err(),
626            Status::NOT_FOUND.into_raw(),
627        );
628    }
629}