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    Abort {
65        host_port: u16,
66        done: oneshot::Sender<()>,
67    },
68    Send {
69        host_port: u16,
70        data: Vec<u8>,
71        res: oneshot::Sender<Result<(), std::io::Error>>,
72    },
73    BindUdp {
74        port: u16,
75        res: oneshot::Sender<(u16, mpsc::UnboundedReceiver<UdpDatagram>)>,
76    },
77    UnbindUdp {
78        port: u16,
79    },
80    SendUdp {
81        source_port: u16,
82        destination_port: u16,
83        data: Vec<u8>,
84        res: oneshot::Sender<Result<(), std::io::Error>>,
85    },
86        Pcap {
87        path: PathBuf,
88        res: oneshot::Sender<Result<(), std::io::Error>>,
89    },
90    Die,
91}
92
93/// Push newly received bytes to each connection's channel, and close the ones
94/// that died, passing any error other than a clean EOF on to the reader.
95async fn deliver(
96    adapter: &mut crate::tcp::adapter::Adapter,
97    handles: &mut HashMap<u16, mpsc::UnboundedSender<Result<Vec<u8>, std::io::Error>>>,
98) {
99    let mut dead = Vec::new();
100    for (&hp, tx) in handles.iter() {
101        match adapter.uncache_all(hp) {
102            Ok(buf) if !buf.is_empty() => {
103                if tx.send(Ok(buf)).is_err() {
104                    dead.push(hp);
105                }
106            }
107            Err(e) => {
108                let _ = tx.send(Err(e));
109                dead.push(hp);
110            }
111            _ => {}
112        }
113    }
114    for hp in dead {
115        handles.remove(&hp);
116        let _ = adapter.close(hp).await;
117    }
118
119    let mut to_close = Vec::new();
120    for (&hp, tx) in handles.iter() {
121        if let Ok(ConnectionStatus::Error(kind)) = adapter.get_status(hp) {
122            if kind != std::io::ErrorKind::UnexpectedEof {
123                let _ = tx.send(Err(std::io::Error::from(kind)));
124            }
125            to_close.push(hp);
126        }
127    }
128    for hp in to_close {
129        handles.remove(&hp);
130        // Best-effort close. For RST this just tidies state on our side
131        let _ = adapter.close(hp).await;
132    }
133}
134
135/// A cloneable, thread-safe handle to a background [`crate::tcp::adapter::Adapter`] task.
136///
137/// Constructed via [`crate::tcp::adapter::Adapter::to_async_handle`]. Cheap to clone.
138/// Each clone shares the same channel sender to the background task.
139///
140/// Drop all clones (or call [`AdapterHandle::close`]) to shut down the background task.
141#[derive(Debug, Clone)]
142pub struct AdapterHandle {
143    sender: mpsc::UnboundedSender<HandleMessage>,
144    host_ip: IpAddr,
145    peer_ip: IpAddr,
146}
147
148impl AdapterHandle {
149    pub fn new(mut adapter: crate::tcp::adapter::Adapter) -> Self {
150        let host_ip = adapter.host_ip();
151        let peer_ip = adapter.peer_ip();
152        let (tx, mut rx) = mpsc::unbounded_channel::<HandleMessage>();
153        crate::tcp::spawn(async move {
154            let mut handles: HashMap<u16, mpsc::UnboundedSender<Result<Vec<u8>, std::io::Error>>> =
155                HashMap::new();
156            let mut udp_handles: HashMap<u16, mpsc::UnboundedSender<UdpDatagram>> = HashMap::new();
157
158            loop {
159                let has_pending_work = adapter.has_pending_work();
160
161                tokio::select! {
162                    // check for messages for us
163                    msg = rx.recv() => {
164                        match msg {
165                            Some(m) => match m {
166                                HandleMessage::ConnectToPort { target, res } => {
167                                    let connect_response = match adapter.connect(target).await {
168                                        Ok(c) => {
169                                            let (ptx, prx) = mpsc::unbounded_channel();
170                                            handles.insert(c, ptx);
171                                            Ok((c, prx))
172                                        }
173                                        Err(e) => Err(e),
174                                    };
175                                    res.send(connect_response).ok();
176                                }
177                                HandleMessage::Close { host_port } => {
178                                    handles.remove(&host_port);
179                                    adapter.close(host_port).await.ok();
180                                }
181                                HandleMessage::Abort { host_port, done } => {
182                                    handles.remove(&host_port);
183                                    adapter.abort(host_port).await.ok();
184                                    done.send(()).ok();
185                                }
186                                HandleMessage::Send {
187                                    host_port,
188                                    data,
189                                    res,
190                                } => {
191                                    if let Err(e) = adapter.queue_send(&data, host_port) {
192                                        res.send(Err(e)).ok();
193                                    } else {
194                                        let response = adapter.write_buffer_flush().await;
195                                        res.send(response).ok();
196                                    }
197                                }
198                                HandleMessage::BindUdp { port, res } => {
199                                    let bound = adapter.bind_udp(port);
200                                    let (utx, urx) = mpsc::unbounded_channel();
201                                    udp_handles.insert(bound, utx);
202                                    res.send((bound, urx)).ok();
203                                }
204                                HandleMessage::UnbindUdp { port } => {
205                                    udp_handles.remove(&port);
206                                    adapter.unbind_udp(port);
207                                }
208                                HandleMessage::SendUdp {
209                                    source_port,
210                                    destination_port,
211                                    data,
212                                    res,
213                                } => {
214                                    let r = adapter
215                                        .send_udp(source_port, destination_port, &data)
216                                        .await;
217                                    res.send(r).ok();
218                                }
219                                                                HandleMessage::Pcap {
220                                    path,
221                                    res
222                                } => {
223                                    res.send(adapter.pcap(path).await).ok();
224                                },
225                                HandleMessage::Die => {
226                                    break;
227                                }
228                            },
229                            None => {
230                                break;
231                            },
232                        }
233                    }
234
235                    r = adapter.process_tcp_packet() => {
236                        if let Err(e) = r {
237                            // propagate error to all streams; close them
238                            for (hp, tx) in handles.drain() {
239                                let _ = tx.send(Err(e.kind().into())); // or clone/convert
240                                let _ = adapter.close(hp).await;
241                            }
242                            break;
243                        }
244
245                        // Forward any inbound UDP datagrams to their bound port's channel.
246                        if !udp_handles.is_empty() {
247                            for dg in adapter.udp_drain() {
248                                if let Some(tx) = udp_handles.get(&dg.destination_port) {
249                                    let _ = tx.send(dg);
250                                }
251                            }
252                        }
253
254                        // An ACK in that packet may have cleared `unacked` for some
255                        // connection; flush now instead of waiting up to 1ms for the tick.
256                        let _ = adapter.write_buffer_flush().await;
257                    }
258
259                    _ = crate::tcp::time::sleep(std::time::Duration::from_millis(250)), if has_pending_work => {
260                        let _ = adapter.write_buffer_flush().await;
261                    }
262                }
263
264                deliver(&mut adapter, &mut handles).await;
265            }
266        });
267
268        Self {
269            sender: tx,
270            host_ip,
271            peer_ip,
272        }
273    }
274
275    /// The local (host) IP of the tunnel — use this as the RTP `receiverIP`.
276    pub fn host_ip(&self) -> IpAddr {
277        self.host_ip
278    }
279
280    /// The remote (device) IP of the tunnel.
281    pub fn peer_ip(&self) -> IpAddr {
282        self.peer_ip
283    }
284
285    /// Bind a local UDP port for connectionless send/receive. Pass 0 to let
286    /// the stack choose a free port (returned in [`UdpSocketHandle::local_port`]).
287    pub async fn bind_udp(&self, port: u16) -> Result<UdpSocketHandle, std::io::Error> {
288        let (res_tx, res_rx) = oneshot::channel();
289        if self
290            .sender
291            .send(HandleMessage::BindUdp { port, res: res_tx })
292            .is_err()
293        {
294            return Err(std::io::Error::new(
295                std::io::ErrorKind::NetworkUnreachable,
296                "adapter closed",
297            ));
298        }
299        match res_rx.await {
300            Ok((local_port, recv_channel)) => Ok(UdpSocketHandle {
301                local_port,
302                recv_channel: tokio::sync::Mutex::new(recv_channel),
303                send_channel: self.sender.clone(),
304            }),
305            Err(_) => Err(std::io::Error::new(
306                std::io::ErrorKind::BrokenPipe,
307                "adapter closed",
308            )),
309        }
310    }
311
312    pub async fn connect(&mut self, port: u16) -> Result<StreamHandle, std::io::Error> {
313        let (res_tx, res_rx) = oneshot::channel();
314        if self
315            .sender
316            .send(HandleMessage::ConnectToPort {
317                target: port,
318                res: res_tx,
319            })
320            .is_err()
321        {
322            return Err(std::io::Error::new(
323                std::io::ErrorKind::NetworkUnreachable,
324                "adapter closed",
325            ));
326        }
327
328        match timeout(std::time::Duration::from_secs(8), res_rx).await {
329            Ok(Ok(r)) => {
330                let (host_port, recv_channel) = r?;
331                Ok(StreamHandle {
332                    host_port,
333                    recv_channel: Mutex::new(recv_channel),
334                    send_channel: self.sender.clone(),
335                    read_buffer: Vec::new(),
336                    pending_writes: FuturesUnordered::new(),
337                    reset: None,
338                })
339            }
340            Ok(Err(_)) => Err(std::io::Error::new(
341                std::io::ErrorKind::BrokenPipe,
342                "adapter closed",
343            )),
344            Err(_) => Err(std::io::Error::new(
345                std::io::ErrorKind::TimedOut,
346                "channel recv timeout",
347            )),
348        }
349    }
350
351        pub async fn pcap(&mut self, path: impl Into<PathBuf>) -> Result<(), std::io::Error> {
352        let (res_tx, res_rx) = oneshot::channel();
353        let path: PathBuf = path.into();
354
355        if self
356            .sender
357            .send(HandleMessage::Pcap { path, res: res_tx })
358            .is_err()
359        {
360            return Err(std::io::Error::new(
361                std::io::ErrorKind::NetworkUnreachable,
362                "adapter closed",
363            ));
364        }
365
366        match res_rx.await {
367            Ok(r) => r,
368            Err(_) => Err(std::io::Error::new(
369                std::io::ErrorKind::BrokenPipe,
370                "adapter closed",
371            )),
372        }
373    }
374
375    pub async fn close(&mut self) -> Result<(), std::io::Error> {
376        if self.sender.send(HandleMessage::Die).is_err() {
377            return Err(std::io::Error::new(
378                std::io::ErrorKind::NetworkUnreachable,
379                "adapter closed",
380            ));
381        }
382        Ok(())
383    }
384}
385
386/// A `Send + Sync + 'static` stream produced by [`AdapterHandle::connect`].
387///
388/// Implements [`tokio::io::AsyncRead`] and [`tokio::io::AsyncWrite`], so it can
389/// be used anywhere a Tokio I/O stream is expected.
390///
391/// Dropping this handle automatically sends a `Close` message to the background
392/// task, which sends a TCP FIN and cleans up connection state, or an `Abort`
393/// (a RST) after [`StreamHandle::reset_on_drop`].
394#[derive(Debug)]
395pub struct StreamHandle {
396    host_port: u16,
397    // Mutex only exists to satisfy the `Sync` bound on `ReadWrite`; this is the
398    // sole owner of the receiver, so it should never actually contend.
399    recv_channel: Mutex<mpsc::UnboundedReceiver<Result<Vec<u8>, std::io::Error>>>,
400    send_channel: mpsc::UnboundedSender<HandleMessage>,
401
402    read_buffer: Vec<u8>,
403    pending_writes: FuturesUnordered<oneshot::Receiver<Result<(), std::io::Error>>>,
404    /// Set by [`StreamHandle::reset_on_drop`]; shared with the returned [`Reset`].
405    reset: Option<ResetSlot>,
406}
407
408/// The one reset a marked stream gets: taken by its drop or by [`Reset::now`],
409/// whichever comes first. After that the connection is gone, and the other
410/// sends nothing, so it can never reach a port a later connection reuses.
411type ResetSlot = std::sync::Arc<Mutex<Option<oneshot::Sender<()>>>>;
412
413impl StreamHandle {
414    pub fn close(&mut self) {
415        let _ = self.send_channel.send(HandleMessage::Close {
416            host_port: self.host_port,
417        });
418    }
419
420    /// Reset the connection (RST) when this stream is dropped, instead of
421    /// closing it (FIN). A peer that only writes, such as the phone's log
422    /// relay, never reads a FIN: it keeps sending into a closed port, and
423    /// serves no other client until it gives up about 30 s later.
424    ///
425    /// Set it before handing the stream to a library that keeps it: the
426    /// reset then goes out however that library ends.
427    pub fn reset_on_drop(&mut self) -> Reset {
428        let (done, sent) = oneshot::channel();
429        let slot = ResetSlot::default();
430        *slot.lock().unwrap() = Some(done);
431        self.reset = Some(slot.clone());
432        Reset { host_port: self.host_port, send_channel: self.send_channel.clone(), slot, sent: Some(sent) }
433    }
434}
435
436/// The reset of a stream marked with [`StreamHandle::reset_on_drop`].
437#[derive(Debug)]
438pub struct Reset {
439    host_port: u16,
440    send_channel: mpsc::UnboundedSender<HandleMessage>,
441    slot: ResetSlot,
442    sent: Option<oneshot::Receiver<()>>,
443}
444
445impl Reset {
446    /// Reset now instead of when the stream is dropped, for an owner that
447    /// cannot wait for a library to drop it, before the tunnel goes.
448    pub fn now(&self) {
449        if let Some(done) = self.slot.lock().unwrap().take() {
450            let _ = self.send_channel.send(HandleMessage::Abort { host_port: self.host_port, done });
451        }
452    }
453
454    /// Resolves once the reset has gone out, or once the tunnel is gone.
455    pub async fn sent(&mut self) {
456        if let Some(sent) = self.sent.take() {
457            let _ = sent.await;
458        }
459    }
460}
461
462impl AsyncRead for StreamHandle {
463    fn poll_read(
464        mut self: std::pin::Pin<&mut Self>,
465        cx: &mut std::task::Context<'_>,
466        buf: &mut tokio::io::ReadBuf<'_>,
467    ) -> std::task::Poll<std::io::Result<()>> {
468        // 1) Serve from cache first.
469        if !self.read_buffer.is_empty() {
470            let n = buf.remaining().min(self.read_buffer.len());
471            buf.put_slice(&self.read_buffer[..n]);
472            self.read_buffer.drain(..n); // fewer allocs than to_vec + reassign
473            return Poll::Ready(Ok(()));
474        }
475
476        // 2) Poll the channel directly; this registers the waker on Empty.
477        let mut lock = self
478            .recv_channel
479            .lock()
480            .expect("somehow the mutex was poisoned");
481        // this should always return, since we're the only owner of the mutex. The mutex is only
482        // used to satisfy the `Send` bounds of ReadWrite.
483        let mut extend_slice = Vec::new();
484        let res = match lock.poll_recv(cx) {
485            Poll::Pending => Poll::Pending,
486
487            // Disconnected/ended: map to BrokenPipe
488            Poll::Ready(None) => Poll::Ready(Err(std::io::Error::new(
489                std::io::ErrorKind::BrokenPipe,
490                "channel closed",
491            ))),
492
493            // Got a chunk: copy what fits; cache the tail.
494            Poll::Ready(Some(res)) => match res {
495                Ok(data) => {
496                    let n = buf.remaining().min(data.len());
497                    buf.put_slice(&data[..n]);
498                    if n < data.len() {
499                        extend_slice = data[n..].to_vec();
500                    }
501                    Poll::Ready(Ok(()))
502                }
503                Err(e) => Poll::Ready(Err(e)),
504            },
505        };
506        std::mem::drop(lock);
507        self.read_buffer.extend(extend_slice);
508        res
509    }
510}
511
512impl AsyncWrite for StreamHandle {
513    fn poll_write(
514        self: std::pin::Pin<&mut Self>,
515        _cx: &mut std::task::Context<'_>,
516        buf: &[u8],
517    ) -> std::task::Poll<Result<usize, std::io::Error>> {
518        trace!("poll psh {}", buf.len());
519        let (tx, rx) = oneshot::channel();
520        self.send_channel
521            .send(HandleMessage::Send {
522                host_port: self.host_port,
523                data: buf.to_vec(),
524                res: tx,
525            })
526            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed"))?;
527        self.pending_writes.push(rx);
528        Poll::Ready(Ok(buf.len()))
529    }
530
531    fn poll_flush(
532        mut self: std::pin::Pin<&mut Self>,
533        cx: &mut std::task::Context<'_>,
534    ) -> Poll<Result<(), std::io::Error>> {
535        while let Poll::Ready(maybe) = self.pending_writes.poll_next_unpin(cx) {
536            match maybe {
537                Some(Ok(Ok(()))) => {}
538                Some(Ok(Err(e))) => return Poll::Ready(Err(e)),
539                Some(Err(_canceled)) => {
540                    return Poll::Ready(Err(std::io::Error::new(
541                        std::io::ErrorKind::BrokenPipe,
542                        "channel closed",
543                    )));
544                }
545                None => break, // nothing pending
546            }
547        }
548        if self.pending_writes.is_empty() {
549            Poll::Ready(Ok(()))
550        } else {
551            Poll::Pending
552        }
553    }
554
555    fn poll_shutdown(
556        self: std::pin::Pin<&mut Self>,
557        _cx: &mut std::task::Context<'_>,
558    ) -> std::task::Poll<Result<(), std::io::Error>> {
559        // Just a drop will close the channel, which will trigger a close
560        std::task::Poll::Ready(Ok(()))
561    }
562}
563
564impl Drop for StreamHandle {
565    fn drop(&mut self) {
566        let host_port = self.host_port;
567        let message = match &self.reset {
568            None => Some(HandleMessage::Close { host_port }),
569            Some(slot) => slot.lock().unwrap().take().map(|done| HandleMessage::Abort { host_port, done }),
570        };
571        if let Some(message) = message {
572            let _ = self.send_channel.send(message);
573        }
574    }
575}
576
577/// A bound UDP port on the userspace stack. Connectionless: [`recv`] yields
578/// whole datagrams and [`send_to`] sends to a peer port. Dropping it unbinds
579/// the port.
580#[derive(Debug)]
581pub struct UdpSocketHandle {
582    local_port: u16,
583    // Mutex only to satisfy `Sync`; this is the sole owner of the receiver.
584    recv_channel: tokio::sync::Mutex<mpsc::UnboundedReceiver<UdpDatagram>>,
585    send_channel: mpsc::UnboundedSender<HandleMessage>,
586}
587
588impl UdpSocketHandle {
589    /// The local port datagrams are received on (and the source port of sends).
590    pub fn local_port(&self) -> u16 {
591        self.local_port
592    }
593
594    /// Await the next inbound datagram. Returns `BrokenPipe` if the stack closed.
595    pub async fn recv(&self) -> Result<UdpDatagram, std::io::Error> {
596        let mut lock = self.recv_channel.lock().await;
597        match lock.recv().await {
598            Some(dg) => Ok(dg),
599            None => Err(std::io::Error::new(
600                std::io::ErrorKind::BrokenPipe,
601                "adapter closed",
602            )),
603        }
604    }
605
606    /// Send a datagram from `local_port` to the peer's `destination_port`.
607    pub async fn send_to(
608        &self,
609        destination_port: u16,
610        data: Vec<u8>,
611    ) -> Result<(), std::io::Error> {
612        let (res_tx, res_rx) = oneshot::channel();
613        self.send_channel
614            .send(HandleMessage::SendUdp {
615                source_port: self.local_port,
616                destination_port,
617                data,
618                res: res_tx,
619            })
620            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "adapter closed"))?;
621        match res_rx.await {
622            Ok(r) => r,
623            Err(_) => Err(std::io::Error::new(
624                std::io::ErrorKind::BrokenPipe,
625                "adapter closed",
626            )),
627        }
628    }
629}
630
631impl Drop for UdpSocketHandle {
632    fn drop(&mut self) {
633        let _ = self.send_channel.send(HandleMessage::UnbindUdp {
634            port: self.local_port,
635        });
636    }
637}