Skip to content

Commit

Permalink
rucimp: +IpRelayTest1; lua example:+ config_16_tun; fix 3 bugs
Browse files Browse the repository at this point in the history
fix tun auto route direct_list not working bug
fix ws client earlyconn early read bug
fix http header host checking bug
  • Loading branch information
e1732a364fed committed Jan 1, 2099
1 parent ae430e3 commit 1753b1e
Show file tree
Hide file tree
Showing 11 changed files with 166 additions and 28 deletions.
53 changes: 49 additions & 4 deletions resource/local.lua
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ local config_15_tun = {
bind_addr = "ip://10.0.0.1:24#utun321",

-- 自动配置 系统路由 以 代理全局
auto_route = {
in_auto_route = {
tun_dev_name = "utun321",
tun_gateway = "10.0.0.1",
router_ip = "192.168.0.1",
Expand All @@ -551,6 +551,7 @@ local config_15_tun = {
tag = "listen1"
},
},
outbounds = { { tag = "dial1", chain = out_stdio_show_bytes_chain } }

--[[
Expand All @@ -564,12 +565,56 @@ local config_15_tun = {
--]]

outbounds = { { tag = "dial1", chain = out_stdio_show_bytes_chain } }
}

Config = config_15_tun
local config_16_tun = {

---[[
inbounds = {

{
chain = { {
BindDialer = {
bind_addr = "ip://10.0.0.1:24#utun321",

in_auto_route = {
tun_dev_name = "utun321",
tun_gateway = "10.0.0.1",
router_ip = "192.168.0.1",
original_dev_name = "enp0s1",
direct_list = { "192.168.0.226" }, -- 服务端的ip要直连
dns_list = { "114.114.114.114" }
}
}
} },
tag = "listen1"
},
},
outbounds = { {
tag = "dial1",
chain = { {
--OptDialer = { -- 如果自动路由没写 direct_list, 也可以用 OptDialer+ bind_to_device 的方法

BindDialer = {
dial_addr = "tcp://192.168.0.226:10801",
-- sockopt = {
-- bind_to_device = "enp0s1"
-- }
}
}, tlsout, websocket_out, "IpRelayTest1" }
} }

--[[
演示 inbound 是 ip, outbound 是 IpRelayTest1
--]]

}


Config = config_16_tun

--[[
-- 有限动态链的 选择器用法 的基本演示
-- 有限动态链使用 Config 所提供的列表, 在 Dyn_Selectors 中动态地
Expand Down
29 changes: 24 additions & 5 deletions resource/remote.lua
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,16 @@ local in_h2_trojans_chain = { tcp, tls, {
}
}, trojan_in }

local in_quic_chain = { {
local quic_in = {
Quic = {
key_path = "test2.key",
cert_path = "test2.crt",
listen_addr = "127.0.0.1:10801",
listen_addr = "0.0.0.0:10801",
alpn = { "h3" }
}
}, trojan_in }
}

local in_quic_chain = { quic_in, trojan_in }

local dial = {
BindDialer = {
Expand All @@ -118,12 +120,13 @@ local direct_out_chain = { "Direct" }

Config = {
inbounds = { -- { chain = trojan_chain, tag = "listen1"}
{ chain = trojans_chain, tag = "listen1" },
-- { chain = trojans_chain, tag = "listen1" },
-- { chain = ws_trojans_chain, tag = "listen1" }
-- { chain = in_h2_trojans_chain, tag = "listen1" }
-- { chain = in_quic_chain, tag = "listen1" }
-- { chain = socks5http_chain, tag = "listen1"} ,
-- { chain = { unix,tls, trojan_in }, tag = "listen1"} ,
{ chain = { tcp,tls, ws, "IpRelayTest1" }, tag = "listen1"} ,
--[[
{
chain = {{
Expand Down Expand Up @@ -153,7 +156,7 @@ Config = {
} },
-- ]]

---[[
--[[
-- 对应 local.lua 使用 tproxy 的 outbound 配置
-- 如果 用 tproxy 时 direct 不用 opt_direct 设置 somark, 将造成无限回环, 无法联网
Expand All @@ -165,6 +168,22 @@ Config = {
} },
--]]

---[[
-- 对应 local.lua 使用 tun+IpRelayTest1 的 outbound 配置

outbounds = { {
tag = "dial1",
chain = {
{
BindDialer = {
bind_addr = "ip://10.0.0.2:24#utun321",
}
}
}
} },
--]]


-- outbounds = { { tag="dial1", chain = out_stdio_chain } }, --以命令行为出口

fallback_route = { { "listen1", "fallback_d" } }
Expand Down
36 changes: 36 additions & 0 deletions rucimp/src/map/ip.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use async_trait::async_trait;
use macro_map::*;
use ruci::{
map::{self, Map, MapParams, MapResult, ProxyBehavior},
net::{Addr, CID},
Name,
};

#[map_ext_fields]
#[derive(Debug, Clone, Default, MapExt)]
pub struct IpTest1 {}

impl Name for IpTest1 {
fn name(&self) -> &'static str {
"ip_relay_test1"
}
}

#[async_trait]
impl Map for IpTest1 {
async fn maps(&self, _cid: CID, behavior: ProxyBehavior, params: MapParams) -> MapResult {
match behavior {
ProxyBehavior::UNSPECIFIED => panic!("impossible"),
ProxyBehavior::ENCODE => MapResult::builder()
.a(params.a)
.b(params.b)
.c(params.c)
.build(),
ProxyBehavior::DECODE => MapResult::builder()
.a(Some(Addr::from_network_addr_url("ip://0.0.0.0").unwrap()))
.b(params.b)
.c(params.c)
.build(),
}
}
}
2 changes: 2 additions & 0 deletions rucimp/src/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub mod ws;

pub mod quic_common;

pub mod ip;

#[cfg(feature = "quic")]
pub mod quic;

Expand Down
3 changes: 2 additions & 1 deletion rucimp/src/map/ws/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,8 @@ impl AsyncRead for EarlyConn {
) -> Poll<io::Result<()>> {
match &mut self.real_c {
Some(c) => c.as_mut().poll_read(cx, buf),
None => Poll::Ready(Err(io_error("can't poll_read when not established"))),
//None => Poll::Ready(Err(io_error("can't poll_read when not established"))),
None => Poll::Pending,
}
}
}
Expand Down
8 changes: 7 additions & 1 deletion rucimp/src/modes/chain/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use ruci::{
use serde::{Deserialize, Serialize};
use tracing::warn;

use crate::map::ws;
use crate::map::{ip, ws};

#[cfg(all(feature = "sockopt", target_os = "linux"))]
use crate::map::tproxy::{self, TcpResolver};
Expand Down Expand Up @@ -305,6 +305,8 @@ pub enum InMapConfig {
},
#[cfg(any(feature = "quic", feature = "quinn"))]
Quic(crate::map::quic_common::ServerConfig),

IpRelayTest1,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
Expand Down Expand Up @@ -345,6 +347,8 @@ pub enum OutMapConfig {
},
#[cfg(any(feature = "quic", feature = "quinn"))]
Quic(crate::map::quic_common::ClientConfig),

IpRelayTest1,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
Expand Down Expand Up @@ -554,6 +558,7 @@ impl ToMapBox for InMapConfig {
sopt: sockopt.clone(),
ext_fields: ext.as_ref().map(|e| e.to_ext_fields()),
}),
InMapConfig::IpRelayTest1 => Box::<ip::IpTest1>::default(),
}
}
}
Expand Down Expand Up @@ -660,6 +665,7 @@ impl ToMapBox for OutMapConfig {
OutMapConfig::OptDialer(sopt) => {
Box::new(crate::map::opt_net::OptDialer::new(sopt.clone()).expect("ok"))
}
OutMapConfig::IpRelayTest1 => Box::<ip::IpTest1>::default(),
}
}
}
Expand Down
27 changes: 22 additions & 5 deletions rucimp/src/net/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,35 @@ fn test_url() {
assert_ne!(u.authority().unwrap(), u.host().unwrap());
}

pub fn match_request_http_header<'a, T: 'a>(
pub fn match_request_http_header<'a, T: 'a + std::fmt::Debug>(
c: &'a CommonConfig,
r: &'a Request<T>,
) -> Result<(), HttpMatchError<'a>> {
let a = r.uri().authority();
let given_host = if let Some(a) = a { a.as_str() } else { "" };

//debug!("checking {r:?}");

if c.authority != given_host {
return Err(HttpMatchError::InvalidHost {
expected: &c.authority,
found: given_host,
});
if given_host == "" {
let hh = r
.headers()
.get("host")
.map(|x| x.to_str().unwrap_or(""))
.unwrap();

if hh != c.authority {
return Err(HttpMatchError::InvalidHost {
expected: &c.authority,
found: hh,
});
}
} else {
return Err(HttpMatchError::InvalidHost {
expected: &c.authority,
found: given_host,
});
}
}

let given_path = r.uri().path();
Expand Down
3 changes: 2 additions & 1 deletion src/map/network/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,11 @@ impl BindDialer {
#[cfg(feature = "tun")]

pub fn down_route(&mut self) {
debug!("BindDialer down auto route");
let mut mg = self.auto_route_state.lock();
match &*mg {
AutoRouteState::Up(opt_dns_list) => {
debug!("BindDialer down auto route");

let mut params = self.in_auto_route.take().unwrap();
params.dns_list = opt_dns_list.to_owned();
let r = tun::route::in_down_route(&params);
Expand Down
12 changes: 10 additions & 2 deletions src/net/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,9 @@ impl AsyncRead for PrintWrapper {
String::from_utf8_lossy(&slice[..min(sl, 64)])
)
}
Err(_) => {}
Err(e) => {
debug!("PrintWrapper read got e: {e}")
}
},
Poll::Pending => {}
}
Expand All @@ -280,7 +282,13 @@ impl AsyncWrite for PrintWrapper {
String::from_utf8_lossy(&buf[..min(*u, 64)])
)
}
Err(_) => {}
Err(e) => {
debug!(
"PrintWrapper write got e:{} {}, {e}",
buf.len(),
String::from_utf8_lossy(&buf[..min(buf.len(), 64)])
);
}
},
Poll::Pending => {}
};
Expand Down
2 changes: 2 additions & 0 deletions src/net/tun/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ where
"tun: create_bind succeed"
);

// let dev = crate::net::helpers::PrintWrapper::from(Box::new(dev));

Ok(Box::new(dev))
}

Expand Down
19 changes: 10 additions & 9 deletions src/net/tun/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct InAutoRouteParams {
pub dns_list: Option<Vec<String>>,
}

const DEFAULT_ROUTER_IP: &str = "192.168.0.1";
// const DEFAULT_ROUTER_IP: &str = "192.168.0.1";
const DEFAULT_ORIGINAL_DEV_NAME: &str = "enp0s1";

pub fn in_auto_route(params: &InAutoRouteParams) -> anyhow::Result<Option<Vec<String>>> {
Expand All @@ -27,7 +27,7 @@ pub fn in_auto_route(params: &InAutoRouteParams) -> anyhow::Result<Option<Vec<St

let tun_gateway = params.tun_gateway.as_deref().unwrap_or("10.0.0.1");
let tun_dev_name = params.tun_dev_name.as_deref().unwrap_or("utun321");
let router_ip = params.router_ip.as_deref().unwrap_or(DEFAULT_ROUTER_IP);
//let router_ip = params.router_ip.as_deref().unwrap_or(DEFAULT_ROUTER_IP);
let original_dev_name = params
.original_dev_name
.as_deref()
Expand All @@ -37,16 +37,17 @@ pub fn in_auto_route(params: &InAutoRouteParams) -> anyhow::Result<Option<Vec<St
// 因此该命令的成败不影响大局
let _r = utils::run_command("ip", "route del default");

let list = format!(
r#"ip route add default via {tun_gateway} dev {tun_dev_name} metric 1
ip route add default via {router_ip} dev {original_dev_name} metric 10"#,
);
let list =
format!(r#"ip route add default via {tun_gateway} dev {tun_dev_name} metric 1"#,);

//ip route add default via {router_ip} dev {original_dev_name} metric 10

let mut list: Vec<_> = list.split('\n').map(String::from).collect();

if let Some(direct_list) = &params.direct_list {
for v in direct_list.iter() {
list.push(format!(
"ip route add {v} via {router_ip} dev {original_dev_name} metric 10"
"ip route add {v} dev {original_dev_name} metric 100"
))
}
}
Expand Down Expand Up @@ -77,7 +78,7 @@ pub fn in_down_route(params: &InAutoRouteParams) -> anyhow::Result<()> {
info!("tun down auto route for linux...");
let mut list = vec![];

let router_ip = params.router_ip.as_deref().unwrap_or(DEFAULT_ROUTER_IP);
//let router_ip = params.router_ip.as_deref().unwrap_or(DEFAULT_ROUTER_IP);
let original_dev_name = params
.original_dev_name
.as_deref()
Expand All @@ -86,7 +87,7 @@ pub fn in_down_route(params: &InAutoRouteParams) -> anyhow::Result<()> {
if let Some(direct_list) = &params.direct_list {
for v in direct_list {
list.push(format!(
"ip route del {v} via {router_ip} dev {original_dev_name} metric 10"
"ip route del {v} dev {original_dev_name} metric 100"
))
}
}
Expand Down

0 comments on commit 1753b1e

Please sign in to comment.