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
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
//! IPv4: Internet Protocol v4
//!
//! # References
//!
//! - [RFC 791: Internet protocol][rfc]
//!
//! [rfc]: https://tools.ietf.org/html/rfc791

use core::marker::PhantomData;
use core::ops::Range;
use core::{fmt, u16};

use as_slice::{AsMutSlice, AsSlice};
use byteorder::{ByteOrder, NetworkEndian as NE};
use cast::{u16, u32, usize};
use hash32_derive::Hash32;
use owning_slice::{IntoSliceFrom, Truncate};

use crate::{
    fmt::Hex,
    icmp,
    traits::{UncheckedIndex, UxxExt},
    udp, Invalid, Valid,
};

/* Packet structure */
const VERSION_IHL: usize = 0;
mod ihl {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = 0;
    pub const SIZE: usize = 4;
}
mod version {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = super::ihl::OFFSET + super::ihl::SIZE;
    pub const SIZE: usize = 4;
}

const DSCP_ECN: usize = 1;
mod ecn {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = 0;
    pub const SIZE: usize = 2;
}
mod dscp {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = super::ecn::OFFSET + super::ecn::SIZE;
    pub const SIZE: usize = 6;
}

const TOTAL_LENGTH: Range<usize> = 2..4;
const IDENTIFICATION: Range<usize> = 4..6;

const FLAGS: usize = 6;
mod mf {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = 5;
    pub const SIZE: usize = 1;
}
mod df {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = super::mf::OFFSET + super::mf::SIZE;
    pub const SIZE: usize = 1;
}
mod reserved {
    pub const MASK: u8 = (1 << SIZE) - 1;
    pub const OFFSET: usize = super::df::OFFSET + super::df::SIZE;
    pub const SIZE: usize = 1;
}

const FRAGMENT_OFFSET: Range<usize> = 6..8;
mod fragment_offset {
    pub const MASK: u16 = (1 << SIZE) - 1;
    pub const OFFSET: usize = 0;
    pub const SIZE: usize = 13;
}

const TTL: usize = 8;
const PROTOCOL: usize = 9;
const CHECKSUM: Range<usize> = 10..12;
const SOURCE: Range<usize> = 12..16;
const DESTINATION: Range<usize> = 16..20;

/// Minimum size of the IPv4 header
pub const MIN_HEADER_SIZE: u8 = DESTINATION.end as u8;

/// IPv4 packet
pub struct Packet<BUFFER, CHECKSUM>
where
    BUFFER: AsSlice<Element = u8>,
{
    buffer: BUFFER,
    _checksum: PhantomData<CHECKSUM>,
}

impl<B> Packet<B, Valid>
where
    B: AsSlice<Element = u8> + Truncate<u16>,
{
    /* Constructors */
    /// Parses bytes into an IPv4 packet
    pub fn parse(bytes: B) -> Result<Self, B> {
        if bytes.as_slice().len() < usize(MIN_HEADER_SIZE) {
            // input doesn't contain a complete header
            return Err(bytes);
        }

        let mut packet = Packet {
            buffer: bytes,
            _checksum: PhantomData,
        };

        let header_len = u16(packet.header_len());
        let total_len = packet.get_total_length();

        if header_len < u16(MIN_HEADER_SIZE) {
            // IHL < 5
            Err(packet.buffer)
        } else if total_len < header_len {
            Err(packet.buffer)
        } else if packet.get_version() != 4 {
            Err(packet.buffer)
        } else {
            if packet.verify_header_checksum() {
                if total_len < u16(packet.as_slice().len()).unwrap_or(u16::MAX) {
                    packet.buffer.truncate(total_len);
                    Ok(packet)
                } else {
                    Ok(packet)
                }
            } else {
                Err(packet.buffer)
            }
        }
    }
}

