pcap-toolkit 0.1.0

A blazing-fast, data-oriented PCAP manipulation, routing, and transformation tool written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Live packet replay onto a real network interface.
//!
//! Reads packets from a PCAP file and injects them via a raw `AF_PACKET`
//! socket (Linux only) using the original or a scaled inter-packet timing.
//!
//! ## Timing modes
//!
//! | CLI flag               | Behaviour                                        |
//! |------------------------|--------------------------------------------------|
//! | *(none)*               | Real-time: honour original inter-packet gaps     |
//! | `--speed 2.0`          | Multiplier: replay 2× faster than original       |
//! | `--speed max`          | No delay — transmit as fast as the NIC allows    |
//! | `--pps 4096`           | Fixed rate: 4 096 packets/second, ignores gaps   |
//!
//! ## Permissions
//!
//! Raw sockets require `CAP_NET_RAW`. If the capability is absent the function
//! returns [`ReplayError::PermissionDenied`] with a remediation hint.

use std::path::Path;
use std::time::{Duration, Instant};

use crate::bpf::BpfExpr;
use crate::error::ReplayError;
use crate::filter::{Filter, PacketMeta};
use crate::pcap;

// ── Public types ─────────────────────────────────────────────────────────────

/// How to pace packet transmission during replay.
#[derive(Debug, Clone)]
pub enum ReplaySpeed {
    /// Honour original inter-packet timing (the default).
    RealTime,
    /// Scale timing by a multiplier: `>1.0` = faster, `<1.0` = slower.
    Multiplier(f64),
    /// Send as fast as possible with no delay between packets.
    Max,
    /// Fixed transmission rate in packets per second (ignores original timing).
    Pps(u64),
}

impl ReplaySpeed {
    /// Parse a speed string.
    ///
    /// | Input  | Result                    |
    /// |--------|---------------------------|
    /// | `"max"` | [`ReplaySpeed::Max`]     |
    /// | `"1.0"` | [`ReplaySpeed::RealTime`] |
    /// | `"2.5"` | [`ReplaySpeed::Multiplier(2.5)`] |
    ///
    /// Returns `None` for non-positive numbers or unrecognised strings.
    pub fn parse(s: &str) -> Option<Self> {
        if s.eq_ignore_ascii_case("max") {
            return Some(ReplaySpeed::Max);
        }
        s.parse::<f64>().ok().filter(|&f| f > 0.0).map(|f| {
            if (f - 1.0).abs() < f64::EPSILON {
                ReplaySpeed::RealTime
            } else {
                ReplaySpeed::Multiplier(f)
            }
        })
    }
}

/// Options for [`replay_file`].
pub struct ReplayOptions {
    /// Network interface names to transmit on (e.g. `["eth0", "eth1"]`).
    /// Each packet is sent to all interfaces (fan-out).
    pub interfaces: Vec<String>,
    /// Packet pacing mode.
    pub speed: ReplaySpeed,
    /// Structured filter applied before sending each packet.
    pub filter: Filter,
    /// BPF expression filter AND-ed with `filter`. `None` = no BPF filter.
    pub bpf_filter: Option<BpfExpr>,
}

/// Summary returned by [`replay_file`] on success.
#[derive(Debug)]
pub struct ReplayReport {
    /// Total packets transmitted.
    pub packets_sent: u64,
    /// Total bytes transmitted (sum of captured lengths).
    pub bytes_sent: u64,
}

// ── Public entry point ───────────────────────────────────────────────────────

/// Replay all packets from `input` onto the network interface in `opts`.
///
/// Packets are read in file order (sort first with `sort_file` if needed).
/// Filters are applied before each packet is sent.
///
/// # Errors
/// Returns [`ReplayError`] on I/O failure, missing `CAP_NET_RAW`,
/// unknown interface name, or if the platform is not Linux.
pub fn replay_file(input: &Path, opts: &ReplayOptions) -> Result<ReplayReport, ReplayError> {
    platform::replay_impl(input, opts)
}

// ── Timing helper (platform-independent) ─────────────────────────────────────

