Compare commits

..

9 Commits

Author SHA1 Message Date
Dandaedre 9a2d0c036a
fix: handle null Cargo metadata resolution
rping CI rping passed CI.
Archive/rping/pipeline/head This commit looks good Details
2026-10-04 04:19:51 +02:00
Dandaedre b5a8be0049
release: add rust_realease workflow
rping CI rping passed CI.
Archive/rping/pipeline/head There was a failure building this commit Details
2026-10-04 04:08:53 +02:00
Dandaedre b0a6b015a2
docs: streamline project documentation 2026-10-04 03:58:47 +02:00
Dandaedre 2cf93474c6
ci: enforce MSRV and generate status badges 2026-10-04 03:58:34 +02:00
Dandaedre 783c36fc8d
Remove extra blank lines from hex output
rping CI rping passed CI.
Archive/rping/pipeline/head This commit looks good Details
2026-09-17 16:55:07 +02:00
Dandaedre 2c7343f57d
Complete ICMP probe controls and add IPv6 support 2026-09-17 16:52:42 +02:00
Dandaedre 81ac0b787d
lessend requiremrent for fmt
rping CI rping passed CI.
Archive/rping/pipeline/head This commit looks good Details
2026-09-14 21:25:40 +02:00
Dandaedre d0e102d415
Modernize Rust toolchain, CLI, and CI; fix ICMP handling 2026-09-14 21:23:38 +02:00
Dandaedre 0437954ba7 Add Jenkinsfile
rping CI rping failed CI.
Archive/rping/pipeline/head There was a failure building this commit Details
2026-09-14 19:40:26 +02:00
23 changed files with 2516 additions and 463 deletions

9
.gitignore vendored
View File

@ -3,16 +3,11 @@
# will have compiled files and executables
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
coverage/
dist/
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
pkts.txt
original.rs

12
CHANGELOG.md Normal file
View File

@ -0,0 +1,12 @@
# Changelog
Notable user-facing changes are recorded here. This project follows Semantic Versioning.
## Unreleased
## 0.1.0 - release pending
- Construct and inspect IPv4 and IPv6 ICMP packets with configurable fields, payloads, sizes, padding, counts, timeouts, intervals, and hop limits.
- Send echo probes through datagram or raw sockets and match replies and quoted ICMP errors.
- Emit summaries, hexadecimal packet dumps, or newline-delimited JSON.
- Support privilege-free dry runs for packet inspection.

293
Cargo.lock generated Normal file
View File

@ -0,0 +1,293 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
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 = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
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 = "clap"
version = "4.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfaff671f6b22ca62406885ece523383b9b64022e341e53e009a62ebc47a45f2"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a216b506622bb1d316cd51328dce24e07bdff4a6128a47c7e7fad11878d5adbb"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[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 = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[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.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "2.0.111"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[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",
]
[[package]]
name = "zerocopy"
version = "0.8.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View File

@ -2,20 +2,23 @@
name = "rping"
version = "0.1.0"
edition = "2021"
rust-version = "1.70"
description = "A small IPv4 and IPv6 ICMP packet utility"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/Archive/rping"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[package.metadata.binstall]
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ target }-v{ version }.tgz"
pkg-fmt = "tgz"
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
[dependencies]
rhexdump = "0.1.1"
hex = " 0.4.3"
argh = "0.1.9"
rand = "0.8.5"
pnet = "0.31.0"
pnet_datalink = "0.31.0"
pnet_transport = "0.31.0"
pnet_packet = "0.31.0"
clap = { version = ">=4.4, <4.5", features = ["derive"] }
socket2 = { version = "0.6", features = ["all"] }
rhexdump = "0.2"
rand = "0.8"
[profile.release]
strip = true # Automatically strip symbols from the binary.
strip = true
opt-level = "z"
lto = true
lto = true

277
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,277 @@
// Jenkins CI for Archive/rping
//
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
//
// rping is a Rust ICMP ping CLI. CI deliberately does not execute a live ping
// because raw ICMP sockets may require elevated privileges/capabilities.
pipeline {
agent { label 'rust_nodocker' }
options {
skipDefaultCheckout(true)
timestamps()
disableConcurrentBuilds()
}
environment {
CARGO_TERM_COLOR = 'never'
RUST_BACKTRACE = '1'
RUST_MSRV = '1.70.0'
CARGO_LLVM_COV_VERSION = '0.9.0'
BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
BADGE_OWNER = 'Archive'
BADGE_PROJECT = 'rping'
DEFAULT_BRANCH = 'main'
}
stages {
stage('Checkout') {
steps {
sh '''
set -eu
rm -rf coverage
mkdir -p coverage
'''
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
# rustup installs the version and components from rust-toolchain.toml.
# Do not change the shared worker's default toolchain.
rustup show active-toolchain
rustup toolchain install "$RUST_MSRV" --profile minimal
rustc --version
cargo --version
'''
}
}
stage('Setup Coverage Tool') {
steps {
sh '''
set -eu
installed_version="$(cargo llvm-cov --version 2>/dev/null | awk '{print $2}' || true)"
if [ "$installed_version" != "$CARGO_LLVM_COV_VERSION" ]; then
cargo install --locked --version "$CARGO_LLVM_COV_VERSION" cargo-llvm-cov
fi
cargo llvm-cov --version
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
cargo fmt --all -- --check
'''
}
}
stage('Check') {
steps {
sh '''
set -eu
cargo check --locked --all-targets --all-features
'''
}
}
stage('Minimum Supported Rust') {
steps {
sh '''
set -eu
cargo "+$RUST_MSRV" check --locked --all-targets --all-features
'''
}
}
stage('Tests') {
steps {
sh '''
set -eu
cargo test --locked --all-targets --all-features
: > "coverage/.tests-passed-$BUILD_NUMBER"
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
cargo clippy --locked --all-targets --all-features -- -D warnings
'''
}
}
stage('Build Release') {
steps {
sh '''
set -eu
cargo build --locked --release --all-features
test -x target/release/rping
'''
}
}
stage('Coverage') {
steps {
sh '''
set -eu
summary=coverage/coverage-summary.json
cargo llvm-cov \
--locked \
--all-features \
--all-targets \
--json \
--summary-only \
--output-path "$summary" \
--fail-under-lines 40
test -s "$summary"
coverage_value="$(python3 - "$summary" <<'PY'
import json
import math
import sys
with open(sys.argv[1], encoding="utf-8") as report:
value = json.load(report)["data"][0]["totals"]["lines"]["percent"]
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise SystemExit("overall line coverage is not numeric")
if not math.isfinite(value) or not 0 <= value <= 100:
raise SystemExit("overall line coverage is outside 0 through 100")
print(value)
PY
)"
scripts/ci-coverage-badges.sh coverage --value "$coverage_value"
rm -f "$summary"
: > "coverage/.coverage-ready-$BUILD_NUMBER"
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'rping CI',
summary: 'rping passed CI.',
text: 'Formatting, MSRV and current-toolchain checks, tests, Clippy, the release build, coverage floor, and badge generation completed successfully.',
title: 'Build Successful'
)
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'rping CI',
summary: 'rping failed CI.',
text: 'A Rust check, test, coverage floor, or badge step failed. Cleanup publishes badges that reflect this build.',
title: 'Build Failed'
)
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'rping CI',
summary: 'rping CI is unstable.',
text: 'The Jenkins build is unstable. Cleanup publishes badges that reflect this build.',
title: 'Build Unstable'
)
}
cleanup {
sh '''
set -eu
if [ -f "coverage/.tests-passed-$BUILD_NUMBER" ]; then
scripts/ci-coverage-badges.sh test --value passing
else
scripts/ci-coverage-badges.sh test --value failing
fi
if [ ! -f "coverage/.coverage-ready-$BUILD_NUMBER" ]; then
scripts/ci-coverage-badges.sh coverage --value -
fi
version="$(cargo metadata --locked --no-deps --format-version 1 | python3 -c '
import json
import sys
metadata = json.load(sys.stdin)
resolve = metadata.get("resolve")
root = resolve.get("root") if isinstance(resolve, dict) else None
packages = metadata["packages"]
if root is not None:
packages = [package for package in packages if package["id"] == root]
if len(packages) != 1:
raise SystemExit("could not resolve one authoritative package version")
print(packages[0]["version"])
')"
scripts/ci-coverage-badges.sh version --value "$version"
rm -f coverage/coverage-summary.json \
"coverage/.tests-passed-$BUILD_NUMBER" \
"coverage/.coverage-ready-$BUILD_NUMBER"
for badge in version test coverage; do
file="coverage/$badge.svg"
test -f "$file"
test ! -L "$file"
test -s "$file"
done
count="$(find coverage -maxdepth 1 -type f -name '*.svg' | wc -l | tr -d ' ')"
test "$count" = 3
'''
archiveArtifacts(
allowEmptyArchive: false,
artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg',
fingerprint: true
)
script {
if (!env.BRANCH_NAME) {
error('BRANCH_NAME is required; badge publication expects a Jenkins multibranch job.')
}
if (env.BRANCH_NAME == env.DEFAULT_BRANCH) {
sh '''
scripts/publish-coverage-badges.sh \
"$BADGE_PUBLICATION_ROOT" \
"$BADGE_OWNER" \
"$BADGE_PROJECT" \
"$DEFAULT_BRANCH" \
version test coverage
'''
}
}
}
}
}

