mirror of
https://github.com/shadowsocks/shadowsocks-rust.git
synced 2026-11-23 08:05:10 +00:00
All TCP relay variants are now support ACL
FIXME: ACL checking requires one more DNS resolving request (may be cached by trust-dns)
This commit is contained in:
+56
-20
@@ -14,7 +14,7 @@ use std::{
|
||||
use ipnetwork::IpNetwork;
|
||||
use regex::RegexSet;
|
||||
|
||||
use crate::relay::socks5::Address;
|
||||
use crate::{context::Context, relay::socks5::Address};
|
||||
|
||||
/// Strategy mode that ACL is running
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
@@ -50,13 +50,13 @@ impl Rules {
|
||||
/// Check if the specified address matches these rules
|
||||
fn check_address_matched(&self, addr: &Address) -> bool {
|
||||
match *addr {
|
||||
Address::SocketAddress(ref saddr) => self.check_socket_addr_matched(saddr),
|
||||
Address::DomainNameAddress(ref domain, ..) => self.rule.is_match(domain),
|
||||
Address::SocketAddress(ref saddr) => self.check_ip_matched(saddr),
|
||||
Address::DomainNameAddress(ref domain, ..) => self.check_host_matched(domain),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the specified client matches these rules
|
||||
fn check_socket_addr_matched(&self, addr: &SocketAddr) -> bool {
|
||||
/// Check if the specified address matches any rules
|
||||
fn check_ip_matched(&self, addr: &SocketAddr) -> bool {
|
||||
let ip = addr.ip();
|
||||
let ip_network = IpNetwork::from(ip); // Create a network which only contains itself
|
||||
|
||||
@@ -70,6 +70,11 @@ impl Rules {
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Check if the specified host matches any rules
|
||||
fn check_host_matched(&self, host: &str) -> bool {
|
||||
self.rule.is_match(host)
|
||||
}
|
||||
}
|
||||
|
||||
/// ACL rules
|
||||
@@ -105,23 +110,24 @@ impl Rules {
|
||||
///
|
||||
/// ## Mode
|
||||
///
|
||||
/// - `BlackList`
|
||||
///
|
||||
/// Only hosts / clients that matches rules in
|
||||
/// - `[bypass_list]` - will be connected directly instead of connecting through remote proxies
|
||||
/// - `[black_list]` - will be rejected (close connection)
|
||||
///
|
||||
/// - `WhiteList`
|
||||
/// - `WhiteList` (reject / bypass all, except ...)
|
||||
///
|
||||
/// Only hosts / clients that matches rules in
|
||||
/// - `[proxy_list]` - will be connected through remote proxies, others will be connected directly
|
||||
/// - `[white_list]` - will be allowed, others will be rejected
|
||||
///
|
||||
/// - `BlackList` (accept / proxy all, except ...)
|
||||
///
|
||||
/// Only hosts / clients that matches rules in
|
||||
/// - `[bypass_list]` - will be connected directly instead of connecting through remote proxies
|
||||
/// - `[black_list]` - will be rejected (close connection)
|
||||
///
|
||||
/// ## Rules
|
||||
///
|
||||
/// Rules can be either
|
||||
///
|
||||
/// - CIDR form network addresses, like `10.9.0.32/16`
|
||||
/// - IP addresses, like `127.0.0.1` or `::1`
|
||||
/// - Regular Expression for matching hosts, like `(^|\.)gmail\.com$`
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AccessControl {
|
||||
@@ -157,10 +163,10 @@ impl AccessControl {
|
||||
|
||||
match line.as_str() {
|
||||
"[reject_all]" | "[bypass_all]" => {
|
||||
mode = Mode::BlackList;
|
||||
mode = Mode::WhiteList;
|
||||
}
|
||||
"[accept_all]" | "[proxy_all]" => {
|
||||
mode = Mode::WhiteList;
|
||||
mode = Mode::BlackList;
|
||||
}
|
||||
"[outbound_block_list]" => {
|
||||
curr_network = &mut outbound_block_network;
|
||||
@@ -225,15 +231,45 @@ impl AccessControl {
|
||||
}
|
||||
|
||||
/// Check if target address should be bypassed (for client)
|
||||
pub fn check_target_bypassed(&self, addr: &Address) -> bool {
|
||||
///
|
||||
/// FIXME: This function may perform a DNS resolution
|
||||
pub async fn check_target_bypassed(&self, context: &Context, addr: &Address) -> bool {
|
||||
match self.mode {
|
||||
Mode::BlackList => {
|
||||
// Only hosts in bypass_list will be bypassed
|
||||
self.black_list.check_address_matched(addr)
|
||||
if self.black_list.check_address_matched(addr) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Address::DomainNameAddress(ref host, port) = *addr {
|
||||
if let Ok(vaddr) = context.dns_resolve(host, port).await {
|
||||
for addr in vaddr {
|
||||
if self.black_list.check_ip_matched(&addr) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
Mode::WhiteList => {
|
||||
// Only hosts in proxy_list will be proxied
|
||||
!self.white_list.check_address_matched(addr)
|
||||
if self.white_list.check_address_matched(addr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Address::DomainNameAddress(ref host, port) = *addr {
|
||||
if let Ok(vaddr) = context.dns_resolve(host, port).await {
|
||||
for addr in vaddr {
|
||||
if self.white_list.check_ip_matched(&addr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,11 +279,11 @@ impl AccessControl {
|
||||
match self.mode {
|
||||
Mode::BlackList => {
|
||||
// Only clients in black_list will be blocked
|
||||
self.black_list.check_socket_addr_matched(addr)
|
||||
self.black_list.check_ip_matched(addr)
|
||||
}
|
||||
Mode::WhiteList => {
|
||||
// Only clients in white_list will be proxied
|
||||
!self.white_list.check_socket_addr_matched(addr)
|
||||
!self.white_list.check_ip_matched(addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -262,6 +298,6 @@ impl AccessControl {
|
||||
|
||||
/// Check resolved outbound address is blocked (for server)
|
||||
pub fn check_resolved_outbound_blocked(&self, outbound: &SocketAddr) -> bool {
|
||||
self.outbound_block.check_socket_addr_matched(outbound)
|
||||
self.outbound_block.check_ip_matched(outbound)
|
||||
}
|
||||
}
|
||||
|
||||
+12
-3
@@ -232,7 +232,7 @@ impl Context {
|
||||
ppbloom.check_and_set(nonce)
|
||||
}
|
||||
|
||||
/// Check client ACL
|
||||
/// Check client ACL (for server)
|
||||
pub fn check_client_blocked(&self, addr: &SocketAddr) -> bool {
|
||||
match self.config.acl {
|
||||
None => false,
|
||||
@@ -240,7 +240,7 @@ impl Context {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check outbound address ACL
|
||||
/// Check outbound address ACL (for server)
|
||||
pub fn check_outbound_blocked(&self, addr: &Address) -> bool {
|
||||
match self.config.acl {
|
||||
None => false,
|
||||
@@ -248,11 +248,20 @@ impl Context {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check resolved outbound address ACL
|
||||
/// Check resolved outbound address ACL (for server)
|
||||
pub fn check_resolved_outbound_blocked(&self, addr: &SocketAddr) -> bool {
|
||||
match self.config.acl {
|
||||
None => false,
|
||||
Some(ref a) => a.check_resolved_outbound_blocked(addr),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check target address ACL (for client)
|
||||
pub async fn check_target_bypassed(&self, target: &Address) -> bool {
|
||||
match self.config.acl {
|
||||
// Proxy everything by default
|
||||
None => false,
|
||||
Some(ref a) => a.check_target_bypassed(self, target).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use std::{
|
||||
future::Future,
|
||||
io::{self},
|
||||
ops::{Deref, DerefMut},
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
time::Duration,
|
||||
@@ -83,6 +82,11 @@ where
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get a reference to the underlying stream
|
||||
pub fn get_ref(&self) -> &S {
|
||||
self.stream.get_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Connection<S> {
|
||||
@@ -122,26 +126,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Deref for Connection<S>
|
||||
where
|
||||
S: AsyncRead,
|
||||
{
|
||||
type Target = S;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.stream.get_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> DerefMut for Connection<S>
|
||||
where
|
||||
S: AsyncRead,
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.stream.get_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Unpin> Unpin for Connection<S> {}
|
||||
|
||||
impl<S> AsyncRead for Connection<S>
|
||||
|
||||
@@ -104,6 +104,11 @@ impl<S> CryptoStream<S> {
|
||||
read_status: ReadStatus::WaitIv(context, vec![0u8; prev_len], 0usize, method, svr_cfg.clone_key()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a reference to the underlying stream
|
||||
pub fn get_ref(&self) -> &S {
|
||||
&self.stream
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> CryptoStream<S>
|
||||
|
||||
+129
-109
@@ -37,7 +37,6 @@ use hyper::{
|
||||
use log::{debug, error, info, trace};
|
||||
use pin_project::pin_project;
|
||||
|
||||
use super::{CryptoStream, STcpStream};
|
||||
use crate::{
|
||||
config::ServerConfig,
|
||||
context::SharedContext,
|
||||
@@ -53,6 +52,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use super::ProxyStream;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ShadowSocksConnector {
|
||||
context: SharedContext,
|
||||
@@ -66,43 +67,10 @@ impl ShadowSocksConnector {
|
||||
}
|
||||
}
|
||||
|
||||
impl tower::Service<Address> for ShadowSocksConnector {
|
||||
type Error = io::Error;
|
||||
type Future = ShadowSocksConnecting;
|
||||
type Response = CryptoStream<STcpStream>;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, addr: Address) -> Self::Future {
|
||||
let context = self.context.clone();
|
||||
let svr_idx = self.svr_idx;
|
||||
let stat = self.stat.clone();
|
||||
|
||||
ShadowSocksConnecting {
|
||||
fut: async move {
|
||||
let svr_cfg = context.server_config(svr_idx);
|
||||
|
||||
let stream = match super::connect_proxy_server(&*context, svr_cfg).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
// Report failure to global statistic
|
||||
stat.report_failure().await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
super::proxy_server_handshake(context.clone(), stream, svr_cfg, &addr).await
|
||||
}
|
||||
.boxed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl tower::Service<Uri> for ShadowSocksConnector {
|
||||
type Error = io::Error;
|
||||
type Future = ShadowSocksConnecting;
|
||||
type Response = CryptoStream<STcpStream>;
|
||||
type Response = ProxyStream;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
@@ -127,15 +95,14 @@ impl tower::Service<Uri> for ShadowSocksConnector {
|
||||
Err(err)
|
||||
}
|
||||
Some(addr) => {
|
||||
let stream = match super::connect_proxy_server(&*context, svr_cfg).await {
|
||||
Ok(s) => s,
|
||||
match ProxyStream::connect_proxied(context.clone(), svr_cfg, &addr).await {
|
||||
Ok(s) => Ok(s),
|
||||
Err(err) => {
|
||||
// Report failure to global statistic
|
||||
stat.report_failure().await;
|
||||
return Err(err);
|
||||
Err(err)
|
||||
}
|
||||
};
|
||||
super::proxy_server_handshake(context.clone(), stream, svr_cfg, &addr).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,11 +114,67 @@ impl tower::Service<Uri> for ShadowSocksConnector {
|
||||
#[pin_project]
|
||||
struct ShadowSocksConnecting {
|
||||
#[pin]
|
||||
fut: BoxFuture<'static, io::Result<CryptoStream<STcpStream>>>,
|
||||
fut: BoxFuture<'static, io::Result<ProxyStream>>,
|
||||
}
|
||||
|
||||
impl Future for ShadowSocksConnecting {
|
||||
type Output = io::Result<CryptoStream<STcpStream>>;
|
||||
type Output = io::Result<ProxyStream>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
|
||||
self.project().fut.poll(cx)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DirectConnector {
|
||||
context: SharedContext,
|
||||
}
|
||||
|
||||
impl DirectConnector {
|
||||
fn new(context: SharedContext) -> DirectConnector {
|
||||
DirectConnector { context }
|
||||
}
|
||||
}
|
||||
|
||||
impl tower::Service<Uri> for DirectConnector {
|
||||
type Error = io::Error;
|
||||
type Future = DirectConnecting;
|
||||
type Response = ProxyStream;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, dst: Uri) -> Self::Future {
|
||||
let context = self.context.clone();
|
||||
|
||||
DirectConnecting {
|
||||
fut: async move {
|
||||
match host_addr(&dst) {
|
||||
None => {
|
||||
use std::io::Error;
|
||||
|
||||
error!("HTTP target URI must be a valid address, but found: {}", dst);
|
||||
|
||||
let err = Error::new(ErrorKind::Other, "URI must be a valid Address");
|
||||
Err(err)
|
||||
}
|
||||
Some(addr) => ProxyStream::connect_direct(&*context, &addr).await,
|
||||
}
|
||||
}
|
||||
.boxed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project]
|
||||
struct DirectConnecting {
|
||||
#[pin]
|
||||
fut: BoxFuture<'static, io::Result<ProxyStream>>,
|
||||
}
|
||||
|
||||
impl Future for DirectConnecting {
|
||||
type Output = io::Result<ProxyStream>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
|
||||
self.project().fut.poll(cx)
|
||||
@@ -331,15 +354,18 @@ fn set_conn_keep_alive(version: Version, headers: &mut HeaderMap<HeaderValue>, k
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection for CryptoStream<STcpStream> {
|
||||
impl Connection for ProxyStream {
|
||||
fn connected(&self) -> Connected {
|
||||
Connected::new()
|
||||
}
|
||||
}
|
||||
|
||||
type ShadowSocksHttpClient = Client<ShadowSocksConnector, Body>;
|
||||
type DirectHttpClient = Client<DirectConnector, Body>;
|
||||
|
||||
async fn establish_connect_tunnel(
|
||||
upgraded: Upgraded,
|
||||
mut stream: CryptoStream<STcpStream>,
|
||||
stream: ProxyStream,
|
||||
svr_cfg: &ServerConfig,
|
||||
client_addr: SocketAddr,
|
||||
addr: Address,
|
||||
@@ -360,49 +386,49 @@ async fn establish_connect_tunnel(
|
||||
);
|
||||
|
||||
match future::select(rhalf, whalf).await {
|
||||
Either::Left((Ok(..), _)) => trace!("CONNECT relay {} -> {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Left((Ok(..), _)) => trace!("CONNECT relay {} -> {} ({}) closed", client_addr, addr, svr_cfg.addr()),
|
||||
Either::Left((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"CONNECT relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
svr_cfg.addr(),
|
||||
err,
|
||||
);
|
||||
} else {
|
||||
error!(
|
||||
"CONNECT relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
svr_cfg.addr(),
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
Either::Right((Ok(..), _)) => trace!("CONNECT relay {} <- {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Right((Ok(..), _)) => trace!("CONNECT relay {} <- {} ({}) closed", client_addr, addr, svr_cfg.addr()),
|
||||
Either::Right((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"CONNECT relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
svr_cfg.addr(),
|
||||
err,
|
||||
);
|
||||
} else {
|
||||
error!(
|
||||
"CONNECT relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
svr_cfg.addr(),
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("CONNECT relay {} <-> {} ({}) closed", client_addr, svr_cfg.addr(), addr);
|
||||
debug!("CONNECT relay {} <-> {} ({}) closed", client_addr, addr, svr_cfg.addr());
|
||||
}
|
||||
|
||||
fn make_bad_request() -> io::Result<Response<Body>> {
|
||||
@@ -486,6 +512,7 @@ async fn server_dispatch(
|
||||
mut req: Request<Body>,
|
||||
svr_score: SharedServerStatistic<ServerScore>,
|
||||
client_addr: SocketAddr,
|
||||
bypass_client: DirectHttpClient,
|
||||
) -> io::Result<Response<Body>> {
|
||||
let context = svr_score.context();
|
||||
|
||||
@@ -510,6 +537,8 @@ async fn server_dispatch(
|
||||
Some(h) => h,
|
||||
};
|
||||
|
||||
let svr_cfg = svr_score.server_config();
|
||||
|
||||
if Method::CONNECT == req.method() {
|
||||
// Establish a TCP tunnel
|
||||
// https://tools.ietf.org/html/draft-luotonen-web-proxy-tunneling-01
|
||||
@@ -519,26 +548,18 @@ async fn server_dispatch(
|
||||
// Connect to Shadowsocks' remote
|
||||
//
|
||||
// FIXME: What STATUS should I return for connection error?
|
||||
let stream = {
|
||||
let svr_cfg = svr_score.server_config();
|
||||
|
||||
let stream = match super::connect_proxy_server(context, svr_cfg).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
let stream = match ProxyStream::connect(svr_score.clone_context(), svr_cfg, &host).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
if err.is_proxied() {
|
||||
// Report failure to global statistic
|
||||
svr_score.report_failure().await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
super::proxy_server_handshake(svr_score.clone_context(), stream, svr_cfg, &host).await?
|
||||
return Err(err.into_inner());
|
||||
}
|
||||
};
|
||||
|
||||
debug!(
|
||||
"CONNECT relay connected {} <-> {} ({})",
|
||||
client_addr,
|
||||
svr_score.server_config().addr(),
|
||||
host
|
||||
);
|
||||
debug!("CONNECT relay connected {} <-> {}", client_addr, host);
|
||||
|
||||
// Upgrade to a TCP tunnel
|
||||
//
|
||||
@@ -550,22 +571,14 @@ async fn server_dispatch(
|
||||
|
||||
match req.into_body().on_upgrade().await {
|
||||
Ok(upgraded) => {
|
||||
trace!(
|
||||
"CONNECT tunnel upgrade success, {} <-> {} ({})",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
host
|
||||
);
|
||||
trace!("CONNECT tunnel upgrade success, {} <-> {}", client_addr, host);
|
||||
|
||||
establish_connect_tunnel(upgraded, stream, svr_cfg, client_addr, host).await
|
||||
}
|
||||
Err(e) => {
|
||||
error!(
|
||||
"failed to upgrade TCP tunnel {} <-> {} ({}), error: {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
host,
|
||||
e
|
||||
"failed to upgrade TCP tunnel {} <-> {}, error: {}",
|
||||
client_addr, host, e
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -589,28 +602,41 @@ async fn server_dispatch(
|
||||
// Set keep-alive for connection with remote
|
||||
set_conn_keep_alive(req.version(), req.headers_mut(), conn_keep_alive);
|
||||
|
||||
let svr_cfg = svr_score.server_config();
|
||||
let mut res = if context.check_target_bypassed(&host).await {
|
||||
// Keep connections in a global client instance
|
||||
match bypass_client.request(req).await {
|
||||
Ok(res) => res,
|
||||
Err(err) => {
|
||||
error!(
|
||||
"HTTP {} {} <-> {} relay failed, error: {}",
|
||||
method, client_addr, host, err
|
||||
);
|
||||
|
||||
// Keep connections for clients in ServerScore::client
|
||||
//
|
||||
// client instance is kept for Keep-Alive connections
|
||||
let client = &svr_score.server().client;
|
||||
let mut res = match client.request(req).await {
|
||||
Ok(res) => res,
|
||||
Err(err) => {
|
||||
error!(
|
||||
"HTTP {} {} <-> {} ({}) relay failed, error: {}",
|
||||
method,
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
host,
|
||||
err
|
||||
);
|
||||
let mut resp = Response::new(Body::from(format!("relay failed to {}", host)));
|
||||
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
|
||||
let mut resp = Response::new(Body::from(format!("relay failed to {}", host)));
|
||||
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
return Ok(resp);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Keep connections for clients in ServerScore::client
|
||||
//
|
||||
// client instance is kept for Keep-Alive connections
|
||||
let client = &svr_score.server().proxy_client;
|
||||
|
||||
return Ok(resp);
|
||||
match client.request(req).await {
|
||||
Ok(res) => res,
|
||||
Err(err) => {
|
||||
error!(
|
||||
"HTTP {} {} <-> {} relay failed, error: {}",
|
||||
method, client_addr, host, err
|
||||
);
|
||||
|
||||
let mut resp = Response::new(Body::from(format!("relay failed to {}", host)));
|
||||
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
|
||||
return Ok(resp);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -622,22 +648,14 @@ async fn server_dispatch(
|
||||
// Set Connection header
|
||||
set_conn_keep_alive(res.version(), res.headers_mut(), res_keep_alive);
|
||||
|
||||
debug!(
|
||||
"HTTP {} relay {} <-> {} ({}) finished",
|
||||
method,
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
host
|
||||
);
|
||||
debug!("HTTP {} relay {} <-> {} finished", method, client_addr, host,);
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
type ShadowSocksHttpClient = Client<ShadowSocksConnector, Body>;
|
||||
|
||||
struct ServerScore {
|
||||
client: ShadowSocksHttpClient,
|
||||
proxy_client: ShadowSocksHttpClient,
|
||||
}
|
||||
|
||||
impl ServerScore {
|
||||
@@ -645,7 +663,7 @@ impl ServerScore {
|
||||
ServerScore {
|
||||
// Create HTTP clients for each remote servers
|
||||
// It may reuse keep-alive connections
|
||||
client: Client::builder().build::<_, Body>(ShadowSocksConnector::new(context, server_idx, data)),
|
||||
proxy_client: Client::builder().build::<_, Body>(ShadowSocksConnector::new(context, server_idx, data)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -658,18 +676,20 @@ impl ServerData for ServerScore {
|
||||
|
||||
/// Starts a TCP local server with HTTP proxy protocol
|
||||
pub async fn run(context: SharedContext) -> io::Result<()> {
|
||||
let local_addr = context.config().local.as_ref().expect("missing local config");
|
||||
let local_addr = context.config().local.as_ref().expect("local config");
|
||||
let bind_addr = local_addr.bind_addr(&*context).await?;
|
||||
|
||||
let bypass_client = Client::builder().build::<_, Body>(DirectConnector::new(context.clone()));
|
||||
let servers: PingBalancer<ServerScore> = PingBalancer::new(context, ServerType::Tcp).await;
|
||||
|
||||
let make_service = make_service_fn(|socket: &AddrStream| {
|
||||
let client_addr = socket.remote_addr();
|
||||
let svr_score = servers.pick_server();
|
||||
let bypass_client = bypass_client.clone();
|
||||
|
||||
async move {
|
||||
Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
|
||||
server_dispatch(req, svr_score.clone(), client_addr)
|
||||
server_dispatch(req, svr_score.clone(), client_addr, bypass_client.clone())
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
@@ -71,7 +71,7 @@ async fn connect_proxy_server_internal(
|
||||
|
||||
/// Connect to proxy server with `ServerConfig`
|
||||
pub(crate) async fn connect_proxy_server(context: &Context, svr_cfg: &ServerConfig) -> io::Result<STcpStream> {
|
||||
let timeout = svr_cfg.timeout();
|
||||
let timeout = svr_cfg.timeout().or(context.config().timeout);
|
||||
|
||||
let svr_addr = match context.config().config_type {
|
||||
ConfigType::Server => svr_cfg.addr(),
|
||||
|
||||
@@ -20,6 +20,7 @@ mod crypto_io;
|
||||
mod http_local;
|
||||
pub mod local;
|
||||
mod monitor;
|
||||
mod proxy_stream;
|
||||
mod redir_local;
|
||||
pub mod server;
|
||||
mod socks5_local;
|
||||
@@ -31,6 +32,7 @@ mod utils;
|
||||
pub use self::{
|
||||
connection::{Connection, TcpConnection},
|
||||
crypto_io::CryptoStream,
|
||||
proxy_stream::ProxyStream,
|
||||
};
|
||||
|
||||
pub(crate) use self::local::{connect_proxy_server, proxy_server_handshake};
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
//! TCP connection stream for local server with remote (proxy server or remote target)
|
||||
|
||||
use std::{
|
||||
fmt::{self, Display, Formatter},
|
||||
io::{self, Error},
|
||||
marker::Unpin,
|
||||
net::SocketAddr,
|
||||
pin::Pin,
|
||||
task::{Context as TaskContext, Poll},
|
||||
};
|
||||
|
||||
use log::trace;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf},
|
||||
net::TcpStream,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::ServerConfig,
|
||||
context::{Context, SharedContext},
|
||||
relay::socks5::Address,
|
||||
};
|
||||
|
||||
use super::{connection::Connection, CryptoStream};
|
||||
|
||||
macro_rules! forward_call {
|
||||
($self:expr, $method:ident $(, $param:expr)*) => {
|
||||
match *$self {
|
||||
ProxyStream::Direct(ref mut s) => Pin::new(s).$method($($param),*),
|
||||
ProxyStream::Proxied(ref mut s) => Pin::new(s).$method($($param),*),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Stream wrapper for both direct connections and proxied connections
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum ProxyStream {
|
||||
Direct(Connection<TcpStream>),
|
||||
Proxied(CryptoStream<Connection<TcpStream>>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProxyStreamError {
|
||||
inner: Error,
|
||||
bypassed: bool,
|
||||
}
|
||||
|
||||
impl ProxyStreamError {
|
||||
fn new(inner: Error, bypassed: bool) -> ProxyStreamError {
|
||||
ProxyStreamError { inner, bypassed }
|
||||
}
|
||||
|
||||
/// Check if it is proxied
|
||||
pub fn is_proxied(&self) -> bool {
|
||||
self.bypassed
|
||||
}
|
||||
|
||||
/// Into internal `std::io::Error`
|
||||
pub fn into_inner(self) -> Error {
|
||||
self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProxyStreamError> for Error {
|
||||
fn from(err: ProxyStreamError) -> Error {
|
||||
err.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ProxyStreamError {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
Display::fmt(&self.inner, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl ProxyStream {
|
||||
/// Connect to remote by ACL rules
|
||||
pub async fn connect(
|
||||
context: SharedContext,
|
||||
svr_cfg: &ServerConfig,
|
||||
addr: &Address,
|
||||
) -> Result<ProxyStream, ProxyStreamError> {
|
||||
if context.check_target_bypassed(addr).await {
|
||||
ProxyStream::connect_direct_wrapped(&*context, addr).await
|
||||
} else {
|
||||
ProxyStream::connect_proxied_wrapped(context, svr_cfg, addr).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to remote directly (without proxy)
|
||||
///
|
||||
/// This is used for hosts that matches ACL bypassed rules
|
||||
pub async fn connect_direct(context: &Context, addr: &Address) -> io::Result<ProxyStream> {
|
||||
trace!("connect to {} directly (bypassed)", addr);
|
||||
|
||||
// NOTE: Direct connection's timeout is controlled by the global key
|
||||
let timeout = context.config().timeout;
|
||||
|
||||
let stream = match *addr {
|
||||
Address::SocketAddress(ref saddr) => TcpStream::connect(saddr).await?,
|
||||
Address::DomainNameAddress(ref domain, port) => {
|
||||
lookup_then!(context, domain, port, |saddr| { TcpStream::connect(saddr).await })?.1
|
||||
}
|
||||
};
|
||||
|
||||
Ok(ProxyStream::Direct(Connection::new(stream, timeout)))
|
||||
}
|
||||
|
||||
async fn connect_direct_wrapped(context: &Context, addr: &Address) -> Result<ProxyStream, ProxyStreamError> {
|
||||
match ProxyStream::connect_direct(context, addr).await {
|
||||
Ok(s) => Ok(s),
|
||||
Err(err) => Err(ProxyStreamError::new(err, true)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to remote through proxy server
|
||||
///
|
||||
/// This is used for hosts that matches ACL proxied rules
|
||||
pub async fn connect_proxied(
|
||||
context: SharedContext,
|
||||
svr_cfg: &ServerConfig,
|
||||
addr: &Address,
|
||||
) -> io::Result<ProxyStream> {
|
||||
trace!("connect to {} through {} (proxied)", addr, svr_cfg.addr());
|
||||
|
||||
let server_stream = super::local::connect_proxy_server(&*context, svr_cfg).await?;
|
||||
let proxy_stream = super::local::proxy_server_handshake(context, server_stream, svr_cfg, addr).await?;
|
||||
|
||||
Ok(ProxyStream::Proxied(proxy_stream))
|
||||
}
|
||||
|
||||
async fn connect_proxied_wrapped(
|
||||
context: SharedContext,
|
||||
svr_cfg: &ServerConfig,
|
||||
addr: &Address,
|
||||
) -> Result<ProxyStream, ProxyStreamError> {
|
||||
match ProxyStream::connect_proxied(context, svr_cfg, addr).await {
|
||||
Ok(s) => Ok(s),
|
||||
Err(err) => Err(ProxyStreamError::new(err, false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split into reader and writer
|
||||
pub fn split(self) -> (ReadHalf<ProxyStream>, WriteHalf<ProxyStream>) {
|
||||
use tokio::io::split;
|
||||
split(self)
|
||||
}
|
||||
|
||||
/// Returns the local socket address of this stream socket
|
||||
pub fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
match *self {
|
||||
ProxyStream::Direct(ref s) => s.get_ref().local_addr(),
|
||||
ProxyStream::Proxied(ref s) => s.get_ref().get_ref().local_addr(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the underlying connection is proxied
|
||||
pub fn is_proxied(&self) -> bool {
|
||||
match *self {
|
||||
ProxyStream::Proxied(..) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Unpin for ProxyStream {}
|
||||
|
||||
impl AsyncRead for ProxyStream {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
|
||||
forward_call!(self, poll_read, cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for ProxyStream {
|
||||
fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
|
||||
forward_call!(self, poll_write, cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
|
||||
forward_call!(self, poll_flush, cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
|
||||
forward_call!(self, poll_shutdown, cx)
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,10 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use super::sys::{create_redir_listener, get_original_destination_addr};
|
||||
use super::{
|
||||
sys::{create_redir_listener, get_original_destination_addr},
|
||||
ProxyStream,
|
||||
};
|
||||
|
||||
/// Established Client Transparent Proxy
|
||||
///
|
||||
@@ -28,25 +31,9 @@ async fn establish_client_tcp_redir<'a>(
|
||||
client_addr: SocketAddr,
|
||||
addr: &Address,
|
||||
) -> io::Result<()> {
|
||||
let context = server.context();
|
||||
let svr_cfg = server.server_config();
|
||||
|
||||
let svr_s = match super::connect_proxy_server(context, svr_cfg).await {
|
||||
Ok(svr_s) => {
|
||||
trace!("proxy server connected, {:?}", svr_cfg);
|
||||
svr_s
|
||||
}
|
||||
Err(err) => {
|
||||
// Report to global statistic
|
||||
server.report_failure().await;
|
||||
|
||||
// Just close the connection.
|
||||
error!("failed to connect remote server {}, err: {}", svr_cfg.addr(), err);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
let mut svr_s = super::proxy_server_handshake(server.clone_context(), svr_s, svr_cfg, addr).await?;
|
||||
let svr_s = ProxyStream::connect(server.clone_context(), svr_cfg, addr).await?;
|
||||
let (mut svr_r, mut svr_w) = svr_s.split();
|
||||
|
||||
let (mut r, mut w) = s.split();
|
||||
@@ -56,57 +43,28 @@ async fn establish_client_tcp_redir<'a>(
|
||||
let rhalf = copy(&mut r, &mut svr_w);
|
||||
let whalf = copy(&mut svr_r, &mut w);
|
||||
|
||||
debug!(
|
||||
"REDIR relay established {} <-> {} ({})",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr
|
||||
);
|
||||
debug!("REDIR relay established {} <-> {}", client_addr, addr);
|
||||
|
||||
match future::select(rhalf, whalf).await {
|
||||
Either::Left((Ok(..), _)) => trace!("REDIR relay {} -> {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Left((Ok(..), _)) => trace!("REDIR relay {} -> {} closed", client_addr, addr),
|
||||
Either::Left((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"REDIR relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
trace!("REDIR relay {} -> {} closed with error {}", client_addr, addr, err);
|
||||
} else {
|
||||
error!(
|
||||
"REDIR relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
error!("REDIR relay {} -> {} closed with error {}", client_addr, addr, err);
|
||||
}
|
||||
}
|
||||
Either::Right((Ok(..), _)) => trace!("REDIR relay {} <- {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Right((Ok(..), _)) => trace!("REDIR relay {} <- {} closed", client_addr, addr),
|
||||
Either::Right((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"REDIR relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
trace!("REDIR relay {} <- {} closed with error {}", client_addr, addr, err);
|
||||
} else {
|
||||
error!(
|
||||
"REDIR relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
error!("REDIR relay {} <- {} closed with error {}", client_addr, addr, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("REDIR relay {} <-> {} ({}) closed", client_addr, svr_cfg.addr(), addr);
|
||||
debug!("REDIR relay {} <-> {} closed", client_addr, addr);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::{
|
||||
io::{self, ErrorKind},
|
||||
net::SocketAddr,
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
};
|
||||
|
||||
use futures::future::{self, Either};
|
||||
@@ -20,7 +20,7 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use super::ignore_until_end;
|
||||
use super::{ignore_until_end, ProxyStream};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct UdpConfig {
|
||||
@@ -37,10 +37,8 @@ async fn handle_socks5_connect<'a>(
|
||||
let context = server.context();
|
||||
let svr_cfg = server.server_config();
|
||||
|
||||
let svr_s = match super::connect_proxy_server(context, svr_cfg).await {
|
||||
let svr_s = match ProxyStream::connect(server.clone_context(), svr_cfg, addr).await {
|
||||
Ok(svr_s) => {
|
||||
trace!("proxy server connected, {:?}", svr_cfg);
|
||||
|
||||
// Tell the client that we are ready
|
||||
let header = TcpResponseHeader::new(socks5::Reply::Succeeded, Address::SocketAddress(svr_s.local_addr()?));
|
||||
header.write_to(stream).await?;
|
||||
@@ -49,31 +47,29 @@ async fn handle_socks5_connect<'a>(
|
||||
|
||||
svr_s
|
||||
}
|
||||
Err(err) => {
|
||||
Err(perr) => {
|
||||
use crate::relay::socks5::Reply;
|
||||
|
||||
error!("failed to connect remote server {}, err: {}", svr_cfg.addr(), err);
|
||||
|
||||
// Report to global statistic
|
||||
server.report_failure().await;
|
||||
if perr.is_proxied() {
|
||||
// Report to global statistic
|
||||
server.report_failure().await;
|
||||
}
|
||||
|
||||
let err = perr.into_inner();
|
||||
let reply = match err.kind() {
|
||||
ErrorKind::ConnectionRefused => Reply::ConnectionRefused,
|
||||
ErrorKind::ConnectionAborted => Reply::HostUnreachable,
|
||||
_ => Reply::NetworkUnreachable,
|
||||
};
|
||||
|
||||
let header = TcpResponseHeader::new(
|
||||
reply,
|
||||
Address::SocketAddress("0.0.0.0:0".parse::<SocketAddr>().unwrap()),
|
||||
);
|
||||
let dummy_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);
|
||||
let header = TcpResponseHeader::new(reply, Address::SocketAddress(dummy_address));
|
||||
header.write_to(stream).await?;
|
||||
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
let mut svr_s = super::proxy_server_handshake(server.clone_context(), svr_s, svr_cfg, addr).await?;
|
||||
let (mut svr_r, mut svr_w) = svr_s.split();
|
||||
|
||||
// Reset `TCP_NODELAY` after Socks5 handshake
|
||||
@@ -90,57 +86,28 @@ async fn handle_socks5_connect<'a>(
|
||||
let rhalf = copy(&mut r, &mut svr_w);
|
||||
let whalf = copy(&mut svr_r, &mut w);
|
||||
|
||||
debug!(
|
||||
"CONNECT relay established {} <-> {} ({})",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr
|
||||
);
|
||||
debug!("CONNECT relay established {} <-> {}", client_addr, addr,);
|
||||
|
||||
match future::select(rhalf, whalf).await {
|
||||
Either::Left((Ok(..), _)) => trace!("CONNECT relay {} -> {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Left((Ok(..), _)) => trace!("CONNECT relay {} -> {} closed", client_addr, addr),
|
||||
Either::Left((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"CONNECT relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
trace!("CONNECT relay {} -> {} closed with error {}", client_addr, addr, err);
|
||||
} else {
|
||||
error!(
|
||||
"CONNECT relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
error!("CONNECT relay {} -> {} closed with error {}", client_addr, addr, err);
|
||||
}
|
||||
}
|
||||
Either::Right((Ok(..), _)) => trace!("CONNECT relay {} <- {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Right((Ok(..), _)) => trace!("CONNECT relay {} <- {} closed", client_addr, addr),
|
||||
Either::Right((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"CONNECT relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
trace!("CONNECT relay {} <- {} closed with error {}", client_addr, addr, err);
|
||||
} else {
|
||||
error!(
|
||||
"CONNECT relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
error!("CONNECT relay {} <- {} closed with error {}", client_addr, addr, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("CONNECT relay {} <-> {} ({}) closed", client_addr, svr_cfg.addr(), addr);
|
||||
debug!("CONNECT relay {} <-> {} closed", client_addr, addr);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -279,7 +246,7 @@ pub async fn run(context: SharedContext) -> io::Result<()> {
|
||||
let udp_conf = udp_conf.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = handle_socks5_client(&server, socket, udp_conf).await {
|
||||
error!("TCP Socks5 client, error: {:?}", err);
|
||||
error!("TCP socks5 client exited with error: {}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use super::ProxyStream;
|
||||
|
||||
/// Established Client Tunnel
|
||||
///
|
||||
/// This method must be called after handshaking with client (for example, socks5 handshaking)
|
||||
@@ -26,22 +28,9 @@ async fn establish_client_tcp_tunnel<'a>(
|
||||
client_addr: SocketAddr,
|
||||
addr: &Address,
|
||||
) -> io::Result<()> {
|
||||
let context = server.context();
|
||||
let svr_cfg = server.server_config();
|
||||
|
||||
let svr_s = match super::connect_proxy_server(context, svr_cfg).await {
|
||||
Ok(svr_s) => {
|
||||
trace!("proxy server connected, {:?}", svr_cfg);
|
||||
svr_s
|
||||
}
|
||||
Err(err) => {
|
||||
// Just close the connection.
|
||||
error!("failed to connect remote server {}, err: {}", svr_cfg.addr(), err);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
let mut svr_s = super::proxy_server_handshake(server.clone_context(), svr_s, svr_cfg, addr).await?;
|
||||
let svr_s = ProxyStream::connect(server.clone_context(), svr_cfg, addr).await?;
|
||||
let (mut svr_r, mut svr_w) = svr_s.split();
|
||||
|
||||
let (mut r, mut w) = s.split();
|
||||
@@ -51,57 +40,28 @@ async fn establish_client_tcp_tunnel<'a>(
|
||||
let rhalf = copy(&mut r, &mut svr_w);
|
||||
let whalf = copy(&mut svr_r, &mut w);
|
||||
|
||||
debug!(
|
||||
"TUNNEL relay established {} <-> {} ({})",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr
|
||||
);
|
||||
debug!("TUNNEL relay established {} <-> {}", client_addr, addr);
|
||||
|
||||
match future::select(rhalf, whalf).await {
|
||||
Either::Left((Ok(..), _)) => trace!("TUNNEL relay {} -> {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Left((Ok(..), _)) => trace!("TUNNEL relay {} -> {} closed", client_addr, addr),
|
||||
Either::Left((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"TUNNEL relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
trace!("TUNNEL relay {} -> {} closed with error {}", client_addr, addr, err);
|
||||
} else {
|
||||
error!(
|
||||
"TUNNEL relay {} -> {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
error!("TUNNEL relay {} -> {} closed with error {}", client_addr, addr, err);
|
||||
}
|
||||
}
|
||||
Either::Right((Ok(..), _)) => trace!("TUNNEL relay {} <- {} ({}) closed", client_addr, svr_cfg.addr(), addr),
|
||||
Either::Right((Ok(..), _)) => trace!("TUNNEL relay {} <- {} closed", client_addr, addr),
|
||||
Either::Right((Err(err), _)) => {
|
||||
if let ErrorKind::TimedOut = err.kind() {
|
||||
trace!(
|
||||
"TUNNEL relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
trace!("TUNNEL relay {} <- {} closed with error {}", client_addr, addr, err);
|
||||
} else {
|
||||
error!(
|
||||
"TUNNEL relay {} <- {} ({}) closed with error {}",
|
||||
client_addr,
|
||||
svr_cfg.addr(),
|
||||
addr,
|
||||
err,
|
||||
);
|
||||
error!("TUNNEL relay {} <- {} closed with error {}", client_addr, addr, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("TUNNEL relay {} <-> {} ({}) closed", client_addr, svr_cfg.addr(), addr);
|
||||
debug!("TUNNEL relay {} <-> {} closed", client_addr, addr);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -158,7 +118,7 @@ pub async fn run(context: SharedContext) -> io::Result<()> {
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = handle_tunnel_client(&server, socket).await {
|
||||
error!("TCP Tunnel client, error: {:?}", err);
|
||||
error!("TCP tunnel client exited with error: {:?}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user