Skip to content

Commit 9a75376

Browse files
committed
Fail the app when binding to a port fails
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
1 parent 495077f commit 9a75376

File tree

3 files changed

+39
-10
lines changed

3 files changed

+39
-10
lines changed

src/init.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,17 @@ impl Launcher {
222222
None
223223
};
224224

225-
tokio::spawn(
226-
server
227-
.clone()
228-
.listen(ip, Duration::new(1, 0), tls_cert, chain, key),
229-
);
225+
let (tcp_socket, udp_socket) = Server::bind(ip).await?;
226+
227+
tokio::spawn(server.clone().listen(
228+
ip,
229+
Duration::new(1, 0),
230+
tls_cert,
231+
chain,
232+
key,
233+
tcp_socket,
234+
udp_socket,
235+
));
230236
}
231237

232238
return Ok(ztauthority);

src/server.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::{
22
net::{IpAddr, SocketAddr},
33
time::Duration,
44
};
5+
use anyhow::Context;
56
use tracing::info;
67

78
use openssl::{
@@ -23,6 +24,15 @@ impl Server {
2324
Self(zt)
2425
}
2526

27+
pub async fn bind(ip: IpAddr) -> Result<(TcpListener, UdpSocket), anyhow::Error> {
28+
let sa = SocketAddr::new(ip, 53);
29+
30+
let tcp = TcpListener::bind(sa).await.with_context(|| "Failed to bind TCP port 53")?;
31+
let udp = UdpSocket::bind(sa).await.with_context(|| "Failed to bind UDP port 53")?;
32+
33+
return Ok((tcp, udp));
34+
}
35+
2636
// listener routine for TCP and UDP.
2737
pub async fn listen(
2838
self,
@@ -31,11 +41,9 @@ impl Server {
3141
certs: Option<X509>,
3242
cert_chain: Option<Stack<X509>>,
3343
key: Option<PKey<Private>>,
44+
tcp: TcpListener,
45+
udp: UdpSocket,
3446
) -> Result<(), anyhow::Error> {
35-
let sa = SocketAddr::new(ip, 53);
36-
let tcp = TcpListener::bind(sa).await?;
37-
let udp = UdpSocket::bind(sa).await?;
38-
3947
let mut sf = ServerFuture::new(init_catalog(self.0).await?);
4048

4149
if let (Some(certs), Some(key)) = (certs.clone(), key.clone()) {

tests/service/mod.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,23 @@ impl Service {
239239

240240
for ip in listen_ips.clone() {
241241
let server = Server::new(ztauthority.to_owned());
242+
243+
let (tcp_socket, udp_socket) = match Server::bind(ip.ip()).await {
244+
Ok(x) => x,
245+
Err(_) => {
246+
panic!("Could not bind port");
247+
}
248+
};
242249
info!("Serving {}", ip.clone());
243-
tokio::spawn(server.listen(ip.ip(), Duration::new(1, 0), None, None, None));
250+
tokio::spawn(server.listen(
251+
ip.ip(),
252+
Duration::new(1, 0),
253+
None,
254+
None,
255+
None,
256+
tcp_socket,
257+
udp_socket,
258+
));
244259
}
245260

246261
listen_ips

0 commit comments

Comments
 (0)