impl<B, C> Packet<B, C>
where
    B: AsSlice<Element = u8>,
{
    /* Getters */
    /// Returns the version field of the header
    pub fn get_version(&self) -> u8 {
        get!(self.header_()[VERSION_IHL], version)
    }

    /// Returns the IHL (Internet Header Length) field of the header
    pub fn get_ihl(&self) -> u8 {
        get!(self.header_()[VERSION_IHL], ihl)
    }

    /// Returns the DSCP (Differentiated Services Code Point) field of the header
    pub fn get_dscp(&self) -> u8 {
        get!(self.header_()[DSCP_ECN], dscp)
    }

    /// Returns the ECN (Explicit Congestion Notification) field of the header
    pub fn get_ecn(&self) -> u8 {
        get!(self.header_()[DSCP_ECN], ecn)
    }

    /// Returns the total length field of the header
    pub fn get_total_length(&self) -> u16 {
        NE::read_u16(&self.header_()[TOTAL_LENGTH])
    }

    /// Returns the length (header + data) of this packet
    ///
    /// This returns the same value as the `get_total_length` method
    pub fn len(&self) -> u16 {
        self.get_total_length()
    }

    /// Returns the identification field of the header
    pub fn get_identification(&self) -> u16 {
        NE::read_u16(&self.header_()[IDENTIFICATION])
    }

    /// Returns the DF (Don't Fragment) field of the header
    pub fn get_df(&self) -> bool {
        get!(self.header_()[FLAGS], df) == 1
    }

    /// Returns the MF (More Fragments) field of the header
    pub fn get_mf(&self) -> bool {
        get!(self.header_()[FLAGS], mf) == 1
    }

    /// Returns the Fragment Offset field of the header
    pub fn get_fragment_offset(&self) -> u16 {
        get!(
            NE::read_u16(&self.header_()[FRAGMENT_OFFSET]),
            fragment_offset
        )
    }

    /// Returns the TTL (Time To Live) field of the header
    pub fn get_ttl(&self) -> u8 {
        self.header_()[TTL]
    }

    /// Returns the protocol field of the header
    pub fn get_protocol(&self) -> Protocol {
        self.header_()[PROTOCOL].into()
    }

    /// Returns the Source (IP address) field of the header
    pub fn get_source(&self) -> Addr {
        unsafe { Addr(*(self.as_slice().as_ptr().add(SOURCE.start) as *const _)) }
    }

    /// Returns the Destination (IP address) field of the header
    pub fn get_destination(&self) -> Addr {
        unsafe { Addr(*(self.as_slice().as_ptr().add(DESTINATION.start) as *const _)) }
    }

    /* Miscellaneous */
    /// Immutable view into the header
    pub fn header(&self) -> &[u8] {
        let end = usize(self.header_len());
        unsafe { &self.as_slice().rt(..end) }
    }

    /// Immutable view into the payload
    pub fn payload(&self) -> &[u8] {
        let start = usize(self.header_len());
        unsafe { &self.as_slice().rf(start..) }
    }

    /// Returns the byte representation of this packet
    pub fn as_bytes(&self) -> &[u8] {
        self.as_slice()
    }

    /* Private */
    fn as_slice(&self) -> &[u8] {
        self.buffer.as_slice()
    }

    fn header_(&self) -> &[u8; MIN_HEADER_SIZE as usize] {
        debug_assert!(self.as_slice().len() >= MIN_HEADER_SIZE as usize);

        unsafe { &*(self.as_slice().as_ptr() as *const _) }
    }

    fn get_header_checksum(&self) -> u16 {
        NE::read_u16(&self.header_()[CHECKSUM])
    }

    fn header_len(&self) -> u8 {
        self.get_ihl() * 4
    }

    fn payload_len(&self) -> u16 {
        self.get_total_length() - u16(self.header_len())
    }

    fn invalidate_header_checksum(self) -> Packet<B, Invalid> {
        Packet {
            buffer: self.buffer,
            _checksum: PhantomData,
        }
    }

    fn verify_header_checksum(&self) -> bool {
        verify_checksum(self.header())
    }
}

impl<B, C> Packet<B, C>
where
    B: AsSlice<Element = u8> + AsMutSlice<Element = u8>,
{
    /* Miscellaneous */
    /// View into the payload
    pub fn payload_mut(&mut self) -> &mut [u8] {
        let start = usize(self.header_len());
        unsafe { self.as_mut_slice().rfm(start..) }
    }

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

    fn header_mut_(&mut self) -> &mut [u8; MIN_HEADER_SIZE as usize] {
        debug_assert!(self.as_slice().len() >= MIN_HEADER_SIZE as usize);

        unsafe { &mut *(self.as_mut_slice().as_mut_ptr() as *mut _) }
    }
}

impl<B, C> Packet<B, C>
where
    B: AsSlice<Element = u8> + IntoSliceFrom<u8>,
{
    /* Miscellaneous */
    /// Returns the payload of this frame
    pub fn into_payload(self) -> B::SliceFrom {
        let offset = self.header_len();
        self.buffer.into_slice_from(offset)
    }
}

