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::{anyhow, Context, Error};
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_to_service_instance_at_dir_svc, Connect};
15use fuchsia_component::directory::{open_directory_async, AsRefDirectory, Directory};
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    while let Some(prefix) = prefix_segments.next() {
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        I2cDevice(fidl_fuchsia_hardware_i2c::DeviceRequestStream),
238        I2cDefaultService(fidl_fuchsia_hardware_i2c::ServiceRequest),
239        I2cOtherService(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 fidl_fuchsia_hardware_i2c::ServiceRequest::*;
261            use IncomingServices::*;
262            match self {
263                I2cDevice(stream) => Self::handle_device_stream(stream, "device").await,
264                I2cDefaultService(Device(stream)) => {
265                    Self::handle_device_stream(stream, "default").await
266                }
267                I2cOtherService(Device(stream)) => {
268                    Self::handle_device_stream(stream, "other").await
269                }
270            }
271        }
272    }
273
274    async fn make_incoming() -> Incoming {
275        let (client, server) = fidl::endpoints::create_endpoints();
276        let mut fs = ServiceFs::new();
277        fs.dir("svc")
278            .add_fidl_service(IncomingServices::I2cDevice)
279            .add_fidl_service_instance("default", IncomingServices::I2cDefaultService)
280            .add_fidl_service_instance("other", IncomingServices::I2cOtherService);
281        fs.serve_connection(server).expect("error serving handle");
282
283        Task::spawn(fs.for_each_concurrent(100, IncomingServices::handle)).detach_on_drop();
284
285        Incoming(vec![Entry { path: NamespacePath::new("/").unwrap(), directory: client }])
286    }
287
288    #[fuchsia::test]
289    async fn protocol_connect_present() -> anyhow::Result<()> {
290        let incoming = make_incoming().await;
291        // try a protocol that we did set up
292        incoming
293            .connect_protocol::<fidl_fuchsia_hardware_i2c::DeviceProxy>()?
294            .get_name()
295            .await?
296            .unwrap();
297        Ok(())
298    }
299
300    #[fuchsia::test]
301    async fn protocol_connect_not_present() -> anyhow::Result<()> {
302        let incoming = make_incoming().await;
303        // try one we didn't
304        incoming
305            .connect_protocol::<fidl_fuchsia_hwinfo::DeviceProxy>()?
306            .get_info()
307            .await
308            .unwrap_err();
309        Ok(())
310    }
311
312    #[fuchsia::test]
313    async fn service_connect_default_instance() -> anyhow::Result<()> {
314        let incoming = make_incoming().await;
315        // try the default service instance that we did set up
316        assert_eq!(
317            "default",
318            &incoming
319                .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
320                .connect()?
321                .connect_to_device()?
322                .get_name()
323                .await?
324                .unwrap()
325        );
326        assert_eq!(
327            "default",
328            &incoming
329                .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
330                .connect()?
331                .connect_to_device()?
332                .get_name()
333                .await?
334                .unwrap()
335        );
336        Ok(())
337    }
338
339    #[fuchsia::test]
340    async fn service_connect_other_instance() -> anyhow::Result<()> {
341        let incoming = make_incoming().await;
342        // try the other service instance that we did set up
343        assert_eq!(
344            "other",
345            &incoming
346                .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
347                .instance("other")
348                .connect()?
349                .connect_to_device()?
350                .get_name()
351                .await?
352                .unwrap()
353        );
354        assert_eq!(
355            "other",
356            &incoming
357                .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
358                .instance("other")
359                .connect()?
360                .connect_to_device()?
361                .get_name()
362                .await?
363                .unwrap()
364        );
365        Ok(())
366    }
367
368    #[fuchsia::test]
369    async fn service_connect_invalid_instance() -> anyhow::Result<()> {
370        let incoming = make_incoming().await;
371        // try the invalid service instance that we did not set up
372        incoming
373            .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
374            .instance("invalid")
375            .connect()?
376            .connect_to_device()?
377            .get_name()
378            .await
379            .unwrap_err();
380        incoming
381            .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
382            .instance("invalid")
383            .connect()?
384            .connect_to_device()?
385            .get_name()
386            .await
387            .unwrap_err();
388        Ok(())
389    }
390}