use std::{
future::Future,
io,
net::{IpAddr, SocketAddr},
time::Duration,
};
use socket2::SockRef;
use thiserror::Error;
use tokio::{net::UdpSocket, time::MissedTickBehavior};
use crate::{
socket_io::{self, ReceivedDatagram},
socket_options::{marks_with_ipv4_option, set_reply_traffic_class},
ServerConfig, ServerCore, ServerError,
};
const RECEIVE_BUFFER_LEN: usize = 65_536;
const MAINTENANCE_INTERVAL: Duration = Duration::from_secs(1);
#[derive(Debug)]
pub struct Server {
socket: UdpSocket,
core: ServerCore,
recv_buffer: Vec<u8>,
listener_is_ipv4: bool,
select_reply_source: bool,
socket_is_marked: bool,
}
impl Server {
pub async fn bind(addr: SocketAddr, config: ServerConfig) -> Result<Self, ServerRuntimeError> {
let socket = UdpSocket::bind(addr)
.await
.map_err(|source| ServerRuntimeError::Bind { addr, source })?;
Self::from_socket(socket, config)
}
pub fn from_socket(
socket: UdpSocket,
config: ServerConfig,
) -> Result<Self, ServerRuntimeError> {
Self::with_core(socket, ServerCore::new(config))
}
#[cfg(test)]
pub(crate) fn from_socket_with_core(
socket: UdpSocket,
core: ServerCore,
) -> Result<Self, ServerRuntimeError> {
Self::with_core(socket, core)
}
fn with_core(socket: UdpSocket, core: ServerCore) -> Result<Self, ServerRuntimeError> {
let addr = socket
.local_addr()
.map_err(|source| ServerRuntimeError::LocalAddr { source })?;
let select_reply_source = is_wildcard(addr);
if select_reply_source {
if !socket_io::SUPPORTED {
return Err(ServerRuntimeError::WildcardSourceSelectionUnsupported { addr });
}
socket_io::configure_destination_metadata(&socket, addr.is_ipv4())
.map_err(|source| ServerRuntimeError::SourceSelectionSetup { addr, source })?;
}
let _ = socket_io::try_configure_kernel_rx_timestamp(&socket);
Ok(Self {
socket,
core,
recv_buffer: vec![0; RECEIVE_BUFFER_LEN],
listener_is_ipv4: marks_with_ipv4_option(addr),
select_reply_source,
socket_is_marked: false,
})
}
fn prepare_reply_traffic_class(&mut self, traffic_class: u8) -> bool {
match self.apply_reply_traffic_class(traffic_class) {
Ok(()) => {
self.socket_is_marked = traffic_class != 0;
true
}
Err(_) => may_send_unappliable(traffic_class, self.socket_is_marked),
}
}
fn apply_reply_traffic_class(&self, traffic_class: u8) -> io::Result<()> {
set_reply_traffic_class(
SockRef::from(&self.socket),
self.listener_is_ipv4,
traffic_class,
)
}
pub fn local_addr(&self) -> Result<SocketAddr, ServerRuntimeError> {
self.socket
.local_addr()
.map_err(|source| ServerRuntimeError::LocalAddr { source })
}
pub async fn run<F>(&mut self, shutdown: F) -> Result<(), ServerRuntimeError>
where
F: Future<Output = ()>,
{
tokio::pin!(shutdown);
let mut maintenance = tokio::time::interval(MAINTENANCE_INTERVAL);
maintenance.set_missed_tick_behavior(MissedTickBehavior::Skip);
maintenance.tick().await;
loop {
tokio::select! {
_ = &mut shutdown => return Ok(()),
_ = maintenance.tick() => self.core.maintain(),
received = socket_io::receive(
&self.socket,
&mut self.recv_buffer,
self.select_reply_source,
) => {
let received = match received {
Ok(Some(received)) => received,
Ok(None) => continue,
Err(source) if source.kind() == io::ErrorKind::Interrupted => continue,
Err(source) => return Err(ServerRuntimeError::Receive { source }),
};
let ReceivedDatagram {
len,
peer,
reply_source,
kernel_rx_timestamp,
} = received;
if let Some(reply) = self.core.handle_received_datagram(
peer,
&self.recv_buffer[..len],
kernel_rx_timestamp,
)? {
if !self.prepare_reply_traffic_class(reply.traffic_class()) {
continue;
}
let send = socket_io::send(
&self.socket,
reply.bytes(),
peer,
reply_source,
);
tokio::pin!(send);
let sent = loop {
tokio::select! {
_ = &mut shutdown => return Ok(()),
_ = maintenance.tick() => self.core.maintain(),
sent = &mut send => break sent,
}
};
if !matches!(sent, Ok(len) if len == reply.bytes().len()) {
continue;
}
}
}
}
}
}
}
fn is_wildcard(addr: SocketAddr) -> bool {
match addr.ip() {
IpAddr::V4(address) => address.is_unspecified(),
IpAddr::V6(address) => {
address.is_unspecified()
|| address
.to_ipv4_mapped()
.is_some_and(|mapped| mapped.is_unspecified())
}
}
}
fn may_send_unappliable(traffic_class: u8, socket_is_marked: bool) -> bool {
traffic_class == 0 && !socket_is_marked
}
#[derive(Debug, Error)]
pub enum ServerRuntimeError {
#[error("could not bind UDP listener at {addr}: {source}")]
Bind {
addr: SocketAddr,
#[source]
source: io::Error,
},
#[error("could not query UDP listener address: {source}")]
LocalAddr {
#[source]
source: io::Error,
},
#[error(
"wildcard listener {addr} cannot select its reply source address on this target: \
bind an explicit local address instead"
)]
WildcardSourceSelectionUnsupported { addr: SocketAddr },
#[error(
"could not configure reply source-address selection for wildcard listener {addr}: \
{source}; bind an explicit local address instead"
)]
SourceSelectionSetup {
addr: SocketAddr,
#[source]
source: io::Error,
},
#[error("UDP receive failed: {source}")]
Receive {
#[source]
source: io::Error,
},
#[error(transparent)]
Core(#[from] ServerError),
}
#[cfg(test)]
mod tests {
use std::{net::Ipv4Addr, time::Duration};
use irtt_proto::{
decode_echo_reply, decode_open_reply, encode_request, Clock, Params, ReceivedStats,
RequestToEncode, StampAt,
};
use tokio::{net::UdpSocket, sync::oneshot, time::timeout};
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn bind_reports_local_address_and_shutdown_stops_run() {
let requested = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
let mut server = Server::bind(requested, ServerConfig::default())
.await
.unwrap();
let bound = server.local_addr().unwrap();
assert_eq!(bound.ip(), requested.ip());
assert_ne!(bound.port(), 0);
let (shutdown_tx, shutdown_rx) = oneshot::channel();
shutdown_tx.send(()).unwrap();
server
.run(async {
let _ = shutdown_rx.await;
})
.await
.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn from_socket_settles_wildcard_source_selection_before_serving_anything() {
let explicit = UdpSocket::bind("127.0.0.1:0").await.unwrap();
assert!(Server::from_socket(explicit, ServerConfig::default()).is_ok());
let wildcard = UdpSocket::bind("0.0.0.0:0").await.unwrap();
let wildcard = Server::from_socket(wildcard, ServerConfig::default());
if socket_io::SUPPORTED {
let server = wildcard.expect("a supported target configures source selection");
assert!(server.select_reply_source);
} else {
assert!(matches!(
wildcard,
Err(ServerRuntimeError::WildcardSourceSelectionUnsupported { .. })
));
}
}
#[tokio::test(flavor = "current_thread")]
async fn ipv4_open_echo_close_crosses_a_real_udp_socket() {
exercise_udp_path(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).await;
}
#[tokio::test(flavor = "current_thread")]
async fn ipv6_open_echo_close_when_loopback_is_available() {
let addr = "[::1]:0".parse().unwrap();
let server = match Server::bind(addr, unthrottled()).await {
Ok(server) => server,
Err(ServerRuntimeError::Bind { source, .. })
if matches!(
source.kind(),
io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
) =>
{
return;
}
Err(error) => panic!("unexpected IPv6 loopback bind failure: {error}"),
};
exercise_bound_server(server).await;
}
async fn exercise_udp_path(addr: SocketAddr) {
let server = Server::bind(addr, unthrottled()).await.unwrap();
exercise_bound_server(server).await;
}
async fn exercise_bound_server(mut server: Server) {
let server_addr = server.local_addr().unwrap();
let client_bind = match server_addr {
SocketAddr::V4(_) => "127.0.0.1:0",
SocketAddr::V6(_) => "[::1]:0",
};
let client = UdpSocket::bind(client_bind).await.unwrap();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server_task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
let requested = Params {
protocol_version: 1,
duration_ns: 1_000_000_000,
interval_ns: 100_000_000,
received_stats: ReceivedStats::Both,
stamp_at: StampAt::Both,
clock: Clock::Both,
..Params::default()
};
let open = encode_request(
RequestToEncode::Open {
params: &requested,
no_test: false,
},
None,
)
.unwrap();
client.send_to(&open, server_addr).await.unwrap();
let mut buffer = vec![0; RECEIVE_BUFFER_LEN];
let (len, reply_source) = timeout(Duration::from_secs(1), client.recv_from(&mut buffer))
.await
.expect("OPEN reply timeout")
.unwrap();
assert_eq!(reply_source, server_addr);
let open_reply = decode_open_reply(&buffer[..len], None).unwrap();
assert_ne!(open_reply.token, 0);
let echo = encode_request(
RequestToEncode::Echo {
token: open_reply.token,
sequence: 0,
params: &open_reply.params,
payload: &[],
},
None,
)
.unwrap();
client.send_to(&echo, server_addr).await.unwrap();
let (len, reply_source) = timeout(Duration::from_secs(1), client.recv_from(&mut buffer))
.await
.expect("ECHO reply timeout")
.unwrap();
assert_eq!(reply_source, server_addr);
let echo_reply = decode_echo_reply(&buffer[..len], &open_reply.params, None).unwrap();
assert_eq!(echo_reply.token, open_reply.token);
assert_eq!(echo_reply.sequence, 0);
assert_eq!(echo_reply.recv_count, Some(1));
assert_eq!(echo_reply.recv_window, Some(1));
let close = encode_request(
RequestToEncode::Close {
token: open_reply.token,
},
None,
)
.unwrap();
client.send_to(&close, server_addr).await.unwrap();
client.send_to(&echo, server_addr).await.unwrap();
assert!(
timeout(Duration::from_millis(100), client.recv_from(&mut buffer))
.await
.is_err()
);
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
fn unthrottled() -> ServerConfig {
ServerConfig::default().with_min_send_interval(Duration::ZERO)
}
#[test]
fn a_bound_address_naming_no_particular_local_address_is_a_wildcard() {
for (addr, wildcard) in [
("0.0.0.0:2112", true),
("[::]:2112", true),
("[::ffff:0.0.0.0]:2112", true),
("127.0.0.1:2112", false),
("192.0.2.10:2112", false),
("[::1]:2112", false),
("[::ffff:127.0.0.1]:2112", false),
] {
assert_eq!(
is_wildcard(addr.parse().unwrap()),
wildcard,
"{addr} classified wrongly"
);
}
}
#[test]
fn only_an_unmarked_reply_on_a_never_marked_socket_survives_an_apply_failure() {
for (traffic_class, socket_is_marked, sendable, why) in [
(
0,
false,
true,
"no marking wanted, and none of ours to clear",
),
(0, true, false, "our own marking may still be on the socket"),
(
0xb8,
false,
false,
"a marking that was wanted but not applied",
),
(0xb8, true, false, "and likewise over a marking already set"),
] {
assert_eq!(
may_send_unappliable(traffic_class, socket_is_marked),
sendable,
"{why}"
);
}
}
}