nex-packet 0.26.0

Cross-platform packet parsing and building library. Provides low-level packet handling. Part of nex project.
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! An ICMP packet abstraction.
use crate::checksum::{ChecksumMode, ChecksumState};
use crate::ipv4::IPV4_HEADER_LEN;
use crate::{
    ethernet::ETHERNET_HEADER_LEN,
    packet::{MutablePacket, Packet},
};
use bytes::{BufMut, Bytes, BytesMut};
use nex_core::bitfield::u16be;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// ICMP Common Header Length.
pub const ICMP_COMMON_HEADER_LEN: usize = 4;
/// ICMPv4 Header Length. Including the common header (4 bytes) and the type specific header (4 bytes).
pub const ICMPV4_HEADER_LEN: usize = 8;
/// ICMPv4 Minimum Packet Length.
pub const ICMPV4_PACKET_LEN: usize = ETHERNET_HEADER_LEN + IPV4_HEADER_LEN + ICMPV4_HEADER_LEN;
/// ICMPv4 IP Packet Length.
pub const ICMPV4_IP_PACKET_LEN: usize = IPV4_HEADER_LEN + ICMPV4_HEADER_LEN;

/// Represents the "ICMP type" header field.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum IcmpType {
    EchoReply,
    DestinationUnreachable,
    SourceQuench,
    RedirectMessage,
    EchoRequest,
    RouterAdvertisement,
    RouterSolicitation,
    TimeExceeded,
    ParameterProblem,
    TimestampRequest,
    TimestampReply,
    InformationRequest,
    InformationReply,
    AddressMaskRequest,
    AddressMaskReply,
    Traceroute,
    DatagramConversionError,
    MobileHostRedirect,
    IPv6WhereAreYou,
    IPv6IAmHere,
    MobileRegistrationRequest,
    MobileRegistrationReply,
    DomainNameRequest,
    DomainNameReply,
    SKIP,
    Photuris,
    Unknown(u8),
}

