crafter 0.3.2

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
use std::net::{Ipv4Addr, Ipv6Addr};

use crate::{
    Arp, ArpOperation, Dhcpv4, Dhcpv4ClientIdentifier, Dhcpv4MessageType, Dhcpv6,
    Dhcpv6MessageType, Dns, Icmpv4, Icmpv6, Igmp, Ipv4, Ipv6, Packet, Tcp, Udp, BOOTP_REPLY,
    DHCPV4_CLIENT_PORT, DHCPV4_SERVER_PORT, DHCPV6_CLIENT_PORT, DHCPV6_SERVER_PORT, DNS_PORT,
    ICMPV6_ECHO_REPLY, ICMPV6_ECHO_REQUEST, ICMP_ECHO_REPLY, ICMP_ECHO_REQUEST,
};

pub struct ReplyMatcher {
    request: Packet,
}

impl ReplyMatcher {
    /// Create a matcher from a request packet.
    pub fn from_packet(request: &Packet) -> Self {
        Self {
            request: request.clone(),
        }
    }

    /// Derived BPF-style filter for likely replies.
    pub fn reply_filter(&self) -> Option<String> {
        request_reply_filter(&self.request)
    }

    /// Return true when `candidate` is a typed reply to the request.
    pub fn matches(&self, candidate: &Packet) -> bool {
        reply_matches(&self.request, candidate)
    }
}

/// Derive a BPF-style reply filter for one packet.
pub fn reply_filter(packet: &Packet) -> Option<String> {
    ReplyMatcher::from_packet(packet).reply_filter()
}

/// Return true when `candidate` is a typed reply to `request`.
pub fn reply_matches(request: &Packet, candidate: &Packet) -> bool {
    if request.layer::<Dns>().is_some() {
        return dns_reply_matches(request, candidate);
    }
    if request.layer::<Dhcpv4>().is_some() {
        return dhcpv4_reply_matches(request, candidate);
    }
    if request.layer::<Dhcpv6>().is_some() {
        return dhcpv6_reply_matches(request, candidate);
    }

    arp_reply_matches(request, candidate)
        || icmp_reply_matches(request, candidate)
        || icmpv6_reply_matches(request, candidate)
        || tcp_reply_matches(request, candidate)
        || udp_reply_matches(request, candidate)
}

fn request_reply_filter(packet: &Packet) -> Option<String> {
    if packet.layer::<Dhcpv4>().is_some() {
        return Some(dhcpv4_filter());
    }
    if packet.layer::<Dhcpv6>().is_some() {
        return Some(dhcpv6_filter(packet));
    }
    if packet.layer::<Dns>().is_some() {
        return Some(transport_filter("udp", packet, Some(DNS_PORT), None));
    }
    if let Some(arp) = packet.layer::<Arp>() {
        return Some(arp_filter(arp));
    }
    if packet.layer::<Igmp>().is_some() {
        return Some(igmp_filter(packet));
    }
    if packet.layer::<Icmpv4>().is_some() {
        return Some(protocol_filter("icmp", packet));
    }
    if packet.layer::<Icmpv6>().is_some() {
        return Some(protocol_filter("icmp6", packet));
    }
    if let Some(tcp) = packet.layer::<Tcp>() {
        return Some(transport_filter(
            "tcp",
            packet,
            Some(tcp.destination_port_value()),
            Some(tcp.source_port_value()),
        ));
    }
    if let Some(udp) = packet.layer::<Udp>() {
        return Some(transport_filter(
            "udp",
            packet,
            Some(udp.destination_port_value()),
            Some(udp.source_port_value()),
        ));
    }

    None
}

pub(crate) fn combine_filters(derived: Option<String>, user: Option<&str>) -> Option<String> {
    let user = user.map(str::trim).filter(|filter| !filter.is_empty());
    match (derived, user) {
        (Some(derived), Some(user)) => Some(format!("({derived}) and ({user})")),
        (Some(derived), None) => Some(derived),
        (None, Some(user)) => Some(user.to_string()),
        (None, None) => None,
    }
}

