crafter 0.3.1

Packet-level network interaction for Rust tools and agents.
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
use std::time::Duration;

use crate::wire::{PacketWire, Sniffer, WireError};
use crate::Packet;

use super::error::{NetError, Result};
use super::reply::{batch_reply_filter, combine_filters};
pub use super::reply::{reply_filter, reply_matches, ReplyMatcher};
use super::send::{validated_interface, SendMode, SendOptions, SendReport, SocketSender};

/// Configuration object for send-and-receive request/reply workflows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendRecv {
    send_options: SendOptions,
    timeout: Duration,
    retries: usize,
    filter: Option<String>,
    capture_limit: usize,
}

impl SendRecv {
    /// Create send/receive options with libcrafter-like defaults.
    pub fn new() -> Self {
        Self {
            send_options: SendOptions::new(),
            timeout: Duration::from_secs(1),
            retries: 3,
            filter: None,
            capture_limit: 64,
        }
    }

    /// Select the interface used for both sending and capture.
    pub fn interface(mut self, interface: impl Into<String>) -> Self {
        self.send_options = self.send_options.interface(interface);
        self
    }

    /// Compatibility alias for [`Self::interface`].
    pub fn iface(self, interface: impl Into<String>) -> Self {
        self.interface(interface)
    }

    /// Set the send mode.
    pub fn mode(mut self, mode: SendMode) -> Self {
        self.send_options = self.send_options.mode(mode);
        self
    }

    /// Require a link-layer send path.
    pub fn link_layer(self) -> Self {
        self.mode(SendMode::LinkLayer)
    }

    /// Require a network-layer send path.
    pub fn network_layer(self) -> Self {
        self.mode(SendMode::NetworkLayer)
    }

    /// Compile and plan the send without transmitting or opening capture.
    pub fn dry_run(mut self) -> Self {
        self.send_options = self.send_options.dry_run();
        self
    }

    /// Enable live send/receive behavior.
    pub fn live(mut self) -> Self {
        self.send_options = self.send_options.live();
        self
    }

    /// Set the per-attempt capture timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the number of send attempts. A zero value is treated as one attempt.
    pub fn retries(mut self, retries: usize) -> Self {
        self.retries = retries;
        self
    }

    /// libcrafter-style singular alias for [`Self::retries`].
    pub fn retry(self, retries: usize) -> Self {
        self.retries(retries)
    }

    /// Add a caller-supplied BPF filter. It is combined with the derived reply filter.
    pub fn filter(mut self, filter: impl Into<String>) -> Self {
        let filter = filter.into();
        self.filter = (!filter.trim().is_empty()).then_some(filter);
        self
    }

    /// Remove any caller-supplied BPF filter.
    pub fn clear_filter(mut self) -> Self {
        self.filter = None;
        self
    }

    /// Set the maximum captured packets inspected per send attempt.
    pub fn capture_limit(mut self, capture_limit: usize) -> Self {
        self.capture_limit = capture_limit.max(1);
        self
    }

    /// Borrow the underlying send options.
    pub const fn send_options(&self) -> &SendOptions {
        &self.send_options
    }

    /// Per-attempt timeout.
    pub const fn timeout_value(&self) -> Duration {
        self.timeout
    }

    /// Configured retry count.
    pub const fn retries_value(&self) -> usize {
        self.retries
    }

    /// Caller-supplied BPF filter, if present.
    pub fn user_filter(&self) -> Option<&str> {
        self.filter.as_deref()
    }

    /// Effective BPF filter used for capture, combining derived and user filters.
    pub fn effective_filter(&self, packet: &Packet) -> Option<String> {
        combine_filters(
            ReplyMatcher::from_packet(packet).reply_filter(),
            self.user_filter(),
        )
    }

    /// Send a packet and return the first matching reply, if any.
    pub fn send_recv(&self, packet: &Packet) -> Result<Option<Packet>> {
        Ok(self.send_recv_report(packet)?.into_reply())
    }

