mirror of
https://github.com/tun2proxy/tun2proxy.git
synced 2025-04-19 05:19:09 +00:00
rustfmt max_width = 140
This commit is contained in:
parent
ebec547ccb
commit
97c4aa5137
7 changed files with 35 additions and 92 deletions
|
@ -1 +1 @@
|
||||||
max_width = 120
|
max_width = 140
|
||||||
|
|
10
src/http.rs
10
src/http.rs
|
@ -1,8 +1,8 @@
|
||||||
use crate::{
|
use crate::{
|
||||||
error::Error,
|
error::Error,
|
||||||
tun2proxy::{
|
tun2proxy::{
|
||||||
ConnectionInfo, ConnectionManager, Direction, IncomingDataEvent, IncomingDirection, OutgoingDataEvent,
|
ConnectionInfo, ConnectionManager, Direction, IncomingDataEvent, IncomingDirection, OutgoingDataEvent, OutgoingDirection,
|
||||||
OutgoingDirection, ProxyHandler,
|
ProxyHandler,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
|
@ -61,11 +61,7 @@ static TRANSFER_ENCODING: &str = "Transfer-Encoding";
|
||||||
static CONTENT_LENGTH: &str = "Content-Length";
|
static CONTENT_LENGTH: &str = "Content-Length";
|
||||||
|
|
||||||
impl HttpConnection {
|
impl HttpConnection {
|
||||||
fn new(
|
fn new(info: &ConnectionInfo, credentials: Option<UserKey>, digest_state: Rc<RefCell<Option<DigestState>>>) -> Result<Self, Error> {
|
||||||
info: &ConnectionInfo,
|
|
||||||
credentials: Option<UserKey>,
|
|
||||||
digest_state: Rc<RefCell<Option<DigestState>>>,
|
|
||||||
) -> Result<Self, Error> {
|
|
||||||
let mut res = Self {
|
let mut res = Self {
|
||||||
state: HttpState::ExpectResponseHeaders,
|
state: HttpState::ExpectResponseHeaders,
|
||||||
client_inbuf: VecDeque::default(),
|
client_inbuf: VecDeque::default(),
|
||||||
|
|
|
@ -150,11 +150,7 @@ impl Options {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn tun_to_proxy<'a>(
|
pub fn tun_to_proxy<'a>(interface: &NetworkInterface, proxy: &Proxy, options: Options) -> Result<TunToProxy<'a>, Error> {
|
||||||
interface: &NetworkInterface,
|
|
||||||
proxy: &Proxy,
|
|
||||||
options: Options,
|
|
||||||
) -> Result<TunToProxy<'a>, Error> {
|
|
||||||
let mut ttp = TunToProxy::new(interface, options)?;
|
let mut ttp = TunToProxy::new(interface, options)?;
|
||||||
let credentials = proxy.credentials.clone();
|
let credentials = proxy.credentials.clone();
|
||||||
let server = proxy.addr;
|
let server = proxy.addr;
|
||||||
|
|
31
src/setup.rs
31
src/setup.rs
|
@ -62,12 +62,7 @@ where
|
||||||
let command = cmdline.as_slice().join(" ");
|
let command = cmdline.as_slice().join(" ");
|
||||||
match String::from_utf8(output.stderr.clone()) {
|
match String::from_utf8(output.stderr.clone()) {
|
||||||
Ok(output) => Err(format!("[{}] Command `{}` failed: {}", nix::unistd::getpid(), command, output).into()),
|
Ok(output) => Err(format!("[{}] Command `{}` failed: {}", nix::unistd::getpid(), command, output).into()),
|
||||||
Err(_) => Err(format!(
|
Err(_) => Err(format!("Command `{:?}` failed with exit code {}", command, output.status.code().unwrap()).into()),
|
||||||
"Command `{:?}` failed with exit code {}",
|
|
||||||
command,
|
|
||||||
output.status.code().unwrap()
|
|
||||||
)
|
|
||||||
.into()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -103,11 +98,7 @@ impl Setup {
|
||||||
["ip", "-4", "route", "show"]
|
["ip", "-4", "route", "show"]
|
||||||
};
|
};
|
||||||
|
|
||||||
let routes = run_iproute(
|
let routes = run_iproute(route_show_args, "failed to get routing table through the ip command", true)?;
|
||||||
route_show_args,
|
|
||||||
"failed to get routing table through the ip command",
|
|
||||||
true,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let mut route_info = Vec::<(IpCidr, Vec<String>)>::new();
|
let mut route_info = Vec::<(IpCidr, Vec<String>)>::new();
|
||||||
for line in routes.stdout.lines() {
|
for line in routes.stdout.lines() {
|
||||||
|
@ -217,14 +208,7 @@ impl Setup {
|
||||||
fn add_tunnel_routes(&self) -> Result<(), Error> {
|
fn add_tunnel_routes(&self) -> Result<(), Error> {
|
||||||
for route in &self.routes {
|
for route in &self.routes {
|
||||||
run_iproute(
|
run_iproute(
|
||||||
[
|
["ip", "route", "add", route.to_string().as_str(), "dev", self.tun.as_str()],
|
||||||
"ip",
|
|
||||||
"route",
|
|
||||||
"add",
|
|
||||||
route.to_string().as_str(),
|
|
||||||
"dev",
|
|
||||||
self.tun.as_str(),
|
|
||||||
],
|
|
||||||
"failed to add route",
|
"failed to add route",
|
||||||
true,
|
true,
|
||||||
)?;
|
)?;
|
||||||
|
@ -238,9 +222,7 @@ impl Setup {
|
||||||
let _ = Command::new("ip").args(["link", "del", self.tun.as_str()]).output();
|
let _ = Command::new("ip").args(["link", "del", self.tun.as_str()]).output();
|
||||||
|
|
||||||
for cidr in &self.delete_proxy_routes {
|
for cidr in &self.delete_proxy_routes {
|
||||||
let _ = Command::new("ip")
|
let _ = Command::new("ip").args(["route", "del", cidr.to_string().as_str()]).output();
|
||||||
.args(["route", "del", cidr.to_string().as_str()])
|
|
||||||
.output();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.unmount_resolvconf {
|
if self.unmount_resolvconf {
|
||||||
|
@ -297,10 +279,7 @@ impl Setup {
|
||||||
loop {
|
loop {
|
||||||
let res = fd.read_signal().unwrap().unwrap();
|
let res = fd.read_signal().unwrap().unwrap();
|
||||||
let signo = nix::sys::signal::Signal::try_from(res.ssi_signo as i32).unwrap();
|
let signo = nix::sys::signal::Signal::try_from(res.ssi_signo as i32).unwrap();
|
||||||
if signo == nix::sys::signal::SIGINT
|
if signo == nix::sys::signal::SIGINT || signo == nix::sys::signal::SIGTERM || signo == nix::sys::signal::SIGQUIT {
|
||||||
|| signo == nix::sys::signal::SIGTERM
|
|
||||||
|| signo == nix::sys::signal::SIGQUIT
|
|
||||||
{
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
14
src/socks.rs
14
src/socks.rs
|
@ -1,8 +1,8 @@
|
||||||
use crate::{
|
use crate::{
|
||||||
error::{Error, Result},
|
error::{Error, Result},
|
||||||
tun2proxy::{
|
tun2proxy::{
|
||||||
ConnectionInfo, ConnectionManager, Direction, IncomingDataEvent, IncomingDirection, OutgoingDataEvent,
|
ConnectionInfo, ConnectionManager, Direction, IncomingDataEvent, IncomingDirection, OutgoingDataEvent, OutgoingDirection,
|
||||||
OutgoingDirection, ProxyHandler,
|
ProxyHandler,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use socks5_impl::protocol::{self, handshake, password_method, Address, AuthMethod, StreamOperation, UserKey, Version};
|
use socks5_impl::protocol::{self, handshake, password_method, Address, AuthMethod, StreamOperation, UserKey, Version};
|
||||||
|
@ -34,12 +34,7 @@ struct SocksProxyImpl {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SocksProxyImpl {
|
impl SocksProxyImpl {
|
||||||
fn new(
|
fn new(info: &ConnectionInfo, credentials: Option<UserKey>, version: Version, command: protocol::Command) -> Result<Self> {
|
||||||
info: &ConnectionInfo,
|
|
||||||
credentials: Option<UserKey>,
|
|
||||||
version: Version,
|
|
||||||
command: protocol::Command,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let mut result = Self {
|
let mut result = Self {
|
||||||
info: info.clone(),
|
info: info.clone(),
|
||||||
state: SocksState::ServerHello,
|
state: SocksState::ServerHello,
|
||||||
|
@ -58,8 +53,7 @@ impl SocksProxyImpl {
|
||||||
|
|
||||||
fn send_client_hello_socks4(&mut self) -> Result<(), Error> {
|
fn send_client_hello_socks4(&mut self) -> Result<(), Error> {
|
||||||
let credentials = &self.credentials;
|
let credentials = &self.credentials;
|
||||||
self.server_outbuf
|
self.server_outbuf.extend(&[self.version as u8, protocol::Command::Connect.into()]);
|
||||||
.extend(&[self.version as u8, protocol::Command::Connect.into()]);
|
|
||||||
self.server_outbuf.extend(self.info.dst.port().to_be_bytes());
|
self.server_outbuf.extend(self.info.dst.port().to_be_bytes());
|
||||||
let mut ip_vec = Vec::<u8>::new();
|
let mut ip_vec = Vec::<u8>::new();
|
||||||
let mut name_vec = Vec::<u8>::new();
|
let mut name_vec = Vec::<u8>::new();
|
||||||
|
|
|
@ -271,8 +271,7 @@ impl<'a> TunToProxy<'a> {
|
||||||
let interests = Interest::READABLE | Interest::WRITABLE;
|
let interests = Interest::READABLE | Interest::WRITABLE;
|
||||||
|
|
||||||
#[cfg(target_family = "unix")]
|
#[cfg(target_family = "unix")]
|
||||||
poll.registry()
|
poll.registry().register(&mut SourceFd(&tun.as_raw_fd()), TUN_TOKEN, interests)?;
|
||||||
.register(&mut SourceFd(&tun.as_raw_fd()), TUN_TOKEN, interests)?;
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
|
@ -288,8 +287,7 @@ impl<'a> TunToProxy<'a> {
|
||||||
|
|
||||||
poll.registry()
|
poll.registry()
|
||||||
.register(&mut exit_trigger, EXIT_TRIGGER_TOKEN, Interest::WRITABLE)?;
|
.register(&mut exit_trigger, EXIT_TRIGGER_TOKEN, Interest::WRITABLE)?;
|
||||||
poll.registry()
|
poll.registry().register(&mut exit_receiver, EXIT_TOKEN, Interest::READABLE)?;
|
||||||
.register(&mut exit_receiver, EXIT_TOKEN, Interest::READABLE)?;
|
|
||||||
|
|
||||||
let config = match tun.capabilities().medium {
|
let config = match tun.capabilities().medium {
|
||||||
Medium::Ethernet => Config::new(smoltcp::wire::EthernetAddress([0x02, 0, 0, 0, 0, 0x01]).into()),
|
Medium::Ethernet => Config::new(smoltcp::wire::EthernetAddress([0x02, 0, 0, 0, 0, 0x01]).into()),
|
||||||
|
@ -585,15 +583,10 @@ impl<'a> TunToProxy<'a> {
|
||||||
state.dns_over_tcp_expiry = Some(Self::common_udp_life_timeout());
|
state.dns_over_tcp_expiry = Some(Self::common_udp_life_timeout());
|
||||||
|
|
||||||
let mut vecbuf = vec![];
|
let mut vecbuf = vec![];
|
||||||
Self::read_data_from_tcp_stream(
|
Self::read_data_from_tcp_stream(&mut state.mio_stream, IP_PACKAGE_MAX_SIZE, &mut state.is_tcp_closed, |data| {
|
||||||
&mut state.mio_stream,
|
|
||||||
IP_PACKAGE_MAX_SIZE,
|
|
||||||
&mut state.is_tcp_closed,
|
|
||||||
|data| {
|
|
||||||
vecbuf.extend_from_slice(data);
|
vecbuf.extend_from_slice(data);
|
||||||
Ok(())
|
Ok(())
|
||||||
},
|
})?;
|
||||||
)?;
|
|
||||||
|
|
||||||
let data_event = IncomingDataEvent {
|
let data_event = IncomingDataEvent {
|
||||||
direction: IncomingDirection::FromServer,
|
direction: IncomingDirection::FromServer,
|
||||||
|
@ -1090,18 +1083,13 @@ impl<'a> TunToProxy<'a> {
|
||||||
|
|
||||||
let mut vecbuf = vec![];
|
let mut vecbuf = vec![];
|
||||||
use std::io::{Error, ErrorKind};
|
use std::io::{Error, ErrorKind};
|
||||||
let r = Self::read_data_from_tcp_stream(
|
let r = Self::read_data_from_tcp_stream(&mut state.mio_stream, IP_PACKAGE_MAX_SIZE, &mut state.is_tcp_closed, |data| {
|
||||||
&mut state.mio_stream,
|
|
||||||
IP_PACKAGE_MAX_SIZE,
|
|
||||||
&mut state.is_tcp_closed,
|
|
||||||
|data| {
|
|
||||||
vecbuf.extend_from_slice(data);
|
vecbuf.extend_from_slice(data);
|
||||||
if vecbuf.len() >= IP_PACKAGE_MAX_SIZE {
|
if vecbuf.len() >= IP_PACKAGE_MAX_SIZE {
|
||||||
return Err(Error::new(ErrorKind::OutOfMemory, "IP_PACKAGE_MAX_SIZE exceeded"));
|
return Err(Error::new(ErrorKind::OutOfMemory, "IP_PACKAGE_MAX_SIZE exceeded"));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
},
|
});
|
||||||
);
|
|
||||||
let len = vecbuf.len();
|
let len = vecbuf.len();
|
||||||
if let Err(error) = r {
|
if let Err(error) = r {
|
||||||
if error.kind() == ErrorKind::OutOfMemory {
|
if error.kind() == ErrorKind::OutOfMemory {
|
||||||
|
|
|
@ -22,8 +22,8 @@ use windows::{
|
||||||
NetworkManagement::{
|
NetworkManagement::{
|
||||||
IpHelper::{
|
IpHelper::{
|
||||||
GetAdaptersAddresses, SetInterfaceDnsSettings, DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1,
|
GetAdaptersAddresses, SetInterfaceDnsSettings, DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1,
|
||||||
DNS_SETTING_NAMESERVER, GAA_FLAG_INCLUDE_GATEWAYS, GAA_FLAG_INCLUDE_PREFIX, IF_TYPE_ETHERNET_CSMACD,
|
DNS_SETTING_NAMESERVER, GAA_FLAG_INCLUDE_GATEWAYS, GAA_FLAG_INCLUDE_PREFIX, IF_TYPE_ETHERNET_CSMACD, IF_TYPE_IEEE80211,
|
||||||
IF_TYPE_IEEE80211, IP_ADAPTER_ADDRESSES_LH,
|
IP_ADAPTER_ADDRESSES_LH,
|
||||||
},
|
},
|
||||||
Ndis::IfOperStatusUp,
|
Ndis::IfOperStatusUp,
|
||||||
},
|
},
|
||||||
|
@ -88,8 +88,9 @@ impl WinTunInterface {
|
||||||
let guid = 324435345345345345_u128;
|
let guid = 324435345345345345_u128;
|
||||||
let adapter = match wintun::Adapter::open(&wintun, tun_name) {
|
let adapter = match wintun::Adapter::open(&wintun, tun_name) {
|
||||||
Ok(a) => a,
|
Ok(a) => a,
|
||||||
Err(_) => wintun::Adapter::create(&wintun, tun_name, tun_name, Some(guid))
|
Err(_) => {
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?,
|
wintun::Adapter::create(&wintun, tun_name, tun_name, Some(guid)).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let session = adapter
|
let session = adapter
|
||||||
|
@ -376,12 +377,7 @@ impl phy::TxToken for TxToken {
|
||||||
let mut buffer = vec![0; len];
|
let mut buffer = vec![0; len];
|
||||||
let result = f(&mut buffer);
|
let result = f(&mut buffer);
|
||||||
|
|
||||||
let buffer = self
|
let buffer = self.pipe_server_cache.borrow_mut().drain(..).chain(buffer).collect::<Vec<_>>();
|
||||||
.pipe_server_cache
|
|
||||||
.borrow_mut()
|
|
||||||
.drain(..)
|
|
||||||
.chain(buffer)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if buffer.is_empty() {
|
if buffer.is_empty() {
|
||||||
// log::trace!("Wintun TxToken (pipe_server) is empty");
|
// log::trace!("Wintun TxToken (pipe_server) is empty");
|
||||||
return result;
|
return result;
|
||||||
|
@ -433,11 +429,7 @@ impl event::Source for NamedPipeSource {
|
||||||
pub(crate) fn run_command(command: &str, args: &[&str]) -> io::Result<()> {
|
pub(crate) fn run_command(command: &str, args: &[&str]) -> io::Result<()> {
|
||||||
let out = std::process::Command::new(command).args(args).output()?;
|
let out = std::process::Command::new(command).args(args).output()?;
|
||||||
if !out.status.success() {
|
if !out.status.success() {
|
||||||
let err = String::from_utf8_lossy(if out.stderr.is_empty() {
|
let err = String::from_utf8_lossy(if out.stderr.is_empty() { &out.stdout } else { &out.stderr });
|
||||||
&out.stdout
|
|
||||||
} else {
|
|
||||||
&out.stderr
|
|
||||||
});
|
|
||||||
let info = format!("{} failed with: \"{}\"", command, err);
|
let info = format!("{} failed with: \"{}\"", command, err);
|
||||||
return Err(std::io::Error::new(std::io::ErrorKind::Other, info));
|
return Err(std::io::Error::new(std::io::ErrorKind::Other, info));
|
||||||
}
|
}
|
||||||
|
@ -463,9 +455,7 @@ pub(crate) fn set_interface_dns_settings(interface: GUID, dns: &[IpAddr]) -> io:
|
||||||
pub(crate) fn get_active_network_interface_gateways() -> io::Result<Vec<SocketAddr>> {
|
pub(crate) fn get_active_network_interface_gateways() -> io::Result<Vec<SocketAddr>> {
|
||||||
let mut addrs = vec![];
|
let mut addrs = vec![];
|
||||||
get_adapters_addresses(|adapter| {
|
get_adapters_addresses(|adapter| {
|
||||||
if adapter.OperStatus == IfOperStatusUp
|
if adapter.OperStatus == IfOperStatusUp && [IF_TYPE_ETHERNET_CSMACD, IF_TYPE_IEEE80211].contains(&adapter.IfType) {
|
||||||
&& [IF_TYPE_ETHERNET_CSMACD, IF_TYPE_IEEE80211].contains(&adapter.IfType)
|
|
||||||
{
|
|
||||||
let mut current_gateway = adapter.FirstGatewayAddress;
|
let mut current_gateway = adapter.FirstGatewayAddress;
|
||||||
while !current_gateway.is_null() {
|
while !current_gateway.is_null() {
|
||||||
let gateway = unsafe { &*current_gateway };
|
let gateway = unsafe { &*current_gateway };
|
||||||
|
|
Loading…
Add table
Reference in a new issue