pub(crate) fn batch_reply_filter(packets: &[Packet]) -> Option<String> {
    let mut filters = Vec::new();
    for packet in packets {
        let Some(filter) = ReplyMatcher::from_packet(packet).reply_filter() else {
            continue;
        };
        if !filters.iter().any(|existing| existing == &filter) {
            filters.push(filter);
        }
    }

    match filters.len() {
        0 => None,
        1 => filters.pop(),
        _ => Some(
            filters
                .into_iter()
                .map(|filter| format!("({filter})"))
                .collect::<Vec<_>>()
                .join(" or "),
        ),
    }
}

fn dhcpv4_filter() -> String {
    format!("udp and src port {DHCPV4_SERVER_PORT} and dst port {DHCPV4_CLIENT_PORT}")
}

fn dhcpv6_filter(packet: &Packet) -> String {
    let mut terms = vec!["udp".to_string()];
    if let Some(hosts) = dhcpv6_reversed_ipv6_host_terms(packet) {
        terms.extend(hosts);
    }

    let (source_port, destination_port) = match packet.layer::<Udp>() {
        Some(udp) => (udp.destination_port_value(), udp.source_port_value()),
        None => (DHCPV6_SERVER_PORT, DHCPV6_CLIENT_PORT),
    };
    terms.push(format!("src port {source_port}"));
    terms.push(format!("dst port {destination_port}"));
    terms.join(" and ")
}

fn dhcpv6_reversed_ipv6_host_terms(packet: &Packet) -> Option<Vec<String>> {
    let ipv6 = packet.layer::<Ipv6>()?;
    let source = ipv6.source();
    let destination = ipv6.destination();
    let mut terms = Vec::new();

    if dhcpv6_ipv6_addr_can_be_matched_as_remote(destination) {
        terms.push(format!("src host {destination}"));
    }
    if dhcpv6_ipv6_addr_can_be_matched_as_local(source) {
        terms.push(format!("dst host {source}"));
    }

    (!terms.is_empty()).then_some(terms)
}

fn dhcpv6_ipv6_addr_can_be_matched_as_remote(address: Ipv6Addr) -> bool {
    !address.is_unspecified() && !address.is_multicast()
}

fn dhcpv6_ipv6_addr_can_be_matched_as_local(address: Ipv6Addr) -> bool {
    !address.is_unspecified() && !address.is_multicast()
}

fn arp_filter(arp: &Arp) -> String {
    // A standard Ethernet/IPv4 ARP request asks for the target's hardware
    // address; the reply comes back from that target (now the sender) to the
    // original requester. So `src host <target>` and `dst host <requester>`
    // narrow the capture to the expected reply. Both clauses are only valid
    // when both protocol addresses are genuine IPv4 (protocol type 0x0800,
    // protocol length 4); `sender_ipv4()`/`target_ipv4()` return `None`
    // otherwise. For non-IPv4 or variable protocol-length ARP we deliberately
    // fall back to a bare `arp` filter rather than emit a misleading or
    // half-populated host clause.
    match (arp.target_ipv4(), arp.sender_ipv4()) {
        (Some(target), Some(sender)) => {
            format!("arp and src host {target} and dst host {sender}")
        }
        _ => "arp".to_string(),
    }
}

fn igmp_filter(packet: &Packet) -> String {
    let mut terms = vec!["igmp".to_string()];
    if let Some(ipv4) = packet.layer::<Ipv4>() {
        let source = ipv4.source();
        let destination = ipv4.destination();
        if !source.is_unspecified() && !destination.is_unspecified() {
            terms.push(format!("src host {destination}"));
            terms.push(format!("dst host {source}"));
        }
    }
    terms.join(" and ")
}

fn protocol_filter(protocol: &str, packet: &Packet) -> String {
    let mut terms = vec![protocol.to_string()];
    if let Some(hosts) = reversed_host_terms(packet) {
        terms.extend(hosts);
    }
    terms.join(" and ")
}

