azalea_protocol/
resolver.rsuse std::net::{IpAddr, SocketAddr};
use async_recursion::async_recursion;
use thiserror::Error;
use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts},
Name, TokioAsyncResolver,
};
use crate::ServerAddress;
#[derive(Error, Debug)]
pub enum ResolverError {
#[error("No SRV record found")]
NoSrvRecord,
#[error("No IP found")]
NoIp,
}
#[must_use]
#[async_recursion]
pub async fn resolve_address(address: &ServerAddress) -> Result<SocketAddr, ResolverError> {
if let Ok(ip) = address.host.parse::<IpAddr>() {
return Ok(SocketAddr::new(ip, address.port));
}
let resolver = TokioAsyncResolver::tokio(ResolverConfig::cloudflare(), ResolverOpts::default());
let srv_redirect_result = resolver
.srv_lookup(format!("_minecraft._tcp.{}", address.host).as_str())
.await;
if let Ok(redirect_result) = srv_redirect_result {
let redirect_srv = redirect_result
.iter()
.next()
.ok_or(ResolverError::NoSrvRecord)?;
let redirect_address = ServerAddress {
host: redirect_srv.target().to_ascii(),
port: redirect_srv.port(),
};
if redirect_address.host == address.host {
let lookup_ip_result = resolver.lookup_ip(redirect_address.host).await;
let lookup_ip = lookup_ip_result.map_err(|_| ResolverError::NoIp)?;
return Ok(SocketAddr::new(
lookup_ip.iter().next().unwrap(),
redirect_address.port,
));
}
return resolve_address(&redirect_address).await;
}
let name = Name::from_ascii(&address.host).map_err(|_| ResolverError::NoIp)?;
let lookup_ip_result = resolver.lookup_ip(name).await;
let lookup_ip = lookup_ip_result.map_err(|_| ResolverError::NoIp)?;
Ok(SocketAddr::new(
lookup_ip.iter().next().unwrap(),
address.port,
))
}