refactor udp framed

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou
2022-01-04 00:44:50 +08:00
parent 6d506cbb64
commit 875570e040
8 changed files with 140 additions and 301 deletions

View File

@@ -1,22 +1,21 @@
use crate::{
config::{Config, Socks5Server},
config::{Config, NetworkType},
tcp::FramedStream,
udp::{FramedSocket, UdpFramedWrapper},
udp::FramedSocket,
ResultType,
};
use anyhow::{bail, Context};
use std::net::SocketAddr;
use tokio::net::ToSocketAddrs;
use tokio_socks::{udp::Socks5UdpFramed, IntoTargetAddr};
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
use tokio_socks::IntoTargetAddr;
pub fn get_socks5_conf() -> Option<Socks5Server> {
// Config::set_socks(Some(Socks5Server {
// proxy: "139.186.136.143:1080".to_owned(),
// ..Default::default()
// }));
Config::get_socks()
}
// fn get_socks5_conf() -> Option<Socks5Server> {
// // Config::set_socks(Some(Socks5Server {
// // proxy: "139.186.136.143:1080".to_owned(),
// // ..Default::default()
// // }));
// Config::get_socks()
// }
pub async fn connect_tcp<'t, T: IntoTargetAddr<'t>>(
target: T,
@@ -25,7 +24,7 @@ pub async fn connect_tcp<'t, T: IntoTargetAddr<'t>>(
) -> ResultType<FramedStream> {
let target_addr = target.into_target_addr()?;
if let Some(conf) = get_socks5_conf() {
if let Some(conf) = Config::get_socks() {
FramedStream::connect(
conf.proxy.as_str(),
target_addr,
@@ -48,26 +47,13 @@ pub async fn connect_tcp<'t, T: IntoTargetAddr<'t>>(
}
}
// TODO: merge connect_udp and connect_udp_socks5
pub async fn connect_udp_socket<T1: ToSocketAddrs>(
local: T1,
) -> ResultType<(
FramedSocket<UdpFramedWrapper<UdpFramed<BytesCodec>>>,
Option<SocketAddr>,
)> {
Ok((FramedSocket::new(local).await?, None))
}
pub async fn connect_udp_socks5<'t, T1: IntoTargetAddr<'t>, T2: ToSocketAddrs>(
pub async fn connect_udp<'t, T1: IntoTargetAddr<'t>, T2: ToSocketAddrs>(
target: T1,
local: T2,
socks5: &Option<Socks5Server>,
ms_timeout: u64,
) -> ResultType<(
FramedSocket<UdpFramedWrapper<Socks5UdpFramed>>,
Option<SocketAddr>,
)> {
match socks5 {
) -> ResultType<(FramedSocket, Option<SocketAddr>)> {
match Config::get_socks() {
None => Ok((FramedSocket::new(local).await?, None)),
Some(conf) => {
let (socket, addr) = FramedSocket::connect(
conf.proxy.as_str(),
@@ -80,8 +66,12 @@ pub async fn connect_udp_socks5<'t, T1: IntoTargetAddr<'t>, T2: ToSocketAddrs>(
.await?;
Ok((socket, Some(addr)))
}
None => {
bail!("Nil socks5 server config")
}
}
}
pub async fn reconnect_udp<T: ToSocketAddrs>(local: T) -> ResultType<Option<FramedSocket>> {
match Config::get_network_type() {
NetworkType::Direct => Ok(Some(FramedSocket::new(local).await?)),
_ => Ok(None),
}
}