fn transport_filter(
    protocol: &str,
    packet: &Packet,
    source_port: Option<u16>,
    destination_port: Option<u16>,
) -> String {
    let mut terms = vec![protocol.to_string()];
    if let Some(hosts) = reversed_host_terms(packet) {
        terms.extend(hosts);
    }
    if let Some(source_port) = source_port {
        terms.push(format!("src port {source_port}"));
    }
    if let Some(destination_port) = destination_port {
        terms.push(format!("dst port {destination_port}"));
    }
    terms.join(" and ")
}

fn reversed_host_terms(packet: &Packet) -> Option<Vec<String>> {
    if let Some(ipv4) = packet.layer::<Ipv4>() {
        Some(vec![
            format!("src host {}", ipv4.destination()),
            format!("dst host {}", ipv4.source()),
        ])
    } else {
        packet.layer::<Ipv6>().map(|ipv6| {
            vec![
                format!("src host {}", ipv6.destination()),
                format!("dst host {}", ipv6.source()),
            ]
        })
    }
}

fn arp_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_arp) = request.layer::<Arp>() else {
        return false;
    };
    let Some(candidate_arp) = candidate.layer::<Arp>() else {
        return false;
    };

    request_arp.opcode_value() == u16::from(ArpOperation::Request)
        && candidate_arp.opcode_value() == u16::from(ArpOperation::Reply)
        && candidate_arp.sender_protocol_bytes_value() == request_arp.target_protocol_bytes_value()
        && candidate_arp.target_protocol_bytes_value() == request_arp.sender_protocol_bytes_value()
        && candidate_arp.target_hardware_bytes_value() == request_arp.sender_hardware_bytes_value()
}

fn icmp_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_icmp) = request.layer::<Icmpv4>() else {
        return false;
    };
    let Some(candidate_icmp) = candidate.layer::<Icmpv4>() else {
        return false;
    };

    request_icmp.icmp_type_value() == ICMP_ECHO_REQUEST
        && candidate_icmp.icmp_type_value() == ICMP_ECHO_REPLY
        && request_icmp.identifier_value() == candidate_icmp.identifier_value()
        && request_icmp.sequence_number_value() == candidate_icmp.sequence_number_value()
        && ip_addresses_are_reversed(request, candidate)
}

fn icmpv6_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_icmp) = request.layer::<Icmpv6>() else {
        return false;
    };
    let Some(candidate_icmp) = candidate.layer::<Icmpv6>() else {
        return false;
    };

    request_icmp.icmp_type_value() == ICMPV6_ECHO_REQUEST
        && candidate_icmp.icmp_type_value() == ICMPV6_ECHO_REPLY
        && request_icmp.identifier_value() == candidate_icmp.identifier_value()
        && request_icmp.sequence_number_value() == candidate_icmp.sequence_number_value()
        && ip_addresses_are_reversed(request, candidate)
}

fn tcp_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_tcp) = request.layer::<Tcp>() else {
        return false;
    };
    let Some(candidate_tcp) = candidate.layer::<Tcp>() else {
        return false;
    };

    candidate_tcp.source_port_value() == request_tcp.destination_port_value()
        && candidate_tcp.destination_port_value() == request_tcp.source_port_value()
        && ip_addresses_are_reversed(request, candidate)
}

fn udp_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_udp) = request.layer::<Udp>() else {
        return false;
    };
    let Some(candidate_udp) = candidate.layer::<Udp>() else {
        return false;
    };

    candidate_udp.source_port_value() == request_udp.destination_port_value()
        && candidate_udp.destination_port_value() == request_udp.source_port_value()
        && ip_addresses_are_reversed(request, candidate)
}

fn dns_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_dns) = request.layer::<Dns>() else {
        return false;
    };
    let Some(candidate_dns) = candidate.layer::<Dns>() else {
        return false;
    };

    !request_dns.is_response()
        && candidate_dns.is_response()
        && request_dns.id_value() == candidate_dns.id_value()
        && udp_optional_reply_matches(request, candidate)
}

