refactor(chain): work out what each actor does before running any of it

A chain has to answer three questions about every actor -- which of its two
handlers runs, what address it is told to reach, and which actor the caller
should dial before any of it starts -- and it answered them in the middle of
doing the I/O. `next_connect_addr` served two of those questions at once with
subtly different rules on the stream and datagram sides, recomputed per actor
per connection; the datagram fold then made the same decisions again in five
branches with a lookahead. Nothing said that actor zero is the one nearest the
wire, or why only the last one is shown the client's stream.

The rules now live in `outbound/plan.rs` as a function from actors to stages:
one backward pass for what each suffix names, one forward fold for which
handler each actor runs. It touches no sockets, so the seven tests under it
are the first statement anywhere of what a chain is supposed to do -- that a
transport leaves the address to what is inside it, that every actor but the
last is told to reach the next hop, that a datagram stays a stream until the
actor that tunnels it. The handlers are left with the I/O and with naming the
actor in any error, which they never did.

Inbound had the same fold written four times -- two handlers and two functions
for the actors behind a multiplexed transport -- agreeing on the interesting
parts and differing in the rest: one panicked with `unimplemented!()` where
another returned, one timed out each actor and the others did not. One fold
now, and the case that used to panic ends the chain instead.

Behaviour is unchanged with two exceptions, both where the old code was
indefensible: a datagram handed to an actor that speaks only streams was
silently dropped and reported as that actor being handed nothing, and is now
an error naming it; and the datagram lookahead asked about the wrong suffix
for every actor after the first, which no configuration here reaches but which
was wrong on its own terms.

Verified against 178 end-to-end cases that put traffic through chains -- every
stack, every relay shape, quic and amux and ws among them -- plus leaf's own
suite.
This commit is contained in:
eric committed 2026-09-09 22:58:32 +08:00
1 parent 63dceed479
commit b83e44ec9f
8 files changed
+716 -335

No files matched your search