impl<B> Packet<B, Invalid>
where
    B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u16>,
{
    /* Constructors */
    /// Transforms the given buffer into an IPv4 packet
    ///
    /// Most of the header will be filled with sensible defaults:
    ///
    /// - Version = 4
    /// - IHL = 5
    /// - DSCP = 0
    /// - ECN = 0
    /// - Total Length = `buffer.len()`
    /// - Identification = 0
    /// - DF = true
    /// - MF = false
    /// - Fragment Offset = 0
    /// - TTL = 64
    ///
    /// The fields that are left unpopulated are:
    ///
    /// - Protocol
    /// - Checksum
    /// - Source
    /// - Destination
    ///
    /// # Panics
    ///
    /// This constructor panics if
    ///
    /// - the given `buffer` is smaller than `MIN_HEADER_SIZE`
    /// - the packet would result in a packet length larger than `u16::MAX`.
    pub fn new(buffer: B) -> Self {
        let blen = buffer.as_slice().len();
        assert!(blen >= usize(MIN_HEADER_SIZE) || blen >= usize(u16::MAX));

        let mut packet: Self = Packet {
            buffer,
            _checksum: PhantomData,
        };

        // NOTE(cast) see `assert` above
        let total_len = blen as u16;
        packet.set_version(4);
        unsafe { packet.set_ihl(5) }

        packet.set_dscp(0);
        packet.set_ecn(0);

        unsafe { packet.set_total_length(total_len) }
        packet.buffer.truncate(total_len);

        packet.set_identification(0);

        packet.clear_reserved_flag();
        packet.set_df(true);
        packet.set_mf(false);
        packet.set_fragment_offset(0);

        packet.set_ttl(64); // see RFC 1700

        // protocol: unpopulated

        // source: unpopulated

        // destination: unpopulated

        packet
    }

    /// Fills the payload with an Echo Request ICMP message
    pub fn echo_request<F>(&mut self, f: F)
    where
        F: FnOnce(&mut icmp::Message<&mut [u8], icmp::EchoRequest, Invalid>),
    {
        self.set_protocol(Protocol::Icmp);
        let len = {
            let mut icmp = icmp::Message::new(self.payload_mut());
            f(&mut icmp);
            icmp.update_checksum().len()
        };
        self.truncate(len);
    }

    /// Fills the payload with an UDP packet
    pub fn udp<F>(&mut self, f: F)
    where
        F: FnOnce(&mut udp::Packet<&mut [u8]>),
    {
        self.set_protocol(Protocol::Udp);
        let len = {
            let mut udp = udp::Packet::new(self.payload_mut());
            f(&mut udp);
            udp.len()
        };
        self.truncate(len);
    }

    /// Truncates the *payload* to the specified length
    pub fn truncate(&mut self, len: u16) {
        if self.payload_len() > len {
            let total_len = u16(self.header_len()) + len;
            unsafe { self.set_total_length(total_len) }
            self.buffer.truncate(total_len);
        }
    }
}

impl<B> Packet<B, Valid>
where
    B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u16>,
{
    /// Truncates the *payload* to the specified length
    pub fn truncate(self, len: u16) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.truncate(len);
        packet
    }
}

