mirror of
https://github.com/eycorsican/leaf.git
synced 2026-12-05 08:01:26 +00:00
Enhance logging
This commit is contained in:
1 parent
bcc2fc803b
commit
e748167d79
38 files changed
+482
-407
No files matched your search
@@ -9,8 +9,7 @@ use bytes::BufMut;
|
||||
use bytes::BytesMut;
|
||||
use leaf::{
|
||||
app::outbound::plugin::{
|
||||
ExternalOutboundDatagramHandler, ExternalOutboundStreamHandler, PluginRegistrar,
|
||||
PluginSpec,
|
||||
ExternalOutboundDatagramHandler, ExternalOutboundStreamHandler, PluginRegistrar, PluginSpec,
|
||||
},
|
||||
proxy::shadowsocks::shadow::{self, ShadowedDatagram, ShadowedStream},
|
||||
proxy::*,
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::time::Duration;
|
||||
use async_recursion::async_recursion;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{debug, info, warn};
|
||||
use tracing::{debug, info, warn, Instrument};
|
||||
|
||||
use crate::{
|
||||
app::SyncDnsClient,
|
||||
@@ -164,7 +164,15 @@ impl Dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn dispatch_stream<T>(&self, mut sess: Session, mut lhs: T)
|
||||
pub async fn dispatch_stream<T>(&self, sess: Session, lhs: T)
|
||||
where
|
||||
T: 'static + AsyncRead + AsyncWrite + Unpin + Send + Sync,
|
||||
{
|
||||
let span = sess.create_span();
|
||||
self.dispatch_stream_inner(sess, lhs).instrument(span).await
|
||||
}
|
||||
|
||||
async fn dispatch_stream_inner<T>(&self, mut sess: Session, mut lhs: T)
|
||||
where
|
||||
T: 'static + AsyncRead + AsyncWrite + Unpin + Send + Sync,
|
||||
{
|
||||
@@ -345,7 +353,13 @@ impl Dispatcher {
|
||||
}
|
||||
|
||||
#[async_recursion]
|
||||
pub async fn dispatch_datagram(
|
||||
pub async fn dispatch_datagram(&self, sess: Session) -> io::Result<Box<dyn OutboundDatagram>> {
|
||||
let span = sess.create_span();
|
||||
self.dispatch_datagram_inner(sess).instrument(span).await
|
||||
}
|
||||
|
||||
#[async_recursion]
|
||||
async fn dispatch_datagram_inner(
|
||||
&self,
|
||||
mut sess: Session,
|
||||
) -> io::Result<Box<dyn OutboundDatagram>> {
|
||||
|
||||
+123
-96
@@ -7,17 +7,17 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use futures::future::select_ok;
|
||||
use lru::LruCache;
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use tokio::sync::Mutex as TokioMutex;
|
||||
use tokio::time::timeout;
|
||||
use tracing::{debug, trace};
|
||||
use hickory_proto::{
|
||||
op::{
|
||||
header::MessageType, op_code::OpCode, query::Query, response_code::ResponseCode, Message,
|
||||
},
|
||||
rr::{record_data::RData, record_type::RecordType, Name},
|
||||
};
|
||||
use lru::LruCache;
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use tokio::sync::Mutex as TokioMutex;
|
||||
use tokio::time::timeout;
|
||||
use tracing::{debug, trace, Instrument};
|
||||
|
||||
use crate::{app::dispatcher::Dispatcher, option, proxy::*, session::*};
|
||||
|
||||
@@ -176,10 +176,13 @@ impl DnsClient {
|
||||
host: &str,
|
||||
server: &SocketAddr,
|
||||
) -> Result<CacheEntry> {
|
||||
let socket = if is_direct {
|
||||
let (socket, span) = if is_direct {
|
||||
debug!("direct lookup");
|
||||
let socket = self.new_udp_socket(server).await?;
|
||||
Box::new(StdOutboundDatagram::new(socket))
|
||||
(
|
||||
Box::new(StdOutboundDatagram::new(socket)) as Box<dyn OutboundDatagram>,
|
||||
tracing::Span::current(),
|
||||
)
|
||||
} else {
|
||||
debug!("dispatched lookup");
|
||||
if let Some(dispatcher_weak) = self.dispatcher.as_ref() {
|
||||
@@ -196,8 +199,9 @@ impl DnsClient {
|
||||
inbound_tag: "internal".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
let span = sess.create_span();
|
||||
if let Some(dispatcher) = dispatcher_weak.upgrade() {
|
||||
dispatcher.dispatch_datagram(sess).await?
|
||||
(dispatcher.dispatch_datagram(sess).await?, span)
|
||||
} else {
|
||||
return Err(anyhow!("dispatcher is deallocated"));
|
||||
}
|
||||
@@ -205,101 +209,119 @@ impl DnsClient {
|
||||
return Err(anyhow!("could not find a dispatcher"));
|
||||
}
|
||||
};
|
||||
let (mut r, mut s) = socket.split();
|
||||
let server = SocksAddr::from(server);
|
||||
let mut last_err = None;
|
||||
for _i in 0..*option::MAX_DNS_RETRIES {
|
||||
debug!("looking up host {} on {}", host, server);
|
||||
let start = tokio::time::Instant::now();
|
||||
// 1) send DNS request
|
||||
if let Err(err) = s.send_to(&request, &server).await {
|
||||
last_err = Some(anyhow!("send DNS request to {} failed: {}", server, err));
|
||||
// socket send_to error, retry
|
||||
continue;
|
||||
}
|
||||
// 2) wait response
|
||||
let mut buf = vec![0u8; 512];
|
||||
let recv_result = match timeout(
|
||||
Duration::from_secs(*option::DNS_TIMEOUT),
|
||||
r.recv_from(&mut buf),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok((n, _))) => Ok((n, ())),
|
||||
Ok(Err(err)) => Err(anyhow!("recv DNS response from {} failed: {}", server, err)), // socket recv_from error
|
||||
Err(e) => Err(anyhow!("recv DNS response from {} timeout: {}", server, e)), // timeout
|
||||
};
|
||||
// retry
|
||||
if let Err(err) = recv_result {
|
||||
last_err = Some(err);
|
||||
continue;
|
||||
}
|
||||
// happy path !!
|
||||
let n: usize = recv_result.unwrap().0;
|
||||
// 3) parse resp
|
||||
let resp = match Message::from_vec(&buf[..n]) {
|
||||
Ok(resp) => resp,
|
||||
Err(err) => {
|
||||
last_err = Some(anyhow!("parse DNS message from {} failed: {}", server, err));
|
||||
// broken response, no retry
|
||||
|
||||
async move {
|
||||
let (mut r, mut s) = socket.split();
|
||||
let server = SocksAddr::from(server);
|
||||
let mut last_err = None;
|
||||
for _i in 0..*option::MAX_DNS_RETRIES {
|
||||
debug!("looking up host {} on {}", host, server);
|
||||
let start = tokio::time::Instant::now();
|
||||
// 1) send DNS request
|
||||
if let Err(err) = s.send_to(&request, &server).await {
|
||||
last_err = Some(anyhow!("send DNS request to {} failed: {}", server, err));
|
||||
// socket send_to error, retry
|
||||
continue;
|
||||
}
|
||||
// 2) wait response
|
||||
let mut buf = vec![0u8; 512];
|
||||
let recv_result = match timeout(
|
||||
Duration::from_secs(*option::DNS_TIMEOUT),
|
||||
r.recv_from(&mut buf),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok((n, _))) => Ok((n, ())),
|
||||
Ok(Err(err)) => {
|
||||
Err(anyhow!("recv DNS response from {} failed: {}", server, err))
|
||||
} // socket recv_from error
|
||||
Err(e) => Err(anyhow!("recv DNS response from {} timeout: {}", server, e)), // timeout
|
||||
};
|
||||
// retry
|
||||
if let Err(err) = recv_result {
|
||||
last_err = Some(err);
|
||||
continue;
|
||||
}
|
||||
// happy path !!
|
||||
let n: usize = recv_result.unwrap().0;
|
||||
// 3) parse resp
|
||||
let resp = match Message::from_vec(&buf[..n]) {
|
||||
Ok(resp) => resp,
|
||||
Err(err) => {
|
||||
last_err =
|
||||
Some(anyhow!("parse DNS message from {} failed: {}", server, err));
|
||||
// broken response, no retry
|
||||
break;
|
||||
}
|
||||
};
|
||||
// 4) check resp code
|
||||
if resp.response_code() != ResponseCode::NoError {
|
||||
last_err = Some(anyhow!(
|
||||
"DNS response from {} for {} error: {}",
|
||||
server,
|
||||
host,
|
||||
resp.response_code()
|
||||
));
|
||||
// error response, no retry
|
||||
//
|
||||
// TODO Needs more careful investigations, I'm not quite sure about
|
||||
// this.
|
||||
break;
|
||||
}
|
||||
};
|
||||
// 4) check resp code
|
||||
if resp.response_code() != ResponseCode::NoError {
|
||||
last_err = Some(anyhow!("DNS response from {} for {} error: {}", server, host, resp.response_code()));
|
||||
// error response, no retry
|
||||
//
|
||||
// TODO Needs more careful investigations, I'm not quite sure about
|
||||
// this.
|
||||
break;
|
||||
}
|
||||
// 5) find address
|
||||
let mut ips = Vec::new();
|
||||
for ans in resp.answers() {
|
||||
// TODO checks?
|
||||
if let Some(data) = ans.data() {
|
||||
match data {
|
||||
RData::A(ip) => {
|
||||
ips.push(IpAddr::V4(**ip));
|
||||
// 5) find address
|
||||
let mut ips = Vec::new();
|
||||
for ans in resp.answers() {
|
||||
// TODO checks?
|
||||
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));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
if ips.is_empty() {
|
||||
// response with 0 records
|
||||
//
|
||||
// TODO Not sure how to due with this.
|
||||
last_err = Some(anyhow!(
|
||||
"no records in DNS response from {} for {}",
|
||||
server,
|
||||
host
|
||||
));
|
||||
break;
|
||||
}
|
||||
// 6) return cache entry
|
||||
let elapsed = tokio::time::Instant::now().duration_since(start);
|
||||
let ttl = resp.answers().iter().next().unwrap().ttl();
|
||||
debug!(
|
||||
"return {} ips (ttl {}) for {} from {} in {}ms",
|
||||
ips.len(),
|
||||
ttl,
|
||||
host,
|
||||
server,
|
||||
elapsed.as_millis(),
|
||||
);
|
||||
|
||||
let Some(deadline) = Instant::now().checked_add(Duration::from_secs(ttl.into()))
|
||||
else {
|
||||
last_err = Some(anyhow!("invalid ttl"));
|
||||
break;
|
||||
};
|
||||
|
||||
let entry = CacheEntry { ips, deadline };
|
||||
debug!("ips for {}: {:#?}", host, &entry);
|
||||
return Ok(entry);
|
||||
}
|
||||
|
||||
if ips.is_empty() {
|
||||
// response with 0 records
|
||||
//
|
||||
// TODO Not sure how to due with this.
|
||||
last_err = Some(anyhow!("no records in DNS response from {} for {}", server, host));
|
||||
break;
|
||||
}
|
||||
// 6) return cache entry
|
||||
let elapsed = tokio::time::Instant::now().duration_since(start);
|
||||
let ttl = resp.answers().iter().next().unwrap().ttl();
|
||||
debug!(
|
||||
"return {} ips (ttl {}) for {} from {} in {}ms",
|
||||
ips.len(),
|
||||
ttl,
|
||||
host,
|
||||
server,
|
||||
elapsed.as_millis(),
|
||||
);
|
||||
|
||||
let Some(deadline) = Instant::now().checked_add(Duration::from_secs(ttl.into())) else {
|
||||
last_err = Some(anyhow!("invalid ttl"));
|
||||
break;
|
||||
};
|
||||
|
||||
let entry = CacheEntry { ips, deadline };
|
||||
debug!("ips for {}: {:#?}", host, &entry);
|
||||
return Ok(entry);
|
||||
Err(last_err.unwrap_or_else(|| anyhow!("all lookup attempts for {} failed", host)))
|
||||
}
|
||||
Err(last_err.unwrap_or_else(|| anyhow!("all lookup attempts for {} failed", host)))
|
||||
.instrument(span)
|
||||
.await
|
||||
}
|
||||
|
||||
fn new_query(name: Name, ty: RecordType) -> Message {
|
||||
@@ -365,6 +387,11 @@ impl DnsClient {
|
||||
}
|
||||
|
||||
pub async fn _lookup(&self, host: &String, is_direct: bool) -> Result<Vec<IpAddr>> {
|
||||
let span = tracing::info_span!("dns_lookup", host = %host);
|
||||
self._lookup_inner(host, is_direct).instrument(span).await
|
||||
}
|
||||
|
||||
async fn _lookup_inner(&self, host: &String, is_direct: bool) -> Result<Vec<IpAddr>> {
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
return Ok(vec![ip]);
|
||||
}
|
||||
|
||||
@@ -2,14 +2,14 @@ use std::collections::HashMap;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::debug;
|
||||
use hickory_proto::op::{
|
||||
header::MessageType, op_code::OpCode, response_code::ResponseCode, Message,
|
||||
};
|
||||
use hickory_proto::rr::{
|
||||
dns_class::DNSClass, rdata, record_data::RData, record_type::RecordType, resource::Record,
|
||||
};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::debug;
|
||||
|
||||
pub enum FakeDnsMode {
|
||||
Include,
|
||||
|
||||
@@ -26,7 +26,10 @@ pub async fn tcp(
|
||||
let mut buf = Vec::with_capacity(4);
|
||||
let n = stream.read_buf(&mut buf).await?;
|
||||
if n == 0 {
|
||||
Err(anyhow!("EOF during TCP health check for [{}]", handler.tag()))
|
||||
Err(anyhow!(
|
||||
"EOF during TCP health check for [{}]",
|
||||
handler.tag()
|
||||
))
|
||||
} else if buf == b"PONG" {
|
||||
Ok(Instant::now().duration_since(start))
|
||||
} else {
|
||||
@@ -58,6 +61,9 @@ pub async fn udp(
|
||||
if &buf[..n] == b"PONG" {
|
||||
Ok(Instant::now().duration_since(start))
|
||||
} else {
|
||||
Err(anyhow!("Unexpected UDP health check response from [{}]", handler.tag()))
|
||||
Err(anyhow!(
|
||||
"Unexpected UDP health check response from [{}]",
|
||||
handler.tag()
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -72,9 +72,7 @@ impl InboundDatagram for Datagram {
|
||||
}
|
||||
|
||||
fn into_std(self: Box<Self>) -> io::Result<std::net::UdpSocket> {
|
||||
Err(io::Error::other(
|
||||
"cannot convert stdin to UDP socket",
|
||||
))
|
||||
Err(io::Error::other("cannot convert stdin to UDP socket"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -180,9 +180,8 @@ impl InboundManager {
|
||||
}
|
||||
#[cfg(feature = "inbound-quic")]
|
||||
"quic" => {
|
||||
let settings =
|
||||
config::QuicInboundSettings::parse_from_bytes(&inbound.settings)
|
||||
.map_err(|e| anyhow!("invalid [{}] inbound settings: {}", &tag, e))?;
|
||||
let settings = config::QuicInboundSettings::parse_from_bytes(&inbound.settings)
|
||||
.map_err(|e| anyhow!("invalid [{}] inbound settings: {}", &tag, e))?;
|
||||
let datagram = Arc::new(quic::inbound::DatagramHandler::new(
|
||||
settings.certificate.clone(),
|
||||
settings.certificate_key.clone(),
|
||||
|
||||
@@ -10,7 +10,7 @@ use tokio::net::{TcpStream, UdpSocket};
|
||||
use tokio::sync::mpsc::channel as tokio_channel;
|
||||
use tokio::sync::mpsc::{Receiver as TokioReceiver, Sender as TokioSender};
|
||||
use tokio::time::timeout;
|
||||
use tracing::{debug, info, trace, warn};
|
||||
use tracing::{debug, info, trace, warn, Instrument};
|
||||
|
||||
use crate::app::dispatcher::Dispatcher;
|
||||
use crate::app::nat_manager::{NatManager, UdpPacket};
|
||||
@@ -41,6 +41,19 @@ async fn handle_inbound_datagram(
|
||||
socket: Box<dyn InboundDatagram>,
|
||||
sess: Option<Session>,
|
||||
nat_manager: Arc<NatManager>,
|
||||
) {
|
||||
let sess = sess.unwrap_or_default();
|
||||
let span = sess.create_span();
|
||||
handle_inbound_datagram_inner(inbound_tag, socket, Some(sess), nat_manager)
|
||||
.instrument(span)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handle_inbound_datagram_inner(
|
||||
inbound_tag: String,
|
||||
socket: Box<dyn InboundDatagram>,
|
||||
sess: Option<Session>,
|
||||
nat_manager: Arc<NatManager>,
|
||||
) {
|
||||
// Left-hand side socket, it's usually encapsulated with inbound protocol
|
||||
// layers.
|
||||
@@ -165,14 +178,19 @@ async fn handle_inbound_tcp_stream(
|
||||
inbound_tag: handler.tag().clone(),
|
||||
..Default::default()
|
||||
};
|
||||
// Transforms the TCP stream into an inbound transport.
|
||||
let transport = timeout(
|
||||
Duration::from_secs(*crate::option::INBOUND_ACCEPT_TIMEOUT),
|
||||
handler.stream()?.handle(sess, Box::new(stream)),
|
||||
)
|
||||
.await??;
|
||||
handle_inbound_transport(transport, handler, dispatcher, nat_manager).await;
|
||||
Ok(())
|
||||
let span = sess.create_span();
|
||||
async move {
|
||||
// Transforms the TCP stream into an inbound transport.
|
||||
let transport = timeout(
|
||||
Duration::from_secs(*crate::option::INBOUND_ACCEPT_TIMEOUT),
|
||||
handler.stream()?.handle(sess, Box::new(stream)),
|
||||
)
|
||||
.await??;
|
||||
handle_inbound_transport(transport, handler, dispatcher, nat_manager).await;
|
||||
Ok(())
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
}
|
||||
|
||||
// Handle inbounds which listen on TCP.
|
||||
|
||||
+87
-78
@@ -7,7 +7,7 @@ use tokio::sync::{
|
||||
mpsc::{self, Sender},
|
||||
oneshot, Mutex, MutexGuard,
|
||||
};
|
||||
use tracing::{debug, error, trace};
|
||||
use tracing::{debug, error, trace, Instrument};
|
||||
|
||||
use crate::app::dispatcher::Dispatcher;
|
||||
use crate::option;
|
||||
@@ -183,99 +183,108 @@ impl NatManager {
|
||||
// because we have stream type transports for UDP traffic, establishing a
|
||||
// TCP stream would block the task.
|
||||
let raddr_cloned = raddr.clone();
|
||||
tokio::spawn(async move {
|
||||
// new socket to communicate with the target.
|
||||
let socket = match dispatcher.dispatch_datagram(sess).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
debug!("dispatch {} failed: {}", &raddr_cloned, e);
|
||||
sessions.lock().await.remove(&raddr_cloned);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let span = sess.create_span();
|
||||
tokio::spawn(
|
||||
async move {
|
||||
// new socket to communicate with the target.
|
||||
let socket = match dispatcher.dispatch_datagram(sess).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
debug!("dispatch {} failed: {}", &raddr_cloned, e);
|
||||
sessions.lock().await.remove(&raddr_cloned);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let (mut target_sock_recv, mut target_sock_send) = socket.split();
|
||||
let (mut target_sock_recv, mut target_sock_send) = socket.split();
|
||||
|
||||
// downlink
|
||||
let raddr_downlink = raddr_cloned.clone();
|
||||
let downlink_task = async move {
|
||||
let mut buf = vec![0u8; *crate::option::DATAGRAM_BUFFER_SIZE * 1024];
|
||||
loop {
|
||||
match target_sock_recv.recv_from(&mut buf).await {
|
||||
Err(err) => {
|
||||
debug!(
|
||||
"Failed to receive downlink packets on session {}: {}",
|
||||
&raddr_downlink, err
|
||||
);
|
||||
break;
|
||||
}
|
||||
Ok((n, addr)) => {
|
||||
trace!("outbound received UDP packet: src {}, {} bytes", &addr, n);
|
||||
let pkt = UdpPacket::new(
|
||||
buf[..n].to_vec(),
|
||||
addr.clone(),
|
||||
SocksAddr::from(raddr_downlink.address),
|
||||
);
|
||||
if let Err(err) = client_ch_tx.send(pkt).await {
|
||||
// downlink
|
||||
let raddr_downlink = raddr_cloned.clone();
|
||||
let downlink_task = async move {
|
||||
let mut buf = vec![0u8; *crate::option::DATAGRAM_BUFFER_SIZE * 1024];
|
||||
loop {
|
||||
match target_sock_recv.recv_from(&mut buf).await {
|
||||
Err(err) => {
|
||||
debug!(
|
||||
"Failed to send downlink packets on session {} to {}: {}",
|
||||
&raddr_downlink, &addr, err
|
||||
"Failed to receive downlink packets on session {}: {}",
|
||||
&raddr_downlink, err
|
||||
);
|
||||
break;
|
||||
}
|
||||
Ok((n, addr)) => {
|
||||
trace!("outbound received UDP packet: src {}, {} bytes", &addr, n);
|
||||
let pkt = UdpPacket::new(
|
||||
buf[..n].to_vec(),
|
||||
addr.clone(),
|
||||
SocksAddr::from(raddr_downlink.address),
|
||||
);
|
||||
if let Err(err) = client_ch_tx.send(pkt).await {
|
||||
debug!(
|
||||
"Failed to send downlink packets on session {} to {}: {}",
|
||||
&raddr_downlink, &addr, err
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
// activity update
|
||||
{
|
||||
let mut sessions = sessions.lock().await;
|
||||
if let Some(sess) = sessions.get_mut(&raddr_downlink) {
|
||||
if addr.port() == 53 {
|
||||
// If the destination port is 53, we assume it's a
|
||||
// DNS query and set a negative timeout so it will
|
||||
// be removed on next check.
|
||||
sess.2.checked_sub(Duration::from_secs(
|
||||
*option::UDP_SESSION_TIMEOUT,
|
||||
));
|
||||
} else {
|
||||
sess.2 = Instant::now();
|
||||
// activity update
|
||||
{
|
||||
let mut sessions = sessions.lock().await;
|
||||
if let Some(sess) = sessions.get_mut(&raddr_downlink) {
|
||||
if addr.port() == 53 {
|
||||
// If the destination port is 53, we assume it's a
|
||||
// DNS query and set a negative timeout so it will
|
||||
// be removed on next check.
|
||||
sess.2.checked_sub(Duration::from_secs(
|
||||
*option::UDP_SESSION_TIMEOUT,
|
||||
));
|
||||
} else {
|
||||
sess.2 = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sessions.lock().await.remove(&raddr_downlink);
|
||||
}
|
||||
sessions.lock().await.remove(&raddr_downlink);
|
||||
};
|
||||
.instrument(tracing::Span::current());
|
||||
|
||||
let (downlink_task, downlink_task_handle) = abortable(downlink_task);
|
||||
tokio::spawn(downlink_task);
|
||||
let (downlink_task, downlink_task_handle) = abortable(downlink_task);
|
||||
tokio::spawn(downlink_task);
|
||||
|
||||
// Runs a task to receive the abort signal.
|
||||
tokio::spawn(async move {
|
||||
let _ = downlink_abort_rx.await;
|
||||
downlink_task_handle.abort();
|
||||
});
|
||||
// Runs a task to receive the abort signal.
|
||||
tokio::spawn(async move {
|
||||
let _ = downlink_abort_rx.await;
|
||||
downlink_task_handle.abort();
|
||||
});
|
||||
|
||||
// uplink
|
||||
let raddr_uplink = raddr_cloned.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(pkt) = target_ch_rx.recv().await {
|
||||
trace!(
|
||||
"outbound send UDP packet: dst {}, {} bytes",
|
||||
&pkt.dst_addr,
|
||||
pkt.data.len()
|
||||
);
|
||||
if let Err(e) = target_sock_send.send_to(&pkt.data, &pkt.dst_addr).await {
|
||||
debug!(
|
||||
"Failed to send uplink packets on session {} to {}: {:?}",
|
||||
&raddr_uplink, &pkt.dst_addr, e
|
||||
);
|
||||
break;
|
||||
// uplink
|
||||
let raddr_uplink = raddr_cloned.clone();
|
||||
tokio::spawn(
|
||||
async move {
|
||||
while let Some(pkt) = target_ch_rx.recv().await {
|
||||
trace!(
|
||||
"outbound send UDP packet: dst {}, {} bytes",
|
||||
&pkt.dst_addr,
|
||||
pkt.data.len()
|
||||
);
|
||||
if let Err(e) = target_sock_send.send_to(&pkt.data, &pkt.dst_addr).await
|
||||
{
|
||||
debug!(
|
||||
"Failed to send uplink packets on session {} to {}: {:?}",
|
||||
&raddr_uplink, &pkt.dst_addr, e
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Err(e) = target_sock_send.close().await {
|
||||
debug!("Failed to close outbound datagram {}: {}", &raddr_uplink, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = target_sock_send.close().await {
|
||||
debug!("Failed to close outbound datagram {}: {}", &raddr_uplink, e);
|
||||
}
|
||||
});
|
||||
});
|
||||
.instrument(tracing::Span::current()),
|
||||
);
|
||||
}
|
||||
.instrument(span),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,8 @@ impl CopyBuffer {
|
||||
|
||||
pub fn new_with_capacity(size: usize) -> Result<Self, std::io::Error> {
|
||||
let mut buf = Vec::new();
|
||||
buf.try_reserve(size).map_err(|e| {
|
||||
std::io::Error::other(
|
||||
format!("new buffer failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
buf.try_reserve(size)
|
||||
.map_err(|e| std::io::Error::other(format!("new buffer failed: {}", e)))?;
|
||||
buf.resize(size, 0);
|
||||
Ok(Self {
|
||||
read_done: false,
|
||||
|
||||
+89
-31
@@ -482,7 +482,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
target_os = "macos",
|
||||
target_os = "linux"
|
||||
))]
|
||||
InboundSettings::Tun { settings: ext_settings } => {
|
||||
InboundSettings::Tun {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "tun".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::TunInboundSettings::new();
|
||||
@@ -536,11 +538,14 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Cat { settings: ext_settings } => {
|
||||
InboundSettings::Cat {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "cat".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::CatInboundSettings::new();
|
||||
settings.network = ext_settings.network.clone().unwrap_or("tcp".to_string());
|
||||
settings.network =
|
||||
ext_settings.network.clone().unwrap_or("tcp".to_string());
|
||||
settings.address = ext_settings.address.clone();
|
||||
settings.port = ext_settings.port as u32;
|
||||
let settings = settings.write_to_bytes().unwrap();
|
||||
@@ -548,7 +553,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Nf { settings: ext_settings } => {
|
||||
InboundSettings::Nf {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "nf".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::NfInboundSettings::new();
|
||||
@@ -582,7 +589,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Hc { settings: ext_settings } => {
|
||||
InboundSettings::Hc {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "hc".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::HcInboundSettings::new();
|
||||
@@ -602,7 +611,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
inbound.protocol = "http".to_string();
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Shadowsocks { settings: ext_settings } => {
|
||||
InboundSettings::Shadowsocks {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "shadowsocks".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::ShadowsocksInboundSettings::new();
|
||||
@@ -617,7 +628,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Trojan { settings: ext_settings } => {
|
||||
InboundSettings::Trojan {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "trojan".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::TrojanInboundSettings::new();
|
||||
@@ -631,7 +644,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::WebSocket { settings: ext_settings } => {
|
||||
InboundSettings::WebSocket {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "ws".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::WebSocketInboundSettings::new();
|
||||
@@ -648,7 +663,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::AMux { settings: ext_settings } => {
|
||||
InboundSettings::AMux {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "amux".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::AMuxInboundSettings::new();
|
||||
@@ -662,7 +679,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Quic { settings: ext_settings } => {
|
||||
InboundSettings::Quic {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "quic".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::QuicInboundSettings::new();
|
||||
@@ -696,7 +715,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Tls { settings: ext_settings } => {
|
||||
InboundSettings::Tls {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "tls".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::TlsInboundSettings::new();
|
||||
@@ -725,7 +746,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
inbounds.push(inbound);
|
||||
}
|
||||
InboundSettings::Chain { settings: ext_settings } => {
|
||||
InboundSettings::Chain {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
inbound.protocol = "chain".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::ChainInboundSettings::new();
|
||||
@@ -759,7 +782,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
outbound.protocol = "drop".to_string();
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Redirect { settings: ext_settings } => {
|
||||
OutboundSettings::Redirect {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "redirect".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::RedirectOutboundSettings::new();
|
||||
@@ -774,7 +799,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Socks { settings: ext_settings } => {
|
||||
OutboundSettings::Socks {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "socks".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::SocksOutboundSettings::new();
|
||||
@@ -795,7 +822,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Shadowsocks { settings: ext_settings } => {
|
||||
OutboundSettings::Shadowsocks {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "shadowsocks".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::ShadowsocksOutboundSettings::new();
|
||||
@@ -821,7 +850,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Obfs { settings: ext_settings } => {
|
||||
OutboundSettings::Obfs {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "obfs".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::ObfsOutboundSettings::new();
|
||||
@@ -839,7 +870,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Trojan { settings: ext_settings } => {
|
||||
OutboundSettings::Trojan {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "trojan".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::TrojanOutboundSettings::new();
|
||||
@@ -857,7 +890,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::VMess { settings: ext_settings } => {
|
||||
OutboundSettings::VMess {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "vmess".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::VMessOutboundSettings::new();
|
||||
@@ -878,7 +913,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Tls { settings: ext_settings } => {
|
||||
OutboundSettings::Tls {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "tls".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::TlsOutboundSettings::new();
|
||||
@@ -906,7 +943,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::WebSocket { settings: ext_settings } => {
|
||||
OutboundSettings::WebSocket {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "ws".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::WebSocketOutboundSettings::new();
|
||||
@@ -921,7 +960,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::TryAll { settings: ext_settings } => {
|
||||
OutboundSettings::TryAll {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "tryall".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::TryAllOutboundSettings::new();
|
||||
@@ -940,7 +981,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Static { settings: ext_settings } => {
|
||||
OutboundSettings::Static {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "static".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::StaticOutboundSettings::new();
|
||||
@@ -959,7 +1002,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::FailOver { settings: ext_settings } => {
|
||||
OutboundSettings::FailOver {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "failover".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::FailOverOutboundSettings::new();
|
||||
@@ -968,8 +1013,10 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
settings.fail_timeout = ext_settings.fail_timeout.unwrap_or(4); // 4 secs
|
||||
settings.health_check = ext_settings.health_check.unwrap_or(true);
|
||||
settings.health_check_timeout = ext_settings.health_check_timeout.unwrap_or(6); // 6 secs
|
||||
settings.health_check_delay = ext_settings.health_check_delay.unwrap_or(200); // 200ms
|
||||
settings.health_check_timeout =
|
||||
ext_settings.health_check_timeout.unwrap_or(6); // 6 secs
|
||||
settings.health_check_delay =
|
||||
ext_settings.health_check_delay.unwrap_or(200); // 200ms
|
||||
settings.health_check_active =
|
||||
ext_settings.health_check_active.unwrap_or(15 * 60); // 15 mins
|
||||
if let Some(ext_health_check_prefers) = &ext_settings.health_check_prefers {
|
||||
@@ -979,7 +1026,8 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
settings.health_check_on_start =
|
||||
ext_settings.health_check_on_start.unwrap_or(false);
|
||||
settings.health_check_wait = ext_settings.health_check_wait.unwrap_or(false);
|
||||
settings.health_check_wait =
|
||||
ext_settings.health_check_wait.unwrap_or(false);
|
||||
settings.health_check_attempts =
|
||||
ext_settings.health_check_attempts.unwrap_or(1);
|
||||
settings.health_check_success_percentage =
|
||||
@@ -994,7 +1042,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::AMux { settings: ext_settings } => {
|
||||
OutboundSettings::AMux {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "amux".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::AMuxOutboundSettings::new();
|
||||
@@ -1018,7 +1068,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Quic { settings: ext_settings } => {
|
||||
OutboundSettings::Quic {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "quic".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::QuicOutboundSettings::new();
|
||||
@@ -1049,7 +1101,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Chain { settings: ext_settings } => {
|
||||
OutboundSettings::Chain {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "chain".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::ChainOutboundSettings::new();
|
||||
@@ -1063,7 +1117,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Select { settings: ext_settings } => {
|
||||
OutboundSettings::Select {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "select".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::SelectOutboundSettings::new();
|
||||
@@ -1077,7 +1133,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
}
|
||||
outbounds.push(outbound);
|
||||
}
|
||||
OutboundSettings::Plugin { settings: ext_settings } => {
|
||||
OutboundSettings::Plugin {
|
||||
settings: ext_settings,
|
||||
} => {
|
||||
outbound.protocol = "plugin".to_string();
|
||||
if let Some(ext_settings) = ext_settings {
|
||||
let mut settings = internal::PluginOutboundSettings::new();
|
||||
|
||||
@@ -1199,10 +1199,7 @@ pub fn to_common(conf: &Config) -> Result<common::Config> {
|
||||
}
|
||||
common_config.router = Some(common::Router {
|
||||
rules: Some(rules),
|
||||
domain_resolve: conf
|
||||
.general
|
||||
.as_ref()
|
||||
.and_then(|g| g.routing_domain_resolve),
|
||||
domain_resolve: conf.general.as_ref().and_then(|g| g.routing_domain_resolve),
|
||||
});
|
||||
|
||||
let mut dns = common::Dns {
|
||||
|
||||
@@ -9,10 +9,10 @@ pub use crate::config::common::{
|
||||
ChainOutboundSettings, Config, Dns, FailOverOutboundSettings, HcInboundSettings, Inbound,
|
||||
InboundSettings, Log, NfInboundSettings, ObfsOutboundSettings, Outbound, OutboundSettings,
|
||||
PluginOutboundSettings, QuicInboundSettings, QuicOutboundSettings, RedirectOutboundSettings,
|
||||
Rule, SelectOutboundSettings, ShadowsocksInboundSettings,
|
||||
ShadowsocksOutboundSettings, SocksOutboundSettings, StaticOutboundSettings, TlsInboundSettings,
|
||||
TlsOutboundSettings, TrojanInboundSettings, TrojanOutboundSettings, TryAllOutboundSettings,
|
||||
TunInboundSettings, VMessOutboundSettings, WebSocketInboundSettings, WebSocketOutboundSettings,
|
||||
Rule, SelectOutboundSettings, ShadowsocksInboundSettings, ShadowsocksOutboundSettings,
|
||||
SocksOutboundSettings, StaticOutboundSettings, TlsInboundSettings, TlsOutboundSettings,
|
||||
TrojanInboundSettings, TrojanOutboundSettings, TryAllOutboundSettings, TunInboundSettings,
|
||||
VMessOutboundSettings, WebSocketInboundSettings, WebSocketOutboundSettings,
|
||||
};
|
||||
|
||||
pub fn to_internal(config: Config) -> Result<internal::Config> {
|
||||
|
||||
@@ -3,10 +3,10 @@ use std::path::Path;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::Result;
|
||||
|
||||
pub mod common;
|
||||
pub mod external_rule;
|
||||
pub mod geosite;
|
||||
pub mod internal;
|
||||
pub mod common;
|
||||
|
||||
#[cfg(feature = "config-json")]
|
||||
pub mod json;
|
||||
|
||||
@@ -58,9 +58,7 @@ impl InboundStreamHandler for Handler {
|
||||
sess = new_sess;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::other(
|
||||
"invalid amux transport",
|
||||
));
|
||||
return Err(io::Error::other("invalid amux transport"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,6 @@ impl OutboundStreamHandler for Handler {
|
||||
};
|
||||
stream.replace(a.stream()?.handle(&new_sess, lhs_stream, s).await?);
|
||||
}
|
||||
Ok(stream
|
||||
.ok_or_else(|| io::Error::other("chain tcp invalid input"))?)
|
||||
Ok(stream.ok_or_else(|| io::Error::other("chain tcp invalid input"))?)
|
||||
}
|
||||
}
|
||||
@@ -61,9 +61,10 @@ impl OutboundDatagramSendHalf for StdOutboundDatagramSendHalf {
|
||||
async fn send_to(&mut self, buf: &[u8], target: &SocksAddr) -> io::Result<usize> {
|
||||
match target {
|
||||
SocksAddr::Ip(a) => self.0.send_to(buf, a).await,
|
||||
SocksAddr::Domain(domain, port) => Err(io::Error::other(
|
||||
format!("unexpected domain address {}:{}", domain, port),
|
||||
)),
|
||||
SocksAddr::Domain(domain, port) => Err(io::Error::other(format!(
|
||||
"unexpected domain address {}:{}",
|
||||
domain, port
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,15 +124,9 @@ impl OutboundDatagramSendHalf for DomainResolveOutboundDatagramSendHalf {
|
||||
.read()
|
||||
.await
|
||||
.direct_lookup(domain)
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("lookup {} failed: {}", domain, e),
|
||||
)
|
||||
})
|
||||
.map_err(|e| io::Error::other(format!("lookup {} failed: {}", domain, e)))
|
||||
.await?;
|
||||
let ip = ips
|
||||
.first()
|
||||
.ok_or_else(|| io::Error::other("no results"))?;
|
||||
let ip = ips.first().ok_or_else(|| io::Error::other("no results"))?;
|
||||
self.0.send_to(buf, SocketAddr::new(*ip, *port)).await
|
||||
}
|
||||
SocksAddr::Ip(addr) => self.0.send_to(buf, addr).await,
|
||||
@@ -223,11 +218,7 @@ impl OutboundDatagramSendHalf for DomainAssociatedOutboundDatagramSendHalf {
|
||||
.read()
|
||||
.await
|
||||
.direct_lookup(domain)
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("lookup {} failed: {}", domain, e),
|
||||
)
|
||||
})
|
||||
.map_err(|e| io::Error::other(format!("lookup {} failed: {}", domain, e)))
|
||||
.await?
|
||||
};
|
||||
// FIXME Since FakeDns returns IPv4 address only, it's always bound
|
||||
|
||||
@@ -219,8 +219,6 @@ impl OutboundDatagramHandler for Handler {
|
||||
.await;
|
||||
}
|
||||
|
||||
Err(io::Error::other(
|
||||
"all outbound attempts failed",
|
||||
))
|
||||
Err(io::Error::other("all outbound attempts failed"))
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,15 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use hickory_proto::{
|
||||
op::{header::MessageType, op_code::OpCode, query::Query, Message},
|
||||
rr::{record_type::RecordType, Name},
|
||||
};
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
use tokio::time::{timeout, Instant};
|
||||
use tracing::{debug, trace, warn};
|
||||
use hickory_proto::{
|
||||
op::{header::MessageType, op_code::OpCode, query::Query, Message},
|
||||
rr::{record_type::RecordType, Name},
|
||||
};
|
||||
|
||||
use crate::{app::SyncDnsClient, proxy::*, session::*};
|
||||
|
||||
|
||||
@@ -270,8 +270,6 @@ impl OutboundStreamHandler for Handler {
|
||||
.await;
|
||||
}
|
||||
|
||||
Err(io::Error::other(
|
||||
"all outbound attempts failed",
|
||||
))
|
||||
Err(io::Error::other("all outbound attempts failed"))
|
||||
}
|
||||
}
|
||||
@@ -454,11 +454,7 @@ pub async fn new_tcp_stream(
|
||||
port: &u16,
|
||||
) -> io::Result<AnyStream> {
|
||||
let mut resolver = Resolver::new(dns_client.clone(), address, port)
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("resolve address failed: {}", e),
|
||||
)
|
||||
})
|
||||
.map_err(|e| io::Error::other(format!("resolve address failed: {}", e)))
|
||||
.await?;
|
||||
|
||||
let mut last_err = None;
|
||||
@@ -489,9 +485,10 @@ pub async fn new_tcp_stream(
|
||||
return Ok(v.0.stream);
|
||||
}
|
||||
Err(e) => {
|
||||
last_err = Some(io::Error::other(
|
||||
format!("all attempts failed, last error: {}", e),
|
||||
));
|
||||
last_err = Some(io::Error::other(format!(
|
||||
"all attempts failed, last error: {}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,16 +100,12 @@ impl AsyncRead for Stream {
|
||||
ReadState::AwaitingResponse { res_buf } => {
|
||||
if res_buf.len() >= RESPONSE_BUFFER_SIZE {
|
||||
// The response may be too large. This should not happen in obfs.
|
||||
return Poll::Ready(Err(io::Error::other(
|
||||
"obfs response too large",
|
||||
)));
|
||||
return Poll::Ready(Err(io::Error::other("obfs response too large")));
|
||||
}
|
||||
let read_len =
|
||||
ready!(tokio_util::io::poll_read_buf(Pin::new(stream), cx, res_buf))?;
|
||||
if read_len == 0 {
|
||||
return Poll::Ready(Err(io::Error::other(
|
||||
"obfs response too short",
|
||||
)));
|
||||
return Poll::Ready(Err(io::Error::other("obfs response too short")));
|
||||
}
|
||||
let req_body_pos = match memmem::find(res_buf, b"\r\n\r\n") {
|
||||
Some(p) => p + 4,
|
||||
|
||||
@@ -63,8 +63,7 @@ impl Handler {
|
||||
Some(Some(ext)) if ext == "der" => {
|
||||
vec![CertificateDer::from(cert)]
|
||||
}
|
||||
_ => certs(&mut io::BufReader::new(&*cert))
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
_ => certs(&mut io::BufReader::new(&*cert)).collect::<Result<Vec<_>, _>>()?,
|
||||
};
|
||||
|
||||
let key = match Path::new(&certificate_key)
|
||||
@@ -102,7 +101,9 @@ impl Handler {
|
||||
crypto.alpn_protocols.push(alpn.as_bytes().to_vec());
|
||||
}
|
||||
|
||||
let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quinn::crypto::rustls::QuicServerConfig::try_from(crypto).unwrap()));
|
||||
let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(
|
||||
quinn::crypto::rustls::QuicServerConfig::try_from(crypto).unwrap(),
|
||||
));
|
||||
let mut transport_config = quinn::TransportConfig::default();
|
||||
transport_config.max_concurrent_bidi_streams(quinn::VarInt::from_u32(64));
|
||||
transport_config.max_idle_timeout(Some(quinn::IdleTimeout::from(quinn::VarInt::from_u32(
|
||||
@@ -155,7 +156,10 @@ impl InboundDatagramHandler for Handler {
|
||||
Ok(connecting) => {
|
||||
if let Err(e) = handle_conn(stream_tx_c, &remote_addr, connecting).await
|
||||
{
|
||||
debug!("handle QUIC connection from {} failed: {}", &remote_addr, e);
|
||||
debug!(
|
||||
"handle QUIC connection from {} failed: {}",
|
||||
&remote_addr, e
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -69,7 +69,9 @@ impl Manager {
|
||||
client_crypto.alpn_protocols.push(alpn.as_bytes().to_vec());
|
||||
}
|
||||
|
||||
let mut client_config = quinn::ClientConfig::new(Arc::new(quinn::crypto::rustls::QuicClientConfig::try_from(client_crypto).unwrap()));
|
||||
let mut client_config = quinn::ClientConfig::new(Arc::new(
|
||||
quinn::crypto::rustls::QuicClientConfig::try_from(client_crypto).unwrap(),
|
||||
));
|
||||
let mut transport_config = quinn::TransportConfig::default();
|
||||
transport_config.max_concurrent_bidi_streams(quinn::VarInt::from_u32(64));
|
||||
transport_config.max_idle_timeout(Some(quinn::IdleTimeout::from(quinn::VarInt::from_u32(
|
||||
@@ -127,11 +129,7 @@ impl Manager {
|
||||
.read()
|
||||
.await
|
||||
.direct_lookup(&self.address)
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("lookup {} failed: {}", &self.address, e),
|
||||
)
|
||||
})
|
||||
.map_err(|e| io::Error::other(format!("lookup {} failed: {}", &self.address, e)))
|
||||
.await?
|
||||
};
|
||||
if ips.is_empty() {
|
||||
@@ -173,11 +171,10 @@ impl Handler {
|
||||
pub async fn new_stream(
|
||||
&self,
|
||||
) -> io::Result<QuicProxyStream<quinn::RecvStream, quinn::SendStream>> {
|
||||
self.manager.new_stream().await.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("new QUIC stream failed: {}", e),
|
||||
)
|
||||
})
|
||||
self.manager
|
||||
.new_stream()
|
||||
.await
|
||||
.map_err(|e| io::Error::other(format!("new QUIC stream failed: {}", e)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,9 +32,9 @@ impl OutboundDatagramHandler for Handler {
|
||||
return Err(io::Error::other("invalid input"));
|
||||
};
|
||||
let target = SocksAddr::from((
|
||||
self.address.parse::<IpAddr>().map_err(|e| {
|
||||
io::Error::other(format!("parse IpAddr failed: {}", e))
|
||||
})?,
|
||||
self.address
|
||||
.parse::<IpAddr>()
|
||||
.map_err(|e| io::Error::other(format!("parse IpAddr failed: {}", e)))?,
|
||||
self.port,
|
||||
));
|
||||
Ok(Box::new(Datagram {
|
||||
|
||||
@@ -46,23 +46,17 @@ pub struct ShadowedStream<T> {
|
||||
|
||||
impl<T> ShadowedStream<T> {
|
||||
pub fn new(s: T, cipher: &str, password: &str, prefix: Option<Box<[u8]>>) -> io::Result<Self> {
|
||||
let cipher = AeadCipher::new(cipher).map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("create AEAD cipher failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
let psk = kdf(password, cipher.key_len()).map_err(|e| {
|
||||
io::Error::other(format!("derive key failed: {}", e))
|
||||
})?;
|
||||
let cipher = AeadCipher::new(cipher)
|
||||
.map_err(|e| io::Error::other(format!("create AEAD cipher failed: {}", e)))?;
|
||||
let psk = kdf(password, cipher.key_len())
|
||||
.map_err(|e| io::Error::other(format!("derive key failed: {}", e)))?;
|
||||
if let Some(prefix) = prefix.as_ref() {
|
||||
if prefix.len() > cipher.key_len() {
|
||||
return Err(io::Error::other(
|
||||
format!(
|
||||
"prefix length exceeding cipher key length: {} > {}",
|
||||
prefix.len(),
|
||||
cipher.key_len()
|
||||
),
|
||||
));
|
||||
return Err(io::Error::other(format!(
|
||||
"prefix length exceeding cipher key length: {} > {}",
|
||||
prefix.len(),
|
||||
cipher.key_len()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(ShadowedStream {
|
||||
@@ -332,14 +326,10 @@ pub struct ShadowedDatagram {
|
||||
|
||||
impl ShadowedDatagram {
|
||||
pub fn new(cipher: &str, password: &str) -> io::Result<Self> {
|
||||
let cipher = AeadCipher::new(cipher).map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("create AEAD cipher failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
let psk = kdf(password, cipher.key_len()).map_err(|e| {
|
||||
io::Error::other(format!("derive key failed: {}", e))
|
||||
})?;
|
||||
let cipher = AeadCipher::new(cipher)
|
||||
.map_err(|e| io::Error::other(format!("create AEAD cipher failed: {}", e)))?;
|
||||
let psk = kdf(password, cipher.key_len())
|
||||
.map_err(|e| io::Error::other(format!("derive key failed: {}", e)))?;
|
||||
Ok(ShadowedDatagram { cipher, psk })
|
||||
}
|
||||
|
||||
|
||||
@@ -26,9 +26,10 @@ impl InboundStreamHandler for Handler {
|
||||
// ver, nmethods
|
||||
stream.read_exact(&mut buf[..]).await?;
|
||||
if buf[0] != 0x05 {
|
||||
return Err(io::Error::other(
|
||||
format!("unknown socks version {}", buf[0]),
|
||||
));
|
||||
return Err(io::Error::other(format!(
|
||||
"unknown socks version {}",
|
||||
buf[0]
|
||||
)));
|
||||
}
|
||||
if buf[1] == 0 {
|
||||
return Err(io::Error::other(
|
||||
@@ -64,23 +65,20 @@ impl InboundStreamHandler for Handler {
|
||||
stream.read_exact(&mut buf[..]).await?;
|
||||
if buf[0] != 0x05 {
|
||||
// TODO reply?
|
||||
return Err(io::Error::other(
|
||||
format!("unknown socks version {}", buf[0]),
|
||||
));
|
||||
return Err(io::Error::other(format!(
|
||||
"unknown socks version {}",
|
||||
buf[0]
|
||||
)));
|
||||
}
|
||||
if buf[2] != 0x0 {
|
||||
// TODO reply?
|
||||
return Err(io::Error::other(
|
||||
"non-zero socks5 reserved field",
|
||||
));
|
||||
return Err(io::Error::other("non-zero socks5 reserved field"));
|
||||
}
|
||||
let cmd = buf[1];
|
||||
// connect, udp associate
|
||||
if cmd != 0x01 && cmd != 0x03 {
|
||||
// TODO reply?
|
||||
return Err(io::Error::other(
|
||||
format!("unsupported socks5 cmd {}", cmd),
|
||||
));
|
||||
return Err(io::Error::other(format!("unsupported socks5 cmd {}", cmd)));
|
||||
}
|
||||
|
||||
let destination = SocksAddr::read_from(&mut stream, SocksAddrWireType::PortLast).await?;
|
||||
|
||||
@@ -52,7 +52,7 @@ impl OutboundDatagramHandler for Handler {
|
||||
(*SocksAddr::try_from((self.address.clone(), self.port))
|
||||
.unwrap()
|
||||
.must_ip())
|
||||
.into(),
|
||||
.into(),
|
||||
)
|
||||
.map_err(Error::other)
|
||||
.await?;
|
||||
@@ -91,11 +91,7 @@ where
|
||||
S: 'static + AsyncRead + AsyncWrite + Send + Unpin + Sync,
|
||||
{
|
||||
async fn recv_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocksAddr)> {
|
||||
let (n, addr) = self
|
||||
.0
|
||||
.recv_from(buf)
|
||||
.map_err(Error::other)
|
||||
.await?;
|
||||
let (n, addr) = self.0.recv_from(buf).map_err(Error::other).await?;
|
||||
match addr {
|
||||
AddrKind::Ip(addr) => Ok((n, SocksAddr::Ip(addr))),
|
||||
AddrKind::Domain(domain, port) => Ok((n, SocksAddr::Domain(domain, port))),
|
||||
|
||||
@@ -25,8 +25,7 @@ impl OutboundStreamHandler for Handler {
|
||||
_lhs: Option<&mut AnyStream>,
|
||||
stream: Option<AnyStream>,
|
||||
) -> io::Result<AnyStream> {
|
||||
let mut stream =
|
||||
stream.ok_or_else(|| io::Error::other("invalid input"))?;
|
||||
let mut stream = stream.ok_or_else(|| io::Error::other("invalid input"))?;
|
||||
let auth = match (&self.username, &self.password) {
|
||||
(auth_username, _) if auth_username.is_empty() => None,
|
||||
(auth_username, auth_password) => Some(Auth {
|
||||
|
||||
@@ -87,6 +87,9 @@ impl InboundStreamHandler for Handler {
|
||||
#[cfg(all(not(feature = "rustls-tls"), feature = "openssl-tls"))]
|
||||
unimplemented!();
|
||||
#[cfg(all(not(feature = "rustls-tls"), not(feature = "openssl-tls")))]
|
||||
Err(io::Error::new(io::ErrorKind::Other, "no tls feature enabled"))
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
"no tls feature enabled",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,7 @@ impl OutboundStreamHandler for Handler {
|
||||
lhs: Option<&mut AnyStream>,
|
||||
stream: Option<AnyStream>,
|
||||
) -> io::Result<AnyStream> {
|
||||
let mut stream =
|
||||
stream.ok_or_else(|| io::Error::other("invalid input"))?;
|
||||
let mut stream = stream.ok_or_else(|| io::Error::other("invalid input"))?;
|
||||
let mut buf = BytesMut::new();
|
||||
let password = Sha224::digest(self.password.as_bytes());
|
||||
let password = hex::encode(&password[..]);
|
||||
|
||||
@@ -61,9 +61,10 @@ impl OutboundDatagramHandler for Handler {
|
||||
);
|
||||
Ok(v.0.dgram)
|
||||
}
|
||||
Err(e) => Err(io::Error::other(
|
||||
format!("all outbound attempts failed, last error: {}", e),
|
||||
)),
|
||||
Err(e) => Err(io::Error::other(format!(
|
||||
"all outbound attempts failed, last error: {}",
|
||||
e
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,9 +57,10 @@ impl OutboundStreamHandler for Handler {
|
||||
);
|
||||
Ok(v.0.stream)
|
||||
}
|
||||
Err(e) => Err(io::Error::other(
|
||||
format!("all outbound attempts failed, last error: {}", e),
|
||||
)),
|
||||
Err(e) => Err(io::Error::other(format!(
|
||||
"all outbound attempts failed, last error: {}",
|
||||
e
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,8 @@ impl OutboundDatagramHandler for Handler {
|
||||
sess: &'a Session,
|
||||
transport: Option<AnyOutboundTransport>,
|
||||
) -> io::Result<AnyOutboundDatagram> {
|
||||
let uuid = Uuid::parse_str(&self.uuid).map_err(|e| {
|
||||
io::Error::other(format!("parse uuid failed: {}", e))
|
||||
})?;
|
||||
let uuid = Uuid::parse_str(&self.uuid)
|
||||
.map_err(|e| io::Error::other(format!("parse uuid failed: {}", e)))?;
|
||||
let mut request_header = RequestHeader {
|
||||
version: 0x1,
|
||||
command: REQUEST_COMMAND_UDP,
|
||||
@@ -56,9 +55,10 @@ impl OutboundDatagramHandler for Handler {
|
||||
request_header.security = SECURITY_TYPE_AES128_GCM;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::other(
|
||||
format!("unsupported cipher: {}", &self.security),
|
||||
))
|
||||
return Err(io::Error::other(format!(
|
||||
"unsupported cipher: {}",
|
||||
&self.security
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,11 +66,7 @@ impl OutboundDatagramHandler for Handler {
|
||||
let client_sess = ClientSession::new();
|
||||
request_header
|
||||
.encode(&mut header_buf, &client_sess)
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("encode request header failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| io::Error::other(format!("encode request header failed: {}", e)))?;
|
||||
|
||||
let enc_size_parser = ShakeSizeParser::new(&client_sess.request_body_iv);
|
||||
let enc = new_encryptor(
|
||||
@@ -78,9 +74,7 @@ impl OutboundDatagramHandler for Handler {
|
||||
&client_sess.request_body_key,
|
||||
&client_sess.request_body_iv,
|
||||
)
|
||||
.map_err(|e| {
|
||||
io::Error::other(format!("new encryptor failed: {}", e))
|
||||
})?;
|
||||
.map_err(|e| io::Error::other(format!("new encryptor failed: {}", e)))?;
|
||||
|
||||
let dec_size_parser = ShakeSizeParser::new(&client_sess.response_body_iv);
|
||||
let dec = new_decryptor(
|
||||
@@ -88,9 +82,7 @@ impl OutboundDatagramHandler for Handler {
|
||||
&client_sess.response_body_key,
|
||||
&client_sess.response_body_iv,
|
||||
)
|
||||
.map_err(|e| {
|
||||
io::Error::other(format!("new decryptor failed: {}", e))
|
||||
})?;
|
||||
.map_err(|e| io::Error::other(format!("new decryptor failed: {}", e)))?;
|
||||
|
||||
let mut stream = if let Some(OutboundTransport::Stream(stream)) = transport {
|
||||
stream
|
||||
|
||||
@@ -30,9 +30,8 @@ impl OutboundStreamHandler for Handler {
|
||||
_lhs: Option<&mut AnyStream>,
|
||||
stream: Option<AnyStream>,
|
||||
) -> io::Result<AnyStream> {
|
||||
let uuid = Uuid::parse_str(&self.uuid).map_err(|e| {
|
||||
io::Error::other(format!("parse uuid failed: {}", e))
|
||||
})?;
|
||||
let uuid = Uuid::parse_str(&self.uuid)
|
||||
.map_err(|e| io::Error::other(format!("parse uuid failed: {}", e)))?;
|
||||
let mut request_header = RequestHeader {
|
||||
version: 0x1,
|
||||
command: REQUEST_COMMAND_TCP,
|
||||
@@ -52,9 +51,10 @@ impl OutboundStreamHandler for Handler {
|
||||
request_header.security = SECURITY_TYPE_AES128_GCM;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::other(
|
||||
format!("unsupported cipher: {}", &self.security),
|
||||
))
|
||||
return Err(io::Error::other(format!(
|
||||
"unsupported cipher: {}",
|
||||
&self.security
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,11 +62,7 @@ impl OutboundStreamHandler for Handler {
|
||||
let client_sess = ClientSession::new();
|
||||
request_header
|
||||
.encode(&mut header_buf, &client_sess)
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("encode request header failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| io::Error::other(format!("encode request header failed: {}", e)))?;
|
||||
|
||||
let enc_size_parser = ShakeSizeParser::new(&client_sess.request_body_iv);
|
||||
|
||||
@@ -75,9 +71,7 @@ impl OutboundStreamHandler for Handler {
|
||||
&client_sess.request_body_key,
|
||||
&client_sess.request_body_iv,
|
||||
)
|
||||
.map_err(|e| {
|
||||
io::Error::other(format!("new encryptor failed: {}", e))
|
||||
})?;
|
||||
.map_err(|e| io::Error::other(format!("new encryptor failed: {}", e)))?;
|
||||
|
||||
let dec_size_parser = ShakeSizeParser::new(&client_sess.response_body_iv);
|
||||
let dec = new_decryptor(
|
||||
@@ -85,12 +79,9 @@ impl OutboundStreamHandler for Handler {
|
||||
&client_sess.response_body_key,
|
||||
&client_sess.response_body_iv,
|
||||
)
|
||||
.map_err(|e| {
|
||||
io::Error::other(format!("new decryptor failed: {}", e))
|
||||
})?;
|
||||
.map_err(|e| io::Error::other(format!("new decryptor failed: {}", e)))?;
|
||||
|
||||
let mut stream =
|
||||
stream.ok_or_else(|| io::Error::other("invalid input"))?;
|
||||
let mut stream = stream.ok_or_else(|| io::Error::other("invalid input"))?;
|
||||
|
||||
stream.write_all(&header_buf).await?; // write request
|
||||
let stream = VMessAuthStream::new(
|
||||
|
||||
@@ -71,11 +71,7 @@ impl OutboundStreamHandler for Handler {
|
||||
..Default::default()
|
||||
};
|
||||
let (socket, _) = client_async_with_config(req, stream, Some(ws_config))
|
||||
.map_err(|e| {
|
||||
io::Error::other(
|
||||
format!("connect ws {} failed: {}", &url, e),
|
||||
)
|
||||
})
|
||||
.map_err(|e| io::Error::other(format!("connect ws {} failed: {}", &url, e)))
|
||||
.await?;
|
||||
let ws_stream = super::ws_stream::WebSocketToStream::new(socket);
|
||||
Ok(Box::new(ws_stream))
|
||||
|
||||
+16
-7
@@ -65,6 +65,8 @@ impl std::fmt::Display for DatagramSource {
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
/// Unique identifier for the session.
|
||||
pub id: u64,
|
||||
/// The network type, representing either TCP or UDP.
|
||||
pub network: Network,
|
||||
/// The socket address of the remote peer of an inbound connection.
|
||||
@@ -91,6 +93,7 @@ pub struct Session {
|
||||
impl Clone for Session {
|
||||
fn clone(&self) -> Self {
|
||||
Session {
|
||||
id: self.id,
|
||||
network: self.network,
|
||||
source: self.source,
|
||||
local_addr: self.local_addr,
|
||||
@@ -107,7 +110,10 @@ impl Clone for Session {
|
||||
|
||||
impl Default for Session {
|
||||
fn default() -> Self {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static SESSION_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
|
||||
Session {
|
||||
id: SESSION_ID_COUNTER.fetch_add(1, Ordering::Relaxed),
|
||||
network: Network::Tcp,
|
||||
source: *crate::option::UNSPECIFIED_BIND_ADDR,
|
||||
local_addr: *crate::option::UNSPECIFIED_BIND_ADDR,
|
||||
@@ -122,6 +128,12 @@ impl Default for Session {
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn create_span(&self) -> tracing::Span {
|
||||
tracing::info_span!("session", id = self.id)
|
||||
}
|
||||
}
|
||||
|
||||
struct SocksAddrPortLastType;
|
||||
|
||||
impl SocksAddrPortLastType {
|
||||
@@ -466,10 +478,8 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
|
||||
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(|e| {
|
||||
io::Error::other(format!("invalid domain: {}", e))
|
||||
})?;
|
||||
let domain = String::from_utf8(buf[2..domain_len + 2].to_vec())
|
||||
.map_err(|e| io::Error::other(format!("invalid domain: {}", e)))?;
|
||||
let mut port_bytes = [0u8; 2];
|
||||
port_bytes.copy_from_slice(&buf[domain_len + 2..domain_len + 4]);
|
||||
let port = u16::from_be_bytes(port_bytes);
|
||||
@@ -514,9 +524,8 @@ impl TryFrom<(&[u8], SocksAddrWireType)> for SocksAddr {
|
||||
if buf.len() < domain_len {
|
||||
return Err(insuff_bytes());
|
||||
}
|
||||
let domain = String::from_utf8(buf[..domain_len].to_vec()).map_err(|e| {
|
||||
io::Error::other(format!("invalid domain: {}", e))
|
||||
})?;
|
||||
let domain = String::from_utf8(buf[..domain_len].to_vec())
|
||||
.map_err(|e| io::Error::other(format!("invalid domain: {}", e)))?;
|
||||
Ok(Self::Domain(domain, port))
|
||||
}
|
||||
_ => Err(io::Error::other("invalid address type")),
|
||||
|
||||
+1
-1
@@ -94,11 +94,11 @@ async fn test_udp_outbound(
|
||||
dns_client: SyncDnsClient,
|
||||
handler: AnyOutboundHandler,
|
||||
) -> Result<Duration> {
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use hickory_proto::{
|
||||
op::{header::MessageType, op_code::OpCode, query::Query, Message},
|
||||
rr::{record_type::RecordType, Name},
|
||||
};
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
let addr = SocksAddr::Ip(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 53));
|
||||
let sess = Session {
|
||||
destination: addr.clone(),
|
||||
|
||||
Reference in new issue
Block a user