test(udp): prove shared-source full-cone through the real kernel path

This commit is contained in:
eries authored and Zakk committed 2026-10-20 05:34:53 +11:00
1 parent 3ea1c24802
commit 9a146ed7de
5 files changed
+507 -20

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ Read with: `AGENTS.md` (Testing instructions); `real-ebpf.md` for the root-gated
- `dns/transport/tests_proto/quic_lifecycle.rs` covers failed/cancelled unpublished DoQ/DoH3 adapter cleanup and sticky worker failure with native ownership both enabled and absent. Exact cache owner and native DNS tests cover filter-before-budget snapshots and frozen pagination under unrelated cache pressure.
- `crates/honk-core/tests/dns_runtime_test.rs` — public reload, hosts, DNS policy/transport replacement and cache boundaries; loopback support stays in the suite.
- `crates/honk-core/src/control/tests.rs` and `tests/` — control-plane behavior, admission, diagnostics and health; shared fixtures live in `tests/support.rs`. Owner-specific connection/prober/DNS/NFQUEUE suites remain with their modules.
- `control/tests/udp_fullcone.rs` exercises Hy2/TUIC source sharing through production daens anyfrom and real TC client-only reply framing, including the first later send to a foreign peer. The ignored `netns_udp_full_cone_source_contract` uses a fresh child process and private network/mount namespaces per protocol/address-family case; shared real protocol peers live in `control/tests/support.rs`, not a fake packet transport.
- `control/tests/udp_fullcone.rs` exercises Hy2/TUIC and the generic shared-source arm (Shadowsocks AEAD, SOCKS5 UDP ASSOCIATE, plaintext Trojan, each over IPv4 and IPv6) through production daens anyfrom and real TC client-only reply framing, including the first later send to a foreign peer. The ignored `netns_udp_full_cone_source_contract` uses a fresh child process and private network/mount namespaces per protocol/address-family case; the QUIC peers live in `control/tests/support.rs` and the independent Shadowsocks/SOCKS5/Trojan wire peers in `control/tests/udp_fullcone/shared_peers.rs`, not a fake packet transport.
- `crates/honk-core/src/control/udp_endpoint/source.rs`, `source/reply.rs`, `source_tests.rs`, and `source_tests/{cross_source,regressions,score}.rs` — VLESS source-scope reuse, cross-source carrier isolation, original-address reply delivery, queue-versus-I/O admission, capacity, Score/health separation, send/reply evidence ordering, and retirement fencing.
- `control/udp_endpoint/source_quic_tests.rs` is unconditional under `cfg(test)` for Hy2/TUIC source ownership with `rprx` off/on: wire association reuse, foreign-peer delivery and exclusions, preparation rollback, queued/admitted send outcomes and sibling retirement. Process-global QUIC counter assertions run in separate child processes. Hy2/TUIC codec tests and `quic/defrag.rs` retain peer/reassembly boundary coverage.
- `control/udp_endpoint/source_shared_tests.rs` covers the generic `MultiTargetTransport` source arm with an in-memory transport: one association for several destinations, `confirmed` only on each view's first send, foreign peers, owner/projection exclusions, sibling retirement, preparation rollback and the retained endpoint permit. Wire framing, real-peer decoding and association reuse for Shadowsocks, Juicity, SOCKS5, Trojan and AnyTLS are tested beside each backend (`proxy/<protocol>` tests) against independent in-test peers.
Generated
+2
View File
@@ -1611,6 +1611,7 @@ dependencies = [
"libmimalloc-sys",
"libsystemd",
"lru",
"md-5",
"mimalloc",
"nix 0.31.3",
"parking_lot",
@@ -1628,6 +1629,7 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"serde_yaml",
"sha1 0.11.0",
"sha2 0.11.0",
"socket2",
"stats_alloc",
+3
View File
@@ -138,6 +138,9 @@ flate2 = { workspace = true, optional = true }
[dev-dependencies]
aya-ebpf-bindings.workspace = true
# Independent Shadowsocks AEAD key schedule in the full-cone fixtures.
md-5.workspace = true
sha1.workspace = true
nix = { workspace = true, features = ["signal"] }
# Test utilities
tokio = { workspace = true, features = ["test-util"] }
@@ -1,4 +1,4 @@
use super::support::{QuicUdpMode, QuicUdpPacket, QuicUdpPeer};
use super::support::{QuicUdpMode, QuicUdpPeer};
use super::{
NETNS_TEST_TIMEOUT, configure_test_edge, fresh_test_netns, in_test_netns, udp_test_config,
udp_test_forwarder, wait_for_test_address,
@@ -14,12 +14,15 @@ use honk_ebpf_common::dae_ip::In6Addr;
use honk_ebpf_common::{ConnState, RedirectEntry, RedirectTuple, TuplesKey};
use nix::mount::{MsFlags, mount};
use nix::sched::{CloneFlags, unshare};
use shared_peers::{SharedUdpMode, SharedUdpPeer};
use std::net::{IpAddr, SocketAddr};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use tokio::net::UdpSocket;
mod shared_peers;
const CASE: &str = "control::tests::udp_fullcone::netns_udp_full_cone_source_contract";
const CHILD: &str = "HONK_UDP_FULLCONE_CHILD";
@@ -36,7 +39,14 @@ fn netns_udp_full_cone_source_contract() -> anyhow::Result<()> {
}
// DAENS_FD is process-lifetime state, not a fixture that can be reset.
for family in ["v4", "v6"] {
for protocol in ["hy2", "tuic-datagram", "tuic-stream"] {
for protocol in [
"hy2",
"tuic-datagram",
"tuic-stream",
"ss",
"socks5",
"trojan",
] {
let case = format!("{family}/{protocol}");
let status = std::process::Command::new(std::env::current_exe()?)
.args([
@@ -60,12 +70,6 @@ fn run_child(case: &str) -> anyhow::Result<()> {
"full-cone acceptance requires root"
);
let (family, protocol) = case.split_once('/').context("missing child case family")?;
let mode = match protocol {
"hy2" => QuicUdpMode::Hysteria2,
"tuic-datagram" => QuicUdpMode::TuicDatagram,
"tuic-stream" => QuicUdpMode::TuicStream,
_ => anyhow::bail!("unknown protocol {protocol}"),
};
let ips: [&str; 5] = match family {
"v4" => [
"10.70.0.1",
@@ -152,14 +156,15 @@ fn run_child(case: &str) -> anyhow::Result<()> {
.enable_all()
.build()?
.block_on(async {
let mut peer = QuicUdpPeer::start(mode, SocketAddr::new(wan_ip, 0)).await?;
let mut peer = Peer::start(protocol, SocketAddr::new(wan_ip, 0)).await?;
let scenario = async {
let group = Group {
name: "fullcone".into(),
nodes: vec![peer.node.id],
nodes: vec![peer.node().id],
..Default::default()
};
let mut config = udp_test_config("fullcone", vec![peer.node.clone()], vec![group]);
let mut config =
udp_test_config("fullcone", vec![peer.node().clone()], vec![group]);
config.ensure_builtin_nodes();
config.global.lan_interface = vec!["honk-lan0".into()];
config.global.wan_interface = vec!["honk-wan0".into()];
@@ -245,7 +250,7 @@ fn run_child(case: &str) -> anyhow::Result<()> {
let second =
send_and_observe(&client, &target_b, &mut peer, b"client-to-B").await?;
ensure!(
first.connection == second.connection && first.session == second.session,
first.association == second.association,
"A/B used different wire associations"
);
ensure!(
@@ -294,9 +299,7 @@ fn run_child(case: &str) -> anyhow::Result<()> {
send_and_observe(&client, &foreign, &mut peer, b"first-client-to-C")
.await?;
ensure!(
third.connection == first.connection
&& third.session == first.session
&& third.mapping == first.mapping,
third.association == first.association && third.mapping == first.mapping,
"first C send did not reuse A/B's association"
);
foreign.send_to(b"C-after-contact", third.mapping).await?;
@@ -390,14 +393,14 @@ async fn receive(
async fn send_and_observe(
client: &UdpSocket,
target: &UdpSocket,
peer: &mut QuicUdpPeer,
peer: &mut Peer,
payload: &[u8],
) -> anyhow::Result<QuicUdpPacket> {
) -> anyhow::Result<Observed> {
let destination = target.local_addr()?;
client.send_to(payload, destination).await?;
let packet = tokio::time::timeout(NETNS_TEST_TIMEOUT, peer.packets.recv())
let packet = tokio::time::timeout(NETNS_TEST_TIMEOUT, peer.next())
.await?
.context("QUIC peer stopped before observing client packet")?;
.context("peer stopped before observing client packet")?;
ensure!(
packet.target == destination && packet.payload == payload,
"fixture did not observe the exact proxied client packet"
@@ -405,3 +408,70 @@ async fn send_and_observe(
receive(target, packet.mapping, payload).await?;
Ok(packet)
}
/// What every fixture reports for one relayed client datagram.
struct Observed {
/// Equal values mean one wire association (QUIC connection and session, or
/// the shared protocol's UDP source / control stream).
association: (u64, u32),
target: SocketAddr,
mapping: SocketAddr,
payload: Vec<u8>,
}
enum Peer {
Quic(QuicUdpPeer),
Shared(SharedUdpPeer),
}
impl Peer {
async fn start(protocol: &str, bind: SocketAddr) -> anyhow::Result<Self> {
let quic = match protocol {
"hy2" => Some(QuicUdpMode::Hysteria2),
"tuic-datagram" => Some(QuicUdpMode::TuicDatagram),
"tuic-stream" => Some(QuicUdpMode::TuicStream),
_ => None,
};
if let Some(mode) = quic {
return Ok(Self::Quic(QuicUdpPeer::start(mode, bind).await?));
}
let mode = match protocol {
"ss" => SharedUdpMode::Shadowsocks,
"socks5" => SharedUdpMode::Socks5,
"trojan" => SharedUdpMode::Trojan,
_ => anyhow::bail!("unknown protocol {protocol}"),
};
Ok(Self::Shared(SharedUdpPeer::start(mode, bind).await?))
}
fn node(&self) -> &honk_config::node::Node {
match self {
Self::Quic(peer) => &peer.node,
Self::Shared(peer) => &peer.node,
}
}
async fn next(&mut self) -> Option<Observed> {
match self {
Self::Quic(peer) => peer.packets.recv().await.map(|packet| Observed {
association: (packet.connection, packet.session),
target: packet.target,
mapping: packet.mapping,
payload: packet.payload,
}),
Self::Shared(peer) => peer.packets.recv().await.map(|packet| Observed {
association: (packet.association, 0),
target: packet.target,
mapping: packet.mapping,
payload: packet.payload,
}),
}
}
async fn close(self) -> anyhow::Result<()> {
match self {
Self::Quic(peer) => peer.close().await,
Self::Shared(peer) => peer.close().await,
}
}
}
@@ -0,0 +1,412 @@
//! Loopback servers for the shared-source protocols (Shadowsocks AEAD, SOCKS5
//! UDP ASSOCIATE, plaintext Trojan). Each maps one client association to ONE
//! unconnected egress socket, exactly like the Hy2/TUIC fixture in
//! `control/tests/support.rs`, so a destination that was never contacted can
//! reach the client through the association's mapped address. Wire formats are
//! spelled out here and never reuse the production codecs.
use aes_gcm::aead::Aead;
use aes_gcm::{Aes128Gcm, KeyInit, Nonce};
use anyhow::{Context, ensure};
use honk_config::node::{Node, OutboundConfig};
use rand::Rng;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, UdpSocket};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use tokio::task::{JoinHandle, JoinSet};
const PASSWORD: &str = "shared-source-test-password";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SharedUdpMode {
Shadowsocks,
Socks5,
Trojan,
}
/// One client datagram as the server relayed it to its destination.
#[derive(Debug)]
pub(super) struct SharedUdpPacket {
/// Serial of the client association (UDP source for SS, control TCP
/// connection for SOCKS5/Trojan): equal values mean one association.
pub(super) association: u64,
pub(super) target: SocketAddr,
/// The association's single egress socket, the address peers see.
pub(super) mapping: SocketAddr,
pub(super) payload: Vec<u8>,
}
pub(super) struct SharedUdpPeer {
pub(super) node: Node,
pub(super) packets: UnboundedReceiver<SharedUdpPacket>,
task: JoinHandle<anyhow::Result<()>>,
}
impl SharedUdpPeer {
pub(super) async fn start(mode: SharedUdpMode, bind: SocketAddr) -> anyhow::Result<Self> {
let (events, packets) = unbounded_channel();
let (address, task) = match mode {
SharedUdpMode::Shadowsocks => {
let server = UdpSocket::bind(bind).await?;
let address = server.local_addr()?;
let task = tokio::spawn(run_shadowsocks(server, address.ip(), events));
(address, task)
}
SharedUdpMode::Socks5 | SharedUdpMode::Trojan => {
let listener = TcpListener::bind(bind).await?;
let address = listener.local_addr()?;
let task = tokio::spawn(run_stream(mode, listener, address.ip(), events));
(address, task)
}
};
let outbound = match mode {
SharedUdpMode::Shadowsocks => {
OutboundConfig::Shadowsocks(honk_config::node::ShadowsocksConfig {
password: Some(PASSWORD.into()),
encryption: Some("aes-128-gcm".into()),
..Default::default()
})
}
SharedUdpMode::Socks5 => OutboundConfig::Socks5(Default::default()),
// `tls.enabled` defaults to false: the Trojan stream is plaintext.
SharedUdpMode::Trojan => OutboundConfig::Trojan(honk_config::node::TrojanConfig {
password: Some(PASSWORD.into()),
..Default::default()
}),
};
let mut node = Node {
name: format!("shared-{mode:?}"),
host: address.ip().to_string(),
address: address.to_string(),
port: address.port(),
outbound,
..Default::default()
};
node.id = node.derive_id();
Ok(Self {
node,
packets,
task,
})
}
/// A peer failure (bad frame, auth mismatch) surfaces here instead of as a
/// silent hang; a healthy peer is simply stopped.
pub(super) async fn close(self) -> anyhow::Result<()> {
if self.task.is_finished() {
return self.task.await?;
}
self.task.abort();
let _ = self.task.await;
Ok(())
}
}
fn put_addr(out: &mut Vec<u8>, address: SocketAddr) {
match address.ip() {
IpAddr::V4(ip) => {
out.push(1);
out.extend_from_slice(&ip.octets());
}
IpAddr::V6(ip) => {
out.push(4);
out.extend_from_slice(&ip.octets());
}
}
out.extend_from_slice(&address.port().to_be_bytes());
}
fn take_addr(wire: &[u8]) -> anyhow::Result<(SocketAddr, &[u8])> {
let (ip, rest): (IpAddr, _) = match wire.split_first() {
Some((1, rest)) if rest.len() >= 6 => (<[u8; 4]>::try_from(&rest[..4])?.into(), &rest[4..]),
Some((4, rest)) if rest.len() >= 18 => {
(<[u8; 16]>::try_from(&rest[..16])?.into(), &rest[16..])
}
_ => anyhow::bail!("fixture expects a numeric target"),
};
let port = u16::from_be_bytes([rest[0], rest[1]]);
Ok((SocketAddr::new(ip, port), &rest[2..]))
}
async fn read_addr<R: AsyncReadExt + Unpin>(stream: &mut R) -> anyhow::Result<SocketAddr> {
let mut atyp = [0u8; 1];
stream.read_exact(&mut atyp).await?;
let mut wire = [0u8; 19];
wire[0] = atyp[0];
let len = match atyp[0] {
1 => 6,
4 => 18,
other => anyhow::bail!("fixture expects a numeric target, got ATYP {other}"),
};
stream.read_exact(&mut wire[1..=len]).await?;
Ok(take_addr(&wire[..=len])?.0)
}
async fn egress(bind: IpAddr) -> anyhow::Result<Arc<UdpSocket>> {
// Marked like the Hy2/TUIC fixture so honk's own datapath ignores it.
Ok(Arc::new(
honk_outbound::util::udp_marked_bind(SocketAddr::new(bind, 0)).await?,
))
}
/// Forward everything the egress socket receives together with its real source.
fn spawn_egress_reader<T: Clone + Send + Sync + 'static>(
tasks: &mut JoinSet<anyhow::Result<()>>,
socket: Arc<UdpSocket>,
tag: T,
replies: UnboundedSender<(T, SocketAddr, Vec<u8>)>,
) {
tasks.spawn(async move {
let mut buffer = vec![0u8; 65536];
loop {
let (size, source) = socket.recv_from(&mut buffer).await?;
replies.send((tag.clone(), source, buffer[..size].to_vec()))?;
}
});
}
// ---- Shadowsocks AEAD (aes-128-gcm), one datagram = salt | AEAD(addr|payload) ----
fn ss_master_key() -> [u8; 16] {
// EVP_BytesToKey(MD5, no salt, one round) per shadowsocks.org/doc/aead.html.
use md5::{Digest, Md5};
let (mut key, mut previous) = (Vec::new(), Vec::new());
while key.len() < 16 {
previous.extend_from_slice(PASSWORD.as_bytes());
previous = Md5::digest(&previous).to_vec();
key.extend_from_slice(&previous);
}
key[..16].try_into().unwrap()
}
fn ss_cipher(master: &[u8; 16], salt: &[u8]) -> Aes128Gcm {
let mut subkey = [0u8; 16];
hkdf::Hkdf::<sha1::Sha1>::new(Some(salt), master)
.expand(b"ss-subkey", &mut subkey)
.unwrap();
Aes128Gcm::new_from_slice(&subkey).unwrap()
}
fn ss_open(master: &[u8; 16], packet: &[u8]) -> anyhow::Result<Vec<u8>> {
ensure!(packet.len() >= 16 + 16, "short Shadowsocks datagram");
let (salt, sealed) = packet.split_at(16);
ss_cipher(master, salt)
.decrypt(&Nonce::from([0u8; 12]), sealed)
.map_err(|_| anyhow::anyhow!("Shadowsocks datagram authentication failed"))
}
fn ss_seal(master: &[u8; 16], plain: &[u8]) -> Vec<u8> {
let mut salt = [0u8; 16];
rand::rng().fill_bytes(&mut salt);
let mut packet = salt.to_vec();
packet.extend(
ss_cipher(master, &salt)
.encrypt(&Nonce::from([0u8; 12]), plain)
.unwrap(),
);
packet
}
async fn run_shadowsocks(
server: UdpSocket,
bind: IpAddr,
events: UnboundedSender<SharedUdpPacket>,
) -> anyhow::Result<()> {
let master = ss_master_key();
let mut clients = HashMap::<SocketAddr, (u64, Arc<UdpSocket>)>::new();
let (reply_tx, mut reply_rx) = unbounded_channel();
let mut tasks = JoinSet::<anyhow::Result<()>>::new();
let mut buffer = vec![0u8; 65536];
loop {
tokio::select! {
received = server.recv_from(&mut buffer) => {
let (size, client) = received?;
let body = ss_open(&master, &buffer[..size])?;
let (target, payload) = take_addr(&body)?;
let serial = clients.len() as u64 + 1;
if !clients.contains_key(&client) {
let socket = egress(bind).await?;
spawn_egress_reader(&mut tasks, Arc::clone(&socket), client, reply_tx.clone());
clients.insert(client, (serial, socket));
}
let (association, socket) = &clients[&client];
socket.send_to(payload, target).await?;
events.send(SharedUdpPacket {
association: *association,
target,
mapping: socket.local_addr()?,
payload: payload.to_vec(),
})?;
}
Some((client, source, payload)) = reply_rx.recv() => {
let mut plain = Vec::new();
put_addr(&mut plain, source);
plain.extend_from_slice(&payload);
server.send_to(&ss_seal(&master, &plain), client).await?;
}
result = tasks.join_next(), if !tasks.is_empty() => result.unwrap()??,
}
}
}
// ---- SOCKS5 UDP ASSOCIATE (RFC 1928) and plaintext Trojan, one TCP control stream per association ----
async fn run_stream(
mode: SharedUdpMode,
listener: TcpListener,
bind: IpAddr,
events: UnboundedSender<SharedUdpPacket>,
) -> anyhow::Result<()> {
let mut associations = JoinSet::<anyhow::Result<()>>::new();
let mut serial = 0;
loop {
tokio::select! {
accepted = listener.accept() => {
let (stream, _) = accepted?;
serial += 1;
let events = events.clone();
associations.spawn(async move {
let result = match mode {
SharedUdpMode::Socks5 => socks5_association(stream, bind, serial, events).await,
_ => trojan_association(stream, bind, serial, events).await,
};
// honk opens a bare connection ahead of use and may drop it
// unused; one that dies before its request is no association.
match result {
Err(error) if error.downcast_ref::<std::io::Error>().is_some_and(
|error| error.kind() == std::io::ErrorKind::UnexpectedEof,
) => Ok(()),
result => result,
}
});
}
result = associations.join_next(), if !associations.is_empty() => result.unwrap()??,
}
}
}
async fn socks5_association(
mut control: tokio::net::TcpStream,
bind: IpAddr,
serial: u64,
events: UnboundedSender<SharedUdpPacket>,
) -> anyhow::Result<()> {
let mut head = [0u8; 2];
control.read_exact(&mut head).await?;
let mut methods = vec![0u8; usize::from(head[1])];
control.read_exact(&mut methods).await?;
ensure!(head[0] == 5 && methods.contains(&0), "SOCKS5 greeting");
control.write_all(&[5, 0]).await?;
let mut request = [0u8; 3];
control.read_exact(&mut request).await?;
ensure!(request == [5, 3, 0], "expected SOCKS5 UDP ASSOCIATE");
read_addr(&mut control).await?;
// One relay socket per association identifies it without trusting a client port.
let relay = UdpSocket::bind(SocketAddr::new(bind, 0)).await?;
let mut reply = vec![5, 0, 0];
put_addr(&mut reply, relay.local_addr()?);
control.write_all(&reply).await?;
let socket = egress(bind).await?;
let mapping = socket.local_addr()?;
let mut client = None;
let mut inbound = vec![0u8; 65536];
let mut outbound = vec![0u8; 65536];
let mut probe = [0u8; 1];
loop {
tokio::select! {
received = relay.recv_from(&mut inbound) => {
let (size, source) = received?;
client = Some(source);
ensure!(size >= 4 && inbound[..3] == [0, 0, 0], "SOCKS5 UDP header");
let (target, payload) = take_addr(&inbound[3..size])?;
socket.send_to(payload, target).await?;
events.send(SharedUdpPacket {
association: serial,
target,
mapping,
payload: payload.to_vec(),
})?;
}
received = socket.recv_from(&mut outbound) => {
let (size, source) = received?;
let client = client.context("reply before the first client datagram")?;
let mut wire = vec![0, 0, 0];
put_addr(&mut wire, source);
wire.extend_from_slice(&outbound[..size]);
relay.send_to(&wire, client).await?;
}
closed = control.read(&mut probe) => {
// The association lives exactly as long as its control stream.
ensure!(closed? == 0, "unexpected SOCKS5 control bytes");
return Ok(());
}
}
}
}
async fn trojan_association(
stream: tokio::net::TcpStream,
bind: IpAddr,
serial: u64,
events: UnboundedSender<SharedUdpPacket>,
) -> anyhow::Result<()> {
use sha2::{Digest, Sha224};
let (mut reader, mut writer) = stream.into_split();
let mut credential = [0u8; 56 + 2 + 1];
reader.read_exact(&mut credential).await?;
let expected: String = Sha224::digest(PASSWORD.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
ensure!(
credential[..56] == *expected.as_bytes() && credential[56..58] == *b"\r\n",
"Trojan credential"
);
ensure!(credential[58] == 3, "expected Trojan UDP command");
read_addr(&mut reader).await?;
let mut crlf = [0u8; 2];
reader.read_exact(&mut crlf).await?;
ensure!(crlf == *b"\r\n", "Trojan request terminator");
let socket = egress(bind).await?;
let mapping = socket.local_addr()?;
let mut tasks = JoinSet::<anyhow::Result<()>>::new();
let (reply_tx, mut reply_rx) = unbounded_channel();
spawn_egress_reader(&mut tasks, Arc::clone(&socket), (), reply_tx);
tasks.spawn(async move {
while let Some(((), source, payload)) = reply_rx.recv().await {
let mut frame = Vec::new();
put_addr(&mut frame, source);
frame.extend_from_slice(&(payload.len() as u16).to_be_bytes());
frame.extend_from_slice(b"\r\n");
frame.extend_from_slice(&payload);
writer.write_all(&frame).await?;
}
Ok(())
});
loop {
let mut probe = [0u8; 1];
if reader.read(&mut probe).await? == 0 {
return Ok(());
}
// Put the peeked ATYP back in front of the address decoder.
let mut chained = (&probe[..]).chain(&mut reader);
let target = read_addr(&mut chained).await?;
let mut head = [0u8; 4];
reader.read_exact(&mut head).await?;
ensure!(head[2..] == *b"\r\n", "Trojan frame terminator");
let mut payload = vec![0u8; usize::from(u16::from_be_bytes([head[0], head[1]]))];
reader.read_exact(&mut payload).await?;
socket.send_to(&payload, target).await?;
events.send(SharedUdpPacket {
association: serial,
target,
mapping,
payload,
})?;
}
}