+22 -25
View File
@@ -4,6 +4,7 @@ use async_trait::async_trait;
use crate::proxy::*;
use super::fold::{fold, Folded};
use super::Incoming;
pub struct Handler {
@@ -12,33 +13,29 @@ pub struct Handler {
#[async_trait]
impl InboundDatagramHandler for Handler {
async fn handle<'a>(
&'a self,
mut socket: AnyInboundDatagram,
) -> io::Result<AnyInboundTransport> {
async fn handle<'a>(&'a self, socket: AnyInboundDatagram) -> io::Result<AnyInboundTransport> {
tracing::trace!("handling inbound datagram");
let mut sess: Option<Session> = None;
for (i, a) in self.actors.iter().enumerate() {
let transport = a.datagram()?.handle(socket).await?;
match transport {
InboundTransport::Stream(..) => {
unimplemented!();
}
InboundTransport::Datagram(new_socket, new_sess) => {
socket = new_socket;
sess = new_sess;
}
InboundTransport::Incoming(incoming) => {
return Ok(InboundTransport::Incoming(Box::new(Incoming::new(
incoming,
self.actors[i + 1..].to_vec(), // FIXME oob check
))));
}
_ => {
return Err(io::Error::other("invalid transport"));
}
match fold(
AnyBaseInboundTransport::Datagram(socket, None),
&self.actors,
None,
)
.await?
{
Folded::Done(AnyBaseInboundTransport::Datagram(socket, sess)) => {
Ok(InboundTransport::Datagram(socket, sess))
}
// A datagram actor that hands back a stream: the chain ends there,
// with the stream, rather than panicking as it used to.
Folded::Done(AnyBaseInboundTransport::Stream(stream, sess)) => {
Ok(InboundTransport::Stream(stream, sess))
}
Folded::Done(AnyBaseInboundTransport::Empty) => {
Err(io::Error::other("the chain produced nothing"))
}
Folded::Incoming(incoming, next) => Ok(InboundTransport::Incoming(Box::new(
Incoming::new(incoming, self.actors[next..].to_vec()),
))),
}
Ok(InboundTransport::Datagram(socket, sess))
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Running a chain's actors over an inbound transport.
//!
//! Four places used to do this: the stream handler, the datagram handler, and
//! one function per shape for the actors that run behind a multiplexed
//! transport. They agreed on the interesting parts and differed in the rest --
//! one panicked where another returned, one timed out each actor and the
//! others did not, and each had its own way of saying "invalid transport"
//! without saying which actor produced it.
//!
//! This is that fold, once. What a chain does is unwrap: each actor takes what
//! the one before it produced and hands back something more specific, until
//! either the actors run out or one of them produces a transport that carries
//! others -- amux, quic -- in which case the actors that have not run belong
//! to each of *those*, not to the thing yielding them.
use std::io;
use std::time::Duration;
use tokio::time::timeout;
use tracing::warn;
use crate::proxy::*;
/// Where a fold stopped.
pub(super) enum Folded {
/// Every actor ran.
Done(AnyBaseInboundTransport),
/// An actor produced a multiplexed transport. The actors from `next`
/// onwards have not run: they belong to what it yields.
Incoming(AnyIncomingTransport, usize),
}
/// Runs `actors` over `transport`, in order.
///
/// `handshake_timeout` bounds each actor when there is one to bound: the
/// actors running behind a multiplexed transport are handshaking with a peer
/// that may never finish, while the ones on the accept path are already bound
/// by the listener.
pub(super) async fn fold(
transport: AnyBaseInboundTransport,
actors: &[AnyInboundHandler],
handshake_timeout: Option<Duration>,
) -> io::Result<Folded> {
let mut carried = transport;
for (index, actor) in actors.iter().enumerate() {
let named = |what: String| -> io::Error {
io::Error::other(format!("chain actor {} [{}]: {}", index, actor.tag(), what))
};
let attributed = |err: io::Error| -> io::Error {
io::Error::new(
err.kind(),
format!("chain actor {} [{}]: {}", index, actor.tag(), err),
)
};
let (was_stream, produced) = match carried {
AnyBaseInboundTransport::Stream(stream, sess) => {
let handler = actor.stream().map_err(attributed)?;
let handled = handler.handle(sess, stream);
(
true,
run(handled, handshake_timeout).await.map_err(attributed)?,
)
}
AnyBaseInboundTransport::Datagram(socket, _) => {
let handler = actor.datagram().map_err(attributed)?;
let handled = handler.handle(socket);
(
false,
run(handled, handshake_timeout).await.map_err(attributed)?,
)
}
AnyBaseInboundTransport::Empty => {
return Err(named("nothing was handed to it".to_string()))
}
};
carried = match produced {
InboundTransport::Stream(stream, sess) => AnyBaseInboundTransport::Stream(stream, sess),
InboundTransport::Datagram(socket, sess) => {
if was_stream {
// A stream that has become a datagram is the end of the
// chain: there is no way back to a stream, and a
// stream-initiated datagram cannot be handed to another
// datagram actor on this node.
let remaining = &actors[index + 1..];
if !remaining.is_empty() {
warn!(
"chain actor {} [{}] produced a datagram, so [{}] will not run",
index,
actor.tag(),
remaining
.iter()
.map(|actor| actor.tag().as_str())
.collect::<Vec<_>>()
.join(", ")
);
}
return Ok(Folded::Done(AnyBaseInboundTransport::Datagram(
socket, sess,
)));
}
AnyBaseInboundTransport::Datagram(socket, sess)
}
InboundTransport::Incoming(incoming) => {
return Ok(Folded::Incoming(incoming, index + 1))
}
InboundTransport::Empty => return Err(named("produced nothing".to_string())),
};
}
Ok(Folded::Done(carried))
}
/// Runs one actor, under a deadline when there is one.
async fn run<F>(handling: F, handshake_timeout: Option<Duration>) -> io::Result<AnyInboundTransport>
where
F: std::future::Future<Output = io::Result<AnyInboundTransport>>,
{
match handshake_timeout {
Some(within) => timeout(within, handling)
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "handshake timed out"))?,
None => handling.await,
}
}
+12 -75
View File
@@ -5,14 +5,16 @@ use futures::{
future::BoxFuture,
task::{Context, Poll},
};
use tokio::time::timeout;
use tracing::debug;
use crate::proxy::*;
mod datagram;
mod fold;
mod stream;
use fold::{fold, Folded};
pub use datagram::Handler as DatagramHandler;
pub use stream::Handler as StreamHandler;
@@ -39,85 +41,20 @@ impl Incoming {
}
}
async fn run_stream_actors(
mut stream: AnyStream,
mut sess: Session,
actors: Vec<AnyInboundHandler>,
handshake_timeout: Duration,
) -> io::Result<AnyBaseInboundTransport> {
for actor in actors {
let transport = timeout(
handshake_timeout,
actor.stream()?.handle(sess.clone(), stream),
)
.await
.map_err(|_| {
io::Error::new(io::ErrorKind::TimedOut, "incoming stream handle timed out")
})??;
match transport {
InboundTransport::Stream(new_stream, new_sess) => {
stream = new_stream;
sess = new_sess;
}
InboundTransport::Datagram(socket, sess) => {
return Ok(AnyBaseInboundTransport::Datagram(socket, sess));
}
_ => {
return Err(io::Error::other(
"invalid chain inbound incoming stream transport",
));
}
}
}
Ok(AnyBaseInboundTransport::Stream(stream, sess))
}
async fn run_datagram_actors(
mut socket: AnyInboundDatagram,
mut sess: Option<Session>,
actors: Vec<AnyInboundHandler>,
handshake_timeout: Duration,
) -> io::Result<AnyBaseInboundTransport> {
for actor in actors {
let transport = timeout(handshake_timeout, actor.datagram()?.handle(socket))
.await
.map_err(|_| {
io::Error::new(
io::ErrorKind::TimedOut,
"incoming datagram handle timed out",
)
})??;
match transport {
InboundTransport::Stream(stream, sess) => {
return Ok(AnyBaseInboundTransport::Stream(stream, sess));
}
InboundTransport::Datagram(new_socket, new_sess) => {
socket = new_socket;
sess = new_sess;
}
_ => {
return Err(io::Error::other(
"invalid chain inbound incoming datagram transport",
));
}
}
}
Ok(AnyBaseInboundTransport::Datagram(socket, sess))
}
/// Runs the actors that had not run when a multiplexed transport appeared,
/// once for every transport it yields.
async fn run_actors(
transport: AnyBaseInboundTransport,
actors: Vec<AnyInboundHandler>,
handshake_timeout: Duration,
) -> io::Result<AnyBaseInboundTransport> {
match transport {
AnyBaseInboundTransport::Stream(stream, sess) => {
run_stream_actors(stream, sess, actors, handshake_timeout).await
}
AnyBaseInboundTransport::Datagram(socket, sess) => {
run_datagram_actors(socket, sess, actors, handshake_timeout).await
}
AnyBaseInboundTransport::Empty => Err(io::Error::other("empty chain inbound transport")),
match fold(transport, &actors, Some(handshake_timeout)).await? {
Folded::Done(transport) => Ok(transport),
// Neither shape of chain unwraps one of these inside another, and a
// silent failure here would look like a connection that never arrived.
Folded::Incoming(..) => Err(io::Error::other(
"a multiplexed transport inside another one is not supported",
)),
}
}
+24 -30
View File
@@ -4,6 +4,7 @@ use async_trait::async_trait;
use crate::{proxy::*, session::Session};
use super::fold::{fold, Folded};
use super::Incoming;
pub struct Handler {
@@ -14,38 +15,31 @@ pub struct Handler {
impl InboundStreamHandler for Handler {
async fn handle<'a>(
&'a self,
mut sess: Session,
mut stream: AnyStream,
) -> std::io::Result<AnyInboundTransport> {
sess: Session,
stream: AnyStream,
) -> io::Result<AnyInboundTransport> {
tracing::trace!("handling inbound stream");
for (i, a) in self.actors.iter().enumerate() {
let transport = a.stream()?.handle(sess.clone(), stream).await?;
match transport {
InboundTransport::Stream(new_stream, new_sess) => {
stream = new_stream;
sess = new_sess;
}
InboundTransport::Datagram(socket, sess) => {
// If the input stream has been converted to a datagram,
// we assume it's the last actor. Because we can not convert
// a datagram back to stream, and can't chain multiple
// inbound datagrams for a stream-initiated transport
// on a single node.
//
// TODO Warns if there are further actors in the chain.
return Ok(InboundTransport::Datagram(socket, sess));
}
InboundTransport::Incoming(incoming) => {
return Ok(InboundTransport::Incoming(Box::new(Incoming::new(
incoming,
self.actors[i + 1..].to_vec(), // FIXME oob check
))));
}
_ => {
return Err(io::Error::other("invalid transport"));
}
match fold(
AnyBaseInboundTransport::Stream(stream, sess),
&self.actors,
None,
)
.await?
{
Folded::Done(AnyBaseInboundTransport::Stream(stream, sess)) => {
Ok(InboundTransport::Stream(stream, sess))
}
Folded::Done(AnyBaseInboundTransport::Datagram(socket, sess)) => {
Ok(InboundTransport::Datagram(socket, sess))
}
Folded::Done(AnyBaseInboundTransport::Empty) => {
Err(io::Error::other("the chain produced nothing"))
}
// The actors that have not run belong to each transport this one
// yields, not to the thing yielding them.
Folded::Incoming(incoming, next) => Ok(InboundTransport::Incoming(Box::new(
Incoming::new(incoming, self.actors[next..].to_vec()),
))),
}
Ok(InboundTransport::Stream(stream, sess))
}
}
+95 -149
View File
@@ -1,157 +1,64 @@
use std::convert::TryFrom;
use std::io;
use async_trait::async_trait;
use tracing::{trace, Instrument};
use tracing::Instrument;
use crate::{proxy::*, session::*};
use crate::{proxy::*, session::Session};
use super::plan::{Input, Kind, Plan};
pub struct Handler {
pub actors: Vec<AnyOutboundHandler>,
}
impl Handler {
fn next_connect_addr(&self, start: usize) -> OutboundConnect {
for a in self.actors[start..].iter() {
match a.datagram() {
Ok(h) => {
if self.unreliable_chain(start + 1) {
let oc = h.connect_addr();
if let OutboundConnect::Next = oc {
continue;
}
return oc;
} else if let Ok(h) = a.stream() {
let oc = h.connect_addr();
if let OutboundConnect::Next = oc {
continue;
}
return oc;
}
}
_ => {
if let Ok(h) = a.stream() {
let oc = h.connect_addr();
if let OutboundConnect::Next = oc {
continue;
}
return oc;
}
}
}
/// What the chain is carrying between two actors.
///
/// A chain that ends in datagrams may still start as a stream: a datagram
/// tunnelled over a reliable protocol is a stream until the actor that
/// tunnels it, and there is no way back.
enum Carried {
Nothing,
Stream(AnyStream),
Datagram(AnyOutboundDatagram),
}
impl Carried {
fn from(transport: Option<AnyOutboundTransport>) -> Self {
match transport {
Some(OutboundTransport::Stream(stream)) => Carried::Stream(stream),
Some(OutboundTransport::Datagram(datagram)) => Carried::Datagram(datagram),
None => Carried::Nothing,
}
OutboundConnect::Unknown
}
fn next_session(&self, mut sess: Session, start: usize) -> Session {
if let OutboundConnect::Proxy(_, address, port) = self.next_connect_addr(start) {
if let Ok(addr) = SocksAddr::try_from((address, port)) {
sess.destination = addr;
sess.dns_sniffed_domain = None;
sess.http_sniffed_domain = None;
sess.tls_sniffed_domain = None;
}
fn input(&self) -> Input {
match self {
Carried::Nothing => Input::Nothing,
Carried::Stream(_) => Input::Stream,
Carried::Datagram(_) => Input::Datagram,
}
sess
}
fn unreliable_chain(&self, start: usize) -> bool {
for a in self.actors[start..].iter() {
if let Ok(uh) = a.datagram() {
if uh.transport_type() != DatagramTransportType::Unreliable {
return false;
}
} else {
return false;
}
}
true
}
async fn handle<'a>(
&'a self,
sess: &'a Session,
mut stream: Option<Box<dyn ProxyStream>>,
mut dgram: Option<Box<dyn OutboundDatagram>>,
) -> io::Result<Box<dyn OutboundDatagram>> {
for (i, a) in self.actors.iter().enumerate() {
let new_sess = self.next_session(sess.clone(), i + 1);
trace!("handle actor idx={} tag={}", i, a.tag());
if let Ok(uh) = a.datagram() {
trace!("has datagram");
if let Some(d) = dgram.take() {
dgram.replace(
uh.handle(&new_sess, Some(OutboundTransport::Datagram(d)))
.instrument(tracing::Span::current())
.await?,
);
} else if let Some(s) = stream.take() {
trace!("has input stream");
// Check whether all subsequent handlers can use unreliable
// transport, otherwise we must not convert the stream to
// a datagram.
if self.unreliable_chain(i + 1) {
trace!("unreliable chain");
dgram.replace(
uh.handle(&new_sess, Some(OutboundTransport::Stream(s)))
.instrument(tracing::Span::current())
.await?,
);
} else {
trace!("reliable chain");
stream.replace(
a.stream()?
.handle(&new_sess, None, Some(s))
.instrument(tracing::Span::current())
.await?,
);
}
} else if self.unreliable_chain(i + 1) {
trace!("unreliable chain fallback");
dgram.replace(
uh.handle(&new_sess, None)
.instrument(tracing::Span::current())
.await?,
);
} else {
trace!("reliable chain");
stream.replace(
a.stream()?
.handle(&new_sess, None, None)
.instrument(tracing::Span::current())
.await?,
);
}
} else {
trace!("no datagram, use stream");
let s = stream.take();
stream.replace(
a.stream()?
.handle(&new_sess, None, s)
.instrument(tracing::Span::current())
.await?,
);
}
}
dgram.ok_or_else(|| io::Error::other("no datagram"))
}
}
#[async_trait]
impl OutboundDatagramHandler for Handler {
fn connect_addr(&self) -> OutboundConnect {
self.next_connect_addr(0)
// What is dialled does not depend on what the chain is handed: the
// first actor that names an endpoint names it either way.
Plan::for_datagram(&self.actors, Input::Nothing).dial
}
/// What the *first* actor accepts, which is what an enclosing chain is
/// asking about when it decides whether it may convert a stream into a
/// datagram before reaching this one. Not what this chain produces.
fn transport_type(&self) -> DatagramTransportType {
self.actors
.first()
.map(|x| {
x.datagram()
.map(|x| x.transport_type())
.unwrap_or(DatagramTransportType::Unknown)
.and_then(|actor| {
actor
.datagram()
.ok()
.map(|handler| handler.transport_type())
})
.unwrap_or(DatagramTransportType::Unknown)
}
@@ -162,27 +69,66 @@ impl OutboundDatagramHandler for Handler {
transport: Option<AnyOutboundTransport>,
) -> io::Result<AnyOutboundDatagram> {
tracing::trace!("handling outbound datagram");
match transport {
Some(transport) => match transport {
OutboundTransport::Datagram(dgram) => {
trace!("datagram transport");
self.handle(sess, None, Some(dgram))
.instrument(tracing::Span::current())
.await
let mut carried = Carried::from(transport);
let plan = Plan::for_datagram(&self.actors, carried.input());
for stage in &plan.stages {
let actor = &self.actors[stage.index];
let sess = stage.session(sess);
carried = match stage.kind {
Kind::Datagram => {
let transport = match carried {
Carried::Nothing => None,
Carried::Stream(stream) => Some(OutboundTransport::Stream(stream)),
Carried::Datagram(datagram) => Some(OutboundTransport::Datagram(datagram)),
};
Carried::Datagram(
actor
.datagram()
.map_err(|err| stage.error(err))?
.handle(&sess, transport)
.instrument(tracing::Span::current())
.await
.map_err(|err| stage.error(err))?,
)
}
OutboundTransport::Stream(stream) => {
trace!("stream transport");
self.handle(sess, Some(stream), None)
.instrument(tracing::Span::current())
.await
Kind::Stream => {
let stream = match carried {
Carried::Nothing => None,
Carried::Stream(stream) => Some(stream),
// The actor before produced a datagram and this one
// speaks only streams. Nothing can be done with it,
// and silently dropping it is how this used to end as
// "invalid input" from an actor that was handed
// nothing.
Carried::Datagram(_) => {
return Err(stage
.failed("cannot carry the datagram the actor before it produced"))
}
};
Carried::Stream(
actor
.stream()
.map_err(|err| stage.error(err))?
.handle(&sess, None, stream)
.instrument(tracing::Span::current())
.await
.map_err(|err| stage.error(err))?,
)
}
},
None => {
trace!("stream=None, datagram=None");
self.handle(sess, None, None)
.instrument(tracing::Span::current())
.await
}
};
}
match carried {
Carried::Datagram(datagram) => Ok(datagram),
_ => Err(io::Error::other(format!(
"chain [{}] carries no datagrams: no actor in it turns a stream into one",
plan.stages
.iter()
.map(|stage| stage.tag.as_str())
.collect::<Vec<_>>()
.join(", ")
))),
}
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod datagram;
mod plan;
pub mod stream;
pub use datagram::Handler as DatagramHandler;
+405
View File
@@ -0,0 +1,405 @@
//! What each actor in a chain is asked to do, worked out before anything is
//! dialled.
//!
//! A chain has to answer three questions about every actor: which of its two
//! handlers runs, what address it is told to reach, and which one of them the
//! caller should dial before any of it starts. The answers depend on each
//! other -- whether a stream becomes a datagram at actor `i` depends on what
//! every actor after it can carry, and what actor `i` is told to reach depends
//! on which actor after it names an endpoint -- so they are worked out here,
//! in one pass, and the handlers are left doing nothing but I/O.
//!
//! Nothing here touches the network, which is the point: the rules a chain
//! follows are a function of its actors and can be tested as one.
use std::convert::TryFrom;
use std::io;
use crate::proxy::*;
use crate::session::{Session, SocksAddr};
/// Which of an actor's two handlers a stage runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Kind {
Stream,
Datagram,
}
/// What the chain was handed to start from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Input {
Nothing,
Stream,
Datagram,
}
/// One actor's part in the chain.
pub(super) struct Stage {
pub index: usize,
pub tag: String,
pub kind: Kind,
/// The address to put in this actor's session: the endpoint of the next
/// actor that names one.
///
/// `None` leaves the session's own destination in place, which is what the
/// last actor needs -- it is the one talking to where the client wanted to
/// go. This is how a chain relays: every actor but the last is told to
/// reach the next hop, and says so in its own protocol.
pub next_hop: Option<SocksAddr>,
}
impl Stage {
/// The session this actor sees.
pub fn session(&self, sess: &Session) -> Session {
let mut sess = sess.clone();
if let Some(next_hop) = self.next_hop.as_ref() {
sess.destination = next_hop.clone();
// The sniffed domains describe the destination that has just been
// replaced, so they no longer describe anything.
sess.dns_sniffed_domain = None;
sess.http_sniffed_domain = None;
sess.tls_sniffed_domain = None;
}
sess
}
/// Names the stage in an error, so a failure says which actor produced it
/// rather than only which chain contained it.
pub fn error(&self, err: io::Error) -> io::Error {
io::Error::new(
err.kind(),
format!("chain actor {} [{}]: {}", self.index, self.tag, err),
)
}
pub fn failed(&self, what: &str) -> io::Error {
io::Error::other(format!(
"chain actor {} [{}]: {}",
self.index, self.tag, what
))
}
}
pub(super) struct Plan {
pub stages: Vec<Stage>,
/// What the caller should dial before the first stage runs.
pub dial: OutboundConnect,
}
impl Plan {
/// A chain carrying a stream: every actor wraps the one before it.
pub fn for_stream(actors: &[AnyOutboundHandler]) -> Plan {
Plan::build(actors, vec![Kind::Stream; actors.len()])
}
/// A chain carrying datagrams, which may still run some of its actors as
/// streams: a datagram tunnelled over a reliable transport is a stream
/// until the actor that tunnels it.
pub fn for_datagram(actors: &[AnyOutboundHandler], input: Input) -> Plan {
Plan::build(actors, datagram_kinds(actors, input))
}
fn build(actors: &[AnyOutboundHandler], kinds: Vec<Kind>) -> Plan {
let resolved = resolve(actors, &kinds);
let stages = actors
.iter()
.enumerate()
.map(|(index, actor)| Stage {
index,
tag: actor.tag().to_string(),
kind: kinds[index],
next_hop: proxy_address(&resolved[index + 1]),
})
.collect();
Plan {
stages,
dial: resolved[0].clone(),
}
}
pub fn last(&self) -> usize {
self.stages.len().saturating_sub(1)
}
}
/// Which handler each actor runs when the chain is carrying datagrams.
///
/// Folded forwards, because it depends on what the actor before produced: an
/// actor holding a datagram keeps it, and an actor holding a stream converts
/// only where everything after it can carry an unreliable datagram. Converting
/// too early would strand the actors that need a stream, and there is no way
/// back.
fn datagram_kinds(actors: &[AnyOutboundHandler], input: Input) -> Vec<Kind> {
let unreliable = unreliable_from(actors);
let mut held = match input {
Input::Nothing => None,
Input::Stream => Some(Kind::Stream),
Input::Datagram => Some(Kind::Datagram),
};
let mut kinds = Vec::with_capacity(actors.len());
for (index, actor) in actors.iter().enumerate() {
let kind = if actor.datagram().is_err() {
// Nothing to run a datagram with. If one is being held this chain
// cannot carry it, which the executor reports against this actor.
Kind::Stream
} else if held == Some(Kind::Datagram) || unreliable[index + 1] {
Kind::Datagram
} else {
Kind::Stream
};
held = Some(kind);
kinds.push(kind);
}
kinds
}
/// Whether every actor from `i` onwards can carry an unreliable datagram.
///
/// Vacuously true past the end, which is what lets the last actor be the one
/// that turns a stream into a datagram.
fn unreliable_from(actors: &[AnyOutboundHandler]) -> Vec<bool> {
let mut unreliable = vec![true; actors.len() + 1];
for index in (0..actors.len()).rev() {
let carries = actors[index]
.datagram()
.map(|handler| handler.transport_type() == DatagramTransportType::Unreliable)
.unwrap_or(false);
unreliable[index] = carries && unreliable[index + 1];
}
unreliable
}
/// The endpoint each suffix of the chain names, resolved from the back.
///
/// `resolved[i]` is what the actors from `i` onwards want dialled: the first
/// one of them that names something. `Next` is an actor saying "whatever the
/// one after me says", which is how a transport that wraps rather than dials
/// -- tls, ws -- leaves the address to the protocol inside it.
fn resolve(actors: &[AnyOutboundHandler], kinds: &[Kind]) -> Vec<OutboundConnect> {
let mut resolved = vec![OutboundConnect::Unknown; actors.len() + 1];
for index in (0..actors.len()).rev() {
resolved[index] = match connect_addr(&actors[index], kinds[index]) {
OutboundConnect::Next => resolved[index + 1].clone(),
named => named,
};
}
resolved
}
/// What one actor names, asked of the handler its stage runs and falling back
/// to the other one: an actor may name its endpoint on only one of its sides.
fn connect_addr(actor: &AnyOutboundHandler, kind: Kind) -> OutboundConnect {
let (mine, other) = match kind {
Kind::Stream => (
actor.stream().ok().map(|h| h.connect_addr()),
actor.datagram().ok().map(|h| h.connect_addr()),
),
Kind::Datagram => (
actor.datagram().ok().map(|h| h.connect_addr()),
actor.stream().ok().map(|h| h.connect_addr()),
),
};
mine.or(other).unwrap_or(OutboundConnect::Unknown)
}
/// Only a proxy endpoint replaces an actor's destination. `Direct` means the
/// actor goes to the session's own destination, which is already there.
fn proxy_address(connect: &OutboundConnect) -> Option<SocksAddr> {
match connect {
OutboundConnect::Proxy(_, address, port) => {
SocksAddr::try_from((address.clone(), *port)).ok()
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use async_trait::async_trait;
use crate::proxy::outbound::HandlerBuilder;
use super::*;
/// An actor that names an endpoint, or does not, and carries streams,
/// datagrams or both. Enough to ask a plan every question it answers.
struct Stream(OutboundConnect);
#[async_trait]
impl OutboundStreamHandler for Stream {
fn connect_addr(&self) -> OutboundConnect {
self.0.clone()
}
async fn handle<'a>(
&'a self,
_sess: &'a Session,
_lhs: Option<&mut AnyStream>,
_stream: Option<AnyStream>,
) -> io::Result<AnyStream> {
unreachable!("a plan runs no I/O")
}
}
struct Datagram(OutboundConnect, DatagramTransportType);
#[async_trait]
impl OutboundDatagramHandler for Datagram {
fn connect_addr(&self) -> OutboundConnect {
self.0.clone()
}
fn transport_type(&self) -> DatagramTransportType {
self.1
}
async fn handle<'a>(
&'a self,
_sess: &'a Session,
_transport: Option<AnyOutboundTransport>,
) -> io::Result<AnyOutboundDatagram> {
unreachable!("a plan runs no I/O")
}
}
fn proxy(port: u16) -> OutboundConnect {
OutboundConnect::Proxy(Network::Tcp, "127.0.0.1".to_string(), port)
}
/// A transport: wraps whatever is inside it and names no endpoint of its
/// own, like tls or ws.
fn wrapper(tag: &str) -> AnyOutboundHandler {
HandlerBuilder::default()
.tag(tag.to_string())
.stream_handler(Arc::new(Stream(OutboundConnect::Next)))
.build()
}
/// A protocol that dials, and tunnels datagrams over the stream it has,
/// like trojan.
fn protocol(tag: &str, port: u16) -> AnyOutboundHandler {
HandlerBuilder::default()
.tag(tag.to_string())
.stream_handler(Arc::new(Stream(proxy(port))))
.datagram_handler(Arc::new(Datagram(
proxy(port),
DatagramTransportType::Reliable,
)))
.build()
}
/// A protocol whose datagrams are datagrams, like shadowsocks over UDP.
fn unreliable(tag: &str, port: u16) -> AnyOutboundHandler {
HandlerBuilder::default()
.tag(tag.to_string())
.stream_handler(Arc::new(Stream(proxy(port))))
.datagram_handler(Arc::new(Datagram(
proxy(port),
DatagramTransportType::Unreliable,
)))
.build()
}
fn hops(plan: &Plan) -> Vec<Option<String>> {
plan.stages
.iter()
.map(|stage| stage.next_hop.as_ref().map(|hop| hop.to_string()))
.collect()
}
#[test]
fn the_endpoint_dialled_is_the_first_one_named() {
let actors = vec![wrapper("tls"), wrapper("ws"), protocol("trojan", 3001)];
let plan = Plan::for_stream(&actors);
assert!(
matches!(plan.dial, OutboundConnect::Proxy(_, _, 3001)),
"the transports name nothing, so the protocol inside them decides"
);
}
/// Every actor but the last is told to reach the next hop; the last is
/// left with the session's own destination. This is the whole of relaying.
#[test]
fn each_actor_is_told_to_reach_the_next_one_that_names_an_endpoint() {
let actors = vec![
protocol("hop1", 3001),
protocol("hop2", 3002),
protocol("hop3", 3003),
];
let plan = Plan::for_stream(&actors);
assert_eq!(
hops(&plan),
vec![
Some("127.0.0.1:3002".to_string()),
Some("127.0.0.1:3003".to_string()),
None,
]
);
}
#[test]
fn a_transport_leaves_the_destination_to_what_is_inside_it() {
let actors = vec![
wrapper("ws"),
protocol("trojan", 3001),
protocol("ss", 3002),
];
let plan = Plan::for_stream(&actors);
assert_eq!(
hops(&plan),
vec![
// ws is followed by trojan, which names 3001... but the chain
// is dialled at 3001 already, so what ws is told is where the
// *next* actor goes: trojan's own endpoint.
Some("127.0.0.1:3001".to_string()),
Some("127.0.0.1:3002".to_string()),
None,
]
);
}
/// A datagram tunnelled over a reliable protocol stays a stream until the
/// actor that tunnels it.
#[test]
fn a_reliable_protocol_carries_datagrams_over_its_stream() {
let actors = vec![wrapper("ws"), protocol("trojan", 3001)];
let plan = Plan::for_datagram(&actors, Input::Nothing);
let kinds: Vec<Kind> = plan.stages.iter().map(|stage| stage.kind).collect();
assert_eq!(kinds, vec![Kind::Stream, Kind::Datagram]);
}
/// And an unreliable one takes the datagram as it is, from the first actor
/// that can.
#[test]
fn an_unreliable_chain_stays_a_datagram_throughout() {
let actors = vec![unreliable("ss1", 3001), unreliable("ss2", 3002)];
let plan = Plan::for_datagram(&actors, Input::Nothing);
let kinds: Vec<Kind> = plan.stages.iter().map(|stage| stage.kind).collect();
assert_eq!(kinds, vec![Kind::Datagram, Kind::Datagram]);
}
/// A transport that speaks only streams in front of a datagram protocol:
/// the plan runs it as a stream, and nothing after it can turn that back
/// into what shadowsocks needs. The executor is what reports it, but the
/// shape is decided here.
#[test]
fn a_stream_only_transport_cannot_lead_to_an_unreliable_protocol() {
let actors = vec![wrapper("ws"), unreliable("ss", 3001)];
let plan = Plan::for_datagram(&actors, Input::Nothing);
let kinds: Vec<Kind> = plan.stages.iter().map(|stage| stage.kind).collect();
assert_eq!(
kinds,
vec![Kind::Stream, Kind::Datagram],
"ss converts the stream it is given, which is not a UDP association"
);
}
#[test]
fn an_empty_chain_names_nothing() {
let plan = Plan::for_stream(&[]);
assert!(matches!(plan.dial, OutboundConnect::Unknown));
assert!(plan.stages.is_empty());
}
}
+30 -56
View File
@@ -1,84 +1,58 @@
use std::convert::TryFrom;
use std::io;
use async_trait::async_trait;
use tracing::Instrument;
use crate::{
proxy::*,
session::{Session, SocksAddr},
};
use crate::{proxy::*, session::Session};
use super::plan::Plan;
pub struct Handler {
pub actors: Vec<AnyOutboundHandler>,
}
impl Handler {
fn next_connect_addr(&self, start: usize) -> OutboundConnect {
for a in self.actors[start..].iter() {
match a.stream() {
Ok(h) => {
let oc = h.connect_addr();
if let OutboundConnect::Next = oc {
continue;
}
return oc;
}
_ => {
if let Ok(h) = a.datagram() {
let oc = h.connect_addr();
if let OutboundConnect::Next = oc {
continue;
}
return oc;
}
}
}
}
OutboundConnect::Unknown
}
fn next_session(&self, mut sess: Session, start: usize) -> Session {
if let OutboundConnect::Proxy(_, address, port) = self.next_connect_addr(start) {
if let Ok(addr) = SocksAddr::try_from((address, port)) {
sess.destination = addr;
sess.dns_sniffed_domain = None;
sess.http_sniffed_domain = None;
sess.tls_sniffed_domain = None;
}
}
sess
}
}
#[async_trait]
impl OutboundStreamHandler for Handler {
fn connect_addr(&self) -> OutboundConnect {
self.next_connect_addr(0)
Plan::for_stream(&self.actors).dial
}
/// Runs each actor over what the one before it produced.
///
/// The plan has already decided what each actor is told to reach; all that
/// is left here is the I/O, in order, with each actor's failure named
/// after it.
async fn handle<'a>(
&'a self,
sess: &'a Session,
mut lhs: Option<&mut AnyStream>,
mut stream: Option<AnyStream>,
stream: Option<AnyStream>,
) -> io::Result<AnyStream> {
tracing::trace!("handling outbound stream");
for (i, a) in self.actors.iter().enumerate() {
let new_sess = self.next_session(sess.clone(), i + 1);
let s = stream.take();
let lhs_stream = if i == self.actors.len() - 1 {
let plan = Plan::for_stream(&self.actors);
let last = plan.last();
let mut stream = stream;
for stage in &plan.stages {
// Only the actor that talks to the destination is shown the
// client's side of the connection: it is the one that can read the
// first payload and put it in its own handshake.
let lhs = if stage.index == last {
lhs.take()
} else {
None
};
stream.replace(
a.stream()?
.handle(&new_sess, lhs_stream, s)
.instrument(sess.span())
.await?,
);
let actor = &self.actors[stage.index];
let handled = actor
.stream()
.map_err(|err| stage.error(err))?
.handle(&stage.session(sess), lhs, stream.take())
.instrument(sess.span())
.await
.map_err(|err| stage.error(err))?;
stream.replace(handled);
}
Ok(stream.ok_or_else(|| io::Error::other("chain tcp invalid input"))?)
stream.ok_or_else(|| io::Error::other("a chain with no actors carries nothing"))
}
}