View File

@ -1,29 +1,72 @@
# 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.
`rping` is a Linux command-line utility for constructing and sending IPv4 or IPv6 ICMP packets. It is intended for network troubleshooting and packet inspection when the standard `ping` command does not expose enough control over packet fields and payloads.
## Usage
<img src="https://proxy.dandaedre.com/gitea/repo-avatars/20-98e285bfee0185a12e362142fd0a5010" alt="drawing" width="140" align="right"/>
## Requirements
To use rping, run the following command:
- Rust 1.70 or newer; `rustup` uses the repository's pinned toolchain automatically.
- Linux for live probes.
- Permission to create ping sockets for normal live probes. Raw probes require root or `CAP_NET_RAW`.
```cargo run --dest <destination IP address> [--request/-r <ping request>] [--data/-d <data>] [--payload/-p <payload>]```
Dry runs only construct and display packets, so they do not require network access or socket privileges.
## Build
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.
From the repository root:
## Example
```sh
cargo build --locked --release
```
To send a ping request to the IP address `192.0.2.1` with the default values, run the following command:
The executable is written to `target/release/rping`.
```cargo run --dest 192.0.2.1```
## Quick start
Construct an exact-size IPv4 echo request without DNS lookups or socket access:
To send a ping request to the same IP address with a custom ping request, data, and payload value, run the following command:
```sh
cargo run --locked --quiet -- 127.0.0.1 \
--payload-hex '00 ff 01' \
--padding none \
--dry-run
```
```cargo run --dest 192.0.2.1 --request 0x1234 --data 0x5678 --payload "hello world"```
Expected output:
```text
probe 1 seq=16962 dry run
1 probes, 0 replies, 0 ICMP errors, 1 dry runs
```
For a live probe, omit `--dry-run`. Review the Linux permissions described in [Usage](docs/usage.md) first; do not grant broader privileges than necessary.
## Advanced
- [Usage](docs/usage.md) covers address families, payloads, packet sizing, output formats, live probes, and raw sockets.
- [Development and CI](docs/development.md) covers contributor commands, the minimum supported Rust version, dependency policy, coverage, and badge publication.
- [Releasing](docs/releasing.md) covers release preparation, local packaging, collision checks, and publication through `rust_realease`.
The complete command reference is always available locally:
```sh
cargo run --locked -- --help
```
## Development
Run the local quality gates from the repository root:
```sh
cargo fmt --all -- --check
cargo check --locked --all-targets --all-features
cargo +1.70.0 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
```
See [Development and CI](docs/development.md) for toolchain setup, documentation, and coverage commands.
## License
This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
Licensed under the [MIT License](LICENSE).

80
docs/development.md Normal file
View File

@ -0,0 +1,80 @@
# Development and CI
This page documents contributor and CI workflows for [`rping`](../README.md). Run all commands from the repository root.
## Toolchains and dependencies
The project declares Rust 1.70 as its minimum supported Rust version (MSRV). Jenkins checks all targets with Rust 1.70.0 and the locked dependency graph. The lockfile uses format version 3 so Cargo 1.70 can read it.
The tracked `rust-toolchain.toml` pins Rust 1.98.1 with `rustfmt`, Clippy, and LLVM tools for normal development and coverage. Install the MSRV toolchain separately before running its check:
```sh
rustup toolchain install 1.70.0 --profile minimal
```
The project has four direct runtime dependencies. `clap` is constrained to the Rust-1.70-compatible 4.4 line, and `rand` uses the mature 0.8 line. CI uses locked dependency resolution.
There is no `no_std` feature. This is an operating-system CLI whose main path uses sockets, DNS resolution, files, clocks, threads, heap allocation, terminal output, and operating-system randomness. A useful `no_std` API would require designing a separate packet-construction library rather than feature-gating the application.
## Quality gates
Run the same checks used by CI:
```sh
cargo fmt --all -- --check
cargo check --locked --all-targets --all-features
cargo +1.70.0 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
cargo doc --locked --all-features --no-deps
```
Tests do not require network access. CI intentionally does not run live probes because worker permissions for ICMP sockets are not assumed.
## Coverage
CI pins `cargo-llvm-cov` 0.9.0 and enforces a 40% line-coverage floor without excluding production code. Run the exact coverage gate locally with:
```sh
cargo llvm-cov \
--locked \
--all-features \
--all-targets \
--json \
--summary-only \
--output-path coverage/coverage-summary.json \
--fail-under-lines 40
```
`coverage/coverage-summary.json` is temporary. CI validates its overall line percentage, renders the coverage badge, and removes the summary.
## CI badges
The authoritative version comes from `Cargo.toml` through `cargo metadata`. Jenkins records successful tests and coverage with build-specific markers, then generates version, test, and coverage badges from cleanup so failed builds cannot leave stale passing results.
Jenkins validates and archives exactly these ignored files with fingerprints:
```text
coverage/version.svg
coverage/test.svg
coverage/coverage.svg
```
In a Jenkins multibranch job, `BRANCH_NAME` restricts publication to the `main` branch. The publisher atomically copies badges to:
```text
/mnt/assets/coverage/Archive/rping/main/
```
The intended public URLs are:
```text
https://assets.dandaedre.com/coverage/Archive/rping/main/version.svg
https://assets.dandaedre.com/coverage/Archive/rping/main/test.svg
https://assets.dandaedre.com/coverage/Archive/rping/main/coverage.svg
```
These URLs must not be presented as live status badges until a successful default-branch Jenkins build has published them and each response has been verified as SVG XML. The asset server should mount the publication directory read-only, disable directory listings, use a restrictive content security policy for SVG, and revalidate mutable badge URLs or give them a short cache lifetime.
The generic renderer in `scripts/ci-coverage-badges.sh` was copied from the `agent-tasks` source at revision `fb9d8f7d16f100c2d1377f23394a2302eac9ab18`.

89
docs/releasing.md Normal file
View File