    /// Send a packet and return the detailed send/receive report.
    pub fn send_recv_report(&self, packet: &Packet) -> Result<SendRecvReport> {
        let interface = validated_interface(&self.send_options)?;
        let matcher = ReplyMatcher::from_packet(packet);
        let effective_filter = combine_filters(matcher.reply_filter(), self.user_filter());
        let sender = SocketSender::new(self.send_options.clone());
        let mut send_reports = Vec::new();

        if self.send_options.is_dry_run() {
            send_reports.push(sender.send(packet)?);
            return Ok(SendRecvReport::new(send_reports, None, effective_filter));
        }

        for _ in 0..self.retries.max(1) {
            let mut sniffer = open_pcap_sniffer(
                &interface,
                effective_filter.as_deref(),
                self.timeout,
                self.capture_limit,
            )?;
            send_reports.push(sender.send(packet)?);
            while let Some(reply) = sniffer.next_record().map_err(capture_wire_error)? {
                if matcher.matches(reply.packet()) {
                    return Ok(SendRecvReport::new(
                        send_reports,
                        Some(reply.into_packet()),
                        effective_filter,
                    ));
                }
            }
        }

        Ok(SendRecvReport::new(send_reports, None, effective_filter))
    }
}

impl Default for SendRecv {
    fn default() -> Self {
        Self::new()
    }
}

impl From<&str> for SendRecv {
    fn from(interface: &str) -> Self {
        Self::new().iface(interface)
    }
}

impl From<String> for SendRecv {
    fn from(interface: String) -> Self {
        Self::new().iface(interface)
    }
}

/// Backwards-compatible alias for callers that prefer an options suffix.
pub type SendRecvOptions = SendRecv;

/// Detailed result returned by send/receive operations.
#[derive(Debug, Clone)]
pub struct SendRecvReport {
    send_reports: Vec<SendReport>,
    reply: Option<Packet>,
    effective_filter: Option<String>,
}

impl SendRecvReport {
    /// Create a send/receive report.
    pub fn new(
        send_reports: Vec<SendReport>,
        reply: Option<Packet>,
        effective_filter: Option<String>,
    ) -> Self {
        Self {
            send_reports,
            reply,
            effective_filter,
        }
    }

    /// Per-attempt send reports.
    pub fn send_reports(&self) -> &[SendReport] {
        &self.send_reports
    }

    /// Number of send attempts made.
    pub fn attempts(&self) -> usize {
        self.send_reports.len()
    }

    /// Borrow the matching reply, if one was captured.
    pub fn reply(&self) -> Option<&Packet> {
        self.reply.as_ref()
    }

    /// Consume this report and return the matching reply, if one was captured.
    pub fn into_reply(self) -> Option<Packet> {
        self.reply
    }

    /// Effective capture filter used for this send/receive operation.
    pub fn effective_filter(&self) -> Option<&str> {
        self.effective_filter.as_deref()
    }

    /// Return true when no matching reply was captured.
    pub fn timed_out(&self) -> bool {
        self.reply.is_none()
    }
}

/// Protocol-aware matcher for replies to one request packet.
pub trait PacketSendRecvExt {
    /// Derive a BPF-style filter for likely replies.
    fn reply_filter(&self) -> Result<String>;

    /// Send a packet and return the first matching reply, if any.
    fn send_recv(&self, options: impl Into<SendRecv>) -> Result<Option<Packet>>;

    /// Send a packet and return a detailed send/receive report.
    fn send_recv_report(&self, options: impl Into<SendRecv>) -> Result<SendRecvReport>;
}

impl PacketSendRecvExt for Packet {
    fn reply_filter(&self) -> Result<String> {
        Ok(reply_filter(self).unwrap_or_default())
    }

    fn send_recv(&self, options: impl Into<SendRecv>) -> Result<Option<Packet>> {
        options.into().send_recv(self)
    }

    fn send_recv_report(&self, options: impl Into<SendRecv>) -> Result<SendRecvReport> {
        options.into().send_recv_report(self)
    }
}

/// Send a packet and return the first matching reply, if any.
pub fn send_recv_packet(packet: &Packet, options: impl Into<SendRecv>) -> Result<Option<Packet>> {
    options.into().send_recv(packet)
}

/// Configuration object for send-and-receive workflows over packet collections.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BatchSendRecv {
    send_recv: SendRecv,
    concurrency_limit: usize,
}

impl BatchSendRecv {
    /// Create batch send/receive options with libcrafter-like defaults.
    pub fn new() -> Self {
        Self {
            send_recv: SendRecv::new(),
            concurrency_limit: 64,
        }
    }

    /// Select the interface used for both sending and capture.
    pub fn interface(mut self, interface: impl Into<String>) -> Self {
        self.send_recv = self.send_recv.interface(interface);
        self
    }

    /// Compatibility alias for [`Self::interface`].
    pub fn iface(self, interface: impl Into<String>) -> Self {
        self.interface(interface)
    }