impl<B> Packet<B, Invalid>
where
    B: AsSlice<Element = u8> + AsMutSlice<Element = u8>,
{
    /* Setters */
    /// Sets the version field of the header
    pub fn set_version(&mut self, version: u8) {
        set!(self.header_mut_()[VERSION_IHL], version, version);
    }

    // NOTE(unsafe) this doesn't check that the header still fits in the buffer
    unsafe fn set_ihl(&mut self, ihl: u8) {
        set!(self.header_mut_()[VERSION_IHL], ihl, ihl);
    }

    /// Sets the DSCP (Differentiated Services Code Point) field of the header
    pub fn set_dscp(&mut self, dscp: u8) {
        set!(self.header_mut_()[DSCP_ECN], dscp, dscp);
    }

    /// Sets the ECN (Explicit Congestion Notification) field of the header
    pub fn set_ecn(&mut self, ecn: u8) {
        set!(self.header_mut_()[DSCP_ECN], ecn, ecn);
    }

    // NOTE(unsafe) this doesn't check that `len` is greater than the header length or that it
    // doesn't exceed the buffer length
    unsafe fn set_total_length(&mut self, len: u16) {
        NE::write_u16(&mut self.header_mut_()[TOTAL_LENGTH], len)
    }

    /// Sets the identification field of the header
    pub fn set_identification(&mut self, id: u16) {
        NE::write_u16(&mut self.header_mut_()[IDENTIFICATION], id)
    }

    fn clear_reserved_flag(&mut self) {
        set!(self.header_mut_()[FLAGS], reserved, 0);
    }

    /// Sets the DF (Don't Fragment) field of the header
    pub fn set_df(&mut self, df: bool) {
        set!(self.header_mut_()[FLAGS], df, if df { 1 } else { 0 });
    }

    /// Sets the MF (More Fragments) field of the header
    pub fn set_mf(&mut self, mf: bool) {
        set!(self.header_mut_()[FLAGS], mf, if mf { 1 } else { 0 });
    }

    /// Sets the Fragment Offset field of the header
    pub fn set_fragment_offset(&mut self, fo: u16) {
        let offset = self::fragment_offset::OFFSET;
        let mask = self::fragment_offset::MASK;
        let start = FRAGMENT_OFFSET.start;

        // low byte
        self.header_mut_()[start + 1] = fo.low();

        // high byte
        let byte = &mut self.as_mut_slice()[start];
        *byte &= !(mask << offset).high();
        *byte |= (fo << offset).high();
    }

    /// Sets the TTL (Time To Live) field of the header
    pub fn set_ttl(&mut self, ttl: u8) {
        self.header_mut_()[TTL] = ttl;
    }

    /// Sets the Protocol field of the header
    pub fn set_protocol(&mut self, proto: Protocol) {
        self.header_mut_()[PROTOCOL] = proto.into();
    }

    /// Sets the Source (IP address) field of the header
    pub fn set_source(&mut self, addr: Addr) {
        self.header_mut_()[SOURCE].copy_from_slice(&addr.0)
    }

    /// Sets the Destination (IP address) field of the header
    pub fn set_destination(&mut self, addr: Addr) {
        self.header_mut_()[DESTINATION].copy_from_slice(&addr.0)
    }

    /* Miscellaneous */
    /// Updates the Checksum field of the header
    pub fn update_checksum(mut self) -> Packet<B, Valid> {
        let cksum = compute_checksum(&self.header(), CHECKSUM.start);
        NE::write_u16(&mut self.header_mut_()[CHECKSUM], cksum);

        Packet {
            buffer: self.buffer,
            _checksum: PhantomData,
        }
    }
}

impl<B> Packet<B, Valid>
where
    B: AsSlice<Element = u8> + AsMutSlice<Element = u8>,
{
    /* Setters */
    /// Sets the version field of the header
    pub fn set_version(self, version: u8) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_version(version);
        packet
    }

    /// Sets the DSCP (Differentiated Services Code Point) field of the header
    pub fn set_dscp(self, dscp: u8) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_dscp(dscp);
        packet
    }

    /// Sets the ECN (Explicit Congestion Notification) field of the header
    pub fn set_ecn(self, ecn: u8) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_ecn(ecn);
        packet
    }

    /// Sets the identification field of the header
    pub fn set_identification(self, id: u16) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_identification(id);
        packet
    }

    /// Sets the DF (Don't Fragment) field of the header
    pub fn set_df(self, df: bool) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_df(df);
        packet
    }

    /// Sets the MF (More Fragments) field of the header
    pub fn set_mf(self, mf: bool) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_mf(mf);
        packet
    }

    /// Sets the Fragment Offset field of the header
    pub fn set_fragment_offset(self, fo: u16) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_fragment_offset(fo);
        packet
    }

    /// Sets the TTL (Time To Live) field of the header
    pub fn set_ttl(self, ttl: u8) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_ttl(ttl);
        packet
    }

    /// Sets the Protocol field of the header
    pub fn set_protocol(self, proto: Protocol) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_protocol(proto);
        packet
    }

    /// Sets the Source (IP address) field of the header
    pub fn set_source(self, addr: Addr) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_source(addr);
        packet
    }

    /// Sets the Destination (IP address) field of the header
    pub fn set_destination(self, addr: Addr) -> Packet<B, Invalid> {
        let mut packet = self.invalidate_header_checksum();
        packet.set_destination(addr);
        packet
    }
}