@ -0,0 +1,89 @@
# Release procedure
This page documents release preparation and publication for the `rping` package and its `rping` binary. The package version in `Cargo.toml` is authoritative; version `X.Y.Z` uses tag `vX.Y.Z`.
## Release contract
- Canonical repository: `Archive/rping`
- Public release URL: `https://proxy.dandaedre.com/gitea/Archive/rping/releases`
- Package and binary: `rping`
- Profile: `release`
- Artifact format: cargo-binstall `.tgz` archives and standalone binaries (`both`)
- Targets: `x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`, and `x86_64-pc-windows-gnu`
- Tag prefix: `v`
The repository is public and contains cargo-binstall metadata. The local wrapper uses the default target matrix reported by `rust_realease`; pass explicit `--target` options only as a deliberate release-policy change.
## Prerequisites
Install and verify:
- `rust_realease`
- Cross
- a working Docker or Podman backend
- `cargo-binstall`
- Git and the Rust toolchain pinned by `rust-toolchain.toml`
The publisher executable intentionally uses the upstream spelling `rust_realease`. Its preferred installation method is:
```sh
cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease \
rust_realease
rust_realease --help
```
See the [upstream repository](https://proxy.dandaedre.com/gitea/idle-org/rust_realease) for source-installation alternatives.
Prepare a token file outside the repository. Its first line must contain a Gitea token able to inspect and create releases for `Archive/rping`. Restrict the file to the maintainer account, for example:
```sh
chmod 600 /path/to/gitea-token.txt
```
Never commit the token or pass its value on the command line. `release.sh` reads the first line and exports it only as `GITEA_TOKEN` to `rust_realease`.
## Prepare and verify
1. Update `CHANGELOG.md`, `Cargo.toml`, and `Cargo.lock` so the changelog and package version agree.
2. Run every command in [Development and CI](development.md#quality-gates), including coverage.
3. Verify the release wrapper tests with `cargo test --locked --test release_wrapper`.
4. Commit the reviewed preparation.
5. Create an annotated or signed `vX.Y.Z` tag at that commit and push the commit and tag through the normal reviewed Git workflow.
6. Confirm the checkout is clean and that the local and remote tags resolve to `HEAD`.
7. Check the Gitea release-by-tag API or repository UI for an existing release and list all existing asset names.
The wrapper never creates, moves, pushes, or deletes Git tags. It also does not edit Cargo metadata, Git remotes, or releases before invoking the publisher.
## Dry run and packaging
Always start with a dry run:
```sh
./release.sh /path/to/gitea-token.txt --dry-run
```
Confirm the package, version, tag, three targets, artifact names, and proxy release destination. Treat every reported issue as a blocker.
When local resources permit, build and inspect the complete package set without contacting Gitea:
```sh
./release.sh /path/to/gitea-token.txt --compile-only
```
Inspect `SHA256SUMS`, archive contents, executable names and modes, and cargo-binstall metadata. Repeat the build in a clean checkout with the same toolchain and compare checksums when reproducibility is required.
## Publish
Immediately before publishing, repeat the tag, release, and asset collision checks. Then run:
```sh
./release.sh /path/to/gitea-token.txt
```
A hyphenated package version such as `0.2.0-rc.1` automatically adds `--prerelease`; a stable version does not. Additional arguments are forwarded exactly to `rust_realease`.
An existing release is not permission to overwrite assets. Stop on any asset-name collision. Use `--replace-assets` only after inspecting that exact release and explicitly deciding that the named assets should be replaced.
## Repository fallback
Development uses the unchanged SSH origin `git@git.dandaedre.com:Archive/rping.git`. `rust-release.toml` maps only that exact origin to `https://proxy.dandaedre.com/gitea/Archive/rping` for release API and download operations. The fallback does not rewrite the Git remote.

90
docs/usage.md Normal file
View File

@ -0,0 +1,90 @@
# Using rping
This page expands on the [README quick start](../README.md#quick-start). Run commands from the repository root after building with `cargo build --locked --release`, or replace `./target/release/rping` with `cargo run --locked --`.
## Safe packet inspection
`--dry-run` builds packets without resolving hostnames or opening a socket. A hostname in a dry run defaults to IPv4 because no DNS lookup occurs; use `--family v6` to inspect an IPv6 packet.
```sh
# Show the bytes of two exact-size IPv4 packets.
./target/release/rping 127.0.0.1 \
--payload-hex '00 ff 01' \
--padding none \
--count 2 \
--output hex \
--dry-run
# Produce newline-delimited JSON for an IPv6 packet.
./target/release/rping ::1 \
--family v6 \
--payload-hex '00 ff' \
--padding none \
--output json \
--dry-run
```
## Live probes and permissions
Linux is the primary runtime target. Datagram mode needs permission to create ping sockets through `net.ipv4.ping_group_range` and, for IPv6, an ICMPv6 datagram socket. Raw mode needs root or the `CAP_NET_RAW` capability. Prefer datagram mode unless control over raw-only fields is required.
```sh
# Send four IPv6 echo probes at 500 ms intervals with a hop limit of 16.
./target/release/rping ::1 --family v6 --count 4 --interval-ms 500 --ttl 16
# Use a raw socket when the ICMP identifier must be controlled.
sudo ./target/release/rping 127.0.0.1 --raw --identifier 4660 --sequence 1
```
Sending non-echo types or nonzero codes requires `--raw`; `--dry-run` can inspect them without privileges. Echo requests require code 0.
## Payload and packet sizing
The `--payload`, `--payload-hex`, and `--payload-file` options are mutually exclusive. Hexadecimal input accepts spaces, colons, and underscores.
The default packet size is 64 bytes. Padding modes behave as follows:
- `auto` fills unused bytes with random alphanumeric data when no payload is supplied and zeroes them otherwise.
- `zero` fills unused bytes with zeroes.
- `random` fills unused bytes with random alphanumeric data.
- `none` makes the packet exactly eight header bytes plus the payload. If `--size` is also supplied, it must match that exact size.
Packet sizes must be between 8 and 65515 bytes. `--count` is limited to 65536 so a single run does not reuse a 16-bit sequence number; the sequence wraps after 65535.
## Output and exit status
The output modes are:
- `summary` prints one status line per probe and a final summary.
- `hex` adds full packet dumps.
- `json` emits one JSON object per probe and a final summary object.
JSON probe objects include status, sequence, requested packet bytes, and received bytes when available. The command exits successfully when every live probe receives a matching reply or when every probe is a dry run. Invalid input, socket failures, timeouts, and matching ICMP errors produce a nonzero exit status. Unrelated or malformed packets are ignored until the probe deadline.
The hex dump is the ICMP packet passed to the socket. In IPv4 datagram mode, Linux may replace its identifier and checksum; use raw mode when those fields must be controlled. The kernel supplies the IPv4 header in either mode.
For ICMPv6, the kernel calculates the mandatory checksum from the IPv6 pseudo-header, so dry-run output contains zero in the checksum field and is not the complete on-wire packet.
## Options
| Option | Meaning | Default |
| --- | --- | --- |
| `--family` | Address family: `auto`, `v4`, or `v6` | `auto` |
| `-t`, `--type` | ICMP type | 8 for IPv4; 128 for IPv6 |
| `--code` | ICMP code | 0 |
| `-i`, `--identifier` | 16-bit identifier | 16962 (`0x4242`) |
| `-q`, `--sequence` | Initial 16-bit sequence number | 16962 |
| `-p`, `--payload` | UTF-8 payload bytes | None |
| `--payload-hex` | Hexadecimal payload bytes | None |
| `--payload-file` | Binary payload file | None |
| `-s`, `--size` | Total ICMP size, including the header | 64 unless padding is `none` |
| `--padding` | `auto`, `zero`, `random`, or `none` | `auto` |
| `-c`, `--count` | Number of probes | 1 |
| `--interval-ms` | Delay between probe starts | 1000 ms |
| `--timeout-ms` | Per-probe response deadline | 1000 ms |
| `--ttl` | IPv4 TTL or IPv6 unicast hop limit | System default |
| `--output` | `summary`, `hex`, or `json` | `summary` |
| `--raw` | Use a raw ICMP socket | Off |
| `--dry-run` | Build packets without DNS or sockets | Off |
Use `rping --help` for the authoritative command-line reference.

64
libc.rs
View File

@ -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::<sockaddr_in>() as u32,
)
};
if send_result < 0 {
// Handle the error
} else {
// The packet was sent successfully
}

48
release.sh Executable file
View File

@ -0,0 +1,48 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 <gitea-token-file> [rust_realease options...]" >&2
exit 2
}
[ "$#" -ge 1 ] || usage
token_file=$1
shift
if [ ! -f "$token_file" ] || [ ! -r "$token_file" ]; then
echo "token file is not a readable regular file: $token_file" >&2
exit 2
fi
if ! command -v rust_realease >/dev/null 2>&1; then
echo "rust_realease is not installed or not available in PATH" >&2
exit 2
fi
GITEA_TOKEN=
IFS= read -r GITEA_TOKEN <"$token_file" || :
if [ -z "$GITEA_TOKEN" ]; then
echo "token file is empty: $token_file" >&2
exit 2
fi
export GITEA_TOKEN
repository_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
manifest_version=$(sed -n 's/^version = "\([^"]*\)"/\1/p' \
"$repository_dir/Cargo.toml" | head -n 1)
if [ -z "$manifest_version" ]; then
echo "could not determine the selected package version" >&2
exit 2
fi
set -- \
"$repository_dir" \
--package rping \
--artifact-format both \
"$@"
case "$manifest_version" in
*-*) set -- "$@" --prerelease ;;
esac
exec rust_realease "$@"

