use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::net::TcpStream;
use super::frames::{close_frame, write_all_frames};
use super::messages::build_error_json;
use super::pre_frame_text;
pub(super) async fn reject_ws_auth(sock: &mut TcpStream, code: &str, message: &str) {
use tokio::io::AsyncWriteExt;
let frames = std::collections::VecDeque::from([
pre_frame_text(&build_error_json(code, message)),
close_frame(4401, "Authentication failed"),
]);
let _ = tokio::time::timeout(
std::time::Duration::from_secs(1),
write_all_frames(sock, &frames),
)
.await;
let _ = sock.shutdown().await;
}
pub(crate) fn normalize_origin(origin: &str) -> Result<String, String> {
let invalid = || format!("allowed_origins: {origin:?} is not scheme://host[:port]");
let lowered = origin.trim().trim_end_matches('/').to_ascii_lowercase();
let Some((scheme, host)) = lowered.split_once("://") else {
return Err(invalid());
};
if scheme.is_empty() || host.is_empty() || host.contains(['/', '?', '#', '@', ' ']) {
return Err(invalid());
}
let default_port = match scheme {
"http" | "ws" => Some(":80"),
"https" | "wss" => Some(":443"),
_ => None,
};
let host = default_port
.and_then(|port| host.strip_suffix(port))
.unwrap_or(host);
Ok(format!("{scheme}://{host}"))
}
pub(super) const MAX_PENDING_HANDSHAKES: usize = 4096;
pub(super) const HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
pub(super) struct HandshakeGuard(Arc<AtomicUsize>);
impl HandshakeGuard {
pub(super) fn new(counter: Arc<AtomicUsize>) -> Self {
counter.fetch_add(1, Ordering::Relaxed);
Self(counter)
}
}
impl Drop for HandshakeGuard {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::Relaxed);
}
}