impl IcmpType {
    /// Create a new `IcmpType` instance.
    pub fn new(val: u8) -> IcmpType {
        match val {
            0 => IcmpType::EchoReply,
            3 => IcmpType::DestinationUnreachable,
            4 => IcmpType::SourceQuench,
            5 => IcmpType::RedirectMessage,
            8 => IcmpType::EchoRequest,
            9 => IcmpType::RouterAdvertisement,
            10 => IcmpType::RouterSolicitation,
            11 => IcmpType::TimeExceeded,
            12 => IcmpType::ParameterProblem,
            13 => IcmpType::TimestampRequest,
            14 => IcmpType::TimestampReply,
            15 => IcmpType::InformationRequest,
            16 => IcmpType::InformationReply,
            17 => IcmpType::AddressMaskRequest,
            18 => IcmpType::AddressMaskReply,
            30 => IcmpType::Traceroute,
            31 => IcmpType::DatagramConversionError,
            32 => IcmpType::MobileHostRedirect,
            33 => IcmpType::IPv6WhereAreYou,
            34 => IcmpType::IPv6IAmHere,
            35 => IcmpType::MobileRegistrationRequest,
            36 => IcmpType::MobileRegistrationReply,
            37 => IcmpType::DomainNameRequest,
            38 => IcmpType::DomainNameReply,
            39 => IcmpType::SKIP,
            40 => IcmpType::Photuris,
            n => IcmpType::Unknown(n),
        }
    }
    /// Get the name of the ICMP type
    pub fn name(&self) -> &'static str {
        match *self {
            IcmpType::EchoReply => "Echo Reply",
            IcmpType::DestinationUnreachable => "Destination Unreachable",
            IcmpType::SourceQuench => "Source Quench",
            IcmpType::RedirectMessage => "Redirect Message",
            IcmpType::EchoRequest => "Echo Request",
            IcmpType::RouterAdvertisement => "Router Advertisement",
            IcmpType::RouterSolicitation => "Router Solicitation",
            IcmpType::TimeExceeded => "Time Exceeded",
            IcmpType::ParameterProblem => "Parameter Problem",
            IcmpType::TimestampRequest => "Timestamp Request",
            IcmpType::TimestampReply => "Timestamp Reply",
            IcmpType::InformationRequest => "Information Request",
            IcmpType::InformationReply => "Information Reply",
            IcmpType::AddressMaskRequest => "Address Mask Request",
            IcmpType::AddressMaskReply => "Address Mask Reply",
            IcmpType::Traceroute => "Traceroute",
            IcmpType::DatagramConversionError => "Datagram Conversion Error",
            IcmpType::MobileHostRedirect => "Mobile Host Redirect",
            IcmpType::IPv6WhereAreYou => "IPv6 Where Are You",
            IcmpType::IPv6IAmHere => "IPv6 I Am Here",
            IcmpType::MobileRegistrationRequest => "Mobile Registration Request",
            IcmpType::MobileRegistrationReply => "Mobile Registration Reply",
            IcmpType::DomainNameRequest => "Domain Name Request",
            IcmpType::DomainNameReply => "Domain Name Reply",
            IcmpType::SKIP => "SKIP",
            IcmpType::Photuris => "Photuris",
            IcmpType::Unknown(_) => "Unknown",
        }
    }
    pub fn value(&self) -> u8 {
        match *self {
            IcmpType::EchoReply => 0,
            IcmpType::DestinationUnreachable => 3,
            IcmpType::SourceQuench => 4,
            IcmpType::RedirectMessage => 5,
            IcmpType::EchoRequest => 8,
            IcmpType::RouterAdvertisement => 9,
            IcmpType::RouterSolicitation => 10,
            IcmpType::TimeExceeded => 11,
            IcmpType::ParameterProblem => 12,
            IcmpType::TimestampRequest => 13,
            IcmpType::TimestampReply => 14,
            IcmpType::InformationRequest => 15,
            IcmpType::InformationReply => 16,
            IcmpType::AddressMaskRequest => 17,
            IcmpType::AddressMaskReply => 18,
            IcmpType::Traceroute => 30,
            IcmpType::DatagramConversionError => 31,
            IcmpType::MobileHostRedirect => 32,
            IcmpType::IPv6WhereAreYou => 33,
            IcmpType::IPv6IAmHere => 34,
            IcmpType::MobileRegistrationRequest => 35,
            IcmpType::MobileRegistrationReply => 36,
            IcmpType::DomainNameRequest => 37,
            IcmpType::DomainNameReply => 38,
            IcmpType::SKIP => 39,
            IcmpType::Photuris => 40,
            IcmpType::Unknown(n) => n,
        }
    }
}

/// Represents the "ICMP code" header field.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IcmpCode(pub u8);

impl IcmpCode {
    /// Create a new `IcmpCode` instance.
    pub fn new(val: u8) -> IcmpCode {
        IcmpCode(val)
    }
    pub fn value(&self) -> u8 {
        self.0
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IcmpHeader {
    pub icmp_type: IcmpType,
    pub icmp_code: IcmpCode,
    pub checksum: u16,
}

/// ICMP packet representation
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IcmpPacket {
    pub header: IcmpHeader,
    pub payload: Bytes,
}

impl Packet for IcmpPacket {
    type Header = IcmpHeader;

    fn from_buf(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < ICMPV4_HEADER_LEN {
            return None;
        }
        let icmp_type = IcmpType::new(bytes[0]);
        let icmp_code = IcmpCode::new(bytes[1]);
        let checksum = u16::from_be_bytes([bytes[2], bytes[3]]);
        let payload = Bytes::copy_from_slice(&bytes[ICMP_COMMON_HEADER_LEN..]);
        Some(IcmpPacket {
            header: IcmpHeader {
                icmp_type,
                icmp_code,
                checksum,
            },
            payload,
        })
    }
    fn from_bytes(bytes: Bytes) -> Option<Self> {
        Self::from_buf(&bytes)
    }

    fn to_bytes(&self) -> Bytes {
        let mut buf = BytesMut::with_capacity(ICMP_COMMON_HEADER_LEN + self.payload.len());
        buf.put_u8(self.header.icmp_type.value());
        buf.put_u8(self.header.icmp_code.value());
        buf.put_u16(self.header.checksum);
        buf.extend_from_slice(&self.payload);
        buf.freeze()
    }

    fn header(&self) -> Bytes {
        self.to_bytes().slice(..self.header_len())
    }

    fn payload(&self) -> Bytes {
        self.payload.clone()
    }

    fn header_len(&self) -> usize {
        ICMP_COMMON_HEADER_LEN
    }

    fn payload_len(&self) -> usize {
        self.payload.len()
    }

    fn total_len(&self) -> usize {
        self.header_len() + self.payload_len()
    }

    fn into_parts(self) -> (Self::Header, Bytes) {
        (self.header, self.payload)
    }
}

impl IcmpPacket {
    pub fn with_computed_checksum(&self) -> Self {
        let mut pkt = self.clone();
        pkt.header.checksum = checksum(&pkt).into();
        pkt
    }
}

/// Represents a mutable ICMP packet.
pub struct MutableIcmpPacket<'a> {
    buffer: &'a mut [u8],
    checksum: ChecksumState,
}

impl<'a> MutablePacket<'a> for MutableIcmpPacket<'a> {
    type Packet = IcmpPacket;

