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 29, 2023
1 parent 495077f commit 7a67efa
Show file tree
Hide file tree
Showing 3 changed files with 39 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
16 changes: 12 additions & 4 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{
net::{IpAddr, SocketAddr},
time::Duration,
};
use anyhow::Context;
use tracing::info;

use openssl::{
Expand All @@ -23,6 +24,15 @@ impl Server {
Self(zt)
}

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

let tcp = TcpListener::bind(sa).await.with_context(|| "Failed to bind TCP port 53")?;
let udp = UdpSocket::bind(sa).await.with_context(|| "Failed to bind UDP port 53")?;

return Ok((tcp, udp));
}

// listener routine for TCP and UDP.
pub async fn listen(
self,
Expand All @@ -31,11 +41,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(e) => {
panic!("Could not bind port. {}", e);
}
};
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 7a67efa

Please sign in to comment.