Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion pkgs/id/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1270,7 +1270,7 @@ pub enum Command {
///
/// 0 = no crawl, 1 = query direct peers (default),
/// N = recursively query up to N levels deep.
#[arg(long, default_value = "1")]
#[arg(long, default_value = "1", allow_negative_numbers = true, value_parser = clap::value_parser!(i32).range(0..))]
depth: i32,
/// Maximum total peers to discover.
///
Expand Down Expand Up @@ -2936,6 +2936,30 @@ mod tests {
}
}

#[test]
fn test_cli_peers_depth_rejects_negative_and_preserves_non_negative_values() {
for argv in [
vec!["id", "peers", "--depth=-1"],
vec!["id", "peers", "--depth", "-1"],
] {
let err = Cli::try_parse_from(argv).unwrap_err();
assert!(
err.to_string().contains("depth"),
"error should name depth: {err}"
);
}

for depth in ["0", "1", "2"] {
let cli = Cli::try_parse_from(["id", "peers", "--depth", depth]).unwrap();
match cli.command {
Some(Command::Peers { depth: parsed, .. }) => {
assert_eq!(parsed, depth.parse::<i32>().unwrap());
}
_ => panic!("Expected Peers command"),
}
}
}

#[test]
fn test_cli_parse_peers_with_node() {
let node_id = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
Expand Down
28 changes: 23 additions & 5 deletions pkgs/id/src/commands/peers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ pub struct PeersOptions {
/// tab, CR, LF or other structure-breaking character is quoted and escaped by
/// [`plain_field`] instead of shifting a column or forging a row (#1613).
pub async fn cmd_peers(node: Option<String>, options: PeersOptions) -> Result<()> {
if options.depth < 0 {
bail!(
"peer crawl depth must be non-negative, got {}",
options.depth
);
}

let mut all_peers: HashMap<EndpointId, PeerAnnouncement> = HashMap::new();

// Determine mode
Expand Down Expand Up @@ -160,7 +167,7 @@ pub async fn cmd_peers(node: Option<String>, options: PeersOptions) -> Result<()
options.no_relay,
options.no_mdns,
)
.await;
.await?;
for peer in crawled {
all_peers.insert(peer.node_id, peer);
}
Expand Down Expand Up @@ -297,7 +304,11 @@ async fn crawl_peers(
timeout_secs: u64,
no_relay: bool,
no_mdns: bool,
) -> Vec<PeerAnnouncement> {
) -> Result<Vec<PeerAnnouncement>> {
if depth < 0 {
bail!("peer crawl depth must be non-negative, got {depth}");
}

let mut all_peers: HashMap<EndpointId, PeerAnnouncement> = HashMap::new();
let mut visited: HashSet<EndpointId> = HashSet::new();
let mut frontier: Vec<EndpointId> = Vec::new();
Expand All @@ -309,10 +320,9 @@ async fn crawl_peers(
}

let mut current_depth = 0;
let max_depth = if depth < 0 { i32::MAX } else { depth };
let timeout = tokio::time::Duration::from_secs(timeout_secs);

while current_depth < max_depth && !frontier.is_empty() {
while current_depth < depth && !frontier.is_empty() {
if all_peers.len() >= max_peers {
tracing::warn!(
"peers: max-peers cap ({}) reached at depth {}",
Expand Down Expand Up @@ -362,7 +372,7 @@ async fn crawl_peers(
current_depth += 1;
}

all_peers.into_values().collect()
Ok(all_peers.into_values().collect())
}

/// Discovers peers via gossip by joining the discovery topic.
Expand Down Expand Up @@ -486,6 +496,14 @@ mod tests {
use crate::discovery::PeerDiscovery;
use iroh_base::SecretKey;

#[tokio::test]
async fn crawl_peers_refuses_negative_depth_before_networking() {
let err = crawl_peers(&[], -1, 1000, 30, false, false)
.await
.unwrap_err();
assert!(err.to_string().contains("depth must be non-negative"));
}

fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
Expand Down
Loading