outbound/tun: automate tun setup

This commit is contained in:
eric committed 2021-04-16 20:06:06 +08:00
1 parent 7324093730
commit c1d685205c
18 files changed
+1177 -202

No files matched your search

+3
View File
@@ -228,6 +228,9 @@ notify = { version = "5.0.0-pre.6", optional = true }
[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 }
[target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies]
pnet_datalink = { version = "0.27", package = "pnet_datalink" }
# Used in mobile logger
[target.'cfg(any(target_os = "ios", target_os = "android"))'.dependencies]
memchr = { version = "2" }
+116 -49
View File
@@ -287,23 +287,32 @@ impl DnsClient {
let mut cached_ips = Vec::new();
if *crate::option::PREFER_IPV6 {
if let Some(ips) = self.ipv6_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
match (*crate::option::ENABLE_IPV6, *crate::option::PREFER_IPV6) {
(true, true) => {
if let Some(ips) = self.ipv6_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
}
if let Some(ips) = self.ipv4_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
}
}
if let Some(ips) = self.ipv4_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
(true, false) => {
if let Some(ips) = self.ipv4_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
}
if let Some(ips) = self.ipv6_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
}
}
} else {
if let Some(ips) = self.ipv4_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
}
if let Some(ips) = self.ipv6_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
_ => {
if let Some(ips) = self.ipv4_cache.lock().await.get(&domain) {
let mut ips = ips.to_vec();
cached_ips.append(&mut ips);
}
}
}
@@ -334,42 +343,100 @@ impl DnsClient {
let mut query_tasks = Vec::new();
let msg = Self::new_query(name.clone(), RecordType::A);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
match (*crate::option::ENABLE_IPV6, *crate::option::PREFER_IPV6) {
(true, true) => {
let msg = Self::new_query(name.clone(), RecordType::AAAA);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
if *crate::option::ENABLE_IPV6 {
let msg = Self::new_query(name.clone(), RecordType::AAAA);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
let msg = Self::new_query(name.clone(), RecordType::A);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
}
(true, false) => {
let msg = Self::new_query(name.clone(), RecordType::A);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
let msg = Self::new_query(name.clone(), RecordType::AAAA);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
}
_ => {
let msg = Self::new_query(name.clone(), RecordType::A);
let msg_buf = match msg.to_vec() {
Ok(b) => b,
Err(e) => return Err(anyhow!("encode message to buffer failed: {}", e)),
};
let mut tasks = Vec::new();
for server in &self.servers {
let t = self.query_task(
msg_buf.clone().into_boxed_slice(),
&domain,
server,
bind_addr,
);
tasks.push(Box::pin(t));
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
}
let query_task = select_ok(tasks.into_iter());
query_tasks.push(query_task);
}
let mut ips = Vec::new();
+85 -13
View File
@@ -30,7 +30,6 @@ use crate::proxy::ws;
use crate::proxy::chain;
use super::network_listener::NetworkInboundListener;
use super::InboundListener;
#[cfg(all(
feature = "inbound-tun",
@@ -41,10 +40,21 @@ use super::InboundListener;
target_os = "linux"
)
))]
use super::tun_listener::TUNInboundListener;
use super::tun_listener::TunInboundListener;
pub struct InboundManager {
listeners: HashMap<String, Arc<dyn InboundListener>>,
network_listeners: HashMap<String, NetworkInboundListener>,
#[cfg(all(
feature = "inbound-tun",
any(
target_os = "ios",
target_os = "android",
target_os = "macos",
target_os = "linux"
)
))]
tun_listener: Option<TunInboundListener>,
tun_auto: bool,
}
impl InboundManager {
@@ -188,7 +198,20 @@ impl InboundManager {
}
}
let mut listeners: HashMap<String, Arc<dyn InboundListener>> = HashMap::new();
let mut network_listeners: HashMap<String, NetworkInboundListener> = HashMap::new();
#[cfg(all(
feature = "inbound-tun",
any(
target_os = "ios",
target_os = "android",
target_os = "macos",
target_os = "linux"
)
))]
let mut tun_listener: Option<TunInboundListener> = None;
let mut tun_auto = false;
for inbound in inbounds.iter() {
let tag = String::from(&inbound.tag);
@@ -203,38 +226,87 @@ impl InboundManager {
)
))]
"tun" => {
let listener = Arc::new(TUNInboundListener {
let listener = TunInboundListener {
inbound: inbound.clone(),
dispatcher: dispatcher.clone(),
nat_manager: nat_manager.clone(),
});
listeners.insert(tag.clone(), listener);
};
tun_listener.replace(listener);
let settings =
crate::config::TunInboundSettings::parse_from_bytes(&inbound.settings)?;
tun_auto = settings.auto;
}
_ => {
if inbound.port != 0 {
if let Some(h) = handlers.get(&tag) {
let listener = Arc::new(NetworkInboundListener {
let listener = NetworkInboundListener {
address: inbound.address.clone(),
port: inbound.port as u16,
handler: h.clone(),
dispatcher: dispatcher.clone(),
nat_manager: nat_manager.clone(),
});
listeners.insert(tag.clone(), listener);
};
network_listeners.insert(tag.clone(), listener);
}
}
}
}
}
Ok(InboundManager { listeners })
Ok(InboundManager {
network_listeners,
#[cfg(all(
feature = "inbound-tun",
any(
target_os = "ios",
target_os = "android",
target_os = "macos",
target_os = "linux"
)
))]
tun_listener,
tun_auto,
})
}
pub fn get_runners(self) -> Result<Vec<Runner>> {
pub fn get_network_runners(&self) -> Result<Vec<Runner>> {
let mut runners: Vec<Runner> = Vec::new();
for (_, listener) in self.listeners {
for (_, listener) in self.network_listeners.iter() {
runners.append(&mut listener.listen()?);
}
Ok(runners)
}
#[cfg(all(
feature = "inbound-tun",
any(
target_os = "ios",
target_os = "android",
target_os = "macos",
target_os = "linux"
)
))]
pub fn get_tun_runner(&self) -> Result<Runner> {
if let Some(listener) = &self.tun_listener {
return listener.listen();
}
Err(anyhow!("no tun inbound"))
}
#[cfg(all(
feature = "inbound-tun",
any(
target_os = "ios",
target_os = "android",
target_os = "macos",
target_os = "linux"
)
))]
pub fn has_tun_listener(&self) -> bool {
self.tun_listener.is_some()
}
pub fn tun_auto(&self) -> bool {
self.tun_auto
}
}
-6
View File
@@ -1,5 +1,3 @@
use anyhow::Result;
mod network_listener;
#[cfg(all(
@@ -14,7 +12,3 @@ mod network_listener;
mod tun_listener;
pub mod manager;
trait InboundListener {
fn listen(&self) -> Result<Vec<crate::Runner>>;
}
+2 -4
View File
@@ -19,8 +19,6 @@ use crate::proxy::{
use crate::session::{Network, Session, SocksAddr};
use crate::Runner;
use super::InboundListener;
async fn handle_inbound_datagram(
inbound_tag: String,
socket: Box<dyn InboundDatagram>,
@@ -178,8 +176,8 @@ pub struct NetworkInboundListener {
pub nat_manager: Arc<NatManager>,
}
impl InboundListener for NetworkInboundListener {
fn listen(&self) -> Result<Vec<Runner>> {
impl NetworkInboundListener {
pub fn listen(&self) -> Result<Vec<Runner>> {
let mut runners: Vec<Runner> = Vec::new();
let handler = self.handler.clone();
let dispatcher = self.dispatcher.clone();
+5 -11
View File
@@ -8,24 +8,18 @@ use crate::config::Inbound;
use crate::proxy::tun;
use crate::Runner;
use super::InboundListener;
pub struct TUNInboundListener {
pub struct TunInboundListener {
pub inbound: Inbound,
pub dispatcher: Arc<Dispatcher>,
pub nat_manager: Arc<NatManager>,
}
impl InboundListener for TUNInboundListener {
fn listen(&self) -> Result<Vec<Runner>> {
let mut runners: Vec<Runner> = Vec::new();
if let Ok(r) = tun::inbound::new(
impl TunInboundListener {
pub fn listen(&self) -> Result<Runner> {
tun::inbound::new(
self.inbound.clone(),
self.dispatcher.clone(),
self.nat_manager.clone(),
) {
runners.push(Box::pin(r));
}
Ok(runners)
)
}
}
+5 -6
View File
@@ -359,8 +359,7 @@ pub struct Router {
}
impl Router {
fn load_rules(routing_rules: &protobuf::RepeatedField<RoutingRule>) -> Vec<Rule> {
let mut rules = Vec::new();
fn load_rules(rules: &mut Vec<Rule>, routing_rules: &protobuf::RepeatedField<RoutingRule>) {
let mut mmdb_readers: HashMap<String, Arc<maxminddb::Reader<Mmap>>> = HashMap::new();
for rr in routing_rules.iter() {
let mut cond_and = ConditionAnd::new();
@@ -406,20 +405,20 @@ impl Router {
rules.push(Rule::new(rr.target_tag.clone(), Box::new(cond_and)));
}
rules
}
pub fn new(
routing_rules: &protobuf::RepeatedField<RoutingRule>,
dns_client: SyncDnsClient,
) -> Self {
let rules = Self::load_rules(routing_rules);
let mut rules: Vec<Rule> = Vec::new();
Self::load_rules(&mut rules, routing_rules);
Router { rules, dns_client }
}
pub fn reload(&mut self, routing_rules: &protobuf::RepeatedField<RoutingRule>) -> Result<()> {
let rules = Self::load_rules(routing_rules);
self.rules = rules;
self.rules.clear();
Self::load_rules(&mut self.rules, routing_rules);
Ok(())
}
+308
View File
@@ -0,0 +1,308 @@
use std::net::{Ipv4Addr, Ipv6Addr};
use std::process::Command;
use anyhow::Result;
pub fn get_default_ipv4_gateway() -> Result<String> {
let out = Command::new("ip")
.arg("route")
.arg("get")
.arg("1")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("via"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() >= 3);
let res = cols[2].to_string();
Ok(res)
}
pub fn get_default_ipv6_gateway() -> Result<String> {
let out = Command::new("ip")
.arg("-6")
.arg("route")
.arg("get")
.arg("::2")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("via"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() >= 5);
let res = cols[4].to_string();
Ok(res)
}
pub fn get_default_ipv4_address() -> Result<String> {
let out = Command::new("ip")
.arg("route")
.arg("get")
.arg("1")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("via"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() >= 7);
let res = cols[6].to_string();
Ok(res)
}
pub fn get_default_ipv6_address() -> Result<String> {
let out = Command::new("ip")
.arg("-6")
.arg("route")
.arg("get")
.arg("::2")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("via"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() >= 11);
let res = cols[10].to_string();
Ok(res)
}
pub fn get_default_interface() -> Result<String> {
let out = Command::new("ip")
.arg("route")
.arg("get")
.arg("1")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("via"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() >= 5);
let res = cols[4].to_string();
Ok(res)
}
pub fn add_interface_ipv4_address(
name: &str,
addr: Ipv4Addr,
gw: Ipv4Addr,
mask: Ipv4Addr,
) -> Result<()> {
Command::new("ip")
.arg("addr")
.arg("add")
.arg(format!("{}/{}", addr.to_string(), mask.to_string()))
.arg("dev")
.arg(name.to_string())
.status()
.expect("failed to execute command");
Ok(())
}
pub fn add_interface_ipv6_address(name: &str, addr: Ipv6Addr, prefixlen: i32) -> Result<()> {
Command::new("ip")
.arg("-6")
.arg("addr")
.arg("add")
.arg(format!("{}/{}", addr.to_string(), prefixlen))
.arg("dev")
.arg(name.to_string())
.status()
.expect("failed to execute command");
Ok(())
}
pub fn add_default_ipv4_route(gateway: Ipv4Addr, ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("ip")
.arg("route")
.arg("add")
.arg("default")
.arg("via")
.arg(gateway.to_string())
.arg("dev")
.arg(ifscope)
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
} else {
Command::new("ip")
.arg("route")
.arg("add")
.arg("default")
.arg("via")
.arg(gateway.to_string())
.arg("table")
.arg("main")
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn add_default_ipv6_route(gateway: Ipv6Addr, ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("ip")
.arg("-6")
.arg("route")
.arg("add")
.arg("default")
.arg("via")
.arg(gateway.to_string())
.arg("dev")
.arg(ifscope)
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
} else {
Command::new("ip")
.arg("-6")
.arg("route")
.arg("add")
.arg("default")
.arg("via")
.arg(gateway.to_string())
.arg("table")
.arg("main")
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn delete_default_ipv4_route(ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("ip")
.arg("route")
.arg("del")
.arg("default")
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
} else {
Command::new("ip")
.arg("route")
.arg("del")
.arg("default")
.arg("table")
.arg("main")
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn delete_default_ipv6_route(ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("ip")
.arg("-6")
.arg("route")
.arg("del")
.arg("default")
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
} else {
Command::new("ip")
.arg("-6")
.arg("route")
.arg("del")
.arg("default")
.arg("table")
.arg("main")
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn add_default_ipv4_rule(addr: Ipv4Addr) -> Result<()> {
Command::new("ip")
.arg("rule")
.arg("add")
.arg("from")
.arg(addr.to_string())
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
Ok(())
}
pub fn add_default_ipv6_rule(addr: Ipv6Addr) -> Result<()> {
Command::new("ip")
.arg("-6")
.arg("rule")
.arg("add")
.arg("from")
.arg(addr.to_string())
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
Ok(())
}
pub fn delete_default_ipv4_rule(addr: Ipv4Addr) -> Result<()> {
Command::new("ip")
.arg("rule")
.arg("del")
.arg("from")
.arg(addr.to_string())
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
Ok(())
}
pub fn delete_default_ipv6_rule(addr: Ipv6Addr) -> Result<()> {
Command::new("ip")
.arg("-6")
.arg("rule")
.arg("del")
.arg("from")
.arg(addr.to_string())
.arg("table")
.arg("default")
.status()
.expect("failed to execute command");
Ok(())
}
+186
View File
@@ -0,0 +1,186 @@
use std::net::{Ipv4Addr, Ipv6Addr};
use std::process::Command;
use anyhow::Result;
pub fn get_default_ipv4_gateway() -> Result<String> {
let out = Command::new("route")
.arg("get")
.arg("1")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("gateway"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() == 2);
let res = cols[1].to_string();
Ok(res)
}
pub fn get_default_ipv6_gateway() -> Result<String> {
let out = Command::new("route")
.arg("get")
.arg("-inet6")
.arg("::2")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("gateway"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() == 2);
let res = cols[1].to_string();
Ok(res)
}
pub fn get_default_interface() -> Result<String> {
let out = Command::new("route")
.arg("get")
.arg("1")
.output()
.expect("failed to execute command");
assert!(out.status.success());
let out = String::from_utf8_lossy(&out.stdout).to_string();
let cols: Vec<&str> = out
.lines()
.filter(|l| l.contains("interface"))
.next()
.unwrap()
.split_whitespace()
.map(str::trim)
.collect();
assert!(cols.len() == 2);
let res = cols[1].to_string();
Ok(res)
}
pub fn add_interface_ipv4_address(
name: &str,
addr: Ipv4Addr,
gw: Ipv4Addr,
mask: Ipv4Addr,
) -> Result<()> {
Command::new("ifconfig")
.arg(name)
.arg("inet")
.arg(addr.to_string())
.arg("netmask")
.arg(mask.to_string())
.arg(gw.to_string())
.status()
.expect("failed to execute command");
Ok(())
}
pub fn add_interface_ipv6_address(name: &str, addr: Ipv6Addr, prefixlen: i32) -> Result<()> {
Command::new("ifconfig")
.arg(name)
.arg("inet6")
.arg(addr.to_string())
.arg("prefixlen")
.arg(prefixlen.to_string())
.status()
.expect("failed to execute command");
Ok(())
}
pub fn add_default_ipv4_route(gateway: Ipv4Addr, ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("route")
.arg("add")
.arg("-inet")
.arg("default")
.arg(gateway.to_string())
.arg("-ifscope")
.arg(ifscope)
.status()
.expect("failed to execute command");
} else {
Command::new("route")
.arg("add")
.arg("-inet")
.arg("default")
.arg(gateway.to_string())
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn add_default_ipv6_route(gateway: Ipv6Addr, ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("route")
.arg("add")
.arg("-inet6")
.arg("default")
.arg(gateway.to_string())
.arg("-ifscope")
.arg(ifscope)
.status()
.expect("failed to execute command");
} else {
Command::new("route")
.arg("add")
.arg("-inet6")
.arg("default")
.arg(gateway.to_string())
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn delete_default_ipv4_route(ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("route")
.arg("delete")
.arg("-inet")
.arg("default")
.arg("-ifscope")
.arg(ifscope)
.status()
.expect("failed to execute command");
} else {
Command::new("route")
.arg("delete")
.arg("-inet")
.arg("default")
.status()
.expect("failed to execute command");
};
Ok(())
}
pub fn delete_default_ipv6_route(ifscope: Option<String>) -> Result<()> {
if let Some(ifscope) = ifscope {
Command::new("route")
.arg("delete")
.arg("-inet6")
.arg("default")
.arg("-ifscope")
.arg(ifscope)
.status()
.expect("failed to execute command");
} else {
Command::new("route")
.arg("delete")
.arg("-inet6")
.arg("default")
.status()
.expect("failed to execute command");
};
Ok(())
}
+10
View File
@@ -2,3 +2,13 @@ pub mod crypto;
pub mod mutex;
pub mod resolver;
pub mod sniff;
#[cfg(target_os = "macos")]
pub mod cmd_macos;
#[cfg(target_os = "macos")]
pub use cmd_macos as cmd;
#[cfg(target_os = "linux")]
pub mod cmd_linux;
#[cfg(target_os = "linux")]
pub use cmd_linux as cmd;
+12 -1
View File
@@ -24,6 +24,7 @@ pub struct Tun {
pub struct General {
pub tun: Option<Tun>,
pub tun_fd: Option<i32>,
pub tun_auto: Option<bool>,
pub loglevel: Option<String>,
pub dns_server: Option<Vec<String>>,
pub dns_interface: Option<String>,
@@ -239,6 +240,10 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
}
"tun" => {
if let Some(items) = get_char_sep_slice(parts[1], ',') {
if items.len() == 1 {
general.tun_auto = Some(items[0] == "auto");
continue;
}
if items.len() != 5 {
continue;
}
@@ -655,7 +660,10 @@ pub fn to_internal(conf: Config) -> Result<internal::Config> {
inbounds.push(inbound);
}
if ext_general.tun_fd.is_some() || ext_general.tun.is_some() {
if ext_general.tun_fd.is_some()
|| ext_general.tun_auto.is_some()
|| ext_general.tun.is_some()
{
let mut inbound = internal::Inbound::new();
inbound.protocol = "tun".to_string();
inbound.tag = "tun".to_string();
@@ -683,6 +691,9 @@ pub fn to_internal(conf: Config) -> Result<internal::Config> {
if ext_general.tun_fd.is_some() {
settings.fd = ext_general.tun_fd.unwrap();
} else if ext_general.tun_auto.is_some() && ext_general.tun_auto.unwrap() {
settings.auto = true;
settings.fd = -1; // disable fd option
} else {
let ext_tun = ext_general.tun.as_ref().unwrap();
+1
View File
@@ -36,6 +36,7 @@ message Log {
message TunInboundSettings {
int32 fd = 1;
bool auto = 9;
string name = 2;
string address = 3;
string gateway = 4;
+116 -81
View File
@@ -946,6 +946,7 @@ impl ::protobuf::reflect::ProtobufValue for Log_Output {
pub struct TunInboundSettings {
// message fields
pub fd: i32,
pub auto: bool,
pub name: ::std::string::String,
pub address: ::std::string::String,
pub gateway: ::std::string::String,
@@ -984,6 +985,21 @@ impl TunInboundSettings {
self.fd = v;
}
// bool auto = 9;
pub fn get_auto(&self) -> bool {
self.auto
}
pub fn clear_auto(&mut self) {
self.auto = false;
}
// Param is passed by value, moved
pub fn set_auto(&mut self, v: bool) {
self.auto = v;
}
// string name = 2;
@@ -1170,6 +1186,13 @@ impl ::protobuf::Message for TunInboundSettings {
let tmp = is.read_int32()?;
self.fd = tmp;
},
9 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_bool()?;
self.auto = tmp;
},
2 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?;
},
@@ -1210,6 +1233,9 @@ impl ::protobuf::Message for TunInboundSettings {
if self.fd != 0 {
my_size += ::protobuf::rt::value_size(1, self.fd, ::protobuf::wire_format::WireTypeVarint);
}
if self.auto != false {
my_size += 2;
}
if !self.name.is_empty() {
my_size += ::protobuf::rt::string_size(2, &self.name);
}
@@ -1240,6 +1266,9 @@ impl ::protobuf::Message for TunInboundSettings {
if self.fd != 0 {
os.write_int32(1, self.fd)?;
}
if self.auto != false {
os.write_bool(9, self.auto)?;
}
if !self.name.is_empty() {
os.write_string(2, &self.name)?;
}
@@ -1304,6 +1333,11 @@ impl ::protobuf::Message for TunInboundSettings {
|m: &TunInboundSettings| { &m.fd },
|m: &mut TunInboundSettings| { &mut m.fd },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBool>(
"auto",
|m: &TunInboundSettings| { &m.auto },
|m: &mut TunInboundSettings| { &mut m.auto },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"name",
|m: &TunInboundSettings| { &m.name },
@@ -1356,6 +1390,7 @@ impl ::protobuf::Message for TunInboundSettings {
impl ::protobuf::Clear for TunInboundSettings {
fn clear(&mut self) {
self.fd = 0;
self.auto = false;
self.name.clear();
self.address.clear();
self.gateway.clear();
@@ -7875,87 +7910,87 @@ static file_descriptor_proto_data: &'static [u8] = b"\
e\x18\x03\x20\x01(\tR\noutputFile\"<\n\x05Level\x12\t\n\x05TRACE\x10\0\
\x12\t\n\x05DEBUG\x10\x01\x12\x08\n\x04INFO\x10\x02\x12\x08\n\x04WARN\
\x10\x03\x12\t\n\x05ERROR\x10\x04\"\x1f\n\x06Output\x12\x0b\n\x07CONSOLE\
\x10\0\x12\x08\n\x04FILE\x10\x01\"\xec\x01\n\x12TunInboundSettings\x12\
\x0e\n\x02fd\x18\x01\x20\x01(\x05R\x02fd\x12\x12\n\x04name\x18\x02\x20\
\x01(\tR\x04name\x12\x18\n\x07address\x18\x03\x20\x01(\tR\x07address\x12\
\x18\n\x07gateway\x18\x04\x20\x01(\tR\x07gateway\x12\x18\n\x07netmask\
\x18\x05\x20\x01(\tR\x07netmask\x12\x10\n\x03mtu\x18\x06\x20\x01(\x05R\
\x03mtu\x12(\n\x10fake_dns_exclude\x18\x07\x20\x03(\tR\x0efakeDnsExclude\
\x12(\n\x10fake_dns_include\x18\x08\x20\x03(\tR\x0efakeDnsInclude\"P\n\
\x1aShadowsocksInboundSettings\x12\x16\n\x06method\x18\x01\x20\x01(\tR\
\x06method\x12\x1a\n\x08password\x18\x02\x20\x01(\tR\x08password\"3\n\
\x15TrojanInboundSettings\x12\x1a\n\x08password\x18\x03\x20\x01(\tR\x08p\
assword\".\n\x18WebSocketInboundSettings\x12\x12\n\x04path\x18\x01\x20\
\x01(\tR\x04path\"-\n\x13AMuxInboundSettings\x12\x16\n\x06actors\x18\x01\
\x20\x03(\tR\x06actors\"`\n\x13QuicInboundSettings\x12\x20\n\x0bcertific\
ate\x18\x01\x20\x01(\tR\x0bcertificate\x12'\n\x0fcertificate_key\x18\x02\
\x20\x01(\tR\x0ecertificateKey\".\n\x14ChainInboundSettings\x12\x16\n\
\x06actors\x18\x01\x20\x03(\tR\x06actors\"\x81\x01\n\x07Inbound\x12\x10\
\n\x03tag\x18\x01\x20\x01(\tR\x03tag\x12\x1a\n\x08protocol\x18\x02\x20\
\x01(\tR\x08protocol\x12\x18\n\x07address\x18\x03\x20\x01(\tR\x07address\
\x12\x12\n\x04port\x18\x04\x20\x01(\rR\x04port\x12\x1a\n\x08settings\x18\
\x05\x20\x01(\x0cR\x08settings\"H\n\x18RedirectOutboundSettings\x12\x18\
\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\x02\
\x20\x01(\rR\x04port\"E\n\x15SocksOutboundSettings\x12\x18\n\x07address\
\x18\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\
\x04port\"\x7f\n\x1bShadowsocksOutboundSettings\x12\x18\n\x07address\x18\
\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04por\
t\x12\x16\n\x06method\x18\x03\x20\x01(\tR\x06method\x12\x1a\n\x08passwor\
d\x18\x04\x20\x01(\tR\x08password\"b\n\x16TrojanOutboundSettings\x12\x18\
\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\x02\
\x20\x01(\rR\x04port\x12\x1a\n\x08password\x18\x03\x20\x01(\tR\x08passwo\
rd\"u\n\x15VMessOutboundSettings\x12\x18\n\x07address\x18\x01\x20\x01(\t\
R\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\x12\x12\n\x04\
uuid\x18\x03\x20\x01(\tR\x04uuid\x12\x1a\n\x08security\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\x04al\
pn\"\xae\x01\n\x19WebSocketOutboundSettings\x12\x12\n\x04path\x18\x01\
\x20\x01(\tR\x04path\x12A\n\x07headers\x18\x02\x20\x03(\x0b2'.WebSocketO\
utboundSettings.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\x15HTTP2OutboundSettings\x12\x12\n\x04path\
\x18\x01\x20\x01(\tR\x04path\x12\x12\n\x04host\x18\x02\x20\x01(\tR\x04ho\
st\"O\n\x16TryAllOutboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\t\
R\x06actors\x12\x1d\n\ndelay_base\x18\x02\x20\x01(\rR\tdelayBase\"0\n\
\x16RandomOutboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06ac\
tors\"\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\x16\n\x06actors\x18\x03\x20\x03(\tR\x06actors\x12\x1f\n\x0bmax_acce\
pts\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\nserverNam\
e\x12\x20\n\x0bcertificate\x18\x04\x20\x01(\tR\x0bcertificate\"/\n\x15Ch\
ainOutboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"K\
\n\x15RetryOutboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06a\
ctors\x12\x1a\n\x08attempts\x18\x02\x20\x01(\rR\x08attempts\"\xa6\x02\n\
\x18FailOverOutboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06\
actors\x12!\n\x0cfail_timeout\x18\x02\x20\x01(\rR\x0bfailTimeout\x12!\n\
\x0chealth_check\x18\x03\x20\x01(\x08R\x0bhealthCheck\x12%\n\x0echeck_in\
terval\x18\x04\x20\x01(\rR\rcheckInterval\x12\x1a\n\x08failover\x18\x05\
\x20\x01(\x08R\x08failover\x12%\n\x0efallback_cache\x18\x06\x20\x01(\x08\
R\rfallbackCache\x12\x1d\n\ncache_size\x18\x07\x20\x01(\rR\tcacheSize\
\x12#\n\rcache_timeout\x18\x08\x20\x01(\rR\x0ccacheTimeout\"0\n\x16Selec\
tOutboundSettings\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\x08pr\
otocol\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\ntarget_tag\x18\x01\x20\x01(\tR\ttar\
getTag\x12-\n\x07domains\x18\x02\x20\x03(\x0b2\x13.RoutingRule.DomainR\
\x07domains\x12\x19\n\x08ip_cidrs\x18\x03\x20\x03(\tR\x07ipCidrs\x12'\n\
\x05mmdbs\x18\x04\x20\x03(\x0b2\x11.RoutingRule.MmdbR\x05mmdbs\x12\x1f\n\
\x0bport_ranges\x18\x05\x20\x03(\tR\nportRanges\x1au\n\x06Domain\x12,\n\
\x04type\x18\x01\x20\x01(\x0e2\x18.RoutingRule.Domain.TypeR\x04type\x12\
\x14\n\x05value\x18\x02\x20\x01(\tR\x05value\"'\n\x04Type\x12\t\n\x05PLA\
IN\x10\0\x12\n\n\x06DOMAIN\x10\x01\x12\x08\n\x04FULL\x10\x02\x1a=\n\x04M\
mdb\x12\x12\n\x04file\x18\x01\x20\x01(\tR\x04file\x12!\n\x0ccountry_code\
\x18\x02\x20\x01(\tR\x0bcountryCode\"\xd2\x01\n\x06Config\x12\x16\n\x03l\
og\x18\x01\x20\x01(\x0b2\x04.LogR\x03log\x12$\n\x08inbounds\x18\x02\x20\
\x03(\x0b2\x08.InboundR\x08inbounds\x12'\n\toutbounds\x18\x03\x20\x03(\
\x0b2\t.OutboundR\toutbounds\x121\n\rrouting_rules\x18\x04\x20\x03(\x0b2\
\x0c.RoutingRuleR\x0croutingRules\x12\x16\n\x03dns\x18\x05\x20\x01(\x0b2\
\x04.DnsR\x03dns\x12\x16\n\x03api\x18\x06\x20\x01(\x0b2\x04.ApiR\x03apib\
\x06proto3\
\x10\0\x12\x08\n\x04FILE\x10\x01\"\x80\x02\n\x12TunInboundSettings\x12\
\x0e\n\x02fd\x18\x01\x20\x01(\x05R\x02fd\x12\x12\n\x04auto\x18\t\x20\x01\
(\x08R\x04auto\x12\x12\n\x04name\x18\x02\x20\x01(\tR\x04name\x12\x18\n\
\x07address\x18\x03\x20\x01(\tR\x07address\x12\x18\n\x07gateway\x18\x04\
\x20\x01(\tR\x07gateway\x12\x18\n\x07netmask\x18\x05\x20\x01(\tR\x07netm\
ask\x12\x10\n\x03mtu\x18\x06\x20\x01(\x05R\x03mtu\x12(\n\x10fake_dns_exc\
lude\x18\x07\x20\x03(\tR\x0efakeDnsExclude\x12(\n\x10fake_dns_include\
\x18\x08\x20\x03(\tR\x0efakeDnsInclude\"P\n\x1aShadowsocksInboundSetting\
s\x12\x16\n\x06method\x18\x01\x20\x01(\tR\x06method\x12\x1a\n\x08passwor\
d\x18\x02\x20\x01(\tR\x08password\"3\n\x15TrojanInboundSettings\x12\x1a\
\n\x08password\x18\x03\x20\x01(\tR\x08password\".\n\x18WebSocketInboundS\
ettings\x12\x12\n\x04path\x18\x01\x20\x01(\tR\x04path\"-\n\x13AMuxInboun\
dSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"`\n\x13Quic\
InboundSettings\x12\x20\n\x0bcertificate\x18\x01\x20\x01(\tR\x0bcertific\
ate\x12'\n\x0fcertificate_key\x18\x02\x20\x01(\tR\x0ecertificateKey\".\n\
\x14ChainInboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06acto\
rs\"\x81\x01\n\x07Inbound\x12\x10\n\x03tag\x18\x01\x20\x01(\tR\x03tag\
\x12\x1a\n\x08protocol\x18\x02\x20\x01(\tR\x08protocol\x12\x18\n\x07addr\
ess\x18\x03\x20\x01(\tR\x07address\x12\x12\n\x04port\x18\x04\x20\x01(\rR\
\x04port\x12\x1a\n\x08settings\x18\x05\x20\x01(\x0cR\x08settings\"H\n\
\x18RedirectOutboundSettings\x12\x18\n\x07address\x18\x01\x20\x01(\tR\
\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\"E\n\x15SocksO\
utboundSettings\x12\x18\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\
\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\"\x7f\n\x1bShadowsocksOutboun\
dSettings\x12\x18\n\x07address\x18\x01\x20\x01(\tR\x07address\x12\x12\n\
\x04port\x18\x02\x20\x01(\rR\x04port\x12\x16\n\x06method\x18\x03\x20\x01\
(\tR\x06method\x12\x1a\n\x08password\x18\x04\x20\x01(\tR\x08password\"b\
\n\x16TrojanOutboundSettings\x12\x18\n\x07address\x18\x01\x20\x01(\tR\
\x07address\x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\x12\x1a\n\x08p\
assword\x18\x03\x20\x01(\tR\x08password\"u\n\x15VMessOutboundSettings\
\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\x04uu\
id\x12\x1a\n\x08security\x18\x04\x20\x01(\tR\x08security\"J\n\x13TlsOutb\
oundSettings\x12\x1f\n\x0bserver_name\x18\x01\x20\x01(\tR\nserverName\
\x12\x12\n\x04alpn\x18\x02\x20\x03(\tR\x04alpn\"\xae\x01\n\x19WebSocketO\
utboundSettings\x12\x12\n\x04path\x18\x01\x20\x01(\tR\x04path\x12A\n\x07\
headers\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\
\x15HTTP2OutboundSettings\x12\x12\n\x04path\x18\x01\x20\x01(\tR\x04path\
\x12\x12\n\x04host\x18\x02\x20\x01(\tR\x04host\"O\n\x16TryAllOutboundSet\
tings\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\x06actors\x18\x01\x20\x03(\tR\x06actors\"\x9f\x01\n\x14AMuxOutbou\
ndSettings\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\x07add\
ress\x12\x12\n\x04port\x18\x02\x20\x01(\rR\x04port\x12\x1f\n\x0bserver_n\
ame\x18\x03\x20\x01(\tR\nserverName\x12\x20\n\x0bcertificate\x18\x04\x20\
\x01(\tR\x0bcertificate\"/\n\x15ChainOutboundSettings\x12\x16\n\x06actor\
s\x18\x01\x20\x03(\tR\x06actors\"K\n\x15RetryOutboundSettings\x12\x16\n\
\x06actors\x18\x01\x20\x03(\tR\x06actors\x12\x1a\n\x08attempts\x18\x02\
\x20\x01(\rR\x08attempts\"\xa6\x02\n\x18FailOverOutboundSettings\x12\x16\
\n\x06actors\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\x0bhealthCheck\x12%\n\x0echeck_interval\x18\x04\x20\x01(\rR\rcheck\
Interval\x12\x1a\n\x08failover\x18\x05\x20\x01(\x08R\x08failover\x12%\n\
\x0efallback_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\x06act\
ors\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\x08pro\
tocol\x12\x12\n\x04bind\x18\x03\x20\x01(\tR\x04bind\x12\x1a\n\x08setting\
s\x18\x04\x20\x01(\x0cR\x08settings\"\xf6\x02\n\x0bRoutingRule\x12\x1d\n\
\ntarget_tag\x18\x01\x20\x01(\tR\ttargetTag\x12-\n\x07domains\x18\x02\
\x20\x03(\x0b2\x13.RoutingRule.DomainR\x07domains\x12\x19\n\x08ip_cidrs\
\x18\x03\x20\x03(\tR\x07ipCidrs\x12'\n\x05mmdbs\x18\x04\x20\x03(\x0b2\
\x11.RoutingRule.MmdbR\x05mmdbs\x12\x1f\n\x0bport_ranges\x18\x05\x20\x03\
(\tR\nportRanges\x1au\n\x06Domain\x12,\n\x04type\x18\x01\x20\x01(\x0e2\
\x18.RoutingRule.Domain.TypeR\x04type\x12\x14\n\x05value\x18\x02\x20\x01\
(\tR\x05value\"'\n\x04Type\x12\t\n\x05PLAIN\x10\0\x12\n\n\x06DOMAIN\x10\
\x01\x12\x08\n\x04FULL\x10\x02\x1a=\n\x04Mmdb\x12\x12\n\x04file\x18\x01\
\x20\x01(\tR\x04file\x12!\n\x0ccountry_code\x18\x02\x20\x01(\tR\x0bcount\
ryCode\"\xd2\x01\n\x06Config\x12\x16\n\x03log\x18\x01\x20\x01(\x0b2\x04.\
LogR\x03log\x12$\n\x08inbounds\x18\x02\x20\x03(\x0b2\x08.InboundR\x08inb\
ounds\x12'\n\toutbounds\x18\x03\x20\x03(\x0b2\t.OutboundR\toutbounds\x12\
1\n\rrouting_rules\x18\x04\x20\x03(\x0b2\x0c.RoutingRuleR\x0croutingRule\
s\x12\x16\n\x03dns\x18\x05\x20\x01(\x0b2\x04.DnsR\x03dns\x12\x16\n\x03ap\
i\x18\x06\x20\x01(\x0b2\x04.ApiR\x03apib\x06proto3\
";
static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT;
+60 -4
View File
@@ -36,6 +36,9 @@ pub mod util;
#[cfg(any(target_os = "ios", target_os = "android"))]
pub mod mobile;
#[cfg(all(feature = "inbound-tun", any(target_os = "macos", target_os = "linux")))]
mod sys;
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
@@ -362,6 +365,7 @@ pub fn start(rt_id: RuntimeId, opts: StartOptions) -> Result<(), Error> {
});
let rt = new_runtime(&opts.runtime_opt)?;
let _g = rt.enter();
#[cfg(target_os = "android")]
if let Some(p) = opts.socket_protect_path.as_ref() {
@@ -385,7 +389,57 @@ pub fn start(rt_id: RuntimeId, opts: StartOptions) -> Result<(), Error> {
let nat_manager = Arc::new(NatManager::new(dispatcher.clone()));
let inbound_manager =
InboundManager::new(&config.inbounds, dispatcher, nat_manager).map_err(Error::Config)?;
runners.append(&mut inbound_manager.get_runners().map_err(Error::Config)?);
let mut inbound_net_runners = inbound_manager
.get_network_runners()
.map_err(Error::Config)?;
runners.append(&mut inbound_net_runners);
#[cfg(all(feature = "inbound-tun", any(target_os = "macos", target_os = "linux")))]
let net_info = if inbound_manager.has_tun_listener() && inbound_manager.tun_auto() {
sys::get_net_info()
} else {
sys::NetInfo::default()
};
#[cfg(any(target_os = "macos", target_os = "linux"))]
if !(&*option::OUTBOUND_INTERFACE).is_empty() {
let mut bind_ips = Vec::new();
for item in (&*option::OUTBOUND_INTERFACE).split(',').map(str::trim) {
if let Ok(ip) = item.parse::<IpAddr>() {
bind_ips.push(ip);
} else {
let all_interfaces = pnet_datalink::interfaces();
if let Some(ifa) = all_interfaces
.iter()
.find(|ifa| ifa.name == item && ifa.is_up() && !ifa.ips.is_empty())
{
let mut ips: Vec<IpAddr> = ifa.ips.iter().map(|ipn| ipn.ip()).collect();
if !ips.is_empty() {
bind_ips.append(&mut ips);
}
}
}
}
if !bind_ips.is_empty() {
rt.block_on(proxy::set_outbound_bind_ips(bind_ips));
}
}
#[cfg(all(
feature = "inbound-tun",
any(
target_os = "ios",
target_os = "android",
target_os = "macos",
target_os = "linux"
)
))]
if let Ok(r) = inbound_manager.get_tun_runner() {
runners.push(r);
}
#[cfg(all(feature = "inbound-tun", any(target_os = "macos", target_os = "linux")))]
sys::post_tun_creation_setup(&net_info);
let runtime_manager = RuntimeManager::new(
#[cfg(feature = "auto-reload")]
@@ -410,9 +464,9 @@ pub fn start(rt_id: RuntimeId, opts: StartOptions) -> Result<(), Error> {
#[cfg(feature = "api")]
{
let listen_addr = if !(&*crate::option::API_LISTEN).is_empty() {
let listen_addr = if !(&*option::API_LISTEN).is_empty() {
Some(
(&*crate::option::API_LISTEN)
(&*option::API_LISTEN)
.parse::<SocketAddr>()
.map_err(|e| Error::Config(anyhow!("parse SocketAddr failed: {}", e)))?,
)
@@ -427,7 +481,6 @@ pub fn start(rt_id: RuntimeId, opts: StartOptions) -> Result<(), Error> {
None
};
if let Some(listen_addr) = listen_addr {
let _g = rt.enter();
let api_server = ApiServer::new(runtime_manager.clone());
runners.push(api_server.serve(listen_addr));
}
@@ -473,6 +526,9 @@ pub fn start(rt_id: RuntimeId, opts: StartOptions) -> Result<(), Error> {
rt.block_on(futures::future::select_all(tasks));
#[cfg(all(feature = "inbound-tun", any(target_os = "macos", target_os = "linux")))]
sys::post_tun_completion_setup(&net_info);
rt.shutdown_background();
log::trace!("leaf shutdown");
+12
View File
@@ -89,6 +89,10 @@ lazy_static! {
};
get_env_var("UNSPECIFIED_BIND_ADDR", default)
};
pub static ref OUTBOUND_INTERFACE: String = {
get_env_var("OUTBOUND_INTERFACE", "".to_string())
};
}
/// UDP session timeout. A UDP session shall be terminated if there are no
@@ -105,3 +109,11 @@ pub static MAX_DNS_RETRIES: usize = 4;
/// Timeout for a DNS query for the built-in DNS client.
pub static DNS_TIMEOUT: u64 = 4;
pub static DEFAULT_TUN_NAME: &str = "utun233";
pub static DEFAULT_TUN_IPV4_ADDR: &str = "240.255.0.2";
pub static DEFAULT_TUN_IPV4_GW: &str = "240.255.0.1";
pub static DEFAULT_TUN_IPV4_MASK: &str = "255.255.255.0";
pub static DEFAULT_TUN_IPV6_ADDR: &str = "2001:2::2";
pub static DEFAULT_TUN_IPV6_GW: &str = "2001:2::1";
pub static DEFAULT_TUN_IPV6_PREFIXLEN: i32 = 64;
+51 -24
View File
@@ -1,16 +1,21 @@
use std::{io, net::SocketAddr};
use std::{
io,
net::{IpAddr, SocketAddr},
};
use async_trait::async_trait;
use futures::future::select_ok;
use futures::stream::Stream;
use futures::TryFutureExt;
use lazy_static::lazy_static;
use log::*;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::{TcpSocket, UdpSocket};
use tokio::sync::Mutex;
#[cfg(target_os = "android")]
use {
lazy_static::lazy_static, std::os::unix::io::AsRawFd, std::os::unix::io::RawFd,
tokio::io::AsyncReadExt, tokio::io::AsyncWriteExt, tokio::net::UnixStream, tokio::sync::Mutex,
std::os::unix::io::AsRawFd, std::os::unix::io::RawFd, tokio::io::AsyncReadExt,
tokio::io::AsyncWriteExt, tokio::net::UnixStream,
};
use crate::{
@@ -111,6 +116,11 @@ lazy_static! {
static ref SOCKET_PROTECT_PATH: Mutex<Option<String>> = Mutex::new(None);
}
lazy_static! {
// TODO split ipv4/ipv6
static ref OUTBOUND_BIND_IPS: Mutex<Option<Vec<IpAddr>>> = Mutex::new(None);
}
// Sets the RPC service endpoint for protecting outbound sockets on Android to
// avoid infinite loop. The `path` is treated as a Unix domain socket endpoint.
// The RPC service simply listens for incoming connections, reads an int32 on
@@ -121,6 +131,10 @@ pub async fn set_socket_protect_path(path: String) {
SOCKET_PROTECT_PATH.lock().await.replace(path);
}
pub async fn set_outbound_bind_ips(ips: Vec<IpAddr>) {
OUTBOUND_BIND_IPS.lock().await.replace(ips);
}
#[cfg(target_os = "android")]
async fn protect_socket(fd: RawFd) -> io::Result<()> {
if let Some(path) = SOCKET_PROTECT_PATH.lock().await.as_ref() {
@@ -136,25 +150,44 @@ async fn protect_socket(fd: RawFd) -> io::Result<()> {
Ok(())
}
async fn get_bind_addr(bind_addr: &SocketAddr, indicator: &SocketAddr) -> SocketAddr {
if let Some(ips) = OUTBOUND_BIND_IPS.lock().await.as_ref() {
match indicator {
SocketAddr::V4(..) => {
if let Some(ip) = ips.iter().find(|ip| ip.is_ipv4()) {
return SocketAddr::new(ip.to_owned(), 0);
}
}
SocketAddr::V6(..) => {
if let Some(ip) = ips.iter().find(|ip| ip.is_ipv6()) {
return SocketAddr::new(ip.to_owned(), 0);
}
}
}
}
if bind_addr.ip().is_unspecified() {
match indicator {
SocketAddr::V4(..) => return "0.0.0.0:0".parse::<SocketAddr>().unwrap(),
SocketAddr::V6(..) => return "[::]:0".parse::<SocketAddr>().unwrap(),
}
}
bind_addr.to_owned()
}
// New UDP socket.
async fn create_udp_socket(
bind_addr: &SocketAddr,
indicator: &SocketAddr,
) -> io::Result<UdpSocket> {
let socket = if bind_addr.ip().is_unspecified() {
match indicator {
SocketAddr::V4(..) => {
UdpSocket::bind("0.0.0.0:0".parse::<SocketAddr>().unwrap()).await?
}
SocketAddr::V6(..) => UdpSocket::bind("[::]:0".parse::<SocketAddr>().unwrap()).await?,
}
} else {
UdpSocket::bind(bind_addr).await?
};
let bind_addr = get_bind_addr(bind_addr, indicator).await;
trace!("udp bind {}", &bind_addr);
let socket = UdpSocket::bind(&bind_addr).await?;
#[cfg(target_os = "android")]
{
protect_socket(socket.as_raw_fd()).await?;
}
Ok(socket)
}
@@ -163,28 +196,22 @@ async fn tcp_dial_task(
dial_addr: SocketAddr,
bind_addr: &SocketAddr,
) -> io::Result<(Box<dyn ProxyStream>, SocketAddr)> {
let bind_addr = get_bind_addr(bind_addr, &dial_addr).await;
let socket = match dial_addr {
SocketAddr::V4(..) => TcpSocket::new_v4()?,
SocketAddr::V6(..) => TcpSocket::new_v6()?,
};
trace!("tcp bind {}", &bind_addr);
socket.bind(bind_addr)?;
#[cfg(target_os = "android")]
{
protect_socket(socket.as_raw_fd()).await?;
}
if bind_addr.ip().is_unspecified() {
match dial_addr {
SocketAddr::V4(..) => socket.bind("0.0.0.0:0".parse::<SocketAddr>().unwrap())?,
SocketAddr::V6(..) => socket.bind("[::]:0".parse::<SocketAddr>().unwrap())?,
}
} else {
socket.bind(*bind_addr)?;
}
trace!("dialing tcp {}", &dial_addr);
trace!("tcp dialing {}", &dial_addr);
let stream = socket.connect(dial_addr).await?;
trace!("connected tcp {}", &dial_addr);
trace!("tcp connected {}", &dial_addr);
Ok((Box::new(SimpleProxyStream(stream)), dial_addr))
}
+26 -3
View File
@@ -13,7 +13,7 @@ use crate::{
app::fake_dns::{FakeDns, FakeDnsMode},
app::nat_manager::NatManager,
config::{Inbound, TunInboundSettings},
Runner,
option, Runner,
};
use super::netstack::NetStack;
@@ -31,6 +31,25 @@ pub fn new(
let mut cfg = tun::Configuration::default();
cfg.raw_fd(settings.fd);
cfg
} else if settings.auto {
let mut cfg = tun::Configuration::default();
cfg.name(option::DEFAULT_TUN_NAME)
.address(option::DEFAULT_TUN_IPV4_ADDR)
.destination(option::DEFAULT_TUN_IPV4_GW)
.mtu(1500);
#[cfg(not(any(
target_arch = "mips",
target_arch = "mips64",
target_arch = "mipsel",
target_arch = "mipsel64",
)))]
{
cfg.netmask(option::DEFAULT_TUN_IPV4_MASK);
}
cfg.up();
cfg
} else {
let mut cfg = tun::Configuration::default();
cfg.name(settings.name)
@@ -66,9 +85,13 @@ pub fn new(
(FakeDnsMode::Exclude, fake_dns_exclude)
};
Ok(Box::pin(async move {
let tun = tun::create_as_async(&cfg).unwrap();
let tun = tun::create_as_async(&cfg).unwrap();
if settings.auto {
assert!(settings.fd == -1, "tun-auto is not compatible with tun-fd");
}
Ok(Box::pin(async move {
let fakedns = Arc::new(TokioMutex::new(FakeDns::new(fake_dns_mode)));
for filter in fake_dns_filters.into_iter() {
+179
View File
@@ -0,0 +1,179 @@
use super::common;
use super::option;
pub struct NetInfo {
pub default_ipv4_gateway: Option<String>,
pub default_ipv6_gateway: Option<String>,
pub default_ipv4_address: Option<String>,
pub default_ipv6_address: Option<String>,
pub default_interface: Option<String>,
}
impl Default for NetInfo {
fn default() -> Self {
Self {
default_ipv4_gateway: None,
default_ipv6_gateway: None,
default_ipv4_address: None,
default_ipv6_address: None,
default_interface: None,
}
}
}
pub fn get_net_info() -> NetInfo {
let iface = common::cmd::get_default_interface().unwrap();
std::env::set_var("OUTBOUND_INTERFACE", iface.clone());
let ipv4_gw = common::cmd::get_default_ipv4_gateway().unwrap();
let ipv6_gw = if *option::ENABLE_IPV6 {
Some(common::cmd::get_default_ipv6_gateway().unwrap())
} else {
None
};
let all_interfaces = pnet_datalink::interfaces();
let ipv4_addr = if let Some(ifa) = all_interfaces
.iter()
.find(|ifa| ifa.name == iface && !ifa.ips.is_empty())
{
if let Some(ipn) = ifa.ips.iter().find(|ipn| ipn.is_ipv4()) {
Some(ipn.ip().to_string())
} else {
None
}
} else {
None
};
let ipv6_addr = if *option::ENABLE_IPV6 {
if let Some(ifa) = all_interfaces
.iter()
.find(|ifa| ifa.name == iface && !ifa.ips.is_empty())
{
if let Some(ipn) = ifa.ips.iter().find(|ipn| ipn.is_ipv6()) {
Some(ipn.ip().to_string())
} else {
None
}
} else {
None
}
} else {
None
};
NetInfo {
default_ipv4_gateway: Some(ipv4_gw),
default_ipv6_gateway: ipv6_gw,
default_ipv4_address: ipv4_addr,
default_ipv6_address: ipv6_addr,
default_interface: Some(iface),
}
}
pub fn post_tun_creation_setup(net_info: &NetInfo) {
if let NetInfo {
default_ipv4_gateway: Some(ipv4_gw),
default_ipv6_gateway: ipv6_gw,
default_ipv4_address: ipv4_addr,
default_ipv6_address: ipv6_addr,
default_interface: Some(iface),
} = net_info
{
use std::net::{Ipv4Addr, Ipv6Addr};
common::cmd::add_interface_ipv4_address(
option::DEFAULT_TUN_NAME,
option::DEFAULT_TUN_IPV4_ADDR.parse::<Ipv4Addr>().unwrap(),
option::DEFAULT_TUN_IPV4_GW.parse::<Ipv4Addr>().unwrap(),
option::DEFAULT_TUN_IPV4_MASK.parse::<Ipv4Addr>().unwrap(),
)
.unwrap();
common::cmd::delete_default_ipv4_route(None).unwrap();
common::cmd::delete_default_ipv4_route(Some(iface.clone())).unwrap();
common::cmd::add_default_ipv4_route(
option::DEFAULT_TUN_IPV4_GW.parse::<Ipv4Addr>().unwrap(),
None,
)
.unwrap();
common::cmd::add_default_ipv4_route(
ipv4_gw.parse::<Ipv4Addr>().unwrap(),
Some(iface.clone()),
)
.unwrap();
#[cfg(target_os = "linux")]
{
if let Some(a) = ipv4_addr {
common::cmd::add_default_ipv4_rule(a.parse::<Ipv4Addr>().unwrap()).unwrap();
}
}
if *option::ENABLE_IPV6 {
if let Some(ipv6_gw) = ipv6_gw {
common::cmd::add_interface_ipv6_address(
option::DEFAULT_TUN_NAME,
option::DEFAULT_TUN_IPV6_ADDR.parse::<Ipv6Addr>().unwrap(),
option::DEFAULT_TUN_IPV6_PREFIXLEN,
)
.unwrap();
common::cmd::delete_default_ipv6_route(None).unwrap();
common::cmd::delete_default_ipv6_route(Some(iface.clone())).unwrap();
common::cmd::add_default_ipv6_route(
option::DEFAULT_TUN_IPV6_GW.parse::<Ipv6Addr>().unwrap(),
None,
)
.unwrap();
common::cmd::add_default_ipv6_route(
ipv6_gw.parse::<Ipv6Addr>().unwrap(),
Some(iface.clone()),
)
.unwrap();
}
#[cfg(target_os = "linux")]
{
if let Some(a) = ipv6_addr {
common::cmd::add_default_ipv6_rule(a.parse::<Ipv6Addr>().unwrap()).unwrap();
}
}
}
}
}
pub fn post_tun_completion_setup(net_info: &NetInfo) {
if let NetInfo {
default_ipv4_gateway: Some(ipv4_gw),
default_ipv6_gateway: ipv6_gw,
default_ipv4_address: ipv4_addr,
default_ipv6_address: ipv6_addr,
default_interface: Some(iface),
} = &net_info
{
use std::net::{Ipv4Addr, Ipv6Addr};
common::cmd::delete_default_ipv4_route(None).unwrap();
common::cmd::delete_default_ipv4_route(Some(iface.clone())).unwrap();
common::cmd::add_default_ipv4_route(ipv4_gw.parse::<Ipv4Addr>().unwrap(), None).unwrap();
#[cfg(target_os = "linux")]
{
if let Some(a) = ipv4_addr {
common::cmd::delete_default_ipv4_rule(a.parse::<Ipv4Addr>().unwrap()).unwrap();
}
}
if *option::ENABLE_IPV6 {
if let Some(ipv6_gw) = ipv6_gw {
common::cmd::delete_default_ipv6_route(None).unwrap();
common::cmd::delete_default_ipv6_route(Some(iface.clone())).unwrap();
common::cmd::add_default_ipv6_route(ipv6_gw.parse::<Ipv6Addr>().unwrap(), None)
.unwrap();
}
#[cfg(target_os = "linux")]
{
if let Some(a) = ipv6_addr {
common::cmd::delete_default_ipv6_rule(a.parse::<Ipv6Addr>().unwrap()).unwrap();
}
}
}
}
}