    fn new(buffer: &'a mut [u8]) -> Option<Self> {
        IcmpPacket::from_buf(buffer)?;
        Some(Self {
            buffer,
            checksum: ChecksumState::new(),
        })
    }

    fn packet(&self) -> &[u8] {
        &*self.buffer
    }

    fn packet_mut(&mut self) -> &mut [u8] {
        &mut *self.buffer
    }

    fn header(&self) -> &[u8] {
        &self.packet()[..ICMP_COMMON_HEADER_LEN]
    }

    fn header_mut(&mut self) -> &mut [u8] {
        let (header, _) = (&mut *self.buffer).split_at_mut(ICMP_COMMON_HEADER_LEN);
        header
    }

    fn payload(&self) -> &[u8] {
        &self.packet()[ICMP_COMMON_HEADER_LEN..]
    }

    fn payload_mut(&mut self) -> &mut [u8] {
        let (_, payload) = (&mut *self.buffer).split_at_mut(ICMP_COMMON_HEADER_LEN);
        payload
    }
}

impl<'a> MutableIcmpPacket<'a> {
    /// Create a mutable ICMP packet without performing validation.
    pub fn new_unchecked(buffer: &'a mut [u8]) -> Self {
        Self {
            buffer,
            checksum: ChecksumState::new(),
        }
    }

    fn raw(&self) -> &[u8] {
        &*self.buffer
    }

    fn raw_mut(&mut self) -> &mut [u8] {
        &mut *self.buffer
    }

    fn after_field_mutation(&mut self) {
        self.checksum.mark_dirty();
        if self.checksum.automatic() {
            let _ = self.recompute_checksum();
        }
    }

    fn write_checksum(&mut self, value: u16) {
        self.raw_mut()[2..4].copy_from_slice(&value.to_be_bytes());
    }

    /// Returns the checksum recalculation mode.
    pub fn checksum_mode(&self) -> ChecksumMode {
        self.checksum.mode()
    }

    /// Sets how checksum updates should be handled.
    pub fn set_checksum_mode(&mut self, mode: ChecksumMode) {
        self.checksum.set_mode(mode);
        if self.checksum.automatic() && self.checksum.is_dirty() {
            let _ = self.recompute_checksum();
        }
    }

    /// Enables automatic checksum recomputation.
    pub fn enable_auto_checksum(&mut self) {
        self.set_checksum_mode(ChecksumMode::Automatic);
    }

    /// Disables automatic checksum recomputation.
    pub fn disable_auto_checksum(&mut self) {
        self.set_checksum_mode(ChecksumMode::Manual);
    }

    /// Returns true if the checksum needs to be recomputed.
    pub fn is_checksum_dirty(&self) -> bool {
        self.checksum.is_dirty()
    }

    /// Marks the checksum as dirty and recomputes it when automatic mode is enabled.
    pub fn mark_checksum_dirty(&mut self) {
        self.checksum.mark_dirty();
        if self.checksum.automatic() {
            let _ = self.recompute_checksum();
        }
    }

