Skip to main content

iphone_cli/tcp/
handle.rs

1//! Thread-safe handle over a background-task [`crate::tcp::adapter::Adapter`].
2//!
3//! [`AdapterHandle`] spawns the adapter's I/O loop onto whatever async
4//! executor is current (tokio on native, `wasm_bindgen_futures::spawn_local`
5//! on `wasm32-unknown-unknown`) and communicates with it through tokio
6//! `mpsc` channels. The resulting [`StreamHandle`] is `Send + Sync + 'static`,
7//! enabling use cases that [`crate::tcp::stream::AdapterStream`] cannot support:
8//!
9//! - **Multiple concurrent connections** on the same adapter.
10//! - Passing a stream to a `spawn` call or storing it in an `Arc<Mutex<…>>`.
11//! - Storing the stream in a struct without a lifetime parameter.
12//! - FFI or any context that requires `'static` bounds.
13//!
14//! The trade-off versus [`crate::tcp::stream::AdapterStream`] is a small channel
15//! round-trip on every write, and the adapter runs in a dedicated background
16//! task rather than being driven directly by the caller.
17//!
18//! # Background task
19//!
20//! [`AdapterHandle::new`] immediately spawns a task. The spawned task runs a
21//! `select!` loop that races three branches:
22//!
23//! 1. **Incoming messages**: connect/send/pcap/close requests from callers.
24//! 2. **Incoming packets**: reads the next frame from the transport and updates
25//!    connection state.
26//! 3. **1 ms tick**: calls `write_buffer_flush`, which drains pending writes and
27//!    checks for retransmission timeouts.
28//!
29//! The task exits when the last [`AdapterHandle`] is dropped or when
30//! [`AdapterHandle::close`] is called.
31
32use std::{collections::HashMap, net::IpAddr, sync::Mutex, task::Poll};
33
34use std::path::PathBuf;
35
36use futures_util::{StreamExt, stream::FuturesUnordered};
37use tokio::{
38    io::{AsyncRead, AsyncWrite},
39    sync::{mpsc, oneshot},
40};
41use tracing::trace;
42
43use crate::tcp::adapter::{ConnectionStatus, UdpDatagram};
44use crate::tcp::time::timeout;
45
46#[allow(clippy::type_complexity)]
47enum HandleMessage {
48    /// Returns the host port
49    ConnectToPort {
50        target: u16,
51        res: oneshot::Sender<
52            Result<
53                (
54                    u16,
55                    mpsc::UnboundedReceiver<Result<Vec<u8>, std::io::Error>>,
56                ),
57                std::io::Error,
58            >,
59        >,
60    },
61    Close {
62        host_port: u16,
63    },
64    Send {
65        host_port: u16,
66        data: Vec<u8>,
67        res: oneshot::Sender<Result<(), std::io::Error>>,
68    },
69    BindUdp {
70        port: u16,
71        res: oneshot::Sender<(u16, mpsc::UnboundedReceiver<UdpDatagram>)>,
72    },
73    UnbindUdp {
74        port: u16,
75    },
76    SendUdp {
77        source_port: u16,
78        destination_port: u16,
79        data: Vec<u8>,
80        res: oneshot::Sender<Result<(), std::io::Error>>,
81    },
82        Pcap {
83        path: PathBuf,
84        res: oneshot::Sender<Result<(), std::io::Error>>,
85    },
86    Die,
87}
88
89/// Push newly received bytes to each connection's channel, and close the ones
90/// that died, passing any error other than a clean EOF on to the reader.
91async fn deliver(
92    adapter: &mut crate::tcp::adapter::Adapter,
93    handles: &mut HashMap<u16, mpsc::UnboundedSender<Result<Vec<u8>, std::io::Error>>>,
94) {
95    let mut dead = Vec::new();
96    for (&hp, tx) in handles.iter() {
97        match adapter.uncache_all(hp) {
98            Ok(buf) if !buf.is_empty() => {
99                if tx.send(Ok(buf)).is_err() {
100                    dead.push(hp);
101                }
102            }
103            Err(e) => {
104                let _ = tx.send(Err(e));
105                dead.push(hp);
106            }
107            _ => {}
108        }
109    }
110    for hp in dead {
111        handles.remove(&hp);
112        let _ = adapter.close(hp).await;
113    }
114
115    let mut to_close = Vec::new();
116    for (&hp, tx) in handles.iter() {
117        if let Ok(ConnectionStatus::Error(kind)) = adapter.get_status(hp) {
118            if kind != std::io::ErrorKind::UnexpectedEof {
119                let _ = tx.send(Err(std::io::Error::from(kind)));
120            }
121            to_close.push(hp);
122        }
123    }
124    for hp in to_close {
125        handles.remove(&hp);
126        // Best-effort close. For RST this just tidies state on our side
127        let _ = adapter.close(hp).await;
128    }
129}
130
131/// A cloneable, thread-safe handle to a background [`crate::tcp::adapter::Adapter`] task.
132///
133/// Constructed via [`crate::tcp::adapter::Adapter::to_async_handle`]. Cheap to clone.
134/// Each clone shares the same channel sender to the background task.
135///
136/// Drop all clones (or call [`AdapterHandle::close`]) to shut down the background task.
137#[derive(Debug, Clone)]
138pub struct AdapterHandle {
139    sender: mpsc::UnboundedSender<HandleMessage>,
140    host_ip: IpAddr,
141    peer_ip: IpAddr,
142}
143
144impl AdapterHandle {
145    pub fn new(mut adapter: crate::tcp::adapter::Adapter) -> Self {
146        let host_ip = adapter.host_ip();
147        let peer_ip = adapter.peer_ip();
148        let (tx, mut rx) = mpsc::unbounded_channel::<HandleMessage>();
149        crate::tcp::spawn(async move {
150            let mut handles: HashMap<u16, mpsc::UnboundedSender<Result<Vec<u8>, std::io::Error>>> =
151                HashMap::new();
152            let mut udp_handles: HashMap<u16, mpsc::UnboundedSender<UdpDatagram>> = HashMap::new();
153
154            loop {
155                let has_pending_work = adapter.has_pending_work();
156
157                tokio::select! {
158                    // check for messages for us
159                    msg = rx.recv() => {
160                        match msg {
161                            Some(m) => match m {
162                                HandleMessage::ConnectToPort { target, res } => {
163                                    let connect_response = match adapter.connect(target).await {
164                                        Ok(c) => {
165                                            let (ptx, prx) = mpsc::unbounded_channel();
166                                            handles.insert(c, ptx);
167                                            Ok((c, prx))
168                                        }
169                                        Err(e) => Err(e),
170                                    };
171                                    res.send(connect_response).ok();
172                                }
173                                HandleMessage::Close { host_port } => {
174                                    handles.remove(&host_port);
175                                    adapter.close(host_port).await.ok();
176                                }
177                                HandleMessage::Send {
178                                    host_port,
179                                    data,
180                                    res,
181                                } => {
182                                    if let Err(e) = adapter.queue_send(&data, host_port) {
183                                        res.send(Err(e)).ok();
184                                    } else {
185                                        let response = adapter.write_buffer_flush().await;
186                                        res.send(response).ok();
187                                    }
188                                }
189                                HandleMessage::BindUdp { port, res } => {
190                                    let bound = adapter.bind_udp(port);
191                                    let (utx, urx) = mpsc::unbounded_channel();
192                                    udp_handles.insert(bound, utx);
193                                    res.send((bound, urx)).ok();
194                                }
195                                HandleMessage::UnbindUdp { port } => {
196                                    udp_handles.remove(&port);
197                                    adapter.unbind_udp(port);
198                                }
199                                HandleMessage::SendUdp {
200                                    source_port,
201                                    destination_port,
202                                    data,
203                                    res,
204                                } => {
205                                    let r = adapter
206                                        .send_udp(source_port, destination_port, &data)
207                                        .await;
208                                    res.send(r).ok();
209                                }
210                                                                HandleMessage::Pcap {
211                                    path,
212                                    res
213                                } => {
214                                    res.send(adapter.pcap(path).await).ok();
215                                },
216                                HandleMessage::Die => {
217                                    break;
218                                }
219                            },
220                            None => {
221                                break;
222                            },
223                        }
224                    }
225
226                    r = adapter.process_tcp_packet() => {
227                        if let Err(e) = r {
228                            // propagate error to all streams; close them
229                            for (hp, tx) in handles.drain() {
230                                let _ = tx.send(Err(e.kind().into())); // or clone/convert
231                                let _ = adapter.close(hp).await;
232                            }
233                            break;
234                        }
235
236                        // Forward any inbound UDP datagrams to their bound port's channel.
237                        if !udp_handles.is_empty() {
238                            for dg in adapter.udp_drain() {
239                                if let Some(tx) = udp_handles.get(&dg.destination_port) {
240                                    let _ = tx.send(dg);
241                                }
242                            }
243                        }
244
245                        // An ACK in that packet may have cleared `unacked` for some
246                        // connection; flush now instead of waiting up to 1ms for the tick.
247                        let _ = adapter.write_buffer_flush().await;
248                    }
249
250                    _ = crate::tcp::time::sleep(std::time::Duration::from_millis(250)), if has_pending_work => {
251                        let _ = adapter.write_buffer_flush().await;
252                    }
253                }
254
255                deliver(&mut adapter, &mut handles).await;
256            }
257        });
258
259        Self {
260            sender: tx,
261            host_ip,
262            peer_ip,
263        }
264    }
265
266    /// The local (host) IP of the tunnel — use this as the RTP `receiverIP`.
267    pub fn host_ip(&self) -> IpAddr {
268        self.host_ip
269    }
270
271    /// The remote (device) IP of the tunnel.
272    pub fn peer_ip(&self) -> IpAddr {
273        self.peer_ip
274    }
275
276    /// Bind a local UDP port for connectionless send/receive. Pass 0 to let
277    /// the stack choose a free port (returned in [`UdpSocketHandle::local_port`]).
278    pub async fn bind_udp(&self, port: u16) -> Result<UdpSocketHandle, std::io::Error> {
279        let (res_tx, res_rx) = oneshot::channel();
280        if self
281            .sender
282            .send(HandleMessage::BindUdp { port, res: res_tx })
283            .is_err()
284        {
285            return Err(std::io::Error::new(
286                std::io::ErrorKind::NetworkUnreachable,
287                "adapter closed",
288            ));
289        }
290        match res_rx.await {
291            Ok((local_port, recv_channel)) => Ok(UdpSocketHandle {
292                local_port,
293                recv_channel: tokio::sync::Mutex::new(recv_channel),
294                send_channel: self.sender.clone(),
295            }),
296            Err(_) => Err(std::io::Error::new(
297                std::io::ErrorKind::BrokenPipe,
298                "adapter closed",
299            )),
300        }
301    }
302
303    pub async fn connect(&mut self, port: u16) -> Result<StreamHandle, std::io::Error> {
304        let (res_tx, res_rx) = oneshot::channel();
305        if self
306            .sender
307            .send(HandleMessage::ConnectToPort {
308                target: port,
309                res: res_tx,
310            })
311            .is_err()
312        {
313            return Err(std::io::Error::new(
314                std::io::ErrorKind::NetworkUnreachable,
315                "adapter closed",
316            ));
317        }
318
319        match timeout(std::time::Duration::from_secs(8), res_rx).await {
320            Ok(Ok(r)) => {
321                let (host_port, recv_channel) = r?;
322                Ok(StreamHandle {
323                    host_port,
324                    recv_channel: Mutex::new(recv_channel),
325                    send_channel: self.sender.clone(),
326                    read_buffer: Vec::new(),
327                    pending_writes: FuturesUnordered::new(),
328                })
329            }
330            Ok(Err(_)) => Err(std::io::Error::new(
331                std::io::ErrorKind::BrokenPipe,
332                "adapter closed",
333            )),
334            Err(_) => Err(std::io::Error::new(
335                std::io::ErrorKind::TimedOut,
336                "channel recv timeout",
337            )),
338        }
339    }
340
341        pub async fn pcap(&mut self, path: impl Into<PathBuf>) -> Result<(), std::io::Error> {
342        let (res_tx, res_rx) = oneshot::channel();
343        let path: PathBuf = path.into();
344
345        if self
346            .sender
347            .send(HandleMessage::Pcap { path, res: res_tx })
348            .is_err()
349        {
350            return Err(std::io::Error::new(
351                std::io::ErrorKind::NetworkUnreachable,
352                "adapter closed",
353            ));
354        }
355
356        match res_rx.await {
357            Ok(r) => r,
358            Err(_) => Err(std::io::Error::new(
359                std::io::ErrorKind::BrokenPipe,
360                "adapter closed",
361            )),
362        }
363    }
364
365    pub async fn close(&mut self) -> Result<(), std::io::Error> {
366        if self.sender.send(HandleMessage::Die).is_err() {
367            return Err(std::io::Error::new(
368                std::io::ErrorKind::NetworkUnreachable,
369                "adapter closed",
370            ));
371        }
372        Ok(())
373    }
374}
375
376/// A `Send + Sync + 'static` stream produced by [`AdapterHandle::connect`].
377///
378/// Implements [`tokio::io::AsyncRead`] and [`tokio::io::AsyncWrite`], so it can
379/// be used anywhere a Tokio I/O stream is expected.
380///
381/// Dropping this handle automatically sends a `Close` message to the background
382/// task, which sends a TCP FIN and cleans up connection state.
383#[derive(Debug)]
384pub struct StreamHandle {
385    host_port: u16,
386    // Mutex only exists to satisfy the `Sync` bound on `ReadWrite`; this is the
387    // sole owner of the receiver, so it should never actually contend.
388    recv_channel: Mutex<mpsc::UnboundedReceiver<Result<Vec<u8>, std::io::Error>>>,
389    send_channel: mpsc::UnboundedSender<HandleMessage>,
390
391    read_buffer: Vec<u8>,
392    pending_writes: FuturesUnordered<oneshot::Receiver<Result<(), std::io::Error>>>,
393}
394
395impl StreamHandle {
396    pub fn close(&mut self) {
397        let _ = self.send_channel.send(HandleMessage::Close {
398            host_port: self.host_port,
399        });
400    }
401}
402
403impl AsyncRead for StreamHandle {
404    fn poll_read(
405        mut self: std::pin::Pin<&mut Self>,
406        cx: &mut std::task::Context<'_>,
407        buf: &mut tokio::io::ReadBuf<'_>,
408    ) -> std::task::Poll<std::io::Result<()>> {
409        // 1) Serve from cache first.
410        if !self.read_buffer.is_empty() {
411            let n = buf.remaining().min(self.read_buffer.len());
412            buf.put_slice(&self.read_buffer[..n]);
413            self.read_buffer.drain(..n); // fewer allocs than to_vec + reassign
414            return Poll::Ready(Ok(()));
415        }
416
417        // 2) Poll the channel directly; this registers the waker on Empty.
418        let mut lock = self
419            .recv_channel
420            .lock()
421            .expect("somehow the mutex was poisoned");
422        // this should always return, since we're the only owner of the mutex. The mutex is only
423        // used to satisfy the `Send` bounds of ReadWrite.
424        let mut extend_slice = Vec::new();
425        let res = match lock.poll_recv(cx) {
426            Poll::Pending => Poll::Pending,
427
428            // Disconnected/ended: map to BrokenPipe
429            Poll::Ready(None) => Poll::Ready(Err(std::io::Error::new(
430                std::io::ErrorKind::BrokenPipe,
431                "channel closed",
432            ))),
433
434            // Got a chunk: copy what fits; cache the tail.
435            Poll::Ready(Some(res)) => match res {
436                Ok(data) => {
437                    let n = buf.remaining().min(data.len());
438                    buf.put_slice(&data[..n]);
439                    if n < data.len() {
440                        extend_slice = data[n..].to_vec();
441                    }
442                    Poll::Ready(Ok(()))
443                }
444                Err(e) => Poll::Ready(Err(e)),
445            },
446        };
447        std::mem::drop(lock);
448        self.read_buffer.extend(extend_slice);
449        res
450    }
451}
452
453impl AsyncWrite for StreamHandle {
454    fn poll_write(
455        self: std::pin::Pin<&mut Self>,
456        _cx: &mut std::task::Context<'_>,
457        buf: &[u8],
458    ) -> std::task::Poll<Result<usize, std::io::Error>> {
459        trace!("poll psh {}", buf.len());
460        let (tx, rx) = oneshot::channel();
461        self.send_channel
462            .send(HandleMessage::Send {
463                host_port: self.host_port,
464                data: buf.to_vec(),
465                res: tx,
466            })
467            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed"))?;
468        self.pending_writes.push(rx);
469        Poll::Ready(Ok(buf.len()))
470    }
471
472    fn poll_flush(
473        mut self: std::pin::Pin<&mut Self>,
474        cx: &mut std::task::Context<'_>,
475    ) -> Poll<Result<(), std::io::Error>> {
476        while let Poll::Ready(maybe) = self.pending_writes.poll_next_unpin(cx) {
477            match maybe {
478                Some(Ok(Ok(()))) => {}
479                Some(Ok(Err(e))) => return Poll::Ready(Err(e)),
480                Some(Err(_canceled)) => {
481                    return Poll::Ready(Err(std::io::Error::new(
482                        std::io::ErrorKind::BrokenPipe,
483                        "channel closed",
484                    )));
485                }
486                None => break, // nothing pending
487            }
488        }
489        if self.pending_writes.is_empty() {
490            Poll::Ready(Ok(()))
491        } else {
492            Poll::Pending
493        }
494    }
495
496    fn poll_shutdown(
497        self: std::pin::Pin<&mut Self>,
498        _cx: &mut std::task::Context<'_>,
499    ) -> std::task::Poll<Result<(), std::io::Error>> {
500        // Just a drop will close the channel, which will trigger a close
501        std::task::Poll::Ready(Ok(()))
502    }
503}
504
505impl Drop for StreamHandle {
506    fn drop(&mut self) {
507        let _ = self.send_channel.send(HandleMessage::Close {
508            host_port: self.host_port,
509        });
510    }
511}
512
513/// A bound UDP port on the userspace stack. Connectionless: [`recv`] yields
514/// whole datagrams and [`send_to`] sends to a peer port. Dropping it unbinds
515/// the port.
516#[derive(Debug)]
517pub struct UdpSocketHandle {
518    local_port: u16,
519    // Mutex only to satisfy `Sync`; this is the sole owner of the receiver.
520    recv_channel: tokio::sync::Mutex<mpsc::UnboundedReceiver<UdpDatagram>>,
521    send_channel: mpsc::UnboundedSender<HandleMessage>,
522}
523
524impl UdpSocketHandle {
525    /// The local port datagrams are received on (and the source port of sends).
526    pub fn local_port(&self) -> u16 {
527        self.local_port
528    }
529
530    /// Await the next inbound datagram. Returns `BrokenPipe` if the stack closed.
531    pub async fn recv(&self) -> Result<UdpDatagram, std::io::Error> {
532        let mut lock = self.recv_channel.lock().await;
533        match lock.recv().await {
534            Some(dg) => Ok(dg),
535            None => Err(std::io::Error::new(
536                std::io::ErrorKind::BrokenPipe,
537                "adapter closed",
538            )),
539        }
540    }
541
542    /// Send a datagram from `local_port` to the peer's `destination_port`.
543    pub async fn send_to(
544        &self,
545        destination_port: u16,
546        data: Vec<u8>,
547    ) -> Result<(), std::io::Error> {
548        let (res_tx, res_rx) = oneshot::channel();
549        self.send_channel
550            .send(HandleMessage::SendUdp {
551                source_port: self.local_port,
552                destination_port,
553                data,
554                res: res_tx,
555            })
556            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "adapter closed"))?;
557        match res_rx.await {
558            Ok(r) => r,
559            Err(_) => Err(std::io::Error::new(
560                std::io::ErrorKind::BrokenPipe,
561                "adapter closed",
562            )),
563        }
564    }
565}
566
567impl Drop for UdpSocketHandle {
568    fn drop(&mut self) {
569        let _ = self.send_channel.send(HandleMessage::UnbindUdp {
570            port: self.local_port,
571        });
572    }
573}