Files
2026-11-22 14:21:54 +01:00

85 lines
2.6 KiB
Rust

#![allow(dead_code, clippy::unwrap_used, clippy::expect_used)]
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use dns_config::{Config, Overrides};
use dns_core::client::{QueryOptions, query};
use dns_core::proto::op::Message;
use dns_core::proto::rr::{Name, RecordType};
use dns_server::{Server, ServerHandle};
pub fn tmpdir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("easydns-it-{tag}-{}-{}", std::process::id(), rand_u32()));
std::fs::create_dir_all(&d).unwrap();
d
}
pub fn rand_u32() -> u32 {
use std::time::{SystemTime, UNIX_EPOCH};
let n = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
n ^ (std::process::id() << 16)
}
pub fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
let p = dir.join(name);
std::fs::write(&p, text).unwrap();
p
}
pub async fn start(dir: &Path, yaml: &str) -> ServerHandle {
let path = write(dir, "config.yaml", yaml);
let cfg = Config::load(&path).unwrap();
Server::start(cfg, Some(path), Overrides::default()).await.unwrap()
}
pub fn n(s: &str) -> Name {
Name::from_ascii(s).unwrap()
}
pub async fn q(server: SocketAddr, name: &str, t: RecordType) -> Message {
q_opts(server, name, t, QueryOptions { timeout: Duration::from_secs(3), retries: 1, ..Default::default() }).await
}
pub async fn q_opts(server: SocketAddr, name: &str, t: RecordType, o: QueryOptions) -> Message {
query(server, &n(name), t, &o).await.unwrap_or_else(|e| panic!("query {name} {t} @{server}: {e}")).message
}
pub fn answers(m: &Message) -> Vec<String> {
let mut v: Vec<String> = m.answers.iter().map(|r| format!("{} {}", r.record_type(), r.data)).collect();
v.sort();
v
}
/// Poll until `f` returns true (max ~10 s).
pub async fn eventually<F, Fut>(what: &str, mut f: F)
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = bool>,
{
for _ in 0..200 {
if f().await {
return;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
panic!("timed out waiting for: {what}");
}
/// A random free port usable on several 127.0.0.x addresses.
pub fn free_port() -> u16 {
for _ in 0..50 {
let p = 20000 + (rand_u32() % 30000) as u16;
let ok = ["127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6"].iter().all(|ip| {
let a: SocketAddr = format!("{ip}:{p}").parse().unwrap();
std::net::UdpSocket::bind(a).is_ok() && std::net::TcpListener::bind(a).is_ok()
});
if ok {
return p;
}
}
panic!("no free port");
}
pub const KEY_B64: &str = "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0MTI=";