fn dhcpv4_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_dhcpv4) = request.layer::<Dhcpv4>() else {
        return false;
    };
    let Some(candidate_dhcpv4) = candidate.layer::<Dhcpv4>() else {
        return false;
    };

    // RFC 2131 section 4.1: a server reply is a BOOTREPLY carrying the same
    // transaction id the client chose. That pairing is the spine of every
    // DHCPv4 exchange (DISCOVER/OFFER, REQUEST/ACK|NAK, and the RFC 4388
    // leasequery families), so it is always required.
    if candidate_dhcpv4.op_value() != BOOTP_REPLY
        || request_dhcpv4.transaction_id_value() != candidate_dhcpv4.transaction_id_value()
    {
        return false;
    }

    if !dhcpv4_transport_reply_matches(request, candidate) {
        return false;
    }

    // Beyond xid, match on whatever identifiers the request shape actually
    // carries. Each identifier is only enforced when both sides expose it, so a
    // leasequery-by-IP request (which has no chaddr) still matches its reply
    // while a normal DISCOVER/OFFER also pins the client hardware address.
    dhcpv4_client_hardware_address_matches(request_dhcpv4, candidate_dhcpv4)
        && dhcpv4_client_identifier_matches(request_dhcpv4, candidate_dhcpv4)
        && dhcpv4_server_identifier_matches(request_dhcpv4, candidate_dhcpv4)
        && dhcpv4_relay_giaddr_matches(request_dhcpv4, candidate_dhcpv4)
        && dhcpv4_message_type_matches(request_dhcpv4, candidate_dhcpv4)
}

/// Match the BOOTP `chaddr` fixed field when both messages carry one.
///
/// RFC 2131 section 2: the client hardware address ties a reply to a client.
/// Leasequery-by-IP requests (RFC 4388 section 6.1) leave `chaddr` empty, so the
/// check is skipped when either side has no hardware address rather than
/// rejecting an otherwise-matching reply.
fn dhcpv4_client_hardware_address_matches(request: &Dhcpv4, candidate: &Dhcpv4) -> bool {
    let request_chaddr = request.client_hardware_address_value();
    let candidate_chaddr = candidate.client_hardware_address_value();
    if request_chaddr.is_empty() || candidate_chaddr.is_empty() {
        return true;
    }
    request_chaddr == candidate_chaddr
}

/// Match the client identifier (option 61) when both messages carry one.
///
/// RFC 6842: a server echoes the client identifier unaltered, so when the
/// request supplied one and the reply carries one they must be equal. A
/// malformed identifier on either side surfaces as `None`/error here and is
/// treated as "not comparable", leaving the other identifiers to decide.
fn dhcpv4_client_identifier_matches(request: &Dhcpv4, candidate: &Dhcpv4) -> bool {
    match (
        dhcpv4_client_identifier(request),
        dhcpv4_client_identifier(candidate),
    ) {
        (Some(request_id), Some(candidate_id)) => request_id == candidate_id,
        _ => true,
    }
}

fn dhcpv4_client_identifier(dhcpv4: &Dhcpv4) -> Option<Dhcpv4ClientIdentifier> {
    dhcpv4.client_identifier_value().and_then(Result::ok)
}

/// Match the server identifier (option 53's companion option 54) when relevant.
///
/// RFC 2131 section 4.3.2: a client unicasts a REQUEST/RELEASE to the server it
/// selected by carrying that server's identifier. When the request names a
/// server identifier and the reply also carries one they must agree; replies
/// that omit it (or requests that never selected a server) are not constrained.
fn dhcpv4_server_identifier_matches(request: &Dhcpv4, candidate: &Dhcpv4) -> bool {
    match (
        request.server_identifier_value(),
        candidate.server_identifier_value(),
    ) {
        (Some(request_server), Some(candidate_server)) => request_server == candidate_server,
        _ => true,
    }
}

