From 14cae83e1b74c954abf216b141bb49e70934538f Mon Sep 17 00:00:00 2001 From: darkfi Date: Sat, 8 Feb 2025 14:00:43 +0100 Subject: [PATCH] net: fix unwrap() crash where `listener.endpoint()` is called before `listener.listen()`. Technically should not be done, but API should not crash in this case. --- src/net/transport/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/net/transport/mod.rs b/src/net/transport/mod.rs index e47f44f3c..ce53f11b0 100644 --- a/src/net/transport/mod.rs +++ b/src/net/transport/mod.rs @@ -370,6 +370,7 @@ impl Listener { } } + /// Should only be called after `listen()` in order to behave correctly. pub async fn endpoint(&self) -> Url { match &self.variant { ListenerVariant::Tcp(listener) | ListenerVariant::TcpTls(listener) => { @@ -382,8 +383,10 @@ impl Listener { // `port == 0` means we got the OS to assign a random listen port to us. // Get the port from the listener and modify the endpoint. if port == 0 { - let actual_port = *listener.port.get().unwrap(); - endpoint.set_port(Some(actual_port)).unwrap(); + // Was `.listen()` called yet? Otherwise do nothing + if let Some(actual_port) = listener.port.get() { + endpoint.set_port(Some(*actual_port)).unwrap(); + } } endpoint