diff --git a/README.md b/README.md index d38f2b4..dabcd38 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ A versatile and efficient proxy framework. | Trojan | ✅ | ✅ | | VMess | ❌ | ✅ | | Vless | ❌ | ✅ | +| MPTP | ✅ | ✅ | ### Transports & Security @@ -29,7 +30,7 @@ A versatile and efficient proxy framework. | WebSocket | ✅ | ✅ | | | TLS | ✅ | ✅ | | | QUIC | ✅ | ✅ | | -| AMux | ✅ | ✅ | Leaf specific | +| AMux | ✅ | ✅ | Leaf specific multiplexing | | Obfs | ❌ | ✅ | Simple obfuscation | | Reality | ❌ | ✅ | Xray Reality | @@ -39,6 +40,7 @@ A versatile and efficient proxy framework. |---|---|---|---| | Chain | ✅ | ✅ | Proxy chaining | | Failover | ❌ | ✅ | Failover with health check | +| MPTP | ✅ | ✅ | Multi-path Transport Protocol (Aggregation) | ### Transparent Proxying diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index 944893a..9efbc2f 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -61,6 +61,7 @@ all-endpoints = [ "inbound-ws", "inbound-tls", "inbound-trojan", + "inbound-mptp", "inbound-http", "inbound-hc", "inbound-shadowsocks", @@ -86,6 +87,7 @@ all-endpoints = [ "outbound-chain", "outbound-vless", "outbound-reality", + "outbound-mptp", # "outbound-select", ] @@ -123,11 +125,13 @@ outbound-vless = ["uuid", "hex"] outbound-reality = ["reality", "reality-rustls", "webpki-roots", "rustls-pemfile", "hex", "base64"] outbound-amux= ["tokio-util"] outbound-quic = ["rustls", "webpki-roots-old", "rustls-pemfile-old"] +outbound-mptp = [] outbound-select = ["directories", "axum/query"] outbound-vmess = ["lz_fnv", "cfb-mode", "hmac", "sha2", "aes", "aes-gcm", "sha3", "digest", "uuid", "md-5", "tokio-util", "byteorder", "crc32fast"] # Inbounds inbound-trojan = ["sha2", "hex"] +inbound-mptp = [] inbound-shadowsocks = ["hkdf", "sha-1", "md-5", "tokio-util"] inbound-socks = [] inbound-http = ["http"] @@ -170,7 +174,6 @@ tracing = "0.1" tracing-appender = "0.2" tracing-subscriber = "0.3" chrono = "0.4" -colored = "2.2" # Router maxminddb = { version = "0.24", features = ["mmap"] } @@ -242,7 +245,7 @@ aes = { version = "0.8", optional = true } aes-gcm = { version = "0.10", optional = true } sha3 = { version = "0.10", optional = true } digest = { version = "0.10", optional = true } -uuid = { version = "1", optional = true } +uuid = { version = "1", features = ["v4"], optional = true } byteorder = { version = "1", optional = true } crc32fast = { version = "1", optional = true } diff --git a/leaf/src/app/dispatcher.rs b/leaf/src/app/dispatcher.rs index 8c09332..bea3da2 100644 --- a/leaf/src/app/dispatcher.rs +++ b/leaf/src/app/dispatcher.rs @@ -86,26 +86,9 @@ impl OutboundDatagram for HealthcheckUdpDatagram { } #[inline] -fn log_request( - sess: &Session, - outbound_tag: &str, - outbound_tag_color: &colored::Color, - handshake_time: Option, -) { +fn log_request(sess: &Session, outbound_tag: &str, handshake_time: Option) { let hs = handshake_time.map_or("failed".to_string(), |hs| format!("{}ms", hs)); - let (network, outbound_tag) = if !*crate::option::LOG_NO_COLOR { - use colored::Colorize; - let network_color = match sess.network { - Network::Tcp => colored::Color::Blue, - Network::Udp => colored::Color::Yellow, - }; - ( - sess.network.to_string().color(network_color).to_string(), - outbound_tag.color(*outbound_tag_color).to_string(), - ) - } else { - (sess.network.to_string(), outbound_tag.to_string()) - }; + let network = sess.network.to_string(); #[cfg(feature = "rule-process-name")] { @@ -281,7 +264,7 @@ impl Dispatcher { &h.tag(), e ); - log_request(&sess, h.tag(), h.color(), None); + log_request(&sess, h.tag(), None); return; } }; @@ -319,7 +302,7 @@ impl Dispatcher { Ok(mut rhs) => { let elapsed = tokio::time::Instant::now().duration_since(handshake_start); - log_request(&sess, h.tag(), h.color(), Some(elapsed.as_millis())); + log_request(&sess, h.tag(), Some(elapsed.as_millis())); if !stats_wrapped { rhs = self @@ -365,7 +348,7 @@ impl Dispatcher { &h.tag(), e ); - log_request(&sess, h.tag(), h.color(), None); + log_request(&sess, h.tag(), None); } } } @@ -454,7 +437,7 @@ impl Dispatcher { Ok(mut d) => { let elapsed = tokio::time::Instant::now().duration_since(handshake_start); - log_request(&sess, h.tag(), h.color(), Some(elapsed.as_millis())); + log_request(&sess, h.tag(), Some(elapsed.as_millis())); d = self .stat_manager @@ -476,7 +459,7 @@ impl Dispatcher { &h.tag(), e ); - log_request(&sess, h.tag(), h.color(), None); + log_request(&sess, h.tag(), None); Err(e) } } diff --git a/leaf/src/app/inbound/manager.rs b/leaf/src/app/inbound/manager.rs index 7de8358..044dc58 100644 --- a/leaf/src/app/inbound/manager.rs +++ b/leaf/src/app/inbound/manager.rs @@ -17,6 +17,8 @@ use crate::proxy::amux; use crate::proxy::hc; #[cfg(feature = "inbound-http")] use crate::proxy::http; +#[cfg(feature = "inbound-mptp")] +use crate::proxy::mptp; #[cfg(all(feature = "inbound-nf", windows))] use crate::proxy::nf; #[cfg(feature = "inbound-quic")] @@ -103,6 +105,16 @@ impl InboundManager { )); handlers.insert(tag.clone(), handler); } + #[cfg(feature = "inbound-mptp")] + "mptp" => { + let stream = Arc::new(mptp::inbound::stream::Handler::new()); + let handler = Arc::new(proxy::inbound::Handler::new( + tag.clone(), + Some(stream), + None, + )); + handlers.insert(tag.clone(), handler); + } #[cfg(feature = "inbound-hc")] "hc" => { let settings = diff --git a/leaf/src/app/inbound/mod.rs b/leaf/src/app/inbound/mod.rs index e6f138b..49850d8 100644 --- a/leaf/src/app/inbound/mod.rs +++ b/leaf/src/app/inbound/mod.rs @@ -1,4 +1,4 @@ -mod network_listener; +pub mod network_listener; #[cfg(feature = "inbound-tun")] mod tun_listener; diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index 7cbd019..13d2061 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -16,6 +16,8 @@ use tracing::{debug, trace}; use crate::proxy::chain; #[cfg(feature = "outbound-failover")] use crate::proxy::failover; +#[cfg(feature = "outbound-mptp")] +use crate::proxy::mptp; #[cfg(feature = "outbound-static")] use crate::proxy::r#static; #[cfg(feature = "outbound-select")] @@ -116,14 +118,12 @@ impl OutboundManager { #[cfg(feature = "outbound-direct")] "direct" => HandlerBuilder::default() .tag(tag.clone()) - .color(colored::Color::Green) .stream_handler(Arc::new(direct::StreamHandler)) .datagram_handler(Arc::new(direct::DatagramHandler)) .build(), #[cfg(feature = "outbound-drop")] "drop" => HandlerBuilder::default() .tag(tag.clone()) - .color(colored::Color::Red) .stream_handler(Arc::new(drop::StreamHandler)) .datagram_handler(Arc::new(drop::DatagramHandler)) .build(), @@ -609,6 +609,42 @@ impl OutboundManager { settings.actors.join(",") ); } + #[cfg(feature = "outbound-mptp")] + "mptp" => { + let settings = + config::MptpOutboundSettings::parse_from_bytes(&outbound.settings) + .map_err(|e| { + anyhow!("invalid [{}] outbound settings: {}", &tag, e) + })?; + let mut actors = Vec::new(); + for actor in settings.actors.iter() { + if let Some(a) = handlers.get(actor) { + actors.push(a.clone()); + } else { + continue 'outbounds; + } + } + if actors.is_empty() { + continue; + } + let stream = Arc::new(mptp::outbound::stream::Handler { + actors: actors.clone(), + address: settings.address.clone(), + port: settings.port as u16, + dns_client: dns_client.clone(), + }); + let handler = HandlerBuilder::default() + .tag(tag.clone()) + .stream_handler(stream.clone()) + .datagram_handler(stream) + .build(); + handlers.insert(tag.clone(), handler); + trace!( + "added handler [{}] with actors: {}", + &tag, + settings.actors.join(",") + ); + } #[cfg(feature = "plugin")] "plugin" => { let settings = diff --git a/leaf/src/app/outbound/plugin.rs b/leaf/src/app/outbound/plugin.rs index ba8ff5e..1bc5db8 100644 --- a/leaf/src/app/outbound/plugin.rs +++ b/leaf/src/app/outbound/plugin.rs @@ -192,6 +192,7 @@ impl OutboundStreamHandler for ExternalOutboundStreamHandlerProxy { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); self.0.handle(sess, stream).await } } @@ -213,6 +214,7 @@ impl OutboundDatagramHandler for ExternalOutboundDatagramHandlerProxy { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); self.0.handle(sess, transport).await } } diff --git a/leaf/src/app/stat_manager.rs b/leaf/src/app/stat_manager.rs index 104d72c..6226f39 100644 --- a/leaf/src/app/stat_manager.rs +++ b/leaf/src/app/stat_manager.rs @@ -187,6 +187,23 @@ impl Counter { } } +impl Drop for Counter { + fn drop(&mut self) { + info!( + "[{}] [{}] [{}] [{}] [{}] [{}] [{}] [END]", + self.sess + .forwarded_source + .unwrap_or_else(|| self.sess.source.ip()), + self.sess.network, + self.sess.inbound_tag, + self.sess.outbound_tag, + self.sess.destination, + self.bytes_sent(), + self.bytes_recvd(), + ); + } +} + fn get_unix_timestamp() -> u32 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -194,22 +211,6 @@ fn get_unix_timestamp() -> u32 { .unwrap_or(0) } -#[inline] -fn log_session_end(c: &Counter) { - info!( - "[{}] [{}] [{}] [{}] [{}] [{}] [{}] [END]", - c.sess - .forwarded_source - .unwrap_or_else(|| c.sess.source.ip()), - c.sess.network, - c.sess.inbound_tag, - c.sess.outbound_tag, - c.sess.destination, - c.bytes_sent(), - c.bytes_recvd(), - ); -} - #[derive(Default)] pub struct StatManager { pub counters: Vec, @@ -228,8 +229,7 @@ impl StatManager { let mut i = 0; while i < sm.counters.len() { if sm.counters[i].recv_completed() && sm.counters[i].send_completed() { - let c = sm.counters.swap_remove(i); - log_session_end(&c); + sm.counters.swap_remove(i); } else { i += 1; } diff --git a/leaf/src/config/common.rs b/leaf/src/config/common.rs index cdc5dae..0daba71 100644 --- a/leaf/src/config/common.rs +++ b/leaf/src/config/common.rs @@ -29,12 +29,12 @@ pub struct CatInboundSettings { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct NfInboundSettings { - #[serde(rename = "driverName")] + #[serde(rename = "driverName", alias = "driver_name")] pub driver_name: String, pub nfapi: Option, - #[serde(rename = "fakeDnsExclude")] + #[serde(rename = "fakeDnsExclude", alias = "fake_dns_exclude")] pub fake_dns_exclude: Option>, - #[serde(rename = "fakeDnsInclude")] + #[serde(rename = "fakeDnsInclude", alias = "fake_dns_include")] pub fake_dns_include: Option>, pub tun2socks: Option, } @@ -82,7 +82,7 @@ pub struct AMuxInboundSettings { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct QuicInboundSettings { pub certificate: Option, - #[serde(rename = "certificateKey")] + #[serde(rename = "certificateKey", alias = "certificate_key")] pub certificate_key: Option, pub alpn: Option>, } @@ -90,7 +90,7 @@ pub struct QuicInboundSettings { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TlsInboundSettings { pub certificate: Option, - #[serde(rename = "certificateKey")] + #[serde(rename = "certificateKey", alias = "certificate_key")] pub certificate_key: Option, } @@ -100,6 +100,10 @@ pub struct ChainInboundSettings { pub actors: Option>, } +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct MptpInboundSettings {} + #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TunInboundSettings { pub auto: Option, @@ -109,13 +113,13 @@ pub struct TunInboundSettings { pub gateway: Option, pub netmask: Option, pub mtu: Option, - #[serde(rename = "fakeDnsExclude")] + #[serde(rename = "fakeDnsExclude", alias = "fake_dns_exclude")] pub fake_dns_exclude: Option>, - #[serde(rename = "fakeDnsInclude")] + #[serde(rename = "fakeDnsInclude", alias = "fake_dns_include")] pub fake_dns_include: Option>, pub tun2socks: Option, pub wintun: Option, - #[serde(rename = "dnsServers")] + #[serde(rename = "dnsServers", alias = "dns_servers")] pub dns_servers: Option>, } @@ -174,18 +178,18 @@ pub struct VlessOutboundSettings { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RealityOutboundSettings { - #[serde(rename = "serverName")] + #[serde(rename = "serverName", alias = "server_name")] pub server_name: Option, - #[serde(rename = "publicKey")] + #[serde(rename = "publicKey", alias = "public_key")] pub public_key: Option, - #[serde(rename = "shortId")] + #[serde(rename = "shortId", alias = "short_id")] pub short_id: Option, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TryAllOutboundSettings { pub actors: Option>, - #[serde(rename = "delayBase")] + #[serde(rename = "delayBase", alias = "delay_base")] pub delay_base: Option, } @@ -197,7 +201,7 @@ pub struct StaticOutboundSettings { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TlsOutboundSettings { - #[serde(rename = "serverName")] + #[serde(rename = "serverName", alias = "server_name")] pub server_name: Option, pub alpn: Option>, pub certificate: Option, @@ -215,7 +219,7 @@ pub struct AMuxOutboundSettings { pub address: Option, pub port: Option, pub actors: Option>, - #[serde(rename = "maxAccepts")] + #[serde(rename = "maxAccepts", alias = "max_accepts")] pub max_accepts: Option, pub concurrency: Option, pub max_recv_bytes: Option, @@ -226,7 +230,7 @@ pub struct AMuxOutboundSettings { pub struct QuicOutboundSettings { pub address: Option, pub port: Option, - #[serde(rename = "serverName")] + #[serde(rename = "serverName", alias = "server_name")] pub server_name: Option, pub certificate: Option, pub alpn: Option>, @@ -238,37 +242,47 @@ pub struct ChainOutboundSettings { pub actors: Option>, } +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct MptpOutboundSettings { + pub actors: Option>, + pub address: Option, + pub port: Option, +} + #[derive(Serialize, Deserialize, Debug, Clone)] pub struct FailOverOutboundSettings { pub actors: Option>, - #[serde(rename = "failTimeout")] + #[serde(rename = "failTimeout", alias = "fail_timeout")] pub fail_timeout: Option, - #[serde(rename = "healthCheck")] + #[serde(rename = "healthCheck", alias = "health_check")] pub health_check: Option, - #[serde(rename = "healthCheckTimeout")] + #[serde(rename = "healthCheckTimeout", alias = "health_check_timeout")] pub health_check_timeout: Option, - #[serde(rename = "healthCheckDelay")] + #[serde(rename = "healthCheckDelay", alias = "health_check_delay")] pub health_check_delay: Option, - #[serde(rename = "healthCheckActive")] + #[serde(rename = "healthCheckActive", alias = "health_check_active")] pub health_check_active: Option, - #[serde(rename = "healthCheckPrefers")] + #[serde(rename = "healthCheckPrefers", alias = "health_check_prefers")] pub health_check_prefers: Option>, - #[serde(rename = "checkInterval")] + #[serde(rename = "checkInterval", alias = "check_interval")] pub check_interval: Option, - #[serde(rename = "healthCheckOnStart")] + #[serde(rename = "healthCheckOnStart", alias = "health_check_on_start")] pub health_check_on_start: Option, - #[serde(rename = "healthCheckWait")] + #[serde(rename = "healthCheckWait", alias = "health_check_wait")] pub health_check_wait: Option, - #[serde(rename = "healthCheckAttempts")] + #[serde(rename = "healthCheckAttempts", alias = "health_check_attempts")] pub health_check_attempts: Option, - #[serde(rename = "healthCheckSuccessPercentage")] + #[serde( + rename = "healthCheckSuccessPercentage", + alias = "health_check_success_percentage" + )] pub health_check_success_percentage: Option, pub failover: Option, - #[serde(rename = "fallbackCache")] + #[serde(rename = "fallbackCache", alias = "fallback_cache")] pub fallback_cache: Option, - #[serde(rename = "cacheSize")] + #[serde(rename = "cacheSize", alias = "cache_size")] pub cache_size: Option, - #[serde(rename = "cacheTimeout")] + #[serde(rename = "cacheTimeout", alias = "cache_timeout")] pub cache_timeout: Option, } @@ -336,6 +350,10 @@ pub enum InboundSettings { #[serde(default)] settings: Option, }, + Mptp { + #[serde(default)] + settings: Option, + }, Tun { #[serde(default)] settings: Option, @@ -418,6 +436,10 @@ pub enum OutboundSettings { #[serde(default)] settings: Option, }, + Mptp { + #[serde(default)] + settings: Option, + }, FailOver { #[serde(default)] settings: Option, @@ -440,18 +462,18 @@ pub struct Rule { pub type_field: Option, pub ip: Option>, pub domain: Option>, - #[serde(rename = "domainKeyword")] + #[serde(rename = "domainKeyword", alias = "domain_keyword")] pub domain_keyword: Option>, - #[serde(rename = "domainSuffix")] + #[serde(rename = "domainSuffix", alias = "domain_suffix")] pub domain_suffix: Option>, pub geoip: Option>, pub external: Option>, - #[serde(rename = "portRange")] + #[serde(rename = "portRange", alias = "port_range")] pub port_range: Option>, pub network: Option>, - #[serde(rename = "inboundTag")] + #[serde(rename = "inboundTag", alias = "inbound_tag")] pub inbound_tag: Option>, - #[serde(rename = "processName")] + #[serde(rename = "processName", alias = "process_name")] pub process_name: Option>, pub target: String, } @@ -459,7 +481,7 @@ pub struct Rule { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Router { pub rules: Option>, - #[serde(rename = "domainResolve")] + #[serde(rename = "domainResolve", alias = "domain_resolve")] pub domain_resolve: Option, } @@ -862,6 +884,17 @@ pub fn to_internal(mut config: Config) -> Result { } inbounds.push(inbound); } + InboundSettings::Mptp { + settings: ext_settings, + } => { + inbound.protocol = "mptp".to_string(); + if let Some(_ext_settings) = ext_settings { + let settings = internal::MptpInboundSettings::new(); + let settings = settings.write_to_bytes().unwrap(); + inbound.settings = settings; + } + inbounds.push(inbound); + } } } } @@ -1265,6 +1298,28 @@ pub fn to_internal(mut config: Config) -> Result { } outbounds.push(outbound); } + OutboundSettings::Mptp { + settings: ext_settings, + } => { + outbound.protocol = "mptp".to_string(); + if let Some(ext_settings) = ext_settings { + let mut settings = internal::MptpOutboundSettings::new(); + if let Some(ext_actors) = &ext_settings.actors { + for ext_actor in ext_actors { + settings.actors.push(ext_actor.clone()); + } + } + if let Some(ext_address) = &ext_settings.address { + settings.address = ext_address.clone(); + } + if let Some(ext_port) = ext_settings.port { + settings.port = ext_port as u32; + } + let settings = settings.write_to_bytes().unwrap(); + outbound.settings = settings; + } + outbounds.push(outbound); + } OutboundSettings::Select { settings: ext_settings, } => { diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index 9ff53fc..1ae15e9 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -102,6 +102,9 @@ message ChainInboundSettings { repeated string actors = 1; } +message MptpInboundSettings { +} + message HcInboundSettings { string path = 1; string request = 2; @@ -211,6 +214,12 @@ message ChainOutboundSettings { repeated string actors = 1; } +message MptpOutboundSettings { + repeated string actors = 1; + string address = 2; + uint32 port = 3; +} + message FailOverOutboundSettings { // A list of outbound tags. repeated string actors = 1; diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index 02f9530..dd2187c 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -1790,6 +1790,82 @@ impl ::protobuf::Message for ChainInboundSettings { } } +// @@protoc_insertion_point(message:MptpInboundSettings) +#[derive(PartialEq,Clone,Default,Debug)] +pub struct MptpInboundSettings { + // special fields + // @@protoc_insertion_point(special_field:MptpInboundSettings.special_fields) + pub special_fields: ::protobuf::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a MptpInboundSettings { + fn default() -> &'a MptpInboundSettings { + ::default_instance() + } +} + +impl MptpInboundSettings { + pub fn new() -> MptpInboundSettings { + ::std::default::Default::default() + } +} + +impl ::protobuf::Message for MptpInboundSettings { + const NAME: &'static str = "MptpInboundSettings"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + tag => { + ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::Result<()> { + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &::protobuf::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut ::protobuf::SpecialFields { + &mut self.special_fields + } + + fn new() -> MptpInboundSettings { + MptpInboundSettings::new() + } + + fn clear(&mut self) { + self.special_fields.clear(); + } + + fn default_instance() -> &'static MptpInboundSettings { + static instance: MptpInboundSettings = MptpInboundSettings { + special_fields: ::protobuf::SpecialFields::new(), + }; + &instance + } +} + // @@protoc_insertion_point(message:HcInboundSettings) #[derive(PartialEq,Clone,Default,Debug)] pub struct HcInboundSettings { @@ -3870,6 +3946,122 @@ impl ::protobuf::Message for ChainOutboundSettings { } } +// @@protoc_insertion_point(message:MptpOutboundSettings) +#[derive(PartialEq,Clone,Default,Debug)] +pub struct MptpOutboundSettings { + // message fields + // @@protoc_insertion_point(field:MptpOutboundSettings.actors) + pub actors: ::std::vec::Vec<::std::string::String>, + // @@protoc_insertion_point(field:MptpOutboundSettings.address) + pub address: ::std::string::String, + // @@protoc_insertion_point(field:MptpOutboundSettings.port) + pub port: u32, + // special fields + // @@protoc_insertion_point(special_field:MptpOutboundSettings.special_fields) + pub special_fields: ::protobuf::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a MptpOutboundSettings { + fn default() -> &'a MptpOutboundSettings { + ::default_instance() + } +} + +impl MptpOutboundSettings { + pub fn new() -> MptpOutboundSettings { + ::std::default::Default::default() + } +} + +impl ::protobuf::Message for MptpOutboundSettings { + const NAME: &'static str = "MptpOutboundSettings"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.actors.push(is.read_string()?); + }, + 18 => { + self.address = is.read_string()?; + }, + 24 => { + self.port = is.read_uint32()?; + }, + tag => { + ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + for value in &self.actors { + my_size += ::protobuf::rt::string_size(1, &value); + }; + if !self.address.is_empty() { + my_size += ::protobuf::rt::string_size(2, &self.address); + } + if self.port != 0 { + my_size += ::protobuf::rt::uint32_size(3, self.port); + } + my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::Result<()> { + for v in &self.actors { + os.write_string(1, &v)?; + }; + if !self.address.is_empty() { + os.write_string(2, &self.address)?; + } + if self.port != 0 { + os.write_uint32(3, self.port)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &::protobuf::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut ::protobuf::SpecialFields { + &mut self.special_fields + } + + fn new() -> MptpOutboundSettings { + MptpOutboundSettings::new() + } + + fn clear(&mut self) { + self.actors.clear(); + self.address.clear(); + self.port = 0; + self.special_fields.clear(); + } + + fn default_instance() -> &'static MptpOutboundSettings { + static instance: MptpOutboundSettings = MptpOutboundSettings { + actors: ::std::vec::Vec::new(), + address: ::std::string::String::new(), + port: 0, + special_fields: ::protobuf::SpecialFields::new(), + }; + &instance + } +} + // @@protoc_insertion_point(message:FailOverOutboundSettings) #[derive(PartialEq,Clone,Default,Debug)] pub struct FailOverOutboundSettings { diff --git a/leaf/src/option/mod.rs b/leaf/src/option/mod.rs index db4f5bc..62461a1 100644 --- a/leaf/src/option/mod.rs +++ b/leaf/src/option/mod.rs @@ -89,10 +89,6 @@ lazy_static! { get_env_var_or("LOG_CONSOLE_OUT", false) }; - pub static ref LOG_NO_COLOR: bool = { - get_env_var_or("LOG_NO_COLOR", false) - }; - /// Turn on TLS SNI sniffing, the sniffed SNI would override the original /// destination address, by default the sniffing would perform only on /// connections with destination port 443, set also TLS_DOMAIN_SNIFFING_ALL diff --git a/leaf/src/proxy/amux/inbound/stream.rs b/leaf/src/proxy/amux/inbound/stream.rs index 3498987..fdeb3e0 100644 --- a/leaf/src/proxy/amux/inbound/stream.rs +++ b/leaf/src/proxy/amux/inbound/stream.rs @@ -51,6 +51,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, mut stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); for a in self.actors.iter() { match a.stream()?.handle(sess, stream).await? { InboundTransport::Stream(new_stream, new_sess) => { diff --git a/leaf/src/proxy/amux/outbound/stream.rs b/leaf/src/proxy/amux/outbound/stream.rs index 7897d17..396f011 100644 --- a/leaf/src/proxy/amux/outbound/stream.rs +++ b/leaf/src/proxy/amux/outbound/stream.rs @@ -185,6 +185,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, _stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); Ok(Box::new(self.manager.new_stream(sess).await?)) } } diff --git a/leaf/src/proxy/chain/inbound/datagram.rs b/leaf/src/proxy/chain/inbound/datagram.rs index 016dddc..bc28d0e 100644 --- a/leaf/src/proxy/chain/inbound/datagram.rs +++ b/leaf/src/proxy/chain/inbound/datagram.rs @@ -16,6 +16,7 @@ impl InboundDatagramHandler for Handler { &'a self, mut socket: AnyInboundDatagram, ) -> io::Result { + tracing::trace!("handling inbound datagram"); let mut sess: Option = None; for (i, a) in self.actors.iter().enumerate() { let transport = a.datagram()?.handle(socket).await?; diff --git a/leaf/src/proxy/chain/inbound/stream.rs b/leaf/src/proxy/chain/inbound/stream.rs index b2cab90..ba462cb 100644 --- a/leaf/src/proxy/chain/inbound/stream.rs +++ b/leaf/src/proxy/chain/inbound/stream.rs @@ -17,6 +17,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, mut stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); for (i, a) in self.actors.iter().enumerate() { let transport = a.stream()?.handle(sess.clone(), stream).await?; match transport { diff --git a/leaf/src/proxy/chain/outbound/datagram.rs b/leaf/src/proxy/chain/outbound/datagram.rs index 0f47871..473e3d0 100644 --- a/leaf/src/proxy/chain/outbound/datagram.rs +++ b/leaf/src/proxy/chain/outbound/datagram.rs @@ -130,6 +130,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); match transport { Some(transport) => match transport { OutboundTransport::Datagram(dgram) => self.handle(sess, None, Some(dgram)).await, diff --git a/leaf/src/proxy/chain/outbound/stream.rs b/leaf/src/proxy/chain/outbound/stream.rs index cb042c2..587b71d 100644 --- a/leaf/src/proxy/chain/outbound/stream.rs +++ b/leaf/src/proxy/chain/outbound/stream.rs @@ -62,6 +62,7 @@ impl OutboundStreamHandler for Handler { mut lhs: Option<&mut AnyStream>, mut stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); for (i, a) in self.actors.iter().enumerate() { let new_sess = self.next_session(sess.clone(), i + 1); let s = stream.take(); diff --git a/leaf/src/proxy/direct/datagram.rs b/leaf/src/proxy/direct/datagram.rs index a916096..27cb14d 100644 --- a/leaf/src/proxy/direct/datagram.rs +++ b/leaf/src/proxy/direct/datagram.rs @@ -21,6 +21,7 @@ impl OutboundDatagramHandler for Handler { _sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", _sess); if let Some(OutboundTransport::Datagram(dgram)) = transport { Ok(dgram) } else { diff --git a/leaf/src/proxy/direct/stream.rs b/leaf/src/proxy/direct/stream.rs index 3ff509e..092c19a 100644 --- a/leaf/src/proxy/direct/stream.rs +++ b/leaf/src/proxy/direct/stream.rs @@ -18,6 +18,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", _sess); stream.ok_or_else(|| io::Error::other("invalid input")) } } diff --git a/leaf/src/proxy/drop/datagram.rs b/leaf/src/proxy/drop/datagram.rs index 37a1416..7adf60a 100644 --- a/leaf/src/proxy/drop/datagram.rs +++ b/leaf/src/proxy/drop/datagram.rs @@ -21,6 +21,7 @@ impl OutboundDatagramHandler for Handler { _sess: &'a Session, _transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", _sess); Err(io::Error::other("dropped")) } } diff --git a/leaf/src/proxy/drop/stream.rs b/leaf/src/proxy/drop/stream.rs index 58867ac..703e9e7 100644 --- a/leaf/src/proxy/drop/stream.rs +++ b/leaf/src/proxy/drop/stream.rs @@ -18,6 +18,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, _stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", _sess); Err(io::Error::other("dropped")) } } diff --git a/leaf/src/proxy/failover/datagram.rs b/leaf/src/proxy/failover/datagram.rs index a7a6401..f115504 100644 --- a/leaf/src/proxy/failover/datagram.rs +++ b/leaf/src/proxy/failover/datagram.rs @@ -117,6 +117,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, _transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); *self.last_active.lock().await = Instant::now(); if let Some(task) = self.health_check_task.lock().await.take() { diff --git a/leaf/src/proxy/failover/stream.rs b/leaf/src/proxy/failover/stream.rs index cf388a0..6d398c6 100644 --- a/leaf/src/proxy/failover/stream.rs +++ b/leaf/src/proxy/failover/stream.rs @@ -131,6 +131,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, _stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); *self.last_active.lock().await = Instant::now(); if let Some(task) = self.health_check_task.lock().await.take() { diff --git a/leaf/src/proxy/hc/inbound/stream.rs b/leaf/src/proxy/hc/inbound/stream.rs index fab2855..ead6e8e 100644 --- a/leaf/src/proxy/hc/inbound/stream.rs +++ b/leaf/src/proxy/hc/inbound/stream.rs @@ -174,6 +174,7 @@ impl InboundStreamHandler for Handler { _sess: Session, mut stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", _sess); // Handle the HTTP request and send response if let Err(_e) = self.handle_request(&mut stream).await { self.delay_and_close().await; diff --git a/leaf/src/proxy/http/inbound/stream.rs b/leaf/src/proxy/http/inbound/stream.rs index 253b85c..a6f21ce 100644 --- a/leaf/src/proxy/http/inbound/stream.rs +++ b/leaf/src/proxy/http/inbound/stream.rs @@ -248,6 +248,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); let mut http_stream = HttpStream { cache: Vec::new(), destination: None, diff --git a/leaf/src/proxy/inbound.rs b/leaf/src/proxy/inbound.rs index 8ac9e55..fb80476 100644 --- a/leaf/src/proxy/inbound.rs +++ b/leaf/src/proxy/inbound.rs @@ -30,12 +30,6 @@ impl Tag for Handler { } } -impl Color for Handler { - fn color(&self) -> &colored::Color { - &colored::Color::White - } -} - impl BaseHandler for Handler {} impl InboundHandler for Handler { diff --git a/leaf/src/proxy/mod.rs b/leaf/src/proxy/mod.rs index 2a5ac77..de8d0ad 100644 --- a/leaf/src/proxy/mod.rs +++ b/leaf/src/proxy/mod.rs @@ -55,6 +55,8 @@ pub mod failover; pub mod hc; #[cfg(feature = "inbound-http")] pub mod http; +#[cfg(feature = "outbound-mptp")] +pub mod mptp; #[cfg(all(feature = "inbound-nf", windows))] pub mod nf; #[cfg(feature = "outbound-obfs")] @@ -111,10 +113,6 @@ pub trait Tag { fn tag(&self) -> &String; } -pub trait Color { - fn color(&self) -> &colored::Color; -} - #[derive(Debug)] pub enum OutboundBind { Ip(SocketAddr), @@ -547,7 +545,7 @@ impl ProxyStream for S where S: AsyncRead + AsyncWrite + Send + Sync + Unpin pub type AnyStream = Box; -pub trait BaseHandler: Tag + Color + Send + Sync + Unpin {} +pub trait BaseHandler: Tag + Send + Sync + Unpin {} /// An outbound handler for both UDP and TCP outgoing connections. pub trait OutboundHandler: BaseHandler { diff --git a/leaf/src/proxy/mptp/inbound/mod.rs b/leaf/src/proxy/mptp/inbound/mod.rs new file mode 100644 index 0000000..baf29e0 --- /dev/null +++ b/leaf/src/proxy/mptp/inbound/mod.rs @@ -0,0 +1 @@ +pub mod stream; diff --git a/leaf/src/proxy/mptp/inbound/stream.rs b/leaf/src/proxy/mptp/inbound/stream.rs new file mode 100644 index 0000000..14c69ee --- /dev/null +++ b/leaf/src/proxy/mptp/inbound/stream.rs @@ -0,0 +1,256 @@ +use std::collections::HashMap; +use std::io; +use std::pin::Pin; +use std::sync::{Arc, RwLock}; +use std::task::{Context, Poll}; + +use crate::proxy::mptp::mptp_conn::{ + protocol::{Address, HandshakeRequest, CMD_UDP}, + MptpDatagram, MptpStream, +}; +use async_trait::async_trait; +use bytes::{Buf, BytesMut}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf}; +use tokio::sync::mpsc::{self, UnboundedSender}; +use uuid::Uuid; + +use crate::{ + proxy::{AnyInboundTransport, AnyStream, InboundStreamHandler, InboundTransport}, + session::{Session, SocksAddr}, +}; + +struct PrefixedStream { + stream: S, + prefix: BytesMut, +} + +impl PrefixedStream { + fn new(stream: S, prefix: BytesMut) -> Self { + Self { stream, prefix } + } +} + +impl AsyncRead for PrefixedStream { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + if !self.prefix.is_empty() { + let len = std::cmp::min(buf.remaining(), self.prefix.len()); + buf.put_slice(&self.prefix[..len]); + self.prefix.advance(len); + return Poll::Ready(Ok(())); + } + Pin::new(&mut self.stream).poll_read(cx, buf) + } +} + +impl AsyncWrite for PrefixedStream { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.stream).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.stream).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.stream).poll_shutdown(cx) + } +} + +struct TrackedMptpStream { + inner: MptpStream, + cid: Uuid, + sessions: Arc)>>>>, +} + +impl AsyncRead for TrackedMptpStream { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_read(cx, buf) + } +} + +impl AsyncWrite for TrackedMptpStream { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } +} + +impl Drop for TrackedMptpStream { + fn drop(&mut self) { + if let Ok(mut sessions) = self.sessions.write() { + sessions.remove(&self.cid); + tracing::debug!("MPTP session {} removed", self.cid); + } + } +} + +pub struct Handler { + sessions: + Arc, Option)>>>>, +} + +impl Handler { + pub fn new() -> Self { + Self { + sessions: Arc::new(RwLock::new(HashMap::new())), + } + } +} + +#[async_trait] +impl InboundStreamHandler for Handler { + async fn handle<'a>( + &'a self, + mut sess: Session, + mut stream: AnyStream, + ) -> io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); + let mut buf = BytesMut::with_capacity(1024); + + // Read handshake + // We need to loop until we have enough data or EOF + loop { + let n = stream.read_buf(&mut buf).await?; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "EOF during handshake", + )); + } + + // Try to decode + let mut buf_copy = buf.clone(); + match HandshakeRequest::decode(&mut buf_copy) { + Ok(Some(req)) => { + // Success + // buf_copy has advanced, so we know how much was consumed. + // Actually HandshakeRequest::decode advances the buffer. + // So we can determine the consumed amount by comparing lengths. + let consumed = buf.len() - buf_copy.len(); + buf.advance(consumed); + + let remaining = buf; // This is the prefix for the stream + + let prefixed_stream = PrefixedStream::new(stream, remaining); + + // Check CID + let is_new = { + let sessions = self + .sessions + .read() + .map_err(|_| io::Error::new(io::ErrorKind::Other, "Lock poisoned"))?; + !sessions.contains_key(&req.cid) + }; + + if is_new { + tracing::info!("New MPTP session: {}", req.cid); + let (tx, rx) = mpsc::unbounded_channel(); + + // Register session + { + let mut sessions = self.sessions.write().map_err(|_| { + io::Error::new(io::ErrorKind::Other, "Lock poisoned") + })?; + sessions.insert(req.cid, tx.clone()); + } + + // Send the first stream (this one) to the MptpStream via channel? + // No, MptpStream::new_with_receiver takes the receiver. + // And we can pass the initial stream(s) via channel or maybe constructor supports it? + // MptpStream::new_with_receiver(rx) creates an empty one that pulls from rx. + // So we should send this stream to tx. + + let _ = tx.send((prefixed_stream, Some(req.cid))); + + let mptp_stream = MptpStream::new_with_receiver(rx); + let tracked_stream = TrackedMptpStream { + inner: mptp_stream, + cid: req.cid, + sessions: self.sessions.clone(), + }; + + // Update session destination + match req.dst_addr { + Address::Ipv4(ip) => { + sess.destination = SocksAddr::from((ip, req.dst_port)); + } + Address::Ipv6(ip) => { + sess.destination = SocksAddr::from((ip, req.dst_port)); + } + Address::Domain(domain) => { + sess.destination = SocksAddr::try_from((domain, req.dst_port)) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + } + } + + if req.cmd == CMD_UDP { + let mptp_datagram = MptpDatagram::new(tracked_stream); + return Ok(InboundTransport::Datagram( + Box::new(mptp_datagram), + Some(sess), + )); + } + + return Ok(InboundTransport::Stream(Box::new(tracked_stream), sess)); + } else { + tracing::debug!("Joining existing MPTP session: {}", req.cid); + let tx = { + let sessions = self.sessions.read().map_err(|_| { + io::Error::new(io::ErrorKind::Other, "Lock poisoned") + })?; + sessions.get(&req.cid).cloned() + }; + + if let Some(tx) = tx { + if let Err(_) = tx.send((prefixed_stream, Some(req.cid))) { + // Channel closed, session probably dead + tracing::warn!("MPTP session {} channel closed", req.cid); + return Err(io::Error::new( + io::ErrorKind::ConnectionAborted, + "Session closed", + )); + } + return Ok(InboundTransport::Empty); + } else { + // Should not happen due to lock, but possible if removed concurrently + return Err(io::Error::new( + io::ErrorKind::ConnectionRefused, + "Session not found", + )); + } + } + } + Ok(None) => { + // Need more data + continue; + } + Err(e) => { + return Err(io::Error::new(io::ErrorKind::InvalidData, e)); + } + } + } + } +} diff --git a/leaf/src/proxy/mptp/mod.rs b/leaf/src/proxy/mptp/mod.rs new file mode 100644 index 0000000..763dbc5 --- /dev/null +++ b/leaf/src/proxy/mptp/mod.rs @@ -0,0 +1,6 @@ +#[cfg(feature = "inbound-mptp")] +pub mod inbound; +#[cfg(feature = "outbound-mptp")] +pub mod outbound; + +pub mod mptp_conn; diff --git a/leaf/src/proxy/mptp/mptp_conn/datagram.rs b/leaf/src/proxy/mptp/mptp_conn/datagram.rs new file mode 100644 index 0000000..860966c --- /dev/null +++ b/leaf/src/proxy/mptp/mptp_conn/datagram.rs @@ -0,0 +1,239 @@ +use std::io; +use std::net::SocketAddr; + +use async_trait::async_trait; +use bytes::{BufMut, BytesMut}; +use tokio::io::{split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf}; + +use crate::proxy::*; +use crate::session::{DatagramSource, SocksAddr}; + +use super::protocol::{Address, UdpHeader}; + +pub struct MptpDatagram { + stream: S, +} + +impl MptpDatagram { + pub fn new(stream: S) -> Self { + Self { stream } + } +} + +impl InboundDatagram for MptpDatagram +where + S: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static, +{ + fn split( + self: Box, + ) -> ( + Box, + Box, + ) { + let (r, w) = split(self.stream); + ( + Box::new(InboundDatagramRecvHalfImpl(r)), + Box::new(InboundDatagramSendHalfImpl(w)), + ) + } + + fn into_std(self: Box) -> io::Result { + Err(io::Error::new(io::ErrorKind::Other, "not supported")) + } +} + +impl OutboundDatagram for MptpDatagram +where + S: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static, +{ + fn split( + self: Box, + ) -> ( + Box, + Box, + ) { + let (r, w) = split(self.stream); + ( + Box::new(OutboundDatagramRecvHalfImpl(r)), + Box::new(OutboundDatagramSendHalfImpl(w)), + ) + } +} + +pub struct InboundDatagramRecvHalfImpl(ReadHalf); + +#[async_trait] +impl InboundDatagramRecvHalf + for InboundDatagramRecvHalfImpl +{ + async fn recv_from( + &mut self, + buf: &mut [u8], + ) -> ProxyResult<(usize, DatagramSource, SocksAddr)> { + // Read length (2 bytes) + let mut len_buf = [0u8; 2]; + if let Err(e) = self.0.read_exact(&mut len_buf).await { + if e.kind() == io::ErrorKind::UnexpectedEof { + return Err(ProxyError::DatagramFatal(anyhow::anyhow!("stream closed"))); + } + return Err(ProxyError::DatagramFatal(e.into())); + } + let len = u16::from_be_bytes(len_buf) as usize; + + let mut data = vec![0u8; len]; + self.0 + .read_exact(&mut data) + .await + .map_err(|e| ProxyError::DatagramFatal(e.into()))?; + + let mut data_buf = BytesMut::from(&data[..]); + let header = UdpHeader::decode(&mut data_buf) + .map_err(|e| ProxyError::DatagramWarn(anyhow::anyhow!(e)))? + .ok_or_else(|| ProxyError::DatagramWarn(anyhow::anyhow!("incomplete header")))?; + + let payload_len = data_buf.len(); + if buf.len() < payload_len { + return Err(ProxyError::DatagramWarn(anyhow::anyhow!( + "buffer too small" + ))); + } + buf[..payload_len].copy_from_slice(&data_buf); + + let dst_addr = match header.addr { + Address::Ipv4(ip) => SocksAddr::from((ip, header.port)), + Address::Ipv6(ip) => SocksAddr::from((ip, header.port)), + Address::Domain(domain) => SocksAddr::try_from((domain, header.port)) + .map_err(|e| ProxyError::DatagramWarn(anyhow::anyhow!(e)))?, + }; + + // For inbound, we don't really know the source addr from the stream itself. + // We just use a placeholder. + let src_addr = DatagramSource::new("0.0.0.0:0".parse().unwrap(), None); + + Ok((payload_len, src_addr, dst_addr)) + } +} + +pub struct InboundDatagramSendHalfImpl(WriteHalf); + +#[async_trait] +impl InboundDatagramSendHalf + for InboundDatagramSendHalfImpl +{ + async fn send_to( + &mut self, + buf: &[u8], + src_addr: &SocksAddr, + _dst_addr: &SocketAddr, + ) -> io::Result { + let address = match src_addr { + SocksAddr::Ip(std::net::SocketAddr::V4(v4)) => Address::Ipv4(*v4.ip()), + SocksAddr::Ip(std::net::SocketAddr::V6(v6)) => Address::Ipv6(*v6.ip()), + SocksAddr::Domain(domain, _) => Address::Domain(domain.clone()), + }; + + let header = UdpHeader { + frag: 0, + addr: address, + port: src_addr.port(), + }; + + let mut encoded = BytesMut::new(); + header.encode(&mut encoded); + encoded.put_slice(buf); + + let len = encoded.len() as u16; + self.0.write_u16(len).await?; + self.0.write_all(&encoded).await?; + + Ok(buf.len()) + } + + async fn close(&mut self) -> io::Result<()> { + self.0.shutdown().await + } +} + +pub struct OutboundDatagramRecvHalfImpl(ReadHalf); + +#[async_trait] +impl OutboundDatagramRecvHalf + for OutboundDatagramRecvHalfImpl +{ + async fn recv_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, SocksAddr)> { + // Read length (2 bytes) + let mut len_buf = [0u8; 2]; + self.0.read_exact(&mut len_buf).await?; + let len = u16::from_be_bytes(len_buf) as usize; + + let mut data = vec![0u8; len]; + self.0.read_exact(&mut data).await?; + + let mut data_buf = BytesMut::from(&data[..]); + let header = UdpHeader::decode(&mut data_buf) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))? + .ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "incomplete header"))?; + + let payload_len = data_buf.len(); + if buf.len() < payload_len { + tracing::warn!( + "UDP payload too large for buffer: {} > {}", + payload_len, + buf.len() + ); + buf.copy_from_slice(&data_buf[..buf.len()]); + let addr = match header.addr { + Address::Ipv4(ip) => SocksAddr::from((ip, header.port)), + Address::Ipv6(ip) => SocksAddr::from((ip, header.port)), + Address::Domain(domain) => SocksAddr::try_from((domain, header.port)) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, + }; + return Ok((buf.len(), addr)); + } + buf[..payload_len].copy_from_slice(&data_buf); + + let addr = match header.addr { + Address::Ipv4(ip) => SocksAddr::from((ip, header.port)), + Address::Ipv6(ip) => SocksAddr::from((ip, header.port)), + Address::Domain(domain) => SocksAddr::try_from((domain, header.port)) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, + }; + + Ok((payload_len, addr)) + } +} + +pub struct OutboundDatagramSendHalfImpl(WriteHalf); + +#[async_trait] +impl OutboundDatagramSendHalf + for OutboundDatagramSendHalfImpl +{ + async fn send_to(&mut self, buf: &[u8], target: &SocksAddr) -> io::Result { + let address = match target { + SocksAddr::Ip(std::net::SocketAddr::V4(v4)) => Address::Ipv4(*v4.ip()), + SocksAddr::Ip(std::net::SocketAddr::V6(v6)) => Address::Ipv6(*v6.ip()), + SocksAddr::Domain(domain, _) => Address::Domain(domain.clone()), + }; + + let header = UdpHeader { + frag: 0, + addr: address, + port: target.port(), + }; + + let mut encoded = BytesMut::new(); + header.encode(&mut encoded); + encoded.put_slice(buf); + + let len = encoded.len() as u16; + self.0.write_u16(len).await?; + self.0.write_all(&encoded).await?; + + Ok(buf.len()) + } + + async fn close(&mut self) -> io::Result<()> { + self.0.shutdown().await + } +} diff --git a/leaf/src/proxy/mptp/mptp_conn/mod.rs b/leaf/src/proxy/mptp/mptp_conn/mod.rs new file mode 100644 index 0000000..b3647ec --- /dev/null +++ b/leaf/src/proxy/mptp/mptp_conn/mod.rs @@ -0,0 +1,6 @@ +pub mod datagram; +pub mod protocol; +pub mod stream; + +pub use datagram::MptpDatagram; +pub use stream::MptpStream; diff --git a/leaf/src/proxy/mptp/mptp_conn/protocol.rs b/leaf/src/proxy/mptp/mptp_conn/protocol.rs new file mode 100644 index 0000000..0e4f944 --- /dev/null +++ b/leaf/src/proxy/mptp/mptp_conn/protocol.rs @@ -0,0 +1,283 @@ +use anyhow::{bail, Result}; +use bytes::{Buf, BufMut, Bytes, BytesMut}; +use std::net::{Ipv4Addr, Ipv6Addr}; + +pub const VER: u8 = 1; + +// Message Types +pub const MTYP_DATA: u8 = 0x01; +pub const MTYP_PING: u8 = 0x02; +pub const MTYP_PONG: u8 = 0x03; +pub const MTYP_FIN: u8 = 0x04; +pub const MTYP_RST: u8 = 0x05; + +// Handshake +pub const CMD_CONNECT: u8 = 0x01; // TCP +pub const CMD_UDP: u8 = 0x03; // UDP (SOCKS5 style) + +pub const ATYP_IPV4: u8 = 0x01; +pub const ATYP_DOMAIN: u8 = 0x03; +pub const ATYP_IPV6: u8 = 0x04; + +// Data Frame Header: MTYP(1) + PN(8) + LEN(4) +pub const DATA_HEADER_LEN: usize = 1 + 8 + 4; +// Control Frame Header (min): MTYP(1) +pub const MIN_HEADER_LEN: usize = 1; + +#[derive(Debug, Clone)] +pub enum Address { + Ipv4(Ipv4Addr), + Domain(String), + Ipv6(Ipv6Addr), +} + +impl Address { + pub fn encode(&self, buf: &mut BytesMut) { + match self { + Address::Ipv4(addr) => { + buf.put_u8(ATYP_IPV4); + buf.put_slice(&addr.octets()); + } + Address::Domain(domain) => { + buf.put_u8(ATYP_DOMAIN); + let bytes = domain.as_bytes(); + buf.put_u8(bytes.len() as u8); + buf.put_slice(bytes); + } + Address::Ipv6(addr) => { + buf.put_u8(ATYP_IPV6); + buf.put_slice(&addr.octets()); + } + } + } + + pub fn to_bytes(&self) -> Vec { + let mut buf = BytesMut::new(); + self.encode(&mut buf); + buf.to_vec() + } + + pub fn decode(buf: &mut BytesMut) -> Result> { + if buf.is_empty() { + return Ok(None); + } + let atyp = buf[0]; + match atyp { + ATYP_IPV4 => { + if buf.len() < 1 + 4 { + return Ok(None); + } + buf.advance(1); + let mut octets = [0u8; 4]; + octets.copy_from_slice(&buf[..4]); + buf.advance(4); + Ok(Some(Address::Ipv4(Ipv4Addr::from(octets)))) + } + ATYP_DOMAIN => { + if buf.len() < 2 { + return Ok(None); + } + let len = buf[1] as usize; + if buf.len() < 1 + 1 + len { + return Ok(None); + } + buf.advance(2); + let domain = String::from_utf8_lossy(&buf[..len]).to_string(); + buf.advance(len); + Ok(Some(Address::Domain(domain))) + } + ATYP_IPV6 => { + if buf.len() < 1 + 16 { + return Ok(None); + } + buf.advance(1); + let mut octets = [0u8; 16]; + octets.copy_from_slice(&buf[..16]); + buf.advance(16); + Ok(Some(Address::Ipv6(Ipv6Addr::from(octets)))) + } + _ => bail!("Unknown ATYP: {}", atyp), + } + } +} + +#[derive(Debug, Clone)] +pub struct HandshakeRequest { + pub ver: u8, + pub cid: uuid::Uuid, + pub cmd: u8, + pub dst_addr: Address, + pub dst_port: u16, +} + +impl HandshakeRequest { + pub fn encode(&self, buf: &mut BytesMut) { + buf.put_u8(self.ver); + buf.put_slice(self.cid.as_bytes()); + buf.put_u8(self.cmd); + self.dst_addr.encode(buf); + buf.put_u16(self.dst_port); + } + + pub fn decode(buf: &mut BytesMut) -> Result> { + // VER(1) + CID(16) + CMD(1) + ATYP(1) ... + if buf.len() < 1 + 16 + 1 + 1 { + return Ok(None); + } + + // Peek to check if we have enough for address + // But Address::decode advances buffer. We need to be careful. + // Actually, let's clone the buffer to try decode, or just implement peek logic. + // Since `Address::decode` handles length check, we can try to decode strictly if we are sure. + // However, we need to handle "Partial" state. + // Let's implement a safe way. + + let mut reader = std::io::Cursor::new(&buf[..]); + + // Skip VER, CID, CMD + reader.advance(1 + 16 + 1); + + // Check Address + if !reader.has_remaining() { + return Ok(None); + } + let atyp = reader.get_u8(); + let addr_len = match atyp { + ATYP_IPV4 => 4, + ATYP_DOMAIN => { + if !reader.has_remaining() { + return Ok(None); + } + reader.get_u8() as usize + } + ATYP_IPV6 => 16, + _ => return Err(anyhow::anyhow!("Unknown ATYP: {}", atyp)), + }; + + if reader.remaining() < addr_len + 2 { + // +2 for Port + return Ok(None); + } + + // Now we know we have enough data. + let ver = buf.get_u8(); + if ver != VER { + return Err(anyhow::anyhow!("Unsupported Version: {}", ver)); + } + + let cid = uuid::Uuid::from_bytes({ + let mut b = [0u8; 16]; + b.copy_from_slice(&buf[..16]); + buf.advance(16); + b + }); + + let cmd = buf.get_u8(); + + let dst_addr = match Address::decode(buf)? { + Some(a) => a, + None => unreachable!("We checked length"), + }; + + let dst_port = buf.get_u16(); + + Ok(Some(HandshakeRequest { + ver, + cid, + cmd, + dst_addr, + dst_port, + })) + } +} + +// UDP Header Helper +// SOCKS5 UDP: RSV(2) FRAG(1) ATYP(1) DST.ADDR DST.PORT DATA +// We'll simplify this for internal use or reuse SOCKS5 format. +// We should implement SOCKS5 UDP header parsing/encoding. +#[derive(Debug, Clone)] +pub struct UdpHeader { + pub frag: u8, + pub addr: Address, + pub port: u16, +} + +impl UdpHeader { + pub fn encode(&self, buf: &mut BytesMut) { + buf.put_u16(0); // RSV + buf.put_u8(self.frag); + self.addr.encode(buf); + buf.put_u16(self.port); + } + + pub fn decode(buf: &mut BytesMut) -> Result> { + if buf.len() < 4 { + // RSV(2) + FRAG(1) + ATYP(1) + return Ok(None); + } + + // Peek + let mut reader = std::io::Cursor::new(&buf[..]); + reader.advance(3); // RSV + FRAG + + let atyp = reader.get_u8(); + let addr_len = match atyp { + ATYP_IPV4 => 4, + ATYP_DOMAIN => { + if !reader.has_remaining() { + return Ok(None); + } + reader.get_u8() as usize + } + ATYP_IPV6 => 16, + _ => return Err(anyhow::anyhow!("Unknown ATYP: {}", atyp)), + }; + + if reader.remaining() < addr_len + 2 { + return Ok(None); + } + + // Consume + buf.advance(2); // RSV + let frag = buf.get_u8(); + let addr = match Address::decode(buf)? { + Some(a) => a, + None => unreachable!(), + }; + let port = buf.get_u16(); + + Ok(Some(UdpHeader { frag, addr, port })) + } +} + +#[derive(Debug, Clone)] +pub enum Frame { + Data { pn: u64, payload: Bytes }, + Ping, + Pong, + Fin, + Rst, + Unknown(u8, Bytes), +} + +impl Frame { + pub fn encode(&self, buf: &mut BytesMut) { + match self { + Frame::Data { pn, payload } => { + buf.reserve(DATA_HEADER_LEN + payload.len()); + buf.put_u8(MTYP_DATA); + buf.put_u64(*pn); + buf.put_u32(payload.len() as u32); + buf.put_slice(payload); + } + Frame::Ping => buf.put_u8(MTYP_PING), + Frame::Pong => buf.put_u8(MTYP_PONG), + Frame::Fin => buf.put_u8(MTYP_FIN), + Frame::Rst => buf.put_u8(MTYP_RST), + Frame::Unknown(mtyp, cnt) => { + buf.put_u8(*mtyp); + buf.put_slice(cnt); + } + } + } +} diff --git a/leaf/src/proxy/mptp/mptp_conn/stream.rs b/leaf/src/proxy/mptp/mptp_conn/stream.rs new file mode 100644 index 0000000..f7b4b63 --- /dev/null +++ b/leaf/src/proxy/mptp/mptp_conn/stream.rs @@ -0,0 +1,551 @@ +use tracing::{error, info, warn}; + +use super::protocol::{ + Frame, DATA_HEADER_LEN, MTYP_DATA, MTYP_FIN, MTYP_PING, MTYP_PONG, MTYP_RST, +}; +use bytes::{Buf, Bytes, BytesMut}; +use std::collections::BTreeMap; +use std::io; +use std::pin::Pin; +use std::task::{Context, Poll}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::sync::mpsc; + +struct SubConnection { + stream: S, + read_buf: BytesMut, + write_buf: BytesMut, + closed: bool, // Mark if this sub-connection is dead + cid: uuid::Uuid, // Add CID for debugging +} + +impl SubConnection { + fn new(stream: S) -> Self { + Self { + stream, + read_buf: BytesMut::with_capacity(4096), + write_buf: BytesMut::with_capacity(4096), + closed: false, + cid: uuid::Uuid::nil(), // Default or placeholder + } + } + + fn new_with_cid(stream: S, cid: uuid::Uuid) -> Self { + Self { + stream, + read_buf: BytesMut::with_capacity(4096), + write_buf: BytesMut::with_capacity(4096), + closed: false, + cid, + } + } +} + +pub struct MptpStream { + subs: Vec>, + new_subs_rx: Option)>>, // Allow passing CID + read_buffer: BytesMut, + next_pn: u64, + + // Reordering logic + expected_read_pn: u64, + reorder_buffer: BTreeMap, + + closed: bool, +} + +impl MptpStream { + pub fn new(streams: Vec, cid: uuid::Uuid) -> Self { + let subs = streams + .into_iter() + .map(|s| SubConnection::new_with_cid(s, cid)) + .collect(); + Self { + subs, + new_subs_rx: None, + read_buffer: BytesMut::new(), + next_pn: 1, + expected_read_pn: 1, + reorder_buffer: BTreeMap::new(), + closed: false, + } + } + + pub fn new_with_receiver(rx: mpsc::UnboundedReceiver<(S, Option)>) -> Self { + Self { + subs: Vec::new(), + new_subs_rx: Some(rx), + read_buffer: BytesMut::new(), + next_pn: 1, + expected_read_pn: 1, + reorder_buffer: BTreeMap::new(), + closed: false, + } + } + + fn poll_new_subs(&mut self, cx: &mut Context<'_>) { + if let Some(rx) = &mut self.new_subs_rx { + loop { + match rx.poll_recv(cx) { + Poll::Ready(Some((stream, cid_opt))) => { + if let Some(cid) = cid_opt { + self.subs.push(SubConnection::new_with_cid(stream, cid)); + } else { + self.subs.push(SubConnection::new(stream)); + } + } + Poll::Ready(None) => { + // Channel closed, no more new subs + self.new_subs_rx = None; + break; + } + Poll::Pending => break, + } + } + } + } +} + +impl AsyncRead for MptpStream { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + + // Check for new sub-connections + this.poll_new_subs(cx); + + // Serve buffered data first + if !this.read_buffer.is_empty() { + let len = std::cmp::min(buf.remaining(), this.read_buffer.len()); + buf.put_slice(&this.read_buffer.split_to(len)); + return Poll::Ready(Ok(())); + } + + if this.closed { + return Poll::Ready(Ok(())); + } + + let mut any_progress = false; + let mut all_eof = !this.subs.is_empty(); // If no subs, not EOF (unless closed), but maybe pending + if this.subs.is_empty() { + all_eof = false; // Waiting for subs? + } + + // Temporary buffer for reading from socket + let mut temp_buf = [0u8; 4096]; + + // First pass: Read from all active subs + for (i, sub) in this.subs.iter_mut().enumerate() { + if sub.closed { + continue; + } + + // Read from socket + let mut read_buf = ReadBuf::new(&mut temp_buf); + match Pin::new(&mut sub.stream).poll_read(cx, &mut read_buf) { + Poll::Ready(Ok(())) => { + let filled = read_buf.filled(); + if !filled.is_empty() { + sub.read_buf.extend_from_slice(filled); + any_progress = true; + all_eof = false; + } else { + // EOF for this sub + warn!("Sub {} (CID={}) EOF, marking closed", i, sub.cid); + sub.closed = true; + // Don't return EOF yet, others might be alive + } + } + Poll::Ready(Err(e)) => { + if e.kind() == io::ErrorKind::UnexpectedEof { + warn!("Sub {} (CID={}) UnexpectedEof, marking closed", i, sub.cid); + } else { + error!( + "Sub {} (CID={}) read error: {}, marking closed", + i, sub.cid, e + ); + } + sub.closed = true; + // Don't return error, just close this sub + } + Poll::Pending => { + all_eof = false; + } + } + } + + // Cleanup closed subs? + // Removing from Vec is tricky while iterating, but we can filter later or just ignore marked closed. + // For simplicity, we just keep them but skip them. + // Ideally we should remove them to free resources, but index stability matters for logging. + // Let's just keep them marked closed. + + // Check if ALL are closed + let all_closed = this.subs.iter().all(|s| s.closed); + if all_closed && !this.subs.is_empty() { + warn!("All sub-connections closed/failed without MTYP_FIN"); + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::ConnectionAborted, + "All sub-connections failed", + ))); + } + + // Second pass: Process frames from buffer + for (i, sub) in this.subs.iter_mut().enumerate() { + if sub.read_buf.is_empty() { + continue; + } + + // Process frames + loop { + if sub.read_buf.is_empty() { + break; + } + + let mtyp = sub.read_buf[0]; + let needed = match mtyp { + MTYP_DATA => { + if sub.read_buf.len() < DATA_HEADER_LEN { + 0 + } else { + let mut slice = &sub.read_buf[1 + 8..]; // Skip MTYP+PN + let len = slice.get_u32() as usize; + DATA_HEADER_LEN + len + } + } + MTYP_FIN | MTYP_RST | MTYP_PING | MTYP_PONG => 1, + _ => { + error!("Unknown MTYP: {}", mtyp); + 1 // Consume 1 byte to maybe recover? Or Error? + } + }; + + if needed == 0 || sub.read_buf.len() < needed { + break; + } + + // Have full frame + match mtyp { + MTYP_DATA => { + // Parse manually to avoid cloning payload if possible, but BytesMut split is cheap + let pn_slice = &sub.read_buf[1..9]; + let mut pn_reader = pn_slice; + let pn = pn_reader.get_u64(); + + sub.read_buf.advance(DATA_HEADER_LEN); + let payload_len = needed - DATA_HEADER_LEN; + let payload = sub.read_buf.split_to(payload_len).freeze(); + + if pn < this.expected_read_pn { + // Duplicate or old packet, ignore + // log::trace!("Duplicate PN: {} (expected {})", pn, this.expected_read_pn); + } else if pn == this.expected_read_pn { + // Expected packet + // log::trace!("Received expected PN: {}", pn); + this.read_buffer.extend_from_slice(&payload); + this.expected_read_pn += 1; + any_progress = true; + + // Check if we can drain reorder buffer + while let Some(payload) = + this.reorder_buffer.remove(&this.expected_read_pn) + { + // log::trace!("Draining reorder buffer PN: {}", this.expected_read_pn); + this.read_buffer.extend_from_slice(&payload); + this.expected_read_pn += 1; + } + } else { + // Future packet, buffer it + // log::trace!("Buffering future PN: {} (expected {})", pn, this.expected_read_pn); + if !this.reorder_buffer.contains_key(&pn) { + this.reorder_buffer.insert(pn, payload); + } + } + } + MTYP_FIN => { + info!("Received FIN from sub {}", i); + sub.read_buf.advance(1); + this.closed = true; + // Don't return EOF yet, we might have data in read_buffer + // But we should stop processing from this sub? + // Actually, FIN should be the last thing. + break; + } + MTYP_RST => { + warn!("Received RST from sub {}", i); + sub.read_buf.advance(1); + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "Peer sent RST", + ))); + } + _ => { + sub.read_buf.advance(1); + } + } + } + } + + if !this.read_buffer.is_empty() { + let len = std::cmp::min(buf.remaining(), this.read_buffer.len()); + buf.put_slice(&this.read_buffer.split_to(len)); + return Poll::Ready(Ok(())); + } + + if all_eof && !this.subs.is_empty() { + info!("All sub-connections EOF"); + return Poll::Ready(Ok(())); + } + + if any_progress { + cx.waker().wake_by_ref(); + } + + Poll::Pending + } +} + +impl AsyncWrite for MptpStream { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let this = self.get_mut(); + + // Check for new sub-connections + this.poll_new_subs(cx); + + // If no subs, we can't write yet? Or buffer internally? + // For now, if no subs, return Pending until we get one. + if this.subs.is_empty() { + return Poll::Pending; + } + + // Check backpressure (if any buffer is too full) + let mut needs_flush = false; + let mut active_subs = 0; + + for sub in &this.subs { + if !sub.closed { + active_subs += 1; + if sub.write_buf.len() > 64 * 1024 { + needs_flush = true; + // Don't break, check all? Or break is fine. + break; + } + } + } + + if active_subs == 0 && !this.subs.is_empty() { + // All closed + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::ConnectionAborted, + "All sub-connections failed (write)", + ))); + } + + if needs_flush { + // Try to flush + let _ = Pin::new(&mut *this).poll_flush(cx); + } + + // If still full, return pending + // But only check active ones + for sub in &this.subs { + if !sub.closed && sub.write_buf.len() > 64 * 1024 { + return Poll::Pending; + } + } + + let pn = this.next_pn; + this.next_pn += 1; + + let frame = Frame::Data { + pn, + payload: Bytes::copy_from_slice(buf), + }; + + let mut encoded = BytesMut::new(); + frame.encode(&mut encoded); + let encoded_bytes = encoded.freeze(); + + // Broadcast to all subs + for sub in &mut this.subs { + if !sub.closed { + sub.write_buf.extend_from_slice(&encoded_bytes); + } + } + + // Try flush immediately + let _ = Pin::new(&mut *this).poll_flush(cx); + + Poll::Ready(Ok(buf.len())) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + + // Check for new sub-connections + this.poll_new_subs(cx); + + let mut all_flushed = true; + + for (i, sub) in this.subs.iter_mut().enumerate() { + if sub.closed { + continue; + } + while !sub.write_buf.is_empty() { + match Pin::new(&mut sub.stream).poll_write(cx, &sub.write_buf) { + Poll::Ready(Ok(n)) => { + sub.write_buf.advance(n); + } + Poll::Ready(Err(e)) => { + error!( + "Sub {} (CID={}) write error: {}, marking closed", + i, sub.cid, e + ); + sub.closed = true; + // Don't return error yet + break; + } + Poll::Pending => { + all_flushed = false; + break; + } + } + } + } + + if all_flushed { + Poll::Ready(Ok(())) + } else { + Poll::Pending + } + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + + // Check for new sub-connections + this.poll_new_subs(cx); + + // Send FIN frame + let frame = Frame::Fin; + let mut encoded = BytesMut::new(); + frame.encode(&mut encoded); + let encoded_bytes = encoded.freeze(); + + // Broadcast FIN to all subs + for sub in &mut this.subs { + // We just append to write buf. poll_flush will send it. + // But shutdown expects to close *now*. + // However, standard AsyncWrite::poll_shutdown implies "flush pending writes and close". + sub.write_buf.extend_from_slice(&encoded_bytes); + } + + // Flush all buffers + let _ = Pin::new(&mut *this).poll_flush(cx); + + // Now shutdown underlying streams + let mut all_done = true; + for sub in &mut this.subs { + if Pin::new(&mut sub.stream).poll_shutdown(cx).is_pending() { + all_done = false; + } + } + + if all_done { + Poll::Ready(Ok(())) + } else { + Poll::Pending + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + #[tokio::test] + async fn test_single_stream_write_read() { + use super::super::protocol::MTYP_DATA; + let (client, mut server) = tokio::io::duplex(1024); + let mut mptp = MptpStream::new(vec![client]); + + // Write to mptp + mptp.write_all(b"hello").await.unwrap(); + + // Read from server (raw frame) + let mut buf = [0u8; 1024]; + let n = server.read(&mut buf).await.unwrap(); + // Expect: MTYP(1) + PN(8) + LEN(4) + PAYLOAD(5) + assert_eq!(n, 1 + 8 + 4 + 5); + assert_eq!(buf[0], MTYP_DATA); + // PN should be 1 + assert_eq!(&buf[1..9], &1u64.to_be_bytes()); + // LEN should be 5 + assert_eq!(&buf[9..13], &5u32.to_be_bytes()); + // Payload + assert_eq!(&buf[13..18], b"hello"); + } + + #[tokio::test] + async fn test_deduplication() { + let (c1, mut s1) = tokio::io::duplex(1024); + let (c2, mut s2) = tokio::io::duplex(1024); + let mut mptp = MptpStream::new(vec![c1, c2]); + + // Construct a frame + let frame = Frame::Data { + pn: 1, + payload: Bytes::from_static(b"data"), + }; + let mut encoded = BytesMut::new(); + frame.encode(&mut encoded); + let bytes = encoded.freeze(); + + // Send to both underlying streams + s1.write_all(&bytes).await.unwrap(); + s2.write_all(&bytes).await.unwrap(); + + // Read from mptp + let mut buf = [0u8; 10]; + let n = mptp.read(&mut buf).await.unwrap(); + assert_eq!(n, 4); + assert_eq!(&buf[..4], b"data"); + + // Try read again - should be empty/pending (no new data) + // Write another packet with DIFFERENT PN to s1 + let frame2 = Frame::Data { + pn: 2, + payload: Bytes::from_static(b"more"), + }; + let mut encoded2 = BytesMut::new(); + frame2.encode(&mut encoded2); + s1.write_all(&encoded2).await.unwrap(); + + let n = mptp.read(&mut buf).await.unwrap(); + assert_eq!(n, 4); + assert_eq!(&buf[..4], b"more"); + } + + #[tokio::test] + async fn test_dynamic_add() { + let (c1, mut s1) = tokio::io::duplex(1024); + let (tx, rx) = mpsc::unbounded_channel(); + let mut mptp = MptpStream::new_with_receiver(rx); + tx.send((c1, None)).unwrap(); + + // Write to mptp (should go to s1) + mptp.write_all(b"hello").await.unwrap(); + + let mut buf = [0u8; 1024]; + let n = s1.read(&mut buf).await.unwrap(); + assert!(n > 0); + } +} diff --git a/leaf/src/proxy/mptp/outbound/mod.rs b/leaf/src/proxy/mptp/outbound/mod.rs new file mode 100644 index 0000000..baf29e0 --- /dev/null +++ b/leaf/src/proxy/mptp/outbound/mod.rs @@ -0,0 +1 @@ +pub mod stream; diff --git a/leaf/src/proxy/mptp/outbound/stream.rs b/leaf/src/proxy/mptp/outbound/stream.rs new file mode 100644 index 0000000..2faa684 --- /dev/null +++ b/leaf/src/proxy/mptp/outbound/stream.rs @@ -0,0 +1,141 @@ +use std::io; + +use crate::proxy::mptp::mptp_conn::protocol::{ + Address, HandshakeRequest, CMD_CONNECT, CMD_UDP, VER, +}; +use crate::proxy::mptp::mptp_conn::{MptpDatagram, MptpStream}; +use async_trait::async_trait; +use bytes::BytesMut; +use tokio::io::AsyncWriteExt; +use uuid::Uuid; + +use crate::{ + app::SyncDnsClient, + proxy::{ + connect_stream_outbound, AnyOutboundDatagram, AnyOutboundHandler, AnyOutboundTransport, + AnyStream, DatagramTransportType, OutboundConnect, OutboundDatagramHandler, + OutboundStreamHandler, + }, + session::{Session, SocksAddr}, +}; + +pub struct Handler { + pub actors: Vec, + pub address: String, + pub port: u16, + pub dns_client: SyncDnsClient, +} + +impl Handler { + async fn establish_mptp_stream( + &self, + sess: &Session, + cmd: u8, + ) -> io::Result> { + let mut sub_streams = Vec::new(); + + // Clone session and set destination to MPTP server + let mut server_sess = sess.clone(); + server_sess.destination = SocksAddr::try_from((self.address.clone(), self.port)) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + + let cid = Uuid::new_v4(); + let target_addr = match &sess.destination { + SocksAddr::Ip(addr) => match addr { + std::net::SocketAddr::V4(v4) => Address::Ipv4(*v4.ip()), + std::net::SocketAddr::V6(v6) => Address::Ipv6(*v6.ip()), + }, + SocksAddr::Domain(domain, _) => Address::Domain(domain.clone()), + }; + let target_port = sess.destination.port(); + + // 1. Establish sub-connections + for (i, actor) in self.actors.iter().enumerate() { + if let Ok(stream_handler) = actor.stream() { + // Try to connect if the actor requires a connection + let stream_opt: Option = + connect_stream_outbound(&server_sess, self.dns_client.clone(), actor) + .await + .map_err(|e| { + io::Error::new(io::ErrorKind::Other, format!("connect failed: {}", e)) + })?; + + match stream_handler.handle(&server_sess, None, stream_opt).await { + Ok(mut stream) => { + // 2. Perform Handshake on each sub-connection + let req = HandshakeRequest { + ver: VER, + cid, + cmd, + dst_addr: target_addr.clone(), + dst_port: target_port, + }; + + let mut buf = BytesMut::new(); + req.encode(&mut buf); + + if let Err(e) = stream.write_all(&buf).await { + tracing::warn!("Failed to send handshake for sub {}: {}", i, e); + continue; + } + + sub_streams.push(stream); + } + Err(e) => { + tracing::warn!("Failed to connect sub {}: {}", i, e); + } + } + } + } + + if sub_streams.is_empty() { + return Err(io::Error::new( + io::ErrorKind::Other, + "No available sub-connections", + )); + } + + // 3. Create MptpStream + Ok(MptpStream::new(sub_streams, cid)) + } +} + +#[async_trait] +impl OutboundStreamHandler for Handler { + fn connect_addr(&self) -> OutboundConnect { + OutboundConnect::Unknown + } + + async fn handle<'a>( + &'a self, + sess: &'a Session, + _lhs: Option<&mut AnyStream>, + _stream: Option, + ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); + let mptp_stream = self.establish_mptp_stream(sess, CMD_CONNECT).await?; + Ok(Box::new(mptp_stream)) + } +} + +#[async_trait] +impl OutboundDatagramHandler for Handler { + fn connect_addr(&self) -> OutboundConnect { + OutboundConnect::Unknown + } + + fn transport_type(&self) -> DatagramTransportType { + DatagramTransportType::Reliable + } + + async fn handle<'a>( + &'a self, + sess: &'a Session, + _transport: Option, + ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); + let mptp_stream = self.establish_mptp_stream(sess, CMD_UDP).await?; + let mptp_datagram = MptpDatagram::new(mptp_stream); + Ok(Box::new(mptp_datagram)) + } +} diff --git a/leaf/src/proxy/nf/inbound/datagram.rs b/leaf/src/proxy/nf/inbound/datagram.rs index 8e59d59..a92eff4 100644 --- a/leaf/src/proxy/nf/inbound/datagram.rs +++ b/leaf/src/proxy/nf/inbound/datagram.rs @@ -22,6 +22,7 @@ pub struct Handler { #[async_trait] impl InboundDatagramHandler for Handler { async fn handle<'a>(&'a self, socket: AnyInboundDatagram) -> io::Result { + tracing::trace!("handling inbound datagram"); Ok(InboundTransport::Datagram( Box::new(Datagram { socket, diff --git a/leaf/src/proxy/nf/inbound/stream.rs b/leaf/src/proxy/nf/inbound/stream.rs index 0b8d927..a6537e4 100644 --- a/leaf/src/proxy/nf/inbound/stream.rs +++ b/leaf/src/proxy/nf/inbound/stream.rs @@ -16,6 +16,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); let (remote_addr, process_name) = if let Some(info) = super::TCP_INFO.lock().unwrap().remove(&sess.source.port()) { (info.remote_addr, info.process_name) diff --git a/leaf/src/proxy/obfs/http.rs b/leaf/src/proxy/obfs/http.rs index b183cee..ef32f0d 100644 --- a/leaf/src/proxy/obfs/http.rs +++ b/leaf/src/proxy/obfs/http.rs @@ -68,6 +68,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", _sess); let stream = stream.ok_or_else(|| io::Error::other("invalid input"))?; Ok(Box::new(Stream::new(self.req_line.clone(), stream))) diff --git a/leaf/src/proxy/obfs/tls.rs b/leaf/src/proxy/obfs/tls.rs index 9f52982..5994785 100644 --- a/leaf/src/proxy/obfs/tls.rs +++ b/leaf/src/proxy/obfs/tls.rs @@ -67,6 +67,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", _sess); let stream = stream.ok_or_else(|| io::Error::other("invalid input"))?; Ok(Box::new(Stream::new(self.host.clone(), stream))) diff --git a/leaf/src/proxy/outbound.rs b/leaf/src/proxy/outbound.rs index 51367b2..d9bd464 100644 --- a/leaf/src/proxy/outbound.rs +++ b/leaf/src/proxy/outbound.rs @@ -7,7 +7,6 @@ use super::*; /// handler. pub struct Handler { tag: String, - color: colored::Color, stream_handler: Option, datagram_handler: Option, } @@ -15,13 +14,11 @@ pub struct Handler { impl Handler { pub(self) fn new( tag: String, - color: colored::Color, stream_handler: Option, datagram_handler: Option, ) -> Arc { Arc::new(Handler { tag, - color, stream_handler, datagram_handler, }) @@ -50,15 +47,8 @@ impl Tag for Handler { } } -impl Color for Handler { - fn color(&self) -> &colored::Color { - &self.color - } -} - pub struct HandlerBuilder { tag: String, - color: colored::Color, stream_handler: Option, datagram_handler: Option, } @@ -67,7 +57,6 @@ impl HandlerBuilder { pub fn new() -> Self { Self { tag: "".to_string(), - color: colored::Color::Magenta, stream_handler: None, datagram_handler: None, } @@ -78,11 +67,6 @@ impl HandlerBuilder { self } - pub fn color(mut self, v: colored::Color) -> Self { - self.color = v; - self - } - pub fn stream_handler(mut self, v: AnyOutboundStreamHandler) -> Self { self.stream_handler.replace(v); self @@ -94,12 +78,7 @@ impl HandlerBuilder { } pub fn build(self) -> AnyOutboundHandler { - Handler::new( - self.tag, - self.color, - self.stream_handler, - self.datagram_handler, - ) + Handler::new(self.tag, self.stream_handler, self.datagram_handler) } } diff --git a/leaf/src/proxy/quic/inbound/datagram.rs b/leaf/src/proxy/quic/inbound/datagram.rs index b6461bd..2b0baea 100644 --- a/leaf/src/proxy/quic/inbound/datagram.rs +++ b/leaf/src/proxy/quic/inbound/datagram.rs @@ -140,6 +140,7 @@ async fn handle_conn( #[async_trait] impl InboundDatagramHandler for Handler { async fn handle<'a>(&'a self, socket: AnyInboundDatagram) -> io::Result { + tracing::trace!("handling inbound datagram"); let (stream_tx, stream_rx) = channel(*crate::option::QUIC_ACCEPT_CHANNEL_SIZE); let endpoint = quinn::Endpoint::new( quinn::EndpointConfig::default(), diff --git a/leaf/src/proxy/quic/outbound/stream.rs b/leaf/src/proxy/quic/outbound/stream.rs index 9e2c389..8108c63 100644 --- a/leaf/src/proxy/quic/outbound/stream.rs +++ b/leaf/src/proxy/quic/outbound/stream.rs @@ -249,6 +249,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, _stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", _sess); Ok(Box::new(self.new_stream().await?)) } } diff --git a/leaf/src/proxy/reality/outbound/stream.rs b/leaf/src/proxy/reality/outbound/stream.rs index c6f8b57..8b5c9ad 100644 --- a/leaf/src/proxy/reality/outbound/stream.rs +++ b/leaf/src/proxy/reality/outbound/stream.rs @@ -28,6 +28,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let stream = stream.ok_or_else(|| io::Error::other("invalid input"))?; let server_name = ServerName::try_from(self.server_name.as_str()) diff --git a/leaf/src/proxy/redirect/datagram.rs b/leaf/src/proxy/redirect/datagram.rs index d9865e6..189a42a 100644 --- a/leaf/src/proxy/redirect/datagram.rs +++ b/leaf/src/proxy/redirect/datagram.rs @@ -26,6 +26,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let dgram = if let Some(OutboundTransport::Datagram(dgram)) = transport { dgram } else { diff --git a/leaf/src/proxy/redirect/stream.rs b/leaf/src/proxy/redirect/stream.rs index 0b47866..d223e54 100644 --- a/leaf/src/proxy/redirect/stream.rs +++ b/leaf/src/proxy/redirect/stream.rs @@ -22,6 +22,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", _sess); stream.ok_or_else(|| io::Error::other("invalid input")) } } diff --git a/leaf/src/proxy/select/datagram.rs b/leaf/src/proxy/select/datagram.rs index be01073..1a3af87 100644 --- a/leaf/src/proxy/select/datagram.rs +++ b/leaf/src/proxy/select/datagram.rs @@ -37,6 +37,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let a = &self.actors[self.selected.load(Ordering::Relaxed)]; tracing::debug!("select handles to [{}]", a.tag()); a.datagram()?.handle(sess, transport).await diff --git a/leaf/src/proxy/select/stream.rs b/leaf/src/proxy/select/stream.rs index 26cd73c..19a5a8a 100644 --- a/leaf/src/proxy/select/stream.rs +++ b/leaf/src/proxy/select/stream.rs @@ -30,6 +30,7 @@ impl OutboundStreamHandler for Handler { lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let a = &self.actors[self.selected.load(Ordering::Relaxed)]; tracing::debug!("select handles to [{}]", a.tag()); a.stream()?.handle(sess, lhs, stream).await diff --git a/leaf/src/proxy/shadowsocks/inbound/datagram.rs b/leaf/src/proxy/shadowsocks/inbound/datagram.rs index 1fb2f96..f8d1c1d 100644 --- a/leaf/src/proxy/shadowsocks/inbound/datagram.rs +++ b/leaf/src/proxy/shadowsocks/inbound/datagram.rs @@ -22,6 +22,7 @@ pub struct Handler { #[async_trait] impl InboundDatagramHandler for Handler { async fn handle<'a>(&'a self, socket: AnyInboundDatagram) -> io::Result { + tracing::trace!("handling inbound datagram"); let dgram = ShadowedDatagram::new(&self.cipher, &self.password)?; Ok(InboundTransport::Datagram( Box::new(Datagram { dgram, socket }), diff --git a/leaf/src/proxy/shadowsocks/inbound/stream.rs b/leaf/src/proxy/shadowsocks/inbound/stream.rs index fdd1590..4e7de41 100644 --- a/leaf/src/proxy/shadowsocks/inbound/stream.rs +++ b/leaf/src/proxy/shadowsocks/inbound/stream.rs @@ -19,6 +19,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); let mut stream = ShadowedStream::new(stream, &self.cipher, &self.password, None)?; let destination = SocksAddr::read_from(&mut stream, SocksAddrWireType::PortLast).await?; sess.destination = destination; diff --git a/leaf/src/proxy/shadowsocks/outbound/datagram.rs b/leaf/src/proxy/shadowsocks/outbound/datagram.rs index 1a1bb9b..d54db60 100644 --- a/leaf/src/proxy/shadowsocks/outbound/datagram.rs +++ b/leaf/src/proxy/shadowsocks/outbound/datagram.rs @@ -29,6 +29,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let server_addr = SocksAddr::try_from((&self.address, self.port))?; let socket = if let Some(OutboundTransport::Datagram(socket)) = transport { diff --git a/leaf/src/proxy/shadowsocks/outbound/stream.rs b/leaf/src/proxy/shadowsocks/outbound/stream.rs index f93b6b5..aed7b6c 100644 --- a/leaf/src/proxy/shadowsocks/outbound/stream.rs +++ b/leaf/src/proxy/shadowsocks/outbound/stream.rs @@ -52,6 +52,7 @@ impl OutboundStreamHandler for Handler { lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let stream = stream.ok_or_else(|| io::Error::other("invalid input"))?; let mut stream = ShadowedStream::new( stream, diff --git a/leaf/src/proxy/socks/inbound/datagram.rs b/leaf/src/proxy/socks/inbound/datagram.rs index 755d7fa..bc426b8 100644 --- a/leaf/src/proxy/socks/inbound/datagram.rs +++ b/leaf/src/proxy/socks/inbound/datagram.rs @@ -16,6 +16,7 @@ pub struct Handler; #[async_trait] impl InboundDatagramHandler for Handler { async fn handle<'a>(&'a self, socket: AnyInboundDatagram) -> io::Result { + tracing::trace!("handling inbound datagram"); Ok(InboundTransport::Datagram( Box::new(Datagram { socket }), None, diff --git a/leaf/src/proxy/socks/inbound/stream.rs b/leaf/src/proxy/socks/inbound/stream.rs index 8ca07a8..2432d92 100644 --- a/leaf/src/proxy/socks/inbound/stream.rs +++ b/leaf/src/proxy/socks/inbound/stream.rs @@ -228,6 +228,7 @@ impl InboundStreamHandler for Handler { sess: Session, mut stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); let mut buf = [0u8; 1]; stream.read_exact(&mut buf).await?; match buf[0] { diff --git a/leaf/src/proxy/socks/outbound/datagram.rs b/leaf/src/proxy/socks/outbound/datagram.rs index 68ff6d4..b6e1efe 100644 --- a/leaf/src/proxy/socks/outbound/datagram.rs +++ b/leaf/src/proxy/socks/outbound/datagram.rs @@ -36,6 +36,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, _transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); // TODO support chaining, this requires implementing our own socks5 client let stream = self .new_tcp_stream(self.dns_client.clone(), &self.address, &self.port) diff --git a/leaf/src/proxy/socks/outbound/stream.rs b/leaf/src/proxy/socks/outbound/stream.rs index 33bacb0..bd5ce0e 100644 --- a/leaf/src/proxy/socks/outbound/stream.rs +++ b/leaf/src/proxy/socks/outbound/stream.rs @@ -25,6 +25,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let mut stream = stream.ok_or_else(|| io::Error::other("invalid input"))?; let auth = match (&self.username, &self.password) { (auth_username, _) if auth_username.is_empty() => None, diff --git a/leaf/src/proxy/static/datagram.rs b/leaf/src/proxy/static/datagram.rs index 9321310..08ddff7 100644 --- a/leaf/src/proxy/static/datagram.rs +++ b/leaf/src/proxy/static/datagram.rs @@ -66,6 +66,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); match self.method { Method::Random => { let current = self.next.load(Ordering::Relaxed); diff --git a/leaf/src/proxy/static/stream.rs b/leaf/src/proxy/static/stream.rs index 992c222..701e3a9 100644 --- a/leaf/src/proxy/static/stream.rs +++ b/leaf/src/proxy/static/stream.rs @@ -60,6 +60,7 @@ impl OutboundStreamHandler for Handler { lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); match self.method { Method::Random => { let current = self.next.load(Ordering::Relaxed); diff --git a/leaf/src/proxy/tls/inbound/stream.rs b/leaf/src/proxy/tls/inbound/stream.rs index bcbcfa3..1f200a3 100644 --- a/leaf/src/proxy/tls/inbound/stream.rs +++ b/leaf/src/proxy/tls/inbound/stream.rs @@ -49,8 +49,11 @@ impl Handler { pub fn new(certificate: String, certificate_key: String) -> Result { #[cfg(feature = "rustls-tls")] { - let certs = load_certs(Path::new(&certificate))?; - let mut keys = load_keys(Path::new(&certificate_key))?; + let certs = load_certs(Path::new(&certificate)).map_err(|e| { + anyhow::anyhow!("load certificates from {} failed: {}", certificate, e) + })?; + let mut keys = load_keys(Path::new(&certificate_key)) + .map_err(|e| anyhow::anyhow!("load keys from {} failed: {}", certificate_key, e))?; #[cfg(feature = "rustls-tls-aws-lc")] let provider = rustls::crypto::aws_lc_rs::default_provider().into(); #[cfg(not(feature = "rustls-tls-aws-lc"))] @@ -79,6 +82,7 @@ impl InboundStreamHandler for Handler { sess: Session, stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); #[cfg(feature = "rustls-tls")] { Ok(InboundTransport::Stream( diff --git a/leaf/src/proxy/tls/outbound/stream.rs b/leaf/src/proxy/tls/outbound/stream.rs index c11d3e2..266877c 100644 --- a/leaf/src/proxy/tls/outbound/stream.rs +++ b/leaf/src/proxy/tls/outbound/stream.rs @@ -121,7 +121,9 @@ impl Handler { roots.add(cert?)?; } } else { - let mut pem = BufReader::new(File::open(cert)?); + let mut pem = BufReader::new(File::open(&cert).map_err(|e| { + anyhow::anyhow!("load certificates from {} failed: {}", cert, e) + })?); for cert in rustls_pemfile::certs(&mut pem) { roots.add(cert?)?; } @@ -189,6 +191,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); // TODO optimize, dont need copy let name = if !&self.server_name.is_empty() { self.server_name.clone() diff --git a/leaf/src/proxy/trojan/inbound/stream.rs b/leaf/src/proxy/trojan/inbound/stream.rs index 15a8d34..5352285 100644 --- a/leaf/src/proxy/trojan/inbound/stream.rs +++ b/leaf/src/proxy/trojan/inbound/stream.rs @@ -136,6 +136,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, mut stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); let mut buf = [0; 56]; // read key stream.read_exact(&mut buf[..56]).await?; diff --git a/leaf/src/proxy/trojan/outbound/datagram.rs b/leaf/src/proxy/trojan/outbound/datagram.rs index d5b6f6a..1199566 100644 --- a/leaf/src/proxy/trojan/outbound/datagram.rs +++ b/leaf/src/proxy/trojan/outbound/datagram.rs @@ -30,6 +30,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let stream = if let Some(OutboundTransport::Stream(stream)) = transport { stream } else { diff --git a/leaf/src/proxy/trojan/outbound/stream.rs b/leaf/src/proxy/trojan/outbound/stream.rs index 030169c..c35498c 100644 --- a/leaf/src/proxy/trojan/outbound/stream.rs +++ b/leaf/src/proxy/trojan/outbound/stream.rs @@ -25,6 +25,7 @@ impl OutboundStreamHandler for Handler { lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let mut stream = stream.ok_or_else(|| io::Error::other("invalid input"))?; let mut buf = BytesMut::new(); let password = Sha224::digest(self.password.as_bytes()); diff --git a/leaf/src/proxy/tryall/datagram.rs b/leaf/src/proxy/tryall/datagram.rs index bea1d16..de9bbf0 100644 --- a/leaf/src/proxy/tryall/datagram.rs +++ b/leaf/src/proxy/tryall/datagram.rs @@ -32,6 +32,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, _transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let mut tasks = Vec::new(); for (i, a) in self.actors.iter().enumerate() { let t = async move { diff --git a/leaf/src/proxy/tryall/stream.rs b/leaf/src/proxy/tryall/stream.rs index 1164c3d..131176e 100644 --- a/leaf/src/proxy/tryall/stream.rs +++ b/leaf/src/proxy/tryall/stream.rs @@ -29,6 +29,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, _stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let mut tasks = Vec::new(); for (i, a) in self.actors.iter().enumerate() { let t = async move { diff --git a/leaf/src/proxy/vless/outbound/datagram.rs b/leaf/src/proxy/vless/outbound/datagram.rs index 02e8921..78b1e25 100644 --- a/leaf/src/proxy/vless/outbound/datagram.rs +++ b/leaf/src/proxy/vless/outbound/datagram.rs @@ -29,6 +29,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let u = Uuid::parse_str(&self.uuid) .map_err(|e| io::Error::other(format!("parse uuid failed: {}", e)))?; let uuid_bytes = *u.as_bytes(); diff --git a/leaf/src/proxy/vless/outbound/stream.rs b/leaf/src/proxy/vless/outbound/stream.rs index 9b33b79..2711930 100644 --- a/leaf/src/proxy/vless/outbound/stream.rs +++ b/leaf/src/proxy/vless/outbound/stream.rs @@ -25,6 +25,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let u = Uuid::parse_str(&self.uuid) .map_err(|e| io::Error::other(format!("parse uuid failed: {}", e)))?; let uuid_bytes = *u.as_bytes(); diff --git a/leaf/src/proxy/vmess/outbound/datagram.rs b/leaf/src/proxy/vmess/outbound/datagram.rs index 671ac28..db557b6 100644 --- a/leaf/src/proxy/vmess/outbound/datagram.rs +++ b/leaf/src/proxy/vmess/outbound/datagram.rs @@ -34,6 +34,7 @@ impl OutboundDatagramHandler for Handler { sess: &'a Session, transport: Option, ) -> io::Result { + tracing::trace!("handling outbound datagram session: {:?}", sess); let uuid = Uuid::parse_str(&self.uuid) .map_err(|e| io::Error::other(format!("parse uuid failed: {}", e)))?; let mut request_header = RequestHeader { diff --git a/leaf/src/proxy/vmess/outbound/stream.rs b/leaf/src/proxy/vmess/outbound/stream.rs index 708fc2a..35e5572 100644 --- a/leaf/src/proxy/vmess/outbound/stream.rs +++ b/leaf/src/proxy/vmess/outbound/stream.rs @@ -30,6 +30,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); let uuid = Uuid::parse_str(&self.uuid) .map_err(|e| io::Error::other(format!("parse uuid failed: {}", e)))?; let mut request_header = RequestHeader { diff --git a/leaf/src/proxy/ws/inbound/stream.rs b/leaf/src/proxy/ws/inbound/stream.rs index a537120..f98ae25 100644 --- a/leaf/src/proxy/ws/inbound/stream.rs +++ b/leaf/src/proxy/ws/inbound/stream.rs @@ -64,6 +64,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, stream: AnyStream, ) -> std::io::Result { + tracing::trace!("handling inbound stream session: {:?}", sess); let s = accept_hdr_async(stream, SimpleCallback::new(&mut sess, &self.path)) .map_err(|e| io::Error::other(format!("accept ws failed: {}", e))) .await?; diff --git a/leaf/src/proxy/ws/outbound/stream.rs b/leaf/src/proxy/ws/outbound/stream.rs index 1a0f274..4e627c8 100644 --- a/leaf/src/proxy/ws/outbound/stream.rs +++ b/leaf/src/proxy/ws/outbound/stream.rs @@ -54,6 +54,7 @@ impl OutboundStreamHandler for Handler { _lhs: Option<&mut AnyStream>, stream: Option, ) -> io::Result { + tracing::trace!("handling outbound stream session: {:?}", sess); if let Some(stream) = stream { let host = if let Some(host) = self.headers.get("Host") { host.to_owned() diff --git a/leaf/src/session.rs b/leaf/src/session.rs index 69172ae..dfa952b 100644 --- a/leaf/src/session.rs +++ b/leaf/src/session.rs @@ -65,6 +65,7 @@ impl std::fmt::Display for DatagramSource { } } +#[derive(Debug)] pub struct Session { /// Unique identifier for the session. pub trace_id: String,