/// NOTE excludes the payload
impl<B, C> fmt::Debug for Packet<B, C>
where
    B: AsSlice<Element = u8>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ipv4::Packet")
            .field("version", &self.get_version())
            .field("ihl", &self.get_ihl())
            .field("dscp", &self.get_dscp())
            .field("ecn", &self.get_ecn())
            .field("total_length", &self.get_total_length())
            .field("identification", &self.get_identification())
            .field("df", &self.get_df())
            .field("mf", &self.get_mf())
            .field("fragment_offset", &self.get_fragment_offset())
            .field("ttl", &self.get_ttl())
            .field("protocol", &self.get_protocol())
            .field("checksum", &Hex(self.get_header_checksum()))
            .field("source", &self.get_source())
            .field("destination", &self.get_destination())
            // .field("payload", &self.payload())
            .finish()
    }
}

/// IPv4 address
#[derive(Clone, Copy, Eq, Hash32, PartialEq)]
pub struct Addr(pub [u8; 4]);

impl Addr {
    /// Loopback address
    pub const LOOPBACK: Self = Addr([127, 0, 0, 1]);

    /// Unspecified address
    pub const UNSPECIFIED: Self = Addr([0; 4]);
}

impl fmt::Debug for Addr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ipv4::Addr").field(&self.0).finish()
    }
}

impl fmt::Display for Addr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use core::fmt::Write;

        let mut is_first = true;
        for byte in &self.0 {
            if is_first {
                is_first = false;
            } else {
                f.write_char('.')?;
            }

            write!(f, "{}", byte)?;
        }

        Ok(())
    }
}