/// Match the relay agent address (`giaddr`) when both messages set one.
///
/// RFC 2131 section 4.1: when a relay agent is involved it stamps `giaddr` and
/// the server returns the reply through the same relay, so a non-zero `giaddr`
/// on both sides must match. Directly broadcast/unicast exchanges leave it zero
/// and are not constrained.
fn dhcpv4_relay_giaddr_matches(request: &Dhcpv4, candidate: &Dhcpv4) -> bool {
    let request_giaddr = request.gateway_ip_address_value();
    let candidate_giaddr = candidate.gateway_ip_address_value();
    if request_giaddr == Ipv4Addr::UNSPECIFIED || candidate_giaddr == Ipv4Addr::UNSPECIFIED {
        return true;
    }
    request_giaddr == candidate_giaddr
}

/// Match leasequery request/reply message-type families (RFC 4388/6926/7724).
///
/// A leasequery exchange does not flip op the way address-allocation does; the
/// reply is identified by its message type. When the request is a leasequery
/// family message the candidate must answer with a leasequery reply family
/// message. Non-leasequery requests (DISCOVER, REQUEST, INFORM, ...) impose no
/// message-type constraint here so OFFER/ACK/NAK replies still match.
fn dhcpv4_message_type_matches(request: &Dhcpv4, candidate: &Dhcpv4) -> bool {
    let Some(request_type) = request.message_type_value() else {
        return true;
    };
    if !is_leasequery_request_type(request_type) {
        return true;
    }
    candidate
        .message_type_value()
        .is_some_and(is_leasequery_reply_type)
}

/// True for the leasequery request message types.
///
/// Source: RFC 4388 (DHCPLEASEQUERY), RFC 6926 (DHCPBULKLEASEQUERY), and
/// RFC 7724 (DHCPACTIVELEASEQUERY).
fn is_leasequery_request_type(message_type: Dhcpv4MessageType) -> bool {
    matches!(
        message_type,
        Dhcpv4MessageType::LeaseQuery
            | Dhcpv4MessageType::BulkLeaseQuery
            | Dhcpv4MessageType::ActiveLeaseQuery
    )
}

/// True for the leasequery reply message types.
///
/// Source: RFC 4388 (DHCPLEASEUNASSIGNED/UNKNOWN/ACTIVE), RFC 6926
/// (DHCPLEASEQUERYDONE), and RFC 7724 (DHCPLEASEQUERYSTATUS). A reply may also
/// echo the query type itself, so those are accepted as well.
fn is_leasequery_reply_type(message_type: Dhcpv4MessageType) -> bool {
    matches!(
        message_type,
        Dhcpv4MessageType::LeaseUnassigned
            | Dhcpv4MessageType::LeaseUnknown
            | Dhcpv4MessageType::LeaseActive
            | Dhcpv4MessageType::LeaseQueryDone
            | Dhcpv4MessageType::LeaseQueryStatus
            | Dhcpv4MessageType::LeaseQuery
            | Dhcpv4MessageType::BulkLeaseQuery
            | Dhcpv4MessageType::ActiveLeaseQuery
    )
}

fn dhcpv4_transport_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    match (request.layer::<Udp>(), candidate.layer::<Udp>()) {
        (Some(request_udp), Some(candidate_udp)) => {
            request_udp.source_port_value() == DHCPV4_CLIENT_PORT
                && request_udp.destination_port_value() == DHCPV4_SERVER_PORT
                && candidate_udp.source_port_value() == DHCPV4_SERVER_PORT
                && candidate_udp.destination_port_value() == DHCPV4_CLIENT_PORT
        }
        (None, None) => true,
        _ => false,
    }
}

fn dhcpv6_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    let Some(request_dhcpv6) = request.layer::<Dhcpv6>() else {
        return false;
    };
    let Some(candidate_dhcpv6) = candidate.layer::<Dhcpv6>() else {
        return false;
    };

    dhcpv6_transport_reply_matches(request, candidate)
        && dhcpv6_ipv6_reply_matches(request, candidate)
        && dhcpv6_message_pair_matches(request_dhcpv6, candidate_dhcpv6)
}

