chore: update deps

This commit is contained in:
eric committed 2023-09-26 08:25:12 +08:00
1 parent dcc6080f7e
commit 8fd4936b86
22 files changed
+214 -145

No files matched your search

+5
View File
@@ -1,5 +1,10 @@
.PHONY: local local-dev test proto-gen
CFG_COMMIT_HASH := $(shell git rev-parse HEAD | cut -c 1-7)
export CFG_COMMIT_HASH := $(CFG_COMMIT_HASH)
CFG_COMMIT_DATE := $(shell git log --format="%ci" -n 1)
export CFG_COMMIT_DATE := $(CFG_COMMIT_DATE)
local:
cargo build -p leaf-bin --release
+45 -42
View File
@@ -100,15 +100,15 @@ outbound-tryall = []
outbound-chain = []
outbound-amux= ["tokio-util"]
outbound-quic = ["quinn", "rustls", "webpki-roots", "rustls-pemfile"]
outbound-select = []
outbound-vmess = ["lz_fnv", "cfb-mode", "hmac", "aes", "sha3", "digest", "uuid", "md-5", "tokio-util"]
outbound-select = ["directories"]
outbound-vmess = ["lz_fnv", "cfb-mode", "hmac", "aes", "sha3", "digest", "uuid", "md-5", "tokio-util", "byteorder"]
# Inbounds
inbound-trojan = ["sha2", "hex"]
inbound-shadowsocks = ["hkdf", "sha-1", "md-5", "tokio-util"]
inbound-socks = []
inbound-http = ["http"]
inbound-tun = ["tun", "netstack-lwip"]
inbound-tun = ["tun", "netstack-lwip", "pnet_datalink"]
inbound-ws = ["tungstenite", "tokio-tungstenite", "url", "http"]
inbound-amux = ["tokio-util"]
inbound-quic = ["quinn", "rustls", "webpki-roots"]
@@ -116,7 +116,7 @@ inbound-tls = []
inbound-chain = []
inbound-cat = ["tokio/io-std"]
plugin = []
plugin = ["async-ffi", "libloading"]
stat = []
api = ["warp"]
auto-reload = ["notify"]
@@ -125,22 +125,40 @@ ctrlc = ["tokio/signal"]
[dependencies]
# Common
tokio = { version = "1", features = ["sync", "io-util", "net", "time", "rt", "rt-multi-thread"] }
futures-util = "0.3"
protobuf = "3.2"
thiserror = "1.0"
futures = "0.3"
async-trait = "0.1"
byteorder = "1"
bytes = "1"
lazy_static = "1.4.0"
lazy_static = "1.4"
anyhow = "1.0"
rand = "0.8"
socket2 = "0.4"
directories = "4.0"
async-ffi = "0.2"
libloading = "0.7"
socket2 = "0.5"
async-recursion = "1.0"
# DNS
trust-dns-proto = { version = "0.23", default-features = false }
lru = "0.11"
# Logging
tracing = "0.1"
tracing-appender = "0.2"
tracing-subscriber = "0.3"
chrono = "0.4"
colored = "2.0"
# Router
maxminddb = { version = "0.23", features = ["mmap"] }
memmap2 = "0.8"
cidr = "0.2"
# outbound-select
directories = { version = "4.0", optional = true }
# plugin
async-ffi = { version = "0.2", optional = true }
libloading = { version = "0.7", optional = true }
# config-json
serde_json = { version = "1.0", features = ["raw_value"], optional = true }
serde_derive = { version = "1.0", optional = true }
@@ -155,46 +173,30 @@ openssl = { version = "0.10", features = ["vendored"], optional = true }
# Ring
ring = { version = "0.16", optional = true }
# Router
maxminddb = { version = "0.21", features = ["mmap"] }
memmap2 = "0.3"
cidr = { version = "0.2" }
# DNS
trust-dns-proto = { version = "0.20", default-features = false }
lru = "0.7"
# Logging
tracing = "0.1"
tracing-appender = "0.2"
tracing-subscriber = "0.3"
chrono = "0.4"
colored = "2.0"
# TLS/rustls/QUIC
tokio-rustls = { version = "0.23", features = ["dangerous_configuration"], optional = true }
webpki-roots = { version = "0.22", optional = true }
rustls-pemfile = { version = "1.0.2", optional = true }
tokio-rustls = { version = "0.24", features = ["dangerous_configuration"], optional = true }
webpki-roots = { version = "0.25", optional = true }
rustls-pemfile = { version = "1.0", optional = true }
# TLS/openssl
openssl-probe = { version = "0.1", optional = true }
tokio-openssl = { version = "0.6", optional = true }
# WebSocket
tungstenite = { version = "0.16", default-features = false, optional = true }
tokio-tungstenite = { version = "0.16", optional = true }
tungstenite = { version = "0.20", default-features = false, optional = true }
tokio-tungstenite = { version = "0.20", optional = true }
# WebSocket
url = { version = "2.2", optional = true }
url = { version = "2.4", optional = true }
http = { version = "0.2", optional = true }
# SOCKS outbound
async-socks5 = { version = "0.5", optional = true }
# Shadowsocks
hkdf = { version = "0.11", optional = true }
hkdf = { version = "0.12", optional = true }
md-5 = { version = "0.10", optional = true }
sha-1 = { version = "0.9", optional = true }
sha-1 = { version = "0.10", optional = true }
percent-encoding = { version = "2", optional = true }
# Obfs
@@ -202,7 +204,7 @@ base64 = { version = "0.21", optional = true }
memchr = { version = "2", optional = true }
# Trojan
sha2 = { version = "0.9", optional = true }
sha2 = { version = "0.10", optional = true }
hex = { version = "0.4", optional = true }
# VMess
@@ -213,12 +215,13 @@ aes = { version = "0.8", optional = true }
sha3 = { version = "0.10", optional = true }
digest = { version = "0.10", optional = true }
uuid = { version = "1", optional = true }
byteorder = { version = "1", optional = true }
# Failover
lru_time_cache = { version = "0.11", optional = true }
# amux
tokio-util = { version = "0.6", default-features = false, features = ["io"], optional = true }
tokio-util = { version = "0.7", default-features = false, features = ["io"], optional = true }
# QUIC
quinn = { version = "0.10", default-features = false, features = ["tls-rustls", "runtime-tokio"], optional = true }
@@ -228,7 +231,7 @@ rustls = { version = "0.21", optional = true }
warp = { version = "0.3", default-features = false, optional = true }
# Auto reload
notify = { version = "5.0.0-pre.13", optional = true }
notify = { version = "6", optional = true }
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.21"
@@ -239,7 +242,7 @@ tun = { git = "https://github.com/eycorsican/rust-tun.git", branch = "fork", fea
netstack-lwip = { git = "https://github.com/eycorsican/netstack-lwip.git", rev = "4fef23", optional = true }
[target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies]
pnet_datalink = { version = "0.28", package = "pnet_datalink" }
pnet_datalink = { version = "0.34", package = "pnet_datalink", optional = true }
libc = "0.2"
# Used in mobile logger
@@ -247,11 +250,11 @@ libc = "0.2"
memchr = { version = "2" }
[dev-dependencies]
rcgen = "0.8"
sha2 = "0.9"
rcgen = "0.11"
sha2 = "0.10"
tokio = { version = "1", features = ["fs", "sync", "io-util", "net", "time", "rt", "rt-multi-thread"] }
[build-dependencies]
cc = "1.0"
bindgen = "0.59"
bindgen = "0.68"
protobuf-codegen = "3.2"
+12 -9
View File
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::{Arc, Weak};
use std::time::{Duration, Instant};
@@ -74,10 +75,10 @@ impl DnsClient {
let servers = Self::load_servers(dns)?;
let hosts = Self::load_hosts(dns);
let ipv4_cache = Arc::new(TokioMutex::new(LruCache::<String, CacheEntry>::new(
*option::DNS_CACHE_SIZE,
NonZeroUsize::new(*option::DNS_CACHE_SIZE).unwrap(),
)));
let ipv6_cache = Arc::new(TokioMutex::new(LruCache::<String, CacheEntry>::new(
*option::DNS_CACHE_SIZE,
NonZeroUsize::new(*option::DNS_CACHE_SIZE).unwrap(),
)));
Ok(Self {
@@ -232,14 +233,16 @@ impl DnsClient {
let mut ips = Vec::new();
for ans in resp.answers() {
// TODO checks?
match ans.rdata() {
RData::A(ip) => {
ips.push(IpAddr::V4(ip.to_owned()));
if let Some(data) = ans.data() {
match data {
RData::A(ip) => {
ips.push(IpAddr::V4(**ip));
}
RData::AAAA(ip) => {
ips.push(IpAddr::V6(**ip));
}
_ => (),
}
RData::AAAA(ip) => {
ips.push(IpAddr::V6(ip.to_owned()));
}
_ => (),
}
}
if !ips.is_empty() {
+3 -4
View File
@@ -2,14 +2,13 @@ use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use anyhow::{anyhow, Result};
use byteorder::{BigEndian, ByteOrder};
use tokio::sync::RwLock;
use tracing::debug;
use trust_dns_proto::op::{
header::MessageType, op_code::OpCode, response_code::ResponseCode, Message,
};
use trust_dns_proto::rr::{
dns_class::DNSClass, record_data::RData, record_type::RecordType, resource::Record,
dns_class::DNSClass, rdata, record_data::RData, record_type::RecordType, resource::Record,
};
pub enum FakeDnsMode {
@@ -158,7 +157,7 @@ impl FakeDnsImpl {
.set_rr_type(RecordType::A)
.set_ttl(self.ttl)
.set_dns_class(DNSClass::IN)
.set_rdata(RData::A(ip));
.set_data(Some(RData::A(rdata::A(ip))));
resp.add_answer(ans);
}
@@ -226,7 +225,7 @@ impl FakeDnsImpl {
}
fn ip_to_u32(ip: &Ipv4Addr) -> u32 {
BigEndian::read_u32(&ip.octets())
u32::from_be_bytes(ip.octets())
}
}
+51 -13
View File
@@ -1,15 +1,19 @@
use std::{
collections::{hash_map, HashMap},
convert::From,
sync::Arc,
};
#[cfg(feature = "outbound-select")]
use std::sync::Arc;
use anyhow::{anyhow, Result};
use futures::future::AbortHandle;
use protobuf::Message;
use tokio::sync::RwLock;
use tracing::{debug, trace};
#[cfg(feature = "outbound-select")]
use tokio::sync::RwLock;
#[cfg(feature = "outbound-chain")]
use crate::proxy::chain;
#[cfg(feature = "outbound-failover")]
@@ -52,12 +56,14 @@ use crate::{
proxy::{outbound::HandlerBuilder, *},
};
#[cfg(feature = "outbound-select")]
use super::selector::OutboundSelector;
pub struct OutboundManager {
handlers: HashMap<String, AnyOutboundHandler>,
#[cfg(feature = "plugin")]
external_handlers: super::plugin::ExternalHandlers,
#[cfg(feature = "outbound-select")]
selectors: Arc<super::Selectors>,
default_handler: Option<String>,
abort_handles: Vec<AbortHandle>,
@@ -596,16 +602,23 @@ impl OutboundManager {
outbounds: &Vec<Outbound>,
handlers: &mut HashMap<String, AnyOutboundHandler>,
#[cfg(feature = "plugin")] external_handlers: &mut super::plugin::ExternalHandlers,
selectors: &mut super::Selectors,
#[cfg(feature = "outbound-select")] selectors: &mut super::Selectors,
) -> Result<()> {
// FIXME a better way to find outbound deps?
for _i in 0..8 {
#[allow(unused_labels)]
'outbounds: for outbound in outbounds.iter() {
let tag = String::from(&outbound.tag);
if handlers.contains_key(&tag) || selectors.contains_key(&tag) {
if handlers.contains_key(&tag) {
continue;
}
#[cfg(feature = "outbound-select")]
{
if selectors.contains_key(&tag) {
continue;
}
}
#[allow(clippy::single_match)]
match outbound.protocol.as_str() {
#[cfg(feature = "outbound-select")]
@@ -648,7 +661,12 @@ impl OutboundManager {
selected: selected.clone(),
});
let datagram = Box::new(select::DatagramHandler { actors, selected });
selectors.insert(tag.clone(), selector);
#[cfg(feature = "outbound-select")]
{
selectors.insert(tag.clone(), selector);
}
let handler = HandlerBuilder::default()
.tag(tag.clone())
.stream_handler(stream)
@@ -676,9 +694,12 @@ impl OutboundManager {
dns_client: SyncDnsClient,
) -> Result<()> {
// Save outound select states.
let mut selected_outbounds = HashMap::new();
for (k, v) in self.selectors.iter() {
selected_outbounds.insert(k.to_owned(), v.read().await.get_selected_tag());
#[cfg(feature = "outbound-select")]
{
let mut selected_outbounds = HashMap::new();
for (k, v) in self.selectors.iter() {
selected_outbounds.insert(k.to_owned(), v.read().await.get_selected_tag());
}
}
// Load new outbounds.
@@ -688,7 +709,10 @@ impl OutboundManager {
let mut external_handlers = super::plugin::ExternalHandlers::new();
let mut default_handler: Option<String> = None;
let mut abort_handles: Vec<AbortHandle> = Vec::new();
#[cfg(feature = "outbound-select")]
let mut selectors: super::Selectors = HashMap::new();
for _i in 0..4 {
Self::load_handlers(
outbounds,
@@ -704,15 +728,19 @@ impl OutboundManager {
&mut handlers,
#[cfg(feature = "plugin")]
&mut external_handlers,
#[cfg(feature = "outbound-select")]
&mut selectors,
)?;
}
// Restore outbound select states.
for (k, v) in selected_outbounds.iter() {
for (k2, v2) in selectors.iter_mut() {
if k == k2 {
let _ = v2.write().await.set_selected(v);
#[cfg(feature = "outbound-select")]
{
for (k, v) in selected_outbounds.iter() {
for (k2, v2) in selectors.iter_mut() {
if k == k2 {
let _ = v2.write().await.set_selected(v);
}
}
}
}
@@ -723,11 +751,16 @@ impl OutboundManager {
}
self.handlers = handlers;
#[cfg(feature = "plugin")]
{
self.external_handlers = external_handlers;
}
self.selectors = Arc::new(selectors);
#[cfg(feature = "outbound-select")]
{
self.selectors = Arc::new(selectors);
}
self.default_handler = default_handler;
self.abort_handles = abort_handles;
Ok(())
@@ -739,6 +772,7 @@ impl OutboundManager {
let mut external_handlers = super::plugin::ExternalHandlers::new();
let mut default_handler: Option<String> = None;
let mut abort_handles: Vec<AbortHandle> = Vec::new();
#[cfg(feature = "outbound-select")]
let mut selectors: super::Selectors = HashMap::new();
for _i in 0..4 {
Self::load_handlers(
@@ -755,6 +789,7 @@ impl OutboundManager {
&mut handlers,
#[cfg(feature = "plugin")]
&mut external_handlers,
#[cfg(feature = "outbound-select")]
&mut selectors,
)?;
}
@@ -762,6 +797,8 @@ impl OutboundManager {
handlers,
#[cfg(feature = "plugin")]
external_handlers,
#[cfg(feature = "outbound-select")]
selectors: Arc::new(selectors),
default_handler,
abort_handles,
@@ -786,6 +823,7 @@ impl OutboundManager {
}
}
#[cfg(feature = "outbound-select")]
pub fn get_selector(&self, tag: &str) -> Option<Arc<RwLock<OutboundSelector>>> {
self.selectors.get(tag).map(Clone::clone)
}
+7 -2
View File
@@ -1,13 +1,18 @@
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "outbound-select")]
use std::{collections::HashMap, sync::Arc};
#[cfg(feature = "outbound-select")]
use tokio::sync::RwLock;
pub mod manager;
#[cfg(feature = "outbound-select")]
pub mod selector;
#[cfg(feature = "outbound-select")]
pub mod selector_cache;
#[cfg(feature = "plugin")]
pub mod plugin;
#[cfg(feature = "outbound-select")]
pub type Selectors = HashMap<String, Arc<RwLock<selector::OutboundSelector>>>;
+1 -1
View File
@@ -6,7 +6,7 @@ use anyhow::Result;
use cidr::IpCidr;
use futures::TryFutureExt;
use maxminddb::geoip2::Country;
use memmap2::Mmap;
use maxminddb::Mmap;
use tracing::{debug, trace, warn};
use crate::app::SyncDnsClient;
+13 -8
View File
@@ -4,7 +4,6 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use byteorder::{BigEndian, ByteOrder};
use bytes::BytesMut;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
use tokio::time::timeout;
@@ -47,7 +46,8 @@ where
if sbuf[1] != 0x3 {
return Ok(None);
}
let header_len = BigEndian::read_u16(&sbuf[3..5]) as usize;
let header_len =
u16::from_be_bytes(sbuf[3..5].try_into().unwrap()) as usize;
if sbuf.len() < 5 + header_len {
continue;
}
@@ -64,7 +64,8 @@ where
if sbuf.len() < 2 {
continue;
}
let cipher_suite_bytes = BigEndian::read_u16(&sbuf[..2]) as usize;
let cipher_suite_bytes =
u16::from_be_bytes(sbuf[..2].try_into().unwrap()) as usize;
if sbuf.len() < 2 + cipher_suite_bytes {
continue;
}
@@ -80,7 +81,8 @@ where
if sbuf.len() < 2 {
continue;
}
let extensions_bytes = BigEndian::read_u16(&sbuf[..2]) as usize;
let extensions_bytes =
u16::from_be_bytes(sbuf[..2].try_into().unwrap()) as usize;
if sbuf.len() < 2 + extensions_bytes {
continue;
}
@@ -90,8 +92,9 @@ where
if sbuf.len() < 4 {
continue 'outer;
}
let extension = BigEndian::read_u16(&sbuf[..2]);
let extension_len = BigEndian::read_u16(&sbuf[2..4]) as usize;
let extension = u16::from_be_bytes(sbuf[..2].try_into().unwrap());
let extension_len =
u16::from_be_bytes(sbuf[2..4].try_into().unwrap()) as usize;
sbuf = &sbuf[4..];
if sbuf.len() < extension_len {
continue 'outer;
@@ -102,7 +105,8 @@ where
if ebuf.len() < 2 {
continue 'outer;
}
let entry_len = BigEndian::read_u16(&ebuf[..2]) as usize;
let entry_len =
u16::from_be_bytes(ebuf[..2].try_into().unwrap()) as usize;
ebuf = &ebuf[2..];
if ebuf.len() < entry_len {
continue 'outer;
@@ -119,7 +123,8 @@ where
if ebuf.len() < 2 {
continue 'outer;
}
let hostname_len = BigEndian::read_u16(&ebuf[..2]) as usize;
let hostname_len =
u16::from_be_bytes(ebuf[..2].try_into().unwrap()) as usize;
ebuf = &ebuf[2..];
if ebuf.len() < hostname_len {
continue 'outer;
+3
View File
@@ -117,6 +117,7 @@ impl RuntimeManager {
self.stat_manager.clone()
}
#[cfg(feature = "outbound-select")]
pub async fn set_outbound_selected(&self, outbound: &str, select: &str) -> Result<(), Error> {
if let Some(selector) = self.outbound_manager.read().await.get_selector(outbound) {
selector
@@ -129,6 +130,7 @@ impl RuntimeManager {
}
}
#[cfg(feature = "outbound-select")]
pub async fn get_outbound_selected(&self, outbound: &str) -> Result<String, Error> {
if let Some(selector) = self.outbound_manager.read().await.get_selector(outbound) {
return Ok(selector.read().await.get_selected_tag());
@@ -136,6 +138,7 @@ impl RuntimeManager {
Err(Error::Config(anyhow!("not found")))
}
#[cfg(feature = "outbound-select")]
pub async fn get_outbound_selects(&self, outbound: &str) -> Result<Vec<String>, Error> {
if let Some(selector) = self.outbound_manager.read().await.get_selector(outbound) {
return Ok(selector.read().await.get_available_tags());
+6 -6
View File
@@ -13,10 +13,10 @@ use thiserror::Error;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::{TcpSocket, TcpStream, UdpSocket};
use tokio::time::timeout;
use tracing::{trace};
use tracing::trace;
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
use std::os::unix::io::{AsFd, AsRawFd};
#[cfg(windows)]
use std::os::windows::io::AsRawSocket;
#[cfg(target_os = "android")]
@@ -163,7 +163,7 @@ async fn protect_socket(fd: RawFd) -> io::Result<()> {
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
trait BindSocket: AsRawFd {
trait BindSocket: AsFd {
fn bind(&self, bind_addr: &SocketAddr) -> io::Result<()>;
}
@@ -232,14 +232,14 @@ async fn bind_socket<T: BindSocket>(socket: &T, indicator: &SocketAddr) -> io::R
let ret = match indicator {
SocketAddr::V4(..) => libc::setsockopt(
socket.as_raw_fd(),
socket.as_fd().as_raw_fd(),
libc::IPPROTO_IP,
libc::IP_BOUND_IF,
&ifidx as *const _ as *const libc::c_void,
std::mem::size_of::<libc::c_uint>() as libc::socklen_t,
),
SocketAddr::V6(..) => libc::setsockopt(
socket.as_raw_fd(),
socket.as_fd().as_raw_fd(),
libc::IPPROTO_IPV6,
libc::IPV6_BOUND_IF,
&ifidx as *const _ as *const libc::c_void,
@@ -334,7 +334,7 @@ fn apply_socket_opts_internal(s: SockRef) -> io::Result<()> {
}
#[cfg(unix)]
fn apply_socket_opts<S: AsRawFd>(socket: &S) -> io::Result<()> {
fn apply_socket_opts<S: AsFd>(socket: &S) -> io::Result<()> {
let sock_ref = SockRef::from(socket);
apply_socket_opts_internal(sock_ref)
}
+1 -1
View File
@@ -59,7 +59,7 @@ impl Manager {
}
}
} else {
roots.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
roots.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
+4 -4
View File
@@ -1,7 +1,6 @@
use std::mem::MaybeUninit;
use std::{cmp::min, io, pin::Pin};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, Bytes, BytesMut};
use futures::{
ready,
@@ -9,7 +8,7 @@ use futures::{
};
use rand::{rngs::StdRng, Rng, RngCore, SeedableRng};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tracing::{debug};
use tracing::debug;
use crate::common::crypto::{
aead::{AeadCipher, AeadDecryptor, AeadEncryptor},
@@ -176,7 +175,8 @@ where
}
let dec = me.dec.as_mut().expect("uninitialized cipher");
dec.decrypt(&mut me.read_buf).map_err(|_| crypto_err())?;
let payload_len = BigEndian::read_u16(&me.read_buf) as usize;
let payload_len =
u16::from_be_bytes(me.read_buf[..2].try_into().unwrap()) as usize;
// ready to read payload
me.read_state = ReadState::WaitingData(payload_len);
@@ -265,7 +265,7 @@ where
let length_size = 2 + me.cipher.tag_len();
length_and_payload.reserve(length_size);
unsafe { length_and_payload.set_len(2) };
BigEndian::write_u16(&mut length_and_payload[..2], consume_len as u16);
length_and_payload[..2].copy_from_slice(&(consume_len as u16).to_be_bytes());
enc.encrypt(&mut length_and_payload)
.map_err(|_| crypto_err())?;
let mut payload = length_and_payload.split_off(length_size);
+10 -16
View File
@@ -5,14 +5,14 @@ use std::io::BufReader;
use anyhow::Result;
use async_trait::async_trait;
use futures::TryFutureExt;
use tracing::{trace};
use tracing::trace;
#[cfg(feature = "rustls-tls")]
use {
std::sync::Arc,
tokio_rustls::{
rustls::{ClientConfig, OwnedTrustAnchor, RootCertStore, ServerName},
webpki, TlsConnector,
rustls::{Certificate, ClientConfig, OwnedTrustAnchor, RootCertStore, ServerName},
TlsConnector,
},
};
@@ -72,25 +72,19 @@ impl Handler {
if let Some(cert) = certificate {
let mut pem = BufReader::new(File::open(cert)?);
let certs = rustls_pemfile::certs(&mut pem)?;
let trust_anchors = certs.iter().map(|cert| {
let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap(); // FIXME
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
});
root_cert_store.add_server_trust_anchors(trust_anchors);
for cert in certs.into_iter().map(Certificate) {
root_cert_store.add(&cert)?;
}
} else {
root_cert_store.add_server_trust_anchors(
webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
root_cert_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(
|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}),
);
},
));
}
let mut config = ClientConfig::builder()
.with_safe_defaults()
+2 -3
View File
@@ -4,12 +4,11 @@ use std::net::SocketAddr;
use anyhow::anyhow;
use async_trait::async_trait;
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use futures::TryFutureExt;
use sha2::{Digest, Sha224};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tracing::{trace};
use tracing::trace;
use crate::{
proxy::*,
@@ -67,7 +66,7 @@ where
.read_exact(&mut buf2)
.map_err(|e| ProxyError::DatagramFatal(e.into()))
.await?;
let payload_len = BigEndian::read_u16(&buf2) as usize;
let payload_len = u16::from_be_bytes(buf2[..2].try_into().unwrap()) as usize;
if buf.len() < payload_len {
return Err(ProxyError::DatagramFatal(anyhow!("Small buffer")));
}
+2 -3
View File
@@ -2,12 +2,11 @@ use std::cmp::min;
use std::io;
use async_trait::async_trait;
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use futures::future::TryFutureExt;
use sha2::{Digest, Sha224};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf};
use tracing::{trace};
use tracing::trace;
use crate::{proxy::*, session::*};
@@ -98,7 +97,7 @@ where
let mut buf2 = BytesMut::new();
buf2.resize(2, 0);
let _ = self.0.read_exact(&mut buf2).await?;
let payload_len = BigEndian::read_u16(&buf2);
let payload_len = u16::from_be_bytes(buf2[..2].try_into().unwrap());
let _ = self.0.read_exact(&mut buf2).await?;
if &buf2[..2] != b"\r\n" {
return Err(io::Error::new(io::ErrorKind::Other, "Expected CLRF"));
+6 -7
View File
@@ -3,6 +3,7 @@ use std::io::{self, ErrorKind};
use async_trait::async_trait;
use futures::TryFutureExt;
use tokio_tungstenite::accept_hdr_async;
use tracing::debug;
use tungstenite::handshake::server::{Callback, ErrorResponse, Request, Response};
use crate::{proxy::*, session::Session};
@@ -63,14 +64,12 @@ impl InboundStreamHandler for Handler {
mut sess: Session,
stream: AnyStream,
) -> std::io::Result<AnyInboundTransport> {
let s = accept_hdr_async(stream, SimpleCallback::new(&mut sess, &self.path))
.map_err(|e| io::Error::new(ErrorKind::Other, format!("accept ws failed: {}", e)))
.await?;
debug!("accepted WS stream");
Ok(InboundTransport::Stream(
Box::new(super::ws_stream::WebSocketToStream::new(
accept_hdr_async(stream, SimpleCallback::new(&mut sess, &self.path))
.map_err(|e| {
io::Error::new(ErrorKind::Other, format!("accept ws failed: {}", e))
})
.await?,
)),
Box::new(super::ws_stream::WebSocketToStream::new(s)),
sess,
))
}
+16 -14
View File
@@ -1,9 +1,11 @@
use std::collections::HashMap;
use std::io;
use ::http::{HeaderName, HeaderValue};
use async_trait::async_trait;
use futures::TryFutureExt;
use tokio_tungstenite::client_async_with_config;
use tungstenite::client::IntoClientRequest;
use tungstenite::protocol::WebSocketConfig;
use url::Url;
@@ -19,20 +21,24 @@ struct Request<'a> {
pub headers: &'a HashMap<String, String>,
}
impl<'a> tungstenite::client::IntoClientRequest for Request<'a> {
impl<'a> IntoClientRequest for Request<'a> {
fn into_client_request(
self,
) -> tungstenite::error::Result<tungstenite::handshake::client::Request> {
let mut builder = ::http::Request::builder()
.method("GET")
.uri(self.uri)
.header("User-Agent", &*crate::option::HTTP_USER_AGENT);
let mut req = self.uri.into_client_request()?;
for (k, v) in self.headers.iter() {
if k != "Host" {
builder = builder.header(k, v);
if k.to_uppercase() != "HOST" {
req.headers_mut()
.insert(HeaderName::try_from(k)?, HeaderValue::from_str(&v)?);
}
}
Ok(builder.body(())?)
if !crate::option::HTTP_USER_AGENT.is_empty() {
req.headers_mut().insert(
::http::header::USER_AGENT,
HeaderValue::from_static(&*crate::option::HTTP_USER_AGENT),
);
}
Ok(req)
}
}
@@ -60,12 +66,8 @@ impl OutboundStreamHandler for Handler {
uri: &url.to_string(),
headers: &self.headers,
};
let ws_config = WebSocketConfig {
max_send_queue: Some(4),
max_message_size: Some(64 << 20),
max_frame_size: Some(16 << 20),
accept_unmasked_frames: false,
};
let mut ws_config = WebSocketConfig::default();
ws_config.write_buffer_size = 0;
let (socket, _) = client_async_with_config(req, stream, Some(ws_config))
.map_err(|e| {
io::Error::new(
+5
View File
@@ -10,6 +10,7 @@ use futures::{
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tracing::trace;
use tungstenite::error::Error as WsError;
use tungstenite::Message;
@@ -59,6 +60,7 @@ impl<S: Stream<Item = Result<Message, WsError>> + Sink<Message> + Unpin> AsyncRe
if data.len() > to_read {
self.buf.extend_from_slice(&data[to_read..]);
}
trace!("poll_read {} bytes", buf.filled().len());
Ok(())
}
Message::Close(_) => Ok(()),
@@ -75,6 +77,7 @@ impl<S: Sink<Message> + Unpin> AsyncWrite for WebSocketToStream<S> {
cx: &mut Context,
buf: &[u8],
) -> Poll<io::Result<usize>> {
trace!("poll_write {} bytes", buf.len());
ready!(Pin::new(&mut self.inner)
.poll_ready(cx)
.map_err(|_| broken_pipe()))?;
@@ -84,6 +87,8 @@ impl<S: Sink<Message> + Unpin> AsyncWrite for WebSocketToStream<S> {
.start_send(msg)
.map_err(|_| broken_pipe())?;
let _ = Pin::new(&mut self.inner).poll_flush(cx);
Poll::Ready(Ok(buf.len()))
}
+3 -4
View File
@@ -5,7 +5,6 @@ use std::{
string::ToString,
};
use byteorder::{BigEndian, ByteOrder};
use bytes::BufMut;
use tokio::io::{AsyncRead, AsyncReadExt};
@@ -463,7 +462,7 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
if buf.len() < 4 + 2 {
return Err(insuff_bytes());
}
let port = BigEndian::read_u16(&buf[..2]);
let port = u16::from_be_bytes(buf[..2].try_into().unwrap());
let buf = &buf[2..];
let mut ip_bytes = [0u8; 4];
(&mut ip_bytes).copy_from_slice(&buf[..4]);
@@ -475,7 +474,7 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
if buf.len() < 16 + 2 {
return Err(insuff_bytes());
}
let port = BigEndian::read_u16(&buf[..2]);
let port = u16::from_be_bytes(buf[..2].try_into().unwrap());
let buf = &buf[2..];
let mut ip_bytes = [0u8; 16];
(&mut ip_bytes).copy_from_slice(&buf[..16]);
@@ -487,7 +486,7 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
if buf.len() < 3 {
return Err(insuff_bytes());
}
let port = BigEndian::read_u16(&buf[..2]);
let port = u16::from_be_bytes(buf[..2].try_into().unwrap());
let buf = &buf[2..];
let domain_len = buf[0] as usize;
let buf = &buf[1..];
+7 -8
View File
@@ -313,14 +313,13 @@ pub fn test_data_transfering_reliability_on_configs(
let dst_file = "destination_random_bytes.bin";
let source = path.join(src_file);
let dst = path.join(dst_file);
if !source.exists() {
let mut rng = StdRng::from_entropy();
let mut data = vec![0u8; 25 * 1024 * 1024]; // 25MB payload
rng.fill_bytes(&mut data);
let mut f = std::fs::File::create(source).unwrap();
f.write_all(&data).unwrap();
f.sync_all().unwrap();
}
std::fs::remove_file(&source).unwrap();
let mut rng = StdRng::from_entropy();
let mut data = vec![0u8; 2 * 1024 * 1024];
rng.fill_bytes(&mut data);
let mut f = std::fs::File::create(source).unwrap();
f.write_all(&data).unwrap();
f.sync_all().unwrap();
// TCP uplink
let recv_task = async move {
+6
View File
@@ -16,6 +16,9 @@ mod common;
fn test_in_chain_1() {
let config1 = r#"
{
"log": {
"level": "trace"
},
"inbounds": [
{
"protocol": "socks",
@@ -55,6 +58,9 @@ fn test_in_chain_1() {
let config2 = r#"
{
"log": {
"level": "trace"
},
"inbounds": [
{
"protocol": "chain",
+6
View File
@@ -16,6 +16,9 @@ mod common;
fn test_ws_trojan() {
let config1 = r#"
{
"log": {
"level": "trace"
},
"inbounds": [
{
"protocol": "socks",
@@ -55,6 +58,9 @@ fn test_ws_trojan() {
let config2 = r#"
{
"log": {
"level": "trace"
},
"inbounds": [
{
"protocol": "chain",