Refactor: project structure and logging. Add: Integration tests for happy flow of UDP and TLS.
This commit is contained in:
@@ -1,138 +0,0 @@
|
||||
use bytes::BytesMut;
|
||||
use niom_turn::constants::*;
|
||||
// use niom_turn::stun; // not needed; use specific functions via path when required
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
// Use shared decoder from library: niom_turn::stun::decode_xor_relayed_address
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
let server: SocketAddr = "127.0.0.1:3478".parse()?;
|
||||
let local = UdpSocket::bind("0.0.0.0:0").await?;
|
||||
|
||||
let username = "testuser";
|
||||
let password = "secretpassword";
|
||||
|
||||
// Build Allocate request (method METHOD_ALLOCATE)
|
||||
let mut buf = BytesMut::new();
|
||||
buf.extend_from_slice(&METHOD_ALLOCATE.to_be_bytes()); // Allocate Request
|
||||
buf.extend_from_slice(&0u16.to_be_bytes()); // length placeholder
|
||||
buf.extend_from_slice(&MAGIC_COOKIE_BYTES);
|
||||
let trans = [13u8; 12];
|
||||
buf.extend_from_slice(&trans);
|
||||
|
||||
// USERNAME
|
||||
let uname = username.as_bytes();
|
||||
buf.extend_from_slice(&ATTR_USERNAME.to_be_bytes());
|
||||
buf.extend_from_slice(&(uname.len() as u16).to_be_bytes());
|
||||
buf.extend_from_slice(uname);
|
||||
while (buf.len() % 4) != 0 {
|
||||
buf.extend_from_slice(&[0u8]);
|
||||
}
|
||||
|
||||
// MESSAGE-INTEGRITY placeholder
|
||||
let mi_attr_offset = buf.len();
|
||||
buf.extend_from_slice(&ATTR_MESSAGE_INTEGRITY.to_be_bytes());
|
||||
buf.extend_from_slice(&((HMAC_SHA1_LEN as u16).to_be_bytes()));
|
||||
let mi_val_pos = buf.len();
|
||||
buf.extend_from_slice(&[0u8; 20]);
|
||||
while (buf.len() % 4) != 0 {
|
||||
buf.extend_from_slice(&[0u8]);
|
||||
}
|
||||
|
||||
// fix length
|
||||
let total_len = (buf.len() - 20) as u16;
|
||||
let len_bytes = total_len.to_be_bytes();
|
||||
buf[2] = len_bytes[0];
|
||||
buf[3] = len_bytes[1];
|
||||
|
||||
// compute HMAC over bytes up to MI attribute header
|
||||
{
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha1::Sha1;
|
||||
type HmacSha1 = Hmac<Sha1>;
|
||||
let mut mac = HmacSha1::new_from_slice(password.as_bytes()).expect("HMAC key");
|
||||
mac.update(&buf[..mi_attr_offset]);
|
||||
let res = mac.finalize().into_bytes();
|
||||
for i in 0..20 {
|
||||
buf[mi_val_pos + i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
// send Allocate
|
||||
local.send_to(&buf, server).await?;
|
||||
|
||||
// receive response
|
||||
let mut r = vec![0u8; 1500];
|
||||
let (len, _addr) = local.recv_from(&mut r).await?;
|
||||
println!("got {} bytes", len);
|
||||
let resp = &r[..len];
|
||||
// expect success (METHOD_ALLOCATE | CLASS_SUCCESS) with XOR-RELAYED-ADDRESS attr
|
||||
if resp.len() < 20 {
|
||||
anyhow::bail!("response too short");
|
||||
}
|
||||
let typ = u16::from_be_bytes([resp[0], resp[1]]);
|
||||
println!("resp type 0x{:04x}", typ);
|
||||
let expected_type = METHOD_ALLOCATE | CLASS_SUCCESS;
|
||||
if typ != expected_type {
|
||||
anyhow::bail!("expected success response, got 0x{:04x}", typ);
|
||||
}
|
||||
// parse attributes
|
||||
let length = u16::from_be_bytes([resp[2], resp[3]]) as usize;
|
||||
let total = 20 + length;
|
||||
let mut offset = 20;
|
||||
let mut relay_addr_opt: Option<SocketAddr> = None;
|
||||
while offset + 4 <= total {
|
||||
let atype = u16::from_be_bytes([resp[offset], resp[offset + 1]]);
|
||||
let alen = u16::from_be_bytes([resp[offset + 2], resp[offset + 3]]) as usize;
|
||||
offset += 4;
|
||||
if offset + alen > total {
|
||||
break;
|
||||
}
|
||||
println!("attr type=0x{:04x} len={}", atype, alen);
|
||||
println!("raw: {}", hex::encode(&resp[offset..offset + alen]));
|
||||
if atype == ATTR_XOR_RELAYED_ADDRESS {
|
||||
// XOR-RELAYED-ADDRESS: decode via shared library function
|
||||
if let Some(sa) =
|
||||
niom_turn::stun::decode_xor_relayed_address(&resp[offset..offset + alen], &trans)
|
||||
{
|
||||
relay_addr_opt = Some(sa);
|
||||
}
|
||||
}
|
||||
offset += alen;
|
||||
let pad = (4 - (alen % 4)) % 4;
|
||||
offset += pad;
|
||||
}
|
||||
|
||||
let relay_addr = match relay_addr_opt {
|
||||
Some(a) => a,
|
||||
None => anyhow::bail!("no relay address in response"),
|
||||
};
|
||||
|
||||
println!("got relayed addr: {}", relay_addr);
|
||||
|
||||
// send test payload to relay addr
|
||||
let payload = b"hello-relay";
|
||||
local.send_to(payload, relay_addr).await?;
|
||||
|
||||
// wait for forwarded packet (should arrive via server socket) using tokio timeout
|
||||
let mut buf2 = vec![0u8; 1500];
|
||||
match tokio::time::timeout(Duration::from_secs(2), local.recv_from(&mut buf2)).await {
|
||||
Ok(Ok((l, src))) => {
|
||||
println!("received {} bytes from {}", l, src);
|
||||
let got = &buf2[..l];
|
||||
println!("payload: {:?}", got);
|
||||
if got == payload {
|
||||
println!("relay test success");
|
||||
Ok(())
|
||||
} else {
|
||||
anyhow::bail!("payload mismatch")
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => anyhow::bail!("recv error: {:?}", e),
|
||||
Err(_) => anyhow::bail!("no forwarded packet received: timeout"),
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
use bytes::BytesMut;
|
||||
use niom_turn::constants::*;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
let server: SocketAddr = "127.0.0.1:3478".parse()?;
|
||||
let local = UdpSocket::bind("0.0.0.0:0").await?;
|
||||
|
||||
// Build a minimal STUN Binding Request with USERNAME and placeholder MESSAGE-INTEGRITY
|
||||
let username = "testuser";
|
||||
let password = "secretpassword"; // matches server's in-memory creds
|
||||
|
||||
let mut buf = BytesMut::new();
|
||||
buf.extend_from_slice(&METHOD_BINDING.to_be_bytes()); // Binding Request
|
||||
buf.extend_from_slice(&0u16.to_be_bytes()); // length placeholder
|
||||
buf.extend_from_slice(&MAGIC_COOKIE_BYTES);
|
||||
let trans = [7u8; 12];
|
||||
buf.extend_from_slice(&trans);
|
||||
|
||||
// USERNAME
|
||||
let uname = username.as_bytes();
|
||||
buf.extend_from_slice(&ATTR_USERNAME.to_be_bytes());
|
||||
buf.extend_from_slice(&(uname.len() as u16).to_be_bytes());
|
||||
buf.extend_from_slice(uname);
|
||||
while (buf.len() % 4) != 0 {
|
||||
buf.extend_from_slice(&[0u8]);
|
||||
}
|
||||
|
||||
// MESSAGE-INTEGRITY placeholder
|
||||
let mi_attr_offset = buf.len();
|
||||
buf.extend_from_slice(&ATTR_MESSAGE_INTEGRITY.to_be_bytes());
|
||||
buf.extend_from_slice(&((HMAC_SHA1_LEN as u16).to_be_bytes()));
|
||||
let mi_val_pos = buf.len();
|
||||
buf.extend_from_slice(&[0u8; 20]);
|
||||
while (buf.len() % 4) != 0 {
|
||||
buf.extend_from_slice(&[0u8]);
|
||||
}
|
||||
|
||||
// fix length
|
||||
let total_len = (buf.len() - 20) as u16;
|
||||
let len_bytes = total_len.to_be_bytes();
|
||||
buf[2] = len_bytes[0];
|
||||
buf[3] = len_bytes[1];
|
||||
|
||||
// compute HMAC over bytes up to MI attribute header
|
||||
{
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha1::Sha1;
|
||||
type HmacSha1 = Hmac<Sha1>;
|
||||
let mut mac = HmacSha1::new_from_slice(password.as_bytes()).expect("HMAC key");
|
||||
mac.update(&buf[..mi_attr_offset]);
|
||||
let res = mac.finalize().into_bytes();
|
||||
for i in 0..20 {
|
||||
buf[mi_val_pos + i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
// send
|
||||
local.send_to(&buf, server).await?;
|
||||
|
||||
let mut r = vec![0u8; 1500];
|
||||
let (len, addr) = local.recv_from(&mut r).await?;
|
||||
println!("got {} bytes from {}", len, addr);
|
||||
// dump hex
|
||||
println!("{:02x?}", &r[..len]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -3,11 +3,15 @@ pub mod alloc;
|
||||
pub mod auth;
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
pub mod logging;
|
||||
pub mod models;
|
||||
pub mod server;
|
||||
pub mod stun;
|
||||
pub mod tls;
|
||||
pub mod traits;
|
||||
|
||||
pub use crate::alloc::*;
|
||||
pub use crate::auth::*;
|
||||
pub use crate::logging::*;
|
||||
pub use crate::server::*;
|
||||
pub use crate::stun::*;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Logging helpers shared between the library, binaries, and integration tests.
|
||||
//! Ensures we configure tracing once with sensible default filters while still
|
||||
//! allowing `RUST_LOG` to override verbosity.
|
||||
use std::sync::Once;
|
||||
use tracing_subscriber::{fmt, EnvFilter};
|
||||
|
||||
static INIT: Once = Once::new();
|
||||
|
||||
/// Initialise tracing with a sane default filter (`warn` globally,
|
||||
/// `niom_turn=info`) unless `RUST_LOG` is provided.
|
||||
pub fn init_tracing() {
|
||||
init_tracing_with_default("warn,niom_turn=info");
|
||||
}
|
||||
|
||||
/// Initialise tracing with a custom default directive that can still be
|
||||
/// overridden via `RUST_LOG` at runtime.
|
||||
pub fn init_tracing_with_default(default_directive: &str) {
|
||||
INIT.call_once(|| {
|
||||
let env_filter =
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_directive));
|
||||
|
||||
fmt()
|
||||
.with_env_filter(env_filter)
|
||||
.with_target(false)
|
||||
.compact()
|
||||
.init();
|
||||
});
|
||||
}
|
||||
+4
-455
@@ -2,24 +2,18 @@
|
||||
//! Backlog: graceful shutdown signals, structured metrics, and coordinated lifecycle management across listeners.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
use tracing::{error, info};
|
||||
|
||||
// Use the library crate's public modules instead of local `mod` declarations.
|
||||
use niom_turn::alloc::AllocationManager;
|
||||
use niom_turn::auth::{AuthManager, AuthStatus, InMemoryStore};
|
||||
use niom_turn::auth::{AuthManager, InMemoryStore};
|
||||
use niom_turn::config::{AuthOptions, Config};
|
||||
use niom_turn::constants::*;
|
||||
use niom_turn::stun::{
|
||||
build_401_response, build_allocate_success, build_error_response, build_lifetime_success,
|
||||
build_success_response, decode_xor_peer_address, extract_lifetime_seconds, parse_channel_data,
|
||||
parse_message,
|
||||
};
|
||||
use niom_turn::server::udp_reader_loop;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
niom_turn::logging::init_tracing();
|
||||
|
||||
info!("niom-turn starting");
|
||||
|
||||
@@ -64,7 +58,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
let udp = UdpSocket::bind(bind_addr).await?;
|
||||
let udp = Arc::new(udp);
|
||||
|
||||
// allocation manager
|
||||
// Allocation manager shared by UDP + TLS frontends.
|
||||
let alloc_mgr = AllocationManager::new();
|
||||
|
||||
// Spawn the asynchronous packet loop that handles all UDP requests.
|
||||
@@ -103,448 +97,3 @@ async fn main() -> anyhow::Result<()> {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp_reader_loop(
|
||||
udp: Arc<UdpSocket>,
|
||||
auth: AuthManager<InMemoryStore>,
|
||||
allocs: AllocationManager,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut buf = vec![0u8; 1500];
|
||||
loop {
|
||||
// Read the next datagram and keep peer metadata for follow-up responses.
|
||||
let (len, peer) = udp.recv_from(&mut buf).await?;
|
||||
tracing::debug!("got {} bytes from {}", len, peer);
|
||||
|
||||
if let Some((channel, payload)) = parse_channel_data(&buf[..len]) {
|
||||
let allocation = match allocs.get_allocation(&peer) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
tracing::warn!("channel data without allocation from {}", peer);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let target = match allocation.channel_peer(channel) {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"channel data with unknown channel 0x{:04x} from {}",
|
||||
channel,
|
||||
peer
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !allocation.is_peer_allowed(&target) {
|
||||
tracing::warn!(
|
||||
"channel data target {} no longer permitted for {}",
|
||||
target,
|
||||
peer
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
match allocation.send_to_peer(target, payload).await {
|
||||
Ok(sent) => tracing::debug!(
|
||||
"forwarded {} bytes via channel 0x{:04x} from {} to {}",
|
||||
sent,
|
||||
channel,
|
||||
peer,
|
||||
target
|
||||
),
|
||||
Err(e) => tracing::error!(
|
||||
"failed to forward channel data 0x{:04x} from {} to {}: {:?}",
|
||||
channel,
|
||||
peer,
|
||||
target,
|
||||
e
|
||||
),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Minimal STUN/TURN detection: parse STUN messages and send 401 challenge
|
||||
if let Ok(msg) = parse_message(&buf[..len]) {
|
||||
tracing::info!(
|
||||
"STUN/TURN message from {} type=0x{:04x} len={}",
|
||||
peer,
|
||||
msg.header.msg_type,
|
||||
len
|
||||
);
|
||||
let requires_auth = matches!(
|
||||
msg.header.msg_type,
|
||||
METHOD_ALLOCATE
|
||||
| METHOD_CREATE_PERMISSION
|
||||
| METHOD_CHANNEL_BIND
|
||||
| METHOD_SEND
|
||||
| METHOD_REFRESH
|
||||
);
|
||||
|
||||
if requires_auth {
|
||||
match auth.authenticate(&msg, &peer).await {
|
||||
AuthStatus::Granted { username } => {
|
||||
tracing::debug!(
|
||||
"TURN auth ok for {} as {} (0x{:04x})",
|
||||
peer,
|
||||
username,
|
||||
msg.header.msg_type
|
||||
);
|
||||
}
|
||||
AuthStatus::Challenge { nonce } => {
|
||||
let resp = build_401_response(
|
||||
&msg.header,
|
||||
auth.realm(),
|
||||
&nonce,
|
||||
401,
|
||||
"Unauthorized",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
AuthStatus::StaleNonce { nonce } => {
|
||||
let resp = build_401_response(
|
||||
&msg.header,
|
||||
auth.realm(),
|
||||
&nonce,
|
||||
438,
|
||||
"Stale Nonce",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
AuthStatus::Reject { code, reason } => {
|
||||
let resp = build_error_response(&msg.header, code, reason);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
match msg.header.msg_type {
|
||||
METHOD_ALLOCATE => {
|
||||
let requested_lifetime = extract_lifetime_seconds(&msg)
|
||||
.map(|secs| Duration::from_secs(secs as u64))
|
||||
.filter(|d| !d.is_zero());
|
||||
|
||||
match allocs.allocate_for(peer, udp.clone()).await {
|
||||
Ok(relay_addr) => {
|
||||
let applied =
|
||||
match allocs.refresh_allocation(peer, requested_lifetime) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to apply lifetime for {}: {:?}",
|
||||
peer,
|
||||
e
|
||||
);
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
500,
|
||||
"Allocate Failed",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let lifetime_secs = applied.as_secs().min(u32::MAX as u64) as u32;
|
||||
let resp =
|
||||
build_allocate_success(&msg.header, &relay_addr, lifetime_secs);
|
||||
tracing::info!(
|
||||
"allocated relay {} for {} lifetime={}s",
|
||||
relay_addr,
|
||||
peer,
|
||||
lifetime_secs
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("allocate failed: {:?}", e);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 500, "Allocate Failed");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_CREATE_PERMISSION => {
|
||||
if allocs.get_allocation(&peer).is_none() {
|
||||
tracing::warn!("create-permission without allocation from {}", peer);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut added = 0usize;
|
||||
for attr in msg
|
||||
.attributes
|
||||
.iter()
|
||||
.filter(|a| a.typ == ATTR_XOR_PEER_ADDRESS)
|
||||
{
|
||||
if let Some(peer_addr) =
|
||||
decode_xor_peer_address(&attr.value, &msg.header.transaction_id)
|
||||
{
|
||||
match allocs.add_permission(peer, peer_addr) {
|
||||
Ok(()) => {
|
||||
tracing::info!(
|
||||
"added permission for {} -> {}",
|
||||
peer,
|
||||
peer_addr
|
||||
);
|
||||
added += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to persist permission {} -> {}: {:?}",
|
||||
peer,
|
||||
peer_addr,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::warn!("invalid XOR-PEER-ADDRESS in request from {}", peer);
|
||||
}
|
||||
}
|
||||
|
||||
if added == 0 {
|
||||
let resp =
|
||||
build_error_response(&msg.header, 400, "No valid XOR-PEER-ADDRESS");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
} else {
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_CHANNEL_BIND => {
|
||||
let allocation = match allocs.get_allocation(&peer) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
tracing::warn!("channel-bind without allocation from {}", peer);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let channel_attr =
|
||||
msg.attributes.iter().find(|a| a.typ == ATTR_CHANNEL_NUMBER);
|
||||
let peer_attr = msg
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|a| a.typ == ATTR_XOR_PEER_ADDRESS);
|
||||
|
||||
let channel = match channel_attr.and_then(|attr| {
|
||||
if attr.value.len() >= 4 {
|
||||
Some(u16::from_be_bytes([attr.value[0], attr.value[1]]))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Missing CHANNEL-NUMBER",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if channel < 0x4000 || channel > 0x7FFF {
|
||||
let resp =
|
||||
build_error_response(&msg.header, 400, "Channel Out Of Range");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let peer_addr = match peer_attr.and_then(|attr| {
|
||||
decode_xor_peer_address(&attr.value, &msg.header.transaction_id)
|
||||
}) {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Missing XOR-PEER-ADDRESS",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !allocation.is_peer_allowed(&peer_addr) {
|
||||
let resp = build_error_response(&msg.header, 403, "Peer Not Permitted");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
match allocs.add_channel_binding(peer, channel, peer_addr) {
|
||||
Ok(()) => {
|
||||
tracing::info!(
|
||||
"bound channel 0x{:04x} for {} -> {}",
|
||||
channel,
|
||||
peer,
|
||||
peer_addr
|
||||
);
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to add channel binding {} -> {} (channel 0x{:04x}): {:?}",
|
||||
peer,
|
||||
peer_addr,
|
||||
channel,
|
||||
e
|
||||
);
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
500,
|
||||
"Channel Binding Failed",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_SEND => {
|
||||
let allocation = match allocs.get_allocation(&peer) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
tracing::warn!("send without allocation from {}", peer);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let peer_attr = msg
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|a| a.typ == ATTR_XOR_PEER_ADDRESS);
|
||||
let data_attr = msg.attributes.iter().find(|a| a.typ == ATTR_DATA);
|
||||
|
||||
let peer_addr = match peer_attr.and_then(|attr| {
|
||||
decode_xor_peer_address(&attr.value, &msg.header.transaction_id)
|
||||
}) {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Missing XOR-PEER-ADDRESS",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let data_attr = match data_attr {
|
||||
Some(attr) => attr,
|
||||
None => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Missing DATA Attribute",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !allocation.is_peer_allowed(&peer_addr) {
|
||||
let resp = build_error_response(&msg.header, 403, "Peer Not Permitted");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
match allocation.send_to_peer(peer_addr, &data_attr.value).await {
|
||||
Ok(sent) => {
|
||||
tracing::info!(
|
||||
"forwarded {} bytes from {} to peer {}",
|
||||
sent,
|
||||
peer,
|
||||
peer_addr
|
||||
);
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to send payload from {} to {}: {:?}",
|
||||
peer,
|
||||
peer_addr,
|
||||
e
|
||||
);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 500, "Peer Send Failed");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_REFRESH => {
|
||||
let requested = extract_lifetime_seconds(&msg)
|
||||
.map(|secs| Duration::from_secs(secs as u64));
|
||||
|
||||
match allocs.refresh_allocation(peer, requested) {
|
||||
Ok(applied) => {
|
||||
if applied.is_zero() {
|
||||
tracing::info!("allocation for {} released", peer);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"allocation for {} refreshed to {}s",
|
||||
peer,
|
||||
applied.as_secs()
|
||||
);
|
||||
}
|
||||
let resp = build_lifetime_success(
|
||||
&msg.header,
|
||||
applied.as_secs().min(u32::MAX as u64) as u32,
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(_) => {
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
let resp = build_error_response(&msg.header, 420, "Unknown TURN Method");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match msg.header.msg_type {
|
||||
METHOD_BINDING => {
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
_ => {
|
||||
let nonce = auth.mint_nonce(&peer);
|
||||
let resp =
|
||||
build_401_response(&msg.header, auth.realm(), &nonce, 401, "Unauthorized");
|
||||
if let Err(e) = udp.send_to(&resp, &peer).await {
|
||||
error!("failed to send 401: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::debug!("Non-STUN or parse error from {} len={}", peer, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// existing helper functions moved to stun.rs
|
||||
|
||||
+429
@@ -0,0 +1,429 @@
|
||||
//! Shared server routines for UDP TURN handling so integration tests can reuse the core loop.
|
||||
use std::sync::Arc;
|
||||
use tokio::net::UdpSocket;
|
||||
use tracing::{error, warn};
|
||||
|
||||
use crate::alloc::AllocationManager;
|
||||
use crate::auth::{AuthManager, AuthStatus, InMemoryStore};
|
||||
use crate::constants::*;
|
||||
use crate::stun::{
|
||||
build_401_response, build_allocate_success, build_error_response, build_lifetime_success,
|
||||
build_success_response, decode_xor_peer_address, extract_lifetime_seconds, parse_channel_data,
|
||||
parse_message,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Main UDP reader loop shared between binary entry point and integration tests.
|
||||
pub async fn udp_reader_loop(
|
||||
udp: Arc<UdpSocket>,
|
||||
auth: AuthManager<InMemoryStore>,
|
||||
allocs: AllocationManager,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut buf = vec![0u8; 1500];
|
||||
loop {
|
||||
let (len, peer) = udp.recv_from(&mut buf).await?;
|
||||
tracing::debug!("got {} bytes from {}", len, peer);
|
||||
|
||||
if let Some((channel, payload)) = parse_channel_data(&buf[..len]) {
|
||||
let allocation = match allocs.get_allocation(&peer) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
warn!("channel data without allocation from {}", peer);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let target = match allocation.channel_peer(channel) {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
warn!(
|
||||
"channel data with unknown channel 0x{:04x} from {}",
|
||||
channel, peer
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !allocation.is_peer_allowed(&target) {
|
||||
warn!(
|
||||
"channel data target {} no longer permitted for {}",
|
||||
target, peer
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
match allocation.send_to_peer(target, payload).await {
|
||||
Ok(sent) => tracing::debug!(
|
||||
"forwarded {} bytes via channel 0x{:04x} from {} to {}",
|
||||
sent,
|
||||
channel,
|
||||
peer,
|
||||
target
|
||||
),
|
||||
Err(e) => error!(
|
||||
"failed to forward channel data 0x{:04x} from {} to {}: {:?}",
|
||||
channel, peer, target, e
|
||||
),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(msg) = parse_message(&buf[..len]) {
|
||||
tracing::info!(
|
||||
"STUN/TURN message from {} type=0x{:04x} len={}",
|
||||
peer,
|
||||
msg.header.msg_type,
|
||||
len
|
||||
);
|
||||
let requires_auth = matches!(
|
||||
msg.header.msg_type,
|
||||
METHOD_ALLOCATE
|
||||
| METHOD_CREATE_PERMISSION
|
||||
| METHOD_CHANNEL_BIND
|
||||
| METHOD_SEND
|
||||
| METHOD_REFRESH
|
||||
);
|
||||
|
||||
if requires_auth {
|
||||
match auth.authenticate(&msg, &peer).await {
|
||||
AuthStatus::Granted { username } => {
|
||||
tracing::debug!(
|
||||
"TURN auth ok for {} as {} (0x{:04x})",
|
||||
peer,
|
||||
username,
|
||||
msg.header.msg_type
|
||||
);
|
||||
}
|
||||
AuthStatus::Challenge { nonce } => {
|
||||
let resp = build_401_response(
|
||||
&msg.header,
|
||||
auth.realm(),
|
||||
&nonce,
|
||||
401,
|
||||
"Unauthorized",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
AuthStatus::StaleNonce { nonce } => {
|
||||
let resp = build_401_response(
|
||||
&msg.header,
|
||||
auth.realm(),
|
||||
&nonce,
|
||||
438,
|
||||
"Stale Nonce",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
AuthStatus::Reject { code, reason } => {
|
||||
let resp = build_error_response(&msg.header, code, reason);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
match msg.header.msg_type {
|
||||
METHOD_ALLOCATE => {
|
||||
let requested_lifetime = extract_lifetime_seconds(&msg)
|
||||
.map(|secs| Duration::from_secs(secs as u64))
|
||||
.filter(|d| !d.is_zero());
|
||||
|
||||
match allocs.allocate_for(peer, udp.clone()).await {
|
||||
Ok(relay_addr) => {
|
||||
let applied =
|
||||
match allocs.refresh_allocation(peer, requested_lifetime) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to apply lifetime for {}: {:?}",
|
||||
peer,
|
||||
e
|
||||
);
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
500,
|
||||
"Allocate Failed",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let lifetime_secs = applied.as_secs().min(u32::MAX as u64) as u32;
|
||||
let resp =
|
||||
build_allocate_success(&msg.header, &relay_addr, lifetime_secs);
|
||||
tracing::info!(
|
||||
"allocated relay {} for {} lifetime={}s",
|
||||
relay_addr,
|
||||
peer,
|
||||
lifetime_secs
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("allocate failed: {:?}", e);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 500, "Allocate Failed");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_CREATE_PERMISSION => {
|
||||
if allocs.get_allocation(&peer).is_none() {
|
||||
warn!("create-permission without allocation from {}", peer);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut added = 0usize;
|
||||
for attr in msg
|
||||
.attributes
|
||||
.iter()
|
||||
.filter(|a| a.typ == ATTR_XOR_PEER_ADDRESS)
|
||||
{
|
||||
if let Some(peer_addr) =
|
||||
decode_xor_peer_address(&attr.value, &msg.header.transaction_id)
|
||||
{
|
||||
match allocs.add_permission(peer, peer_addr) {
|
||||
Ok(()) => {
|
||||
tracing::info!(
|
||||
"added permission for {} -> {}",
|
||||
peer,
|
||||
peer_addr
|
||||
);
|
||||
added += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to persist permission {} -> {}: {:?}",
|
||||
peer,
|
||||
peer_addr,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::warn!("invalid XOR-PEER-ADDRESS in request from {}", peer);
|
||||
}
|
||||
}
|
||||
|
||||
if added == 0 {
|
||||
let resp =
|
||||
build_error_response(&msg.header, 400, "No valid XOR-PEER-ADDRESS");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
} else {
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_CHANNEL_BIND => {
|
||||
let allocation = match allocs.get_allocation(&peer) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
warn!("channel-bind without allocation from {}", peer);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let channel_attr =
|
||||
msg.attributes.iter().find(|a| a.typ == ATTR_CHANNEL_NUMBER);
|
||||
let peer_attr = msg
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|a| a.typ == ATTR_XOR_PEER_ADDRESS);
|
||||
let (channel_attr, peer_attr) = match (channel_attr, peer_attr) {
|
||||
(Some(c), Some(p)) => (c, p),
|
||||
_ => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Missing CHANNEL-NUMBER or XOR-PEER-ADDRESS",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let channel =
|
||||
u16::from_be_bytes([channel_attr.value[0], channel_attr.value[1]]);
|
||||
let peer_addr = match decode_xor_peer_address(
|
||||
&peer_attr.value,
|
||||
&msg.header.transaction_id,
|
||||
) {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Invalid XOR-PEER-ADDRESS",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !allocation.is_peer_allowed(&peer_addr) {
|
||||
let resp = build_error_response(&msg.header, 403, "Peer Not Permitted");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(e) = allocs.add_channel_binding(peer, channel, peer_addr) {
|
||||
tracing::error!(
|
||||
"failed to persist channel binding {} -> {} (0x{:04x}): {:?}",
|
||||
peer,
|
||||
peer_addr,
|
||||
channel,
|
||||
e
|
||||
);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 500, "Channel Bind Failed");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
METHOD_SEND => {
|
||||
let allocation = match allocs.get_allocation(&peer) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
warn!("send indication without allocation from {}", peer);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let peer_attr = msg
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|a| a.typ == ATTR_XOR_PEER_ADDRESS);
|
||||
let data_attr = msg.attributes.iter().find(|a| a.typ == ATTR_DATA);
|
||||
let (peer_attr, data_attr) = match (peer_attr, data_attr) {
|
||||
(Some(p), Some(d)) => (p, d),
|
||||
_ => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Missing DATA or XOR-PEER-ADDRESS",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let peer_addr = match decode_xor_peer_address(
|
||||
&peer_attr.value,
|
||||
&msg.header.transaction_id,
|
||||
) {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
let resp = build_error_response(
|
||||
&msg.header,
|
||||
400,
|
||||
"Invalid XOR-PEER-ADDRESS",
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !allocation.is_peer_allowed(&peer_addr) {
|
||||
let resp = build_error_response(&msg.header, 403, "Peer Not Permitted");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
match allocation.send_to_peer(peer_addr, &data_attr.value).await {
|
||||
Ok(sent) => {
|
||||
tracing::info!(
|
||||
"forwarded {} bytes from {} to {}",
|
||||
sent,
|
||||
peer,
|
||||
peer_addr
|
||||
);
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"failed to send payload from {} to {}: {:?}",
|
||||
peer,
|
||||
peer_addr,
|
||||
e
|
||||
);
|
||||
let resp =
|
||||
build_error_response(&msg.header, 500, "Peer Send Failed");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
METHOD_REFRESH => {
|
||||
let requested = extract_lifetime_seconds(&msg)
|
||||
.map(|secs| Duration::from_secs(secs as u64));
|
||||
|
||||
match allocs.refresh_allocation(peer, requested) {
|
||||
Ok(applied) => {
|
||||
if applied.is_zero() {
|
||||
tracing::info!("allocation for {} released", peer);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"allocation for {} refreshed to {}s",
|
||||
peer,
|
||||
applied.as_secs()
|
||||
);
|
||||
}
|
||||
let resp = build_lifetime_success(
|
||||
&msg.header,
|
||||
applied.as_secs().min(u32::MAX as u64) as u32,
|
||||
);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
Err(_) => {
|
||||
let resp =
|
||||
build_error_response(&msg.header, 437, "Allocation Mismatch");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
let resp = build_error_response(&msg.header, 420, "Unknown TURN Method");
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match msg.header.msg_type {
|
||||
METHOD_BINDING => {
|
||||
let resp = build_success_response(&msg.header);
|
||||
let _ = udp.send_to(&resp, &peer).await;
|
||||
}
|
||||
_ => {
|
||||
let nonce = auth.mint_nonce(&peer);
|
||||
let resp =
|
||||
build_401_response(&msg.header, auth.realm(), &nonce, 401, "Unauthorized");
|
||||
if let Err(e) = udp.send_to(&resp, &peer).await {
|
||||
error!("failed to send 401: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::debug!("Non-STUN or parse error from {} len={}", peer, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
+605
-667
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user