/// Compute how long to wait before sending the next packet.
///
/// - `speed`        — pacing mode
/// - `pkt_ts_ns`    — original capture timestamp of this packet (nanoseconds)
/// - `first_ts_ns`  — mutable slot that stores the first packet's timestamp
/// - `sent_count`   — number of packets already sent (used for PPS mode)
/// - `start_time`   — wall-clock instant when the first packet was sent
pub(crate) fn compute_delay(
    speed: &ReplaySpeed,
    pkt_ts_ns: u64,
    first_ts_ns: &mut Option<u64>,
    sent_count: u64,
    start_time: &Instant,
) -> Duration {
    match speed {
        ReplaySpeed::Max => Duration::ZERO,

        ReplaySpeed::Pps(pps) => {
            if *pps == 0 {
                return Duration::ZERO;
            }
            // Packet N should go out at N * (1_000_000_000 / pps) ns after start.
            let target_ns = sent_count * 1_000_000_000 / pps;
            let elapsed_ns = start_time.elapsed().as_nanos() as u64;
            if target_ns > elapsed_ns {
                Duration::from_nanos(target_ns - elapsed_ns)
            } else {
                Duration::ZERO
            }
        }

        ReplaySpeed::RealTime | ReplaySpeed::Multiplier(_) => {
            // Measure the gap from the first packet's timestamp, then scale.
            let first = *first_ts_ns.get_or_insert(pkt_ts_ns);
            let capture_gap_ns = pkt_ts_ns.saturating_sub(first);
            let scaled_gap_ns = match speed {
                ReplaySpeed::Multiplier(f) => (capture_gap_ns as f64 / f) as u64,
                _ => capture_gap_ns,
            };
            let elapsed_ns = start_time.elapsed().as_nanos() as u64;
            if scaled_gap_ns > elapsed_ns {
                Duration::from_nanos(scaled_gap_ns - elapsed_ns)
            } else {
                Duration::ZERO
            }
        }
    }
}

// ── Platform implementations ─────────────────────────────────────────────────

#[cfg(target_os = "linux")]
mod platform {
    use socket2::{Domain, Protocol, Socket, Type};

    use super::*;

    /// `AF_PACKET` address-family constant (Linux, all architectures).
    const AF_PACKET: i32 = 17;

    /// `ETH_P_ALL` in network byte order — required by `AF_PACKET` sockets.
    ///
    /// `htons(0x0003)` = `0x0300` = 768 on little-endian (the overwhelming
    /// majority of Linux systems). Computed portably with `to_be()`.
    const ETH_P_ALL_NBO: i32 = (0x0003_u16.to_be()) as i32;

    /// Mirror of `struct sockaddr_ll` from `<linux/if_packet.h>`.
    ///
    /// `AF_PACKET` bind requires this address structure; `socket2` has no
    /// built-in constructor for it, so we construct it directly.
    #[repr(C)]
    struct SockAddrLl {
        sll_family: u16,
        sll_protocol: u16,
        sll_ifindex: i32,
        sll_hatype: u16,
        sll_pkttype: u8,
        sll_halen: u8,
        sll_addr: [u8; 8],
    }

    /// Read the interface index from `/sys/class/net/<iface>/ifindex`.
    ///
    /// This avoids a `libc` dependency while remaining reliable on any
    /// Linux system (the sysfs entry is always present for real interfaces).
    fn read_ifindex(iface: &str) -> Result<i32, ReplayError> {
        let path = format!("/sys/class/net/{iface}/ifindex");
        let s = std::fs::read_to_string(&path)
            .map_err(|_| ReplayError::UnknownInterface(iface.to_owned()))?;
        s.trim()
            .parse::<i32>()
            .map_err(|_| ReplayError::UnknownInterface(iface.to_owned()))
    }

