use crate::libs::args::{Config, Family, Output, Padding}; use rand::{distributions::Alphanumeric, Rng}; use socket2::{Domain, Protocol, Socket, Type}; use std::{ io, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs, UdpSocket}, thread, time::{Duration, Instant}, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Version { V4, V6, } impl Version { fn request_type(self) -> u8 { match self { Self::V4 => 8, Self::V6 => 128, } } fn reply_type(self) -> u8 { match self { Self::V4 => 0, Self::V6 => 129, } } } pub fn generate_ping_request(config: Config) -> io::Result<()> { config.validate()?; let payload = config.payload_bytes()?; let size = config.packet_size(payload.len())?; let destination = if config.dry_run { // Dry runs do not perform DNS or create sockets. Literal addresses determine the family. config .dest_addr .parse::() .ok() .map(|ip| SocketAddr::new(ip, 0)) } else { Some(resolve_destination(&config)?) }; let version = match destination.map(|addr| addr.ip()) { Some(IpAddr::V4(_)) => Version::V4, Some(IpAddr::V6(_)) => Version::V6, None => match config.family { Family::V6 => Version::V6, _ => Version::V4, }, }; if matches!( (config.family, version), (Family::V4, Version::V6) | (Family::V6, Version::V4) ) { return Err(io::Error::new( io::ErrorKind::InvalidInput, "destination and --family disagree", )); } let ty = config.ping_type.unwrap_or(version.request_type()); if config.code != 0 && ty == version.request_type() { return Err(io::Error::new( io::ErrorKind::InvalidInput, "echo requests require code 0", )); } if !config.raw && !config.dry_run && (ty != version.request_type() || config.code != 0) { return Err(io::Error::new( io::ErrorKind::InvalidInput, "custom type or code requires --raw", )); } let socket = if config.dry_run { None } else { let socket = Socket::new( match version { Version::V4 => Domain::IPV4, Version::V6 => Domain::IPV6, }, if config.raw { Type::RAW } else { Type::DGRAM }, Some(match version { Version::V4 => Protocol::ICMPV4, Version::V6 => Protocol::ICMPV6, }), )?; if let Some(ttl) = config.ttl { match version { Version::V4 => socket.set_ttl_v4(u32::from(ttl))?, Version::V6 => socket.set_unicast_hops_v6(u32::from(ttl))?, } } let bind_addr = match version { Version::V4 => SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)), Version::V6 => SocketAddr::from((Ipv6Addr::UNSPECIFIED, 0)), }; socket.bind(&bind_addr.into())?; Some(UdpSocket::from(socket)) }; let mut results = Vec::new(); let run_start = Instant::now(); for index in 0..config.count { if index > 0 && !config.dry_run { let scheduled = run_start + Duration::from_millis(config.interval_ms).saturating_mul(index); if let Some(delay) = scheduled.checked_duration_since(Instant::now()) { thread::sleep(delay); } } let seq = config.sequence.wrapping_add(index as u16); let packet = create_buffer( ty, config.code, config.identifier, seq, &payload, size, config.padding, version, )?; let result = if let (Some(socket), Some(destination)) = (&socket, destination) { probe(socket, destination, &packet, seq, &config, version)? } else { ProbeResult::DryRun }; render_probe(&config, index, seq, &packet, &result); results.push(result); } render_summary(&config, &results); if results .iter() .all(|r| matches!(r, ProbeResult::Echo { .. } | ProbeResult::DryRun)) { Ok(()) } else { Err(io::Error::new( io::ErrorKind::Other, "one or more probes did not receive a matching reply", )) } } fn resolve_destination(config: &Config) -> io::Result { (config.dest_addr.as_str(), 0) .to_socket_addrs()? .find(|addr| match config.family { Family::Auto => true, Family::V4 => addr.is_ipv4(), Family::V6 => addr.is_ipv6(), }) .ok_or_else(|| { io::Error::new( io::ErrorKind::InvalidInput, "destination has no address in the requested family", ) }) } enum ProbeResult { DryRun, Echo { source: IpAddr, bytes: usize, elapsed: Duration, response: Vec, }, Error { source: IpAddr, ty: u8, code: u8, response: Vec, }, Timeout, } fn probe( socket: &UdpSocket, destination: SocketAddr, packet: &[u8], seq: u16, config: &Config, version: Version, ) -> io::Result { let start = Instant::now(); let sent = socket.send_to(packet, destination)?; if sent != packet.len() { return Err(io::Error::new( io::ErrorKind::WriteZero, "partial ICMP packet send", )); } let expected_id = if config.raw { config.identifier } else { socket.local_addr()?.port() }; let deadline = start + config.timeout(); let mut buf = vec![0; 65535]; loop { let Some(remaining) = deadline .checked_duration_since(Instant::now()) .filter(|d| !d.is_zero()) else { return Ok(ProbeResult::Timeout); }; socket.set_read_timeout(Some(remaining))?; let (length, source) = match socket.recv_from(&mut buf) { Ok(value) => value, Err(e) if matches!( e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut ) => { return Ok(ProbeResult::Timeout); } Err(e) => return Err(e), }; let Some(icmp) = received_icmp(&buf[..length], config.raw && version == Version::V4) else { continue; }; match classify_response( icmp, source.ip(), destination.ip(), expected_id, seq, &packet[8..], version, ) { Response::Ignore => continue, Response::Echo => { return Ok(ProbeResult::Echo { source: source.ip(), bytes: icmp.len(), elapsed: start.elapsed(), response: icmp.to_vec(), }); } Response::Error(ty, code) => { return Ok(ProbeResult::Error { source: source.ip(), ty, code, response: icmp.to_vec(), }); } } } } fn received_icmp(packet: &[u8], raw_ipv4: bool) -> Option<&[u8]> { if !raw_ipv4 { return (packet.len() >= 8).then_some(packet); } let first = *packet.first()?; let header_len = usize::from(first & 0x0f) * 4; if first >> 4 != 4 || header_len < 20 || packet.len() < header_len + 8 { return None; } Some(&packet[header_len..]) } enum Response { Ignore, Echo, Error(u8, u8), } fn classify_response( packet: &[u8], source: IpAddr, destination: IpAddr, id: u16, seq: u16, sent_payload: &[u8], version: Version, ) -> Response { if packet.len() < 8 { return Response::Ignore; } let ty = packet[0]; let code = packet[1]; let checksum_ok = version == Version::V6 || calculate_checksum(packet) == 0; if ty == version.reply_type() && code == 0 && source == destination && packet[4..6] == id.to_be_bytes() && packet[6..8] == seq.to_be_bytes() && packet[8..] == *sent_payload && checksum_ok { return Response::Echo; } let is_error = match version { Version::V4 => matches!(ty, 3 | 11 | 12), Version::V6 => matches!(ty, 1..=4), }; if is_error && checksum_ok && quoted_probe_matches(&packet[8..], destination, id, seq, version) { return Response::Error(ty, code); } Response::Ignore } fn quoted_probe_matches( quoted: &[u8], destination: IpAddr, id: u16, seq: u16, version: Version, ) -> bool { let embedded = match (version, destination) { (Version::V4, IpAddr::V4(ip)) if quoted.len() >= 28 && quoted[16..20] == ip.octets() => { received_icmp(quoted, true) } (Version::V6, IpAddr::V6(ip)) if quoted.len() >= 48 && quoted[0] >> 4 == 6 && quoted[24..40] == ip.octets() => { Some("ed[40..]) } _ => None, }; embedded.is_some_and(|p| { p.len() >= 8 && p[0] == version.request_type() && p[4..6] == id.to_be_bytes() && p[6..8] == seq.to_be_bytes() }) } #[allow(clippy::too_many_arguments)] fn create_buffer( ty: u8, code: u8, id: u16, seq: u16, payload: &[u8], size: usize, padding: Padding, version: Version, ) -> io::Result> { if !(8..=65515).contains(&size) || payload.len() > size - 8 { return Err(io::Error::new( io::ErrorKind::InvalidInput, "invalid packet size", )); } let mut buf = vec![0; size]; buf[0] = ty; buf[1] = code; buf[4..6].copy_from_slice(&id.to_be_bytes()); buf[6..8].copy_from_slice(&seq.to_be_bytes()); buf[8..8 + payload.len()].copy_from_slice(payload); if matches!(padding, Padding::Random) || (matches!(padding, Padding::Auto) && payload.is_empty()) { let mut rng = rand::thread_rng(); for byte in &mut buf[8 + payload.len()..] { *byte = rng.sample(Alphanumeric); } } if version == Version::V4 { let checksum = calculate_checksum(&buf); buf[2..4].copy_from_slice(&checksum.to_be_bytes()); } // Linux ICMPv6 sockets calculate the mandatory pseudo-header checksum. Ok(buf) } fn calculate_checksum(buf: &[u8]) -> u16 { let mut sum = 0u32; for chunk in buf.chunks(2) { sum += u32::from(u16::from_be_bytes([chunk[0], *chunk.get(1).unwrap_or(&0)])); } while sum >> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16); } !(sum as u16) } fn hex_bytes(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } fn json_string(value: &str) -> String { let mut out = String::from("\""); for ch in value.chars() { match ch { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), c if c <= '\u{001f}' => out.push_str(&format!("\\u{:04x}", c as u32)), c => out.push(c), } } out.push('"'); out } fn render_probe(config: &Config, index: u32, seq: u16, packet: &[u8], result: &ProbeResult) { match config.output { Output::Summary => println!("{}", probe_line(index, seq, result)), Output::Hex => { println!("[PROBE {}] sequence {}", index + 1, seq); print!( "{}", rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(packet) ); match result { ProbeResult::Echo { response, .. } | ProbeResult::Error { response, .. } => { print!( "{}", rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(response) ) } _ => {} } println!("{}", probe_line(index, seq, result)); } Output::Json => { let (status, source, elapsed, response, error) = match result { ProbeResult::DryRun => ("dry_run", None, None, None, None), ProbeResult::Timeout => ("timeout", None, None, None, None), ProbeResult::Echo { source, elapsed, response, .. } => ( "reply", Some(source.to_string()), Some(elapsed.as_secs_f64() * 1000.0), Some(hex_bytes(response)), None, ), ProbeResult::Error { source, ty, code, response, } => ( "icmp_error", Some(source.to_string()), None, Some(hex_bytes(response)), Some((*ty, *code)), ), }; println!( "{{\"kind\":\"probe\",\"index\":{},\"sequence\":{},\"status\":{},\"destination\":{},\"source\":{},\"elapsed_ms\":{},\"sent_hex\":{},\"received_hex\":{},\"icmp_type\":{},\"icmp_code\":{}}}", index + 1, seq, json_string(status), json_string(&config.dest_addr), source .as_deref() .map(json_string) .unwrap_or_else(|| "null".into()), elapsed .map(|ms| ms.to_string()) .unwrap_or_else(|| "null".into()), json_string(&hex_bytes(packet)), response .as_deref() .map(json_string) .unwrap_or_else(|| "null".into()), error .map(|e| e.0.to_string()) .unwrap_or_else(|| "null".into()), error .map(|e| e.1.to_string()) .unwrap_or_else(|| "null".into()) ); } } } fn probe_line(index: u32, seq: u16, result: &ProbeResult) -> String { match result { ProbeResult::DryRun => format!("probe {} seq={} dry run", index + 1, seq), ProbeResult::Timeout => format!("probe {} seq={} timed out", index + 1, seq), ProbeResult::Echo { source, bytes, elapsed, .. } => format!( "probe {} seq={} reply from {}: {} bytes in {:.2} ms", index + 1, seq, source, bytes, elapsed.as_secs_f64() * 1000.0 ), ProbeResult::Error { source, ty, code, .. } => format!( "probe {} seq={} ICMP error from {}: type {}, code {}", index + 1, seq, source, ty, code ), } } fn render_summary(config: &Config, results: &[ProbeResult]) { let sent = results.len(); let received = results .iter() .filter(|r| matches!(r, ProbeResult::Echo { .. })) .count(); let errors = results .iter() .filter(|r| matches!(r, ProbeResult::Error { .. })) .count(); let dry = results .iter() .filter(|r| matches!(r, ProbeResult::DryRun)) .count(); let rtts: Vec = results .iter() .filter_map(|r| { if let ProbeResult::Echo { elapsed, .. } = r { Some(elapsed.as_secs_f64() * 1000.0) } else { None } }) .collect(); let stats = if rtts.is_empty() { None } else { Some(( rtts.iter().copied().fold(f64::INFINITY, f64::min), rtts.iter().sum::() / rtts.len() as f64, rtts.iter().copied().fold(0.0, f64::max), )) }; match config.output { Output::Json => println!( "{{\"kind\":\"summary\",\"sent\":{sent},\"received\":{received},\"errors\":{errors},\"dry_run\":{dry},\"rtt_min_ms\":{},\"rtt_avg_ms\":{},\"rtt_max_ms\":{}}}", stats .map(|s| s.0.to_string()) .unwrap_or_else(|| "null".into()), stats .map(|s| s.1.to_string()) .unwrap_or_else(|| "null".into()), stats .map(|s| s.2.to_string()) .unwrap_or_else(|| "null".into()) ), _ => { println!("{sent} probes, {received} replies, {errors} ICMP errors, {dry} dry runs"); if let Some((min, avg, max)) = stats { println!("RTT min/avg/max = {min:.2}/{avg:.2}/{max:.2} ms"); } } } } #[cfg(test)] mod tests { use super::*; use std::net::IpAddr; #[test] fn checksum_and_exact_payload() { assert_eq!( calculate_checksum(&[0, 1, 0xf2, 3, 0xf4, 0xf5, 0xf6, 0xf7]), 0x220d ); let packet = create_buffer( 8, 0, 0x1234, 7, &[0, 0xff, 0x01], 11, Padding::None, Version::V4, ) .unwrap(); assert_eq!(&packet[8..], &[0, 0xff, 0x01]); assert_eq!(calculate_checksum(&packet), 0); } #[test] fn matches_only_the_sent_reply() { let destination: IpAddr = "127.0.0.1".parse().unwrap(); let mut reply = create_buffer(0, 0, 4, 9, b"abc", 11, Padding::None, Version::V4).unwrap(); assert!(matches!( classify_response(&reply, destination, destination, 4, 9, b"abc", Version::V4), Response::Echo )); assert!(matches!( classify_response(&reply, destination, destination, 4, 10, b"abc", Version::V4), Response::Ignore )); reply[8] = b'z'; assert!(matches!( classify_response(&reply, destination, destination, 4, 9, b"abc", Version::V4), Response::Ignore )); } #[test] fn malformed_raw_header_is_ignored() { assert!(received_icmp(&[], true).is_none()); assert!(received_icmp(&[0; 7], false).is_none()); } #[test] fn recognizes_quoted_probe_in_router_error() { let destination: IpAddr = "192.0.2.1".parse().unwrap(); let router: IpAddr = "192.0.2.254".parse().unwrap(); let mut error = vec![0u8; 8 + 20 + 8]; error[0] = 3; error[8] = 0x45; error[8 + 16..8 + 20].copy_from_slice(&[192, 0, 2, 1]); error[28] = 8; error[32..34].copy_from_slice(&4u16.to_be_bytes()); error[34..36].copy_from_slice(&9u16.to_be_bytes()); let checksum = calculate_checksum(&error); error[2..4].copy_from_slice(&checksum.to_be_bytes()); assert!(matches!( classify_response(&error, router, destination, 4, 9, &[], Version::V4), Response::Error(3, 0) )); assert!(matches!( classify_response(&error, router, destination, 4, 10, &[], Version::V4), Response::Ignore )); } #[test] fn ipv6_reply_and_quoted_error_match() { let destination: IpAddr = "2001:db8::1".parse().unwrap(); let router: IpAddr = "2001:db8::ff".parse().unwrap(); let reply = create_buffer(129, 0, 4, 9, b"abc", 11, Padding::None, Version::V6).unwrap(); assert!(matches!( classify_response(&reply, destination, destination, 4, 9, b"abc", Version::V6), Response::Echo )); assert!(matches!( classify_response(&reply, router, destination, 4, 9, b"abc", Version::V6), Response::Ignore )); let mut error = vec![0u8; 8 + 40 + 8]; error[0] = 1; error[8] = 0x60; error[8 + 24..8 + 40].copy_from_slice(&match destination { IpAddr::V6(ip) => ip.octets(), _ => unreachable!(), }); error[48] = 128; error[52..54].copy_from_slice(&4u16.to_be_bytes()); error[54..56].copy_from_slice(&9u16.to_be_bytes()); assert!(matches!( classify_response(&error, router, destination, 4, 9, b"abc", Version::V6), Response::Error(1, 0) )); } }