From 7d8df4ba9ee6667041ace5a6a40c8ea1b8796900 Mon Sep 17 00:00:00 2001 From: nibon7 Date: Sat, 2 Dec 2023 23:17:14 +0800 Subject: [PATCH] Fix capacity overflow caused by large range of ports (#11210) # Description Try to fix capacity overflow caused by large range of ports. ``` $ port 1024 999999999999999999 12/02/23 20:03:14 PM thread 'main' panicked at 'capacity overflow', library/alloc/src/raw_vec.rs:524:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` # User-Facing Changes # Tests + Formatting # After Submitting --- crates/nu-command/src/network/port.rs | 20 ++++++++++--------- .../nu-command/tests/commands/network/port.rs | 5 ++++- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/crates/nu-command/src/network/port.rs b/crates/nu-command/src/network/port.rs index 64df0047a8..5d0a53a4a4 100644 --- a/crates/nu-command/src/network/port.rs +++ b/crates/nu-command/src/network/port.rs @@ -101,15 +101,17 @@ fn get_free_port( } // try given port one by one. - let addrs: Vec = (start_port..=end_port) - .map(|current| { - SocketAddr::V4(SocketAddrV4::new( - Ipv4Addr::new(127, 0, 0, 1), - current as u16, - )) - }) - .collect(); - TcpListener::bind(addrs.as_slice())? + match (start_port..=end_port) + .map(|port| SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port as u16))) + .find_map(|addr| TcpListener::bind(addr).ok()) + { + Some(listener) => listener, + None => { + return Err(ShellError::IOError { + msg: "Every port has been tried, but no valid one was found".to_string(), + }) + } + } }; let free_port = listener.local_addr()?.port(); diff --git a/crates/nu-command/tests/commands/network/port.rs b/crates/nu-command/tests/commands/network/port.rs index f9c739a27d..d5921face4 100644 --- a/crates/nu-command/tests/commands/network/port.rs +++ b/crates/nu-command/tests/commands/network/port.rs @@ -30,7 +30,10 @@ fn port_with_already_usage() { handler.join().unwrap(); // check for error kind str. - if actual.err.contains("AddrInUse") { + if actual + .err + .contains("Every port has been tried, but no valid one was found") + { return; } }