Skip to main content

iphone_cli/tcp/
mod.rs

1//! A userspace TCP stack that runs over any [`ReadWrite`] transport.
2//!
3//! iphone-cli: this is jktcp 0.1.8 by Jackson Coxson (MIT, see LICENSE.jktcp),
4//! taken into this crate so that it can be published without a `[patch]`.
5//! Changed here: two retransmission constants in `adapter.rs`, the capture's
6//! microseconds in `log_packet`, packet capture always built in, and the
7//! TUN-device tests left out.
8//!
9//! `jktcp` is intentionally simplified: it targets **reliable, ordered transports**
10//! (e.g. CDTunnel, a Unix socket carrying raw IP frames) where real packet loss is
11//! rare. It still implements stop-and-wait retransmission with exponential back-off
12//! so that transient glitches do not silently drop data.
13//!
14//! # Two usage patterns
15//!
16//! ## 1. `AdapterStream` — single-threaded, lifetime-bound
17//!
18//! [`stream::AdapterStream`] holds a `&mut` reference to the [`adapter::Adapter`],
19//! so it can only be used from the same task that owns the adapter.  One stream is
20//! alive at a time; while it exists the adapter is exclusively borrowed.
21//!
22//! **Choose this when** you open exactly one connection, drive it entirely from a
23//! single async task, and do not need to move the stream across tasks or store it
24//! on the heap alongside other things that reference the adapter.
25//!
26//! ```rust,ignore
27//! use iphone_cli::tcp::adapter::Adapter;
28//! use iphone_cli::tcp::stream::AdapterStream;
29//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
30//! # use std::net::{IpAddr, Ipv6Addr};
31//!
32//! # async fn example(transport: impl iphone_cli::tcp::ReadWrite + 'static) -> std::io::Result<()> {
33//! let mut adapter = Adapter::new(Box::new(transport), todo!(), todo!());
34//!
35//! let mut stream = AdapterStream::connect(&mut adapter, 1234).await?;
36//! stream.write_all(b"hello").await?;
37//!
38//! let mut buf = [0u8; 32];
39//! let n = stream.read(&mut buf).await?;
40//! println!("received: {:?}", &buf[..n]);
41//!
42//! stream.close().await?;
43//! # Ok(())
44//! # }
45//! ```
46//!
47//! ## 2. `AdapterHandle` / `StreamHandle` — multi-threaded, `'static`
48//!
49//! [`handle::AdapterHandle`] spawns the adapter's I/O loop onto the Tokio runtime.
50//! All interaction happens through channels, so the resulting [`handle::StreamHandle`]
51//! is `Send + Sync + 'static` and can be stored in `Arc`, passed across tasks, or
52//! boxed as a trait object.  Multiple streams can be open simultaneously.
53//!
54//! **Choose this when** any of the following apply:
55//! - You need to open more than one connection on the same adapter.
56//! - The stream must cross an `async` task boundary (e.g. `tokio::spawn`).
57//! - You store the stream in a struct alongside other owned data (no lifetime
58//!   parameter on the struct).
59//! - You expose the stream through an interface that requires `'static` bounds
60//!   (FFI, trait objects, etc.).
61//!
62//! ```rust,ignore
63//! use iphone_cli::tcp::adapter::Adapter;
64//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
65//! # use std::net::{IpAddr, Ipv6Addr};
66//!
67//! # async fn example(transport: impl iphone_cli::tcp::ReadWrite + 'static) -> std::io::Result<()> {
68//! let adapter = Adapter::new(Box::new(transport), todo!(), todo!());
69//! let mut handle = adapter.to_async_handle();
70//!
71//! let mut stream = handle.connect(1234).await?;
72//!
73//! // stream is Send + 'static — spawn it freely
74//! tokio::spawn(async move {
75//!     stream.write_all(b"hello").await.unwrap();
76//!     let mut buf = [0u8; 32];
77//!     stream.read(&mut buf).await.unwrap();
78//! });
79//! # Ok(())
80//! # }
81//! ```
82//!
83//! # Retransmission behaviour
84//!
85//! Both paths share the same [`adapter::Adapter`] logic:
86//!
87//! - Data is sent stop-and-wait: a second segment is not put on the wire until
88//!   the first is acknowledged.
89//! - If no ACK arrives within the RTO (200 ms initially, doubling on each retry),
90//!   the segment is retransmitted.
91//! - After 5 failed attempts the connection is closed with
92//!   `ErrorKind::TimedOut`.
93//! - Out-of-order segments (sequence number ahead of expected) are dropped
94//!   silently; duplicate segments (already acknowledged) are re-ACKed.
95//!
96//! # PCAP capture
97//!
98//! Call [`adapter::Adapter::pcap`] (or [`handle::AdapterHandle::pcap`]) with a
99//! file path before connecting to write a `.pcap` file that Wireshark can open.
100
101// Jackson Coxson
102
103use tokio::io::{AsyncRead, AsyncWrite};
104
105pub mod adapter;
106pub mod handle;
107pub mod packets;
108pub mod stream;
109
110/// `Option<PcapLog>` is the type of the optional pcap log handle threaded through
111/// packet parsing.
112pub type PcapLog = std::sync::Arc<tokio::sync::Mutex<tokio::fs::File>>;
113
114/// Time primitives that work across native and wasm32-unknown-unknown.
115///
116/// On native this is `tokio::time`; on wasm32 we route to `wasmtimer` because
117/// tokio's timer panics at runtime there (no timer backend available).
118/// `Instant` lives under `wasmtimer::std` rather than `wasmtimer::tokio`, so
119/// it's re-exported explicitly.
120#[allow(unused_imports)]
121pub(crate) mod time {
122    #[cfg(not(target_arch = "wasm32"))]
123    pub use tokio::time::*;
124    #[cfg(target_arch = "wasm32")]
125    pub use wasmtimer::std::Instant;
126    #[cfg(target_arch = "wasm32")]
127    pub use wasmtimer::tokio::*;
128}
129
130/// Spawn a `'static + Send` future on whatever executor is current. On native
131/// this is `tokio::spawn`; on wasm32 it's `wasm_bindgen_futures::spawn_local`,
132/// which doesn't require Send but accepts Send futures fine.
133#[allow(dead_code)]
134pub(crate) fn spawn<F>(fut: F)
135where
136    F: std::future::Future<Output = ()> + Send + 'static,
137{
138    #[cfg(not(target_arch = "wasm32"))]
139    {
140        tokio::spawn(fut);
141    }
142    #[cfg(target_arch = "wasm32")]
143    {
144        wasm_bindgen_futures::spawn_local(fut);
145    }
146}
147
148/// A marker trait for types that can act as the underlying transport.
149///
150/// Any type that implements [`tokio::io::AsyncRead`] + [`tokio::io::AsyncWrite`]
151/// + [`Unpin`] + [`Send`] + [`Sync`] + [`std::fmt::Debug`] automatically
152///   satisfies this bound via the blanket impl below.  Tokio's `TcpStream`,
153///   `UnixStream`, and the TUN-device wrappers used in tests all qualify.
154pub trait ReadWrite: AsyncRead + AsyncWrite + Unpin + Send + Sync + std::fmt::Debug {}
155
156impl<T: AsyncRead + AsyncWrite + Unpin + Send + Sync + std::fmt::Debug> ReadWrite for T {}
157
158pub(crate) fn log_packet(file: &PcapLog, packet: &[u8]) {
159    use std::time::{SystemTime, UNIX_EPOCH};
160    use tokio::io::AsyncWriteExt;
161    use tracing::trace;
162    trace!("Logging {} byte packet", packet.len());
163    let packet = packet.to_vec();
164    let file = file.to_owned();
165    let now = SystemTime::now();
166    tokio::task::spawn(async move {
167        let mut file = file.lock().await;
168        file.write_all(&(now.duration_since(UNIX_EPOCH).unwrap().as_secs() as u32).to_le_bytes())
169            .await
170            .unwrap();
171        let micros = now.duration_since(UNIX_EPOCH).unwrap().subsec_micros();
172        file.write_all(&micros.to_le_bytes())
173            .await
174            .unwrap();
175        file.write_all(&(packet.len() as u32).to_le_bytes())
176            .await
177            .unwrap();
178        file.write_all(&(packet.len() as u32).to_le_bytes())
179            .await
180            .unwrap();
181        file.write_all(&packet).await.unwrap();
182    });
183}
184
185/// idevice opens every service through this: RSD, the accessibility service,
186/// DVT and the rest connect over the tunnel by port.
187impl idevice::provider::RsdProvider for handle::AdapterHandle {
188    async fn connect_to_service_port(&mut self, port: u16) -> Result<Box<dyn idevice::ReadWrite>, idevice::IdeviceError> {
189        let s = self.connect(port).await?;
190        Ok(Box::new(s))
191    }
192}