Skip to main content

fdomain_container/
handles.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 fidl::{AsHandleRef, Peered, SocketOpts};
6use fidl_fuchsia_fdomain as proto;
7
8/// This is implemented on the `fidl::*` objects for every type of handle FDomain
9/// supports. It essentially makes the handle object a responder to a stream of
10/// [`HandleOperation`]s.
11pub trait HandleType:
12    Sync + Sized + Into<fidl::NullableHandle> + fidl::AsHandleRef + 'static
13{
14    /// This should be the handle type corresponding to the implementing handle.
15    /// We use this to generalize some of the error reporting in this trait.
16    fn object_type(&self) -> fidl::ObjectType;
17
18    /// Returns `Ok` if this handle is the given type, `Err` otherwise.
19    fn expected_type(&self, expected_type: fidl::ObjectType) -> Result<(), proto::Error> {
20        if expected_type == self.object_type() {
21            Ok(())
22        } else {
23            Err(proto::Error::WrongHandleType(proto::WrongHandleType {
24                expected: expected_type,
25                got: self.object_type(),
26            }))
27        }
28    }
29
30    /// Implements [`HandleOperation::SocketDisposition`].
31    fn socket_disposition(
32        &self,
33        _disposition: proto::SocketDisposition,
34        _disposition_peer: proto::SocketDisposition,
35    ) -> Result<(), proto::Error> {
36        self.expected_type(fidl::ObjectType::SOCKET)
37    }
38
39    /// Implements [`HandleOperation::ReadSocket`].
40    fn read_socket(&self, _max_bytes: u64) -> Result<Option<Vec<u8>>, proto::Error> {
41        Err(self.expected_type(fidl::ObjectType::SOCKET).unwrap_err())
42    }
43
44    /// Implements [`HandleOperation::ReadChannel`].
45    fn read_channel(&self) -> Result<Option<fidl::MessageBufEtc>, proto::Error> {
46        Err(self.expected_type(fidl::ObjectType::CHANNEL).unwrap_err())
47    }
48
49    /// Implements [`HandleOperation::WriteSocket`].
50    fn write_socket(&self, _data: &[u8]) -> Result<usize, proto::Error> {
51        Err(self.expected_type(fidl::ObjectType::SOCKET).unwrap_err())
52    }
53
54    /// Implements [`HandleOperation::WriteChannel`].
55    fn write_channel(
56        &self,
57        _data: &[u8],
58        _handles: &mut Vec<fidl::HandleDisposition<'static>>,
59    ) -> Option<Result<(), proto::WriteChannelError>> {
60        Some(Err(proto::WriteChannelError::Error(
61            self.expected_type(fidl::ObjectType::CHANNEL).unwrap_err(),
62        )))
63    }
64
65    /// Implements reading from a VMO.
66    fn read_vmo(&self, _offset: u64, _size: u64) -> Result<Vec<u8>, proto::Error> {
67        Err(self.expected_type(fidl::ObjectType::VMO).unwrap_err())
68    }
69
70    /// Implements writing to a VMO.
71    fn write_vmo(&self, _offset: u64, _data: &[u8]) -> Result<(), proto::Error> {
72        self.expected_type(fidl::ObjectType::VMO)
73    }
74
75    /// Implements getting the size of a VMO.
76    fn get_vmo_size(&self) -> Result<u64, proto::Error> {
77        Err(self.expected_type(fidl::ObjectType::VMO).unwrap_err())
78    }
79
80    /// Implements setting the size of a VMO.
81    fn set_vmo_size(&self, _size: u64) -> Result<(), proto::Error> {
82        self.expected_type(fidl::ObjectType::VMO)
83    }
84
85    /// Implements getting the stream size of a VMO.
86    fn get_vmo_stream_size(&self) -> Result<u64, proto::Error> {
87        Err(self.expected_type(fidl::ObjectType::VMO).unwrap_err())
88    }
89
90    /// Implements setting the stream size of a VMO.
91    fn set_vmo_stream_size(&self, _size: u64) -> Result<(), proto::Error> {
92        self.expected_type(fidl::ObjectType::VMO)
93    }
94}
95
96impl HandleType for fidl::Socket {
97    fn object_type(&self) -> fidl::ObjectType {
98        fidl::ObjectType::SOCKET
99    }
100
101    #[cfg(not(target_os = "fuchsia"))]
102    fn socket_disposition(
103        &self,
104        _disposition: proto::SocketDisposition,
105        _disposition_peer: proto::SocketDisposition,
106    ) -> Result<(), proto::Error> {
107        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
108    }
109
110    #[cfg(target_os = "fuchsia")]
111    fn socket_disposition(
112        &self,
113        disposition: proto::SocketDisposition,
114        disposition_peer: proto::SocketDisposition,
115    ) -> Result<(), proto::Error> {
116        fn map_disposition(
117            disposition: proto::SocketDisposition,
118        ) -> Result<Option<zx::SocketWriteDisposition>, proto::Error> {
119            match disposition {
120                proto::SocketDisposition::NoChange => Ok(None),
121                proto::SocketDisposition::WriteDisabled => {
122                    Ok(Some(zx::SocketWriteDisposition::Disabled))
123                }
124                proto::SocketDisposition::WriteEnabled => {
125                    Ok(Some(zx::SocketWriteDisposition::Enabled))
126                }
127                disposition => {
128                    Err(proto::Error::SocketDispositionUnknown(proto::SocketDispositionUnknown {
129                        disposition,
130                    }))
131                }
132            }
133        }
134
135        self.set_disposition(map_disposition(disposition)?, map_disposition(disposition_peer)?)
136            .map_err(|e| proto::Error::TargetError(e.into_raw()))
137    }
138
139    fn read_socket(&self, max_bytes: u64) -> Result<Option<Vec<u8>>, proto::Error> {
140        let max_bytes = max_bytes.try_into().unwrap_or(usize::MAX);
141        let mut buf = Vec::with_capacity(max_bytes);
142        // SAFETY: We've derived this pointer and length from a vec in a way
143        // that should guarantee they are valid.
144        #[cfg(target_os = "fuchsia")]
145        let read = unsafe {
146            let buf_ptr = buf.spare_capacity_mut();
147            let buf_ptr = buf_ptr.as_mut_ptr().cast::<u8>();
148            self.read_raw(buf_ptr, max_bytes)
149        };
150        #[cfg(not(target_os = "fuchsia"))]
151        let read = {
152            buf.resize(max_bytes, 0);
153            self.read(&mut buf)
154        };
155        match read {
156            Ok(size) => {
157                // SAFETY: The `read_raw` call should guarantee that this many
158                // bytes in the capacity have now been initialized.
159                #[cfg(target_os = "fuchsia")]
160                unsafe {
161                    buf.set_len(size);
162                }
163                #[cfg(not(target_os = "fuchsia"))]
164                buf.truncate(size);
165                Ok(Some(buf))
166            }
167            Err(fidl::Status::SHOULD_WAIT) => Ok(None),
168            Err(other) => Err(proto::Error::TargetError(other.into_raw())),
169        }
170    }
171
172    fn write_socket(&self, data: &[u8]) -> Result<usize, proto::Error> {
173        let mut wrote = 0;
174        loop {
175            match self.write(&data[wrote..]) {
176                Ok(count) => {
177                    wrote += count;
178
179                    if wrote >= data.len() {
180                        break Ok(wrote);
181                    }
182                }
183                Err(fidl::Status::SHOULD_WAIT) => break Ok(wrote),
184
185                Err(other) => break Err(proto::Error::TargetError(other.into_raw())),
186            }
187        }
188    }
189}
190
191impl HandleType for fidl::Channel {
192    fn object_type(&self) -> fidl::ObjectType {
193        fidl::ObjectType::CHANNEL
194    }
195
196    fn read_channel(&self) -> Result<Option<fidl::MessageBufEtc>, proto::Error> {
197        let mut buf = fidl::MessageBufEtc::new();
198        match self.read_etc(&mut buf) {
199            Err(fidl::Status::SHOULD_WAIT) => Ok(None),
200            other => other.map(|_| Some(buf)).map_err(|e| proto::Error::TargetError(e.into_raw())),
201        }
202    }
203
204    fn write_channel(
205        &self,
206        data: &[u8],
207        handles: &mut Vec<fidl::HandleDisposition<'static>>,
208    ) -> Option<Result<(), proto::WriteChannelError>> {
209        match self.write_etc(data, handles) {
210            Ok(()) => Some(Ok(())),
211            Err(fidl::Status::SHOULD_WAIT) => None,
212            Err(other) => {
213                if handles.iter().any(|x| x.result.is_err()) {
214                    Some(Err(proto::WriteChannelError::OpErrors(
215                        handles
216                            .iter_mut()
217                            .map(|x| {
218                                x.result
219                                    .err()
220                                    .map(|e| Box::new(proto::Error::TargetError(e.into_raw())))
221                            })
222                            .collect(),
223                    )))
224                } else {
225                    Some(Err(proto::WriteChannelError::Error(proto::Error::TargetError(
226                        other.into_raw(),
227                    ))))
228                }
229            }
230        }
231    }
232}
233
234impl HandleType for fidl::EventPair {
235    fn object_type(&self) -> fidl::ObjectType {
236        fidl::ObjectType::EVENTPAIR
237    }
238}
239
240impl HandleType for fidl::Event {
241    fn object_type(&self) -> fidl::ObjectType {
242        fidl::ObjectType::EVENT
243    }
244}
245
246impl HandleType for fidl::Vmo {
247    fn object_type(&self) -> fidl::ObjectType {
248        fidl::ObjectType::VMO
249    }
250
251    #[cfg(target_os = "fuchsia")]
252    fn read_vmo(&self, offset: u64, size: u64) -> Result<Vec<u8>, proto::Error> {
253        self.read_to_vec::<u8>(offset, size).map_err(|e| proto::Error::TargetError(e.into_raw()))
254    }
255
256    #[cfg(not(target_os = "fuchsia"))]
257    fn read_vmo(&self, _offset: u64, _size: u64) -> Result<Vec<u8>, proto::Error> {
258        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
259    }
260
261    #[cfg(target_os = "fuchsia")]
262    fn write_vmo(&self, offset: u64, data: &[u8]) -> Result<(), proto::Error> {
263        self.write(data, offset).map_err(|e| proto::Error::TargetError(e.into_raw()))
264    }
265
266    #[cfg(not(target_os = "fuchsia"))]
267    fn write_vmo(&self, _offset: u64, _data: &[u8]) -> Result<(), proto::Error> {
268        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
269    }
270
271    #[cfg(target_os = "fuchsia")]
272    fn get_vmo_size(&self) -> Result<u64, proto::Error> {
273        self.get_size().map_err(|e| proto::Error::TargetError(e.into_raw()))
274    }
275
276    #[cfg(not(target_os = "fuchsia"))]
277    fn get_vmo_size(&self) -> Result<u64, proto::Error> {
278        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
279    }
280
281    #[cfg(target_os = "fuchsia")]
282    fn set_vmo_size(&self, size: u64) -> Result<(), proto::Error> {
283        self.set_size(size).map_err(|e| proto::Error::TargetError(e.into_raw()))
284    }
285
286    #[cfg(not(target_os = "fuchsia"))]
287    fn set_vmo_size(&self, _size: u64) -> Result<(), proto::Error> {
288        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
289    }
290
291    #[cfg(target_os = "fuchsia")]
292    fn get_vmo_stream_size(&self) -> Result<u64, proto::Error> {
293        self.get_stream_size().map_err(|e| proto::Error::TargetError(e.into_raw()))
294    }
295
296    #[cfg(not(target_os = "fuchsia"))]
297    fn get_vmo_stream_size(&self) -> Result<u64, proto::Error> {
298        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
299    }
300
301    #[cfg(target_os = "fuchsia")]
302    fn set_vmo_stream_size(&self, size: u64) -> Result<(), proto::Error> {
303        self.set_stream_size(size).map_err(|e| proto::Error::TargetError(e.into_raw()))
304    }
305
306    #[cfg(not(target_os = "fuchsia"))]
307    fn set_vmo_stream_size(&self, _size: u64) -> Result<(), proto::Error> {
308        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
309    }
310}
311
312pub struct Unknown(pub fidl::NullableHandle, pub fidl::ObjectType);
313
314impl Into<fidl::NullableHandle> for Unknown {
315    fn into(self) -> fidl::NullableHandle {
316        self.0
317    }
318}
319
320impl fidl::AsHandleRef for Unknown {
321    fn as_handle_ref(&self) -> fidl::HandleRef<'_> {
322        self.0.as_handle_ref()
323    }
324}
325
326impl HandleType for Unknown {
327    fn object_type(&self) -> fidl::ObjectType {
328        self.1
329    }
330}
331
332pub enum AnyHandle {
333    Socket(fidl::Socket),
334    EventPair(fidl::EventPair),
335    Event(fidl::Event),
336    Channel(fidl::Channel),
337    Vmo(fidl::Vmo),
338    Unknown(Unknown),
339}
340
341/// Whether a socket is a datagram socket.
342#[derive(Debug, Copy, Clone, PartialEq, Eq)]
343pub(crate) enum IsDatagramSocket {
344    NotDatagram,
345    Datagram,
346    Unknown,
347}
348
349impl IsDatagramSocket {
350    pub fn is_datagram(&self) -> bool {
351        matches!(self, IsDatagramSocket::Datagram)
352    }
353}
354
355impl AnyHandle {
356    /// Signals that indicate we should do write processing on a handle.
357    pub(crate) fn write_signals(&self) -> fidl::Signals {
358        let sock_signals = if let AnyHandle::Socket(_) = self {
359            fidl::Signals::SOCKET_WRITE_DISABLED
360        } else {
361            fidl::Signals::empty()
362        };
363
364        sock_signals | fidl::Signals::OBJECT_WRITABLE | fidl::Signals::OBJECT_PEER_CLOSED
365    }
366
367    /// Signals that indicate we should do write processing on a handle.
368    pub(crate) fn read_signals(&self) -> fidl::Signals {
369        let sock_signals = if let AnyHandle::Socket(_) = self {
370            fidl::Signals::SOCKET_PEER_WRITE_DISABLED
371        } else {
372            fidl::Signals::empty()
373        };
374
375        sock_signals | fidl::Signals::OBJECT_READABLE | fidl::Signals::OBJECT_PEER_CLOSED
376    }
377
378    /// Whether this is a datagram socket.
379    pub(crate) fn is_datagram_socket(&self) -> IsDatagramSocket {
380        let AnyHandle::Socket(socket) = self else {
381            return IsDatagramSocket::NotDatagram;
382        };
383
384        let Ok(info) = socket.info() else {
385            return IsDatagramSocket::Unknown;
386        };
387
388        if info.options == SocketOpts::DATAGRAM {
389            IsDatagramSocket::Datagram
390        } else {
391            IsDatagramSocket::NotDatagram
392        }
393    }
394
395    /// zx_handle_duplicate but preserving our metadata.
396    pub fn duplicate(&self, rights: fidl::Rights) -> Result<AnyHandle, proto::Error> {
397        let handle = self
398            .as_handle_ref()
399            .duplicate_handle(rights)
400            .map_err(|e| proto::Error::TargetError(e.into_raw()))?;
401
402        Ok(match self {
403            AnyHandle::Socket(_) => AnyHandle::Socket(fidl::Socket::from(handle)),
404            AnyHandle::EventPair(_) => AnyHandle::EventPair(fidl::EventPair::from(handle)),
405            AnyHandle::Event(_) => AnyHandle::Event(fidl::Event::from(handle)),
406            AnyHandle::Channel(_) => AnyHandle::Channel(fidl::Channel::from(handle)),
407            AnyHandle::Vmo(_) => AnyHandle::Vmo(fidl::Vmo::from(handle)),
408            AnyHandle::Unknown(Unknown(_, ty)) => AnyHandle::Unknown(Unknown(handle, *ty)),
409        })
410    }
411
412    /// zx_handle_replace but preserving our metadata.
413    #[cfg(not(target_os = "fuchsia"))]
414    pub fn replace(self, _rights: fidl::Rights) -> Result<AnyHandle, proto::Error> {
415        Err(proto::Error::TargetError(fidl::Status::NOT_SUPPORTED.into_raw()))
416    }
417
418    /// zx_handle_replace but preserving our metadata.
419    #[cfg(target_os = "fuchsia")]
420    pub fn replace(self, rights: fidl::Rights) -> Result<AnyHandle, proto::Error> {
421        Ok(match self {
422            AnyHandle::Socket(h) => AnyHandle::Socket(
423                h.replace_handle(rights).map_err(|e| proto::Error::TargetError(e.into_raw()))?,
424            ),
425            AnyHandle::EventPair(h) => AnyHandle::EventPair(
426                h.replace_handle(rights).map_err(|e| proto::Error::TargetError(e.into_raw()))?,
427            ),
428            AnyHandle::Event(h) => AnyHandle::Event(
429                h.replace_handle(rights).map_err(|e| proto::Error::TargetError(e.into_raw()))?,
430            ),
431            AnyHandle::Channel(h) => AnyHandle::Channel(
432                h.replace_handle(rights).map_err(|e| proto::Error::TargetError(e.into_raw()))?,
433            ),
434            AnyHandle::Vmo(h) => AnyHandle::Vmo(
435                h.replace_handle(rights).map_err(|e| proto::Error::TargetError(e.into_raw()))?,
436            ),
437            AnyHandle::Unknown(Unknown(h, ty)) => AnyHandle::Unknown(Unknown(
438                h.replace_handle(rights).map_err(|e| proto::Error::TargetError(e.into_raw()))?,
439                ty,
440            )),
441        })
442    }
443
444    pub fn signal(&self, clear: fidl::Signals, set: fidl::Signals) -> Result<(), proto::Error> {
445        match self {
446            AnyHandle::Socket(s) => s.signal(clear, set),
447            AnyHandle::EventPair(e) => e.signal(clear, set),
448            AnyHandle::Event(e) => e.signal(clear, set),
449            AnyHandle::Channel(c) => c.signal(clear, set),
450            AnyHandle::Vmo(v) => v.as_handle_ref().signal(clear, set),
451            AnyHandle::Unknown(u) => u.0.signal(clear, set),
452        }
453        .map_err(|e| proto::Error::TargetError(e.into_raw()))
454    }
455
456    pub fn signal_peer(
457        &self,
458        clear: fidl::Signals,
459        set: fidl::Signals,
460    ) -> Result<(), proto::Error> {
461        // TODO: Rust is being helpful and only letting us signal peers for
462        // things we know have them, but we'd really like to just make the
463        // syscall and get it to report whatever error it will. Especially for
464        // `Unknown`, which may well have peers the type system just isn't aware
465        // of.
466        match self {
467            AnyHandle::Socket(h) => h.signal_peer(clear, set),
468            AnyHandle::EventPair(h) => h.signal_peer(clear, set),
469            AnyHandle::Event(_) => Err(fidl::Status::INVALID_ARGS),
470            AnyHandle::Channel(h) => h.signal_peer(clear, set),
471            AnyHandle::Vmo(_) => Err(fidl::Status::INVALID_ARGS),
472            AnyHandle::Unknown(_) => Err(fidl::Status::INVALID_ARGS),
473        }
474        .map_err(|e| proto::Error::TargetError(e.into_raw()))
475    }
476}
477
478impl From<fidl::Channel> for AnyHandle {
479    fn from(other: fidl::Channel) -> AnyHandle {
480        AnyHandle::Channel(other)
481    }
482}
483
484impl From<fidl::Socket> for AnyHandle {
485    fn from(other: fidl::Socket) -> AnyHandle {
486        AnyHandle::Socket(other)
487    }
488}
489
490impl From<fidl::EventPair> for AnyHandle {
491    fn from(other: fidl::EventPair) -> AnyHandle {
492        AnyHandle::EventPair(other)
493    }
494}
495
496impl From<fidl::Event> for AnyHandle {
497    fn from(other: fidl::Event) -> AnyHandle {
498        AnyHandle::Event(other)
499    }
500}
501
502impl From<fidl::Vmo> for AnyHandle {
503    fn from(other: fidl::Vmo) -> AnyHandle {
504        AnyHandle::Vmo(other)
505    }
506}
507
508macro_rules! impl_method {
509    ($this:ident => $h:ident . $meth:ident ( $($args:tt)* )) => {
510        match $this {
511            AnyHandle::Socket($h) => $h.$meth($($args)*),
512            AnyHandle::EventPair($h) => $h.$meth($($args)*),
513            AnyHandle::Event($h) => $h.$meth($($args)*),
514            AnyHandle::Channel($h) => $h.$meth($($args)*),
515            AnyHandle::Vmo($h) => $h.$meth($($args)*),
516            AnyHandle::Unknown($h) => $h.$meth($($args)*),
517        }
518    };
519}
520
521impl HandleType for AnyHandle {
522    fn object_type(&self) -> fidl::ObjectType {
523        impl_method!(self => h.object_type())
524    }
525
526    fn socket_disposition(
527        &self,
528        disposition: proto::SocketDisposition,
529        disposition_peer: proto::SocketDisposition,
530    ) -> Result<(), proto::Error> {
531        impl_method!(self => h.socket_disposition(disposition, disposition_peer))
532    }
533
534    fn read_socket(&self, max_bytes: u64) -> Result<Option<Vec<u8>>, proto::Error> {
535        impl_method!(self => h.read_socket(max_bytes))
536    }
537
538    fn read_channel(&self) -> Result<Option<fidl::MessageBufEtc>, proto::Error> {
539        impl_method!(self => h.read_channel())
540    }
541
542    fn write_socket(&self, data: &[u8]) -> Result<usize, proto::Error> {
543        impl_method!(self => h.write_socket(data))
544    }
545
546    fn write_channel(
547        &self,
548        data: &[u8],
549        handles: &mut Vec<fidl::HandleDisposition<'static>>,
550    ) -> Option<Result<(), proto::WriteChannelError>> {
551        impl_method!(self => h.write_channel(data, handles))
552    }
553
554    fn read_vmo(&self, offset: u64, size: u64) -> Result<Vec<u8>, proto::Error> {
555        impl_method!(self => h.read_vmo(offset, size))
556    }
557
558    fn write_vmo(&self, offset: u64, data: &[u8]) -> Result<(), proto::Error> {
559        impl_method!(self => h.write_vmo(offset, data))
560    }
561
562    fn get_vmo_size(&self) -> Result<u64, proto::Error> {
563        impl_method!(self => h.get_vmo_size())
564    }
565
566    fn set_vmo_size(&self, size: u64) -> Result<(), proto::Error> {
567        impl_method!(self => h.set_vmo_size(size))
568    }
569
570    fn get_vmo_stream_size(&self) -> Result<u64, proto::Error> {
571        impl_method!(self => h.get_vmo_stream_size())
572    }
573
574    fn set_vmo_stream_size(&self, size: u64) -> Result<(), proto::Error> {
575        impl_method!(self => h.set_vmo_stream_size(size))
576    }
577}
578
579impl fidl::AsHandleRef for AnyHandle {
580    fn as_handle_ref(&self) -> fidl::HandleRef<'_> {
581        impl_method!(self => h.as_handle_ref())
582    }
583}
584
585impl Into<fidl::NullableHandle> for AnyHandle {
586    fn into(self) -> fidl::NullableHandle {
587        impl_method!(self => h.into())
588    }
589}