diff --git a/.gitignore b/.gitignore
index 3ca43ae..698065d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,10 +4,6 @@
debug/
target/
-# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
-# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
-Cargo.lock
-
# These are backup files generated by rustfmt
**/*.rs.bk
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..5d7aca7
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,272 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "rand_core",
+]
+
+[[package]]
+name = "clap"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
+dependencies = [
+ "chacha20",
+ "getrandom",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rhexdump"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a92cbe1a3dd221e3777fef339115d3b85e17a538668e03a0f3ae9c6a98351c7"
+
+[[package]]
+name = "rping"
+version = "0.1.0"
+dependencies = [
+ "clap",
+ "rand",
+ "rhexdump",
+ "socket2",
+]
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "syn"
+version = "3.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
diff --git a/Cargo.toml b/Cargo.toml
index 515ed22..89a61ed 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,18 +1,18 @@
[package]
name = "rping"
version = "0.1.0"
-edition = "2021"
-
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+edition = "2024"
+rust-version = "1.98"
+description = "A small IPv4 ICMP ping utility"
+license = "MIT"
[dependencies]
-socket2 = { version = "0.4.7", features = ["all"] }
-env_logger = "0.10"
-rhexdump = "0.1.1"
-rand = "0.8.5"
-#dns-lookup = "1.0.8"
+clap = { version = "4.6", features = ["derive"] }
+socket2 = { version = "0.6", features = ["all"] }
+rhexdump = "0.2"
+rand = "0.10"
[profile.release]
-strip = true # Automatically strip symbols from the binary.
+strip = true
opt-level = "z"
-lto = true
\ No newline at end of file
+lto = true
diff --git a/Jenkinsfile b/Jenkinsfile
index 87c8f30..9e32cd6 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -11,6 +11,7 @@ pipeline {
agent { label 'rust_nodocker' }
options {
+ skipDefaultCheckout(true)
timestamps()
disableConcurrentBuilds()
}
@@ -44,19 +45,9 @@ pipeline {
exit 1
fi
- if [ -f rust-toolchain.toml ] || [ -f rust-toolchain ]; then
- echo "Using repository-pinned Rust toolchain."
- rustup show active-toolchain
-
- TOOLCHAIN="$(rustup show active-toolchain | awk '{print $1}')"
- rustup component add rustfmt clippy --toolchain "$TOOLCHAIN"
- else
- rustup toolchain install stable \
- --profile minimal \
- --component rustfmt \
- --component clippy
- rustup default stable
- fi
+ # rustup installs the version and components from rust-toolchain.toml.
+ # Do not change the shared worker's default toolchain.
+ rustup show active-toolchain
rustc --version
cargo --version
@@ -77,7 +68,7 @@ pipeline {
steps {
sh '''
set -eu
- cargo check --all-targets --all-features
+ cargo check --locked --all-targets --all-features
'''
}
}
@@ -86,7 +77,7 @@ pipeline {
steps {
sh '''
set -eu
- cargo test --all-targets --all-features
+ cargo test --locked --all-targets --all-features
'''
}
}
@@ -95,7 +86,7 @@ pipeline {
steps {
sh '''
set -eu
- cargo clippy --all-targets --all-features
+ cargo clippy --locked --all-targets --all-features -- -D warnings
'''
}
}
@@ -104,7 +95,7 @@ pipeline {
steps {
sh '''
set -eu
- cargo build --release --all-features
+ cargo build --locked --release --all-features
test -x target/release/rping
'''
}
@@ -142,4 +133,4 @@ pipeline {
)
}
}
-}
\ No newline at end of file
+}
diff --git a/README.md b/README.md
index a404299..5676198 100644
--- a/README.md
+++ b/README.md
@@ -1,29 +1,62 @@
# rping
-rping is a simple implementation of the Internet Control Message Protocol (ICMP) ping utility. It sends a ping request to a specified IP address and prints the response time if a reply is received.
+A small IPv4 ICMP ping utility. It sends one packet, waits up to one second for a response, and prints the packet bytes, ICMP fields, and elapsed time.
+
+## Build
+
+Install [Rust with rustup](https://www.rust-lang.org/tools/install), then run:
+
+```sh
+cargo build --locked --release
+```
+
+The repository pins Rust 1.98.1 and uses the Rust 2024 edition. Rustup installs the required toolchain automatically. Dependencies are recorded in `Cargo.lock`.
+
+Linux is the primary runtime target. The default mode uses an ICMP datagram socket; your system must permit ping sockets for your user (on Linux, through `net.ipv4.ping_group_range`). Raw mode requires root or `CAP_NET_RAW`. IPv6 is not supported.
## Usage
-
-To use rping, run the following command:
+```sh
+rping [OPTIONS]
+```
-```cargo run --dest [--request/-r ] [--data/-d ] [--payload/-p ]```
+Use an IPv4 address or a hostname with an IPv4 address. When running from the checkout, use `cargo run --` or `./target/release/rping`:
+```sh
+cargo run -- 127.0.0.1
+cargo run -- 127.0.0.1 --payload "hello world" --size 64
+./target/release/rping 127.0.0.1 --identifier 4660 --sequence 1
+sudo ./target/release/rping 127.0.0.1 --raw
+cargo run -- --help
+```
-The `--dest` argument is required and specifies the destination IP address to send the ping request to. The `--request`, `--data`, and `--payload` arguments are optional and allow you to specify the ping request, data, and payload values, respectively. If these arguments are not provided, default values will be used.
+| Option | Meaning | Default |
+| --- | --- | --- |
+| `-t, --type ` | ICMP type, as a decimal byte; 8 is an echo request | `8` |
+| `-i, --identifier ` | Decimal 16-bit identifier | `16962` (`0x4242`) |
+| `-q, --sequence ` | Decimal 16-bit sequence number | `16962` (`0x4242`) |
+| `-p, --payload ` | UTF-8 text; remaining space is zero-filled | Random alphanumeric bytes |
+| `-s, --size ` | Total ICMP size, including the 8-byte header; 8–65515 bytes | `64` |
+| `--raw` | Use a raw ICMP socket | Off |
+| `-h, --help` | Show usage and options | |
+| `-V, --version` | Show version | |
-## Example
+The payload must fit within `--size` minus 8 bytes; text is measured in UTF-8 bytes. An empty payload generates random data. The ICMP code is always zero. The OS may replace the identifier and checksum in datagram mode. Large packets may exceed the network's MTU.
-To send a ping request to the IP address `192.0.2.1` with the default values, run the following command:
+The destination is positional. Older README examples using `--dest`, `--request`, or `--data` were incorrect; these are not supported options. Invalid arguments, socket errors, and timeouts return a nonzero exit status.
-```cargo run --dest 192.0.2.1```
+## Development and CI
+```sh
+cargo fmt --all -- --check
+cargo check --locked --all-targets --all-features
+cargo test --locked --all-targets --all-features
+cargo clippy --locked --all-targets --all-features -- -D warnings
+cargo build --locked --release --all-features
+```
-To send a ping request to the same IP address with a custom ping request, data, and payload value, run the following command:
-
- ```cargo run --dest 192.0.2.1 --request 0x1234 --data 0x5678 --payload "hello world"```
-
+The Jenkins pipeline runs these checks on a `rust_nodocker` worker with rustup installed and access to the Rust distribution server and crates.io. It uses the repository's toolchain without changing the worker's default. The existing `publishChecks` step requires the Jenkins Checks API plugin and a configured SCM checks publisher. Tests do not require network access or elevated socket privileges; CI does not run live pings.
## License
-This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
+[MIT](LICENSE).
diff --git a/libc.rs b/libc.rs
deleted file mode 100644
index a5dd50f..0000000
--- a/libc.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-extern crate libc;
-
-use std::net::Ipv4Addr;
-use std::mem;
-use std::slice;
-
-use libc::{c_int, c_void, sockaddr_in, in_addr, htons, inet_pton};
-
-const IHL_MASK: u8 = 0x0F; // The mask for the IHL field
-const IHL_SHIFT: u8 = 4; // The number of bits to shift the IHL value
-
-fn main() {
- // Create the raw socket
- let socket_fd = unsafe {
- socket(AF_INET, SOCK_RAW, libc::IPPROTO_RAW)
- };
-
- if socket_fd < 0 {
- // Handle the error
- } else {
- // Construct the packet
- let mut packet: [u8; 40] = [0; 40]; // 40 bytes for a header with IHL=10
-
- // Set the IHL field
- let ihl = 10;
- packet[0] |= (ihl << IHL_SHIFT) & IHL_MASK;
-
- // Set the other fields in the header as needed...
-
- // Create the sockaddr_in structure to specify the destination
- let mut addr: sockaddr_in = mem::zeroed();
- addr.sin_family = AF_INET as u16;
- addr.sin_port = htons(0); // Set the port to 0
-
- // Set the destination IP address
- let ip_str = "192.0.2.1";
- let ip = Ipv4Addr::from_str(ip_str).unwrap();
- let in_addr = in_addr { s_addr: u32::from(ip) };
- inet_pton(AF_INET, &in_addr as *const in_addr as *const c_void, &mut addr.sin_addr as *mut sockaddr_in as *mut c_void);
-
- // Send the packet
- let send_result = unsafe {
- libc::sendto(
- socket_fd,
- packet.as_ptr() as *const c_void,
- packet.len() as u64,
- 0,
- // Send the packet
- let send_result = unsafe {
- libc::sendto(
- socket_fd,
- packet.as_ptr() as *const c_void,
- packet.len() as u64,
- 0,
- &addr as *const sockaddr_in as *const libc::sockaddr,
- mem::size_of::() as u32,
- )
-};
-
-if send_result < 0 {
- // Handle the error
-} else {
- // The packet was sent successfully
-}
diff --git a/rust-toolchain.toml b/rust-toolchain.toml
new file mode 100644
index 0000000..c3f67b6
--- /dev/null
+++ b/rust-toolchain.toml
@@ -0,0 +1,4 @@
+[toolchain]
+channel = "1.98.1"
+profile = "minimal"
+components = ["rustfmt", "clippy"]
diff --git a/src/libs.rs b/src/libs.rs
index bac686e..fca83b5 100644
--- a/src/libs.rs
+++ b/src/libs.rs
@@ -1,7 +1,5 @@
-mod icmp;
mod args;
+mod icmp;
-pub use icmp::{
- generate_ping_request
-};
-pub use args::parse_all_arguments;
\ No newline at end of file
+pub use args::parse_all_arguments;
+pub use icmp::generate_ping_request;
diff --git a/src/libs/args.rs b/src/libs/args.rs
index a28778d..8501ceb 100644
--- a/src/libs/args.rs
+++ b/src/libs/args.rs
@@ -1,62 +1,93 @@
-use std::env;
+use clap::{CommandFactory, Parser, error::ErrorKind};
-pub struct Config{
- pub dest_addr : String,
- pub ping_type : u8,
- pub identifier : u16,
- pub sequence : u16,
- pub payload : Vec,
- pub payload_size : usize,
- pub raw_packet : bool,
+#[derive(Debug, Parser)]
+#[command(version, about, arg_required_else_help = true)]
+pub struct Config {
+ /// Destination IPv4 address or hostname
+ #[arg(value_name = "DESTINATION")]
+ pub dest_addr: String,
+ /// ICMP type (8 is an echo request); code is always 0
+ #[arg(short = 't', long = "type", default_value_t = 8)]
+ pub ping_type: u8,
+ /// ICMP identifier (decimal; the OS may replace it in datagram mode)
+ #[arg(short = 'i', long, default_value_t = 16962)]
+ pub identifier: u16,
+ /// ICMP sequence number (decimal)
+ #[arg(short = 'q', long, default_value_t = 16962)]
+ pub sequence: u16,
+ /// UTF-8 payload; unused space is zero-filled
+ #[arg(short = 'p', long)]
+ pub payload: Option,
+ /// Total ICMP packet size in bytes, including the 8-byte header
+ #[arg(short = 's', long = "size", default_value = "64", value_parser = parse_size)]
+ pub payload_size: usize,
+ /// Use a raw ICMP socket (requires root or CAP_NET_RAW on Linux)
+ #[arg(long = "raw")]
+ pub raw_packet: bool,
+}
+
+fn parse_size(value: &str) -> Result {
+ let size = value
+ .parse::()
+ .map_err(|_| "expected a byte count")?;
+ if !(8..=65515).contains(&size) {
+ return Err("size must be between 8 and 65515 bytes".into());
+ }
+ Ok(size)
}
pub fn parse_all_arguments() -> Config {
- // Load all inline arguments and create a config structure
-
- let args: Vec = env::args().collect();
- let mut config = Config {
- dest_addr : String::new(),
- ping_type : 0x08,
- identifier : 0x4242,
- sequence : 0x4242,
- payload: Vec::::new(),
- payload_size : 64,
- raw_packet: false,
- };
- if args.len() == 1 {
- exit_with_help();
- }
-
- config.dest_addr= args[1].clone();
- for (i,arg) in args[1..].iter().enumerate(){
- if arg == "--help" || arg == "-h" {
- exit_with_help();
- } else if arg == "--type" || arg == "-t" {
- config.ping_type = args[i + 2].parse::().unwrap();
- } else if arg == "--identifier" || arg == "-i" {
- config.identifier = args[i + 2].parse::().unwrap();
- } else if arg == "--sequence" || arg == "-q" {
- config.sequence = args[i + 2].parse::().unwrap();
- } else if arg == "--payload" || arg == "-p" {
- config.payload = args[i + 2].as_bytes().to_vec();
- } else if arg == "--size" || arg == "-s" {
- config.payload_size = args[i + 2].parse::().unwrap();
- } else if arg =="--raw" {
- config.raw_packet=true; // This enable raw packets but requires root privilege
- }
+ let config = Config::parse();
+ if config
+ .payload
+ .as_ref()
+ .is_some_and(|p| p.len() > config.payload_size - 8)
+ {
+ Config::command()
+ .error(
+ ErrorKind::ValueValidation,
+ "payload exceeds --size minus the 8-byte ICMP header",
+ )
+ .exit();
}
config
}
-fn exit_with_help() {
- eprintln!("Usage: cargo run --dest
- [--type/-t ] The type of ping request 8 for IPv4 128 for IPv6 (8b)
- [--code/-c ] The mandatory 0 code (8b)
- [--identifier/-i ] The Header identifier (16b)
- [--sequence/-q ] The Sequence number (16b)
- [--payload/-p ] The Payload, generated randomly if not given (any)
- [--size/-s ] The Payload size (any) but smaller than ???
- [--raw] Enable raw packet, require root privileges
- ");
- std::process::exit(1);
-}
\ No newline at end of file
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_existing_options_in_any_order() {
+ let config = Config::try_parse_from([
+ "rping",
+ "--raw",
+ "-s",
+ "16",
+ "localhost",
+ "-p",
+ "hello",
+ "-q",
+ "7",
+ ])
+ .unwrap();
+ assert!(config.raw_packet);
+ assert_eq!(config.dest_addr, "localhost");
+ assert_eq!(config.sequence, 7);
+ assert_eq!(config.payload_size, 16);
+ }
+
+ #[test]
+ fn rejects_invalid_input_without_panicking() {
+ for args in [
+ vec!["rping"],
+ vec!["rping", "localhost", "--size", "7"],
+ vec!["rping", "localhost", "--size", "65516"],
+ vec!["rping", "localhost", "--type", "256"],
+ vec!["rping", "localhost", "--sequence"],
+ vec!["rping", "localhost", "--unknown"],
+ ] {
+ assert!(Config::try_parse_from(args).is_err());
+ }
+ }
+}
diff --git a/src/libs/icmp.rs b/src/libs/icmp.rs
index 060552e..746102b 100644
--- a/src/libs/icmp.rs
+++ b/src/libs/icmp.rs
@@ -1,197 +1,152 @@
use crate::libs::args::Config;
-use core::time::Duration;
-use rand::{
- Rng,
- thread_rng,
- distributions::Alphanumeric,
-};
-use std::time::Instant;
-
+use rand::{RngExt, distr::Alphanumeric};
+use socket2::{Domain, Protocol, Socket, Type};
use std::{
- io::{self},
- net,
- net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs},
-};
-use std::os::{
- unix::io::AsRawFd,
- unix::io::FromRawFd
+ io,
+ net::{Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket},
+ time::{Duration, Instant},
};
-
-struct SocketAddresses{
- socket1_addr: net::SocketAddr,
- socket2_addr: socket2::SockAddr,
- dest_addr: net::SocketAddr,
-}
-//use env_logger::Env;
-pub fn generate_ping_request(config : crate::libs::args::Config) -> Result<(),()>{
-
- let addr = create_addresses(&config.dest_addr);
- let mut socket2_ipv4_socket=create_sockets(addr.socket1_addr, addr.socket2_addr);
- let socket_final = match config.raw_packet{
- true => create_socket_raw(&config, &mut socket2_ipv4_socket),
- false => create_socket_udp(&mut socket2_ipv4_socket),
- };
-
+pub fn generate_ping_request(config: Config) -> io::Result<()> {
+ let dest_addr = (config.dest_addr.as_str(), 0)
+ .to_socket_addrs()?
+ .find(SocketAddr::is_ipv4)
+ .ok_or_else(|| {
+ io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "destination has no IPv4 address",
+ )
+ })?;
let (buffer, checksum) = create_buffer(
config.ping_type,
- config.identifier,
- config.sequence,
- config.payload,
- config.payload_size
- );
-
- // Send the ping request to the specified destination IP address.
- print_send_pre_message(checksum, &buffer);
-
- // Starting the timer
- let now = Instant::now();
- let result = socket_final.send_to(&buffer, addr.dest_addr);
- // let result = socket_arc.send_to_with_flags(&buffer, dest_addr, 0);
-
- match result {
- Ok(bytes) => print_send_post_messages(bytes, addr.dest_addr, checksum),
- Err(err) => println!(" [ERROR] Failed to send data over the socket: {}", err)
- }
-
- // Wait for a response from the destination.
- let mut buf = vec![0; config.payload_size]; // Make that buffer arbitrary large
- let timeout = std::time::Duration::from_secs(1);
-
-
- socket_final.set_read_timeout(Some(timeout)).unwrap();
- let (bytes_recv, _src_addr) = match socket_final.recv_from(&mut buf) {
- Ok(res) => res,
- Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => {
- println!(" [ERROR] No response from destination");
- println!(" [ERROR] {:?}", err);
- std::process::exit(0);
- }
- Err(err) => panic!(" [ERROR] Error receiving data: {}", err),
- };
- let elapsed = now.elapsed();
-
- print_recv_post_message(&buf, bytes_recv, elapsed);
- Ok(())
-}
-
-fn create_addresses(dest_ip: &String) -> SocketAddresses{
- // SOURCE IP ADDRESS
- let localhost = Ipv4Addr::UNSPECIFIED;
- let socket1_addr = SocketAddr::new(IpAddr::V4(localhost), 80);
- let socket2_addr = socket1_addr.into();
-
- let dest_addr = ((*dest_ip).clone(),0).to_socket_addrs().unwrap().next().unwrap();
- SocketAddresses {socket1_addr, socket2_addr, dest_addr}
-}
-
-fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::SockAddr) -> socket2::Socket {
- let socket2_ipv4_socket = socket2::Socket::new(
- socket2::Domain::IPV4,
- socket2::Type::DGRAM,
- Some(socket2::Protocol::ICMPV4),
- ).unwrap();
-
- // BIND TO LOCAL ADDRESS
- socket2_ipv4_socket
- .bind(&socket2_ip_address)
- .expect(&format!(
- "Failed binding to Ipv4 address {:?}",
- &socket_ip_address
- ));
-
- socket2_ipv4_socket
-}
-
-fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> std::net::UdpSocket/*socket2::Socket,std::net::UdpSocketArc*/ {
- // CREATE STD SOCKET FROM SOCKET2 SOCKET
- let raw_ipv4_socket = socket2_ipv4_socket.as_raw_fd();
- let std_ipv4_socket = unsafe { std::net::UdpSocket::from_raw_fd(raw_ipv4_socket) };
-
- std_ipv4_socket
- .set_read_timeout(Some(Duration::from_millis(100)))
- .expect(&format!("Failed to set read timeout"));
- *Box::new(std_ipv4_socket)
- //Arc::new(std_ipv4_socket)
-}
-
-fn create_socket_raw(config: &Config, _socket2_ipv4_socket: &mut socket2::Socket) -> std::net::UdpSocket /*socket2::Socket*/{
- let socket = match socket2::Socket::new_raw(
- socket2::Domain::IPV4,
- socket2::Type::RAW,
- Some(socket2::Protocol::ICMPV4)
- ){
- Err(error) => match error.kind() {
- std::io::ErrorKind::PermissionDenied => {
- println!("[ERROR] Raw socket require root privilege on your OS");
- std::process::exit(1);
- },
- _ => panic!("Couldn't create raw socket {:?} ",error)
+ config.identifier,
+ config.sequence,
+ config.payload.as_deref().unwrap_or_default().as_bytes(),
+ config.payload_size,
+ )?;
+ let socket = Socket::new(
+ Domain::IPV4,
+ if config.raw_packet {
+ Type::RAW
+ } else {
+ Type::DGRAM
},
- Ok(res) => res,
- };
- if config.raw_packet { match socket.set_header_included(true){
- Err(e) => panic!("Can't setup a raw packet via Socket2 options {}",e),
- _ => (),}};
- socket.set_read_timeout(Some(Duration::from_millis(100)))
- .expect(&format!("Failed to set read timeout"));
- //Into::::into(socket);
- std::net::UdpSocket::from(socket)
-}
-
-fn create_buffer(ping_type: u8, identifier: u16, sequence: u16, mut payload: Vec, payload_size : usize) -> (Vec,u16){
- // Create the ping request message.
- let mut buf = vec![0u8; payload_size];
- let header = [
- ping_type, 0x00, // Type and Code=0 fields
- 0x00, 0x00, // Checksum (filled in later)
- 0x00, 0x00, 0x00, 0x00, // Identifier and Sequence Number fields
- ];
- buf[..header.len()].copy_from_slice(&header);
-
- // Add the data to the ping request message.
- let header = [
- (identifier >> 8) as u8, (identifier & 0xff) as u8,
- (sequence >> 8) as u8, (sequence & 0xff) as u8,
- ];
-
- if payload.len() == 0{
- generate_payload(&mut payload, payload_size);
- }
- buf[header.len()..(header.len() + header.len())].copy_from_slice(&header);
- buf[header.len() + header.len()..(header.len() + header.len()+payload.len())].copy_from_slice(&payload);
-
- // Calculate the checksum of the ping request message.
- let checksum = calculate_checksum(&buf);
- buf[2] = (checksum >> 8) as u8;
- buf[3] = (checksum & 0xff) as u8;
- (buf, checksum)
-}
-
-fn calculate_checksum(buf : &Vec) -> u16 {
- let checksum = {
- let mut sum = 0;
- for i in 0..(buf.len() / 2) {
- sum += (buf[2 * i+1 ] as usize) << 8 | buf[2 * i] as usize;
+ Some(Protocol::ICMPV4),
+ )?;
+ // The kernel supplies the IPv4 header, including in raw mode.
+ socket.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)).into())?;
+ socket.set_read_timeout(Some(Duration::from_secs(1)))?;
+ // Transfer ownership instead of creating two owners of the same descriptor.
+ let socket: UdpSocket = socket.into();
+ print_send_pre_message(checksum, &buffer);
+ let now = Instant::now();
+ let bytes = socket.send_to(&buffer, dest_addr)?;
+ print_send_post_messages(bytes, dest_addr, checksum);
+ let mut buf = vec![0; 65535];
+ loop {
+ let remaining = Duration::from_secs(1)
+ .checked_sub(now.elapsed())
+ .filter(|duration| !duration.is_zero())
+ .ok_or_else(|| {
+ io::Error::new(io::ErrorKind::TimedOut, "no response from destination")
+ })?;
+ socket.set_read_timeout(Some(remaining))?;
+ let (bytes_recv, source) = socket.recv_from(&mut buf)?;
+ let packet = received_icmp(&buf[..bytes_recv], config.raw_packet)?;
+ // Raw sockets also receive the outgoing echo request on loopback.
+ if config.raw_packet && packet[0] == 8 {
+ continue;
}
- if buf.len()%2==1 { sum += buf[buf.len()-1] as usize; }
- while sum>>16!=0 { sum = (sum & 0xffff) + (sum >> 16) }
- !(sum as u16)
- };
- checksum
+ if source.ip() != dest_addr.ip() {
+ continue;
+ }
+ print_recv_post_message(packet, packet.len(), now.elapsed());
+ return Ok(());
+ }
}
-fn print_send_pre_message(_checksum:u16, buffer:&Vec){
+fn received_icmp(packet: &[u8], raw: bool) -> io::Result<&[u8]> {
+ let invalid = || {
+ io::Error::new(
+ io::ErrorKind::InvalidData,
+ "truncated or invalid ICMP response",
+ )
+ };
+ let packet = if raw {
+ let first = *packet.first().ok_or_else(invalid)?;
+ let header_len = usize::from(first & 0x0f) * 4;
+ if first >> 4 != 4 || header_len < 20 {
+ return Err(invalid());
+ }
+ packet.get(header_len..).ok_or_else(invalid)?
+ } else {
+ packet
+ };
+ if packet.len() < 8 {
+ return Err(invalid());
+ }
+ Ok(packet)
+}
+
+fn create_buffer(
+ ping_type: u8,
+ identifier: u16,
+ sequence: u16,
+ payload: &[u8],
+ size: usize,
+) -> io::Result<(Vec, u16)> {
+ if !(8..=65515).contains(&size) || payload.len() > size - 8 {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "packet size must be 8..=65515 and fit the header and payload",
+ ));
+ }
+ let mut buf = vec![0; size];
+ buf[0] = ping_type;
+ buf[4..6].copy_from_slice(&identifier.to_be_bytes());
+ buf[6..8].copy_from_slice(&sequence.to_be_bytes());
+ if payload.is_empty() {
+ for byte in &mut buf[8..] {
+ *byte = rand::rng().sample(Alphanumeric);
+ }
+ } else {
+ buf[8..8 + payload.len()].copy_from_slice(payload);
+ }
+ let checksum = calculate_checksum(&buf);
+ buf[2..4].copy_from_slice(&checksum.to_be_bytes());
+ Ok((buf, checksum))
+}
+
+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 print_send_pre_message(_checksum: u16, buffer: &[u8]) {
println!("[SENDING ICMP DATA]\n");
println!(" TY C0 CHECK ID SQ PAYLOAD----------> ");
- println!("{}",rhexdump::hexdump(&buffer));
+ println!(
+ "{}",
+ rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(buffer)
+ );
}
-fn print_send_post_messages(bytes:usize, dest_addr:std::net::SocketAddr, checksum:u16){
- println!(" > Checksum [{:02x} {:02x}] - {} bytes sent to {}", (checksum&0xff00)>>8, (checksum)&0xff, bytes, dest_addr);
+fn print_send_post_messages(bytes: usize, dest_addr: std::net::SocketAddr, checksum: u16) {
+ println!(
+ " > Checksum [{:02x} {:02x}] - {} bytes sent to {}",
+ (checksum & 0xff00) >> 8,
+ (checksum) & 0xff,
+ bytes,
+ dest_addr
+ );
}
-fn print_recv_post_message(buf: &Vec, bytes_recv:usize, elapsed:Duration){
+fn print_recv_post_message(buf: &[u8], bytes_recv: usize, elapsed: Duration) {
// Parse the response from the destination.
let icmp_type = buf[0];
let icmp_code = buf[1];
@@ -204,21 +159,68 @@ fn print_recv_post_message(buf: &Vec, bytes_recv:usize, elapsed:Duration){
println!("\n[RECEIVING ICMP DATA] \n");
println!(" TY C0 CHECK ID SQ PAYLOAD----------> ");
// println!("CHECKSUM: {:02x} {:02x}", (icmp_checksum&0xff00)>>8, (icmp_checksum)&0xff);
- println!("{}",rhexdump::hexdump(&buf));
- println!(" > Checksum [{:02x} {:02x}] - \
- {} bytes recv over the socket in {:.2} milliseconds",
- (icmp_checksum)>>8, (icmp_checksum)&0xff,
- bytes_recv, (elapsed.as_micros() as f64)/1000.
+ println!(
+ "{}",
+ rhexdump::hexdump::RhexdumpString::new().hexdump_bytes(buf)
+ );
+ println!(
+ " > Checksum [{:02x} {:02x}] - \
+ {} bytes recv over the socket in {:.2} milliseconds",
+ (icmp_checksum) >> 8,
+ (icmp_checksum) & 0xff,
+ bytes_recv,
+ (elapsed.as_micros() as f64) / 1000.
+ );
+ println!(
+ " > icmp_type = {:width$} icmp_code = {:width$}",
+ icmp_type,
+ icmp_code,
+ width = 2
+ );
+ println!(
+ " > icmp_id = {:width$} icmp_seq = {:width$}",
+ icmp_id,
+ icmp_seq,
+ width = 2
);
- println!(" > icmp_type = {:width$} icmp_code = {:width$}", icmp_type, icmp_code, width=2);
- println!(" > icmp_id = {:width$} icmp_seq = {:width$}", icmp_id, icmp_seq, width=2);
println!();
}
-fn generate_payload(payload: &mut Vec,size:usize){
- // Generate a payload of size lenght
- let mut rng = thread_rng();
- for _ in 0..(size-10){
- payload.push(rng.sample(Alphanumeric) as u8);
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn checksum_uses_network_byte_order_and_handles_odd_lengths() {
+ assert_eq!(
+ calculate_checksum(&[0, 1, 0xf2, 3, 0xf4, 0xf5, 0xf6, 0xf7]),
+ 0x220d
+ );
+ assert_eq!(calculate_checksum(&[1, 2, 3]), 0xfbfd);
+ for size in [8, 9, 64, 65515] {
+ let (packet, _) = create_buffer(8, 0x1234, 7, &[], size).unwrap();
+ assert_eq!(packet.len(), size);
+ assert_eq!(&packet[4..8], &[0x12, 0x34, 0, 7]);
+ assert_eq!(calculate_checksum(&packet), 0);
+ }
}
-}
\ No newline at end of file
+
+ #[test]
+ fn payload_is_padded_and_invalid_sizes_are_rejected() {
+ let (packet, _) = create_buffer(8, 1, 2, b"hello", 16).unwrap();
+ assert_eq!(&packet[8..], b"hello\0\0\0");
+ assert!(create_buffer(8, 1, 2, b"hello", 12).is_err());
+ assert!(create_buffer(8, 1, 2, &[], 7).is_err());
+ assert!(create_buffer(8, 1, 2, &[], 65516).is_err());
+ }
+
+ #[test]
+ fn raw_responses_skip_ipv4_header_and_reject_truncation() {
+ let mut packet = vec![0; 32];
+ packet[0] = 0x46;
+ assert_eq!(received_icmp(&packet, true).unwrap().len(), 8);
+ assert!(received_icmp(&packet[..31], true).is_err());
+ assert!(received_icmp(&[], true).is_err());
+ assert!(received_icmp(&[0; 7], false).is_err());
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 0552333..fb7170d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,12 +1,11 @@
-// Import libs
mod libs;
-// mod test;
-fn main() {
- // Parse the command line arguments.
- let res = libs::generate_ping_request(libs::parse_all_arguments());
- match res {
- Ok(()) => (),
- Err(()) => eprintln!("Program exited with errors")
+fn main() -> std::process::ExitCode {
+ match libs::generate_ping_request(libs::parse_all_arguments()) {
+ Ok(()) => std::process::ExitCode::SUCCESS,
+ Err(error) => {
+ eprintln!("error: {error}");
+ std::process::ExitCode::FAILURE
+ }
}
-}
\ No newline at end of file
+}