fn dhcpv6_message_pair_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    match (request.message_type_value(), candidate.message_type_value()) {
        (Dhcpv6MessageType::RelayForw, Dhcpv6MessageType::RelayRepl) => {
            dhcpv6_relay_reply_matches(request, candidate)
        }
        (Dhcpv6MessageType::RelayForw, _) | (_, Dhcpv6MessageType::RelayRepl) => false,
        _ => {
            request.transaction_id_value() == candidate.transaction_id_value()
                && dhcpv6_client_id_matches(request, candidate)
                && dhcpv6_server_id_matches(request, candidate)
                && dhcpv6_message_type_family_matches(request, candidate)
        }
    }
}

fn dhcpv6_relay_reply_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    if !dhcpv6_relay_header_matches(request, candidate) {
        return false;
    }
    if !dhcpv6_relay_interface_id_matches(request, candidate) {
        return false;
    }

    match (
        request.relayed_message_value(),
        candidate.relayed_message_value(),
    ) {
        (Ok(Some(request_inner)), Ok(Some(candidate_inner))) => {
            dhcpv6_message_pair_matches(&request_inner, &candidate_inner)
        }
        _ => false,
    }
}

fn dhcpv6_relay_header_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    match (request.relay(), candidate.relay()) {
        (Some(request_relay), Some(candidate_relay)) => {
            request_relay.link_address_value() == candidate_relay.link_address_value()
                && request_relay.peer_address_value() == candidate_relay.peer_address_value()
        }
        _ => false,
    }
}

fn dhcpv6_relay_interface_id_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    match (request.interface_id_value(), candidate.interface_id_value()) {
        (Some(request_id), Some(candidate_id)) => request_id == candidate_id,
        (Some(_), None) => false,
        _ => true,
    }
}

fn dhcpv6_client_id_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    match (request.client_id_value(), candidate.client_id_value()) {
        (Some(request_id), Some(candidate_id)) => request_id == candidate_id,
        (Some(_), None) => false,
        _ => true,
    }
}

fn dhcpv6_server_id_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    match (request.server_id_value(), candidate.server_id_value()) {
        (Some(request_id), Some(candidate_id)) => request_id == candidate_id,
        (Some(_), None) => false,
        _ => true,
    }
}

fn dhcpv6_message_type_family_matches(request: &Dhcpv6, candidate: &Dhcpv6) -> bool {
    let candidate_type = candidate.message_type_value();
    match request.message_type_value() {
        Dhcpv6MessageType::Solicit => {
            matches!(
                candidate_type,
                Dhcpv6MessageType::Advertise | Dhcpv6MessageType::Reply
            )
        }
        Dhcpv6MessageType::Request
        | Dhcpv6MessageType::Confirm
        | Dhcpv6MessageType::Renew
        | Dhcpv6MessageType::Rebind
        | Dhcpv6MessageType::Release
        | Dhcpv6MessageType::Decline
        | Dhcpv6MessageType::InformationRequest => {
            matches!(candidate_type, Dhcpv6MessageType::Reply)
        }
        Dhcpv6MessageType::Reconfigure => {
            dhcpv6_reconfigure_response_type_matches(request, candidate_type)
        }
        Dhcpv6MessageType::LeaseQuery => {
            matches!(candidate_type, Dhcpv6MessageType::LeaseQueryReply)
        }
        Dhcpv6MessageType::ActiveLeaseQuery => {
            matches!(
                candidate_type,
                Dhcpv6MessageType::LeaseQueryData | Dhcpv6MessageType::LeaseQueryDone
            )
        }
        Dhcpv6MessageType::ReconfigureRequest => {
            matches!(candidate_type, Dhcpv6MessageType::ReconfigureReply)
        }
        Dhcpv6MessageType::Dhcpv4Query => {
            matches!(candidate_type, Dhcpv6MessageType::Dhcpv4Response)
        }
        Dhcpv6MessageType::BndUpd => matches!(candidate_type, Dhcpv6MessageType::BndReply),
        Dhcpv6MessageType::PoolReq => matches!(candidate_type, Dhcpv6MessageType::PoolResp),
        Dhcpv6MessageType::UpdReq | Dhcpv6MessageType::UpdReqAll => {
            matches!(candidate_type, Dhcpv6MessageType::UpdDone)
        }
        Dhcpv6MessageType::Connect => {
            matches!(candidate_type, Dhcpv6MessageType::ConnectReply)
        }
        Dhcpv6MessageType::AddrRegInform => {
            matches!(candidate_type, Dhcpv6MessageType::AddrRegReply)
        }
        _ => false,
    }
}

