Skip to main content

fdomain_client/
lib.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_fuchsia_fdomain as proto;
6use fidl_message::TransactionHeader;
7use fuchsia_async as _;
8use fuchsia_sync::Mutex;
9use futures::FutureExt;
10use futures::channel::oneshot::Sender as OneshotSender;
11use futures::stream::Stream as StreamTrait;
12use std::collections::{HashMap, VecDeque};
13use std::convert::Infallible;
14use std::future::Future;
15use std::num::NonZeroU32;
16use std::pin::Pin;
17use std::sync::{Arc, LazyLock, Weak};
18use std::task::{Context, Poll, Waker, ready};
19
20mod channel;
21mod event;
22mod event_pair;
23mod handle;
24mod responder;
25mod socket;
26
27#[cfg(test)]
28mod test;
29
30pub mod fidl;
31pub mod fidl_next;
32
33use responder::Responder;
34
35pub use channel::{
36    AnyHandle, Channel, ChannelMessageStream, ChannelWriter, HandleInfo, HandleOp, MessageBuf,
37};
38pub use event::Event;
39pub use event_pair::Eventpair as EventPair;
40pub use handle::unowned::Unowned;
41pub use handle::{
42    AsHandleRef, Handle, HandleBased, HandleRef, NullableHandle, OnFDomainSignals, Peered,
43};
44pub use proto::{Error as FDomainError, WriteChannelError, WriteSocketError};
45pub use socket::{Socket, SocketDisposition, SocketReadStream, SocketWriter};
46
47// Unsupported handle types.
48#[rustfmt::skip]
49pub use Handle as Clock;
50#[rustfmt::skip]
51pub use Handle as Exception;
52#[rustfmt::skip]
53pub use Handle as Fifo;
54#[rustfmt::skip]
55pub use Handle as Iob;
56#[rustfmt::skip]
57pub use Handle as Job;
58#[rustfmt::skip]
59pub use Handle as Process;
60#[rustfmt::skip]
61pub use Handle as Resource;
62#[rustfmt::skip]
63pub use Handle as Stream;
64#[rustfmt::skip]
65pub use Handle as Thread;
66#[rustfmt::skip]
67pub use Handle as Vmar;
68#[rustfmt::skip]
69pub use Handle as Vmo;
70#[rustfmt::skip]
71pub use Handle as Counter;
72
73use proto::f_domain_ordinals as ordinals;
74
75fn write_fdomain_error(error: &FDomainError, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76    match error {
77        FDomainError::TargetError(e) => {
78            let e = zx_status::Status::from_raw(*e);
79            write!(f, "Target-side error {e}")
80        }
81        FDomainError::BadHandleId(proto::BadHandleId { id }) => {
82            write!(f, "Tried to use invalid handle id {id}")
83        }
84        FDomainError::WrongHandleType(proto::WrongHandleType { expected, got }) => write!(
85            f,
86            "Tried to use handle as {expected:?} but target reported handle was of type {got:?}"
87        ),
88        FDomainError::StreamingReadInProgress(proto::StreamingReadInProgress {}) => {
89            write!(f, "Handle is occupied delivering streaming reads")
90        }
91        FDomainError::NoReadInProgress(proto::NoReadInProgress {}) => {
92            write!(f, "No streaming read was in progress")
93        }
94        FDomainError::NewHandleIdOutOfRange(proto::NewHandleIdOutOfRange { id }) => {
95            write!(
96                f,
97                "Tried to create a handle with id {id}, which is outside the valid range for client handles"
98            )
99        }
100        FDomainError::NewHandleIdReused(proto::NewHandleIdReused { id, same_call }) => {
101            if *same_call {
102                write!(f, "Tried to create two or more new handles with the same id {id}")
103            } else {
104                write!(
105                    f,
106                    "Tried to create a new handle with id {id}, which is already the id of an existing handle"
107                )
108            }
109        }
110        FDomainError::WroteToSelf(proto::WroteToSelf {}) => {
111            write!(f, "Tried to write a channel into itself")
112        }
113        FDomainError::ClosedDuringRead(proto::ClosedDuringRead {}) => {
114            write!(f, "Handle closed while being read")
115        }
116        _ => todo!(),
117    }
118}
119
120/// Result type alias.
121pub type Result<T, E = Error> = std::result::Result<T, E>;
122
123/// Error type emitted by FDomain operations.
124#[derive(Clone)]
125pub enum Error {
126    SocketWrite(WriteSocketError),
127    ChannelWrite(WriteChannelError),
128    FDomain(FDomainError),
129    Protocol(::fidl::Error),
130    ProtocolObjectTypeIncompatible,
131    ProtocolRightsIncompatible,
132    ProtocolSignalsIncompatible,
133    ProtocolStreamEventIncompatible,
134    Transport(Option<Arc<std::io::Error>>),
135    ConnectionMismatch,
136    StreamingAborted,
137}
138
139impl std::fmt::Display for Error {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        match self {
142            Self::SocketWrite(proto::WriteSocketError { error, wrote }) => {
143                write!(f, "While writing socket (after {wrote} bytes written successfully): ")?;
144                write_fdomain_error(error, f)
145            }
146            Self::ChannelWrite(proto::WriteChannelError::Error(error)) => {
147                write!(f, "While writing channel: ")?;
148                write_fdomain_error(error, f)
149            }
150            Self::ChannelWrite(proto::WriteChannelError::OpErrors(errors)) => {
151                write!(f, "Couldn't write all handles into a channel:")?;
152                for (pos, error) in
153                    errors.iter().enumerate().filter_map(|(num, x)| x.as_ref().map(|y| (num, &**y)))
154                {
155                    write!(f, "\n  Handle in position {pos}: ")?;
156                    write_fdomain_error(error, f)?;
157                }
158                Ok(())
159            }
160            Self::ProtocolObjectTypeIncompatible => {
161                write!(f, "The FDomain protocol does not recognize an object type")
162            }
163            Self::ProtocolRightsIncompatible => {
164                write!(f, "The FDomain protocol does not recognize some rights")
165            }
166            Self::ProtocolSignalsIncompatible => {
167                write!(f, "The FDomain protocol does not recognize some signals")
168            }
169            Self::ProtocolStreamEventIncompatible => {
170                write!(f, "The FDomain protocol does not recognize a received streaming IO event")
171            }
172            Self::FDomain(e) => write_fdomain_error(e, f),
173            Self::Protocol(e) => write!(f, "Protocol error: {e}"),
174            Self::Transport(Some(e)) => write!(f, "Transport error: {e:?}"),
175            Self::Transport(None) => write!(f, "Transport closed"),
176            Self::ConnectionMismatch => {
177                write!(f, "Tried to use an FDomain handle from a different connection")
178            }
179            Self::StreamingAborted => write!(f, "This channel is no longer streaming"),
180        }
181    }
182}
183
184impl std::fmt::Debug for Error {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        match self {
187            Self::SocketWrite(e) => f.debug_tuple("SocketWrite").field(e).finish(),
188            Self::ChannelWrite(e) => f.debug_tuple("ChannelWrite").field(e).finish(),
189            Self::FDomain(e) => f.debug_tuple("FDomain").field(e).finish(),
190            Self::Protocol(e) => f.debug_tuple("Protocol").field(e).finish(),
191            Self::Transport(e) => f.debug_tuple("Transport").field(e).finish(),
192            Self::ProtocolObjectTypeIncompatible => write!(f, "ProtocolObjectTypeIncompatible "),
193            Self::ProtocolRightsIncompatible => write!(f, "ProtocolRightsIncompatible "),
194            Self::ProtocolSignalsIncompatible => write!(f, "ProtocolSignalsIncompatible "),
195            Self::ProtocolStreamEventIncompatible => write!(f, "ProtocolStreamEventIncompatible"),
196            Self::ConnectionMismatch => write!(f, "ConnectionMismatch"),
197            Self::StreamingAborted => write!(f, "StreamingAborted"),
198        }
199    }
200}
201
202impl std::error::Error for Error {}
203
204impl From<FDomainError> for Error {
205    fn from(other: FDomainError) -> Self {
206        Self::FDomain(other)
207    }
208}
209
210impl From<::fidl::Error> for Error {
211    fn from(other: ::fidl::Error) -> Self {
212        Self::Protocol(other)
213    }
214}
215
216impl From<WriteSocketError> for Error {
217    fn from(other: WriteSocketError) -> Self {
218        Self::SocketWrite(other)
219    }
220}
221
222impl From<WriteChannelError> for Error {
223    fn from(other: WriteChannelError) -> Self {
224        Self::ChannelWrite(other)
225    }
226}
227
228/// An error emitted internally by the client. Similar to [`Error`] but does not
229/// contain several variants which are irrelevant in the contexts where it is
230/// used.
231#[derive(Clone)]
232enum InnerError {
233    Protocol(::fidl::Error),
234    ProtocolStreamEventIncompatible,
235    Transport(Option<Arc<std::io::Error>>),
236}
237
238impl From<InnerError> for Error {
239    fn from(other: InnerError) -> Self {
240        match other {
241            InnerError::Protocol(p) => Error::Protocol(p),
242            InnerError::ProtocolStreamEventIncompatible => Error::ProtocolStreamEventIncompatible,
243            InnerError::Transport(t) => Error::Transport(t),
244        }
245    }
246}
247
248impl From<::fidl::Error> for InnerError {
249    fn from(other: ::fidl::Error) -> Self {
250        InnerError::Protocol(other)
251    }
252}
253
254// TODO(399717689) Figure out if we could just use AsyncRead/Write instead of a special trait.
255/// Implemented by objects which provide a transport over which we can speak the
256/// FDomain protocol.
257///
258/// The implementer must provide two things:
259/// 1) An incoming stream of messages presented as `Vec<u8>`. This is provided
260///    via the `Stream` trait, which this trait requires.
261/// 2) A way to send messages. This is provided by implementing the
262///    `poll_send_message` method.
263pub trait FDomainTransport: StreamTrait<Item = Result<Box<[u8]>, std::io::Error>> + Send {
264    /// Attempt to send a message asynchronously. Messages should be sent so
265    /// that they arrive at the target in order.
266    fn poll_send_message(
267        self: Pin<&mut Self>,
268        msg: &[u8],
269        ctx: &mut Context<'_>,
270    ) -> Poll<Result<(), Option<std::io::Error>>>;
271
272    /// Optional debug information outlet.
273    fn debug_fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        Ok(())
275    }
276
277    /// Whether `debug_fmt` does anything.
278    fn has_debug_fmt(&self) -> bool {
279        false
280    }
281}
282
283/// Wrapper for an `FDomainTransport` implementer that:
284/// 1) Provides a queue for outgoing messages so we need not have an await point
285///    when we submit a message.
286/// 2) Drops the transport on error, then returns the last observed error for
287///    all future operations.
288enum Transport {
289    Transport(Pin<Box<dyn FDomainTransport>>, VecDeque<Box<[u8]>>, Vec<Waker>),
290    Error(InnerError),
291}
292
293impl Transport {
294    /// Get the failure mode of the transport if it has failed.
295    fn error(&self) -> Option<InnerError> {
296        match self {
297            Transport::Transport(_, _, _) => None,
298            Transport::Error(inner_error) => Some(inner_error.clone()),
299        }
300    }
301
302    /// Enqueue a message to be sent on this transport.
303    fn push_msg(&mut self, msg: Box<[u8]>) {
304        if let Transport::Transport(_, v, w) = self {
305            v.push_back(msg);
306            w.drain(..).for_each(Waker::wake);
307        }
308    }
309
310    /// Push messages in the send queue out through the transport.
311    fn poll_send_messages(&mut self, ctx: &mut Context<'_>) -> Poll<InnerError> {
312        match self {
313            Transport::Error(e) => Poll::Ready(e.clone()),
314            Transport::Transport(t, v, w) => {
315                while let Some(msg) = v.front() {
316                    match t.as_mut().poll_send_message(msg, ctx) {
317                        Poll::Ready(Ok(())) => {
318                            v.pop_front();
319                        }
320                        Poll::Ready(Err(e)) => {
321                            let e = e.map(Arc::new);
322                            *self = Transport::Error(InnerError::Transport(e.clone()));
323                            return Poll::Ready(InnerError::Transport(e));
324                        }
325                        Poll::Pending => return Poll::Pending,
326                    }
327                }
328
329                if v.is_empty() {
330                    w.push(ctx.waker().clone());
331                } else {
332                    ctx.waker().wake_by_ref();
333                }
334                Poll::Pending
335            }
336        }
337    }
338
339    /// Get the next incoming message from the transport.
340    fn poll_next(&mut self, ctx: &mut Context<'_>) -> Poll<Result<Box<[u8]>, InnerError>> {
341        match self {
342            Transport::Error(e) => Poll::Ready(Err(e.clone())),
343            Transport::Transport(t, _, _) => match ready!(t.as_mut().poll_next(ctx)) {
344                Some(Ok(x)) => Poll::Ready(Ok(x)),
345                Some(Err(e)) => {
346                    let e = Arc::new(e);
347                    *self = Transport::Error(InnerError::Transport(Some(Arc::clone(&e))));
348                    Poll::Ready(Err(InnerError::Transport(Some(e))))
349                }
350                Option::None => Poll::Ready(Err(InnerError::Transport(None))),
351            },
352        }
353    }
354}
355
356impl Drop for Transport {
357    fn drop(&mut self) {
358        if let Transport::Transport(_, _, wakers) = self {
359            wakers.drain(..).for_each(Waker::wake);
360        }
361    }
362}
363
364/// State of a socket that is or has been read from.
365struct SocketReadState {
366    wakers: Vec<Waker>,
367    queued: VecDeque<Result<proto::SocketData, Error>>,
368    read_request_pending: bool,
369    is_streaming: bool,
370}
371
372impl SocketReadState {
373    /// Handle an incoming message, which is either a channel streaming event or
374    /// response to a `ChannelRead` request.
375    fn handle_incoming_message(&mut self, msg: Result<proto::SocketData, Error>) -> Vec<Waker> {
376        self.queued.push_back(msg);
377        std::mem::replace(&mut self.wakers, Vec::new())
378    }
379}
380
381/// State of a channel that is or has been read from.
382struct ChannelReadState {
383    wakers: Vec<Waker>,
384    queued: VecDeque<Result<proto::ChannelMessage, Error>>,
385    read_request_pending: bool,
386    is_streaming: bool,
387}
388
389impl ChannelReadState {
390    /// Handle an incoming message, which is either a channel streaming event or
391    /// response to a `ChannelRead` request.
392    fn handle_incoming_message(&mut self, msg: Result<proto::ChannelMessage, Error>) -> Vec<Waker> {
393        self.queued.push_back(msg);
394        std::mem::replace(&mut self.wakers, Vec::new())
395    }
396}
397
398/// Lock-protected interior of `Client`
399struct ClientInner {
400    transport: Transport,
401    transactions: HashMap<NonZeroU32, responder::Responder>,
402    channel_read_states: HashMap<proto::HandleId, ChannelReadState>,
403    socket_read_states: HashMap<proto::HandleId, SocketReadState>,
404    next_tx_id: u32,
405    waiting_to_close: Vec<proto::HandleId>,
406    waiting_to_close_waker: Waker,
407
408    /// There is a lock around `ClientInner`, and sometimes the FIDL bindings
409    /// give us wakers that want to do handle operations synchronously on wake,
410    /// which means we can double-take the lock if we wake a waker while we hold
411    /// it. This is a place to store wakers that we'd like to be woken as soon
412    /// as we're not holding that lock, to avoid these weird reentrancy issues.
413    wakers_to_wake: Vec<Waker>,
414}
415
416impl ClientInner {
417    /// Serialize and enqueue a new transaction, including header and transaction ID.
418    fn request<S: fidl_message::Body>(&mut self, ordinal: u64, request: S, responder: Responder) {
419        if ordinal != ordinals::CLOSE {
420            self.process_waiting_to_close();
421        }
422        let tx_id = self.next_tx_id;
423
424        let header = TransactionHeader::new(tx_id, ordinal, fidl_message::DynamicFlags::FLEXIBLE);
425        let msg = fidl_message::encode_message(header, request).expect("Could not encode request!");
426        self.next_tx_id += 1;
427        assert!(
428            self.transactions.insert(tx_id.try_into().unwrap(), responder).is_none(),
429            "Allocated same tx id twice!"
430        );
431        self.transport.push_msg(msg.into());
432    }
433
434    fn process_waiting_to_close(&mut self) {
435        if !self.waiting_to_close.is_empty() {
436            let handles = std::mem::replace(&mut self.waiting_to_close, Vec::new());
437            // We've dropped the handle object. Nobody is going to wait to read
438            // the buffers anymore. This is a safe time to drop the read state.
439            for handle in &handles {
440                let _ = self.channel_read_states.remove(handle);
441                let _ = self.socket_read_states.remove(handle);
442            }
443            self.request(
444                ordinals::CLOSE,
445                proto::FDomainCloseRequest { handles },
446                Responder::Ignore,
447            );
448        }
449    }
450
451    /// Polls the underlying transport to ensure any incoming or outgoing
452    /// messages are processed as far as possible. Errors if the transport has failed.
453    fn try_poll_transport(
454        &mut self,
455        ctx: &mut Context<'_>,
456    ) -> Poll<Result<Infallible, InnerError>> {
457        self.process_waiting_to_close();
458
459        self.waiting_to_close_waker = ctx.waker().clone();
460
461        loop {
462            if let Poll::Ready(e) = self.transport.poll_send_messages(ctx) {
463                for mut state in std::mem::take(&mut self.socket_read_states).into_values() {
464                    state.queued.push_back(Err(Error::from(e.clone())));
465                    self.wakers_to_wake.extend(state.wakers);
466                }
467                for (_, mut state) in self.channel_read_states.drain() {
468                    state.queued.push_back(Err(Error::from(e.clone())));
469                    self.wakers_to_wake.extend(state.wakers);
470                }
471                return Poll::Ready(Err(e));
472            }
473            let Poll::Ready(result) = self.transport.poll_next(ctx) else {
474                return Poll::Pending;
475            };
476            let data = result?;
477            let (header, data) = match fidl_message::decode_transaction_header(&data) {
478                Ok(x) => x,
479                Err(e) => {
480                    self.transport = Transport::Error(InnerError::Protocol(e));
481                    continue;
482                }
483            };
484
485            let Some(tx_id) = NonZeroU32::new(header.tx_id) else {
486                match self.process_event(header, data) {
487                    Ok(wakers) => self.wakers_to_wake.extend(wakers),
488                    Err(e) => self.transport = Transport::Error(e),
489                }
490                continue;
491            };
492
493            let tx = self.transactions.remove(&tx_id).ok_or(::fidl::Error::InvalidResponseTxid)?;
494            match tx.handle(self, Ok((header, data))) {
495                Ok(x) => x,
496                Err(e) => {
497                    self.transport = Transport::Error(InnerError::Protocol(e));
498                    continue;
499                }
500            }
501        }
502    }
503
504    /// Process an incoming message that arose from an event rather than a transaction reply.
505    fn process_event(
506        &mut self,
507        header: TransactionHeader,
508        data: &[u8],
509    ) -> Result<Vec<Waker>, InnerError> {
510        match header.ordinal {
511            ordinals::ON_SOCKET_STREAMING_DATA => {
512                let msg = fidl_message::decode_message::<proto::SocketOnSocketStreamingDataRequest>(
513                    header, data,
514                )?;
515                let o =
516                    self.socket_read_states.entry(msg.handle).or_insert_with(|| SocketReadState {
517                        wakers: Vec::new(),
518                        queued: VecDeque::new(),
519                        is_streaming: false,
520                        read_request_pending: false,
521                    });
522                match msg.socket_message {
523                    proto::SocketMessage::Data(data) => Ok(o.handle_incoming_message(Ok(data))),
524                    proto::SocketMessage::Stopped(proto::AioStopped { error }) => {
525                        let ret = if let Some(error) = error {
526                            o.handle_incoming_message(Err(Error::FDomain(*error)))
527                        } else {
528                            Vec::new()
529                        };
530                        o.is_streaming = false;
531                        Ok(ret)
532                    }
533                    _ => Err(InnerError::ProtocolStreamEventIncompatible),
534                }
535            }
536            ordinals::ON_CHANNEL_STREAMING_DATA => {
537                let msg = fidl_message::decode_message::<
538                    proto::ChannelOnChannelStreamingDataRequest,
539                >(header, data)?;
540                let o = self.channel_read_states.entry(msg.handle).or_insert_with(|| {
541                    ChannelReadState {
542                        wakers: Vec::new(),
543                        queued: VecDeque::new(),
544                        is_streaming: false,
545                        read_request_pending: false,
546                    }
547                });
548                match msg.channel_sent {
549                    proto::ChannelSent::Message(data) => Ok(o.handle_incoming_message(Ok(data))),
550                    proto::ChannelSent::Stopped(proto::AioStopped { error }) => {
551                        let ret = if let Some(error) = error {
552                            o.handle_incoming_message(Err(Error::FDomain(*error)))
553                        } else {
554                            Vec::new()
555                        };
556                        o.is_streaming = false;
557                        Ok(ret)
558                    }
559                    _ => Err(InnerError::ProtocolStreamEventIncompatible),
560                }
561            }
562            _ => Err(::fidl::Error::UnknownOrdinal {
563                ordinal: header.ordinal,
564                protocol_name:
565                    <proto::FDomainMarker as ::fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
566            }
567            .into()),
568        }
569    }
570
571    /// Polls the underlying transport to ensure any incoming or outgoing
572    /// messages are processed as far as possible. If a failure occurs, puts the
573    /// transport into an error state and fails all pending transactions.
574    fn poll_transport(&mut self, ctx: &mut Context<'_>) -> Poll<()> {
575        if let Poll::Ready(Err(e)) = self.try_poll_transport(ctx) {
576            for (_, v) in std::mem::take(&mut self.transactions) {
577                let _ = v.handle(self, Err(e.clone()));
578            }
579
580            Poll::Ready(())
581        } else {
582            Poll::Pending
583        }
584    }
585
586    /// Handles the response to a `SocketRead` protocol message.
587    pub(crate) fn handle_socket_read_response(
588        &mut self,
589        msg: Result<proto::SocketData, Error>,
590        id: proto::HandleId,
591    ) {
592        let state = self.socket_read_states.entry(id).or_insert_with(|| SocketReadState {
593            wakers: Vec::new(),
594            queued: VecDeque::new(),
595            is_streaming: false,
596            read_request_pending: false,
597        });
598        let wakers = state.handle_incoming_message(msg);
599        self.wakers_to_wake.extend(wakers);
600        state.read_request_pending = false;
601    }
602
603    /// Handles the response to a `ChannelRead` protocol message.
604    pub(crate) fn handle_channel_read_response(
605        &mut self,
606        msg: Result<proto::ChannelMessage, Error>,
607        id: proto::HandleId,
608    ) {
609        let state = self.channel_read_states.entry(id).or_insert_with(|| ChannelReadState {
610            wakers: Vec::new(),
611            queued: VecDeque::new(),
612            is_streaming: false,
613            read_request_pending: false,
614        });
615        let wakers = state.handle_incoming_message(msg);
616        self.wakers_to_wake.extend(wakers);
617        state.read_request_pending = false;
618    }
619}
620
621impl Drop for ClientInner {
622    fn drop(&mut self) {
623        let responders = self.transactions.drain().map(|x| x.1).collect::<Vec<_>>();
624        for responder in responders {
625            let _ = responder.handle(self, Err(InnerError::Transport(None)));
626        }
627        for state in self.channel_read_states.values_mut() {
628            state.wakers.drain(..).for_each(Waker::wake);
629        }
630        for state in self.socket_read_states.values_mut() {
631            state.wakers.drain(..).for_each(Waker::wake);
632        }
633        self.waiting_to_close_waker.wake_by_ref();
634        self.wakers_to_wake.drain(..).for_each(Waker::wake);
635    }
636}
637
638/// Represents a connection to an FDomain.
639///
640/// The client is constructed by passing it a transport object which represents
641/// the raw connection to the remote FDomain. The `Client` wrapper then allows
642/// us to construct and use handles which behave similarly to their counterparts
643/// on a Fuchsia device.
644pub struct Client(pub(crate) Mutex<ClientInner>);
645
646impl std::fmt::Debug for Client {
647    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
648        let inner = self.0.lock();
649        match &inner.transport {
650            Transport::Transport(transport, ..) if transport.has_debug_fmt() => {
651                write!(f, "Client(")?;
652                transport.debug_fmt(f)?;
653                write!(f, ")")
654            }
655            Transport::Error(error) => {
656                let error = Error::from(error.clone());
657                write!(f, "Client(Failed: {error})")
658            }
659            _ => f.debug_tuple("Client").field(&"<transport>").finish(),
660        }
661    }
662}
663
664/// A client which is always disconnected. Handles that lose their clients
665/// connect to this client instead, which always returns a "Client Lost"
666/// transport failure.
667pub(crate) static DEAD_CLIENT: LazyLock<Arc<Client>> = LazyLock::new(|| {
668    Arc::new(Client(Mutex::new(ClientInner {
669        transport: Transport::Error(InnerError::Transport(None)),
670        transactions: HashMap::new(),
671        channel_read_states: HashMap::new(),
672        socket_read_states: HashMap::new(),
673        next_tx_id: 1,
674        waiting_to_close: Vec::new(),
675        waiting_to_close_waker: std::task::Waker::noop().clone(),
676        wakers_to_wake: Vec::new(),
677    })))
678});
679
680/// A wrapper around the FDomain client background future that ensures
681/// all pending transactions and reads are failed if the loop is dropped.
682///
683/// This prevents hangs when the transport is abruptly closed (e.g. during target reboot)
684/// by waking up any futures waiting for responses or data on channels/sockets.
685pub struct ClientLoop {
686    client: Weak<Client>,
687    fut: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
688}
689
690impl Future for ClientLoop {
691    type Output = ();
692    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
693        self.fut.as_mut().poll(cx)
694    }
695}
696
697impl Drop for ClientLoop {
698    fn drop(&mut self) {
699        let Some(client) = self.client.upgrade() else {
700            return;
701        };
702
703        let (channel_read_states, socket_read_states, deferred_wakers) = {
704            let mut inner = client.0.lock();
705            let transactions = std::mem::take(&mut inner.transactions);
706            log::debug!("ClientLoop dropped, failing {} transactions", transactions.len());
707            for (_, v) in transactions {
708                let _ = v.handle(&mut *inner, Err(InnerError::Transport(None)));
709            }
710
711            let channel_read_states = std::mem::take(&mut inner.channel_read_states);
712            let socket_read_states = std::mem::take(&mut inner.socket_read_states);
713
714            let deferred_wakers = std::mem::replace(&mut inner.wakers_to_wake, Vec::new());
715
716            (channel_read_states, socket_read_states, deferred_wakers)
717        };
718
719        log::debug!("Failing reads on {} channels", channel_read_states.len());
720        for (_, mut state) in channel_read_states {
721            state.queued.push_back(Err(Error::Transport(None)));
722            state.wakers.into_iter().for_each(Waker::wake);
723        }
724
725        log::debug!("Failing reads on {} sockets", socket_read_states.len());
726        for (_, mut state) in socket_read_states {
727            state.queued.push_back(Err(Error::Transport(None)));
728            state.wakers.into_iter().for_each(Waker::wake);
729        }
730
731        deferred_wakers.into_iter().for_each(Waker::wake);
732    }
733}
734
735impl Client {
736    /// Create a new FDomain client. The `transport` argument should contain the
737    /// established connection to the target, ready to communicate the FDomain
738    /// protocol.
739    ///
740    /// The second return item is a future that must be polled to keep
741    /// transactions running.
742    pub fn new(
743        transport: impl FDomainTransport + 'static,
744    ) -> (Arc<Self>, impl Future<Output = ()> + Send + 'static) {
745        let ret = Arc::new(Client(Mutex::new(ClientInner {
746            transport: Transport::Transport(Box::pin(transport), VecDeque::new(), Vec::new()),
747            transactions: HashMap::new(),
748            socket_read_states: HashMap::new(),
749            channel_read_states: HashMap::new(),
750            next_tx_id: 1,
751            waiting_to_close: Vec::new(),
752            waiting_to_close_waker: std::task::Waker::noop().clone(),
753            wakers_to_wake: Vec::new(),
754        })));
755
756        let client_weak = Arc::downgrade(&ret);
757        let fut = futures::future::poll_fn(move |ctx| {
758            let Some(client) = client_weak.upgrade() else {
759                return Poll::Ready(());
760            };
761
762            let (ret, deferred_wakers) = {
763                let mut inner = client.0.lock();
764                let ret = inner.poll_transport(ctx);
765                let deferred_wakers = std::mem::replace(&mut inner.wakers_to_wake, Vec::new());
766                (ret, deferred_wakers)
767            };
768            deferred_wakers.into_iter().for_each(Waker::wake);
769            ret
770        });
771
772        let client_loop = ClientLoop { client: Arc::downgrade(&ret), fut: Box::pin(fut) };
773
774        (ret, client_loop)
775    }
776
777    /// Get the namespace for the connected FDomain. Calling this more than once is an error.
778    pub async fn namespace(self: &Arc<Self>) -> Result<Channel, Error> {
779        let new_handle = self.new_hid();
780        self.transaction(
781            ordinals::GET_NAMESPACE,
782            proto::FDomainGetNamespaceRequest { new_handle },
783            Responder::Namespace,
784        )
785        .await?;
786        Ok(Channel(Handle { id: new_handle.id, client: Arc::downgrade(self) }))
787    }
788
789    /// Create a new channel in the connected FDomain.
790    pub fn create_channel(self: &Arc<Self>) -> (Channel, Channel) {
791        let id_a = self.new_hid();
792        let id_b = self.new_hid();
793        let fut = self.transaction(
794            ordinals::CREATE_CHANNEL,
795            proto::ChannelCreateChannelRequest { handles: [id_a, id_b] },
796            Responder::CreateChannel,
797        );
798
799        fuchsia_async::Task::spawn(async move {
800            if let Err(e) = fut.await {
801                log::debug!("FDomain channel creation failed: {e}");
802            }
803        })
804        .detach();
805
806        (
807            Channel(Handle { id: id_a.id, client: Arc::downgrade(self) }),
808            Channel(Handle { id: id_b.id, client: Arc::downgrade(self) }),
809        )
810    }
811
812    /// Creates client and server endpoints connected to by a channel.
813    pub fn create_endpoints<F: crate::fidl::ProtocolMarker>(
814        self: &Arc<Self>,
815    ) -> (crate::fidl::ClientEnd<F>, crate::fidl::ServerEnd<F>) {
816        let (client, server) = self.create_channel();
817        let client_end = crate::fidl::ClientEnd::<F>::new(client);
818        let server_end = crate::fidl::ServerEnd::new(server);
819        (client_end, server_end)
820    }
821
822    /// Creates a client proxy and a server endpoint connected by a channel.
823    pub fn create_proxy<F: crate::fidl::ProtocolMarker>(
824        self: &Arc<Self>,
825    ) -> (F::Proxy, crate::fidl::ServerEnd<F>) {
826        let (client_end, server_end) = self.create_endpoints::<F>();
827        (client_end.into_proxy(), server_end)
828    }
829
830    /// Creates a client proxy and a server request stream connected by a channel.
831    pub fn create_proxy_and_stream<F: crate::fidl::ProtocolMarker>(
832        self: &Arc<Self>,
833    ) -> (F::Proxy, F::RequestStream) {
834        let (client_end, server_end) = self.create_endpoints::<F>();
835        (client_end.into_proxy(), server_end.into_stream())
836    }
837
838    /// Creates a client end and a server request stream connected by a channel.
839    pub fn create_request_stream<F: crate::fidl::ProtocolMarker>(
840        self: &Arc<Self>,
841    ) -> (crate::fidl::ClientEnd<F>, F::RequestStream) {
842        let (client_end, server_end) = self.create_endpoints::<F>();
843        (client_end, server_end.into_stream())
844    }
845
846    /// Create a new socket in the connected FDomain.
847    fn create_socket(self: &Arc<Self>, options: proto::SocketType) -> (Socket, Socket) {
848        let id_a = self.new_hid();
849        let id_b = self.new_hid();
850        let fut = self.transaction(
851            ordinals::CREATE_SOCKET,
852            proto::SocketCreateSocketRequest { handles: [id_a, id_b], options },
853            Responder::CreateSocket,
854        );
855
856        fuchsia_async::Task::spawn(async move {
857            if let Err(e) = fut.await {
858                log::debug!("FDomain socket creation failed: {e}");
859            }
860        })
861        .detach();
862
863        (
864            Socket(Handle { id: id_a.id, client: Arc::downgrade(self) }),
865            Socket(Handle { id: id_b.id, client: Arc::downgrade(self) }),
866        )
867    }
868
869    /// Create a new streaming socket in the connected FDomain.
870    pub fn create_stream_socket(self: &Arc<Self>) -> (Socket, Socket) {
871        self.create_socket(proto::SocketType::Stream)
872    }
873
874    /// Create a new datagram socket in the connected FDomain.
875    pub fn create_datagram_socket(self: &Arc<Self>) -> (Socket, Socket) {
876        self.create_socket(proto::SocketType::Datagram)
877    }
878
879    /// Create a new event pair in the connected FDomain.
880    pub fn create_event_pair(self: &Arc<Self>) -> (EventPair, EventPair) {
881        let id_a = self.new_hid();
882        let id_b = self.new_hid();
883        let fut = self.transaction(
884            ordinals::CREATE_EVENT_PAIR,
885            proto::EventPairCreateEventPairRequest { handles: [id_a, id_b] },
886            Responder::CreateEventPair,
887        );
888
889        fuchsia_async::Task::spawn(async move {
890            if let Err(e) = fut.await {
891                log::debug!("FDomain event pair creation failed: {e}");
892            }
893        })
894        .detach();
895
896        (
897            EventPair(Handle { id: id_a.id, client: Arc::downgrade(self) }),
898            EventPair(Handle { id: id_b.id, client: Arc::downgrade(self) }),
899        )
900    }
901
902    /// Create a new event handle in the connected FDomain.
903    pub fn create_event(self: &Arc<Self>) -> Event {
904        let id = self.new_hid();
905        let fut = self.transaction(
906            ordinals::CREATE_EVENT,
907            proto::EventCreateEventRequest { handle: id },
908            Responder::CreateEvent,
909        );
910
911        fuchsia_async::Task::spawn(async move {
912            if let Err(e) = fut.await {
913                log::debug!("FDomain event creation failed: {e}");
914            }
915        })
916        .detach();
917
918        Event(Handle { id: id.id, client: Arc::downgrade(self) })
919    }
920
921    /// Allocate a new HID, which should be suitable for use with the connected FDomain.
922    pub(crate) fn new_hid(&self) -> proto::NewHandleId {
923        // TODO: On the target side we have to keep a table of these which means
924        // we can automatically detect collisions in the random value. On the
925        // client side we'd have to add a whole data structure just for that
926        // purpose. Should we?
927        proto::NewHandleId { id: rand::random::<u32>() >> 1 }
928    }
929
930    /// Create a future which sends a FIDL message to the connected FDomain and
931    /// waits for a response.
932    ///
933    /// Calling this method queues the transaction synchronously. Awaiting is
934    /// only necessary to wait for the response.
935    pub(crate) fn transaction<S: fidl_message::Body, R: 'static, F>(
936        self: &Arc<Self>,
937        ordinal: u64,
938        request: S,
939        f: F,
940    ) -> impl Future<Output = Result<R, Error>> + 'static + use<S, R, F>
941    where
942        F: Fn(OneshotSender<Result<R, Error>>) -> Responder,
943    {
944        let mut inner = self.0.lock();
945
946        let (sender, receiver) = futures::channel::oneshot::channel();
947        inner.request(ordinal, request, f(sender));
948        receiver.map(|x| x.expect("Oneshot went away without reply!"))
949    }
950
951    /// Start getting streaming events for socket reads.
952    pub(crate) fn start_socket_streaming(&self, id: proto::HandleId) -> Result<(), Error> {
953        let mut inner = self.0.lock();
954        if let Some(e) = inner.transport.error() {
955            return Err(e.into());
956        }
957
958        let state = inner.socket_read_states.entry(id).or_insert_with(|| SocketReadState {
959            wakers: Vec::new(),
960            queued: VecDeque::new(),
961            is_streaming: false,
962            read_request_pending: false,
963        });
964
965        assert!(!state.is_streaming, "Initiated streaming twice!");
966        state.is_streaming = true;
967
968        inner.request(
969            ordinals::READ_SOCKET_STREAMING_START,
970            proto::SocketReadSocketStreamingStartRequest { handle: id },
971            Responder::Ignore,
972        );
973        Ok(())
974    }
975
976    /// Stop getting streaming events for socket reads. Doesn't return errors
977    /// because it's exclusively called in destructors where we have nothing to
978    /// do with them.
979    pub(crate) fn stop_socket_streaming(&self, id: proto::HandleId) {
980        let mut inner = self.0.lock();
981        if let Some(state) = inner.socket_read_states.get_mut(&id) {
982            if state.is_streaming {
983                state.is_streaming = false;
984                // TODO: Log?
985                let _ = inner.request(
986                    ordinals::READ_SOCKET_STREAMING_STOP,
987                    proto::ChannelReadChannelStreamingStopRequest { handle: id },
988                    Responder::Ignore,
989                );
990            }
991        }
992    }
993
994    /// Start getting streaming events for socket reads.
995    pub(crate) fn start_channel_streaming(&self, id: proto::HandleId) -> Result<(), Error> {
996        let mut inner = self.0.lock();
997        if let Some(e) = inner.transport.error() {
998            return Err(e.into());
999        }
1000        let state = inner.channel_read_states.entry(id).or_insert_with(|| ChannelReadState {
1001            wakers: Vec::new(),
1002            queued: VecDeque::new(),
1003            is_streaming: false,
1004            read_request_pending: false,
1005        });
1006
1007        assert!(!state.is_streaming, "Initiated streaming twice!");
1008        state.is_streaming = true;
1009
1010        inner.request(
1011            ordinals::READ_CHANNEL_STREAMING_START,
1012            proto::ChannelReadChannelStreamingStartRequest { handle: id },
1013            Responder::Ignore,
1014        );
1015
1016        Ok(())
1017    }
1018
1019    /// Stop getting streaming events for socket reads. Doesn't return errors
1020    /// because it's exclusively called in destructors where we have nothing to
1021    /// do with them.
1022    pub(crate) fn stop_channel_streaming(&self, id: proto::HandleId) {
1023        let mut inner = self.0.lock();
1024        if let Some(state) = inner.channel_read_states.get_mut(&id) {
1025            if state.is_streaming {
1026                state.is_streaming = false;
1027                // TODO: Log?
1028                let _ = inner.request(
1029                    ordinals::READ_CHANNEL_STREAMING_STOP,
1030                    proto::ChannelReadChannelStreamingStopRequest { handle: id },
1031                    Responder::Ignore,
1032                );
1033            }
1034        }
1035    }
1036
1037    /// Execute a read from a channel.
1038    pub(crate) fn poll_socket(
1039        &self,
1040        id: proto::HandleId,
1041        ctx: &mut Context<'_>,
1042        out: &mut [u8],
1043    ) -> Poll<Result<usize, Error>> {
1044        let mut inner = self.0.lock();
1045        if let Some(error) = inner.transport.error() {
1046            return Poll::Ready(Err(error.into()));
1047        }
1048
1049        let state = inner.socket_read_states.entry(id).or_insert_with(|| SocketReadState {
1050            wakers: Vec::new(),
1051            queued: VecDeque::new(),
1052            is_streaming: false,
1053            read_request_pending: false,
1054        });
1055
1056        if let Some(got) = state.queued.front_mut() {
1057            match got.as_mut() {
1058                Ok(data) => {
1059                    let read_size = std::cmp::min(data.data.len(), out.len());
1060                    out[..read_size].copy_from_slice(&data.data[..read_size]);
1061
1062                    if data.data.len() > read_size && !data.is_datagram {
1063                        let _ = data.data.drain(..read_size);
1064                    } else {
1065                        let _ = state.queued.pop_front();
1066                    }
1067
1068                    return Poll::Ready(Ok(read_size));
1069                }
1070                Err(_) => {
1071                    let err = state.queued.pop_front().unwrap().unwrap_err();
1072                    return Poll::Ready(Err(err));
1073                }
1074            }
1075        } else if !state.wakers.iter().any(|x| ctx.waker().will_wake(x)) {
1076            state.wakers.push(ctx.waker().clone());
1077        }
1078
1079        if !state.read_request_pending && !state.is_streaming {
1080            inner.request(
1081                ordinals::READ_SOCKET,
1082                proto::SocketReadSocketRequest { handle: id, max_bytes: out.len() as u64 },
1083                Responder::ReadSocket(id),
1084            );
1085        }
1086
1087        Poll::Pending
1088    }
1089
1090    /// Execute a read from a channel.
1091    pub(crate) fn poll_channel(
1092        &self,
1093        id: proto::HandleId,
1094        ctx: &mut Context<'_>,
1095        for_stream: bool,
1096    ) -> Poll<Option<Result<proto::ChannelMessage, Error>>> {
1097        let mut inner = self.0.lock();
1098        if let Some(error) = inner.transport.error() {
1099            return Poll::Ready(Some(Err(error.into())));
1100        }
1101
1102        let state = inner.channel_read_states.entry(id).or_insert_with(|| ChannelReadState {
1103            wakers: Vec::new(),
1104            queued: VecDeque::new(),
1105            is_streaming: false,
1106            read_request_pending: false,
1107        });
1108
1109        if let Some(got) = state.queued.pop_front() {
1110            return Poll::Ready(Some(got));
1111        } else if for_stream && !state.is_streaming {
1112            return Poll::Ready(None);
1113        } else if !state.wakers.iter().any(|x| ctx.waker().will_wake(x)) {
1114            state.wakers.push(ctx.waker().clone());
1115        }
1116
1117        if !state.read_request_pending && !state.is_streaming {
1118            inner.request(
1119                ordinals::READ_CHANNEL,
1120                proto::ChannelReadChannelRequest { handle: id },
1121                Responder::ReadChannel(id),
1122            );
1123        }
1124
1125        Poll::Pending
1126    }
1127
1128    /// Check whether this channel is streaming
1129    pub(crate) fn channel_is_streaming(&self, id: proto::HandleId) -> bool {
1130        let inner = self.0.lock();
1131        let Some(state) = inner.channel_read_states.get(&id) else {
1132            return false;
1133        };
1134        state.is_streaming
1135    }
1136
1137    /// Check that all the given handles are safe to transfer through a channel
1138    /// e.g. that there's no chance of in-flight reads getting dropped.
1139    pub(crate) fn clear_handles_for_transfer(&self, handles: &proto::Handles) {
1140        let inner = self.0.lock();
1141        match handles {
1142            proto::Handles::Handles(handles) => {
1143                for handle in handles {
1144                    assert!(
1145                        !(inner.channel_read_states.contains_key(handle)
1146                            || inner.socket_read_states.contains_key(handle)),
1147                        "Tried to transfer handle after reading"
1148                    );
1149                }
1150            }
1151            proto::Handles::Dispositions(dispositions) => {
1152                for disposition in dispositions {
1153                    match &disposition.handle {
1154                        proto::HandleOp::Move_(handle) => assert!(
1155                            !(inner.channel_read_states.contains_key(handle)
1156                                || inner.socket_read_states.contains_key(handle)),
1157                            "Tried to transfer handle after reading"
1158                        ),
1159                        // Pretty sure this should be fine regardless of read state.
1160                        proto::HandleOp::Duplicate(_) => (),
1161                    }
1162                }
1163            }
1164        }
1165    }
1166}