    /// Recomputes the checksum for the current packet contents.
    pub fn recompute_checksum(&mut self) -> Option<u16> {
        let checksum = crate::util::checksum(self.raw(), 1) as u16;
        self.write_checksum(checksum);
        self.checksum.clear_dirty();
        Some(checksum)
    }

    /// Returns the current ICMP type field.
    pub fn get_type(&self) -> IcmpType {
        IcmpType::new(self.raw()[0])
    }

    /// Sets the ICMP type field and marks the checksum as dirty.
    pub fn set_type(&mut self, icmp_type: IcmpType) {
        self.raw_mut()[0] = icmp_type.value();
        self.after_field_mutation();
    }

    /// Returns the current ICMP code field.
    pub fn get_code(&self) -> IcmpCode {
        IcmpCode::new(self.raw()[1])
    }

    /// Sets the ICMP code field and marks the checksum as dirty.
    pub fn set_code(&mut self, icmp_code: IcmpCode) {
        self.raw_mut()[1] = icmp_code.value();
        self.after_field_mutation();
    }

    /// Returns the serialized checksum value.
    pub fn get_checksum(&self) -> u16 {
        u16::from_be_bytes([self.raw()[2], self.raw()[3]])
    }

    /// Sets the serialized checksum value and clears the dirty flag.
    pub fn set_checksum(&mut self, checksum: u16) {
        self.write_checksum(checksum);
        self.checksum.clear_dirty();
    }
}

/// Calculates a checksum of an ICMP packet.
pub fn checksum(packet: &IcmpPacket) -> u16be {
    use crate::util;
    util::checksum(&packet.to_bytes(), 1)
}

pub mod echo_request {
    use bytes::Bytes;

    use crate::icmp::{IcmpHeader, IcmpPacket, IcmpType};

    /// Represents the identifier field.
    #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct Identifier(pub u16);

    impl Identifier {
        /// Create a new `Identifier` instance.
        pub fn new(val: u16) -> Identifier {
            Identifier(val)
        }
        pub fn value(&self) -> u16 {
            self.0
        }
    }

    /// Represents the sequence number field.
    #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct SequenceNumber(pub u16);

    impl SequenceNumber {
        /// Create a new `SequenceNumber` instance.
        pub fn new(val: u16) -> SequenceNumber {
            SequenceNumber(val)
        }
        pub fn value(&self) -> u16 {
            self.0
        }
    }

    /// Enumeration of available ICMP codes for "echo reply" ICMP packets. There is actually only
    /// one, since the only valid ICMP code is 0.
    #[allow(non_snake_case)]
    #[allow(non_upper_case_globals)]
    pub mod IcmpCodes {
        use crate::icmp::IcmpCode;
        /// 0 is the only available ICMP code for "echo reply" ICMP packets.
        pub const NoCode: IcmpCode = IcmpCode(0);
    }

    /// Represents an "echo request" ICMP packet.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct EchoRequestPacket {
        pub header: IcmpHeader,
        pub identifier: u16,
        pub sequence_number: u16,
        pub payload: Bytes,
    }

    impl TryFrom<IcmpPacket> for EchoRequestPacket {
        type Error = &'static str;

        fn try_from(pkt: IcmpPacket) -> Result<Self, Self::Error> {
            if pkt.header.icmp_type != IcmpType::EchoRequest {
                return Err("Not an Echo Request");
            }
            if pkt.payload.len() < 4 {
                return Err("Payload too short for Echo Request");
            }

            Ok(Self {
                header: pkt.header,
                identifier: u16::from_be_bytes([pkt.payload[0], pkt.payload[1]]),
                sequence_number: u16::from_be_bytes([pkt.payload[2], pkt.payload[3]]),
                payload: pkt.payload.slice(4..),
            })
        }
    }
}

pub mod echo_reply {
    use bytes::Bytes;

    use crate::icmp::{IcmpHeader, IcmpPacket, IcmpType};

    /// Represent the "identifier" field of the ICMP echo replay header.
    #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct Identifier(pub u16);

    impl Identifier {
        /// Create a new `Identifier` instance.
        pub fn new(val: u16) -> Identifier {
            Identifier(val)
        }
        pub fn value(&self) -> u16 {
            self.0
        }
    }

