Skip to content

Commit

Permalink
Fail the app when binding to a port fails
Browse files Browse the repository at this point in the history
tokio is was eating the panics and continuing on
with no socket listening on 53

making tokio crash would take a bunch of rewrite
i think, so i moved the `bind` calls out to a different,
non-async fn
  • Loading branch information
laduke committed Mar 28, 2023
1 parent 495077f commit 7c59e43
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 10 deletions.
16 changes: 11 additions & 5 deletions src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,17 @@ impl Launcher {
None
};

tokio::spawn(
server
.clone()
.listen(ip, Duration::new(1, 0), tls_cert, chain, key),
);
let (tcp_socket, udp_socket) = Server::bind(ip).await?;

tokio::spawn(server.clone().listen(
ip,
Duration::new(1, 0),
tls_cert,
chain,
key,
tcp_socket,
udp_socket,
));
}

return Ok(ztauthority);
Expand Down
22 changes: 18 additions & 4 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,22 @@ impl Server {
Self(zt)
}

pub async fn bind(ip: IpAddr) -> Result<(TcpListener, UdpSocket), anyhow::Error> {
let sa = SocketAddr::new(ip, 53);

let tcp = match TcpListener::bind(sa).await {
Ok(x) => x,
Err(_) => panic!("Could not bind TCP port 53. Are you root?"),
};

let udp = match UdpSocket::bind(sa).await {
Ok(x) => x,
Err(_) => panic!("Could not bind UDP port 53. Are you root?"),
};

return Ok((tcp, udp));
}

// listener routine for TCP and UDP.
pub async fn listen(
self,
Expand All @@ -31,11 +47,9 @@ impl Server {
certs: Option<X509>,
cert_chain: Option<Stack<X509>>,
key: Option<PKey<Private>>,
tcp: TcpListener,
udp: UdpSocket,
) -> Result<(), anyhow::Error> {
let sa = SocketAddr::new(ip, 53);
let tcp = TcpListener::bind(sa).await?;
let udp = UdpSocket::bind(sa).await?;

let mut sf = ServerFuture::new(init_catalog(self.0).await?);

if let (Some(certs), Some(key)) = (certs.clone(), key.clone()) {
Expand Down
17 changes: 16 additions & 1 deletion tests/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,23 @@ impl Service {

for ip in listen_ips.clone() {
let server = Server::new(ztauthority.to_owned());

let (tcp_socket, udp_socket) = match Server::bind(ip.ip()).await {
Ok(x) => x,
Err(_) => {
panic!("Could not bind port");
}
};
info!("Serving {}", ip.clone());
tokio::spawn(server.listen(ip.ip(), Duration::new(1, 0), None, None, None));
tokio::spawn(server.listen(
ip.ip(),
Duration::new(1, 0),
None,
None,
None,
tcp_socket,
udp_socket,
));
}

listen_ips
Expand Down

0 comments on commit 7c59e43

Please sign in to comment.