    /// Open an `AF_PACKET / SOCK_RAW` socket and bind it to `iface`.
    fn open_raw_socket(iface: &str) -> Result<Socket, ReplayError> {
        let sock = Socket::new(
            Domain::from(AF_PACKET),
            Type::RAW,
            Some(Protocol::from(ETH_P_ALL_NBO)),
        )
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::PermissionDenied {
                ReplayError::PermissionDenied(
                    "creating a raw AF_PACKET socket requires CAP_NET_RAW; \
                     run as root or: sudo setcap cap_net_raw+eip <binary>"
                        .to_owned(),
                )
            } else {
                ReplayError::Io(e)
            }
        })?;

        let ifindex = read_ifindex(iface)?;

        // Build sockaddr_ll and bind so that all outgoing packets use this NIC.
        // try_init returns (T, SockAddr) where T is the closure's Ok type.
        let (_, addr) = unsafe {
            socket2::SockAddr::try_init(|storage, len| {
                let sa = &mut *storage.cast::<SockAddrLl>();
                sa.sll_family = AF_PACKET as u16;
                sa.sll_protocol = 0x0003_u16.to_be(); // ETH_P_ALL in NBO
                sa.sll_ifindex = ifindex;
                sa.sll_hatype = 0;
                sa.sll_pkttype = 0;
                sa.sll_halen = 0;
                sa.sll_addr = [0u8; 8];
                *len = std::mem::size_of::<SockAddrLl>() as _;
                Ok(())
            })
        }
        .map_err(ReplayError::Io)?;

        sock.bind(&addr).map_err(|e| {
            if e.kind() == std::io::ErrorKind::PermissionDenied {
                ReplayError::PermissionDenied("binding raw socket requires CAP_NET_RAW".to_owned())
            } else {
                ReplayError::Io(e)
            }
        })?;

        Ok(sock)
    }

    pub fn replay_impl(input: &Path, opts: &ReplayOptions) -> Result<ReplayReport, ReplayError> {
        let sockets: Vec<Socket> = opts
            .interfaces
            .iter()
            .map(|iface| open_raw_socket(iface))
            .collect::<Result<_, _>>()?;

        let has_filter = !opts.filter.is_empty() || opts.bpf_filter.is_some();

        let iter =
            pcap::open_with_payload(input).map_err(|e| ReplayError::PcapParse(e.to_string()))?;

        let mut packets_sent: u64 = 0;
        let mut bytes_sent: u64 = 0;
        let mut first_ts_ns: Option<u64> = None;
        let start_time = Instant::now();

        for result in iter {
            let pkt = result.map_err(|e| ReplayError::PcapParse(e.to_string()))?;

            if has_filter {
                let meta = PacketMeta::from_packet(
                    pkt.info.timestamp_ns,
                    pkt.info.captured_len,
                    &pkt.data,
                );
                let struct_pass = opts.filter.is_empty() || opts.filter.matches(&meta);
                let bpf_pass = opts
                    .bpf_filter
                    .as_ref()
                    .map(|b| b.eval(&meta))
                    .unwrap_or(true);
                if !struct_pass || !bpf_pass {
                    continue;
                }
            }

            let delay = compute_delay(
                &opts.speed,
                pkt.info.timestamp_ns,
                &mut first_ts_ns,
                packets_sent,
                &start_time,
            );
            if !delay.is_zero() {
                std::thread::sleep(delay);
            }

            for sock in &sockets {
                sock.send(&pkt.data).map_err(ReplayError::Io)?;
            }
            packets_sent += 1;
            bytes_sent += pkt.data.len() as u64;
        }

        Ok(ReplayReport {
            packets_sent,
            bytes_sent,
        })
    }
}

#[cfg(not(target_os = "linux"))]
mod platform {
    use super::*;