3
rust-release.toml Normal file
View File

@ -0,0 +1,3 @@
[[repository.fallbacks]]
origin = "git@git.dandaedre.com:Archive/rping.git"
fallback-url = "https://proxy.dandaedre.com/gitea/Archive/rping"

4
rust-toolchain.toml Normal file
View File

@ -0,0 +1,4 @@
[toolchain]
channel = "1.98.1"
profile = "minimal"
components = ["rustfmt", "clippy", "llvm-tools-preview"]

270
scripts/ci-coverage-badges.sh Executable file
View File

@ -0,0 +1,270 @@
#!/bin/sh
set -eu
usage() {
cat >&2 <<'EOF'
usage: $0 <version|test|coverage> [options]
Render one deterministic SVG badge. Defaults:
version --text version --value unknown --color #007ec6
test --text tests --value passing --color #4c1
coverage --text coverage --value - --color #9f9f9f --suffix %
Options:
--text TEXT left-hand label
--value VALUE right-hand value
--color COLOR value background (#RGB or #RRGGBB)
--size PX font size, from 6 through 24 (default: 11)
--height PX badge height, from 14 through 64 (default: 20)
--label-width PX fixed label width instead of automatic sizing
--value-width PX fixed value width instead of automatic sizing
--suffix TEXT text appended to the displayed value
--output PATH output file (default: coverage/<kind>.svg)
-h, --help show this help
Examples:
./ci-coverage-badges.sh version --value 1.2.3
./ci-coverage-badges.sh test --value failing
./ci-coverage-badges.sh coverage --value 87.4
./ci-coverage-badges.sh version --text release --value rc.12 --size 12 --color '#8a2be2'
EOF
exit "${1:-2}"
}
[ "$#" -ge 1 ] || usage
kind=$1
shift
case "$kind" in
version)
text=version
value=unknown
color='#007ec6'
suffix=
output=coverage/version.svg
;;
test)
text=tests
value=passing
color=
suffix=
output=coverage/test.svg
;;
coverage)
text=coverage
value=-
color=
suffix=%
output=coverage/coverage.svg
;;
-h|--help) usage 0 ;;
*)
echo "unsupported badge kind: $kind" >&2
usage
;;
esac
font_size=11
height=20
label_width=
value_width=
color_set=false
while [ "$#" -gt 0 ]; do
option=$1
case "$option" in
--text|--value|--color|--size|--height|--label-width|--value-width|--suffix|--output)
[ "$#" -ge 2 ] || {
echo "missing value for $option" >&2
exit 2
}
option_value=$2
shift 2
case "$option" in
--text) text=$option_value ;;
--value) value=$option_value ;;
--color) color=$option_value; color_set=true ;;
--size) font_size=$option_value ;;
--height) height=$option_value ;;
--label-width) label_width=$option_value ;;
--value-width) value_width=$option_value ;;
--suffix) suffix=$option_value ;;
--output) output=$option_value ;;
esac
;;
-h|--help) usage 0 ;;
*)
echo "unknown option: $option" >&2
usage
;;
esac
done
validate_text() {
field_name=$1
field_value=$2
if ! printf '%sX\n' "$field_value" | LC_ALL=C awk '
BEGIN { valid = 1 }
NR != 1 || $0 !~ /^[ -~]+X$/ || length($0) <= 1 { valid = 0 }
END { exit(valid == 0 ? 1 : 0) }
'; then
echo "$field_name must contain printable ASCII characters: $field_value" >&2
exit 2
fi
}
validate_integer() {
field_name=$1
field_value=$2
minimum=$3
maximum=$4
case "$field_value" in
''|*[!0-9]*)
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
;;
esac
if [ "$field_value" -lt "$minimum" ] || [ "$field_value" -gt "$maximum" ]; then
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
fi
}
validate_text text "$text"
validate_text value "$value"
if [ -n "$suffix" ]; then
validate_text suffix "$suffix"
fi
validate_integer size "$font_size" 6 24
validate_integer height "$height" 14 64
if [ -n "$label_width" ]; then
validate_integer label-width "$label_width" 20 1000
fi
if [ -n "$value_width" ]; then
validate_integer value-width "$value_width" 20 1000
fi
case "$output" in
''|*/) echo "output must name an SVG file: $output" >&2; exit 2 ;;
esac
case "$kind" in
test)
if [ "$color_set" = false ]; then
case "$value" in
passing) color='#4c1' ;;
failing) color='#e05d44' ;;
*) color='#9f9f9f' ;;
esac
fi
;;
coverage)
if [ "$value" = '-' ]; then
[ "$color_set" = true ] || color='#9f9f9f'
else
if ! awk -v candidate="$value" 'BEGIN {
valid = candidate ~ /^[0-9]+([.][0-9]+)?$/ && candidate >= 0 && candidate <= 100
exit(valid ? 0 : 1)
}'; then
echo "coverage value must be - or a number from 0 through 100: $value" >&2
exit 2
fi
value=$(awk -v candidate="$value" 'BEGIN { printf "%.0f", candidate }')
if [ "$color_set" = false ]; then
if [ "$value" -ge 90 ]; then
color='#4c1'
elif [ "$value" -ge 70 ]; then
color='#dfb317'
else
color='#e05d44'
fi
fi
fi
;;
esac
case "$color" in
\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]|\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]) ;;
*) echo "color must be #RGB or #RRGGBB: $color" >&2; exit 2 ;;
esac
display_value=$value$suffix
if [ -z "$label_width" ]; then
label_width=$(printf '%s\\n' "$text" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
if [ -z "$value_width" ]; then
value_width=$(printf '%s\\n' "$display_value" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
badge_width=$((label_width + value_width))
label_center=$(awk -v width="$label_width" 'BEGIN { printf "%.1f", width / 2 }')
value_center=$(awk -v left="$label_width" -v width="$value_width" 'BEGIN {
printf "%.1f", left + width / 2
}')
vertical_center=$(awk -v badge_height="$height" 'BEGIN { printf "%.1f", badge_height / 2 }')
xml_escape() {
sed \
-e 's/&/\&amp;/g' \
-e 's/</\&lt;/g' \
-e 's/>/\&gt;/g' \
-e 's/"/\&quot;/g'
}
sed_replacement_escape() {
sed -e 's/[\\&|]/\\&/g'
}
escaped_text=$(printf '%s' "$text" | xml_escape | sed_replacement_escape)
escaped_value=$(printf '%s' "$display_value" | xml_escape | sed_replacement_escape)
escaped_title=$(printf '%s: %s' "$text" "$display_value" | xml_escape | sed_replacement_escape)
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p "$output_dir"
fi
temporary="${output}.tmp.$$"
trap 'rm -f "$temporary"' EXIT HUP INT TERM
sed \
-e "s/@BADGE_WIDTH@/$badge_width/g" \
-e "s/@HEIGHT@/$height/g" \
-e "s/@LABEL_WIDTH@/$label_width/g" \
-e "s/@VALUE_WIDTH@/$value_width/g" \
-e "s/@LABEL_CENTER@/$label_center/g" \
-e "s/@VALUE_CENTER@/$value_center/g" \
-e "s/@VERTICAL_CENTER@/$vertical_center/g" \
-e "s/@FONT_SIZE@/$font_size/g" \
-e "s/@COLOR@/$color/g" \
-e "s|@TITLE@|$escaped_title|g" \
-e "s|@TEXT@|$escaped_text|g" \
-e "s|@VALUE@|$escaped_value|g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="@BADGE_WIDTH@" height="@HEIGHT@" role="img" aria-label="@TITLE@">
<title>@TITLE@</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="@BADGE_WIDTH@" height="@HEIGHT@" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="@LABEL_WIDTH@" height="@HEIGHT@" fill="#555"/>
<rect x="@LABEL_WIDTH@" width="@VALUE_WIDTH@" height="@HEIGHT@" fill="@COLOR@"/>
<rect width="@BADGE_WIDTH@" height="@HEIGHT@" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="@FONT_SIZE@">
<text x="@LABEL_CENTER@" y="@VERTICAL_CENTER@">@TEXT@</text>
<text x="@VALUE_CENTER@" y="@VERTICAL_CENTER@">@VALUE@</text>
</g>
</svg>
EOF
mv "$temporary" "$output"
trap - EXIT HUP INT TERM

View File

@ -0,0 +1,84 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 ABSOLUTE_ROOT OWNER PROJECT DEFAULT_BRANCH NAME..." >&2
exit 2
}
[ "$#" -ge 5 ] || usage
root=$1
owner=$2
project=$3
branch=$4
shift 4
case $root in /*) ;; *) echo "publication root must be absolute" >&2; exit 1 ;; esac
[ -d "$root" ] && [ ! -L "$root" ] && [ -w "$root" ] || {
echo "publication root must be an existing writable directory, not a symlink" >&2
exit 1
}
for component in "$owner" "$project" "$branch"; do
case $component in
''|*[!A-Za-z0-9._-]*) echo "invalid publication path component: $component" >&2; exit 1 ;;
esac
done
seen=' '
for name in "$@"; do
case $name in coverage|test|version) ;; *) echo "invalid badge name: $name" >&2; exit 1 ;; esac
case $seen in *" $name "*) echo "duplicate badge name: $name" >&2; exit 1 ;; esac
seen="$seen$name "
source_file="coverage/$name.svg"
[ -f "$source_file" ] && [ ! -L "$source_file" ] && [ -s "$source_file" ] || {
echo "invalid badge source: $source_file" >&2
exit 1
}
done
owner_dir=$root/$owner
project_dir=$owner_dir/$project
destination=$project_dir/$branch
for directory in "$owner_dir" "$project_dir"; do
[ ! -L "$directory" ] || { echo "refusing symlink directory: $directory" >&2; exit 1; }
[ ! -e "$directory" ] || [ -d "$directory" ] || {
echo "publication component is not a directory: $directory" >&2
exit 1
}
mkdir -p "$directory"
chmod 0755 "$directory"
done
if [ -L "$destination" ]; then
unlink "$destination"
fi
[ ! -e "$destination" ] || [ -d "$destination" ] || {
echo "publication destination is not a directory: $destination" >&2
exit 1
}
mkdir -p "$destination"
chmod 0755 "$destination"
cleanup() {
for name in "$@"; do
temporary=$destination/.$name.svg.tmp-$$
[ ! -e "$temporary" ] || rm -f "$temporary"
done
}
trap cleanup 0
trap 'exit 1' HUP INT TERM
for name in "$@"; do
temporary=$destination/.$name.svg.tmp-$$
(umask 077; set -C; : > "$temporary") || {
echo "cannot create publication temporary: $temporary" >&2
exit 1
}
cp "coverage/$name.svg" "$temporary"
chmod 0644 "$temporary"
mv -f "$temporary" "$destination/$name.svg"
done
trap - 0 HUP INT TERM

View File

@ -1,19 +1,5 @@
mod rp_icmp;
mod rp_args;
mod rp_ipv4;
mod args;
mod icmp;
pub use rp_icmp::{
create_icmp_packet,
// generate_ping_request,
// calculate_checksum
};
pub use rp_args::{
parse_all_arguments,
get_payload_from_str,
};
pub use rp_ipv4::{
create_ethernet_packet,
create_interface,
send_packet,
recv_packet,
};
pub use args::parse_all_arguments;
pub use icmp::generate_ping_request;

244
src/libs/args.rs Normal file
View File

@ -0,0 +1,244 @@
use clap::{Parser, ValueEnum};
use std::{fs, io, path::PathBuf, time::Duration};
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum Padding {
#[default]
Auto,
Zero,
Random,
None,
}
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum Family {
#[default]
Auto,
V4,
V6,
}
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum Output {
#[default]
Summary,
Hex,
Json,
}
#[derive(Debug, Parser)]
#[command(version, about, arg_required_else_help = true)]
pub struct Config {
/// Destination IP address or hostname
#[arg(value_name = "DESTINATION")]
pub dest_addr: String,
/// ICMP type (8 is an echo request)
#[arg(short = 't', long = "type")]
pub ping_type: Option<u8>,
/// ICMP code
#[arg(long, default_value_t = 0)]
pub code: u8,
/// ICMP identifier (the OS may replace it in datagram mode)
#[arg(short = 'i', long, default_value_t = 16962)]
pub identifier: u16,
/// ICMP sequence number
#[arg(short = 'q', long, default_value_t = 16962)]
pub sequence: u16,
/// UTF-8 payload
#[arg(short = 'p', long, conflicts_with_all = ["payload_hex", "payload_file"])]
pub payload: Option<String>,
/// Hexadecimal payload bytes (spaces, colons and underscores allowed)
#[arg(long, conflicts_with = "payload_file")]
pub payload_hex: Option<String>,
/// Read payload bytes from a file
#[arg(long)]
pub payload_file: Option<PathBuf>,
/// Total ICMP packet size, including the 8-byte header (8–65515)
#[arg(short = 's', long = "size", value_parser = parse_size)]
pub size: Option<usize>,
/// Padding: auto, zero, random, or none
#[arg(long, value_enum, default_value_t = Padding::Auto)]
pub padding: Padding,
/// Use a raw ICMP socket (requires root or CAP_NET_RAW on Linux)
#[arg(long)]
pub raw: bool,
/// Print the packet without opening a socket
#[arg(long)]
pub dry_run: bool,
/// Response timeout in milliseconds
#[arg(long, default_value_t = 1000, value_parser = clap::value_parser!(u64).range(1..))]
pub timeout_ms: u64,
/// Number of probes
#[arg(short = 'c', long, default_value_t = 1, value_parser = clap::value_parser!(u32).range(1..))]
pub count: u32,
/// Time between probe starts in milliseconds
#[arg(long, default_value_t = 1000)]
pub interval_ms: u64,
/// IP time to live (IPv4) or hop limit (IPv6)
#[arg(long, value_parser = clap::value_parser!(u8).range(1..))]
pub ttl: Option<u8>,
/// Address family
#[arg(long, value_enum, default_value_t = Family::Auto)]
pub family: Family,
/// Output format
#[arg(long, value_enum, default_value_t = Output::Summary)]
pub output: Output,
}
fn parse_size(value: &str) -> Result<usize, String> {
let size = value
.parse::<usize>()
.map_err(|_| "expected a byte count")?;
if !(8..=65515).contains(&size) {
return Err("size must be between 8 and 65515 bytes".into());
}
Ok(size)
}
impl Config {
pub fn payload_bytes(&self) -> io::Result<Vec<u8>> {
if let Some(s) = &self.payload {
Ok(s.as_bytes().to_vec())
} else if let Some(s) = &self.payload_hex {
let hex: String = s
.chars()
.filter(|c| !matches!(c, ' ' | ':' | '_' | '\n' | '\t'))
.collect();
if hex.len() % 2 != 0 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"payload hex must contain complete byte pairs",
));
}
hex.as_bytes()
.chunks_exact(2)
.map(|pair| {
u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidInput, "invalid payload hex")
})
})
.collect()
} else if let Some(path) = &self.payload_file {
fs::read(path)
} else {
Ok(Vec::new())
}
}
pub fn packet_size(&self, payload_len: usize) -> io::Result<usize> {
let size = if matches!(self.padding, Padding::None) {
self.size.unwrap_or(payload_len.saturating_add(8))
} else {
self.size.unwrap_or(64)
};
if !(8..=65515).contains(&size)
|| payload_len > size - 8
|| (matches!(self.padding, Padding::None) && payload_len != size - 8)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"packet size must be 8..=65515, fit the payload, and match it with --padding none",
));
}
Ok(size)
}
pub fn validate(&self) -> io::Result<()> {
if self.count > u16::MAX as u32 + 1 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"count exceeds sequence number range",
));
}
if !self.raw
&& !self.dry_run
&& (self.ping_type.is_some_and(|ty| ty != 8 && ty != 128) || self.code != 0)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"non-echo ICMP type or nonzero code requires --raw",
));
}
if matches!(self.ping_type, Some(8 | 128)) && self.code != 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"echo requests require code 0",
));
}
Ok(())
}
pub fn timeout(&self) -> Duration {
Duration::from_millis(self.timeout_ms)
}
}
pub fn parse_all_arguments() -> Config {
Config::parse()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_binary_payload_and_exact_size() {
let config = Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload-hex",
"00:ff_01",
"--padding",
"none",
])
.unwrap();
assert_eq!(config.payload_bytes().unwrap(), [0, 255, 1]);
assert_eq!(config.packet_size(3).unwrap(), 11);
}
#[test]
fn rejects_invalid_hex_and_mismatched_size() {
let config = Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload-hex",
"0",
"--padding",
"none",
])
.unwrap();
assert!(config.payload_bytes().is_err());
let config = Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload-hex",
"00",
"--padding",
"none",
"--size",
"64",
])
.unwrap();
assert!(config.packet_size(1).is_err());
assert!(Config::try_parse_from([
"rping",
"127.0.0.1",
"--payload",
"a",
"--payload-hex",
"61"
])
.is_err());
}
#[test]
fn custom_code_needs_raw_mode() {
let config =
Config::try_parse_from(["rping", "127.0.0.1", "--type", "3", "--code", "1"]).unwrap();
assert!(config.validate().is_err());
let config =
Config::try_parse_from(["rping", "127.0.0.1", "--type", "3", "--code", "1", "--raw"])
.unwrap();
assert!(config.validate().is_ok());
}
}

661
src/libs/icmp.rs Normal file
View File

@ -0,0 +1,661 @@
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::<IpAddr>()
.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<SocketAddr> {
(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<u8>,
},
Error {
source: IpAddr,
ty: u8,
code: u8,
response: Vec<u8>,
},
Timeout,
}
fn probe(
socket: &UdpSocket,
destination: SocketAddr,
packet: &[u8],
seq: u16,
config: &Config,
version: Version,
) -> io::Result<ProbeResult> {
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(&quoted[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<Vec<u8>> {
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<f64> = 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::<f64>() / 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)
));
}
}

View File

@ -1,134 +0,0 @@
// use std::env;
use argh::FromArgs;
use hex;
#[derive(FromArgs)]
/// rping, sending very custom icmp requests
pub struct Config{
/// the destination address for the request
#[argh(positional)]
pub dest_addr : String,
/// the source address for the request
#[argh(option, default = "String::from(\"0.0.0.0\")")]
pub src_addr : String,
/// the type of ping request
#[argh(option, default = "8")]
pub ping_type : u8,
/// the ping identifier u16 number
#[argh(option, default = "0x4242")]
pub identifier : u16,
/// the ping sequence u16 number
#[argh(option, default = "0x0001")]
pub sequence : u16,
/// the actual ping payload,
#[argh(option, default = "String::new()")]
pub payload : String,
/// the total icmp payload size
#[argh(option, default = "64")]
pub payload_size : usize,
/// force the usage of a raw packet
#[argh(option, default = "false")]
pub raw_packet : bool,
/// the packet size (excluding header)
#[argh(option, default = "64")]
pub packet_size : u8,
/// the ip version used (4 or 6)
#[argh(option, default = "4")]
pub ipv4_version : u8,
/// inter header length (must be >=5)
#[argh(option, default = "5")]
pub ihl : u8,
/// differentiated service code points
#[argh(option, default = "0")]
pub dcsp : u8,
/// explicit congestion notification
#[argh(option, default = "0")]
pub ecn : u8,
/// time to live
#[argh(option, default = "64")]
pub ttl: u8,
/// identification (lacking documentation)
#[argh(option, default = "52703")]
pub identification : u16,
/// flags : 2 don't fragment, 4 more fragments
#[argh(option, default = "2")]
pub flags : u8,
/// the fragment offset (if fragmented)
#[argh(option, default = "0")]
pub offset : u16,
}
pub fn get_payload_from_str(inputp: &str) -> Vec<u8> {
// If you start your payload by 0x all following will be parsed as hex (ignoring spaces)
let mut payload = Vec::<u8>::new();
payload.resize(0,4); // The identifier and sequence are in the payload for dumb reasons
if inputp.len()<2 {
return payload
}
if &inputp[..2]=="0x"{
let nopx = inputp.trim_start_matches("0x");
hex::decode_to_slice(nopx,&mut payload[4..]).expect("Couldn't parse the payload");
} else {
payload = inputp.as_bytes().to_vec();
}
payload
}
pub fn sanitize_config(config: &mut Config){
// Expected behaviour is as follows:
// If you specify a payload, it will increase the payload length and total length as needed
// If you have length set longer than your payloads zeroes will be added as needed
// if config.payload.len()<=4{
// config.payload.resize(config.payload_size+4,0); // Resize payload to match the size given
// }
// if config.packet_size
// if config.payload.len()>=2{
// if &config.payload[..2]=="0x"{
// let nopx = config.payload.trim_start_matches("0x");
// hex::decode_to_slice(nopx,&mut payload).expect("Couldn't parse the payload");
// } else {
// payload = config.payload.as_bytes().to_vec();
// }
// }
// if config.packet_size < (config.payload.len()-4) as u8{
// config.packet_size = (config.payload.len()-4) as u8;
// }
}
pub fn parse_all_arguments() -> Config {
// Load all inline arguments and create a config structure
// let args: Vec<String> = env::args().collect();
let mut_config = argh::from_env();
//Sanitize inputs and show it
// if config.payload.len()!=0{
// println!("Corrected payload size, went from {} to {} according to given input",config.payload_size,config.payload.len()/4);
// config.payload_size=config.payload.len()/4;
// }
// config
mut_config
}

View File

@ -1,112 +0,0 @@
use crate::libs::rp_args::Config;
// use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
// use pnet::packet::ipv4;
use pnet::packet::icmp;
// use pnet::packet::Packet;
// use pnet_datalink::{
// self,
// // MacAddr
// };
// use pnet_transport::{
// icmp_packet_iter, transport_channel, TransportChannelType::Layer4, TransportProtocol::Ipv4,
// TransportChannelType::Layer3
// };
// use pnet::packet::ip::{
// IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
// };
// use std::net::{IpAddr, Ipv4Addr};
// use pnet::packet::icmp::{
// echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
// };
use rand::{
thread_rng,
distributions::Alphanumeric,
Rng,
};
pub fn create_icmp_packet<'a>(config: &Config, icmp_payload: &Vec<u8>) -> icmp::MutableIcmpPacket<'a>{
// Create a new mutable ICMP packet
let mut binding = vec![0u8;config.packet_size as usize];
// // Loading a custom Id, because I didn't want to split it into two functions
// binding[4]=(config.identifier >> 8) as u8;
// binding[5]=(config.identifier&0xff) as u8;
// // Loading a custom Seq Number, because I didn't wat to split it into two
// binding[6]=(config.sequence>>8) as u8;
// binding[7]=(config.sequence&0xff) as u8;
let mut packet = icmp::MutableIcmpPacket::owned(binding).expect("Couldn't create packet");
// Set the ICMP packet type and code to the appropriate values for a ping request
packet.set_icmp_type(icmp::IcmpTypes::EchoRequest);
packet.set_icmp_code(pnet::packet::icmp::IcmpCode(0));
packet.set_payload(&icmp_payload);
// if config.payload.len()==0{
// // let payload=vec![4u8;(config.packet_size-4).into()]; // For a fixed payload
// let mut payload=Vec::<u8>::new();
// // Loading a custom Id, because I didn't want to split it into two functions
// payload.push((config.identifier >> 8) as u8);
// payload.push((config.identifier&0xff) as u8);
// // Loading a custom Seq Number, because I didn't wat to split it into two
// payload.push((config.sequence>>8) as u8);
// payload.push((config.sequence&0xff) as u8);
// generate_payload(&mut payload, (config.packet_size).into());
// packet.set_payload(&payload);
// } else {
// packet.set_payload(&config.payload.as_bytes());
// }
packet.set_checksum(pnet_packet::icmp::checksum(&packet.to_immutable()));
packet
}
// fn print_send_pre_message(_checksum:u16, buffer:&Vec<u8>){
// println!("[SENDING ICMP DATA]\n");
// println!(" TY C0 CHECK ID SQ PAYLOAD----------> ");
// println!("{}",rhexdump::hexdump(&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_recv_post_message(buf: &Vec<std::mem::MaybeUninit<u8>>, bytes_recv:usize, elapsed:Duration){
// // Parse the response from the destination.
// // unsafe {buf.assume_init()};
// println!("Received {} bytes in {:?} {:?}",bytes_recv, elapsed, buf);
// // let icmp_type = buf[0];
// // let icmp_code = buf[1];
// // let icmp_checksum = ((buf[2] as u16) << 8) | (buf[3] as u16);
// // let icmp_id = ((buf[4] as u16) << 8) | (buf[5] as u16);
// // let icmp_seq = ((buf[6] as u16) << 8) | (buf[7] as u16);
// // //let data = &buf[8..bytes_recv];
// // // Print the parsed response.
// // 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!(" > 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<u8>,size:usize){
// Generate a payload of size lenght
let mut rng = thread_rng();
for _ in 0..(size-8){
payload.push(rng.sample(Alphanumeric) as u8);
}
}

View File

@ -1,84 +0,0 @@
// Create an Ipv4 connection and have it ready to send IPv4 packets
use crate::libs::rp_args::Config;
// use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
use pnet::packet::ipv4;
// use pnet::packet::icmp;
use pnet::packet::Packet;
// use pnet_datalink::{
// self,
// MacAddr
// };
use pnet_transport::{
icmp_packet_iter,
transport_channel,
// TransportChannelType::Layer4,
// TransportProtocol::Ipv4,
TransportChannelType::Layer3,
TransportReceiver,
TransportSender,
};
// use pnet::packet::ip::{
// IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
// };
use std::net::{
// IpAddr,
Ipv4Addr
};
use pnet::packet::icmp::{
echo_reply::EchoReplyPacket,
// echo_request::MutableEchoRequestPacket, IcmpTypes,
};
// Takes a config structure and generate a wrapper Packet, note that it will need to be filled with a payload
pub fn create_ethernet_packet<'a>(config: &'a Config) -> ipv4::MutableIpv4Packet<'a>{
// The total length is dependent on the packed sent
let size_tot: u16 = (config.ihl*4 + config.packet_size).into(); //84; // ihl*4+packet_size
let binding = vec![0; size_tot as usize];
let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::owned(binding).unwrap();
// IPv4
ethernet_packet.set_total_length(size_tot);
ethernet_packet.set_version(config.ipv4_version);
ethernet_packet.set_header_length(config.ihl);
ethernet_packet.set_dscp(config.dcsp);
ethernet_packet.set_ecn(config.ecn);
ethernet_packet.set_ttl(config.ttl);
ethernet_packet.set_identification(config.identification);
ethernet_packet.set_flags(config.flags);
ethernet_packet.set_fragment_offset(config.offset);
ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Icmp);//pnet_packet::ip::IpNextHeaderProtocol(6));
ethernet_packet.set_source(config.src_addr.parse::<Ipv4Addr>().expect("Couldn't parse source address"));
ethernet_packet.set_destination(config.dest_addr.parse::<Ipv4Addr>().expect("Couldn't parse destination address"));
ethernet_packet.set_checksum(ipv4::checksum(&ethernet_packet.to_immutable()));
ethernet_packet
}
// Create a transmiter/receiver interface with the send_to, recv methods
pub fn create_interface(_config: &Config) -> (TransportSender,TransportReceiver) {
let (tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("An error occurred when creating transport channel: {}", e),
};
(tx,rx)
}
pub fn send_packet(packet: ipv4::Ipv4Packet, mut interface: TransportSender, dst: Ipv4Addr) -> Result<usize,std::io::Error>{
let res = interface.send_to(packet, std::net::IpAddr::V4(dst));
println!("{:?}",res);
res
}
pub fn recv_packet(mut interface: TransportReceiver){
let mut recv = icmp_packet_iter(&mut interface);
match recv.next() {
Ok((pkt, addr)) => {
let packet = EchoReplyPacket::new(pkt.packet()).unwrap();
println!("{:?}:{}",packet,addr);
}
Err(e) => eprintln!("Error: {} ", e),
}
}

View File

@ -1,25 +1,11 @@
mod libs;
use std::net::{
// IpAddr,
Ipv4Addr
};
use pnet::packet::Packet;
fn main() {
// Parse the command line arguments.
let mut config = libs::parse_all_arguments();
// let icmp_payload = libs::get_payload_from_config(&mut config);
let mut packet = libs::create_ethernet_packet(&config);
let payload = libs::create_icmp_packet(&config, &libs::get_payload_from_str(&config.payload));
packet.set_payload(payload.packet());
let (tx, rx) = libs::create_interface(&config);
let res = libs::send_packet(packet.to_immutable(),tx,config.dest_addr.parse::<Ipv4Addr>().expect("Couldn't parse the IpAddr"));
libs::recv_packet(rx);
match res {
Ok(s) => println!("{:?}", s),
Err(e) => eprintln!("Program exited with errors {:?}",e)
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
}
}
}

279
tests/release_wrapper.rs Normal file
View File

@ -0,0 +1,279 @@
#![cfg(unix)]
use std::{
env, fs,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
process::{Command, Output},
sync::atomic::{AtomicUsize, Ordering},
};
const DEVELOPMENT_ORIGIN: &str = "git@git.dandaedre.com:Archive/rping.git";
const RELEASE_CONFIG: &str = "[[repository.fallbacks]]\n\
origin = \"git@git.dandaedre.com:Archive/rping.git\"\n\
fallback-url = \"https://proxy.dandaedre.com/gitea/Archive/rping\"\n";
static NEXT_TEMPORARY: AtomicUsize = AtomicUsize::new(0);
struct TemporaryDirectory(PathBuf);
impl TemporaryDirectory {
fn new(label: &str) -> Self {
let serial = NEXT_TEMPORARY.fetch_add(1, Ordering::Relaxed);
let path = env::temp_dir().join(format!("rping-{label}-{}-{serial}", std::process::id()));
fs::create_dir(&path).expect("temporary directory should be created");
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TemporaryDirectory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn run(command: &mut Command) -> Output {
command.output().expect("test command should start")
}
fn make_executable(path: &Path) {
let mut permissions = fs::metadata(path)
.expect("executable metadata should be readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(path, permissions).expect("executable mode should be set");
}
fn prepare_repository(temporary: &TemporaryDirectory, version_line: &str) -> (PathBuf, PathBuf) {
let repository = temporary.path().join("repository with spaces");
let fake_bin = temporary.path().join("fake bin");
fs::create_dir(&repository).expect("repository should be created");
fs::create_dir(&fake_bin).expect("fake binary directory should be created");
fs::copy(
Path::new(env!("CARGO_MANIFEST_DIR")).join("release.sh"),
repository.join("release.sh"),
)
.expect("release wrapper should be copied");
make_executable(&repository.join("release.sh"));
fs::copy(
Path::new(env!("CARGO_MANIFEST_DIR")).join("rust-release.toml"),
repository.join("rust-release.toml"),
)
.expect("release configuration should be copied");
fs::write(
repository.join("Cargo.toml"),
format!("[package]\nname = \"rping\"\n{version_line}\n"),
)
.expect("manifest should be written");
assert!(run(Command::new("git")
.arg("-C")
.arg(&repository)
.args(["init", "--quiet"]))
.status
.success());
assert!(run(Command::new("git").arg("-C").arg(&repository).args([
"remote",
"add",
"origin",
DEVELOPMENT_ORIGIN
]))
.status
.success());
(repository, fake_bin)
}
fn install_fake_publisher(fake_bin: &Path) {
let publisher = fake_bin.join("rust_realease");
fs::write(
&publisher,
"#!/bin/sh\n\
[ \"$GITEA_TOKEN\" = test-token ] || exit 91\n\
printf '%s\\n' \"$GITEA_TOKEN\" >\"$OBSERVED_TOKEN\"\n\
printf '%s\\n' \"$@\" >\"$OBSERVED_ARGS\"\n\
git -C \"$1\" remote get-url origin >\"$OBSERVED_ORIGIN\"\n\
cat \"$1/rust-release.toml\" >\"$OBSERVED_CONFIG\"\n\
printf 'fake publisher ran\\n'\n\
exit \"$FAKE_RELEASE_STATUS\"\n",
)
.expect("fake publisher should be written");
make_executable(&publisher);
}
fn wrapper_command(
repository: &Path,
fake_bin: &Path,
token_file: &Path,
temporary: &TemporaryDirectory,
status: i32,
) -> Command {
let mut command = Command::new(repository.join("release.sh"));
command
.arg(token_file)
.env(
"PATH",
format!(
"{}:{}",
fake_bin.display(),
env::var("PATH").expect("PATH should be available")
),
)
.env("FAKE_RELEASE_STATUS", status.to_string())
.env("OBSERVED_TOKEN", temporary.path().join("observed token"))
.env("OBSERVED_ARGS", temporary.path().join("observed args"))
.env("OBSERVED_ORIGIN", temporary.path().join("observed origin"))
.env("OBSERVED_CONFIG", temporary.path().join("observed config"));
command
}
#[test]
fn stable_release_forwards_exact_arguments_without_leaking_token() {
let temporary = TemporaryDirectory::new("stable-release");
let (repository, fake_bin) = prepare_repository(&temporary, "version = \"0.1.0\"");
install_fake_publisher(&fake_bin);
let token_file = temporary.path().join("token file");
fs::write(&token_file, "test-token\nignored-second-line\n").expect("token should be written");
let output = run(
wrapper_command(&repository, &fake_bin, &token_file, &temporary, 0).args([
"--dry-run",
"--tag",
"tag with spaces",
]),
);
assert!(output.status.success());
assert!(!String::from_utf8_lossy(&output.stdout).contains("test-token"));
assert!(!String::from_utf8_lossy(&output.stderr).contains("test-token"));
let arguments = fs::read_to_string(temporary.path().join("observed args"))
.expect("arguments should be recorded");
assert_eq!(
arguments.lines().collect::<Vec<_>>(),
[
repository
.to_str()
.expect("repository path should be UTF-8"),
"--package",
"rping",
"--artifact-format",
"both",
"--dry-run",
"--tag",
"tag with spaces",
]
);
assert!(!arguments.contains("test-token"));
assert_eq!(
fs::read_to_string(temporary.path().join("observed token"))
.expect("token should be recorded"),
"test-token\n"
);
assert_eq!(
fs::read_to_string(temporary.path().join("observed config"))
.expect("config should be recorded"),
RELEASE_CONFIG
);
assert_eq!(
fs::read_to_string(temporary.path().join("observed origin"))
.expect("origin should be recorded")
.trim(),
DEVELOPMENT_ORIGIN
);
assert_eq!(
String::from_utf8(
run(Command::new("git")
.arg("-C")
.arg(&repository)
.args(["remote", "get-url", "origin"]))
.stdout
)
.expect("origin should be UTF-8")
.trim(),
DEVELOPMENT_ORIGIN
);
}
#[test]
fn prerelease_is_added_and_publisher_status_is_preserved() {
let temporary = TemporaryDirectory::new("prerelease");
let (repository, fake_bin) = prepare_repository(&temporary, "version = \"0.2.0-rc.1\"");
install_fake_publisher(&fake_bin);
let token_file = temporary.path().join("token");
fs::write(&token_file, "test-token\n").expect("token should be written");
let output = run(&mut wrapper_command(
&repository,
&fake_bin,
&token_file,
&temporary,
17,
));
assert_eq!(output.status.code(), Some(17));
let arguments = fs::read_to_string(temporary.path().join("observed args"))
.expect("arguments should be recorded");
assert!(arguments.lines().any(|argument| argument == "--prerelease"));
}
#[test]
fn invalid_inputs_fail_before_publishing() {
let temporary = TemporaryDirectory::new("invalid-inputs");
let (repository, fake_bin) = prepare_repository(&temporary, "version = \"0.1.0\"");
install_fake_publisher(&fake_bin);
let wrapper = repository.join("release.sh");
let empty_path = temporary.path().join("empty path");
fs::create_dir(&empty_path).expect("empty PATH directory should be created");
assert!(!run(&mut Command::new(&wrapper)).status.success());
assert!(
!run(Command::new(&wrapper).arg(temporary.path().join("missing token")))
.status
.success()
);
let empty_token = temporary.path().join("empty token");
fs::write(&empty_token, "").expect("empty token should be written");
assert!(!run(Command::new(&wrapper).arg(&empty_token))
.status
.success());
let unreadable_token = temporary.path().join("unreadable token");
fs::write(&unreadable_token, "test-token\n").expect("token should be written");
let mut permissions = fs::metadata(&unreadable_token)
.expect("token metadata should be readable")
.permissions();
permissions.set_mode(0o000);
fs::set_permissions(&unreadable_token, permissions).expect("token mode should be set");
assert!(!run(Command::new(&wrapper).arg(&unreadable_token))
.status
.success());
let valid_token = temporary.path().join("valid token");
fs::write(&valid_token, "test-token\n").expect("token should be written");
let missing_publisher = run(Command::new(&wrapper)
.arg(&valid_token)
.env("PATH", &empty_path));
assert_eq!(missing_publisher.status.code(), Some(2));
assert!(String::from_utf8_lossy(&missing_publisher.stderr)
.contains("rust_realease is not installed"));
fs::write(
repository.join("Cargo.toml"),
"[package]\nname = \"rping\"\n",
)
.expect("manifest without a version should be written");
let unresolved_version = run(&mut wrapper_command(
&repository,
&fake_bin,
&valid_token,
&temporary,
0,
));
assert_eq!(unresolved_version.status.code(), Some(2));
assert!(String::from_utf8_lossy(&unresolved_version.stderr)
.contains("could not determine the selected package version"));
}