// From https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
// ("Last Updated: 2017-10-13")
full_range!(
    u8,
    /// IP protocol
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub enum Protocol {
        /// IPv6 Hop-by-Hop Option
        Hopopt = 0,

        /// ICMP
        Icmp = 1,

        /// Internet Group Management Protocol
        Igmp = 2,

        /// Gateway-to-Gateway Protocol
        Ggp = 3,

        /// IPv4 encapsulation
        Ipv4 = 4,

        /// Stream
        St = 5,

        /// Transmission Control Protocol
        Tcp = 6,

        /// CBT
        Cbt = 7,

        /// Exterior Gateway Protocol
        Egp = 8,

        /// Any private interior gateway
        Igp = 9,

        /// BBN RCC Monitoring
        BbnRccMon = 10,

        /// Network Voice Protocol
        NvpIi = 11,

        /// PUP
        Pup = 12,

        /// ARGUS (deprecated)
        Argus = 13,

        /// EMCON
        Emcon = 14,

        /// Cross Net Debugger
        Xnet = 15,

        /// Chaos
        Chaos = 16,

        /// UDP
        Udp = 17,

        /// Multiplexing
        Mux = 18,

        /// DCN Measurement Subsystems
        DcnMeas = 19,

        /// Host Monitoring
        Hmp = 20,

        /// Packet Radio Measurement
        Prm = 21,

        /// XEROX NS IDP
        XnsIdp = 22,

        /// Trunk-1
        Trunk1 = 23,

        /// Trunk-2
        Trunk2 = 24,

        /// Leaf-1
        Leaf1 = 25,

        /// Leaf-2
        Leaf2 = 26,

        /// Reliable Data Protocol
        Rdp = 27,

        /// Internet Reliable Transaction
        Irtp = 28,

        /// ISO Transport Protocol Class 4
        IsoTp4 = 29,

        /// Bulk Data Transfer Protocol
        Netblt = 30,

        /// MFE Network Services Protocol
        MfeNsp = 31,

        /// MERIT Internodal Protocol
        MeritInp = 32,

        /// Datagram Congestion Control Protocol
        Dccp = 33,

        /// Third Party Connect Protocol
        ThreePc = 34,

        /// Inter-Domain Policy Routing Protocol
        Idpr = 35,

        /// Xpress Transport Protocol
        Xtp = 36,

        /// Datagram Delivery Protocol
        Ddp = 37,

        /// IDPR Control Message Transport Proto
        IdprCmtp = 38,

        /// TP++ Transport Protocol
        Tppp = 39,

        /// IL Transport Protocol
        Il = 40,

        /// IPv6 Encapsulation
        Ipv6 = 41,

        /// Source Demand Routing Protocol
        Sdrp = 42,

        /// Routing Header for IPv6
        Ipv6Route = 43,

        /// Fragment Header for IPv6
        Ipv6Frag = 44,

        /// Inter-Domain Routing Protocol
        Idrp = 45,

        /// Resource Protocol
        Rsvp = 46,

        /// Generic Routing Encapsulation
        Gres = 47,

        /// Dynamic Source Routing Protocol
        Dsr = 48,

        /// BNA
        Bna = 49,

        /// Encap Security Payload
        Esp = 50,

        /// Authentication Header
        Ah = 51,

        /// Integrated Net Layer Security Protocol
        INlsp = 52,

        /// IP with Encryption (deprecated)
        Swipe = 53,

        /// NBMA Address Resolution Protocol
        Narp = 54,

        /// IP Mobility
        Mobile = 55,

        /// Transport Layer Security Protocol using Kryptonet key management
        Tlsp = 56,

        /// SKIP
        Skip = 57,

        /// ICMP for IPv6
        Ipv6Icmp = 58,

        /// No Next Header for IPv6
        Ipv6NoNxt = 59,

        /// Destination Options for IPv6
        Ipv6Opts = 60,

        /// Any host internal protocol
        AnyHostInternalProtocol = 61,

        /// CFTP
        Cftp = 62,

        /// Any local network
        AnyLocalNetwork = 63,

        /// SATNET and Backroom EXPAK
        SatExpak = 64,

        /// Kryptolan
        Kryptolan = 65,

        /// MIT Remote Virtual Disk Protocol
        Rvd = 66,

        /// Internet Pluribus Packet Core
        Ippc = 67,

        /// Any distributed file system
        AnyDistributedFileSystem = 68,

        /// SATNET Monitoring
        SatMon = 69,

        /// VISA Protocol
        Visa = 70,

        /// Internet Packet Core Utility
        Ipcu = 71,

        /// Computer Protocol Network Executive
        Cpnx = 72,

        /// Computer Protocol Heart Beat
        Cphb = 73,

        /// Wang Span Network
        Wsn = 74,

        /// Packet Video Protocol
        Pvp = 75,

        /// Backroom SATNET Monitoring
        BrSatMon = 76,

        /// SUN ND PROTOCOL-Temporary
        SunNd = 77,

        /// WIDEBAND Monitoring
        WbMon = 78,

        /// WIDEBAND EXPAK
        WbExpak = 79,

        /// International Organization for Standardization Internet Protocol
        IsoIp = 80,

        /// VMTP
        Vmtp = 81,

        /// Secure-VMTP
        SecureVmtp = 82,

        /// VINES
        Vines = 83,

        /// Transaction Transport Protocol || Internet Protocol Traffic Manager
        TtpIptm = 84,

        /// NSFNET-IGP
        NfsnetIgp = 85,

        /// Dissimilar Gateway Protocol
        Dgp = 86,

        /// TCF
        Tcf = 87,

        /// EIGRP
        Eigrp = 88,

        /// OSPFIGP
        Ospfigp = 89,

        /// Sprite RPC Protocol
        SpriteRpc = 90,

        /// Locus Address Resolution Protocol
        Larp = 91,

        /// Multicast Transport Protocol
        Mtp = 92,

        /// AX.25 Frames
        Ax25 = 93,

        /// IP-within-IP Encapsulation Protocol
        Ipip = 94,

        /// Mobile Internetworking Control Pro. (deprecated)
        Micp = 95,

        /// Semaphore Communications Sec. Pro.
        SccSp = 96,

        /// Ethernet-within-IP Encapsulation
        Etherip = 97,

        /// Encapsulation Header
        Encap = 98,

        /// Any private encryption scheme
        AnyPrivateEncryptionScheme = 99,

        /// GMTP
        Gmtp = 100,

        /// Ipsilon Flow Management Protocol
        Ifmp = 101,

        /// PNNI over IP
        Pnni = 102,

        /// Protocol Independent Multicast
        Pim = 103,

        /// ARIS
        Aris = 104,

        /// SCPS
        Scps = 105,

        /// QNX
        Qnx = 106,

        /// Active Networks
        AN = 107,

        /// IP Payload Compression Protocol
        IpComp = 108,

        /// Sitara Networks Protocol
        Snp = 109,

        /// Compaq Peer Protocol
        CompaqPeer = 110,

        /// IPX in IP
        IpxInIp = 111,

        /// Virtual Router Redundancy Protocol
        Vrrp = 112,

        /// PGM Reliable Transport Protocol
        Pgm = 113,

        /// any 0-hop protocol
        Any0HopProtocol = 114,

        /// Layer Two Tunneling Protocol
        L2tp = 115,

        /// D-II Data Exchange (DDX)
        Ddx = 116,

        /// Interactive Agent Transfer Protocol
        Iatp = 117,

        /// Schedule Transfer Protocol
        Stp = 118,

        /// SpectraLink Radio Protocol
        Srp = 119,

        /// UTI
        Uti = 120,

        /// Simple Message Protocol
        Smp = 121,

        /// Simple Multicast Protocol (deprecated)
        Sm = 122,

        /// Performance Transparency Protocol
        Ptp = 123,

        /// ISIS over IPv4
        IsisOverIpv4 = 124,

        /// FIRE
        Fire = 125,

        /// Combat Radio Transport Protocol
        Crtp = 126,

        /// Combat Radio User Datagram
        Crudp = 127,

        /// SSCOPMCE
        Sscopmce = 128,

        /// IPLT
        Iplt = 129,

        /// Secure Packet Shield
        Sps = 130,

        /// Private IP Encapsulation within IP
        Pipe = 131,

        /// Stream Control Transmission Protocol
        Sctp = 132,

        /// Fibre Channel
        Fc = 133,

        /// RSVP-E2E-IGNORE
        RsvpE2eIgnore = 134,

        /// Mobility Header
        MobilityHeader = 135,

        /// UDPLite
        UdpLite = 136,

        /// MPLS-in-IP
        MplsInIp = 137,

        /// MANET Protocols
        Manet = 138,

        /// Host Identity Protocol
        Hip = 139,

        /// Shim6 Protocol
        Shim6 = 140,

        /// Wrapped Encapsulating Security Payload
        Wesp = 141,

        /// Robust Header Compression
        Rohc = 142,

        /// Reserved
        Reserved = 255,
    }
);

