mirror of
https://github.com/eycorsican/leaf.git
synced 2026-12-06 16:01:29 +00:00
Refactoring according to clippy suggestions
This commit is contained in:
1 parent
11b7426337
commit
705aae52fe
73 files changed
+515
-831
No files matched your search
+52
-54
@@ -10,7 +10,7 @@ fn main() {
|
||||
cc::Build::new()
|
||||
.file("src/proxy/tun/netstack/lwip/core/init.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/def.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/dns.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/dns.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/inet_chksum.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ip.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/mem.c")
|
||||
@@ -18,29 +18,29 @@ fn main() {
|
||||
.file("src/proxy/tun/netstack/lwip/core/netif.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/pbuf.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/raw.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/stats.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/sys.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/stats.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/sys.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/tcp.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/tcp_in.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/tcp_out.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/timeouts.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/udp.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/autoip.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/dhcp.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/etharp.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv4/autoip.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv4/dhcp.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv4/etharp.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/icmp.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/igmp.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv4/igmp.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/ip4_frag.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/ip4.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv4/ip4_addr.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/dhcp6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/ethip6.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv6/dhcp6.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv6/ethip6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/icmp6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/inet6.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv6/inet6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/ip6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/ip6_addr.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/ip6_frag.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/mld6.c")
|
||||
// .file("src/proxy/tun/netstack/lwip/core/ipv6/mld6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/core/ipv6/nd6.c")
|
||||
.file("src/proxy/tun/netstack/lwip/custom/sys_arch.c")
|
||||
.include("src/proxy/tun/netstack/lwip/custom")
|
||||
@@ -50,53 +50,51 @@ fn main() {
|
||||
.compile("liblwip.a");
|
||||
}
|
||||
|
||||
if let Ok(_) = env::var("BINDINGS_GEN") {
|
||||
if os == "ios" || os == "linux" || os == "macos" {
|
||||
println!("cargo:rustc-link-lib=lwip");
|
||||
// println!("cargo:rerun-if-changed=src/proxy/tun/netstack/wrapper.h");
|
||||
println!("cargo:include=src/proxy/tun/netstack/lwip/include");
|
||||
if env::var("BINDINGS_GEN").is_ok() && (os == "ios" || os == "linux" || os == "macos") {
|
||||
println!("cargo:rustc-link-lib=lwip");
|
||||
// println!("cargo:rerun-if-changed=src/proxy/tun/netstack/wrapper.h");
|
||||
println!("cargo:include=src/proxy/tun/netstack/lwip/include");
|
||||
|
||||
let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
|
||||
let os = env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
let bindings = bindgen::Builder::default()
|
||||
.header("src/proxy/tun/netstack/wrapper.h")
|
||||
.clang_arg("-I./src/proxy/tun/netstack/lwip/include")
|
||||
.clang_arg("-I./src/proxy/tun/netstack/lwip/custom")
|
||||
.clang_arg("-Wno-everything")
|
||||
.layout_tests(false)
|
||||
.clang_arg(if arch == "aarch64" && os == "ios" {
|
||||
// https://github.com/rust-lang/rust-bindgen/issues/1211
|
||||
"--target=arm64-apple-ios"
|
||||
} else {
|
||||
""
|
||||
})
|
||||
.clang_arg(if arch == "aarch64" && os == "ios" {
|
||||
// sdk path find by `xcrun --sdk iphoneos --show-sdk-path`
|
||||
let output = Command::new("xcrun")
|
||||
.arg("--sdk")
|
||||
.arg("iphoneos")
|
||||
.arg("--show-sdk-path")
|
||||
.output()
|
||||
.expect("failed to execute xcrun");
|
||||
let inc_path = Path::new(String::from_utf8_lossy(&output.stdout).trim())
|
||||
.join("usr/include");
|
||||
format!("-I{}", inc_path.to_str().expect("invalid include path"))
|
||||
} else {
|
||||
"".to_string()
|
||||
})
|
||||
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
|
||||
.generate()
|
||||
.expect("Unable to generate bindings");
|
||||
let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
|
||||
let os = env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
let bindings = bindgen::Builder::default()
|
||||
.header("src/proxy/tun/netstack/wrapper.h")
|
||||
.clang_arg("-I./src/proxy/tun/netstack/lwip/include")
|
||||
.clang_arg("-I./src/proxy/tun/netstack/lwip/custom")
|
||||
.clang_arg("-Wno-everything")
|
||||
.layout_tests(false)
|
||||
.clang_arg(if arch == "aarch64" && os == "ios" {
|
||||
// https://github.com/rust-lang/rust-bindgen/issues/1211
|
||||
"--target=arm64-apple-ios"
|
||||
} else {
|
||||
""
|
||||
})
|
||||
.clang_arg(if arch == "aarch64" && os == "ios" {
|
||||
// sdk path find by `xcrun --sdk iphoneos --show-sdk-path`
|
||||
let output = Command::new("xcrun")
|
||||
.arg("--sdk")
|
||||
.arg("iphoneos")
|
||||
.arg("--show-sdk-path")
|
||||
.output()
|
||||
.expect("failed to execute xcrun");
|
||||
let inc_path =
|
||||
Path::new(String::from_utf8_lossy(&output.stdout).trim()).join("usr/include");
|
||||
format!("-I{}", inc_path.to_str().expect("invalid include path"))
|
||||
} else {
|
||||
"".to_string()
|
||||
})
|
||||
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
|
||||
.generate()
|
||||
.expect("Unable to generate bindings");
|
||||
|
||||
let mut out_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
|
||||
out_path = out_path.join("src/proxy/tun/netstack");
|
||||
bindings
|
||||
.write_to_file(out_path.join("bindings.rs"))
|
||||
.expect("Couldn't write bindings!");
|
||||
}
|
||||
let mut out_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
|
||||
out_path = out_path.join("src/proxy/tun/netstack");
|
||||
bindings
|
||||
.write_to_file(out_path.join("bindings.rs"))
|
||||
.expect("Couldn't write bindings!");
|
||||
}
|
||||
|
||||
if let Ok(_) = env::var("PROTO_GEN") {
|
||||
if env::var("PROTO_GEN").is_ok() {
|
||||
// println!("cargo:rerun-if-changed=src/config/internal/config.proto");
|
||||
protoc_rust::Codegen::new()
|
||||
.out_dir("src/config/internal")
|
||||
|
||||
+31
-48
@@ -86,7 +86,7 @@ where
|
||||
continue;
|
||||
}
|
||||
let sbuf = &sbuf[2 + cipher_suite_bytes..];
|
||||
if sbuf.len() < 1 {
|
||||
if sbuf.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let compression_method_bytes = sbuf[0] as usize;
|
||||
@@ -102,7 +102,7 @@ where
|
||||
continue;
|
||||
}
|
||||
let mut sbuf = &sbuf[2..2 + extensions_bytes];
|
||||
while sbuf.len() > 0 {
|
||||
while !sbuf.is_empty() {
|
||||
// extension + extension-specific-len
|
||||
if sbuf.len() < 4 {
|
||||
continue 'outer;
|
||||
@@ -125,7 +125,7 @@ where
|
||||
continue 'outer;
|
||||
}
|
||||
// just make sure no oob
|
||||
if ebuf.len() < 1 {
|
||||
if ebuf.is_empty() {
|
||||
continue 'outer;
|
||||
}
|
||||
let entry_type = ebuf[0];
|
||||
@@ -282,7 +282,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn log_tcp(tag: &String, tag_color: colored::Color, handshake_time: u128, addr: &SocksAddr) {
|
||||
fn log_tcp(tag: &str, tag_color: colored::Color, handshake_time: u128, addr: &SocksAddr) {
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
{
|
||||
info!(
|
||||
@@ -299,7 +299,7 @@ fn log_tcp(tag: &String, tag_color: colored::Color, handshake_time: u128, addr:
|
||||
}
|
||||
}
|
||||
|
||||
fn log_udp(tag: &String, tag_color: colored::Color, handshake_time: u128, addr: &SocksAddr) {
|
||||
fn log_udp(tag: &str, tag_color: colored::Color, handshake_time: u128, addr: &SocksAddr) {
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
{
|
||||
info!(
|
||||
@@ -359,15 +359,12 @@ impl Dispatcher {
|
||||
}
|
||||
|
||||
async fn dispatch_endpoint_tcp_done(&self) {
|
||||
match self.endpoint_tcp_rx.lock().await.try_recv() {
|
||||
Ok(_) => {
|
||||
*self.num_endpoint_tcp.lock().await -= 1;
|
||||
debug!(
|
||||
"active proxied tcp connections -1: {}",
|
||||
self.num_endpoint_tcp.lock().await
|
||||
);
|
||||
}
|
||||
Err(_) => (),
|
||||
if self.endpoint_tcp_rx.lock().await.try_recv().is_ok() {
|
||||
*self.num_endpoint_tcp.lock().await -= 1;
|
||||
debug!(
|
||||
"active proxied tcp connections -1: {}",
|
||||
self.num_endpoint_tcp.lock().await
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,15 +384,12 @@ impl Dispatcher {
|
||||
}
|
||||
|
||||
async fn dispatch_direct_tcp_done(&self) {
|
||||
match self.direct_tcp_rx.lock().await.try_recv() {
|
||||
Ok(_) => {
|
||||
*self.num_direct_tcp.lock().await -= 1;
|
||||
debug!(
|
||||
"active direct tcp connections -1: {}",
|
||||
self.num_direct_tcp.lock().await
|
||||
);
|
||||
}
|
||||
Err(_) => (),
|
||||
if self.direct_tcp_rx.lock().await.try_recv().is_ok() {
|
||||
*self.num_direct_tcp.lock().await -= 1;
|
||||
debug!(
|
||||
"active direct tcp connections -1: {}",
|
||||
self.num_direct_tcp.lock().await
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,12 +401,9 @@ impl Dispatcher {
|
||||
Box::new(SimpleStream(lhs))
|
||||
} else {
|
||||
let mut lhs = SniffingStream::new(lhs);
|
||||
match lhs.sniff().await? {
|
||||
Some(domain) => {
|
||||
debug!("sniffed domain {}", &domain);
|
||||
sess.destination = SocksAddr::from((domain, sess.destination.port()));
|
||||
}
|
||||
None => (),
|
||||
if let Some(domain) = lhs.sniff().await? {
|
||||
debug!("sniffed domain {}", &domain);
|
||||
sess.destination = SocksAddr::from((domain, sess.destination.port()));
|
||||
}
|
||||
Box::new(SimpleStream(lhs))
|
||||
};
|
||||
@@ -421,9 +412,7 @@ impl Dispatcher {
|
||||
Ok(tag) => {
|
||||
debug!(
|
||||
"picked route [{}] for {} -> {}",
|
||||
tag,
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.destination
|
||||
tag, &sess.source, &sess.destination
|
||||
);
|
||||
tag
|
||||
}
|
||||
@@ -432,9 +421,7 @@ impl Dispatcher {
|
||||
if let Some(tag) = self.handler_manager.default_handler() {
|
||||
debug!(
|
||||
"picked default route [{}] for {} -> {}",
|
||||
tag,
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.destination
|
||||
tag, &sess.source, &sess.destination
|
||||
);
|
||||
tag
|
||||
} else {
|
||||
@@ -513,7 +500,7 @@ impl Dispatcher {
|
||||
Ok(up_n) => {
|
||||
debug!(
|
||||
"tcp uplink {} -> {} done, {} bytes transfered [{}]",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
up_n,
|
||||
&h.tag(),
|
||||
@@ -522,7 +509,7 @@ impl Dispatcher {
|
||||
Err(e) => {
|
||||
debug!(
|
||||
"tcp uplink {} -> {} error: {} [{}]",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
e,
|
||||
&h.tag()
|
||||
@@ -533,7 +520,7 @@ impl Dispatcher {
|
||||
Ok(down_n) => {
|
||||
debug!(
|
||||
"tcp downlink {} <- {} done, {} bytes transfered [{}]",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
down_n,
|
||||
&h.tag(),
|
||||
@@ -542,7 +529,7 @@ impl Dispatcher {
|
||||
Err(e) => {
|
||||
debug!(
|
||||
"tcp downlink {} <- {} error: {} [{}]",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
e,
|
||||
&h.tag()
|
||||
@@ -553,7 +540,7 @@ impl Dispatcher {
|
||||
Err(e) => {
|
||||
debug!(
|
||||
"tcp link {} <-> {} interrupted: {} [{}]",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
e,
|
||||
&h.tag()
|
||||
@@ -573,7 +560,7 @@ impl Dispatcher {
|
||||
Err(e) => {
|
||||
debug!(
|
||||
"dispatch tcp {} -> {} to [{}] failed: {}",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
&h.tag(),
|
||||
e
|
||||
@@ -600,9 +587,7 @@ impl Dispatcher {
|
||||
Ok(tag) => {
|
||||
debug!(
|
||||
"picked route [{}] for {} -> {}",
|
||||
tag,
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.destination
|
||||
tag, &sess.source, &sess.destination
|
||||
);
|
||||
tag
|
||||
}
|
||||
@@ -611,9 +596,7 @@ impl Dispatcher {
|
||||
if let Some(tag) = self.handler_manager.default_handler() {
|
||||
debug!(
|
||||
"picked default route [{}] for {} -> {}",
|
||||
tag,
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.destination
|
||||
tag, &sess.source, &sess.destination
|
||||
);
|
||||
tag
|
||||
} else {
|
||||
@@ -634,7 +617,7 @@ impl Dispatcher {
|
||||
Err(e) => {
|
||||
debug!(
|
||||
"dispatch udp {} -> {} to [{}] failed: {}",
|
||||
&sess.source.unwrap_or("0.0.0.0:0".parse().unwrap()),
|
||||
&sess.source,
|
||||
&sess.destination,
|
||||
&h.tag(),
|
||||
e
|
||||
|
||||
@@ -59,7 +59,7 @@ impl HandlerManager {
|
||||
dns_servers.push(SocketAddr::new(ip, 53));
|
||||
}
|
||||
}
|
||||
if dns_servers.len() == 0 {
|
||||
if dns_servers.is_empty() {
|
||||
panic!("no dns servers");
|
||||
}
|
||||
let bind_addr = {
|
||||
@@ -448,8 +448,7 @@ impl HandlerManager {
|
||||
actors.push(a.clone());
|
||||
}
|
||||
}
|
||||
if actors.len() == 0 {
|
||||
// warn!("no actors in [{}] outbound", &tag);
|
||||
if actors.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tcp = Box::new(tryall::TcpHandler {
|
||||
@@ -491,8 +490,7 @@ impl HandlerManager {
|
||||
actors.push(a.clone());
|
||||
}
|
||||
}
|
||||
if actors.len() == 0 {
|
||||
// warn!("no actors in [{}] outbound", &tag);
|
||||
if actors.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tcp = Box::new(random::TcpHandler {
|
||||
@@ -530,8 +528,7 @@ impl HandlerManager {
|
||||
actors.push(a.clone());
|
||||
}
|
||||
}
|
||||
if actors.len() == 0 {
|
||||
// warn!("no actors in [{}] outbound", &tag);
|
||||
if actors.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tcp = Box::new(failover::TcpHandler::new(
|
||||
@@ -579,8 +576,7 @@ impl HandlerManager {
|
||||
actors.push(a.clone());
|
||||
}
|
||||
}
|
||||
if actors.len() == 0 {
|
||||
// warn!("no actors in [{}] outbound", &tag);
|
||||
if actors.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tcp = Box::new(chain::TcpHandler {
|
||||
@@ -623,7 +619,7 @@ impl HandlerManager {
|
||||
self.handlers.insert(tag, handler);
|
||||
}
|
||||
|
||||
pub fn get(&self, tag: &String) -> Option<&Arc<dyn ProxyHandler>> {
|
||||
pub fn get(&self, tag: &str) -> Option<&Arc<dyn ProxyHandler>> {
|
||||
self.handlers.get(tag)
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Condition for MmdbMatcher {
|
||||
if let Ok(country) = self.reader.lookup::<Country>(ip) {
|
||||
if let Some(country) = country.country {
|
||||
if let Some(iso_code) = country.iso_code {
|
||||
if &iso_code.to_lowercase() == &self.country_code.to_lowercase() {
|
||||
if iso_code.to_lowercase() == self.country_code.to_lowercase() {
|
||||
debug!("[{}] matches geoip code [{}]", ip, &self.country_code);
|
||||
return true;
|
||||
}
|
||||
@@ -140,14 +140,14 @@ impl DomainSuffixMatcher {
|
||||
// video.google.com vs google.com -> true
|
||||
// video.google.com vs gle.com -> false
|
||||
// google.com vs video.google.com -> false
|
||||
fn is_sub_domain(d1: &String, d2: &String) -> bool {
|
||||
fn is_sub_domain(d1: &str, d2: &str) -> bool {
|
||||
let d1_parts: Vec<&str> = d1.split('.').rev().collect();
|
||||
let d2_parts: Vec<&str> = d2.split('.').rev().collect();
|
||||
if d1_parts.len() < d2_parts.len() {
|
||||
return false;
|
||||
}
|
||||
let mut d2_enum = d2_parts.iter().enumerate();
|
||||
while let Some((i, v)) = d2_enum.next() {
|
||||
let d2_enum = d2_parts.iter().enumerate();
|
||||
for (i, v) in d2_enum {
|
||||
if &d1_parts[i] != v {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ impl DnsClient {
|
||||
|
||||
async fn query_task(
|
||||
request: Box<[u8]>,
|
||||
domain: &String,
|
||||
domain: &str,
|
||||
server: &SocketAddr,
|
||||
bind_addr: &SocketAddr,
|
||||
) -> Result<Vec<IpAddr>> {
|
||||
@@ -92,14 +92,11 @@ impl DnsClient {
|
||||
let mut addrs = Vec::new();
|
||||
for ans in resp.answers() {
|
||||
// TODO checks?
|
||||
match ans.rdata() {
|
||||
RData::A(addr) => {
|
||||
addrs.push(IpAddr::V4(addr.to_owned()));
|
||||
}
|
||||
_ => (),
|
||||
if let RData::A(addr) = ans.rdata() {
|
||||
addrs.push(IpAddr::V4(addr.to_owned()));
|
||||
}
|
||||
}
|
||||
if addrs.len() > 0 {
|
||||
if !addrs.is_empty() {
|
||||
let elapsed = tokio::time::Instant::now().duration_since(start);
|
||||
debug!(
|
||||
"return {} ips for {} from {} in {}ms",
|
||||
@@ -157,7 +154,7 @@ impl DnsClient {
|
||||
|
||||
let mut msg = Message::new();
|
||||
|
||||
let mut fqdn = String::from(domain.clone());
|
||||
let mut fqdn = domain.clone();
|
||||
fqdn.push('.');
|
||||
let name = match Name::from_str(&fqdn) {
|
||||
Ok(n) => n,
|
||||
|
||||
@@ -39,7 +39,7 @@ impl FakeDns {
|
||||
self.exclude_domains.push(domain);
|
||||
}
|
||||
|
||||
fn allocate_ip(&mut self, domain: &String) -> Ipv4Addr {
|
||||
fn allocate_ip(&mut self, domain: &str) -> Ipv4Addr {
|
||||
self.map.insert(self.cursor, domain.to_owned());
|
||||
let ip = Self::u32_to_ip(self.cursor);
|
||||
self.cursor += 1;
|
||||
@@ -63,7 +63,7 @@ impl FakeDns {
|
||||
pub fn generate_fake_response(&mut self, request: &[u8]) -> Result<Vec<u8>> {
|
||||
let req = Message::from_vec(request)?;
|
||||
|
||||
if req.queries().len() == 0 {
|
||||
if req.queries().is_empty() {
|
||||
return Err(anyhow!("no queries in this DNS request"));
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ impl FakeDns {
|
||||
.set_checking_disabled(req.checking_disabled());
|
||||
}
|
||||
resp.set_response_code(ResponseCode::NoError);
|
||||
if req.queries().len() > 0 {
|
||||
if !req.queries().is_empty() {
|
||||
resp.add_query(query.clone());
|
||||
}
|
||||
|
||||
@@ -135,11 +135,7 @@ impl FakeDns {
|
||||
_ => return false,
|
||||
};
|
||||
let ip = Self::ip_to_u32(ip);
|
||||
if ip >= self.min_cursor && ip <= self.max_cursor {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
ip >= self.min_cursor && ip <= self.max_cursor
|
||||
}
|
||||
|
||||
fn u32_to_ip(ip: u32) -> Ipv4Addr {
|
||||
@@ -151,6 +147,12 @@ impl FakeDns {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FakeDns {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -19,7 +19,7 @@ impl AtomicMutex {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_lock<'a>(&'a self) -> Result<AtomicMutexGuard<'a>, AtomicMutexErr> {
|
||||
pub fn try_lock(&self) -> Result<AtomicMutexGuard<'_>, AtomicMutexErr> {
|
||||
if self.locked.swap(true, Acquire) {
|
||||
Err(AtomicMutexErr)
|
||||
} else {
|
||||
@@ -27,7 +27,7 @@ impl AtomicMutex {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lock<'a>(&'a self) -> AtomicMutexGuard<'a> {
|
||||
pub fn lock(&self) -> AtomicMutexGuard<'_> {
|
||||
loop {
|
||||
if let Ok(m) = self.try_lock() {
|
||||
break m;
|
||||
@@ -36,6 +36,12 @@ impl AtomicMutex {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AtomicMutex {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for AtomicMutex {}
|
||||
|
||||
unsafe impl Sync for AtomicMutex {}
|
||||
|
||||
@@ -15,7 +15,7 @@ impl Resolver {
|
||||
pub async fn new<'a>(
|
||||
client: Arc<DnsClient>,
|
||||
bind_addr: &'a SocketAddr,
|
||||
address: &'a String,
|
||||
address: &'a str,
|
||||
port: &'a u16,
|
||||
) -> Result<Self> {
|
||||
let mut ips = client
|
||||
@@ -24,7 +24,7 @@ impl Resolver {
|
||||
.await?;
|
||||
ips.reverse();
|
||||
Ok(Resolver {
|
||||
ips: ips,
|
||||
ips,
|
||||
port: port.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -137,12 +137,10 @@ fn remove_comments(text: &str) -> Cow<str> {
|
||||
re.replace(text, "")
|
||||
}
|
||||
|
||||
fn get_section<'a>(text: &'a str) -> Option<&'a str> {
|
||||
fn get_section(text: &str) -> Option<&str> {
|
||||
let re = Regex::new(r"^\s*\[\s*([^\]]*)\s*\]\s*$").unwrap();
|
||||
let caps = re.captures(text);
|
||||
if caps.is_none() {
|
||||
return None;
|
||||
}
|
||||
caps.as_ref()?;
|
||||
Some(caps.unwrap().get(1).unwrap().as_str())
|
||||
}
|
||||
|
||||
@@ -161,7 +159,7 @@ where
|
||||
}
|
||||
if curr_sect.as_str() == section {
|
||||
let line = line.trim();
|
||||
if line.len() > 0 {
|
||||
if !line.is_empty() {
|
||||
new_lines.push(line.to_string());
|
||||
}
|
||||
}
|
||||
@@ -176,11 +174,11 @@ where
|
||||
let mut items = Vec::new();
|
||||
for item in text.trim().split(pat) {
|
||||
let item = item.trim();
|
||||
if item.len() > 0 {
|
||||
if !item.is_empty() {
|
||||
items.push(item.to_string());
|
||||
}
|
||||
}
|
||||
if items.len() > 0 {
|
||||
if !items.is_empty() {
|
||||
Some(items)
|
||||
} else {
|
||||
None
|
||||
@@ -189,7 +187,7 @@ where
|
||||
|
||||
fn get_string(text: &str) -> Option<String> {
|
||||
let s = text.trim();
|
||||
if s.len() > 0 {
|
||||
if !s.is_empty() {
|
||||
Some(s.to_string())
|
||||
} else {
|
||||
None
|
||||
@@ -200,7 +198,7 @@ fn get_value<T>(text: &str) -> Option<T>
|
||||
where
|
||||
T: std::str::FromStr,
|
||||
{
|
||||
if text.trim().len() > 0 {
|
||||
if !text.trim().is_empty() {
|
||||
if let Ok(v) = text.trim().parse::<T>() {
|
||||
return Some(v);
|
||||
}
|
||||
@@ -271,7 +269,7 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
}
|
||||
let mut proxy = Proxy::default();
|
||||
let tag = parts[0].trim();
|
||||
if tag.len() == 0 {
|
||||
if tag.is_empty() {
|
||||
// empty tag is not allowed
|
||||
continue;
|
||||
}
|
||||
@@ -281,7 +279,7 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if params.len() == 0 {
|
||||
if params.is_empty() {
|
||||
// there must be at least one param, i.e. the protocol field
|
||||
continue;
|
||||
}
|
||||
@@ -296,7 +294,7 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
}
|
||||
let k = parts[0].trim();
|
||||
let v = parts[1].trim();
|
||||
if k.len() == 0 || v.len() == 0 {
|
||||
if k.is_empty() || v.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match k {
|
||||
@@ -357,12 +355,9 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
};
|
||||
proxy.port = Some(port);
|
||||
|
||||
match proxy.protocol.as_str() {
|
||||
// compat
|
||||
"ss" => {
|
||||
proxy.protocol = "shadowsocks".to_string();
|
||||
}
|
||||
_ => {}
|
||||
// compat
|
||||
if let "ss" = proxy.protocol.as_str() {
|
||||
proxy.protocol = "shadowsocks".to_string();
|
||||
}
|
||||
|
||||
proxies.push(proxy);
|
||||
@@ -377,7 +372,7 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
}
|
||||
let mut group = ProxyGroup::default();
|
||||
let tag = parts[0].trim();
|
||||
if tag.len() == 0 {
|
||||
if tag.is_empty() {
|
||||
// empty tag is not allowed
|
||||
continue;
|
||||
}
|
||||
@@ -387,14 +382,14 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if params.len() == 0 {
|
||||
if params.is_empty() {
|
||||
// there must be at least one param, i.e. the protocol field
|
||||
continue;
|
||||
}
|
||||
group.protocol = params[0].clone();
|
||||
|
||||
let params = ¶ms[1..];
|
||||
if params.len() == 0 {
|
||||
if params.is_empty() {
|
||||
// require at least one proxy
|
||||
continue;
|
||||
}
|
||||
@@ -403,12 +398,12 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
for param in params {
|
||||
if !param.contains('=') {
|
||||
let actor = param.trim();
|
||||
if actor.len() > 0 {
|
||||
if !actor.is_empty() {
|
||||
actors.push(actor.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if actors.len() == 0 {
|
||||
if actors.is_empty() {
|
||||
// require at least one actor
|
||||
continue;
|
||||
}
|
||||
@@ -422,7 +417,7 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
|
||||
}
|
||||
let k = parts[0].trim();
|
||||
let v = parts[1].trim();
|
||||
if k.len() == 0 || v.len() == 0 {
|
||||
if k.is_empty() || v.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match k {
|
||||
@@ -750,10 +745,10 @@ pub fn to_internal(conf: Config) -> Result<internal::Config> {
|
||||
let mut chain_outbound = internal::Outbound::new();
|
||||
chain_outbound.tag = ext_proxy.tag.clone();
|
||||
let mut chain_settings = internal::ChainOutboundSettings::new();
|
||||
if ext_proxy.tls.unwrap() == true {
|
||||
if ext_proxy.tls.unwrap() {
|
||||
chain_settings.actors.push(tls_outbound.tag.clone());
|
||||
}
|
||||
if ext_proxy.ws.unwrap() == true {
|
||||
if ext_proxy.ws.unwrap() {
|
||||
chain_settings.actors.push(ws_outbound.tag.clone());
|
||||
}
|
||||
chain_settings.actors.push(outbound.tag.clone());
|
||||
@@ -764,10 +759,10 @@ pub fn to_internal(conf: Config) -> Result<internal::Config> {
|
||||
// always push chain first, in case there isn't final rule,
|
||||
// the chain outbound will be the default one to use
|
||||
outbounds.push(chain_outbound);
|
||||
if ext_proxy.tls.unwrap() == true {
|
||||
if ext_proxy.tls.unwrap() {
|
||||
outbounds.push(tls_outbound);
|
||||
}
|
||||
if ext_proxy.ws.unwrap() == true {
|
||||
if ext_proxy.ws.unwrap() {
|
||||
outbounds.push(ws_outbound);
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
@@ -824,10 +819,10 @@ pub fn to_internal(conf: Config) -> Result<internal::Config> {
|
||||
let mut chain_outbound = internal::Outbound::new();
|
||||
chain_outbound.tag = ext_proxy.tag.clone();
|
||||
let mut chain_settings = internal::ChainOutboundSettings::new();
|
||||
if ext_proxy.tls.unwrap() == true {
|
||||
if ext_proxy.tls.unwrap() {
|
||||
chain_settings.actors.push(tls_outbound.tag.clone());
|
||||
}
|
||||
if ext_proxy.ws.unwrap() == true {
|
||||
if ext_proxy.ws.unwrap() {
|
||||
chain_settings.actors.push(ws_outbound.tag.clone());
|
||||
}
|
||||
chain_settings.actors.push(outbound.tag.clone());
|
||||
@@ -838,10 +833,10 @@ pub fn to_internal(conf: Config) -> Result<internal::Config> {
|
||||
// always push chain first, in case there isn't final rule,
|
||||
// the chain outbound will be the default one to use
|
||||
outbounds.push(chain_outbound);
|
||||
if ext_proxy.tls.unwrap() == true {
|
||||
if ext_proxy.tls.unwrap() {
|
||||
outbounds.push(tls_outbound);
|
||||
}
|
||||
if ext_proxy.ws.unwrap() == true {
|
||||
if ext_proxy.ws.unwrap() {
|
||||
outbounds.push(ws_outbound);
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
|
||||
@@ -8,7 +8,7 @@ use anyhow::Result;
|
||||
|
||||
use super::{geosite, internal};
|
||||
|
||||
pub fn load_file_or_default(filter: &String, default: &str) -> Result<(String, String)> {
|
||||
pub fn load_file_or_default(filter: &str, default: &str) -> Result<(String, String)> {
|
||||
let parts: Vec<&str> = filter.split(':').collect();
|
||||
let (file, code) = if parts.len() == 3 {
|
||||
let path = if Path::new(parts[1]).is_absolute() {
|
||||
@@ -31,17 +31,17 @@ pub fn load_file_or_default(filter: &String, default: &str) -> Result<(String, S
|
||||
Ok((file, code))
|
||||
}
|
||||
|
||||
pub fn load_mmdb_rule(filter: &String) -> Result<(String, String)> {
|
||||
pub fn load_mmdb_rule(filter: &str) -> Result<(String, String)> {
|
||||
load_file_or_default(filter, "geo.mmdb")
|
||||
}
|
||||
|
||||
pub fn load_site_rule(filter: &String) -> Result<(String, String)> {
|
||||
pub fn load_site_rule(filter: &str) -> Result<(String, String)> {
|
||||
load_file_or_default(filter, "site.dat")
|
||||
}
|
||||
|
||||
pub fn add_external_rule(
|
||||
rule: &mut internal::RoutingRule,
|
||||
ext_external: &String,
|
||||
ext_external: &str,
|
||||
site_group_lists: &mut HashMap<String, geosite::SiteGroupList>,
|
||||
) -> Result<()> {
|
||||
if ext_external.starts_with("mmdb") {
|
||||
|
||||
@@ -17,16 +17,15 @@ pub use internal::*;
|
||||
|
||||
pub fn from_file(path: &str) -> Result<internal::Config> {
|
||||
if let Some(ext) = Path::new(path).extension() {
|
||||
match ext.to_str() {
|
||||
Some(ext) => match ext {
|
||||
if let Some(ext) = ext.to_str() {
|
||||
match ext {
|
||||
#[cfg(feature = "json")]
|
||||
"json" => return json::from_file(path),
|
||||
#[cfg(feature = "conf")]
|
||||
"conf" => return conf::from_file(path),
|
||||
_ => (),
|
||||
},
|
||||
None => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("config files use extension .json or .conf"));
|
||||
Err(anyhow!("config files use extension .json or .conf"))
|
||||
}
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "chain";
|
||||
pub static NAME: &str = "chain";
|
||||
@@ -18,7 +18,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -76,6 +76,6 @@ impl ProxyTcpHandler for Handler {
|
||||
return Ok(Box::new(SimpleStream(stream)));
|
||||
}
|
||||
}
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid chain"));
|
||||
Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid chain"))
|
||||
}
|
||||
}
|
||||
+27
-39
@@ -34,17 +34,11 @@ impl AsyncRead for DatagramToStream {
|
||||
let mut recv = self.get_mut().recv.recv_from(buf);
|
||||
match recv.as_mut().poll(cx) {
|
||||
Poll::Ready(res) => match res {
|
||||
Ok((n, _)) => {
|
||||
return Poll::Ready(Ok(n));
|
||||
}
|
||||
Err(e) => {
|
||||
return Poll::Ready(Err(e));
|
||||
}
|
||||
Ok((n, _)) => Poll::Ready(Ok(n)),
|
||||
Err(e) => Poll::Ready(Err(e)),
|
||||
},
|
||||
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,12 +49,10 @@ impl AsyncWrite for DatagramToStream {
|
||||
let mut send = me.send.send_to(buf, &me.target);
|
||||
match send.as_mut().poll(cx) {
|
||||
Poll::Ready(res) => match res {
|
||||
Ok(n) => {
|
||||
return Poll::Ready(Ok(n));
|
||||
}
|
||||
Err(e) => return Poll::Ready(Err(e)),
|
||||
Ok(n) => Poll::Ready(Ok(n)),
|
||||
Err(e) => Poll::Ready(Err(e)),
|
||||
},
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<io::Result<()>> {
|
||||
@@ -79,7 +71,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -161,35 +153,31 @@ impl ProxyUdpHandler for Handler {
|
||||
}
|
||||
}
|
||||
// if all actors are Packet transports, simply chaining the datagrams.
|
||||
match transport_type {
|
||||
UdpTransportType::Packet => {
|
||||
let mut bind_addr: SocketAddr =
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);
|
||||
for a in self.actors.iter() {
|
||||
if let Some((_, _, baddr)) = a.udp_connect_addr() {
|
||||
bind_addr = baddr;
|
||||
}
|
||||
if let UdpTransportType::Packet = transport_type {
|
||||
let mut bind_addr: SocketAddr =
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);
|
||||
for a in self.actors.iter() {
|
||||
if let Some((_, _, baddr)) = a.udp_connect_addr() {
|
||||
bind_addr = baddr;
|
||||
}
|
||||
let socket = UdpSocket::bind(bind_addr).await?;
|
||||
let mut dgram: Box<dyn ProxyDatagram> = Box::new(SimpleDatagram(socket));
|
||||
}
|
||||
let socket = UdpSocket::bind(bind_addr).await?;
|
||||
let mut dgram: Box<dyn ProxyDatagram> = Box::new(SimpleDatagram(socket));
|
||||
|
||||
for (i, a) in self.actors.iter().enumerate() {
|
||||
let mut new_sess = sess.clone();
|
||||
for j in (i + 1)..self.actors.len() {
|
||||
if let Some((connect_addr, port, _)) = self.actors[j].udp_connect_addr() {
|
||||
if let Ok(addr) =
|
||||
SocksAddr::try_from(format!("{}:{}", connect_addr, port))
|
||||
{
|
||||
new_sess.destination = addr;
|
||||
break;
|
||||
}
|
||||
for (i, a) in self.actors.iter().enumerate() {
|
||||
let mut new_sess = sess.clone();
|
||||
for j in (i + 1)..self.actors.len() {
|
||||
if let Some((connect_addr, port, _)) = self.actors[j].udp_connect_addr() {
|
||||
if let Ok(addr) = SocksAddr::try_from(format!("{}:{}", connect_addr, port))
|
||||
{
|
||||
new_sess.destination = addr;
|
||||
break;
|
||||
}
|
||||
}
|
||||
dgram = a.connect(&new_sess, Some(dgram), None).await?;
|
||||
}
|
||||
return Ok(dgram);
|
||||
dgram = a.connect(&new_sess, Some(dgram), None).await?;
|
||||
}
|
||||
_ => (),
|
||||
return Ok(dgram);
|
||||
}
|
||||
|
||||
for a in self.actors.iter() {
|
||||
@@ -275,6 +263,6 @@ impl ProxyUdpHandler for Handler {
|
||||
}
|
||||
}
|
||||
}
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid chain"));
|
||||
Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid chain"))
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "direct";
|
||||
pub static NAME: &str = "direct";
|
||||
@@ -25,7 +25,7 @@ impl Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -27,7 +27,7 @@ impl Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "drop";
|
||||
pub static NAME: &str = "drop";
|
||||
@@ -13,7 +13,7 @@ pub struct Handler {}
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -13,7 +13,7 @@ pub struct Handler {}
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "failover";
|
||||
pub static NAME: &str = "failover";
|
||||
@@ -47,15 +47,13 @@ impl Handler {
|
||||
debug!("health checking tcp for [{}] index [{}]", a.tag(), i);
|
||||
let single_measure = async move {
|
||||
let sess = Session {
|
||||
source: None,
|
||||
source: "0.0.0.0:0".parse().unwrap(),
|
||||
destination: SocksAddr::Domain("www.google.com".to_string(), 80),
|
||||
};
|
||||
let start = tokio::time::Instant::now();
|
||||
match a.handle(&sess, None).await {
|
||||
Ok(mut stream) => {
|
||||
if let Err(_) =
|
||||
stream.write_all(b"HEAD / HTTP/1.1\r\n\r\n").await
|
||||
{
|
||||
if stream.write_all(b"HEAD / HTTP/1.1\r\n\r\n").await.is_err() {
|
||||
return Measure(i, u128::MAX - 2); // handshake is ok
|
||||
}
|
||||
let mut buf = vec![0u8; 1];
|
||||
@@ -64,18 +62,14 @@ impl Handler {
|
||||
Ok(_) => {
|
||||
let elapsed =
|
||||
tokio::time::Instant::now().duration_since(start);
|
||||
return Measure(i, elapsed.as_millis());
|
||||
Measure(i, elapsed.as_millis())
|
||||
}
|
||||
// handshake and write are ok
|
||||
Err(_) => {
|
||||
return Measure(i, u128::MAX - 3);
|
||||
}
|
||||
Err(_) => Measure(i, u128::MAX - 3),
|
||||
}
|
||||
}
|
||||
// handshake not ok
|
||||
Err(_) => {
|
||||
return Measure(i, u128::MAX);
|
||||
}
|
||||
Err(_) => Measure(i, u128::MAX),
|
||||
}
|
||||
};
|
||||
match timeout(time::Duration::from_secs(10), single_measure).await {
|
||||
@@ -96,9 +90,9 @@ impl Handler {
|
||||
.map(|m| {
|
||||
// construct tag(millis)
|
||||
let mut repr = actors2[m.0].tag().to_owned();
|
||||
repr.push_str("(");
|
||||
repr.push('(');
|
||||
repr.push_str(m.1.to_string().as_str());
|
||||
repr.push_str(")");
|
||||
repr.push(')');
|
||||
repr
|
||||
})
|
||||
.collect();
|
||||
@@ -143,7 +137,7 @@ impl Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -56,7 +56,7 @@ impl Handler {
|
||||
debug!("health checking udp for [{}] index [{}]", a.tag(), i);
|
||||
let single_measure = async move {
|
||||
let sess = Session {
|
||||
source: None,
|
||||
source: "0.0.0.0:0".parse().unwrap(),
|
||||
destination: SocksAddr::Ip(SocketAddr::new(
|
||||
IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
|
||||
53,
|
||||
@@ -93,7 +93,7 @@ impl Handler {
|
||||
|
||||
let (mut recv, mut send) = socket.split();
|
||||
|
||||
if let Err(_) = send.send_to(&msg_buf, &addr).await {
|
||||
if send.send_to(&msg_buf, &addr).await.is_err() {
|
||||
return Measure(i, u128::MAX - 2); // handshake is ok
|
||||
}
|
||||
let mut buf = [0u8; 1500];
|
||||
@@ -102,18 +102,14 @@ impl Handler {
|
||||
Ok(_) => {
|
||||
let elapsed =
|
||||
tokio::time::Instant::now().duration_since(start);
|
||||
return Measure(i, elapsed.as_millis());
|
||||
Measure(i, elapsed.as_millis())
|
||||
}
|
||||
// handshake and write are ok
|
||||
Err(_) => {
|
||||
return Measure(i, u128::MAX - 3);
|
||||
}
|
||||
Err(_) => Measure(i, u128::MAX - 3),
|
||||
}
|
||||
}
|
||||
// handshake not ok
|
||||
Err(_) => {
|
||||
return Measure(i, u128::MAX);
|
||||
}
|
||||
Err(_) => Measure(i, u128::MAX),
|
||||
}
|
||||
};
|
||||
match timeout(time::Duration::from_secs(10), single_measure).await {
|
||||
@@ -134,9 +130,9 @@ impl Handler {
|
||||
.map(|m| {
|
||||
// construct tag(millis)
|
||||
let mut repr = actors2[m.0].tag().to_owned();
|
||||
repr.push_str("(");
|
||||
repr.push('(');
|
||||
repr.push_str(m.1.to_string().as_str());
|
||||
repr.push_str(")");
|
||||
repr.push(')');
|
||||
repr
|
||||
})
|
||||
.collect();
|
||||
@@ -180,7 +176,7 @@ impl Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "h2";
|
||||
pub static NAME: &str = "h2";
|
||||
+13
-19
@@ -50,19 +50,17 @@ impl AsyncRead for Adapter {
|
||||
if data.len() > to_read {
|
||||
self.recv_buf.extend_from_slice(&data[to_read..]);
|
||||
}
|
||||
return Poll::Ready(Ok(to_read));
|
||||
}
|
||||
Err(e) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("receive data failed: {}", e),
|
||||
)));
|
||||
Poll::Ready(Ok(to_read))
|
||||
}
|
||||
Err(e) => Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("receive data failed: {}", e),
|
||||
))),
|
||||
},
|
||||
None => {
|
||||
panic!("could never happend, we already checked stream end");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,15 +71,11 @@ impl AsyncWrite for Adapter {
|
||||
let mut buf2 = BytesMut::new();
|
||||
buf2.extend_from_slice(buf);
|
||||
match me.send_stream.send_data(buf2.freeze(), false) {
|
||||
Ok(_) => {
|
||||
return Poll::Ready(Ok(buf.len()));
|
||||
}
|
||||
Err(e) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("send data failed: {}", e),
|
||||
)));
|
||||
}
|
||||
Ok(_) => Poll::Ready(Ok(buf.len())),
|
||||
Err(e) => Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("send data failed: {}", e),
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +96,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -160,7 +154,7 @@ impl ProxyTcpHandler for Handler {
|
||||
recv_stream,
|
||||
recv_buf: BytesMut::new(),
|
||||
};
|
||||
return Ok(Box::new(SimpleStream(h2_stream)));
|
||||
Ok(Box::new(SimpleStream(h2_stream)))
|
||||
}
|
||||
None => Err(io::Error::new(io::ErrorKind::Other, "invalid h2 input")),
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::{
|
||||
ProxyTcpHandler, ProxyUdpHandler, Tag, UdpTransportType,
|
||||
};
|
||||
|
||||
pub static NAME: &'static str = "handler";
|
||||
pub static NAME: &str = "handler";
|
||||
|
||||
pub struct Handler {
|
||||
tag: String,
|
||||
@@ -66,7 +66,7 @@ impl HandlerTyped for Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return NAME;
|
||||
NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -85,7 +85,7 @@ impl ProxyTcpHandler for Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return NAME;
|
||||
NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -30,10 +30,10 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
impl Service<Request<Body>> for ProxyService {
|
||||
type Error = Box<dyn std::error::Error + Send + Sync>;
|
||||
type Future =
|
||||
Pin<Box<dyn Future<Output = std::result::Result<Self::Response, Self::Error>> + Send>>;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
||||
type Response = Response<Body>;
|
||||
|
||||
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||
@@ -66,13 +66,9 @@ pub fn new(inbound: Inbound, dispatcher: Arc<Dispatcher>) -> Result<Runner> {
|
||||
if let Ok(stream) = stream {
|
||||
let dispatcher = dispatcher.clone();
|
||||
tokio::spawn(async move {
|
||||
let source = match stream.peer_addr() {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
warn!("invalid peer addr {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let source = stream
|
||||
.peer_addr()
|
||||
.unwrap_or_else(|_| "0.0.0.0:0".parse().unwrap());
|
||||
let http = Http::new();
|
||||
let proxy_service = ProxyService::new();
|
||||
let conn = http
|
||||
@@ -111,7 +107,7 @@ pub fn new(inbound: Inbound, dispatcher: Arc<Dispatcher>) -> Result<Runner> {
|
||||
};
|
||||
|
||||
let mut sess = Session {
|
||||
source: Some(source),
|
||||
source,
|
||||
destination,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
pub mod inbound;
|
||||
|
||||
pub static NAME: &'static str = "http";
|
||||
pub static NAME: &str = "http";
|
||||
+10
-12
@@ -98,21 +98,19 @@ async fn dial_task(
|
||||
match TcpStream::connect_std(socket.into_tcp_stream(), &dial_addr).await {
|
||||
Ok(stream) => {
|
||||
trace!("connected tcp {}", &dial_addr);
|
||||
return Ok(Box::new(SimpleStream(stream)));
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("connect failed: {}", e),
|
||||
))
|
||||
Ok(Box::new(SimpleStream(stream)))
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("connect failed: {}", e),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn dial_tcp_stream(
|
||||
dns_client: Arc<DnsClient>,
|
||||
bind_addr: &SocketAddr,
|
||||
address: &String,
|
||||
address: &str,
|
||||
port: &u16,
|
||||
) -> io::Result<Box<dyn ProxyStream>> {
|
||||
let mut resolver = Resolver::new(dns_client, bind_addr, address, port)
|
||||
@@ -140,10 +138,10 @@ async fn dial_tcp_stream(
|
||||
break; // break and execute tasks if there're any
|
||||
}
|
||||
};
|
||||
let t = dial_task(dial_addr.clone(), bind_addr);
|
||||
let t = dial_task(dial_addr, bind_addr);
|
||||
tasks.push(Box::pin(t));
|
||||
}
|
||||
if tasks.len() > 0 {
|
||||
if !tasks.is_empty() {
|
||||
match select_ok(tasks.into_iter()).await {
|
||||
Ok(v) => return Ok(v.0),
|
||||
Err(e) => {
|
||||
@@ -178,7 +176,7 @@ pub trait ProxyTcpHandler: Send + Sync + Unpin {
|
||||
&self,
|
||||
dns_client: Arc<DnsClient>,
|
||||
bind_addr: &SocketAddr,
|
||||
address: &String,
|
||||
address: &str,
|
||||
port: &u16,
|
||||
) -> io::Result<Box<dyn ProxyStream>> {
|
||||
dial_tcp_stream(dns_client, bind_addr, address, port).await
|
||||
@@ -220,7 +218,7 @@ pub trait ProxyUdpHandler: Send + Sync + Unpin {
|
||||
&self,
|
||||
dns_client: Arc<DnsClient>,
|
||||
bind_addr: &SocketAddr,
|
||||
address: &String,
|
||||
address: &str,
|
||||
port: &u16,
|
||||
) -> io::Result<Box<dyn ProxyStream>> {
|
||||
dial_tcp_stream(dns_client, bind_addr, address, port).await
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "random";
|
||||
pub static NAME: &str = "random";
|
||||
@@ -16,7 +16,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -17,7 +17,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "redirect";
|
||||
pub static NAME: &str = "redirect";
|
||||
@@ -18,7 +18,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -69,7 +69,7 @@ impl ProxyDatagram for Datagram {
|
||||
Box<dyn ProxyDatagramSendHalf>,
|
||||
) {
|
||||
(
|
||||
Box::new(DatagramRecvHalf(self.recv_half, self.target.clone())),
|
||||
Box::new(DatagramRecvHalf(self.recv_half, self.target)),
|
||||
Box::new(DatagramSendHalf(self.send_half, self.target)),
|
||||
)
|
||||
}
|
||||
@@ -80,7 +80,7 @@ pub struct DatagramRecvHalf(RecvHalf, SocketAddr);
|
||||
#[async_trait]
|
||||
impl ProxyDatagramRecvHalf for DatagramRecvHalf {
|
||||
async fn recv_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
|
||||
let addr = self.1.clone();
|
||||
let addr = self.1;
|
||||
self.0.recv_from(buf).map_ok(|(n, _)| (n, addr)).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,11 +10,7 @@ pub struct ShadowsocksNonceSequence(Vec<u8>);
|
||||
|
||||
impl ShadowsocksNonceSequence {
|
||||
pub fn new(size: usize) -> Self {
|
||||
let mut c = Vec::new();
|
||||
for _ in 0..size {
|
||||
c.push(0xff);
|
||||
}
|
||||
ShadowsocksNonceSequence(c)
|
||||
ShadowsocksNonceSequence(vec![0xff; size])
|
||||
}
|
||||
|
||||
fn inc(&mut self) {
|
||||
|
||||
@@ -11,4 +11,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "shadowsocks";
|
||||
pub static NAME: &str = "shadowsocks";
|
||||
@@ -47,7 +47,7 @@ pub struct ShadowedStream<T> {
|
||||
}
|
||||
|
||||
impl<T> ShadowedStream<T> {
|
||||
pub fn new(s: T, cipher: &String, password: &String) -> Result<Self> {
|
||||
pub fn new(s: T, cipher: &str, password: &str) -> Result<Self> {
|
||||
let cipher = AeadCipher::new(cipher)?;
|
||||
let psk = kdf(password, cipher.key_len())?;
|
||||
Ok(ShadowedStream {
|
||||
@@ -437,7 +437,7 @@ pub struct ShadowedDatagram {
|
||||
}
|
||||
|
||||
impl ShadowedDatagram {
|
||||
pub fn new(socket: Box<dyn ProxyDatagram>, cipher: &String, password: &String) -> Result<Self> {
|
||||
pub fn new(socket: Box<dyn ProxyDatagram>, cipher: &str, password: &str) -> Result<Self> {
|
||||
let cipher =
|
||||
AeadCipher::new(cipher).map_err(|e| anyhow!("new aead cipher failed: {}", e))?;
|
||||
let psk =
|
||||
@@ -456,8 +456,8 @@ impl ShadowedDatagram {
|
||||
/// (allocate extra memory when need) enough space each time sending or receiving packets.
|
||||
pub fn with_initial_buffer_size(
|
||||
socket: Box<dyn ProxyDatagram>,
|
||||
cipher: &String,
|
||||
password: &String,
|
||||
cipher: &str,
|
||||
password: &str,
|
||||
buf_size: usize,
|
||||
) -> Result<Self> {
|
||||
let cipher =
|
||||
|
||||
@@ -21,11 +21,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
@@ -54,6 +54,6 @@ impl ProxyTcpHandler for Handler {
|
||||
sess.destination
|
||||
.write_to(&mut stream, SocksAddrWireType::PortLast)
|
||||
.await?;
|
||||
return Ok(Box::new(SimpleStream(stream)));
|
||||
Ok(Box::new(SimpleStream(stream)))
|
||||
}
|
||||
}
|
||||
@@ -33,11 +33,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
fn udp_transport_type(&self) -> UdpTransportType {
|
||||
@@ -64,7 +64,7 @@ impl ProxyUdpHandler for Handler {
|
||||
}
|
||||
};
|
||||
|
||||
if ips.len() == 0 {
|
||||
if ips.is_empty() {
|
||||
return Err(Error::new(ErrorKind::Other, "no resolved address"));
|
||||
}
|
||||
|
||||
@@ -75,8 +75,7 @@ impl ProxyUdpHandler for Handler {
|
||||
socket
|
||||
} else {
|
||||
let socket = UdpSocket::bind(self.bind_addr).await?;
|
||||
let socket = Box::new(SimpleDatagram(socket));
|
||||
socket
|
||||
Box::new(SimpleDatagram(socket))
|
||||
};
|
||||
|
||||
let dgram = ShadowedDatagram::with_initial_buffer_size(
|
||||
@@ -92,7 +91,7 @@ impl ProxyUdpHandler for Handler {
|
||||
)
|
||||
})?;
|
||||
let (r, s) = dgram.split();
|
||||
return Ok(Box::new(Datagram { r, s, server: addr }));
|
||||
Ok(Box::new(Datagram { r, s, server: addr }))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,15 +36,15 @@ pub fn new(
|
||||
bind = "0.0.0.0".to_string();
|
||||
}
|
||||
|
||||
if let Ok(r) = tcp::new(listen, port, bind, dispatcher.clone()) {
|
||||
if let Ok(r) = tcp::new(listen, port, bind, dispatcher) {
|
||||
runners.push(r);
|
||||
}
|
||||
|
||||
if runners.len() > 0 {
|
||||
return Ok(Box::pin(async move {
|
||||
if !runners.is_empty() {
|
||||
Ok(Box::pin(async move {
|
||||
futures::future::join_all(runners).await;
|
||||
}));
|
||||
}))
|
||||
} else {
|
||||
return Err(anyhow!("no runners"));
|
||||
Err(anyhow!("no runners"))
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn new(
|
||||
while let Some(stream) = listener.next().await {
|
||||
if let Ok(mut stream) = stream {
|
||||
let dispatcher = dispatcher.clone();
|
||||
let bind_addr = bind_addr.clone();
|
||||
let bind_addr = bind_addr;
|
||||
tokio::spawn(async move {
|
||||
let mut buf = BytesMut::with_capacity(1024);
|
||||
|
||||
@@ -74,12 +74,10 @@ pub fn new(
|
||||
debug!("write auth response failed: {}", e);
|
||||
};
|
||||
return;
|
||||
} else {
|
||||
if let Err(e) = stream.write_all(&[0x05, method_idx]).await {
|
||||
debug!("write auth response failed: {}", e);
|
||||
return;
|
||||
};
|
||||
}
|
||||
} else if let Err(e) = stream.write_all(&[0x05, method_idx]).await {
|
||||
debug!("write auth response failed: {}", e);
|
||||
return;
|
||||
};
|
||||
|
||||
// handle request
|
||||
buf.resize(3, 0);
|
||||
@@ -140,15 +138,11 @@ pub fn new(
|
||||
return;
|
||||
};
|
||||
|
||||
let peer_addr = match stream.peer_addr() {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
warn!("error get peer addr: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let source = stream
|
||||
.peer_addr()
|
||||
.unwrap_or_else(|_| "0.0.0.0:0".parse().unwrap());
|
||||
let mut sess = Session {
|
||||
source: Some(peer_addr),
|
||||
source,
|
||||
destination,
|
||||
};
|
||||
|
||||
@@ -171,7 +165,8 @@ pub fn new(
|
||||
return;
|
||||
};
|
||||
let mut buf = [0u8; 1];
|
||||
if let Err(_) = stream.read_exact(&mut buf).await {
|
||||
// TODO explicitly drop resources allocated above before waiting?
|
||||
if stream.read_exact(&mut buf).await.is_err() {
|
||||
// perhaps explicitly notifies the NAT manager?
|
||||
debug!("udp association end");
|
||||
}
|
||||
|
||||
@@ -90,13 +90,14 @@ pub fn new(listen: String, port: u16, nat_manager: Arc<NatManager>) -> Result<Ru
|
||||
|
||||
if !nat_manager.contains_key(&src_addr).await {
|
||||
let sess = Session {
|
||||
source: Some(src_addr.clone()),
|
||||
source: src_addr,
|
||||
destination: dst_addr.clone(),
|
||||
};
|
||||
|
||||
if let Err(_) = nat_manager
|
||||
if nat_manager
|
||||
.add_session(&sess, src_addr, client_ch_tx.clone())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
continue; // dispatch failed
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
pub mod inbound;
|
||||
pub mod outbound;
|
||||
|
||||
pub static NAME: &'static str = "socks";
|
||||
pub static NAME: &str = "socks";
|
||||
@@ -23,11 +23,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
@@ -59,6 +59,6 @@ impl ProxyTcpHandler for Handler {
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
return Ok(stream);
|
||||
Ok(stream)
|
||||
}
|
||||
}
|
||||
@@ -29,11 +29,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
fn udp_transport_type(&self) -> UdpTransportType {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "tls";
|
||||
pub static NAME: &str = "tls";
|
||||
@@ -19,7 +19,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -45,7 +45,7 @@ impl ProxyTcpHandler for Handler {
|
||||
io::Error::new(io::ErrorKind::Other, format!("wrap tls failed: {}", e))
|
||||
})
|
||||
.await?;
|
||||
return Ok(tls_stream);
|
||||
Ok(tls_stream)
|
||||
}
|
||||
None => Err(io::Error::new(io::ErrorKind::Other, "invalid tls input")),
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "trojan";
|
||||
pub static NAME: &str = "trojan";
|
||||
@@ -24,11 +24,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
|
||||
@@ -31,11 +31,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
fn udp_transport_type(&self) -> UdpTransportType {
|
||||
|
||||
@@ -4,4 +4,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "tryall";
|
||||
pub static NAME: &str = "tryall";
|
||||
@@ -17,7 +17,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
pub mod inbound;
|
||||
pub mod netstack;
|
||||
|
||||
pub static NAME: &'static str = "tun";
|
||||
pub static NAME: &str = "tun";
|
||||
@@ -111,17 +111,17 @@ impl NetStackImpl {
|
||||
.query_domain(&stream.remote_addr().ip())
|
||||
{
|
||||
Some(domain) => Session {
|
||||
source: Some(stream.local_addr().to_owned()),
|
||||
source: stream.local_addr().to_owned(),
|
||||
destination: SocksAddr::Domain(domain, stream.remote_addr().port()),
|
||||
},
|
||||
None => Session {
|
||||
source: Some(stream.local_addr().to_owned()),
|
||||
source: stream.local_addr().to_owned(),
|
||||
destination: SocksAddr::Ip(*stream.remote_addr()),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
Session {
|
||||
source: Some(stream.local_addr().to_owned()),
|
||||
source: stream.local_addr().to_owned(),
|
||||
destination: SocksAddr::Ip(*stream.remote_addr()),
|
||||
}
|
||||
};
|
||||
@@ -229,13 +229,14 @@ impl NetStackImpl {
|
||||
|
||||
if !nat_manager.contains_key(&src_addr).await {
|
||||
let sess = Session {
|
||||
source: Some(src_addr.clone()),
|
||||
source: src_addr,
|
||||
destination: SocksAddr::Ip(dst_addr),
|
||||
};
|
||||
|
||||
if let Err(_) = nat_manager
|
||||
if nat_manager
|
||||
.add_session(&sess, src_addr, client_ch_tx.clone())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
// dispatch err logging was handled in dispatcher
|
||||
continue; // in case the pkt was sent to drop, err is returned immediately
|
||||
|
||||
@@ -195,7 +195,7 @@ impl AsyncRead for TcpStreamImpl {
|
||||
cx: &mut Context,
|
||||
buf: &mut [u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
if self.write_buf.len() > 0 {
|
||||
if !self.write_buf.is_empty() {
|
||||
let to_read = min(buf.len(), self.write_buf.len());
|
||||
let piece = self.write_buf.split_to(to_read);
|
||||
(&mut buf[..to_read]).copy_from_slice(&piece[..to_read]);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
mod vless;
|
||||
pub use vless::*;
|
||||
mod stream;
|
||||
pub use stream::*;
|
||||
|
||||
pub mod tcp;
|
||||
pub mod udp;
|
||||
@@ -7,4 +7,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "vless";
|
||||
pub static NAME: &str = "vless";
|
||||
File renamed without changes.
@@ -26,11 +26,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
|
||||
@@ -31,11 +31,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
fn udp_transport_type(&self) -> UdpTransportType {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod crypto;
|
||||
mod vmess;
|
||||
mod protocol;
|
||||
mod stream;
|
||||
|
||||
pub mod tcp;
|
||||
pub mod udp;
|
||||
@@ -7,4 +8,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "vmess";
|
||||
pub static NAME: &str = "vmess";
|
||||
+141
-231
@@ -1,253 +1,163 @@
|
||||
use std::convert::TryFrom;
|
||||
use std::{
|
||||
io,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||
};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use bytes::{Buf, BufMut, BytesMut};
|
||||
use aes::Aes128;
|
||||
use anyhow::{anyhow, Result};
|
||||
use byteorder::{BigEndian, ByteOrder};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use cfb_mode::stream_cipher::{NewStreamCipher, StreamCipher};
|
||||
use cfb_mode::Cfb;
|
||||
use hmac::{Hmac, Mac, NewMac};
|
||||
use lz_fnv::{Fnv1a, FnvHasher};
|
||||
use md5::{Digest, Md5};
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use uuid::Uuid;
|
||||
|
||||
// pub const MAX_SOCKS_ADDR_SIZE: usize = 1 + 1 + 255 + 2;
|
||||
use crate::session::{SocksAddr, SocksAddrWireType};
|
||||
|
||||
struct SocksAddrType;
|
||||
type RequestCommand = u8;
|
||||
|
||||
impl SocksAddrType {
|
||||
const V4: u8 = 0x1;
|
||||
const V6: u8 = 0x3;
|
||||
const DOMAIN: u8 = 0x2;
|
||||
pub const REQUEST_COMMAND_TCP: RequestCommand = 0x01;
|
||||
pub const REQUEST_COMMAND_UDP: RequestCommand = 0x02;
|
||||
|
||||
type Security = u8;
|
||||
|
||||
pub const SECURITY_TYPE_AES128_GCM: Security = 0x03;
|
||||
pub const SECURITY_TYPE_CHACHA20_POLY1305: Security = 0x04;
|
||||
|
||||
type RequestOption = u8;
|
||||
|
||||
pub const REQUEST_OPTION_CHUNK_STREAM: RequestOption = 0x01;
|
||||
pub const REQUEST_OPTION_CHUNK_MASKING: RequestOption = 0x04;
|
||||
pub const REQUEST_OPTION_GLOBAL_PADDING: RequestOption = 0x08;
|
||||
|
||||
pub struct RequestHeader {
|
||||
pub version: u8,
|
||||
pub command: RequestCommand,
|
||||
pub option: u8,
|
||||
pub security: Security,
|
||||
pub address: SocksAddr,
|
||||
pub uuid: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SocksAddr {
|
||||
Ip(SocketAddr),
|
||||
Domain(String, u16),
|
||||
}
|
||||
|
||||
const INSUFF_BYTES: &str = "insufficient bytes";
|
||||
|
||||
/// Tries to read `SocksAddr` from `BytesBuf` and advances the cursor.
|
||||
impl TryFrom<&mut BytesMut> for SocksAddr {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(buf: &mut BytesMut) -> Result<Self, Self::Error> {
|
||||
if buf.remaining() < 1 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
|
||||
match buf.get_u8() {
|
||||
SocksAddrType::V4 => {
|
||||
if buf.remaining() < 4 + 2 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let ip = Ipv4Addr::from(buf.get_u32());
|
||||
let port = buf.get_u16();
|
||||
Ok(Self::Ip((ip, port).into()))
|
||||
}
|
||||
SocksAddrType::V6 => {
|
||||
if buf.remaining() < 16 + 2 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let ip = Ipv6Addr::from(buf.get_u128());
|
||||
let port = buf.get_u16();
|
||||
Ok(Self::Ip((ip, port).into()))
|
||||
}
|
||||
SocksAddrType::DOMAIN => {
|
||||
if buf.remaining() < 1 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let domain_len = buf.get_u8() as usize;
|
||||
if buf.remaining() < domain_len + 2 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let domain = String::from_utf8((&buf[..domain_len]).to_vec())
|
||||
.map_err(|_| "invalid domain")?;
|
||||
buf.advance(domain_len);
|
||||
let port = buf.get_u16();
|
||||
Ok(Self::Domain(domain, port))
|
||||
}
|
||||
_ => Err("invalid address type"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to read `SocksAddr` from `&[u8]`.
|
||||
impl TryFrom<&[u8]> for SocksAddr {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
|
||||
if buf.len() < 1 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
|
||||
match buf[0] {
|
||||
SocksAddrType::V4 => {
|
||||
if buf.len() < 1 + 4 + 2 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let mut ip_bytes = [0u8; 4];
|
||||
(&mut ip_bytes).copy_from_slice(&buf[1..5]);
|
||||
let ip = Ipv4Addr::from(ip_bytes);
|
||||
let mut port_bytes = [0u8; 2];
|
||||
(&mut port_bytes).copy_from_slice(&buf[5..7]);
|
||||
let port = u16::from_be_bytes(port_bytes);
|
||||
Ok(Self::Ip((ip, port).into()))
|
||||
}
|
||||
SocksAddrType::V6 => {
|
||||
if buf.len() < 1 + 16 + 2 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let mut ip_bytes = [0u8; 16];
|
||||
(&mut ip_bytes).copy_from_slice(&buf[1..17]);
|
||||
let ip = Ipv6Addr::from(ip_bytes);
|
||||
let mut port_bytes = [0u8; 2];
|
||||
(&mut port_bytes).copy_from_slice(&buf[17..19]);
|
||||
let port = u16::from_be_bytes(port_bytes);
|
||||
Ok(Self::Ip((ip, port).into()))
|
||||
}
|
||||
SocksAddrType::DOMAIN => {
|
||||
if buf.len() < 1 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let domain_len = buf[1] as usize;
|
||||
if buf.len() < 1 + domain_len + 2 {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let domain = String::from_utf8((&buf[2..domain_len + 2]).to_vec())
|
||||
.map_err(|_| "invalid domain")?;
|
||||
let mut port_bytes = [0u8; 2];
|
||||
(&mut port_bytes).copy_from_slice(&buf[domain_len + 2..domain_len + 4]);
|
||||
let port = u16::from_be_bytes(port_bytes);
|
||||
Ok(Self::Domain(domain, port))
|
||||
}
|
||||
_ => Err("invalid address type"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn insuff() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Other, "buffer too small")
|
||||
}
|
||||
|
||||
impl SocksAddr {
|
||||
pub fn size(&self) -> usize {
|
||||
match self {
|
||||
Self::Ip(addr) => match addr {
|
||||
SocketAddr::V4(_addr) => 1 + 4 + 2,
|
||||
SocketAddr::V6(_addr) => 1 + 16 + 2,
|
||||
},
|
||||
Self::Domain(domain, _port) => 1 + 1 + domain.len() + 2,
|
||||
}
|
||||
impl RequestHeader {
|
||||
pub fn set_option(&mut self, opt: RequestOption) {
|
||||
self.option |= opt;
|
||||
}
|
||||
|
||||
/// Writes `self` into `buf`.
|
||||
pub fn write_into<T: BufMut>(&self, buf: &mut T) -> io::Result<()> {
|
||||
match self {
|
||||
Self::Ip(addr) => match addr {
|
||||
SocketAddr::V4(addr) => {
|
||||
if buf.remaining_mut() < 1 + 4 + 2 {
|
||||
return Err(insuff());
|
||||
}
|
||||
buf.put_u16(addr.port());
|
||||
buf.put_u8(SocksAddrType::V4);
|
||||
buf.put_slice(&addr.ip().octets());
|
||||
}
|
||||
SocketAddr::V6(addr) => {
|
||||
if buf.remaining_mut() < 1 + 16 + 2 {
|
||||
return Err(insuff());
|
||||
}
|
||||
buf.put_u16(addr.port());
|
||||
buf.put_u8(SocksAddrType::V6);
|
||||
buf.put_slice(&addr.ip().octets());
|
||||
}
|
||||
},
|
||||
Self::Domain(domain, port) => {
|
||||
if buf.remaining_mut() < 1 + domain.len() + 2 {
|
||||
return Err(insuff());
|
||||
}
|
||||
buf.put_u16(*port);
|
||||
buf.put_u8(SocksAddrType::DOMAIN);
|
||||
buf.put_u8(domain.len() as u8);
|
||||
buf.put_slice(domain.as_bytes());
|
||||
pub fn encode(&self, buf: &mut BytesMut, sess: &ClientSession) -> Result<()> {
|
||||
// generate auth info
|
||||
let mut timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||
Ok(n) => n.as_secs(),
|
||||
Err(_) => return Err(anyhow!("invalid system time")),
|
||||
};
|
||||
let mut rng = StdRng::from_entropy();
|
||||
let delta: i32 = rng.gen_range(0, 30 * 2) - 30;
|
||||
timestamp = timestamp.wrapping_add(delta as u64);
|
||||
let mut mac =
|
||||
Hmac::<Md5>::new_varkey(self.uuid.as_bytes()).map_err(|_| anyhow!("md5 failed"))?;
|
||||
let mut tmp = [0u8; 8];
|
||||
BigEndian::write_u64(&mut tmp, timestamp as u64);
|
||||
mac.update(&tmp);
|
||||
let auth_info = mac.finalize().into_bytes();
|
||||
|
||||
buf.put_slice(&auth_info[..]);
|
||||
|
||||
buf.put_u8(self.version);
|
||||
buf.put_slice(&sess.request_body_iv);
|
||||
buf.put_slice(&sess.request_body_key);
|
||||
buf.put_u8(sess.response_header);
|
||||
buf.put_u8(self.option);
|
||||
|
||||
let padding_len = StdRng::from_entropy().gen_range(0, 16) as u8;
|
||||
let security = (padding_len << 4) | self.security as u8;
|
||||
|
||||
buf.put_u8(security);
|
||||
buf.put_u8(0);
|
||||
buf.put_u8(self.command);
|
||||
|
||||
self.address.write_buf(buf, SocksAddrWireType::PortFirst)?;
|
||||
|
||||
// add random bytes
|
||||
if padding_len > 0 {
|
||||
let mut padding_bytes = BytesMut::with_capacity(padding_len as usize);
|
||||
unsafe { padding_bytes.set_len(padding_len as usize) };
|
||||
let mut rng = StdRng::from_entropy();
|
||||
for i in 0..padding_bytes.len() {
|
||||
padding_bytes[i] = rng.gen();
|
||||
}
|
||||
buf.put_slice(&padding_bytes);
|
||||
}
|
||||
|
||||
// checksum
|
||||
let mut hasher = Fnv1a::<u32>::default();
|
||||
hasher.write(&buf[auth_info.len()..]);
|
||||
let h = hasher.finish();
|
||||
let buf_size = buf.len();
|
||||
buf.resize(buf_size + 4, 0);
|
||||
BigEndian::write_u32(&mut buf[buf_size..], h);
|
||||
|
||||
// iv for header encryption
|
||||
let mut tmp = [0u8; 8];
|
||||
BigEndian::write_u64(&mut tmp, timestamp as u64);
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(&tmp);
|
||||
hasher.update(&tmp);
|
||||
hasher.update(&tmp);
|
||||
hasher.update(&tmp);
|
||||
let iv = hasher.finalize();
|
||||
|
||||
// key for header ecnryption
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(self.uuid.as_bytes());
|
||||
hasher.update(
|
||||
"c48619fe-8f02-49e0-b9e9-edf763e17e21"
|
||||
.to_string()
|
||||
.as_bytes(),
|
||||
);
|
||||
let key = hasher.finalize();
|
||||
|
||||
// encrypt cmd part
|
||||
let mut enc =
|
||||
Cfb::<Aes128>::new_var(&key, &iv).map_err(|_| anyhow!("new aes128 enc failed"))?;
|
||||
enc.encrypt(&mut buf[auth_info.len()..]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<(IpAddr, u16)> for SocksAddr {
|
||||
fn from(value: (IpAddr, u16)) -> Self {
|
||||
Self::Ip(value.into())
|
||||
}
|
||||
pub struct ClientSession {
|
||||
pub request_body_key: Vec<u8>,
|
||||
pub request_body_iv: Vec<u8>,
|
||||
pub response_body_key: Vec<u8>,
|
||||
pub response_body_iv: Vec<u8>,
|
||||
pub response_header: u8,
|
||||
}
|
||||
|
||||
impl From<(Ipv4Addr, u16)> for SocksAddr {
|
||||
fn from(value: (Ipv4Addr, u16)) -> Self {
|
||||
Self::Ip(value.into())
|
||||
}
|
||||
}
|
||||
impl ClientSession {
|
||||
pub fn new() -> Self {
|
||||
let mut request_body_key = vec![0u8; 16];
|
||||
let mut request_body_iv = vec![0u8; 16];
|
||||
let response_header: u8;
|
||||
|
||||
impl From<(Ipv6Addr, u16)> for SocksAddr {
|
||||
fn from(value: (Ipv6Addr, u16)) -> Self {
|
||||
Self::Ip(value.into())
|
||||
}
|
||||
}
|
||||
// fill random bytes
|
||||
let mut rand_bytes = BytesMut::with_capacity(16 + 16 + 1);
|
||||
unsafe { rand_bytes.set_len(16 + 16 + 1) };
|
||||
let mut rng = StdRng::from_entropy();
|
||||
for i in 0..rand_bytes.len() {
|
||||
rand_bytes[i] = rng.gen();
|
||||
}
|
||||
(&mut request_body_key[..]).copy_from_slice(&rand_bytes[..16]);
|
||||
(&mut request_body_iv[..]).copy_from_slice(&rand_bytes[16..32]);
|
||||
response_header = rand_bytes[32];
|
||||
|
||||
impl From<SocketAddr> for SocksAddr {
|
||||
fn from(addr: SocketAddr) -> Self {
|
||||
Self::Ip(addr)
|
||||
}
|
||||
}
|
||||
let response_body_key = Md5::digest(&request_body_key).to_vec();
|
||||
let response_body_iv = Md5::digest(&request_body_iv).to_vec();
|
||||
|
||||
impl From<&SocketAddr> for SocksAddr {
|
||||
fn from(addr: &SocketAddr) -> Self {
|
||||
Self::Ip(addr.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<(String, u16)> for SocksAddr {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from((domain, port): (String, u16)) -> Result<Self, Self::Error> {
|
||||
if domain.len() > 0xff {
|
||||
Err("domain too long")
|
||||
} else {
|
||||
Ok(Self::Domain(domain, port))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<(&String, u16)> for SocksAddr {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from((domain, port): (&String, u16)) -> Result<Self, Self::Error> {
|
||||
if domain.len() > 0xff {
|
||||
Err("domain too long")
|
||||
} else {
|
||||
Ok(Self::Domain(domain.to_owned(), port))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<(&str, u16)> for SocksAddr {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from((domain, port): (&str, u16)) -> Result<Self, Self::Error> {
|
||||
let domain = domain.to_owned();
|
||||
if domain.len() > 0xff {
|
||||
Err("domain too long")
|
||||
} else {
|
||||
Ok(Self::Domain(domain, port))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for SocksAddr {
|
||||
fn to_string(&self) -> String {
|
||||
match self {
|
||||
Self::Ip(addr) => match addr {
|
||||
SocketAddr::V4(addr) => addr.to_string(),
|
||||
SocketAddr::V6(addr) => addr.to_string(),
|
||||
},
|
||||
Self::Domain(domain, port) => format!("{}:{}", domain, port),
|
||||
ClientSession {
|
||||
request_body_key,
|
||||
request_body_iv,
|
||||
response_body_key,
|
||||
response_body_iv,
|
||||
response_header,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use std::{cmp::min, io, pin::Pin};
|
||||
|
||||
use aes::Aes128;
|
||||
use anyhow::anyhow;
|
||||
use byteorder::{BigEndian, ByteOrder};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use cfb_mode::stream_cipher::{NewStreamCipher, StreamCipher};
|
||||
use cfb_mode::Cfb;
|
||||
@@ -11,168 +8,16 @@ use futures::{
|
||||
ready,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use hmac::{Hmac, Mac, NewMac};
|
||||
use lz_fnv::{Fnv1a, FnvHasher};
|
||||
use md5::{Digest, Md5};
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::common::crypto::{
|
||||
aead::{AeadDecryptor, AeadEncryptor},
|
||||
Decryptor, Encryptor,
|
||||
};
|
||||
use crate::session::{SocksAddr, SocksAddrWireType};
|
||||
|
||||
use super::crypto::{PaddingLengthGenerator, ShakeSizeParser, VMessAEADSequence};
|
||||
|
||||
type RequestCommand = u8;
|
||||
|
||||
pub const REQUEST_COMMAND_TCP: RequestCommand = 0x01;
|
||||
pub const REQUEST_COMMAND_UDP: RequestCommand = 0x02;
|
||||
|
||||
type Security = u8;
|
||||
|
||||
pub const SECURITY_TYPE_AES128_GCM: Security = 0x03;
|
||||
pub const SECURITY_TYPE_CHACHA20_POLY1305: Security = 0x04;
|
||||
|
||||
type RequestOption = u8;
|
||||
|
||||
pub const REQUEST_OPTION_CHUNK_STREAM: RequestOption = 0x01;
|
||||
pub const REQUEST_OPTION_CHUNK_MASKING: RequestOption = 0x04;
|
||||
pub const REQUEST_OPTION_GLOBAL_PADDING: RequestOption = 0x08;
|
||||
|
||||
pub struct RequestHeader {
|
||||
pub version: u8,
|
||||
pub command: RequestCommand,
|
||||
pub option: u8,
|
||||
pub security: Security,
|
||||
pub address: SocksAddr,
|
||||
pub uuid: Uuid,
|
||||
}
|
||||
|
||||
impl RequestHeader {
|
||||
pub fn set_option(&mut self, opt: RequestOption) {
|
||||
self.option |= opt;
|
||||
}
|
||||
|
||||
pub fn encode(&self, buf: &mut BytesMut, sess: &ClientSession) -> anyhow::Result<()> {
|
||||
// generate auth info
|
||||
let mut timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||
Ok(n) => n.as_secs(),
|
||||
Err(_) => return Err(anyhow!("invalid system time")),
|
||||
};
|
||||
let mut rng = StdRng::from_entropy();
|
||||
let delta: i32 = rng.gen_range(0, 30 * 2) - 30;
|
||||
timestamp = timestamp.wrapping_add(delta as u64);
|
||||
let mut mac =
|
||||
Hmac::<Md5>::new_varkey(self.uuid.as_bytes()).map_err(|_| anyhow!("md5 failed"))?;
|
||||
let mut tmp = [0u8; 8];
|
||||
BigEndian::write_u64(&mut tmp, timestamp as u64);
|
||||
mac.update(&tmp);
|
||||
let auth_info = mac.finalize().into_bytes();
|
||||
|
||||
buf.put_slice(&auth_info[..]);
|
||||
|
||||
buf.put_u8(self.version);
|
||||
buf.put_slice(&sess.request_body_iv);
|
||||
buf.put_slice(&sess.request_body_key);
|
||||
buf.put_u8(sess.response_header);
|
||||
buf.put_u8(self.option);
|
||||
|
||||
let padding_len = StdRng::from_entropy().gen_range(0, 16) as u8;
|
||||
let security = (padding_len << 4) | self.security as u8;
|
||||
|
||||
buf.put_u8(security);
|
||||
buf.put_u8(0);
|
||||
buf.put_u8(self.command);
|
||||
|
||||
self.address.write_buf(buf, SocksAddrWireType::PortFirst)?;
|
||||
|
||||
// add random bytes
|
||||
if padding_len > 0 {
|
||||
let mut padding_bytes = BytesMut::with_capacity(padding_len as usize);
|
||||
unsafe { padding_bytes.set_len(padding_len as usize) };
|
||||
let mut rng = StdRng::from_entropy();
|
||||
for i in 0..padding_bytes.len() {
|
||||
padding_bytes[i] = rng.gen();
|
||||
}
|
||||
buf.put_slice(&padding_bytes);
|
||||
}
|
||||
|
||||
// checksum
|
||||
let mut hasher = Fnv1a::<u32>::default();
|
||||
hasher.write(&buf[auth_info.len()..]);
|
||||
let h = hasher.finish();
|
||||
let buf_size = buf.len();
|
||||
buf.resize(buf_size + 4, 0);
|
||||
BigEndian::write_u32(&mut buf[buf_size..], h);
|
||||
|
||||
// iv for header encryption
|
||||
let mut tmp = [0u8; 8];
|
||||
BigEndian::write_u64(&mut tmp, timestamp as u64);
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(&tmp);
|
||||
hasher.update(&tmp);
|
||||
hasher.update(&tmp);
|
||||
hasher.update(&tmp);
|
||||
let iv = hasher.finalize();
|
||||
|
||||
// key for header ecnryption
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(self.uuid.as_bytes());
|
||||
hasher.update(
|
||||
"c48619fe-8f02-49e0-b9e9-edf763e17e21"
|
||||
.to_string()
|
||||
.as_bytes(),
|
||||
);
|
||||
let key = hasher.finalize();
|
||||
|
||||
// encrypt cmd part
|
||||
let mut enc =
|
||||
Cfb::<Aes128>::new_var(&key, &iv).map_err(|_| anyhow!("new aes128 enc failed"))?;
|
||||
enc.encrypt(&mut buf[auth_info.len()..]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ClientSession {
|
||||
pub request_body_key: Vec<u8>,
|
||||
pub request_body_iv: Vec<u8>,
|
||||
pub response_body_key: Vec<u8>,
|
||||
pub response_body_iv: Vec<u8>,
|
||||
pub response_header: u8,
|
||||
}
|
||||
|
||||
impl ClientSession {
|
||||
pub fn new() -> Self {
|
||||
let mut request_body_key = vec![0u8; 16];
|
||||
let mut request_body_iv = vec![0u8; 16];
|
||||
let response_header: u8;
|
||||
|
||||
// fill random bytes
|
||||
let mut rand_bytes = BytesMut::with_capacity(16 + 16 + 1);
|
||||
unsafe { rand_bytes.set_len(16 + 16 + 1) };
|
||||
let mut rng = StdRng::from_entropy();
|
||||
for i in 0..rand_bytes.len() {
|
||||
rand_bytes[i] = rng.gen();
|
||||
}
|
||||
(&mut request_body_key[..]).copy_from_slice(&rand_bytes[..16]);
|
||||
(&mut request_body_iv[..]).copy_from_slice(&rand_bytes[16..32]);
|
||||
response_header = rand_bytes[32];
|
||||
|
||||
let response_body_key = Md5::digest(&request_body_key).to_vec();
|
||||
let response_body_iv = Md5::digest(&request_body_iv).to_vec();
|
||||
|
||||
ClientSession {
|
||||
request_body_key,
|
||||
request_body_iv,
|
||||
response_body_key,
|
||||
response_body_iv,
|
||||
response_header,
|
||||
}
|
||||
}
|
||||
}
|
||||
use super::protocol::ClientSession;
|
||||
|
||||
enum ReadState {
|
||||
WaitingResponseHeader,
|
||||
+11
-11
@@ -12,8 +12,8 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::crypto::*;
|
||||
use super::vmess;
|
||||
use super::vmess::*;
|
||||
use super::protocol::*;
|
||||
use super::stream::*;
|
||||
|
||||
pub struct Handler {
|
||||
pub address: String,
|
||||
@@ -27,11 +27,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
@@ -44,21 +44,21 @@ impl ProxyTcpHandler for Handler {
|
||||
})?;
|
||||
let mut request_header = RequestHeader {
|
||||
version: 0x1,
|
||||
command: vmess::REQUEST_COMMAND_TCP,
|
||||
option: vmess::REQUEST_OPTION_CHUNK_STREAM,
|
||||
security: vmess::SECURITY_TYPE_CHACHA20_POLY1305,
|
||||
command: REQUEST_COMMAND_TCP,
|
||||
option: REQUEST_OPTION_CHUNK_STREAM,
|
||||
security: SECURITY_TYPE_CHACHA20_POLY1305,
|
||||
address: sess.destination.clone(),
|
||||
uuid,
|
||||
};
|
||||
request_header.set_option(vmess::REQUEST_OPTION_CHUNK_MASKING);
|
||||
request_header.set_option(vmess::REQUEST_OPTION_GLOBAL_PADDING);
|
||||
request_header.set_option(REQUEST_OPTION_CHUNK_MASKING);
|
||||
request_header.set_option(REQUEST_OPTION_GLOBAL_PADDING);
|
||||
|
||||
match self.security.to_lowercase().as_str() {
|
||||
"chacha20-poly1305" | "chacha20-ietf-poly1305" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_CHACHA20_POLY1305;
|
||||
request_header.security = SECURITY_TYPE_CHACHA20_POLY1305;
|
||||
}
|
||||
"aes-128-gcm" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_AES128_GCM;
|
||||
request_header.security = SECURITY_TYPE_AES128_GCM;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
|
||||
+11
-11
@@ -17,8 +17,8 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::crypto::*;
|
||||
use super::vmess;
|
||||
use super::vmess::*;
|
||||
use super::protocol::*;
|
||||
use super::stream::*;
|
||||
|
||||
pub struct Handler {
|
||||
pub address: String,
|
||||
@@ -32,11 +32,11 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
Some((self.address.clone(), self.port, self.bind_addr.clone()))
|
||||
Some((self.address.clone(), self.port, self.bind_addr))
|
||||
}
|
||||
|
||||
fn udp_transport_type(&self) -> UdpTransportType {
|
||||
@@ -54,21 +54,21 @@ impl ProxyUdpHandler for Handler {
|
||||
})?;
|
||||
let mut request_header = RequestHeader {
|
||||
version: 0x1,
|
||||
command: vmess::REQUEST_COMMAND_UDP,
|
||||
option: vmess::REQUEST_OPTION_CHUNK_STREAM,
|
||||
security: vmess::SECURITY_TYPE_CHACHA20_POLY1305,
|
||||
command: REQUEST_COMMAND_UDP,
|
||||
option: REQUEST_OPTION_CHUNK_STREAM,
|
||||
security: SECURITY_TYPE_CHACHA20_POLY1305,
|
||||
address: sess.destination.clone(),
|
||||
uuid,
|
||||
};
|
||||
request_header.set_option(vmess::REQUEST_OPTION_CHUNK_MASKING);
|
||||
request_header.set_option(vmess::REQUEST_OPTION_GLOBAL_PADDING);
|
||||
request_header.set_option(REQUEST_OPTION_CHUNK_MASKING);
|
||||
request_header.set_option(REQUEST_OPTION_GLOBAL_PADDING);
|
||||
|
||||
match self.security.to_lowercase().as_str() {
|
||||
"chacha20-poly1305" | "chacha20-ietf-poly1305" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_CHACHA20_POLY1305;
|
||||
request_header.security = SECURITY_TYPE_CHACHA20_POLY1305;
|
||||
}
|
||||
"aes-128-gcm" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_AES128_GCM;
|
||||
request_header.security = SECURITY_TYPE_AES128_GCM;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
mod ws;
|
||||
mod stream;
|
||||
|
||||
pub mod tcp;
|
||||
pub mod udp;
|
||||
@@ -6,4 +6,4 @@ pub mod udp;
|
||||
pub use tcp::Handler as TcpHandler;
|
||||
pub use udp::Handler as UdpHandler;
|
||||
|
||||
pub static NAME: &'static str = "ws";
|
||||
pub static NAME: &str = "ws";
|
||||
@@ -51,38 +51,38 @@ impl<S: Stream<Item = Result<Message, WsError>> + Sink<Message> + Unpin> AsyncRe
|
||||
if data.len() > to_read {
|
||||
self.buf.extend_from_slice(&data[to_read..]);
|
||||
}
|
||||
return Poll::Ready(Ok(to_read));
|
||||
Poll::Ready(Ok(to_read))
|
||||
}
|
||||
Message::Close(_) => {
|
||||
// FIXME should we send close here?
|
||||
return Pin::new(&mut self.inner)
|
||||
Pin::new(&mut self.inner)
|
||||
.poll_close(cx)
|
||||
.map_ok(|_| 0)
|
||||
.map_err(|_| {
|
||||
io::Error::new(io::ErrorKind::Other, "error closing")
|
||||
});
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
// FIXME
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"unexpected ws msg",
|
||||
)));
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
// FIXME
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
format!("ws error: {}", err),
|
||||
)));
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// FIXME
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Interrupted, "none msg")));
|
||||
Poll::Ready(Err(io::Error::new(io::ErrorKind::Interrupted, "none msg")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,37 +94,31 @@ impl<S: Sink<Message> + Unpin> AsyncWrite for Adapter<S> {
|
||||
cx: &mut Context,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
match Pin::new(&mut self.inner).poll_ready(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
_ => (),
|
||||
if let Poll::Pending = Pin::new(&mut self.inner).poll_ready(cx) {
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
let msg = Message::Binary(Vec::from(buf));
|
||||
match Pin::new(&mut self.inner).start_send(msg) {
|
||||
Err(_) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"ws send error",
|
||||
)));
|
||||
}
|
||||
Ok(()) => return Poll::Ready(Ok(buf.len())),
|
||||
Err(_) => Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"ws send error",
|
||||
))),
|
||||
Ok(()) => Poll::Ready(Ok(buf.len())),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
|
||||
match Pin::new(&mut self.inner).poll_flush(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(_) => {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(_) => Poll::Ready(Ok(())),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
|
||||
match Pin::new(&mut self.inner).poll_close(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(_) => {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(_) => Poll::Ready(Ok(())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use crate::{
|
||||
session::Session,
|
||||
};
|
||||
|
||||
use super::ws;
|
||||
use super::stream;
|
||||
|
||||
pub struct Handler {
|
||||
pub path: String,
|
||||
@@ -22,7 +22,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyTcpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn tcp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
@@ -51,8 +51,8 @@ impl ProxyTcpHandler for Handler {
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
let ws_stream = ws::Adapter::new(socket);
|
||||
return Ok(Box::new(SimpleStream(ws_stream)));
|
||||
let ws_stream = stream::Adapter::new(socket);
|
||||
Ok(Box::new(SimpleStream(ws_stream)))
|
||||
}
|
||||
None => Err(io::Error::new(io::ErrorKind::Other, "invalid tls input")),
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub struct Handler {
|
||||
#[async_trait]
|
||||
impl ProxyUdpHandler for Handler {
|
||||
fn name(&self) -> &str {
|
||||
return super::NAME;
|
||||
super::NAME
|
||||
}
|
||||
|
||||
fn udp_connect_addr(&self) -> Option<(String, u16, SocketAddr)> {
|
||||
|
||||
+6
-6
@@ -11,14 +11,14 @@ use log::*;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
pub struct Session {
|
||||
pub source: Option<SocketAddr>,
|
||||
pub source: SocketAddr,
|
||||
pub destination: SocksAddr,
|
||||
}
|
||||
|
||||
impl Clone for Session {
|
||||
fn clone(&self) -> Self {
|
||||
Session {
|
||||
source: self.source.clone(),
|
||||
source: self.source,
|
||||
destination: self.destination.clone(),
|
||||
}
|
||||
}
|
||||
@@ -369,9 +369,9 @@ impl TryFrom<String> for SocksAddr {
|
||||
if parts[0].len() > 0xff {
|
||||
return Err("domain too long");
|
||||
}
|
||||
return Ok(Self::from((parts[0], port)));
|
||||
Ok(Self::from((parts[0], port)))
|
||||
} else {
|
||||
return Err("invalid port");
|
||||
Err("invalid port")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -381,7 +381,7 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from((buf, addr_type): (&[u8], SocksAddrWireType)) -> Result<Self, Self::Error> {
|
||||
if buf.len() < 1 {
|
||||
if buf.is_empty() {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
|
||||
Ok(Self::Ip((ip, port).into()))
|
||||
}
|
||||
SocksAddrPortLastType::DOMAIN => {
|
||||
if buf.len() < 1 {
|
||||
if buf.is_empty() {
|
||||
return Err(INSUFF_BYTES);
|
||||
}
|
||||
let domain_len = buf[1] as usize;
|
||||
|
||||
Reference in new issue
Block a user