use std::{
net::SocketAddr,
task::{Context, Poll},
};
use tokio::net::TcpListener;
pub mod auth;
pub mod connection;
pub use crate::{
server::auth::{AuthAdaptor, AuthExecutor},
server::connection::{
ClientConnection, IncomingConnection,
associate::{AssociatedUdpSocket, UdpAssociate},
bind::Bind,
connect::Connect,
},
};
pub struct Server<O> {
listener: TcpListener,
auth: AuthAdaptor<O>,
}
impl<O: 'static> Server<O> {
#[inline]
pub fn new(listener: TcpListener, auth: AuthAdaptor<O>) -> Self {
Self { listener, auth }
}
#[inline]
pub async fn bind(addr: SocketAddr, auth: AuthAdaptor<O>) -> std::io::Result<Self> {
Self::bind_with_backlog(addr, auth, 1024).await
}
pub async fn bind_with_backlog(addr: SocketAddr, auth: AuthAdaptor<O>, backlog: u32) -> std::io::Result<Self> {
let socket = if addr.is_ipv4() {
tokio::net::TcpSocket::new_v4()?
} else {
tokio::net::TcpSocket::new_v6()?
};
socket.set_reuseaddr(true)?;
socket.bind(addr)?;
let listener = socket.listen(backlog)?;
Ok(Self::new(listener, auth))
}
#[inline]
pub async fn accept(&self) -> std::io::Result<(IncomingConnection<O>, SocketAddr)> {
let (stream, addr) = self.listener.accept().await?;
Ok((IncomingConnection::new(stream, self.auth.clone()), addr))
}
#[inline]
pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<(IncomingConnection<O>, SocketAddr)>> {
self.listener
.poll_accept(cx)
.map_ok(|(stream, addr)| (IncomingConnection::new(stream, self.auth.clone()), addr))
}
#[inline]
pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
self.listener.local_addr()
}
}
impl<O> From<(TcpListener, AuthAdaptor<O>)> for Server<O> {
#[inline]
fn from((listener, auth): (TcpListener, AuthAdaptor<O>)) -> Self {
Self { listener, auth }
}
}
impl<O> From<Server<O>> for (TcpListener, AuthAdaptor<O>) {
#[inline]
fn from(server: Server<O>) -> Self {
(server.listener, server.auth)
}
}