socks5_impl/server/
mod.rs1use std::{
2 net::SocketAddr,
3 task::{Context, Poll},
4};
5use tokio::net::TcpListener;
6
7pub mod auth;
8pub mod connection;
9
10pub use crate::{
11 server::auth::{AuthAdaptor, AuthExecutor},
12 server::connection::{
13 ClientConnection, IncomingConnection,
14 associate::{AssociatedUdpSocket, UdpAssociate},
15 bind::Bind,
16 connect::Connect,
17 },
18};
19
20pub struct Server<O> {
27 listener: TcpListener,
28 auth: AuthAdaptor<O>,
29}
30
31impl<O: 'static> Server<O> {
32 #[inline]
34 pub fn new(listener: TcpListener, auth: AuthAdaptor<O>) -> Self {
35 Self { listener, auth }
36 }
37
38 #[inline]
40 pub async fn bind(addr: SocketAddr, auth: AuthAdaptor<O>) -> std::io::Result<Self> {
41 let socket = if addr.is_ipv4() {
42 tokio::net::TcpSocket::new_v4()?
43 } else {
44 tokio::net::TcpSocket::new_v6()?
45 };
46 socket.set_reuseaddr(true)?;
47 socket.bind(addr)?;
48 let listener = socket.listen(1024)?;
49 Ok(Self::new(listener, auth))
50 }
51
52 #[inline]
57 pub async fn accept(&self) -> std::io::Result<(IncomingConnection<O>, SocketAddr)> {
58 let (stream, addr) = self.listener.accept().await?;
59 Ok((IncomingConnection::new(stream, self.auth.clone()), addr))
60 }
61
62 #[inline]
72 pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<(IncomingConnection<O>, SocketAddr)>> {
73 self.listener
74 .poll_accept(cx)
75 .map_ok(|(stream, addr)| (IncomingConnection::new(stream, self.auth.clone()), addr))
76 }
77
78 #[inline]
80 pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
81 self.listener.local_addr()
82 }
83}
84
85impl<O> From<(TcpListener, AuthAdaptor<O>)> for Server<O> {
86 #[inline]
87 fn from((listener, auth): (TcpListener, AuthAdaptor<O>)) -> Self {
88 Self { listener, auth }
89 }
90}
91
92impl<O> From<Server<O>> for (TcpListener, AuthAdaptor<O>) {
93 #[inline]
94 fn from(server: Server<O>) -> Self {
95 (server.listener, server.auth)
96 }
97}