diff --git a/android/README.md b/android/README.md index 91b702b..c7c6907 100644 --- a/android/README.md +++ b/android/README.md @@ -20,11 +20,25 @@ Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join wi The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic. +When Android chooses the first VPN address for a connection to another mesh, tsunagi translates TCP, UDP and ICMP echo traffic to that mesh’s address and returns replies to the original socket. Applications using other IPv4 protocols should bind to the address of their target mesh. If two sockets would use the same addresses, ports and protocol on the wire, the existing flow keeps its binding. + Applications using Android’s system resolver can connect to `.` and `.`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records. The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard. -Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications) +Open **Exit node…** on a network tile to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications) + +## Check two networks on an emulator + +Use a disposable ARM64 emulator. The test establishes a temporary VPN, sends UDP and system pings through the production TUN adapter to a local echo peer in each subnet, and checks that the originating applications receive their replies. Set `ANDROID_SERIAL` to that emulator's serial and run from the `android` directory. + +```sh +./gradlew :app:assembleDebug :app:assembleDebugAndroidTest +adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/debug/app-debug.apk +adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk +adb -s "$ANDROID_SERIAL" shell appops set cy.hexor.tsunagi ACTIVATE_VPN allow +adb -s "$ANDROID_SERIAL" shell am instrument -w cy.hexor.tsunagi.test/androidx.test.runner.AndroidJUnitRunner +``` ## Configure GitHub release signing diff --git a/android/app/build.gradle b/android/app/build.gradle index 7083206..d33aebf 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -22,6 +22,7 @@ android { applicationId 'cy.hexor.tsunagi' minSdk 26 targetSdk 35 + testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger() versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.1') ndk { abiFilters abi } @@ -33,7 +34,8 @@ def metadata = providers.exec { workingDir workspace commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android' }.standardOutput.asText.get() -def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' } +def cargoMetadata = new JsonSlurper().parseText(metadata) +def verifier = cargoMetadata.packages.find { it.name == 'rustls-platform-verifier-android' } repositories { maven { url new File(new File(verifier.manifest_path).parent, 'maven') @@ -43,7 +45,11 @@ repositories { google() mavenCentral() } -dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" } +dependencies { + implementation "rustls:rustls-platform-verifier:${verifier.version}" + androidTestImplementation 'androidx.test:runner:1.5.2' + androidTestImplementation 'junit:junit:4.13.2' +} abstract class BuildRust extends Exec { @OutputDirectory abstract DirectoryProperty getJniLibs() @@ -63,4 +69,20 @@ androidComponents.onVariants(androidComponents.selector().all()) { variant -> if (mode == 'release') args '--release' } variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs } + if (variant.androidTest != null) { + def probe = tasks.register('cargoVpnSourceProbe', BuildRust) { + workingDir workspace + jniLibs.set(layout.buildDirectory.dir('generated/rust/vpnSourceTest')) + inputs.files(nativeBuild.map { it.inputs.files }, fileTree("${workspace}/crates/tsunagi-android/examples")) + commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26', + 'build', '--locked', '--example', 'vpn_source_probe', '-p', 'tsunagi-android' + doLast { + project.copy { + from "${cargoMetadata.target_directory}/aarch64-linux-android/debug/examples/libvpn_source_probe.so" + into jniLibs.dir(abi) + } + } + } + variant.androidTest.sources.jniLibs.addGeneratedSourceDirectory(probe) { it.jniLibs } + } } diff --git a/android/app/src/androidTest/java/cy/hexor/tsunagi/VpnSourceTest.kt b/android/app/src/androidTest/java/cy/hexor/tsunagi/VpnSourceTest.kt new file mode 100644 index 0000000..cf3fd8f --- /dev/null +++ b/android/app/src/androidTest/java/cy/hexor/tsunagi/VpnSourceTest.kt @@ -0,0 +1,52 @@ +package cy.hexor.tsunagi + +import android.content.Context +import android.content.ContextWrapper +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.VpnService +import android.os.ParcelFileDescriptor +import android.os.SystemClock +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Test + +class VpnSourceTest { + private external fun checkSockets(fd: Int, networkCount: Int) + + @Test fun udpAndPingReceiveFromBothNetworksAfterAddingTheSecond() { + System.loadLibrary("vpn_source_probe") + val context = InstrumentationRegistry.getInstrumentation().targetContext + check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" } + val connectivity = context.getSystemService(ConnectivityManager::class.java) + // Android requires the manifest-declared service class. Attach it under the + // application UID without starting the agent and binding this process to the underlay. + val vpn = MeshVpn() + ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java) + .apply { isAccessible = true }.invoke(vpn, context) + MeshVpn::class.java.getDeclaredField("upstream").apply { isAccessible = true } + .set(vpn, connectivity.activeNetwork) + val hosts = listOf("198.18.234.1/24", "198.19.234.1/24") + val routes = listOf("198.18.234.0/24", "198.19.234.0/24") + fun establish(count: Int): ParcelFileDescriptor { + val fd = vpn.establishTun(hosts.take(count).joinToString(","), + routes.take(count).joinToString(","), "", 1280, false) + check(fd >= 0) { "VPN establishment failed" } + return ParcelFileDescriptor.adoptFd(fd) + } + fun checkVpn(fd: ParcelFileDescriptor, count: Int) { + val deadline = SystemClock.elapsedRealtime() + 5000 + while (true) { + val active = connectivity.activeNetwork + if (connectivity.getNetworkCapabilities(active)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true + && connectivity.getLinkProperties(active)?.linkAddresses?.size == count) break + check(SystemClock.elapsedRealtime() < deadline) { "Timed out waiting for VPN routes" } + SystemClock.sleep(25) + } + checkSockets(ParcelFileDescriptor.dup(fd.fileDescriptor).detachFd(), count) + } + establish(1).use { first -> + checkVpn(first, 1) + establish(2).use { both -> checkVpn(both, 2) } + } + } +} diff --git a/crates/tsunagi-android/Cargo.toml b/crates/tsunagi-android/Cargo.toml index 609e524..3c1ac27 100644 --- a/crates/tsunagi-android/Cargo.toml +++ b/crates/tsunagi-android/Cargo.toml @@ -11,6 +11,10 @@ publish = false [lib] crate-type = ["cdylib", "rlib"] +[[example]] +name = "vpn_source_probe" +crate-type = ["cdylib"] + [dependencies] tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.1" } tsunagi-ui = { path = "../tsunagi-ui" } diff --git a/crates/tsunagi-android/examples/vpn_source_probe.rs b/crates/tsunagi-android/examples/vpn_source_probe.rs new file mode 100644 index 0000000..4cdb7d4 --- /dev/null +++ b/crates/tsunagi-android/examples/vpn_source_probe.rs @@ -0,0 +1,142 @@ +//! Peer for the Android instrumentation test. Only the test APK packages it. +#![cfg(target_os = "android")] + +use jni::{JNIEnv, objects::JObject}; +use std::{ + fs::File, + io, + net::Ipv4Addr, + os::fd::{FromRawFd, OwnedFd}, + process::Command, + time::Duration, +}; +use tsunagi::overlay::{Cidr, TunDevice, TunFactory, TunRequest}; +use tsunagi_android::{dns::Resolver, tun::AndroidTun}; + +#[allow(unsafe_code)] +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_VpnSourceTest_checkSockets( + mut env: JNIEnv, + _: JObject, + fd: i32, + count: i32, +) { + // SAFETY: the instrumentation test transfers a duplicate with detachFd(). + let file = File::from(unsafe { OwnedFd::from_raw_fd(fd) }); + let result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .and_then(|rt| rt.block_on(check(file, count))); + if let Err(error) = result { + let _ = env.throw_new("java/lang/AssertionError", error.to_string()); + } +} + +async fn check(file: File, count: i32) -> io::Result<()> { + let factory = AndroidTun::new( + Resolver::new(|_| None), + move |_| file.try_clone(), + |_, _| Ok(()), + ); + let locals = [ + Ipv4Addr::new(198, 18, 234, 1), + Ipv4Addr::new(198, 19, 234, 1), + ]; + let mut req = TunRequest::bare("vpn", 1280); + for &local in locals.iter().take(count as usize) { + req.addresses + .push(Cidr::new(local.into(), 24).map_err(io::Error::other)?); + } + let tun = factory.create(req).await.map_err(io::Error::other)?; + for &local in locals.iter().take(count as usize) { + let mut octets = local.octets(); + octets[3] = 2; + let remote = Ipv4Addr::from(octets); + let exchange = async { + udp(tun.as_ref(), local, remote).await?; + ping(tun.as_ref(), local, remote).await + }; + tokio::time::timeout(Duration::from_secs(8), exchange) + .await + .map_err(|_| io::Error::other(format!("echo timed out on network {local}")))??; + } + Ok(()) +} + +async fn echo( + tun: &dyn TunDevice, + local: Ipv4Addr, + remote: Ipv4Addr, + protocol: u8, +) -> io::Result<()> { + use smoltcp::wire::{Icmpv4Message, Icmpv4Packet}; + loop { + let mut pkt = tun + .recv() + .await + .ok_or_else(|| io::Error::other("VPN closed"))? + .to_vec(); + if pkt.len() < 28 || pkt[0] != 0x45 || pkt[9] != protocol || pkt[16..20] != remote.octets() + { + continue; + } + if protocol == 17 { + if pkt[22..24] != 45678u16.to_be_bytes() || &pkt[28..] != b"mesh probe" { + continue; + } + // Swapping ports preserves the UDP checksum. + pkt[20..24].rotate_left(2); + } else { + let mut icmp = Icmpv4Packet::new_checked(&mut pkt[20..]).map_err(io::Error::other)?; + if icmp.msg_type() != Icmpv4Message::EchoRequest { + continue; + } + icmp.set_msg_type(Icmpv4Message::EchoReply); + icmp.fill_checksum(); + } + if pkt[12..16] != local.octets() { + return Err(io::Error::other(format!( + "peer {remote} saw source {:?}, expected {local}", + &pkt[12..16] + ))); + } + // Swapping addresses preserves the IPv4 checksum and the pseudo-header sum. + pkt[12..20].rotate_left(4); + return tun.send(pkt.into()).await.map_err(io::Error::other); + } +} + +async fn udp(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> { + let socket = tokio::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?; + socket.connect((remote, 45678)).await?; + socket.send(b"mesh probe").await?; + echo(tun, local, remote, 17).await?; + let mut reply = [0; 64]; + let n = socket.recv(&mut reply).await?; + if &reply[..n] != b"mesh probe" { + return Err(io::Error::other("UDP echo payload changed")); + } + Ok(()) +} + +async fn ping(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> { + let command = async { + let output = tokio::task::spawn_blocking(move || { + Command::new("/system/bin/ping") + .args(["-n", "-c", "1", "-w", "4"]) + .arg(remote.to_string()) + .output() + }) + .await??; + if !output.status.success() { + return Err(io::Error::other(format!( + "ping {remote} failed: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ))); + } + Ok(()) + }; + tokio::try_join!(command, echo(tun, local, remote, 1))?; + Ok(()) +} diff --git a/crates/tsunagi-android/src/lib.rs b/crates/tsunagi-android/src/lib.rs index 75c6a3a..94add38 100644 --- a/crates/tsunagi-android/src/lib.rs +++ b/crates/tsunagi-android/src/lib.rs @@ -6,6 +6,8 @@ pub mod plan; #[cfg(target_os = "android")] mod android; pub mod service; +#[cfg(unix)] +mod source; #[cfg(test)] mod tests; #[cfg(unix)] diff --git a/crates/tsunagi-android/src/source.rs b/crates/tsunagi-android/src/source.rs new file mode 100644 index 0000000..219ec68 --- /dev/null +++ b/crates/tsunagi-android/src/source.rs @@ -0,0 +1,685 @@ +//! Normalize Android's primary IPv4 source at the local VPN boundary. +use crate::plan::VpnPlan; +use bytes::Bytes; +use smoltcp::wire::{Ipv4Cidr, Ipv4Packet}; +use std::collections::HashMap; +use std::net::{IpAddr, Ipv4Addr}; +use std::time::{Duration, Instant}; +use tsunagi::overlay::packet::{Ipv4Reassembly, fragment_ipv4}; + +mod icmp; + +// No mappings are persisted, and a new flow cannot evict a live socket. +const MAX_FLOWS: usize = 4096; +const MAX_FRAGMENTED: usize = 16; +const UDP_IDLE: Duration = Duration::from_secs(120); +const TCP_IDLE: Duration = Duration::from_secs(2 * 60 * 60); +const ECHO_IDLE: Duration = Duration::from_secs(30); + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +struct WireFlow { + local: Ipv4Addr, + remote: Ipv4Addr, + protocol: u8, + local_port: u16, + remote_port: u16, +} + +impl WireFlow { + // ICMP errors quote as few as eight transport bytes; the caller validates + // the outer packet separately. Echo requests in opposite directions can + // have the same identifier without sharing a flow. + fn parse(packet: &[u8], outbound: bool) -> Option { + let h = usize::from(*packet.first()? & 15) * 4; + if packet[0] >> 4 != 4 + || h < 20 + || packet.len() < h + 8 + || u16::from_be_bytes([packet[6], packet[7]]) & 0x1fff != 0 + { + return None; + } + let src = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[12..16]).ok()?); + let dst = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[16..20]).ok()?); + let (local, remote) = if outbound { (src, dst) } else { (dst, src) }; + let protocol = packet[9]; + let data = &packet[h..]; + let (local_port, remote_port) = match protocol { + 6 | 17 => { + let src = u16::from_be_bytes([data[0], data[1]]); + let dst = u16::from_be_bytes([data[2], data[3]]); + if outbound { (src, dst) } else { (dst, src) } + } + 1 if matches!(data[0], 0 | 8) && data[1] == 0 => { + let id = u16::from_be_bytes([data[4], data[5]]); + (id, u16::from(outbound != (data[0] == 8))) + } + _ => return None, + }; + Some(Self { + local, + remote, + protocol, + local_port, + remote_port, + }) + } +} + +#[derive(Clone, Copy)] +struct Binding { + host: Ipv4Addr, + // A response from an unbound UDP listener can leave Android with the + // primary address even though its request targeted a different alias. + remote_initiated: bool, + expires: Instant, +} + +#[derive(Default)] +struct Domains { + aliases: Vec, + exit: Option, +} +impl Domains { + fn from_plan(plan: &VpnPlan) -> Self { + let aliases = plan + .addresses_in_order() + .into_iter() + .filter_map(|cidr| match cidr.addr { + IpAddr::V4(addr) if cidr.prefix_len <= 32 => { + Some(Ipv4Cidr::new(addr, cidr.prefix_len)) + } + _ => None, + }) + .collect(); + Self { + aliases, + exit: match (plan.full_tunnel, plan.exit) { + (true, Some(IpAddr::V4(addr))) => Some(addr), + _ => None, + }, + } + } + fn has(&self, addr: Ipv4Addr) -> bool { + self.aliases.iter().any(|alias| alias.address() == addr) + } + fn owner(&self, remote: Ipv4Addr) -> Option { + if remote.is_broadcast() + || remote.is_multicast() + || remote.is_unspecified() + || remote.is_loopback() + || self.has(remote) + { + return None; + } + if let Some(prefix) = self.aliases.iter().find(|p| p.contains_addr(&remote)) { + return (prefix.broadcast() != Some(remote)).then(|| prefix.address()); + } + self.exit + } +} + +/// Android's VPN routes name only the interface. The local host socket keeps +/// its address while authenticated mesh traffic uses the subnet's own alias. +pub(crate) struct SourceFlows { + domains: Domains, + mtu: u32, + flows: HashMap>, + primary_has_translations: bool, + last_sweep: Instant, + outgoing_parts: HashMap, + incoming_parts: HashMap, +} + +impl SourceFlows { + pub(crate) fn new(plan: &VpnPlan) -> Self { + Self { + domains: Domains::from_plan(plan), + mtu: plan.mtu, + flows: HashMap::new(), + primary_has_translations: false, + last_sweep: Instant::now(), + outgoing_parts: HashMap::new(), + incoming_parts: HashMap::new(), + } + } + + pub(crate) fn reconfigure(&mut self, plan: &VpnPlan) { + self.domains = Domains::from_plan(plan); + self.mtu = plan.mtu; + self.flows.retain(|_, table| { + table.retain(|wire, entry| { + self.domains.has(entry.host) && self.domains.owner(wire.remote) == Some(wire.local) + }); + !table.is_empty() + }); + self.refresh_primary(); + // Outstanding fragments belong to the previous VPN attachment. + self.outgoing_parts.clear(); + self.incoming_parts.clear(); + } + + fn refresh_primary(&mut self) { + if let Some(primary) = self.domains.aliases.first().map(Ipv4Cidr::address) { + self.primary_has_translations = self + .flows + .get(&primary) + .is_some_and(|table| table.values().any(|entry| entry.host != primary)); + if !self.primary_has_translations { + self.flows.remove(&primary); + } + } + } + + pub(crate) fn outbound(&mut self, packet: Bytes) -> Vec { + self.process(packet, true) + } + + pub(crate) fn inbound(&mut self, packet: Bytes) -> Vec { + self.process(packet, false) + } + + fn process(&mut self, packet: Bytes, outbound: bool) -> Vec { + if self.domains.aliases.len() < 2 || packet.first().is_none_or(|byte| byte >> 4 != 4) { + return vec![packet]; + } + let Ok(ip) = Ipv4Packet::new_checked(&packet[..]) else { + return vec![]; + }; + let h = usize::from(ip.header_len()); + if h < 20 || usize::from(ip.total_len()) != packet.len() || !ip.verify_checksum() { + return vec![]; + } + let (local, remote) = if outbound { + (ip.src_addr(), ip.dst_addr()) + } else { + (ip.dst_addr(), ip.src_addr()) + }; + // ICMP errors can come from a router other than the original peer. + let is_icmp = packet[9] == 1; + let owner = self.domains.owner(remote); + let primary = self.domains.aliases[0].address(); + // The kernel already uses the primary address for its own subnet. A + // primary change can leave earlier translated sockets draining there. + if local == primary + && (!outbound || owner == Some(primary)) + && !self.primary_has_translations + { + return vec![packet]; + } + if owner.is_none() && !(is_icmp && self.domains.has(local)) { + return vec![packet]; + } + if !self.domains.has(local) { + // Never translate addresses outside the local host's assignments. + return if outbound { vec![] } else { vec![packet] }; + } + + let now = Instant::now(); + if now.duration_since(self.last_sweep) >= Duration::from_secs(5) { + self.flows.retain(|_, table| { + table.retain(|_, entry| now < entry.expires); + !table.is_empty() + }); + self.refresh_primary(); + self.last_sweep = now; + } + let fragmented = u16::from_be_bytes([packet[6], packet[7]]) & 0x3fff != 0; + let packet = if fragmented { + let parts = if outbound { + &mut self.outgoing_parts + } else { + &mut self.incoming_parts + }; + let key = if outbound { + owner.unwrap_or(local) + } else { + local + }; + let Some(packet) = parts + .entry(key) + .or_default() + .accept(packet, MAX_FRAGMENTED, None) + else { + return vec![]; + }; + packet + } else { + packet + }; + let h = usize::from(packet[0] & 15) * 4; + let output = if is_icmp + && packet + .get(h) + .is_some_and(|kind| matches!(kind, 3 | 11 | 12)) + { + icmp::rewrite_error(packet, h, !outbound, |quote, quote_outbound| { + let flow = WireFlow::parse(quote, quote_outbound)?; + let wire = WireFlow { + local: self.domains.owner(flow.remote)?, + ..flow + }; + let entry = self + .flows + .get(&wire.local) + .and_then(|table| table.get(&wire)) + .filter(|entry| now < entry.expires); + let Some(entry) = entry else { + return (wire.local == primary && flow.local == primary) + .then_some((primary, primary)); + }; + if quote_outbound { + (flow.local == wire.local).then_some((wire.local, entry.host)) + } else { + (flow.local == entry.host).then_some((entry.host, wire.local)) + } + }) + } else { + self.translate(packet, h, local, remote, outbound, now) + }; + match output { + Some(packet) if fragmented => fragment_ipv4(packet, self.mtu), + Some(packet) => vec![packet], + None => vec![], + } + } + + fn translate( + &mut self, + packet: Bytes, + h: usize, + local: Ipv4Addr, + remote: Ipv4Addr, + outbound: bool, + now: Instant, + ) -> Option { + let Some(alias) = self.domains.owner(remote) else { + return Some(packet); + }; + // VIP/exit replies and any other special delivery already admitted by + // core may have a source outside the addressed subnet. + if !outbound && local != alias { + return Some(packet); + } + let Some(flow) = WireFlow::parse(&packet, outbound) else { + return (local == alias).then_some(packet); + }; + let data = &packet[h..]; + let idle = match flow.protocol { + 6 => { + let n = usize::from(*data.get(12)? >> 4) * 4; + if n < 20 || n > data.len() { + return None; + } + if data[13] & 5 != 0 { + UDP_IDLE + } else { + TCP_IDLE + } + } + 17 => { + if usize::from(u16::from_be_bytes([data[4], data[5]])) != data.len() { + return None; + } + UDP_IDLE + } + _ => ECHO_IDLE, + }; + let wire = WireFlow { + local: alias, + ..flow + }; + let table = self.flows.entry(alias).or_default(); + if table.get(&wire).is_some_and(|entry| entry.expires <= now) { + table.remove(&wire); + } + if !table.contains_key(&wire) { + if alias == self.domains.aliases.first()?.address() && local == alias { + return Some(packet); + } + if table.len() >= MAX_FLOWS { + return None; + } + if outbound && local != alias { + let primary = self.domains.aliases.first()?.address(); + if local != primary || flow.protocol == 6 && data[13] & 0x12 != 2 { + return None; + } + } + } + let entry = table.entry(wire).or_insert(Binding { + host: local, + remote_initiated: !outbound, + expires: now + idle, + }); + let target = if outbound { + if local != entry.host { + let wildcard_reply = entry.remote_initiated + && entry.host == alias + && flow.protocol == 17 + && self.domains.aliases.first()?.address() == local; + if !wildcard_reply { + return None; + } + } + alias + } else { + if entry.host != alias && flow.protocol == 6 && data[13] & 0x12 == 2 { + return None; + } + entry.host + }; + entry.expires = now + idle; + if target == local { + return Some(packet); + } + let mut out = packet.to_vec(); + let address = if outbound { 12 } else { 16 }; + out[address..address + 4].copy_from_slice(&target.octets()); + let check = u16::from_be_bytes([out[10], out[11]]); + out[10..12].copy_from_slice(&update_checksum(check, local, target).to_be_bytes()); + if matches!(flow.protocol, 6 | 17) { + let off = h + if flow.protocol == 6 { 16 } else { 6 }; + let check = u16::from_be_bytes([out[off], out[off + 1]]); + if flow.protocol == 6 || check != 0 { + let new = update_checksum(check, local, target); + let new = if new == 0 && flow.protocol == 17 { + u16::MAX + } else { + new + }; + out[off..off + 2].copy_from_slice(&new.to_be_bytes()); + } + } + Some(out.into()) + } +} + +/// RFC 1624 one's-complement adjustment for replacing an IPv4 address. +fn update_checksum(checksum: u16, old: Ipv4Addr, new: Ipv4Addr) -> u16 { + let mut sum = u32::from(!checksum); + for (old, new) in old + .octets() + .as_chunks::<2>() + .0 + .iter() + .zip(new.octets().as_chunks::<2>().0) + { + sum += u32::from(!u16::from_be_bytes(*old)) + u32::from(u16::from_be_bytes(*new)); + } + while sum >> 16 != 0 { + sum = (sum & 0xffff) + (sum >> 16); + } + !(sum as u16) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + use tsunagi::overlay::Cidr; + + const FIRST: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1); + const SECOND: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1); + const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 8); + + fn plan() -> VpnPlan { + VpnPlan { + addresses: vec![ + Cidr::new(FIRST.into(), 24).unwrap(), + Cidr::new(SECOND.into(), 24).unwrap(), + ], + mtu: 1280, + ..Default::default() + } + } + + fn udp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, payload: &[u8]) -> Bytes { + use smoltcp::wire::{IpAddress, Ipv4Packet, UdpPacket}; + let mut bytes = vec![0; 28 + payload.len()]; + bytes[0] = 0x45; + let size = bytes.len() as u16; + bytes[2..4].copy_from_slice(&size.to_be_bytes()); + bytes[8] = 64; + bytes[9] = 17; + bytes[12..16].copy_from_slice(&src.octets()); + bytes[16..20].copy_from_slice(&dst.octets()); + Ipv4Packet::new_unchecked(&mut bytes[..]).fill_checksum(); + let mut udp = UdpPacket::new_unchecked(&mut bytes[20..]); + udp.set_src_port(sport); + udp.set_dst_port(dport); + udp.set_len(size - 20); + udp.payload_mut().copy_from_slice(payload); + udp.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst)); + bytes.into() + } + + #[test] + fn connected_udp_keeps_its_kernel_address_while_the_peer_sees_the_right_alias() { + let mut flows = SourceFlows::new(&plan()); + let request = udp(FIRST, PEER, 4123, 1234, b"request"); + assert_eq!( + flows.outbound(request), + vec![udp(SECOND, PEER, 4123, 1234, b"request")] + ); + assert_eq!( + flows.inbound(udp(PEER, SECOND, 1234, 4123, b"reply")), + vec![udp(PEER, FIRST, 1234, 4123, b"reply")] + ); + assert!( + flows + .outbound(udp(SECOND, PEER, 4123, 1234, b"bound collision")) + .is_empty() + ); + assert_eq!( + flows.inbound(udp(PEER, SECOND, 1234, 4124, b"to a listener")), + vec![udp(PEER, SECOND, 1234, 4124, b"to a listener")] + ); + assert_eq!( + flows.outbound(udp(FIRST, PEER, 4124, 1234, b"wildcard listener reply")), + vec![udp(SECOND, PEER, 4124, 1234, b"wildcard listener reply")] + ); + assert_eq!( + flows.inbound(udp(PEER, SECOND, 1234, 4124, b"again")), + vec![udp(PEER, SECOND, 1234, 4124, b"again")] + ); + } + + #[test] + fn proper_bound_flows_and_limited_broadcast_keep_their_identity() { + let mut flows = SourceFlows::new(&plan()); + let native = udp(SECOND, PEER, 3000, 3001, b"bound"); + assert_eq!(flows.outbound(native.clone()), vec![native]); + assert!( + flows + .outbound(udp(FIRST, PEER, 3000, 3001, b"collision")) + .is_empty() + ); + let reply = udp(PEER, SECOND, 3001, 3000, b"native"); + assert_eq!(flows.inbound(reply.clone()), vec![reply]); + let broadcast = udp(FIRST, Ipv4Addr::BROADCAST, 3000, 3001, b"lan"); + assert_eq!(flows.outbound(broadcast.clone()), vec![broadcast]); + assert!( + flows + .outbound(udp(PEER, PEER, 3100, 3100, b"forged source")) + .is_empty() + ); + } + + fn packet(src: Ipv4Addr, dst: Ipv4Addr, protocol: u8, data: &[u8]) -> Bytes { + let mut out = vec![0; 20 + data.len()]; + let size = out.len() as u16; + out[0] = 0x45; + out[2..4].copy_from_slice(&size.to_be_bytes()); + out[8] = 64; + out[9] = protocol; + out[12..16].copy_from_slice(&src.octets()); + out[16..20].copy_from_slice(&dst.octets()); + out[20..].copy_from_slice(data); + Ipv4Packet::new_unchecked(&mut out).fill_checksum(); + out.into() + } + + fn tcp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, flags: u8) -> Bytes { + use smoltcp::wire::{IpAddress, TcpPacket}; + let mut data = [0; 20]; + data[..2].copy_from_slice(&sport.to_be_bytes()); + data[2..4].copy_from_slice(&dport.to_be_bytes()); + data[12] = 0x50; + data[13] = flags; + TcpPacket::new_unchecked(&mut data[..]) + .fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst)); + packet(src, dst, 6, &data) + } + + #[test] + fn tcp_keeps_direction_and_bindings_survive_unrelated_plans() { + let mut plan = plan(); + let mut flows = SourceFlows::new(&plan); + assert!(flows.outbound(tcp(FIRST, PEER, 333, 443, 16)).is_empty()); + assert_eq!( + flows.outbound(tcp(FIRST, PEER, 333, 443, 2)), + [tcp(SECOND, PEER, 333, 443, 2)] + ); + plan.broadcast = !plan.broadcast; + flows.reconfigure(&plan); + assert_eq!( + flows.inbound(tcp(PEER, SECOND, 443, 333, 18)), + [tcp(PEER, FIRST, 443, 333, 18)] + ); + // An inbound connection cannot replace a client's active translation. + assert!(flows.inbound(tcp(PEER, SECOND, 443, 333, 2)).is_empty()); + let inbound = tcp(PEER, SECOND, 12345, 80, 2); + assert_eq!(flows.inbound(inbound.clone()), [inbound]); + let syn_ack = tcp(SECOND, PEER, 80, 12345, 18); + assert_eq!(flows.outbound(syn_ack.clone()), [syn_ack]); + plan.addresses.remove(0); + flows.reconfigure(&plan); + assert!( + !flows + .flows + .values() + .any(|table| table.values().any(|e| e.host == FIRST)) + ); + } + + #[test] + fn a_new_primary_drains_earlier_translations_and_passes_its_own_packets() { + let mut plan = plan(); + let mut flows = SourceFlows::new(&plan); + assert_eq!(flows.outbound(udp(FIRST, PEER, 2222, 53, b"q")).len(), 1); + plan.full_tunnel = true; + plan.exit = Some(SECOND.into()); + flows.reconfigure(&plan); + assert_eq!( + flows.inbound(udp(PEER, SECOND, 53, 2222, b"a")), + [udp(PEER, FIRST, 53, 2222, b"a")] + ); + let bound = udp(SECOND, PEER, 4444, 443, b"native"); + assert_eq!(flows.outbound(bound.clone()), [bound]); + let native_reply = udp(PEER, SECOND, 443, 4444, b"r"); + assert_eq!(flows.inbound(native_reply.clone()), [native_reply]); + assert_eq!(flows.flows[&SECOND].len(), 1); + } + + #[test] + fn untracked_primary_errors_and_point_to_point_destinations_are_preserved() { + let mut plan = plan(); + let mut flows = SourceFlows::new(&plan); + let router = Ipv4Addr::new(10, 1, 0, 7); + let mut unreachable = vec![3, 1, 0, 0, 0, 0, 0, 0]; + unreachable.extend_from_slice(&udp(FIRST, router, 50_000, 7, b"probe")[..28]); + smoltcp::wire::Icmpv4Packet::new_unchecked(&mut unreachable).fill_checksum(); + let error = packet(router, FIRST, 1, &unreachable); + assert_eq!(flows.inbound(error.clone()), [error]); + let directed = udp(FIRST, Ipv4Addr::new(10, 2, 0, 255), 5, 6, b"broadcast"); + assert_eq!(flows.outbound(directed.clone()), [directed]); + let point = Ipv4Addr::new(10, 2, 0, 0); + plan.addresses[1] = Cidr::new(point.into(), 31).unwrap(); + flows.reconfigure(&plan); + assert_eq!( + flows.outbound(udp(FIRST, SECOND, 5, 6, b"p2p")), + [udp(point, SECOND, 5, 6, b"p2p")] + ); + } + + #[test] + fn echo_ids_can_match_in_both_directions() { + let mut flows = SourceFlows::new(&plan()); + let message = |src, dst, kind| { + use smoltcp::wire::Icmpv4Packet; + let mut data = [kind, 0, 0, 0, 0x12, 0x34, 0, 2]; + Icmpv4Packet::new_unchecked(&mut data[..]).fill_checksum(); + packet(src, dst, 1, &data) + }; + assert_eq!( + flows.outbound(message(FIRST, PEER, 8)), + [message(SECOND, PEER, 8)] + ); + assert_eq!( + flows.inbound(message(PEER, SECOND, 8)), + [message(PEER, SECOND, 8)] + ); + assert_eq!( + flows.outbound(message(SECOND, PEER, 0)), + [message(SECOND, PEER, 0)] + ); + assert_eq!( + flows.inbound(message(PEER, SECOND, 0)), + [message(PEER, FIRST, 0)] + ); + } + + #[test] + fn saturated_network_does_not_take_another_networks_capacity() { + let mut flows = SourceFlows::new(&plan()); + for port in 0..MAX_FLOWS { + assert_eq!( + flows + .outbound(udp(FIRST, PEER, port as u16, 53, b"q")) + .len(), + 1 + ); + } + assert!( + flows + .outbound(udp(FIRST, PEER, 60000, 53, b"full")) + .is_empty() + ); + let primary_peer = Ipv4Addr::new(10, 1, 0, 20); + let own = udp(FIRST, primary_peer, 60000, 53, b"first"); + assert_eq!(flows.outbound(own.clone()), [own]); + for entry in flows.flows.get_mut(&SECOND).unwrap().values_mut() { + entry.expires = Instant::now(); + } + flows.last_sweep -= Duration::from_secs(6); + assert_eq!( + flows.outbound(udp(FIRST, PEER, 60000, 53, b"free")).len(), + 1 + ); + assert_eq!(flows.flows[&SECOND].len(), 1); + } + + #[test] + fn fragmented_udp_translates_after_assembly_in_both_directions() { + let mut flows = SourceFlows::new(&plan()); + let mut original = udp(FIRST, PEER, 3333, 4444, &[7; 1900]); + let parts = fragment_ipv4(original.clone(), 1280); + let mut output = Vec::new(); + for part in parts.into_iter().rev() { + output.extend(flows.outbound(part)); + } + assert_eq!( + output, + fragment_ipv4(udp(SECOND, PEER, 3333, 4444, &[7; 1900]), 1280) + ); + original = udp(PEER, SECOND, 4444, 3333, &[8; 1900]); + let mut output = Vec::new(); + for part in fragment_ipv4(original, 1280) { + output.extend(flows.inbound(part)); + } + assert_eq!( + output, + fragment_ipv4(udp(PEER, FIRST, 4444, 3333, &[8; 1900]), 1280) + ); + } +} diff --git a/crates/tsunagi-android/src/source/icmp.rs b/crates/tsunagi-android/src/source/icmp.rs new file mode 100644 index 0000000..69ffdd2 --- /dev/null +++ b/crates/tsunagi-android/src/source/icmp.rs @@ -0,0 +1,226 @@ +//! Translate errors on existing flows, including truncated RFC 792 quotations. +use super::update_checksum; +use bytes::Bytes; +use smoltcp::wire::{Icmpv4Packet, IpProtocol, Ipv4Packet}; +use std::net::Ipv4Addr; + +pub(super) fn rewrite_error( + packet: Bytes, + header_len: usize, + inbound: bool, + mut lookup: impl FnMut(&[u8], bool) -> Option<(Ipv4Addr, Ipv4Addr)>, +) -> Option { + let outer = Ipv4Packet::new_checked(&packet[..]).ok()?; + if outer.version() != 4 + || header_len < 20 + || header_len != usize::from(outer.header_len()) + || usize::from(outer.total_len()) != packet.len() + || outer.next_header() != IpProtocol::Icmp + || outer.more_frags() + || outer.frag_offset() != 0 + || !outer.verify_checksum() + { + return None; + } + let icmp = outer.payload(); + if !Icmpv4Packet::new_checked(icmp).ok()?.verify_checksum() || !matches!(icmp[0], 3 | 11 | 12) { + return None; + } + let payload = &icmp[8..]; + // RFC 4884 records the padded quotation length in words when extensions follow. + let quote = match icmp[5] { + 0 => payload, + words => payload.get(..usize::from(words) * 4)?, + }; + quote.get(..20)?; + // The original total length may exceed the bytes the router chose to quote. + let inner = Ipv4Packet::new_unchecked(quote); + let inner_header = usize::from(inner.header_len()); + let quote_len = quote.len().min(usize::from(inner.total_len())); + if inner.version() != 4 + || inner_header < 20 + || quote_len < inner_header + 8 + || inner.frag_offset() != 0 + || !inner.verify_checksum() + { + return None; + } + let (outer_local, inner_local) = if inbound { + (outer.dst_addr(), inner.src_addr()) + } else { + (outer.src_addr(), inner.dst_addr()) + }; + if outer_local != inner_local { + return None; + } + let (old, new) = lookup("e[..quote_len], inbound)?; + if old != inner_local { + return None; + } + if old == new { + return Some(packet); + } + let transport = inner.next_header(); + let mut result = packet.to_vec(); + let quote_start = header_len + 8; + let mut inner = Ipv4Packet::new_unchecked(&mut result[quote_start..quote_start + quote_len]); + if inbound { + inner.set_src_addr(new); + } else { + inner.set_dst_addr(new); + } + inner.fill_checksum(); + let transport_bytes = &mut inner.into_inner()[inner_header..]; + // A minimum TCP quote includes ports and sequence number, but not its checksum. + let field = match transport { + IpProtocol::Tcp => transport_bytes.get_mut(16..18), + IpProtocol::Udp => transport_bytes.get_mut(6..8), + _ => None, + }; + if let Some(field) = field { + let previous = u16::from_be_bytes([field[0], field[1]]); + if previous != 0 || transport == IpProtocol::Tcp { + let adjusted = update_checksum(previous, old, new); + let value = if adjusted == 0 && transport == IpProtocol::Udp { + u16::MAX + } else { + adjusted + }; + field.copy_from_slice(&value.to_be_bytes()); + } + } + Icmpv4Packet::new_unchecked(&mut result[header_len..]).fill_checksum(); + let mut outer = Ipv4Packet::new_unchecked(&mut result); + if inbound { + outer.set_dst_addr(new); + } else { + outer.set_src_addr(new); + } + outer.fill_checksum(); + Some(result.into()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + use smoltcp::wire::{TcpPacket, UdpPacket}; + + const APP: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1); + const WIRE: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1); + const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 2); + const ROUTER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 3); + + fn ipv4(protocol: u8, src: Ipv4Addr, dst: Ipv4Addr, payload: &[u8]) -> Vec { + let mut p = vec![0; 20 + payload.len()]; + let total = p.len() as u16; + p[0] = 0x45; + p[2..4].copy_from_slice(&total.to_be_bytes()); + p[8] = 64; + p[9] = protocol; + p[12..16].copy_from_slice(&src.octets()); + p[16..20].copy_from_slice(&dst.octets()); + p[20..].copy_from_slice(payload); + Ipv4Packet::new_unchecked(&mut p).fill_checksum(); + p + } + + fn error(src: Ipv4Addr, dst: Ipv4Addr, quote: &[u8]) -> Bytes { + let mut icmp = vec![3, 4, 0, 0, 0, 0, 5, 0]; + icmp.extend_from_slice(quote); + Icmpv4Packet::new_unchecked(&mut icmp).fill_checksum(); + ipv4(1, src, dst, &icmp).into() + } + + #[test] + fn inbound_pmtu_restores_a_truncated_udp_quote_and_preserves_the_reporting_router() { + use crate::plan::VpnPlan; + use crate::source::SourceFlows; + use tsunagi::overlay::Cidr; + + let mut flows = SourceFlows::new(&VpnPlan { + addresses: vec![ + Cidr::new(APP.into(), 24).unwrap(), + Cidr::new(WIRE.into(), 24).unwrap(), + ], + mtu: 1280, + ..Default::default() + }); + let mut udp = [0x71; 16]; + udp[4..6].copy_from_slice(&16u16.to_be_bytes()); + UdpPacket::new_unchecked(&mut udp[..]).fill_checksum(&APP.into(), &PEER.into()); + let original = ipv4(17, APP, PEER, &udp); + let wire = flows.outbound(original.clone().into()).pop().unwrap(); + let p = error(ROUTER, WIRE, &wire[..28]); + let restored = flows.inbound(p).pop().unwrap(); + let outer = Ipv4Packet::new_checked(&restored[..]).unwrap(); + assert!(outer.verify_checksum()); + assert_eq!(outer.src_addr(), ROUTER); + assert_eq!(outer.dst_addr(), APP); + assert!( + Icmpv4Packet::new_checked(outer.payload()) + .unwrap() + .verify_checksum() + ); + assert_eq!(outer.payload()[6..8], 1280u16.to_be_bytes()); + assert_eq!(outer.payload()[8..], original[..28]); + } + + #[test] + fn outbound_error_restores_tcp_quotes_with_or_without_a_transport_checksum() { + let mut tcp = [0x41; 48]; + tcp[12] = 0x50; + TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &APP.into()); + let original = ipv4(6, PEER, APP, &tcp); + TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &WIRE.into()); + let wire = ipv4(6, PEER, WIRE, &tcp); + for length in [28, original.len()] { + let p = error(APP, PEER, &original[..length]); + let rewritten = rewrite_error(p, 20, false, |_, outbound| { + assert!(!outbound); + Some((APP, WIRE)) + }) + .unwrap(); + assert_eq!(rewritten, error(WIRE, PEER, &wire[..length])); + } + } + + #[test] + fn malformed_quotes_unknown_flows_and_unrelated_outer_addresses_are_rejected() { + let original = ipv4(17, WIRE, PEER, &[0; 8]); + let p = error(ROUTER, WIRE, &original); + assert_eq!( + rewrite_error(p.clone(), 20, true, |_, _| Some((WIRE, WIRE))), + Some(p.clone()) + ); + assert!(rewrite_error(p, 20, true, |_, _| None).is_none()); + for invalid in [ + error(ROUTER, APP, &original), + error(ROUTER, WIRE, &original[..26]), + { + let mut fragment = original.clone(); + fragment[7] = 1; + Ipv4Packet::new_unchecked(&mut fragment).fill_checksum(); + error(ROUTER, WIRE, &fragment) + }, + { + let mut damaged = error(ROUTER, WIRE, &original).to_vec(); + damaged[22] ^= 1; + damaged.into() + }, + ] { + assert!( + rewrite_error(invalid, 20, true, |_, _| panic!( + "invalid quote reached lookup" + )) + .is_none() + ); + } + // IPv4 UDP allows a zero checksum; translation may not enable it. + let restored = rewrite_error(error(ROUTER, WIRE, &original), 20, true, |_, _| { + Some((WIRE, APP)) + }) + .unwrap(); + assert_eq!(restored[54..56], [0, 0]); + } +} diff --git a/crates/tsunagi-android/src/tun.rs b/crates/tsunagi-android/src/tun.rs index 120bfce..10246d4 100644 --- a/crates/tsunagi-android/src/tun.rs +++ b/crates/tsunagi-android/src/tun.rs @@ -1,12 +1,13 @@ //! A stable packet device over the file descriptors replaced by VpnService. use crate::dns::{Resolver, stack::DnsPort}; use crate::plan::VpnPlan; +use crate::source::SourceFlows; use bytes::Bytes; use std::{ fmt, fs::File, io::{self, Read, Write}, - sync::Arc, + sync::{Arc, Mutex as StdMutex}, }; use tokio::{ io::unix::AsyncFd, @@ -30,6 +31,17 @@ struct Attachment { device: Arc>, addresses: Vec, dns: DnsPort, + packets: StdMutex>, +} +struct PacketState { + flows: SourceFlows, + // At most one reassembled IPv4 datagram's worth of remaining fragments. + pending: std::vec::IntoIter, +} +impl Attachment { + fn packets(&self) -> std::sync::MutexGuard<'_, Option> { + self.packets.lock().unwrap_or_else(|err| err.into_inner()) + } } type Descriptor = Option>; @@ -76,7 +88,7 @@ impl AndroidTun { return Ok(()); } let dns_address = next.dns_address(); - let fd = if next.addresses.is_empty() { + let device = if next.addresses.is_empty() { None } else { let address = dns_address.ok_or_else(|| OverlayError::Unavailable( @@ -92,12 +104,32 @@ impl AndroidTun { self.0.resolver.clone(), file.clone(), ); - Some(Arc::new(Attachment { + Some((file, dns)) + }; + // Only retire the old descriptor once establishing its replacement succeeds. + let previous = self + .0 + .current + .borrow() + .clone() + .and_then(|fd| fd.packets().take()); + let fd = device.map(|(file, dns)| { + let flows = if let Some(mut previous) = previous { + previous.flows.reconfigure(&next); + previous.flows + } else { + SourceFlows::new(&next) + }; + Arc::new(Attachment { device: file, addresses: next.addresses.iter().map(|a| a.addr).collect(), dns, - })) - }; + packets: StdMutex::new(Some(PacketState { + flows, + pending: Vec::new().into_iter(), + })), + }) + }); self.0.current.send_replace(fd); self.0.resolver.publish(dns_address); *applied = next; @@ -122,10 +154,14 @@ impl TunDevice for Device { fn recv(&self) -> BoxFuture<'_, Option> { Box::pin(async move { let mut rx = self.tun.0.current.subscribe(); - let mut buffer = vec![0; self.mtu as usize + 1]; + let mut buffer = Vec::new(); loop { let fd = rx.borrow_and_update().clone(); if let Some(fd) = fd { + if let Some(packet) = fd.packets().as_mut().and_then(|p| p.pending.next()) { + return Some(packet); + } + buffer.resize(self.mtu as usize + 1, 0); let result = tokio::select! { biased; _ = rx.changed() => continue, @@ -136,7 +172,14 @@ impl TunDevice for Device { continue; } buffer.truncate(len); - return Some(buffer.into()); + if let Some(state) = fd.packets().as_mut() { + let frames = state.flows.outbound(std::mem::take(&mut buffer).into()); + state.pending = frames.into_iter(); + if let Some(packet) = state.pending.next() { + return Some(packet); + } + } + continue; } } // No networks yet, last one left, or Android revoked this fd. @@ -152,14 +195,22 @@ impl TunDevice for Device { .borrow_and_update() .clone() .ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".into()))?; - let len = tokio::select! { - biased; - _ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())), - write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) => - write.map_err(|e| OverlayError::Other(e.to_string()))?, - }; - if len != packet.len() { - return Err(OverlayError::Other("short VPN datagram write".into())); + let packets = fd + .packets() + .as_mut() + .ok_or_else(|| OverlayError::Unavailable("VPN was reconfigured".into()))? + .flows + .inbound(packet); + for packet in packets { + let len = tokio::select! { + biased; + _ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())), + write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) => + write.map_err(|e| OverlayError::Other(e.to_string()))?, + }; + if len != packet.len() { + return Err(OverlayError::Other("short VPN datagram write".into())); + } } Ok(()) }) diff --git a/crates/tsunagi-core/src/overlay/packet.rs b/crates/tsunagi-core/src/overlay/packet.rs index e6c36ea..8a25945 100644 --- a/crates/tsunagi-core/src/overlay/packet.rs +++ b/crates/tsunagi-core/src/overlay/packet.rs @@ -6,6 +6,8 @@ use std::net::{Ipv4Addr, Ipv6Addr}; +pub use crate::vip::packet::{Reassembly as Ipv4Reassembly, fragments as fragment_ipv4}; + /// The addresses of an IP packet, as far as routing cares. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IpHeader { diff --git a/crates/tsunagi-core/src/vip/packet.rs b/crates/tsunagi-core/src/vip/packet.rs index 9e8661a..bbf1bbf 100644 --- a/crates/tsunagi-core/src/vip/packet.rs +++ b/crates/tsunagi-core/src/vip/packet.rs @@ -273,15 +273,19 @@ struct Datagram { bytes: usize, } type FragmentKey = (Option<[u8; 32]>, Ipv4Addr, Ipv4Addr, u16, u8); +/// Bounded IPv4 fragment assembly for a local packet consumer. #[derive(Debug, Default)] -pub(crate) struct Reassembly { +pub struct Reassembly { pending: HashMap, } impl Reassembly { + /// Forget incomplete datagrams after their five-second lifetime. pub fn expire(&mut self, now: Instant) { self.pending .retain(|_, d| now.duration_since(d.at) < Duration::from_secs(5)); } + /// Accept one fragment or complete packet. `max` bounds pending datagrams; + /// `scope` separates authenticated senders sharing an address domain. pub fn accept(&mut self, p: Bytes, max: usize, scope: Option<[u8; 32]>) -> Option { let n = header(&p)?; let flags = u16::from_be_bytes([p[6], p[7]]); @@ -363,7 +367,7 @@ impl Reassembly { } /// Re-fragments an assembled NAT datagram for the unchanged overlay MTU. -pub(crate) fn fragments(packet: Bytes, mtu: u32) -> Vec { +pub fn fragments(packet: Bytes, mtu: u32) -> Vec { if packet.len() <= mtu as usize { return vec![packet]; }