From a2dadff60dc634a4dd863e13ae755af94e06985c Mon Sep 17 00:00:00 2001 From: eric Date: Wed, 7 Apr 2021 18:49:48 +0800 Subject: [PATCH] outbound/select: new outbound --- leaf-bin/src/main.rs | 2 +- leaf-ffi/src/lib.rs | 2 +- leaf/Cargo.toml | 9 + leaf/src/app/api/api_server.rs | 80 +++++ leaf/src/app/api/mod.rs | 1 + leaf/src/app/dispatcher.rs | 13 +- leaf/src/app/mod.rs | 3 + leaf/src/app/outbound/manager.rs | 59 +++- leaf/src/app/outbound/mod.rs | 8 + leaf/src/app/outbound/selector.rs | 38 +++ leaf/src/config/conf/config.rs | 11 + leaf/src/config/internal/config.proto | 4 + leaf/src/config/internal/config.rs | 417 +++++--------------------- leaf/src/config/json/config.rs | 21 +- leaf/src/proxy/mod.rs | 2 + leaf/src/proxy/select/mod.rs | 7 + leaf/src/proxy/select/tcp.rs | 39 +++ leaf/src/proxy/select/udp.rs | 46 +++ leaf/src/util.rs | 17 +- 19 files changed, 417 insertions(+), 362 deletions(-) create mode 100644 leaf/src/app/api/api_server.rs create mode 100644 leaf/src/app/api/mod.rs create mode 100644 leaf/src/app/outbound/selector.rs create mode 100644 leaf/src/proxy/select/mod.rs create mode 100644 leaf/src/proxy/select/tcp.rs create mode 100644 leaf/src/proxy/select/udp.rs diff --git a/leaf-bin/src/main.rs b/leaf-bin/src/main.rs index 0fae076..cbd8415 100644 --- a/leaf-bin/src/main.rs +++ b/leaf-bin/src/main.rs @@ -112,7 +112,7 @@ fn main() { exit(1); } - let runners = match leaf::util::prepare(config) { + let runners = match leaf::util::prepare(&rt, config) { Ok(v) => v, Err(e) => { println!("prepare failed: {}", e); diff --git a/leaf-ffi/src/lib.rs b/leaf-ffi/src/lib.rs index ba4dd50..276dc80 100644 --- a/leaf-ffi/src/lib.rs +++ b/leaf-ffi/src/lib.rs @@ -11,7 +11,7 @@ pub extern "C" fn run_leaf(config_path: *const c_char) { .map_err(Into::into) .and_then(leaf::config::from_file) { - let runners = match leaf::util::prepare(config) { + let runners = match leaf::util::prepare(&rt, config) { Ok(v) => v, Err(e) => { println!("prepare failed: {}", e); diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index cceae9b..bc81c72 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -22,6 +22,7 @@ default-ring = [ # quinn supports only rustls as tls backend for now "inbound-quic", "outbound-quic", + "api", ] default-openssl = [ @@ -29,6 +30,7 @@ default-openssl = [ "all-endpoints", "openssl-aead", "openssl-tls", + "api", ] # Grouping all features @@ -65,6 +67,7 @@ all-endpoints = [ "outbound-tryall", "outbound-chain", "outbound-retry", + "outbound-select", ] # Ring-related @@ -97,6 +100,7 @@ outbound-chain = [] outbound-retry = [] outbound-amux= ["tokio-util"] outbound-quic = ["quinn", "rustls", "webpki-roots"] +outbound-select = [] # Inbounds inbound-trojan = ["sha2", "hex"] @@ -109,6 +113,8 @@ inbound-amux = ["tokio-util"] inbound-quic = ["quinn", "rustls", "webpki-roots"] inbound-chain = [] +api = ["warp"] + [dependencies] # Common tokio = { version = "1", features = ["macros", "sync", "io-util", "net", "time", "rt"] } @@ -209,6 +215,9 @@ tokio-util = { version = "0.6", default-features = false, features = ["io"], opt quinn = { version = "0.7", default-features = false, features = ["tls-rustls"], optional = true } rustls = { version = "0.19", optional = true } +# API +warp = { version = "0.3", optional = true } + # TUN [target.'cfg(any(target_os = "ios", target_os = "android", target_os = "macos", target_os = "linux"))'.dependencies] tun = { git = "https://github.com/eycorsican/rust-tun.git", branch = "upgrade", features = ["async"], optional = true } diff --git a/leaf/src/app/api/api_server.rs b/leaf/src/app/api/api_server.rs new file mode 100644 index 0000000..425bf64 --- /dev/null +++ b/leaf/src/app/api/api_server.rs @@ -0,0 +1,80 @@ +use std::convert::Infallible; +use std::net::SocketAddr; +use std::sync::Arc; + +use crate::app::outbound::manager::OutboundManager; + +pub struct ApiServer { + listen_addr: SocketAddr, + outbound_manager: Arc, +} + +mod models { + use serde_derive::Deserialize; + + #[derive(Debug, Deserialize)] + pub struct SelectOptions { + pub outbound: Option, + pub select: Option, + } +} + +mod handlers { + use super::*; + use warp::http::StatusCode; + + pub async fn select_update( + opts: models::SelectOptions, + obm: Arc, + ) -> Result { + if let models::SelectOptions { + outbound: Some(outbound), + select: Some(select), + } = opts + { + if let Some(selector) = obm.get_selector(&outbound) { + if selector.write().await.set_selected(&select).is_ok() { + return Ok(StatusCode::OK); + } + } + } + Ok(StatusCode::ACCEPTED) + } +} + +mod filters { + use super::*; + use warp::Filter; + + fn with_outbound_manager( + obm: Arc, + ) -> impl Filter,), Error = Infallible> + Clone { + warp::any().map(move || obm.clone()) + } + + // PUT /api/v1/app/outbound/select?outbound=Proxy&select=p3 + pub fn select_update( + obm: Arc, + ) -> impl Filter + Clone { + warp::path!("api" / "v1" / "app" / "outbound" / "select") + .and(warp::put()) + .and(warp::query::()) + .and(with_outbound_manager(obm)) + .and_then(handlers::select_update) + } +} + +impl ApiServer { + pub fn new(outbound_manager: Arc) -> Self { + let listen_addr = "127.0.0.1:9991".parse().unwrap(); + Self { + listen_addr, + outbound_manager, + } + } + + pub fn serve(&self, rt: &tokio::runtime::Runtime) -> crate::Runner { + let routes = filters::select_update(self.outbound_manager.clone()); + Box::pin(rt.block_on(async { warp::serve(routes).bind(self.listen_addr) })) + } +} diff --git a/leaf/src/app/api/mod.rs b/leaf/src/app/api/mod.rs new file mode 100644 index 0000000..c086767 --- /dev/null +++ b/leaf/src/app/api/mod.rs @@ -0,0 +1 @@ +pub mod api_server; diff --git a/leaf/src/app/dispatcher.rs b/leaf/src/app/dispatcher.rs index 77b8916..adcb737 100644 --- a/leaf/src/app/dispatcher.rs +++ b/leaf/src/app/dispatcher.rs @@ -1,5 +1,6 @@ use std::io::{self, ErrorKind}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::time::Duration; use futures::future::{self, Either}; @@ -12,7 +13,7 @@ use crate::{ common::sniff, option, proxy::{OutboundDatagram, ProxyHandlerType, ProxyStream, SimpleProxyStream}, - session::{Session, SocksAddr}, + session::{Network, Session, SocksAddr}, }; use super::outbound::manager::OutboundManager; @@ -27,10 +28,14 @@ fn log_request( ) { if let Some(color) = outbound_tag_color { use colored::Colorize; + let network_color = match sess.network { + Network::Tcp => colored::Color::Blue, + Network::Udp => colored::Color::Yellow, + }; info!( "[{}] [{}] [{}] [{}ms] {}", &sess.inbound_tag, - sess.network.to_string().color(colored::Color::Blue), + sess.network.to_string().color(network_color), outbound_tag.color(color), handshake_time, &sess.destination, @@ -44,7 +49,7 @@ fn log_request( } pub struct Dispatcher { - outbound_manager: OutboundManager, + outbound_manager: Arc, router: Router, endpoint_tcp_sem: Semaphore, direct_tcp_sem: Semaphore, @@ -53,7 +58,7 @@ pub struct Dispatcher { } impl Dispatcher { - pub fn new(outbound_manager: OutboundManager, router: Router) -> Self { + pub fn new(outbound_manager: Arc, router: Router) -> Self { Dispatcher { outbound_manager, router, diff --git a/leaf/src/app/mod.rs b/leaf/src/app/mod.rs index 088733b..7494205 100644 --- a/leaf/src/app/mod.rs +++ b/leaf/src/app/mod.rs @@ -5,6 +5,9 @@ pub mod nat_manager; pub mod outbound; pub mod router; +#[cfg(feature = "api")] +pub mod api; + #[cfg(any( target_os = "ios", target_os = "android", diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index 87d3357..90e4b96 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -9,6 +9,7 @@ use std::{ use anyhow::{anyhow, Result}; use log::*; use protobuf::Message; +use tokio::sync::RwLock; #[cfg(feature = "outbound-chain")] use crate::proxy::chain; @@ -18,6 +19,8 @@ use crate::proxy::failover; use crate::proxy::random; #[cfg(feature = "outbound-retry")] use crate::proxy::retry; +#[cfg(feature = "outbound-select")] +use crate::proxy::select; #[cfg(feature = "outbound-tryall")] use crate::proxy::tryall; @@ -50,8 +53,11 @@ use crate::{ proxy::{self, OutboundHandler, ProxyHandlerType}, }; +use super::selector::OutboundSelector; + pub struct OutboundManager { handlers: HashMap>, + selectors: Arc, default_handler: Option, } @@ -59,8 +65,9 @@ impl OutboundManager { pub fn new( outbounds: &protobuf::RepeatedField, dns_client: Arc, - ) -> Result { + ) -> Result> { let mut handlers: HashMap> = HashMap::new(); + let mut selectors: super::Selectors = HashMap::new(); let mut default_handler: Option = None; for outbound in outbounds.iter() { @@ -675,15 +682,57 @@ impl OutboundManager { ); handlers.insert(tag.clone(), handler); } + #[cfg(feature = "outbound-select")] + "select" => { + let settings = match config::SelectOutboundSettings::parse_from_bytes( + &outbound.settings, + ) { + Ok(s) => s, + Err(e) => { + warn!("invalid [{}] outbound settings: {}", &tag, e); + continue; + } + }; + let mut actors = HashMap::new(); + for actor in settings.actors.iter() { + if let Some(a) = handlers.get(actor) { + actors.insert(actor.to_owned(), a.clone()); + } + } + if actors.is_empty() { + continue; + } + let selector = Arc::new(RwLock::new(OutboundSelector::new(actors))); + let tcp = Box::new(select::TcpHandler { + selector: selector.clone(), + }); + let udp = Box::new(select::UdpHandler { + selector: selector.clone(), + }); + selectors.insert(tag.clone(), selector); + let handler = proxy::outbound::Handler::new( + tag.clone(), + colored::Color::TrueColor { + r: 182, + g: 235, + b: 250, + }, + ProxyHandlerType::Ensemble, + Some(tcp), + Some(udp), + ); + handlers.insert(tag.clone(), handler); + } _ => (), } } } - Ok(OutboundManager { + Ok(Arc::new(OutboundManager { handlers, + selectors: Arc::new(selectors), default_handler, - }) + })) } pub fn add(&mut self, tag: String, handler: Arc) { @@ -703,6 +752,10 @@ impl OutboundManager { inner: self.handlers.values(), } } + + pub fn get_selector(&self, tag: &str) -> Option>> { + self.selectors.get(tag).map(Clone::clone) + } } pub struct Handlers<'a> { diff --git a/leaf/src/app/outbound/mod.rs b/leaf/src/app/outbound/mod.rs index ff8de9e..2006fbc 100644 --- a/leaf/src/app/outbound/mod.rs +++ b/leaf/src/app/outbound/mod.rs @@ -1 +1,9 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use tokio::sync::RwLock; + pub mod manager; +pub mod selector; + +pub type Selectors = HashMap>>; diff --git a/leaf/src/app/outbound/selector.rs b/leaf/src/app/outbound/selector.rs new file mode 100644 index 0000000..a69565f --- /dev/null +++ b/leaf/src/app/outbound/selector.rs @@ -0,0 +1,38 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use crate::proxy::OutboundHandler; +use anyhow::{anyhow, Result}; + +/// OutboundSelector typically associates to a `select` outbound. +pub struct OutboundSelector { + handlers: HashMap>, + selected: Option, +} + +impl OutboundSelector { + pub fn new(handlers: HashMap>) -> Self { + Self { + handlers, + selected: None, + } + } + + pub fn get_selected(&self) -> Option> { + if let Some(tag) = self.selected.as_ref() { + if let Some(h) = self.handlers.get(tag) { + return Some(h.clone()); + } + } + None + } + + pub fn set_selected(&mut self, tag: &str) -> Result<()> { + if self.handlers.contains_key(tag) { + self.selected.replace(tag.to_string()); + Ok(()) + } else { + Err(anyhow!("handler not exists")) + } + } +} diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index e32c2dd..349cfeb 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -1072,6 +1072,17 @@ pub fn to_internal(conf: Config) -> Result { outbound.settings = settings; outbounds.push(outbound); } + "select" => { + let mut settings = internal::SelectOutboundSettings::new(); + if let Some(ext_actors) = &ext_proxy_group.actors { + for ext_actor in ext_actors { + settings.actors.push(ext_actor.to_string()); + } + } + let settings = settings.write_to_bytes().unwrap(); + outbound.settings = settings; + outbounds.push(outbound); + } _ => {} } } diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index a50b44f..3d2f2ce 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -165,6 +165,10 @@ message FailOverOutboundSettings { uint32 cache_timeout = 8; } +message SelectOutboundSettings { + repeated string actors = 1; +} + message Outbound { string tag = 1; string protocol = 2; // TODO use enum diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index c882314..2dd78a1 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -3721,242 +3721,6 @@ impl ::protobuf::reflect::ProtobufValue for VMessOutboundSettings { } } -#[derive(PartialEq,Clone,Default)] -pub struct VLessOutboundSettings { - // message fields - pub address: ::std::string::String, - pub port: u32, - pub uuid: ::std::string::String, - // special fields - pub unknown_fields: ::protobuf::UnknownFields, - pub cached_size: ::protobuf::CachedSize, -} - -impl<'a> ::std::default::Default for &'a VLessOutboundSettings { - fn default() -> &'a VLessOutboundSettings { - ::default_instance() - } -} - -impl VLessOutboundSettings { - pub fn new() -> VLessOutboundSettings { - ::std::default::Default::default() - } - - // string address = 1; - - - pub fn get_address(&self) -> &str { - &self.address - } - pub fn clear_address(&mut self) { - self.address.clear(); - } - - // Param is passed by value, moved - pub fn set_address(&mut self, v: ::std::string::String) { - self.address = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_address(&mut self) -> &mut ::std::string::String { - &mut self.address - } - - // Take field - pub fn take_address(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.address, ::std::string::String::new()) - } - - // uint32 port = 2; - - - pub fn get_port(&self) -> u32 { - self.port - } - pub fn clear_port(&mut self) { - self.port = 0; - } - - // Param is passed by value, moved - pub fn set_port(&mut self, v: u32) { - self.port = v; - } - - // string uuid = 3; - - - pub fn get_uuid(&self) -> &str { - &self.uuid - } - pub fn clear_uuid(&mut self) { - self.uuid.clear(); - } - - // Param is passed by value, moved - pub fn set_uuid(&mut self, v: ::std::string::String) { - self.uuid = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_uuid(&mut self) -> &mut ::std::string::String { - &mut self.uuid - } - - // Take field - pub fn take_uuid(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.uuid, ::std::string::String::new()) - } -} - -impl ::protobuf::Message for VLessOutboundSettings { - fn is_initialized(&self) -> bool { - true - } - - fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.address)?; - }, - 2 => { - if wire_type != ::protobuf::wire_format::WireTypeVarint { - return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_uint32()?; - self.port = tmp; - }, - 3 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.uuid)?; - }, - _ => { - ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.address.is_empty() { - my_size += ::protobuf::rt::string_size(1, &self.address); - } - if self.port != 0 { - my_size += ::protobuf::rt::value_size(2, self.port, ::protobuf::wire_format::WireTypeVarint); - } - if !self.uuid.is_empty() { - my_size += ::protobuf::rt::string_size(3, &self.uuid); - } - my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { - if !self.address.is_empty() { - os.write_string(1, &self.address)?; - } - if self.port != 0 { - os.write_uint32(2, self.port)?; - } - if !self.uuid.is_empty() { - os.write_string(3, &self.uuid)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { - self - } - - fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> VLessOutboundSettings { - VLessOutboundSettings::new() - } - - fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { - static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "address", - |m: &VLessOutboundSettings| { &m.address }, - |m: &mut VLessOutboundSettings| { &mut m.address }, - )); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( - "port", - |m: &VLessOutboundSettings| { &m.port }, - |m: &mut VLessOutboundSettings| { &mut m.port }, - )); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "uuid", - |m: &VLessOutboundSettings| { &m.uuid }, - |m: &mut VLessOutboundSettings| { &mut m.uuid }, - )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "VLessOutboundSettings", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static VLessOutboundSettings { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(VLessOutboundSettings::new) - } -} - -impl ::protobuf::Clear for VLessOutboundSettings { - fn clear(&mut self) { - self.address.clear(); - self.port = 0; - self.uuid.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for VLessOutboundSettings { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::protobuf::text_format::fmt(self, f) - } -} - -impl ::protobuf::reflect::ProtobufValue for VLessOutboundSettings { - fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { - ::protobuf::reflect::ReflectValueRef::Message(self) - } -} - #[derive(PartialEq,Clone,Default)] pub struct TlsOutboundSettings { // message fields @@ -6243,69 +6007,52 @@ impl ::protobuf::reflect::ProtobufValue for FailOverOutboundSettings { } #[derive(PartialEq,Clone,Default)] -pub struct StatOutboundSettings { +pub struct SelectOutboundSettings { // message fields - pub address: ::std::string::String, - pub port: u32, + pub actors: ::protobuf::RepeatedField<::std::string::String>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } -impl<'a> ::std::default::Default for &'a StatOutboundSettings { - fn default() -> &'a StatOutboundSettings { - ::default_instance() +impl<'a> ::std::default::Default for &'a SelectOutboundSettings { + fn default() -> &'a SelectOutboundSettings { + ::default_instance() } } -impl StatOutboundSettings { - pub fn new() -> StatOutboundSettings { +impl SelectOutboundSettings { + pub fn new() -> SelectOutboundSettings { ::std::default::Default::default() } - // string address = 1; + // repeated string actors = 1; - pub fn get_address(&self) -> &str { - &self.address + pub fn get_actors(&self) -> &[::std::string::String] { + &self.actors } - pub fn clear_address(&mut self) { - self.address.clear(); + pub fn clear_actors(&mut self) { + self.actors.clear(); } // Param is passed by value, moved - pub fn set_address(&mut self, v: ::std::string::String) { - self.address = v; + pub fn set_actors(&mut self, v: ::protobuf::RepeatedField<::std::string::String>) { + self.actors = v; } // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_address(&mut self) -> &mut ::std::string::String { - &mut self.address + pub fn mut_actors(&mut self) -> &mut ::protobuf::RepeatedField<::std::string::String> { + &mut self.actors } // Take field - pub fn take_address(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.address, ::std::string::String::new()) - } - - // uint32 port = 2; - - - pub fn get_port(&self) -> u32 { - self.port - } - pub fn clear_port(&mut self) { - self.port = 0; - } - - // Param is passed by value, moved - pub fn set_port(&mut self, v: u32) { - self.port = v; + pub fn take_actors(&mut self) -> ::protobuf::RepeatedField<::std::string::String> { + ::std::mem::replace(&mut self.actors, ::protobuf::RepeatedField::new()) } } -impl ::protobuf::Message for StatOutboundSettings { +impl ::protobuf::Message for SelectOutboundSettings { fn is_initialized(&self) -> bool { true } @@ -6315,14 +6062,7 @@ impl ::protobuf::Message for StatOutboundSettings { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.address)?; - }, - 2 => { - if wire_type != ::protobuf::wire_format::WireTypeVarint { - return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_uint32()?; - self.port = tmp; + ::protobuf::rt::read_repeated_string_into(wire_type, is, &mut self.actors)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; @@ -6336,24 +6076,18 @@ impl ::protobuf::Message for StatOutboundSettings { #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; - if !self.address.is_empty() { - my_size += ::protobuf::rt::string_size(1, &self.address); - } - if self.port != 0 { - my_size += ::protobuf::rt::value_size(2, self.port, ::protobuf::wire_format::WireTypeVarint); - } + for value in &self.actors { + my_size += ::protobuf::rt::string_size(1, &value); + }; my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { - if !self.address.is_empty() { - os.write_string(1, &self.address)?; - } - if self.port != 0 { - os.write_uint32(2, self.port)?; - } + for v in &self.actors { + os.write_string(1, &v)?; + }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } @@ -6384,53 +6118,47 @@ impl ::protobuf::Message for StatOutboundSettings { Self::descriptor_static() } - fn new() -> StatOutboundSettings { - StatOutboundSettings::new() + fn new() -> SelectOutboundSettings { + SelectOutboundSettings::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "address", - |m: &StatOutboundSettings| { &m.address }, - |m: &mut StatOutboundSettings| { &mut m.address }, + fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "actors", + |m: &SelectOutboundSettings| { &m.actors }, + |m: &mut SelectOutboundSettings| { &mut m.actors }, )); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( - "port", - |m: &StatOutboundSettings| { &m.port }, - |m: &mut StatOutboundSettings| { &mut m.port }, - )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "StatOutboundSettings", + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "SelectOutboundSettings", fields, file_descriptor_proto() ) }) } - fn default_instance() -> &'static StatOutboundSettings { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(StatOutboundSettings::new) + fn default_instance() -> &'static SelectOutboundSettings { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(SelectOutboundSettings::new) } } -impl ::protobuf::Clear for StatOutboundSettings { +impl ::protobuf::Clear for SelectOutboundSettings { fn clear(&mut self) { - self.address.clear(); - self.port = 0; + self.actors.clear(); self.unknown_fields.clear(); } } -impl ::std::fmt::Debug for StatOutboundSettings { +impl ::std::fmt::Debug for SelectOutboundSettings { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } -impl ::protobuf::reflect::ProtobufValue for StatOutboundSettings { +impl ::protobuf::reflect::ProtobufValue for SelectOutboundSettings { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } @@ -7926,40 +7654,37 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x20\x01(\tR\x08password\"u\n\x15VMessOutboundSettings\x12\x18\n\x07addr\ ess\x18\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\ \x04port\x12\x12\n\x04uuid\x18\x03\x20\x01(\tR\x04uuid\x12\x1a\n\x08secu\ - rity\x18\x04\x20\x01(\tR\x08security\"Y\n\x15VLessOutboundSettings\x12\ + rity\x18\x04\x20\x01(\tR\x08security\"J\n\x13TlsOutboundSettings\x12\x1f\ + \n\x0bserver_name\x18\x01\x20\x01(\tR\nserverName\x12\x12\n\x04alpn\x18\ + \x02\x20\x03(\tR\x04alpn\"\xae\x01\n\x19WebSocketOutboundSettings\x12\ + \x12\n\x04path\x18\x01\x20\x01(\tR\x04path\x12A\n\x07headers\x18\x02\x20\ + \x03(\x0b2'.WebSocketOutboundSettings.HeadersEntryR\x07headers\x1a:\n\ + \x0cHeadersEntry\x12\x10\n\x03key\x18\x01\x20\x01(\tR\x03key\x12\x14\n\ + \x05value\x18\x02\x20\x01(\tR\x05value:\x028\x01\"?\n\x15HTTP2OutboundSe\ + ttings\x12\x12\n\x04path\x18\x01\x20\x01(\tR\x04path\x12\x12\n\x04host\ + \x18\x02\x20\x01(\tR\x04host\"O\n\x16TryAllOutboundSettings\x12\x16\n\ + \x06actors\x18\x01\x20\x03(\tR\x06actors\x12\x1d\n\ndelay_base\x18\x02\ + \x20\x01(\rR\tdelayBase\"0\n\x16RandomOutboundSettings\x12\x16\n\x06acto\ + rs\x18\x01\x20\x03(\tR\x06actors\"\x9f\x01\n\x14AMuxOutboundSettings\x12\ \x18\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\ - \x02\x20\x01(\rR\x04port\x12\x12\n\x04uuid\x18\x03\x20\x01(\tR\x04uuid\"\ - J\n\x13TlsOutboundSettings\x12\x1f\n\x0bserver_name\x18\x01\x20\x01(\tR\ - \nserverName\x12\x12\n\x04alpn\x18\x02\x20\x03(\tR\x04alpn\"\xae\x01\n\ - \x19WebSocketOutboundSettings\x12\x12\n\x04path\x18\x01\x20\x01(\tR\x04p\ - ath\x12A\n\x07headers\x18\x02\x20\x03(\x0b2'.WebSocketOutboundSettings.H\ - eadersEntryR\x07headers\x1a:\n\x0cHeadersEntry\x12\x10\n\x03key\x18\x01\ - \x20\x01(\tR\x03key\x12\x14\n\x05value\x18\x02\x20\x01(\tR\x05value:\x02\ - 8\x01\"?\n\x15HTTP2OutboundSettings\x12\x12\n\x04path\x18\x01\x20\x01(\t\ - R\x04path\x12\x12\n\x04host\x18\x02\x20\x01(\tR\x04host\"O\n\x16TryAllOu\ - tboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\x12\x1d\ - \n\ndelay_base\x18\x02\x20\x01(\rR\tdelayBase\"0\n\x16RandomOutboundSett\ - ings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"\x9f\x01\n\x14AM\ - uxOutboundSettings\x12\x18\n\x07address\x18\x01\x20\x01(\tR\x07address\ - \x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\x12\x16\n\x06actors\x18\ - \x03\x20\x03(\tR\x06actors\x12\x1f\n\x0bmax_accepts\x18\x04\x20\x01(\rR\ - \nmaxAccepts\x12\x20\n\x0bconcurrency\x18\x05\x20\x01(\rR\x0bconcurrency\ - \"\x87\x01\n\x14QuicOutboundSettings\x12\x18\n\x07address\x18\x01\x20\ - \x01(\tR\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\x12\ - \x1f\n\x0bserver_name\x18\x03\x20\x01(\tR\nserverName\x12\x20\n\x0bcerti\ - ficate\x18\x04\x20\x01(\tR\x0bcertificate\"/\n\x15ChainOutboundSettings\ - \x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"K\n\x15RetryOutbound\ - Settings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\x12\x1a\n\x08\ - attempts\x18\x02\x20\x01(\rR\x08attempts\"\xa6\x02\n\x18FailOverOutbound\ - Settings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\x12!\n\x0cfai\ - l_timeout\x18\x02\x20\x01(\rR\x0bfailTimeout\x12!\n\x0chealth_check\x18\ - \x03\x20\x01(\x08R\x0bhealthCheck\x12%\n\x0echeck_interval\x18\x04\x20\ - \x01(\rR\rcheckInterval\x12\x1a\n\x08failover\x18\x05\x20\x01(\x08R\x08f\ - ailover\x12%\n\x0efallback_cache\x18\x06\x20\x01(\x08R\rfallbackCache\ - \x12\x1d\n\ncache_size\x18\x07\x20\x01(\rR\tcacheSize\x12#\n\rcache_time\ - out\x18\x08\x20\x01(\rR\x0ccacheTimeout\"D\n\x14StatOutboundSettings\x12\ - \x18\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\ - \x02\x20\x01(\rR\x04port\"h\n\x08Outbound\x12\x10\n\x03tag\x18\x01\x20\ + \x02\x20\x01(\rR\x04port\x12\x16\n\x06actors\x18\x03\x20\x03(\tR\x06acto\ + rs\x12\x1f\n\x0bmax_accepts\x18\x04\x20\x01(\rR\nmaxAccepts\x12\x20\n\ + \x0bconcurrency\x18\x05\x20\x01(\rR\x0bconcurrency\"\x87\x01\n\x14QuicOu\ + tboundSettings\x12\x18\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\ + \x12\n\x04port\x18\x02\x20\x01(\rR\x04port\x12\x1f\n\x0bserver_name\x18\ + \x03\x20\x01(\tR\nserverName\x12\x20\n\x0bcertificate\x18\x04\x20\x01(\t\ + R\x0bcertificate\"/\n\x15ChainOutboundSettings\x12\x16\n\x06actors\x18\ + \x01\x20\x03(\tR\x06actors\"K\n\x15RetryOutboundSettings\x12\x16\n\x06ac\ + tors\x18\x01\x20\x03(\tR\x06actors\x12\x1a\n\x08attempts\x18\x02\x20\x01\ + (\rR\x08attempts\"\xa6\x02\n\x18FailOverOutboundSettings\x12\x16\n\x06ac\ + tors\x18\x01\x20\x03(\tR\x06actors\x12!\n\x0cfail_timeout\x18\x02\x20\ + \x01(\rR\x0bfailTimeout\x12!\n\x0chealth_check\x18\x03\x20\x01(\x08R\x0b\ + healthCheck\x12%\n\x0echeck_interval\x18\x04\x20\x01(\rR\rcheckInterval\ + \x12\x1a\n\x08failover\x18\x05\x20\x01(\x08R\x08failover\x12%\n\x0efallb\ + ack_cache\x18\x06\x20\x01(\x08R\rfallbackCache\x12\x1d\n\ncache_size\x18\ + \x07\x20\x01(\rR\tcacheSize\x12#\n\rcache_timeout\x18\x08\x20\x01(\rR\ + \x0ccacheTimeout\"0\n\x16SelectOutboundSettings\x12\x16\n\x06actors\x18\ + \x01\x20\x03(\tR\x06actors\"h\n\x08Outbound\x12\x10\n\x03tag\x18\x01\x20\ \x01(\tR\x03tag\x12\x1a\n\x08protocol\x18\x02\x20\x01(\tR\x08protocol\ \x12\x12\n\x04bind\x18\x03\x20\x01(\tR\x04bind\x12\x1a\n\x08settings\x18\ \x04\x20\x01(\x0cR\x08settings\"\xf6\x02\n\x0bRoutingRule\x12\x1d\n\ntar\ diff --git a/leaf/src/config/json/config.rs b/leaf/src/config/json/config.rs index 09715af..18498a6 100644 --- a/leaf/src/config/json/config.rs +++ b/leaf/src/config/json/config.rs @@ -193,9 +193,8 @@ pub struct FailOverOutboundSettings { } #[derive(Serialize, Deserialize, Debug)] -pub struct StatOutboundSettings { - pub address: Option, - pub port: Option, +pub struct SelectOutboundSettings { + pub actors: Option>, } #[derive(Serialize, Deserialize, Debug)] @@ -838,6 +837,22 @@ pub fn to_internal(json: Config) -> Result { outbound.settings = settings; outbounds.push(outbound); } + "select" => { + if ext_outbound.settings.is_none() { + return Err(anyhow!("invalid select outbound settings")); + } + let mut settings = internal::SelectOutboundSettings::new(); + let ext_settings: SelectOutboundSettings = + serde_json::from_str(ext_outbound.settings.unwrap().get()).unwrap(); + if let Some(ext_actors) = ext_settings.actors { + for ext_actor in ext_actors { + settings.actors.push(ext_actor); + } + } + let settings = settings.write_to_bytes().unwrap(); + outbound.settings = settings; + outbounds.push(outbound); + } _ => { // skip outbound with unknown protocol } diff --git a/leaf/src/proxy/mod.rs b/leaf/src/proxy/mod.rs index 9298533..5efdd44 100644 --- a/leaf/src/proxy/mod.rs +++ b/leaf/src/proxy/mod.rs @@ -48,6 +48,8 @@ pub mod random; pub mod redirect; #[cfg(feature = "outbound-retry")] pub mod retry; +#[cfg(feature = "outbound-select")] +pub mod select; #[cfg(any(feature = "inbound-shadowsocks", feature = "outbound-shadowsocks"))] pub mod shadowsocks; #[cfg(any(feature = "inbound-socks", feature = "outbound-socks"))] diff --git a/leaf/src/proxy/select/mod.rs b/leaf/src/proxy/select/mod.rs new file mode 100644 index 0000000..30dae4d --- /dev/null +++ b/leaf/src/proxy/select/mod.rs @@ -0,0 +1,7 @@ +pub mod tcp; +pub mod udp; + +pub use tcp::Handler as TcpHandler; +pub use udp::Handler as UdpHandler; + +pub static NAME: &str = "select"; diff --git a/leaf/src/proxy/select/tcp.rs b/leaf/src/proxy/select/tcp.rs new file mode 100644 index 0000000..09cc6ff --- /dev/null +++ b/leaf/src/proxy/select/tcp.rs @@ -0,0 +1,39 @@ +use std::{io, sync::Arc}; + +use async_trait::async_trait; +use log::*; +use tokio::sync::RwLock; + +use crate::{ + app::outbound::selector::OutboundSelector, + proxy::{OutboundConnect, ProxyStream, TcpOutboundHandler}, + session::Session, +}; + +pub struct Handler { + pub selector: Arc>, +} + +#[async_trait] +impl TcpOutboundHandler for Handler { + fn name(&self) -> &str { + super::NAME + } + + fn tcp_connect_addr(&self) -> Option { + None + } + + async fn handle_tcp<'a>( + &'a self, + sess: &'a Session, + stream: Option>, + ) -> io::Result> { + if let Some(a) = self.selector.read().await.get_selected() { + debug!("select handles tcp [{}] to [{}]", sess.destination, a.tag()); + a.handle_tcp(sess, stream).await + } else { + Err(io::Error::new(io::ErrorKind::Other, "no selected outbound")) + } + } +} diff --git a/leaf/src/proxy/select/udp.rs b/leaf/src/proxy/select/udp.rs new file mode 100644 index 0000000..b339b61 --- /dev/null +++ b/leaf/src/proxy/select/udp.rs @@ -0,0 +1,46 @@ +use std::io; +use std::sync::Arc; + +use async_trait::async_trait; +use log::*; +use tokio::sync::RwLock; + +use crate::{ + app::outbound::selector::OutboundSelector, + proxy::{ + OutboundConnect, OutboundDatagram, OutboundTransport, UdpOutboundHandler, UdpTransportType, + }, + session::Session, +}; + +pub struct Handler { + pub selector: Arc>, +} + +#[async_trait] +impl UdpOutboundHandler for Handler { + fn name(&self) -> &str { + super::NAME + } + + fn udp_connect_addr(&self) -> Option { + None + } + + fn udp_transport_type(&self) -> UdpTransportType { + UdpTransportType::Unknown + } + + async fn handle_udp<'a>( + &'a self, + sess: &'a Session, + transport: Option, + ) -> io::Result> { + if let Some(a) = self.selector.read().await.get_selected() { + debug!("select handles tcp [{}] to [{}]", sess.destination, a.tag()); + a.handle_udp(sess, transport).await + } else { + Err(io::Error::new(io::ErrorKind::Other, "no selected outbound")) + } + } +} diff --git a/leaf/src/util.rs b/leaf/src/util.rs index 6d50465..caa3a39 100644 --- a/leaf/src/util.rs +++ b/leaf/src/util.rs @@ -13,22 +13,31 @@ use crate::{ Runner, }; +#[cfg(feature = "api")] +use crate::app::api::api_server::ApiServer; + #[cfg(any(target_os = "ios", target_os = "android"))] use super::mobile; use super::{common, config}; -pub fn create_runners(config: Config) -> Result> { +pub fn create_runners(rt: &tokio::runtime::Runtime, config: Config) -> Result> { + let mut runners = Vec::new(); let dns_client = Arc::new(DnsClient::new(&config.dns)?); let outbound_manager = OutboundManager::new(&config.outbounds, dns_client.clone())?; + #[cfg(feature = "api")] + { + let api_server = ApiServer::new(outbound_manager.clone()); + runners.push(api_server.serve(rt)); + } let router = Router::new(&config.routing_rules, dns_client); let dispatcher = Arc::new(Dispatcher::new(outbound_manager, router)); let nat_manager = Arc::new(NatManager::new(dispatcher.clone())); let inbound_manager = InboundManager::new(&config.inbounds, dispatcher, nat_manager); - let runners = inbound_manager.get_runners(); + runners.append(&mut inbound_manager.get_runners()); Ok(runners) } -pub fn prepare(config: config::Config) -> Result> { +pub fn prepare(rt: &tokio::runtime::Runtime, config: config::Config) -> Result> { let loglevel = if let Some(log) = config.log.as_ref() { match log.level { config::Log_Level::TRACE => log::LevelFilter::Trace, @@ -66,7 +75,7 @@ pub fn prepare(config: config::Config) -> Result> { } common::log::apply_logger(logger); - create_runners(config).map_err(|e| anyhow!("create runners fialed: {}", e)) + create_runners(rt, config).map_err(|e| anyhow!("create runners fialed: {}", e)) } pub async fn test_outbound(tag: &str, config: &Config) {