    pub fn replay_impl(_input: &Path, _opts: &ReplayOptions) -> Result<ReplayReport, ReplayError> {
        Err(ReplayError::NotSupported)
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_replay_speed_parse_max() {
        assert!(matches!(ReplaySpeed::parse("max"), Some(ReplaySpeed::Max)));
        assert!(matches!(ReplaySpeed::parse("MAX"), Some(ReplaySpeed::Max)));
        assert!(matches!(ReplaySpeed::parse("Max"), Some(ReplaySpeed::Max)));
    }

    #[test]
    fn test_replay_speed_parse_real_time() {
        assert!(matches!(
            ReplaySpeed::parse("1.0"),
            Some(ReplaySpeed::RealTime)
        ));
        assert!(matches!(
            ReplaySpeed::parse("1"),
            Some(ReplaySpeed::RealTime)
        ));
    }

    #[test]
    fn test_replay_speed_parse_multiplier() {
        assert!(matches!(
            ReplaySpeed::parse("2.0"),
            Some(ReplaySpeed::Multiplier(f)) if (f - 2.0).abs() < 1e-9
        ));
        assert!(matches!(
            ReplaySpeed::parse("0.5"),
            Some(ReplaySpeed::Multiplier(f)) if (f - 0.5).abs() < 1e-9
        ));
        assert!(matches!(
            ReplaySpeed::parse("10"),
            Some(ReplaySpeed::Multiplier(f)) if (f - 10.0).abs() < 1e-9
        ));
    }

    #[test]
    fn test_replay_speed_parse_invalid() {
        assert!(ReplaySpeed::parse("").is_none());
        assert!(ReplaySpeed::parse("abc").is_none());
        assert!(ReplaySpeed::parse("-1.0").is_none());
        assert!(ReplaySpeed::parse("0").is_none());
        assert!(ReplaySpeed::parse("0.0").is_none());
    }

    #[test]
    fn test_compute_delay_max_is_zero() {
        let mut first_ts = None;
        let start = Instant::now();
        let d = compute_delay(&ReplaySpeed::Max, 1_000_000_000, &mut first_ts, 0, &start);
        assert_eq!(d, Duration::ZERO);
    }

    #[test]
    fn test_compute_delay_real_time_first_packet_is_zero() {
        let mut first_ts = None;
        let start = Instant::now();
        let d = compute_delay(
            &ReplaySpeed::RealTime,
            1_000_000_000,
            &mut first_ts,
            0,
            &start,
        );
        // First packet: gap = 0, so delay must be zero (or negligible).
        assert!(d < Duration::from_millis(10));
    }

    #[test]
    fn test_compute_delay_pps_first_packet_is_zero() {
        let mut first_ts = None;
        let start = Instant::now();
        // Packet 0 at 1000 pps: target = 0 * 1e9 / 1000 = 0 ns.
        let d = compute_delay(&ReplaySpeed::Pps(1000), 0, &mut first_ts, 0, &start);
        assert_eq!(d, Duration::ZERO);
    }

    #[test]
    fn test_compute_delay_pps_zero_is_safe() {
        let mut first_ts = None;
        let start = Instant::now();
        let d = compute_delay(&ReplaySpeed::Pps(0), 0, &mut first_ts, 5, &start);
        assert_eq!(d, Duration::ZERO);
    }

    /// On Linux: verify that a nonexistent interface produces the right error.
    /// The test passes whether it fails at socket creation (PermissionDenied —
    /// no CAP_NET_RAW in CI) or at interface lookup (UnknownInterface).
    #[cfg(target_os = "linux")]
    #[test]
    fn test_replay_unknown_interface_returns_error() {
        use crate::filter::Filter;

        let opts = ReplayOptions {
            interfaces: vec!["nonexistent_iface_xyz999".to_owned()],
            speed: ReplaySpeed::Max,
            filter: Filter::default(),
            bpf_filter: None,
        };

        // Build a minimal valid PCAP (header only, no packets).
        let mut pcap_bytes = Vec::new();
        pcap_bytes.extend_from_slice(&0xa1b2_c3d4u32.to_le_bytes()); // magic
        pcap_bytes.extend_from_slice(&2u16.to_le_bytes()); // version major
        pcap_bytes.extend_from_slice(&4u16.to_le_bytes()); // version minor
        pcap_bytes.extend_from_slice(&0i32.to_le_bytes()); // thiszone
        pcap_bytes.extend_from_slice(&0u32.to_le_bytes()); // sigfigs
        pcap_bytes.extend_from_slice(&65535u32.to_le_bytes()); // snaplen
        pcap_bytes.extend_from_slice(&1i32.to_le_bytes()); // network (Ethernet)

        let path = std::env::temp_dir().join("replay_test_no_iface.pcap");
        std::fs::write(&path, &pcap_bytes).unwrap();

        let err = replay_file(&path, &opts).unwrap_err();
        assert!(
            matches!(
                err,
                ReplayError::PermissionDenied(_) | ReplayError::UnknownInterface(_)
            ),
            "expected PermissionDenied or UnknownInterface, got: {err}"
        );
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn test_replay_not_supported_on_non_linux() {
        use crate::filter::Filter;

        let opts = ReplayOptions {
            interfaces: vec!["eth0".to_owned()],
            speed: ReplaySpeed::RealTime,
            filter: Filter::default(),
            bpf_filter: None,
        };
        let path = std::path::Path::new("/dev/null");
        assert!(matches!(
            replay_file(path, &opts),
            Err(ReplayError::NotSupported)
        ));
    }
}