    /// Set the send mode.
    pub fn mode(mut self, mode: SendMode) -> Self {
        self.send_recv = self.send_recv.mode(mode);
        self
    }

    /// Require link-layer send plans.
    pub fn link_layer(self) -> Self {
        self.mode(SendMode::LinkLayer)
    }

    /// Require network-layer send plans.
    pub fn network_layer(self) -> Self {
        self.mode(SendMode::NetworkLayer)
    }

    /// Compile and plan sends without transmitting or opening capture.
    pub fn dry_run(mut self) -> Self {
        self.send_recv = self.send_recv.dry_run();
        self
    }

    /// Enable live send/receive behavior.
    pub fn live(mut self) -> Self {
        self.send_recv = self.send_recv.live();
        self
    }

    /// Set the per-attempt capture timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.send_recv = self.send_recv.timeout(timeout);
        self
    }

    /// Set the number of send attempts per request. A zero value is treated as one attempt.
    pub fn retries(mut self, retries: usize) -> Self {
        self.send_recv = self.send_recv.retries(retries);
        self
    }

    /// libcrafter-style singular alias for [`Self::retries`].
    pub fn retry(self, retries: usize) -> Self {
        self.retries(retries)
    }

    /// Add a caller-supplied BPF filter. It is combined with the derived batch reply filter.
    pub fn filter(mut self, filter: impl Into<String>) -> Self {
        self.send_recv = self.send_recv.filter(filter);
        self
    }

    /// Remove any caller-supplied BPF filter.
    pub fn clear_filter(mut self) -> Self {
        self.send_recv = self.send_recv.clear_filter();
        self
    }

    /// Set the maximum captured packets inspected per request in each batch window.
    pub fn capture_limit(mut self, capture_limit: usize) -> Self {
        self.send_recv = self.send_recv.capture_limit(capture_limit);
        self
    }

    /// Set the maximum number of requests sent before collecting replies.
    pub fn concurrency_limit(mut self, limit: usize) -> Self {
        self.concurrency_limit = limit.max(1);
        self
    }

    /// Borrow the underlying single-request send/receive options.
    pub const fn send_recv_options(&self) -> &SendRecv {
        &self.send_recv
    }

    /// Configured concurrency limit.
    pub const fn concurrency_limit_value(&self) -> usize {
        self.concurrency_limit
    }

    /// Effective BPF filter for the whole request collection.
    pub fn effective_filter(&self, packets: &[Packet]) -> Option<String> {
        combine_filters(batch_reply_filter(packets), self.send_recv.user_filter())
    }

    /// Send every request and collect matching replies in request order.
    pub fn send_recv_all(&self, packets: &[Packet]) -> Result<BatchSendRecvReport> {
        let mut entries = (0..packets.len())
            .map(BatchSendRecvEntry::new)
            .collect::<Vec<_>>();
        let effective_filter = self.effective_filter(packets);

        if packets.is_empty() {
            return Ok(BatchSendRecvReport::new(
                entries,
                effective_filter,
                self.concurrency_limit,
                self.send_recv.retries_value().max(1),
                self.send_recv.timeout_value(),
            ));
        }

        let sender = SocketSender::new(self.send_recv.send_options().clone());

        if self.send_recv.send_options().is_dry_run() {
            for chunk_start in (0..packets.len()).step_by(self.concurrency_limit) {
                let chunk_end = (chunk_start + self.concurrency_limit).min(packets.len());
                for _ in 0..self.send_recv.retries_value().max(1) {
                    for request_index in chunk_start..chunk_end {
                        entries[request_index]
                            .send_reports
                            .push(sender.send(&packets[request_index])?);
                    }
                }
            }
            return Ok(BatchSendRecvReport::new(
                entries,
                effective_filter,
                self.concurrency_limit,
                self.send_recv.retries_value().max(1),
                self.send_recv.timeout_value(),
            ));
        }

        let interface = validated_interface(self.send_recv.send_options())?;
        for chunk_start in (0..packets.len()).step_by(self.concurrency_limit) {
            let chunk_end = (chunk_start + self.concurrency_limit).min(packets.len());
            for _ in 0..self.send_recv.retries_value().max(1) {
                let pending = (chunk_start..chunk_end)
                    .filter(|request_index| entries[*request_index].reply.is_none())
                    .collect::<Vec<_>>();
                if pending.is_empty() {
                    break;
                }

                let mut sniffer = open_pcap_sniffer(
                    &interface,
                    effective_filter.as_deref(),
                    self.send_recv.timeout_value(),
                    self.send_recv
                        .capture_limit
                        .saturating_mul(pending.len().max(1))
                        .max(1),
                )?;
                for request_index in pending.iter().copied() {
                    entries[request_index]
                        .send_reports
                        .push(sender.send(&packets[request_index])?);
                }

                while let Some(reply) = sniffer.next_record().map_err(capture_wire_error)? {
                    let packet = reply.into_packet();
                    assign_reply_to_first_match(&mut entries, packets, packet);
                    if pending
                        .iter()
                        .all(|request_index| entries[*request_index].reply.is_some())
                    {
                        break;
                    }
                }
            }
        }

        Ok(BatchSendRecvReport::new(
            entries,
            effective_filter,
            self.concurrency_limit,
            self.send_recv.retries_value().max(1),
            self.send_recv.timeout_value(),
        ))
    }

    /// Match already-captured candidate replies to requests without sending packets.
    pub fn collect_replies_from_candidates<I>(
        &self,
        requests: &[Packet],
        candidates: I,
    ) -> BatchSendRecvReport
    where
        I: IntoIterator<Item = Packet>,
    {
        let mut entries = (0..requests.len())
            .map(BatchSendRecvEntry::new)
            .collect::<Vec<_>>();

        for candidate in candidates {
            assign_reply_to_first_match(&mut entries, requests, candidate);
        }

        BatchSendRecvReport::new(
            entries,
            self.effective_filter(requests),
            self.concurrency_limit,
            self.send_recv.retries_value().max(1),
            self.send_recv.timeout_value(),
        )
    }
}