    /// Represent the "sequence number" field of the ICMP echo replay header.
    #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct SequenceNumber(pub u16);

    impl SequenceNumber {
        /// Create a new `SequenceNumber` instance.
        pub fn new(val: u16) -> SequenceNumber {
            SequenceNumber(val)
        }
        pub fn value(&self) -> u16 {
            self.0
        }
    }

    /// Enumeration of available ICMP codes for ICMP echo replay packets. There is actually only
    /// one, since the only valid ICMP code is 0.
    #[allow(non_snake_case)]
    #[allow(non_upper_case_globals)]
    pub mod IcmpCodes {
        use crate::icmp::IcmpCode;
        /// 0 is the only available ICMP code for "echo reply" ICMP packets.
        pub const NoCode: IcmpCode = IcmpCode(0);
    }

    /// Represents an ICMP echo reply packet.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct EchoReplyPacket {
        pub header: IcmpHeader,
        pub identifier: u16,
        pub sequence_number: u16,
        pub payload: Bytes,
    }

    impl TryFrom<IcmpPacket> for EchoReplyPacket {
        type Error = &'static str;

        fn try_from(pkt: IcmpPacket) -> Result<Self, Self::Error> {
            if pkt.header.icmp_type != IcmpType::EchoReply {
                return Err("Not an Echo Reply");
            }
            if pkt.payload.len() < 4 {
                return Err("Payload too short for Echo Reply");
            }

            Ok(Self {
                header: pkt.header,
                identifier: u16::from_be_bytes([pkt.payload[0], pkt.payload[1]]).into(),
                sequence_number: u16::from_be_bytes([pkt.payload[2], pkt.payload[3]]).into(),
                payload: pkt.payload.slice(4..),
            })
        }
    }
}

pub mod destination_unreachable {
    use bytes::Bytes;

    use crate::icmp::{IcmpHeader, IcmpPacket, IcmpType};

    /// Enumeration of the recognized ICMP codes for "destination unreachable" ICMP packets.
    #[allow(non_snake_case)]
    #[allow(non_upper_case_globals)]
    pub mod IcmpCodes {
        use crate::icmp::IcmpCode;
        /// ICMP code for "destination network unreachable" packet.
        pub const DestinationNetworkUnreachable: IcmpCode = IcmpCode(0);
        /// ICMP code for "destination host unreachable" packet.
        pub const DestinationHostUnreachable: IcmpCode = IcmpCode(1);
        /// ICMP code for "destination protocol unreachable" packet.
        pub const DestinationProtocolUnreachable: IcmpCode = IcmpCode(2);
        /// ICMP code for "destination port unreachable" packet.
        pub const DestinationPortUnreachable: IcmpCode = IcmpCode(3);
        /// ICMP code for "fragmentation required and DFF flag set" packet.
        pub const FragmentationRequiredAndDFFlagSet: IcmpCode = IcmpCode(4);
        /// ICMP code for "source route failed" packet.
        pub const SourceRouteFailed: IcmpCode = IcmpCode(5);
        /// ICMP code for "destination network unknown" packet.
        pub const DestinationNetworkUnknown: IcmpCode = IcmpCode(6);
        /// ICMP code for "destination host unknown" packet.
        pub const DestinationHostUnknown: IcmpCode = IcmpCode(7);
        /// ICMP code for "source host isolated" packet.
        pub const SourceHostIsolated: IcmpCode = IcmpCode(8);
        /// ICMP code for "network administrative prohibited" packet.
        pub const NetworkAdministrativelyProhibited: IcmpCode = IcmpCode(9);
        /// ICMP code for "host administrative prohibited" packet.
        pub const HostAdministrativelyProhibited: IcmpCode = IcmpCode(10);
        /// ICMP code for "network unreachable for this Type Of Service" packet.
        pub const NetworkUnreachableForTOS: IcmpCode = IcmpCode(11);
        /// ICMP code for "host unreachable for this Type Of Service" packet.
        pub const HostUnreachableForTOS: IcmpCode = IcmpCode(12);
        /// ICMP code for "communication administratively prohibited" packet.
        pub const CommunicationAdministrativelyProhibited: IcmpCode = IcmpCode(13);
        /// ICMP code for "host precedence violation" packet.
        pub const HostPrecedenceViolation: IcmpCode = IcmpCode(14);
        /// ICMP code for "precedence cut off in effect" packet.
        pub const PrecedenceCutoffInEffect: IcmpCode = IcmpCode(15);
    }

