use anyhow::{Result, anyhow};
use std::io::ErrorKind;
use std::net::{IpAddr, SocketAddr};
use tokio::net::TcpListener;
pub(crate) const DEFAULT_PORT: u16 = 3030;
const PORTS_TO_TRY: u16 = 10;
pub(crate) async fn listen(host: IpAddr, port: Option<u16>) -> Result<TcpListener> {
if let Some(port) = port {
let address = SocketAddr::new(host, port);
return match TcpListener::bind(address).await {
Ok(listener) => Ok(listener),
Err(error) if error.kind() == ErrorKind::AddrInUse => {
Err(cannot_use(format!("port {port} is already in use")))
}
Err(error) if error.kind() == ErrorKind::PermissionDenied => Err(cannot_use(format!(
"the system will not give this program port {port}"
))),
Err(error) if error.kind() == ErrorKind::AddrNotAvailable => Err(no_such_address(host)),
Err(error) => Err(cannot_listen(address, &error)),
};
}
for port in DEFAULT_PORT..DEFAULT_PORT + PORTS_TO_TRY {
let address = SocketAddr::new(host, port);
match TcpListener::bind(address).await {
Ok(listener) => return Ok(listener),
Err(error) if is_taken(&error) => continue,
Err(error) if error.kind() == ErrorKind::AddrNotAvailable => {
return Err(no_such_address(host));
}
Err(error) => return Err(cannot_listen(address, &error)),
}
}
Err(cannot_use(format!(
"no free port between {DEFAULT_PORT} and {}",
DEFAULT_PORT + PORTS_TO_TRY - 1
)))
}
fn is_taken(error: &std::io::Error) -> bool {
matches!(
error.kind(),
ErrorKind::AddrInUse | ErrorKind::PermissionDenied
)
}
fn cannot_use(what: String) -> anyhow::Error {
anyhow!("{what} — choose another one with --port")
}
fn no_such_address(host: IpAddr) -> anyhow::Error {
anyhow!("this machine has no address {host} — check --host")
}
fn cannot_listen(address: SocketAddr, error: &std::io::Error) -> anyhow::Error {
anyhow!("cannot listen on {address}: {}", crate::errors::why(error))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_port_the_system_keeps_is_stepped_past_like_a_busy_one() {
assert!(is_taken(&ErrorKind::AddrInUse.into()));
assert!(is_taken(&ErrorKind::PermissionDenied.into()));
assert!(!is_taken(&ErrorKind::AddrNotAvailable.into()));
}
}