impl Default for BatchSendRecv {
    fn default() -> Self {
        Self::new()
    }
}

impl From<SendRecv> for BatchSendRecv {
    fn from(send_recv: SendRecv) -> Self {
        Self::new().with_send_recv(send_recv)
    }
}

impl From<SendOptions> for BatchSendRecv {
    fn from(send_options: SendOptions) -> Self {
        Self::new().with_send_recv(SendRecv::new().with_send_options(send_options))
    }
}

impl From<&str> for BatchSendRecv {
    fn from(interface: &str) -> Self {
        Self::new().iface(interface)
    }
}

impl From<String> for BatchSendRecv {
    fn from(interface: String) -> Self {
        Self::new().iface(interface)
    }
}

impl BatchSendRecv {
    fn with_send_recv(mut self, send_recv: SendRecv) -> Self {
        self.send_recv = send_recv;
        self
    }
}

impl SendRecv {
    fn with_send_options(mut self, send_options: SendOptions) -> Self {
        self.send_options = send_options;
        self
    }
}

/// Per-request result in a batch send/receive operation.
#[derive(Debug, Clone)]
pub struct BatchSendRecvEntry {
    request_index: usize,
    send_reports: Vec<SendReport>,
    reply: Option<Packet>,
}

impl BatchSendRecvEntry {
    fn new(request_index: usize) -> Self {
        Self {
            request_index,
            send_reports: Vec::new(),
            reply: None,
        }
    }

    /// Index of the request packet in the input collection.
    pub const fn request_index(&self) -> usize {
        self.request_index
    }

    /// Per-attempt send reports for this request.
    pub fn send_reports(&self) -> &[SendReport] {
        &self.send_reports
    }

    /// Number of send attempts made for this request.
    pub fn attempts(&self) -> usize {
        self.send_reports.len()
    }

    /// Borrow the matching reply, if one was collected.
    pub fn reply(&self) -> Option<&Packet> {
        self.reply.as_ref()
    }

    /// Consume this entry and return the matching reply, if one was collected.
    pub fn into_reply(self) -> Option<Packet> {
        self.reply
    }

    /// Return true when no matching reply was collected.
    pub fn timed_out(&self) -> bool {
        self.reply.is_none()
    }
}

/// Detailed result returned by batch send/receive operations.
#[derive(Debug, Clone)]
pub struct BatchSendRecvReport {
    entries: Vec<BatchSendRecvEntry>,
    effective_filter: Option<String>,
    concurrency_limit: usize,
    retries: usize,
    timeout: Duration,
}

impl BatchSendRecvReport {
    fn new(
        entries: Vec<BatchSendRecvEntry>,
        effective_filter: Option<String>,
        concurrency_limit: usize,
        retries: usize,
        timeout: Duration,
    ) -> Self {
        Self {
            entries,
            effective_filter,
            concurrency_limit,
            retries,
            timeout,
        }
    }