impl Protocol {
    /// Is this an IPv6 extension header?
    pub fn is_ipv6_extension_header(&self) -> bool {
        match *self {
            Protocol::Hopopt => true,
            Protocol::Ipv6Route => true,
            Protocol::Ipv6Frag => true,
            Protocol::Esp => true,
            Protocol::Ah => true,
            Protocol::Ipv6Opts => true,
            Protocol::MobilityHeader => true,
            Protocol::Hip => true,
            Protocol::Shim6 => true,
            Protocol::Unknown(byte) => byte == 253 || byte == 254,
            _ => false,
        }
    }
}

/// Computes the IPv4 checksum of the header
pub(crate) fn compute_checksum(header: &[u8], cksum_pos: usize) -> u16 {
    let mut sum = 0u32;
    let skip = cksum_pos / 2;

    // Header length is always even
    debug_assert_eq!(header.len() % 2, 0);
    for (i, chunk) in header.chunks_exact(2).enumerate() {
        if i == skip {
            // skip checksum field
            continue;
        }
        sum = sum.wrapping_add(u32(NE::read_u16(chunk)));
    }

    loop {
        let carry = sum.high();
        if carry == 0 {
            break;
        }
        sum = u32(sum.low()) + u32(carry);
    }

    !sum.low()
}

/// Verifies the IPv4 checksum of the header
pub(crate) fn verify_checksum(header: &[u8]) -> bool {
    debug_assert!(header.len() % 2 == 0);

    let mut sum = 0u32;
    for chunk in header.chunks_exact(2) {
        sum = sum.wrapping_add(u32(NE::read_u16(chunk)));
    }

    sum.low() + sum.high() == 0xffff
}

#[cfg(test)]
mod tests {
    use crate::ipv4;

    #[test]
    fn checksum() {
        let header = [
            0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0xb8, 0x61, 0xc0, 0xa8,
            0x00, 0x01, 0xc0, 0xa8, 0x00, 0xc7,
        ];

        assert_eq!(
            super::compute_checksum(&header, super::CHECKSUM.start),
            0xb861
        )
    }

    #[test]
    fn new() {
        const SZ: u16 = 128;

        let mut chunk = [0; SZ as usize];
        let buf = &mut chunk[..];

        let ip = ipv4::Packet::new(buf);
        assert_eq!(ip.len(), SZ);
        assert_eq!(ip.get_total_length(), SZ);
    }

    #[test]
    fn verify() {
        let header = [
            0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0xb8, 0x61, 0xc0, 0xa8,
            0x00, 0x01, 0xc0, 0xa8, 0x00, 0xc7,
        ];

        assert!(super::verify_checksum(&header))
    }
}