fn dhcpv6_reconfigure_response_type_matches(
    request: &Dhcpv6,
    candidate_type: Dhcpv6MessageType,
) -> bool {
    match request.reconfigure_message_value() {
        Ok(Some(requested_type)) => candidate_type == requested_type,
        _ => matches!(
            candidate_type,
            Dhcpv6MessageType::Renew
                | Dhcpv6MessageType::Rebind
                | Dhcpv6MessageType::InformationRequest
        ),
    }
}

fn dhcpv6_transport_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    match (request.layer::<Udp>(), candidate.layer::<Udp>()) {
        (Some(request_udp), Some(candidate_udp)) => {
            request_udp.source_port_value() == candidate_udp.destination_port_value()
                && request_udp.destination_port_value() == candidate_udp.source_port_value()
                && dhcpv6_udp_port_pair_is_valid(
                    request_udp.source_port_value(),
                    request_udp.destination_port_value(),
                )
                && dhcpv6_udp_port_pair_is_valid(
                    candidate_udp.source_port_value(),
                    candidate_udp.destination_port_value(),
                )
        }
        (None, None) => true,
        _ => false,
    }
}

fn dhcpv6_udp_port_pair_is_valid(source_port: u16, destination_port: u16) -> bool {
    matches!(
        (source_port, destination_port),
        (DHCPV6_CLIENT_PORT, DHCPV6_SERVER_PORT)
            | (DHCPV6_SERVER_PORT, DHCPV6_CLIENT_PORT)
            | (DHCPV6_SERVER_PORT, DHCPV6_SERVER_PORT)
    )
}

fn dhcpv6_ipv6_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    match (request.layer::<Ipv6>(), candidate.layer::<Ipv6>()) {
        (Some(request_ip), Some(candidate_ip)) => {
            let request_source = request_ip.source();
            let request_destination = request_ip.destination();
            if dhcpv6_ipv6_addr_can_be_matched_as_local(request_source)
                && candidate_ip.destination() != request_source
            {
                return false;
            }
            if dhcpv6_ipv6_addr_can_be_matched_as_remote(request_destination)
                && candidate_ip.source() != request_destination
            {
                return false;
            }
            true
        }
        (None, None) => true,
        _ => false,
    }
}

fn udp_optional_reply_matches(request: &Packet, candidate: &Packet) -> bool {
    match (request.layer::<Udp>(), candidate.layer::<Udp>()) {
        (Some(_), Some(_)) => udp_reply_matches(request, candidate),
        (None, None) => ip_addresses_are_reversed(request, candidate),
        _ => false,
    }
}

fn ip_addresses_are_reversed(request: &Packet, candidate: &Packet) -> bool {
    ipv4_addresses_are_reversed(request, candidate)
        && ipv6_addresses_are_reversed(request, candidate)
}

fn ipv4_addresses_are_reversed(request: &Packet, candidate: &Packet) -> bool {
    match (request.layer::<Ipv4>(), candidate.layer::<Ipv4>()) {
        (Some(request_ip), Some(candidate_ip)) => {
            candidate_ip.source() == request_ip.destination()
                && candidate_ip.destination() == request_ip.source()
        }
        (None, None) => true,
        _ => false,
    }
}

fn ipv6_addresses_are_reversed(request: &Packet, candidate: &Packet) -> bool {
    match (request.layer::<Ipv6>(), candidate.layer::<Ipv6>()) {
        (Some(request_ip), Some(candidate_ip)) => {
            candidate_ip.source() == request_ip.destination()
                && candidate_ip.destination() == request_ip.source()
        }
        (None, None) => true,
        _ => false,
    }
}