    /// Per-request reports in the same order as the input packets.
    pub fn entries(&self) -> &[BatchSendRecvEntry] {
        &self.entries
    }

    /// Borrow one entry by request index.
    pub fn entry(&self, request_index: usize) -> Option<&BatchSendRecvEntry> {
        self.entries.get(request_index)
    }

    /// Number of request packets represented by this report.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Return true when no request packets were supplied.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Borrow replies in request order.
    pub fn replies(&self) -> Vec<Option<&Packet>> {
        self.entries.iter().map(BatchSendRecvEntry::reply).collect()
    }

    /// Consume this report and return replies in request order.
    pub fn into_replies(self) -> Vec<Option<Packet>> {
        self.entries
            .into_iter()
            .map(BatchSendRecvEntry::into_reply)
            .collect()
    }

    /// Number of requests with matching replies.
    pub fn reply_count(&self) -> usize {
        self.entries
            .iter()
            .filter(|entry| entry.reply.is_some())
            .count()
    }

    /// Number of requests without matching replies.
    pub fn timed_out_count(&self) -> usize {
        self.entries
            .iter()
            .filter(|entry| entry.reply.is_none())
            .count()
    }

    /// Request indexes that did not receive a matching reply.
    pub fn timed_out_indices(&self) -> Vec<usize> {
        self.entries
            .iter()
            .filter(|entry| entry.reply.is_none())
            .map(BatchSendRecvEntry::request_index)
            .collect()
    }

    /// Effective capture filter used for the batch.
    pub fn effective_filter(&self) -> Option<&str> {
        self.effective_filter.as_deref()
    }

    /// Concurrency limit used by the batch.
    pub const fn concurrency_limit(&self) -> usize {
        self.concurrency_limit
    }

    /// Retry count used by the batch.
    pub const fn retries(&self) -> usize {
        self.retries
    }

    /// Per-attempt timeout used by the batch.
    pub const fn timeout(&self) -> Duration {
        self.timeout
    }
}

/// Extension methods for send/receive packet collections.
pub trait PacketBatchSendRecvExt {
    /// Send every request and collect matching replies in request order.
    fn batch_send_recv(&self, options: impl Into<BatchSendRecv>) -> Result<BatchSendRecvReport>;

    /// Compile and plan every request without transmitting or opening capture.
    fn batch_send_recv_dry_run(
        &self,
        options: impl Into<BatchSendRecv>,
    ) -> Result<BatchSendRecvReport>;
}

impl PacketBatchSendRecvExt for [Packet] {
    fn batch_send_recv(&self, options: impl Into<BatchSendRecv>) -> Result<BatchSendRecvReport> {
        options.into().send_recv_all(self)
    }

    fn batch_send_recv_dry_run(
        &self,
        options: impl Into<BatchSendRecv>,
    ) -> Result<BatchSendRecvReport> {
        options.into().dry_run().send_recv_all(self)
    }
}

/// Send a packet collection and collect replies in one call.
pub fn send_recv_packets(
    packets: &[Packet],
    options: impl Into<BatchSendRecv>,
) -> Result<BatchSendRecvReport> {
    options.into().send_recv_all(packets)
}

fn assign_reply_to_first_match(
    entries: &mut [BatchSendRecvEntry],
    requests: &[Packet],
    candidate: Packet,
) -> bool {
    let Some(entry_index) = entries.iter().position(|entry| {
        entry.reply.is_none() && reply_matches(&requests[entry.request_index], &candidate)
    }) else {
        return false;
    };

    entries[entry_index].reply = Some(candidate);
    true
}

fn open_pcap_sniffer(
    interface: &str,
    filter: Option<&str>,
    timeout: Duration,
    count: usize,
) -> Result<Sniffer> {
    let mut builder = PacketWire::pcap_interface(interface.to_owned()).timeout(timeout);
    if let Some(filter) = filter {
        builder = builder.filter(filter);
    }

    let source = builder
        .open()
        .and_then(PacketWire::source)
        .map_err(capture_wire_error)?;

    Ok(Sniffer::new(source).timeout(timeout).count(count))
}

fn capture_wire_error(err: WireError) -> NetError {
    match err {
        WireError::Pcap(err) => NetError::Capture(err),
        WireError::Packet(err) => NetError::Packet(err),
        WireError::Net(err) => err,
        WireError::Io { operation, source } => NetError::Io { operation, source },
        other => NetError::WireCapture {
            reason: other.to_string(),
        },
    }
}