fdf_component/
incoming.rs

1// Copyright 2024 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
5use std::marker::PhantomData;
6
7use anyhow::{Context, Error, anyhow};
8use cm_types::{IterablePath, RelativePath};
9use fdf_sys::fdf_token_transfer;
10use fidl::endpoints::{DiscoverableProtocolMarker, ServiceMarker, ServiceProxy};
11use fidl_fuchsia_io as fio;
12use fidl_fuchsia_io::Flags;
13use fidl_next_bind::Service;
14use fuchsia_component::client::{Connect, connect_to_service_instance_at_dir_svc};
15use fuchsia_component::directory::{AsRefDirectory, Directory, open_directory_async};
16use fuchsia_component::{DEFAULT_SERVICE_INSTANCE, SVC_DIR};
17use log::error;
18use namespace::{Entry, Namespace};
19use zx::{HandleBased, Status};
20
21/// Implements access to the incoming namespace for a driver. It provides methods
22/// for accessing incoming protocols and services by either their marker or proxy
23/// types, and can be used as a [`Directory`] with the functions in
24/// [`fuchsia_component::client`].
25pub struct Incoming(Vec<Entry>);
26
27impl Incoming {
28    /// Connects to the protocol in the service instance's path in the incoming namespace. Logs and
29    /// returns a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
30    pub fn connect_protocol<T: Connect>(&self) -> Result<T, Status> {
31        T::connect_at_dir_svc(&self).map_err(|e| {
32            error!(
33                "Failed to connect to discoverable protocol `{}`: {e}",
34                T::Protocol::PROTOCOL_NAME
35            );
36            Status::CONNECTION_REFUSED
37        })
38    }
39
40    /// Creates a connector to the given service's default instance by its marker type. This can be
41    /// convenient when the compiler can't deduce the [`ServiceProxy`] type on its own.
42    ///
43    /// See [`ServiceConnector`] for more about what you can do with the connector.
44    ///
45    /// # Example
46    ///
47    /// ```ignore
48    /// let service = context.incoming.service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker).connect()?;
49    /// let device = service.connect_to_device()?;
50    /// ```
51    pub fn service_marker<M: ServiceMarker>(&self, _marker: M) -> ServiceConnector<'_, M::Proxy> {
52        ServiceConnector { incoming: self, instance: DEFAULT_SERVICE_INSTANCE, _p: PhantomData }
53    }
54
55    /// Creates a connector to the given service's default instance by its proxy type. This can be
56    /// convenient when the compiler can deduce the [`ServiceProxy`] type on its own.
57    ///
58    /// See [`ServiceConnector`] for more about what you can do with the connector.
59    ///
60    /// # Example
61    ///
62    /// ```ignore
63    /// struct MyProxies {
64    ///     i2c_service: fidl_fuchsia_hardware_i2c::ServiceProxy,
65    /// }
66    /// let proxies = MyProxies {
67    ///     i2c_service: context.incoming.service().connect()?;
68    /// };
69    /// ```
70    pub fn service<P>(&self) -> ServiceConnector<'_, P> {
71        ServiceConnector { incoming: self, instance: DEFAULT_SERVICE_INSTANCE, _p: PhantomData }
72    }
73}
74
75/// A builder for connecting to an aggregated service instance in the driver's incoming namespace.
76/// By default, it will connect to the default instance, named `default`. You can override this
77/// by calling [`Self::instance`].
78pub struct ServiceConnector<'incoming, ServiceProxy> {
79    incoming: &'incoming Incoming,
80    instance: &'incoming str,
81    _p: PhantomData<ServiceProxy>,
82}
83
84impl<'a, S> ServiceConnector<'a, S> {
85    /// Overrides the instance name to connect to when [`Self::connect`] is called.
86    pub fn instance(self, instance: &'a str) -> Self {
87        let Self { incoming, _p, .. } = self;
88        Self { incoming, instance, _p }
89    }
90}
91
92impl<'a, S: ServiceProxy> ServiceConnector<'a, S>
93where
94    S::Service: ServiceMarker,
95{
96    /// Connects to the service instance's path in the incoming namespace. Logs and returns
97    /// a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
98    pub fn connect(self) -> Result<S, Status> {
99        connect_to_service_instance_at_dir_svc::<S::Service>(self.incoming, self.instance).map_err(
100            |e| {
101                error!(
102                    "Failed to connect to aggregated service connector `{}`, instance `{}`: {e}",
103                    S::Service::SERVICE_NAME,
104                    self.instance
105                );
106                Status::CONNECTION_REFUSED
107            },
108        )
109    }
110}
111
112/// Used with [`ServiceHandlerAdapter`] as a connector to members of a service instance.
113pub struct ServiceMemberConnector(fio::DirectoryProxy);
114
115fn connect(
116    dir: &fio::DirectoryProxy,
117    member: &str,
118    server_end: zx::Channel,
119) -> Result<(), fidl::Error> {
120    #[cfg(fuchsia_api_level_at_least = "27")]
121    return dir.open(member, fio::Flags::PROTOCOL_SERVICE, &fio::Options::default(), server_end);
122    #[cfg(not(fuchsia_api_level_at_least = "27"))]
123    return dir.open3(member, fio::Flags::PROTOCOL_SERVICE, &fio::Options::default(), server_end);
124}
125
126impl fidl_next_protocol::ServiceConnector<zx::Channel> for ServiceMemberConnector {
127    type Error = fidl::Error;
128    fn connect_to_member(&self, member: &str, server_end: zx::Channel) -> Result<(), Self::Error> {
129        connect(&self.0, member, server_end)
130    }
131}
132
133impl fidl_next_protocol::ServiceConnector<fdf_fidl::DriverChannel> for ServiceMemberConnector {
134    type Error = Status;
135    fn connect_to_member(
136        &self,
137        member: &str,
138        server_end: fdf_fidl::DriverChannel,
139    ) -> Result<(), Self::Error> {
140        let (client_token, server_token) = zx::Channel::create();
141        connect(&self.0, member, server_token).map_err(|err| {
142            error!("Failed to connect to service member {member}: {err:?}");
143            Status::CONNECTION_REFUSED
144        })?;
145        // SAFETY: client_token and server_end are valid by construction and `fdf_token_transfer`
146        // consumes both handles and does not interact with rust memory.
147        Status::ok(unsafe {
148            fdf_token_transfer(
149                client_token.into_raw(),
150                server_end.into_driver_handle().into_raw().get(),
151            )
152        })
153    }
154}
155
156/// A type alias representing a service instance with members that can be connected to using the
157/// [`fidl_next`] bindings.
158pub type ServiceInstance<S> = fidl_next_bind::ServiceConnector<S, ServiceMemberConnector>;
159
160impl<'a, S: Service<ServiceMemberConnector>> ServiceConnector<'a, ServiceInstance<S>> {
161    /// Connects to the service instance's path in the incoming namespace with the new wire bindings.
162    /// Logs and returns a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
163    pub fn connect_next(self) -> Result<ServiceInstance<S>, Status> {
164        let service_path = format!("{SVC_DIR}/{}/{}", S::SERVICE_NAME, self.instance);
165        let dir = open_directory_async(self.incoming, &service_path, fio::Rights::empty())
166            .map_err(|e| {
167                error!(
168                    "Failed to connect to aggregated service connector `{}`, instance `{}`: {e}",
169                    S::SERVICE_NAME,
170                    self.instance
171                );
172                Status::CONNECTION_REFUSED
173            })?;
174        Ok(fidl_next_bind::ServiceConnector::from_untyped(ServiceMemberConnector(dir)))
175    }
176}
177
178impl From<Namespace> for Incoming {
179    fn from(value: Namespace) -> Self {
180        Incoming(value.flatten())
181    }
182}
183
184/// Returns the remainder of a prefix match of `prefix` against `self` in terms of path segments.
185///
186/// For example:
187/// ```ignore
188/// match_prefix("pkg/data", "pkg") == Some("/data")
189/// match_prefix("pkg_data", "pkg") == None
190/// ```
191fn match_prefix(match_in: &impl IterablePath, prefix: &impl IterablePath) -> Option<RelativePath> {
192    let mut my_segments = match_in.iter_segments();
193    let mut prefix_segments = prefix.iter_segments();
194    for prefix in prefix_segments.by_ref() {
195        if prefix != my_segments.next()? {
196            return None;
197        }
198    }
199    if prefix_segments.next().is_some() {
200        // did not match all prefix segments
201        return None;
202    }
203    let segments = Vec::from_iter(my_segments);
204    Some(RelativePath::from(segments))
205}
206
207impl Directory for Incoming {
208    fn open(&self, path: &str, flags: Flags, server_end: zx::Channel) -> Result<(), Error> {
209        let path = path.strip_prefix("/").unwrap_or(path);
210        let path = RelativePath::new(path)?;
211
212        for entry in &self.0 {
213            if let Some(remain) = match_prefix(&path, &entry.path) {
214                return entry.directory.open(&format!("/{}", remain), flags, server_end);
215            }
216        }
217        Err(Status::NOT_FOUND)
218            .with_context(|| anyhow!("Path {path} not found in incoming namespace"))
219    }
220}
221
222impl AsRefDirectory for Incoming {
223    fn as_ref_directory(&self) -> &dyn Directory {
224        self
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use cm_types::NamespacePath;
232    use fuchsia_async::Task;
233    use fuchsia_component::server::ServiceFs;
234    use futures::stream::StreamExt;
235
236    enum IncomingServices {
237        Device(fidl_fuchsia_hardware_i2c::DeviceRequestStream),
238        DefaultService(fidl_fuchsia_hardware_i2c::ServiceRequest),
239        OtherService(fidl_fuchsia_hardware_i2c::ServiceRequest),
240    }
241
242    impl IncomingServices {
243        async fn handle_device_stream(
244            stream: fidl_fuchsia_hardware_i2c::DeviceRequestStream,
245            name: &str,
246        ) {
247            stream
248                .for_each(|msg| async move {
249                    match msg.unwrap() {
250                        fidl_fuchsia_hardware_i2c::DeviceRequest::GetName { responder } => {
251                            responder.send(Ok(name)).unwrap();
252                        }
253                        _ => unimplemented!(),
254                    }
255                })
256                .await
257        }
258
259        async fn handle(self) {
260            use IncomingServices::*;
261            match self {
262                Device(stream) => Self::handle_device_stream(stream, "device").await,
263                DefaultService(fidl_fuchsia_hardware_i2c::ServiceRequest::Device(stream)) => {
264                    Self::handle_device_stream(stream, "default").await
265                }
266                OtherService(fidl_fuchsia_hardware_i2c::ServiceRequest::Device(stream)) => {
267                    Self::handle_device_stream(stream, "other").await
268                }
269            }
270        }
271    }
272
273    async fn make_incoming() -> Incoming {
274        let (client, server) = fidl::endpoints::create_endpoints();
275        let mut fs = ServiceFs::new();
276        fs.dir("svc")
277            .add_fidl_service(IncomingServices::Device)
278            .add_fidl_service_instance("default", IncomingServices::DefaultService)
279            .add_fidl_service_instance("other", IncomingServices::OtherService);
280        fs.serve_connection(server).expect("error serving handle");
281
282        Task::spawn(fs.for_each_concurrent(100, IncomingServices::handle)).detach_on_drop();
283
284        Incoming(vec![Entry { path: NamespacePath::new("/").unwrap(), directory: client }])
285    }
286
287    #[fuchsia::test]
288    async fn protocol_connect_present() -> anyhow::Result<()> {
289        let incoming = make_incoming().await;
290        // try a protocol that we did set up
291        incoming
292            .connect_protocol::<fidl_fuchsia_hardware_i2c::DeviceProxy>()?
293            .get_name()
294            .await?
295            .unwrap();
296        Ok(())
297    }
298
299    #[fuchsia::test]
300    async fn protocol_connect_not_present() -> anyhow::Result<()> {
301        let incoming = make_incoming().await;
302        // try one we didn't
303        incoming
304            .connect_protocol::<fidl_fuchsia_hwinfo::DeviceProxy>()?
305            .get_info()
306            .await
307            .unwrap_err();
308        Ok(())
309    }
310
311    #[fuchsia::test]
312    async fn service_connect_default_instance() -> anyhow::Result<()> {
313        let incoming = make_incoming().await;
314        // try the default service instance that we did set up
315        assert_eq!(
316            "default",
317            &incoming
318                .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
319                .connect()?
320                .connect_to_device()?
321                .get_name()
322                .await?
323                .unwrap()
324        );
325        assert_eq!(
326            "default",
327            &incoming
328                .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
329                .connect()?
330                .connect_to_device()?
331                .get_name()
332                .await?
333                .unwrap()
334        );
335        Ok(())
336    }
337
338    #[fuchsia::test]
339    async fn service_connect_other_instance() -> anyhow::Result<()> {
340        let incoming = make_incoming().await;
341        // try the other service instance that we did set up
342        assert_eq!(
343            "other",
344            &incoming
345                .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
346                .instance("other")
347                .connect()?
348                .connect_to_device()?
349                .get_name()
350                .await?
351                .unwrap()
352        );
353        assert_eq!(
354            "other",
355            &incoming
356                .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
357                .instance("other")
358                .connect()?
359                .connect_to_device()?
360                .get_name()
361                .await?
362                .unwrap()
363        );
364        Ok(())
365    }
366
367    #[fuchsia::test]
368    async fn service_connect_invalid_instance() -> anyhow::Result<()> {
369        let incoming = make_incoming().await;
370        // try the invalid service instance that we did not set up
371        incoming
372            .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
373            .instance("invalid")
374            .connect()?
375            .connect_to_device()?
376            .get_name()
377            .await
378            .unwrap_err();
379        incoming
380            .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
381            .instance("invalid")
382            .connect()?
383            .connect_to_device()?
384            .get_name()
385            .await
386            .unwrap_err();
387        Ok(())
388    }
389}