diff --git a/Makefile b/Makefile index 8a5a21d..6cdbd73 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index 5007148..feecc6c 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -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" diff --git a/leaf/src/app/dns_client.rs b/leaf/src/app/dns_client.rs index 631e44a..56718fe 100644 --- a/leaf/src/app/dns_client.rs +++ b/leaf/src/app/dns_client.rs @@ -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::::new( - *option::DNS_CACHE_SIZE, + NonZeroUsize::new(*option::DNS_CACHE_SIZE).unwrap(), ))); let ipv6_cache = Arc::new(TokioMutex::new(LruCache::::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() { diff --git a/leaf/src/app/fake_dns.rs b/leaf/src/app/fake_dns.rs index 376b104..f642d3b 100644 --- a/leaf/src/app/fake_dns.rs +++ b/leaf/src/app/fake_dns.rs @@ -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()) } } diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index 8659c17..9648583 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -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, #[cfg(feature = "plugin")] external_handlers: super::plugin::ExternalHandlers, + #[cfg(feature = "outbound-select")] selectors: Arc, default_handler: Option, abort_handles: Vec, @@ -596,16 +602,23 @@ impl OutboundManager { outbounds: &Vec, handlers: &mut HashMap, #[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 = None; let mut abort_handles: Vec = 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 = None; let mut abort_handles: Vec = 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>> { self.selectors.get(tag).map(Clone::clone) } diff --git a/leaf/src/app/outbound/mod.rs b/leaf/src/app/outbound/mod.rs index 9d45794..b37b815 100644 --- a/leaf/src/app/outbound/mod.rs +++ b/leaf/src/app/outbound/mod.rs @@ -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>>; diff --git a/leaf/src/app/router.rs b/leaf/src/app/router.rs index 9d4ce14..53aaf4a 100644 --- a/leaf/src/app/router.rs +++ b/leaf/src/app/router.rs @@ -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; diff --git a/leaf/src/common/sniff.rs b/leaf/src/common/sniff.rs index 70e3095..737bd2a 100644 --- a/leaf/src/common/sniff.rs +++ b/leaf/src/common/sniff.rs @@ -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; diff --git a/leaf/src/lib.rs b/leaf/src/lib.rs index c13903f..829a325 100644 --- a/leaf/src/lib.rs +++ b/leaf/src/lib.rs @@ -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 { 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, Error> { if let Some(selector) = self.outbound_manager.read().await.get_selector(outbound) { return Ok(selector.read().await.get_available_tags()); diff --git a/leaf/src/proxy/mod.rs b/leaf/src/proxy/mod.rs index d8fdc57..aec4a0e 100644 --- a/leaf/src/proxy/mod.rs +++ b/leaf/src/proxy/mod.rs @@ -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(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::() 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(socket: &S) -> io::Result<()> { +fn apply_socket_opts(socket: &S) -> io::Result<()> { let sock_ref = SockRef::from(socket); apply_socket_opts_internal(sock_ref) } diff --git a/leaf/src/proxy/quic/outbound/stream.rs b/leaf/src/proxy/quic/outbound/stream.rs index f5623eb..4f9072f 100644 --- a/leaf/src/proxy/quic/outbound/stream.rs +++ b/leaf/src/proxy/quic/outbound/stream.rs @@ -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, diff --git a/leaf/src/proxy/shadowsocks/shadow.rs b/leaf/src/proxy/shadowsocks/shadow.rs index f648ddd..53899e1 100644 --- a/leaf/src/proxy/shadowsocks/shadow.rs +++ b/leaf/src/proxy/shadowsocks/shadow.rs @@ -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); diff --git a/leaf/src/proxy/tls/outbound/stream.rs b/leaf/src/proxy/tls/outbound/stream.rs index 592cb7d..2af55f3 100644 --- a/leaf/src/proxy/tls/outbound/stream.rs +++ b/leaf/src/proxy/tls/outbound/stream.rs @@ -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() diff --git a/leaf/src/proxy/trojan/inbound/stream.rs b/leaf/src/proxy/trojan/inbound/stream.rs index ee723f9..fe8541e 100644 --- a/leaf/src/proxy/trojan/inbound/stream.rs +++ b/leaf/src/proxy/trojan/inbound/stream.rs @@ -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"))); } diff --git a/leaf/src/proxy/trojan/outbound/datagram.rs b/leaf/src/proxy/trojan/outbound/datagram.rs index b2a09c5..cdadc23 100644 --- a/leaf/src/proxy/trojan/outbound/datagram.rs +++ b/leaf/src/proxy/trojan/outbound/datagram.rs @@ -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")); diff --git a/leaf/src/proxy/ws/inbound/stream.rs b/leaf/src/proxy/ws/inbound/stream.rs index 91d0472..55b9395 100644 --- a/leaf/src/proxy/ws/inbound/stream.rs +++ b/leaf/src/proxy/ws/inbound/stream.rs @@ -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 { + 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, )) } diff --git a/leaf/src/proxy/ws/outbound/stream.rs b/leaf/src/proxy/ws/outbound/stream.rs index c29ac49..6ad0f82 100644 --- a/leaf/src/proxy/ws/outbound/stream.rs +++ b/leaf/src/proxy/ws/outbound/stream.rs @@ -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, } -impl<'a> tungstenite::client::IntoClientRequest for Request<'a> { +impl<'a> IntoClientRequest for Request<'a> { fn into_client_request( self, ) -> tungstenite::error::Result { - 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( diff --git a/leaf/src/proxy/ws/stream.rs b/leaf/src/proxy/ws/stream.rs index 5cbfac3..4fc5ae6 100644 --- a/leaf/src/proxy/ws/stream.rs +++ b/leaf/src/proxy/ws/stream.rs @@ -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> + Sink + 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 + Unpin> AsyncWrite for WebSocketToStream { cx: &mut Context, buf: &[u8], ) -> Poll> { + trace!("poll_write {} bytes", buf.len()); ready!(Pin::new(&mut self.inner) .poll_ready(cx) .map_err(|_| broken_pipe()))?; @@ -84,6 +87,8 @@ impl + Unpin> AsyncWrite for WebSocketToStream { .start_send(msg) .map_err(|_| broken_pipe())?; + let _ = Pin::new(&mut self.inner).poll_flush(cx); + Poll::Ready(Ok(buf.len())) } diff --git a/leaf/src/session.rs b/leaf/src/session.rs index bd06b14..12fbb14 100644 --- a/leaf/src/session.rs +++ b/leaf/src/session.rs @@ -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..]; diff --git a/leaf/tests/common.rs b/leaf/tests/common.rs index 407e334..cf72f92 100644 --- a/leaf/tests/common.rs +++ b/leaf/tests/common.rs @@ -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 { diff --git a/leaf/tests/test_in_chain_1.rs b/leaf/tests/test_in_chain_1.rs index 983930d..9308132 100644 --- a/leaf/tests/test_in_chain_1.rs +++ b/leaf/tests/test_in_chain_1.rs @@ -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", diff --git a/leaf/tests/test_ws_trojan.rs b/leaf/tests/test_ws_trojan.rs index 357fbff..a834404 100644 --- a/leaf/tests/test_ws_trojan.rs +++ b/leaf/tests/test_ws_trojan.rs @@ -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",