    /// Represents an "echo request" ICMP packet.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct DestinationUnreachablePacket {
        pub header: IcmpHeader,
        pub unused: u16,
        pub next_hop_mtu: u16,
        pub payload: Bytes,
    }

    impl TryFrom<IcmpPacket> for DestinationUnreachablePacket {
        type Error = &'static str;

        fn try_from(pkt: IcmpPacket) -> Result<Self, Self::Error> {
            if pkt.header.icmp_type != IcmpType::DestinationUnreachable {
                return Err("Not a Destination Unreachable");
            }
            if pkt.payload.len() < 4 {
                return Err("Payload too short for Destination Unreachable");
            }

            Ok(Self {
                header: pkt.header,
                unused: u16::from_be_bytes([pkt.payload[0], pkt.payload[1]]).into(),
                next_hop_mtu: u16::from_be_bytes([pkt.payload[2], pkt.payload[3]]).into(),
                payload: pkt.payload.slice(4..),
            })
        }
    }
}

pub mod time_exceeded {
    use bytes::Bytes;

    use crate::icmp::{IcmpHeader, IcmpPacket, IcmpType};

    /// Enumeration of the recognized ICMP codes for "time exceeded" ICMP packets.
    #[allow(non_snake_case)]
    #[allow(non_upper_case_globals)]
    pub mod IcmpCodes {
        use crate::icmp::IcmpCode;
        /// ICMP code for "time to live exceeded in transit" packet.
        pub const TimeToLiveExceededInTransit: IcmpCode = IcmpCode(0);
        /// ICMP code for "fragment reassembly time exceeded" packet.
        pub const FragmentReasemblyTimeExceeded: IcmpCode = IcmpCode(1);
    }
    /// Represents an "echo request" ICMP packet.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct TimeExceededPacket {
        pub header: IcmpHeader,
        pub unused: u32,
        pub payload: Bytes,
    }

    impl TryFrom<IcmpPacket> for TimeExceededPacket {
        type Error = &'static str;

        fn try_from(pkt: IcmpPacket) -> Result<Self, Self::Error> {
            if pkt.header.icmp_type != IcmpType::TimeExceeded {
                return Err("Not a Time Exceeded");
            }
            if pkt.payload.len() < 4 {
                return Err("Payload too short for Time Exceeded");
            }

            Ok(Self {
                header: pkt.header,
                unused: u32::from_be_bytes([
                    pkt.payload[0],
                    pkt.payload[1],
                    pkt.payload[2],
                    pkt.payload[3],
                ])
                .into(),
                payload: pkt.payload.slice(4..),
            })
        }
    }
}

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

    #[test]
    fn test_echo_request_from_bytes() {
        let raw_bytes = Bytes::from_static(&[
            8, 0, 0x3a, 0xbc, // Type = 8 (Echo Request), Code = 0, Checksum = 0x3abc
            0x04, 0xd2, // Identifier = 0x04d2 (1234)
            0x00, 0x2a, // Sequence = 0x002a (42)
            b'p', b'i', b'n', b'g',
        ]);

        let parsed = IcmpPacket::from_bytes(raw_bytes.clone()).expect("Failed to parse ICMP");
        let echo = echo_request::EchoRequestPacket::try_from(parsed).expect("Failed to downcast");

        assert_eq!(echo.header.icmp_type, IcmpType::EchoRequest);
        assert_eq!(echo.header.icmp_code, IcmpCode(0));
        assert_eq!(echo.header.checksum, 0x3abc);
        assert_eq!(echo.identifier, 1234);
        assert_eq!(echo.sequence_number, 42);
        assert_eq!(echo.payload, Bytes::from_static(b"ping"));
    }

    #[test]
    fn test_echo_reply_roundtrip() {
        let identifier: u16 = 5678;
        let sequence: u16 = 99;
        let payload = Bytes::from_static(b"pong");

        let header = IcmpHeader {
            icmp_type: IcmpType::EchoReply,
            icmp_code: IcmpCode(0),
            checksum: 0,
        };

        let mut buf = BytesMut::with_capacity(4 + payload.len());
        buf.put_u16(identifier);
        buf.put_u16(sequence);
        buf.extend_from_slice(&payload);

        let pkt = IcmpPacket {
            header,
            payload: buf.freeze(),
        }
        .with_computed_checksum();
        let bytes = pkt.to_bytes();

        let parsed = IcmpPacket::from_bytes(bytes.clone()).expect("Failed to parse ICMP");
        let echo = echo_reply::EchoReplyPacket::try_from(parsed).expect("Failed to downcast");

        assert_eq!(echo.identifier, identifier);
        assert_eq!(echo.sequence_number, sequence);
        assert_eq!(echo.payload, payload);
    }

    #[test]
    fn test_destination_unreachable() {
        let unused: u16 = 0;
        let mtu: u16 = 1500;
        let payload = Bytes::from_static(b"bad ip");

        let header = IcmpHeader {
            icmp_type: IcmpType::DestinationUnreachable,
            icmp_code: IcmpCode(3), // Port unreachable
            checksum: 0,
        };

        let mut buf = BytesMut::with_capacity(4 + payload.len());
        buf.put_u16(unused);
        buf.put_u16(mtu);
        buf.extend_from_slice(&payload);

        let pkt = IcmpPacket {
            header,
            payload: buf.freeze(),
        }
        .with_computed_checksum();
        let parsed = IcmpPacket::from_bytes(pkt.to_bytes()).unwrap();
        let unreachable =
            destination_unreachable::DestinationUnreachablePacket::try_from(parsed).unwrap();

        assert_eq!(unreachable.next_hop_mtu, mtu);
        assert_eq!(unreachable.payload, payload);
    }

    #[test]
    fn test_time_exceeded() {
        let unused: u32 = 0xdeadbeef;
        let payload = Bytes::from_static(b"timeout");

        let header = IcmpHeader {
            icmp_type: IcmpType::TimeExceeded,
            icmp_code: IcmpCode(0), // TTL exceeded
            checksum: 0,
        };

        let mut buf = BytesMut::with_capacity(4 + payload.len());
        buf.put_u32(unused);
        buf.extend_from_slice(&payload);

        let pkt = IcmpPacket {
            header,
            payload: buf.freeze(),
        }
        .with_computed_checksum();
        let parsed = IcmpPacket::from_bytes(pkt.to_bytes()).unwrap();
        let exceeded = time_exceeded::TimeExceededPacket::try_from(parsed).unwrap();

        assert_eq!(exceeded.unused, unused);
        assert_eq!(exceeded.payload, payload);
    }

    #[test]
    fn test_mutable_icmp_packet_manual_checksum() {
        let mut raw = [
            8, 0, 0, 0, // type, code, checksum
            0, 1, 0, 1, // identifier, sequence
            b'p', b'i',
        ];

        let mut packet = MutableIcmpPacket::new(&mut raw).expect("mutable icmp");
        packet.set_type(IcmpType::EchoReply);
        assert!(packet.is_checksum_dirty());

        let updated = packet.recompute_checksum().expect("checksum");
        assert_eq!(packet.get_checksum(), updated);

        let frozen = packet.freeze().expect("freeze");
        let expected: u16 = checksum(&frozen).into();
        assert_eq!(packet.get_checksum(), expected);
    }

    #[test]
    fn test_mutable_icmp_packet_auto_checksum() {
        let mut raw = [
            8, 0, 0, 0, // type, code, checksum
            0, 1, 0, 1, // identifier, sequence
            b'p', b'i',
        ];

        let mut packet = MutableIcmpPacket::new(&mut raw).expect("mutable icmp");
        let baseline = packet.recompute_checksum().expect("checksum");
        packet.enable_auto_checksum();
        packet.set_code(IcmpCode::new(1));

        assert!(!packet.is_checksum_dirty());

        let frozen = packet.freeze().expect("freeze");
        let expected: u16 = checksum(&frozen).into();
        assert_ne!(baseline, expected);
        assert_eq!(packet.get_checksum(), expected);
    }
}