ethox 0.0.2

A standalone network stack for user-space networking and unikernels
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
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
use core::{i32, ops, cmp, fmt};
use byteorder::{ByteOrder, NetworkEndian};

use crate::wire::{ip, Error, Result, Payload, PayloadMut};
use crate::wire::pretty_print::{PrettyPrint, PrettyIndent};

use super::ip::checksum;

/// A TCP sequence number.
///
/// A sequence number is a monotonically advancing integer modulo 2<sup>32</sup>.
/// Sequence numbers do not have a discontinuity when compared pairwise across a signed overflow.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default, Hash)]
pub struct SeqNumber(pub i32);

impl fmt::Display for SeqNumber {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0 as u32)
    }
}

impl ops::Add<usize> for SeqNumber {
    type Output = SeqNumber;

    fn add(self, rhs: usize) -> SeqNumber {
        if rhs > i32::MAX as usize {
            panic!("attempt to add to sequence number with unsigned overflow")
        }
        SeqNumber(self.0.wrapping_add(rhs as i32))
    }
}

impl ops::Sub<usize> for SeqNumber {
    type Output = SeqNumber;

    fn sub(self, rhs: usize) -> SeqNumber {
        if rhs > i32::MAX as usize {
            panic!("attempt to subtract to sequence number with unsigned overflow")
        }
        SeqNumber(self.0.wrapping_sub(rhs as i32))
    }
}

impl ops::AddAssign<usize> for SeqNumber {
    fn add_assign(&mut self, rhs: usize) {
        *self = *self + rhs;
    }
}

impl ops::Sub for SeqNumber {
    type Output = usize;

    fn sub(self, rhs: SeqNumber) -> usize {
        let result = self.0.wrapping_sub(rhs.0);
        if result < 0 {
            panic!("attempt to subtract sequence numbers with underflow")
        }
        result as usize
    }
}

impl cmp::PartialOrd for SeqNumber {
    fn partial_cmp(&self, other: &SeqNumber) -> Option<cmp::Ordering> {
        self.0.wrapping_sub(other.0).partial_cmp(&0)
    }
}

impl SeqNumber {
    /// Check if the window contains the other sequence number.
    ///
    /// The length of the window must be at most `i32::MAX`.
    pub fn contains_in_window(self, other: SeqNumber, len: usize) -> bool {
        self <= other && other < (self + len)
    }
}

/// A set of tcp flags.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Flags(pub u16);

/// A read/write wrapper around a Transmission Control Protocol packet buffer.
#[derive(Debug, PartialEq, Clone)]
pub struct Packet<T> {
    buffer: T,
    repr: Repr,
}

mod field {
    #![allow(non_snake_case)]

    use crate::wire::field::Field;

    pub(crate) const SRC_PORT: Field = 0..2;
    pub(crate) const DST_PORT: Field = 2..4;
    pub(crate) const SEQ_NUM:  Field = 4..8;
    pub(crate) const ACK_NUM:  Field = 8..12;
    pub(crate) const FLAGS:    Field = 12..14;
    pub(crate) const WIN_SIZE: Field = 14..16;
    pub(crate) const CHECKSUM: Field = 16..18;
    pub(crate) const URGENT:   Field = 18..20;

    pub(crate) fn OPTIONS(length: u8) -> Field {
        URGENT.end..(length as usize)
    }

    pub(crate) const OPT_END: u8 = 0x00;
    pub(crate) const OPT_NOP: u8 = 0x01;
    pub(crate) const OPT_MSS: u8 = 0x02;
    pub(crate) const OPT_WS:  u8 = 0x03;
    pub(crate) const OPT_SACKPERM: u8 = 0x04;
    pub(crate) const OPT_SACKRNG:  u8 = 0x05;
}

impl<T: Payload> Packet<T> {
    /// Imbue a raw octet buffer with TCP packet structure.
    pub fn new_unchecked(buffer: T, repr: Repr) -> Packet<T> {
        Packet { buffer, repr, }
    }

    /// Shorthand for a combination of [new_unchecked] and [check_len].
    ///
    /// [new_unchecked]: #method.new_unchecked
    /// [check_len]: #method.check_len
    pub fn new_checked(buffer: T, checksum: Checksum) -> Result<Packet<T>> {
        let repr = Repr::parse(&buffer, checksum)?;
        Ok(Packet { buffer, repr })
    }

    /// Ensure that no header accessor method will panic if called.
    /// Returns `Err(Error::Truncated)` if the buffer is too short.
    /// Returns `Err(Error::Malformed)` if the header length field has a value smaller
    /// than the minimal header length.
    ///
    /// The result of this check is invalidated by calling [set_header_len].
    ///
    /// [set_header_len]: #method.set_header_len
    pub fn check_len(&self) -> Result<()> {
        let len = self.buffer.payload().as_bytes().len();
        if len < field::URGENT.end {
            Err(Error::Truncated)
        } else {
            let header_len = self.header_len() as usize;
            if len < header_len {
                Err(Error::Truncated)
            } else if header_len < field::URGENT.end {
                Err(Error::Malformed)
            } else {
                Ok(())
            }
        }
    }

    /// Get a reference to the containing buffer.
    pub fn inner(&self) -> &T {
        &self.buffer
    }

    /// Consume the packet, returning the underlying buffer.
    pub fn into_inner(self) -> T {
        self.buffer
    }

    /// Retrieve the packet representation.
    pub fn repr(&self) -> Repr {
        self.repr
    }

    /// Return the source port field.
    #[inline]
    pub fn src_port(&self) -> u16 {
        let data = self.buffer.payload().as_bytes();
        NetworkEndian::read_u16(&data[field::SRC_PORT])
    }

    /// Return the destination port field.
    #[inline]
    pub fn dst_port(&self) -> u16 {
        let data = self.buffer.payload().as_bytes();
        NetworkEndian::read_u16(&data[field::DST_PORT])
    }

    /// Return the sequence number field.
    #[inline]
    pub fn seq_number(&self) -> SeqNumber {
        let data = self.buffer.payload().as_bytes();
        SeqNumber(NetworkEndian::read_i32(&data[field::SEQ_NUM]))
    }

    /// Return the acknowledgement number field.
    #[inline]
    pub fn ack_number(&self) -> SeqNumber {
        let data = self.buffer.payload().as_bytes();
        SeqNumber(NetworkEndian::read_i32(&data[field::ACK_NUM]))
    }

    /// Read all flags at once.
    pub fn flags(&self) -> Flags {
        let data = self.buffer.payload().as_bytes();
        Flags(NetworkEndian::read_u16(&data[field::FLAGS]) & 0x1ff)
    }

    /// Return the header length, in octets.
    #[inline]
    pub fn header_len(&self) -> u8 {
        let data = self.buffer.payload().as_bytes();
        let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
        ((raw >> 12) * 4) as u8
    }

    /// Return the window size field.
    #[inline]
    pub fn window_len(&self) -> u16 {
        let data = self.buffer.payload().as_bytes();
        NetworkEndian::read_u16(&data[field::WIN_SIZE])
    }

    /// Return the checksum field.
    #[inline]
    pub fn checksum(&self) -> u16 {
        let data = self.buffer.payload().as_bytes();
        NetworkEndian::read_u16(&data[field::CHECKSUM])
    }

    /// Return the urgent pointer field.
    #[inline]
    pub fn urgent_at(&self) -> u16 {
        let data = self.buffer.payload().as_bytes();
        NetworkEndian::read_u16(&data[field::URGENT])
    }

    /// Return the length of the segment, in terms of sequence space.
    pub fn sequence_len(&self) -> usize {
        let data = self.buffer.payload().as_bytes();
        data.len()
            - self.header_len() as usize
            + self.flags().sequence_len()
    }

    /// Returns whether the selective acknowledgement SYN flag is set or not.
    pub fn selective_ack_permitted(&self) -> Result<bool> {
        let data = self.buffer.payload().as_bytes();
        let mut options = &data[field::OPTIONS(self.header_len())];
        while options.len() > 0 {
            let (next_options, option) = TcpOption::parse(options)?;
            match option {
                TcpOption::SackPermitted => {
                    return Ok(true);
                },
                _ => {},
            }
            options = next_options;
        }
        Ok(false)
    }

    /// Return the selective acknowledgement ranges, if any. If there are none in the packet, an
    /// array of ``None`` values will be returned.
    ///
    pub fn selective_ack_ranges<'s>(
        &'s self
    ) -> Result<[Option<(u32, u32)>; 3]> {
        let data = self.buffer.payload().as_bytes();
        let mut options = &data[field::OPTIONS(self.header_len())];
        while options.len() > 0 {
            let (next_options, option) = TcpOption::parse(options)?;
            match option {
                TcpOption::SackRange(slice) => {
                    return Ok(slice);
                },
                _ => {},
            }
            options = next_options;
        }
        Ok([None, None, None])
    }

    /// Validate the packet checksum.
    ///
    /// # Panics
    /// This function panics unless `src_addr` and `dst_addr` belong to the same family,
    /// and that family is IPv4 or IPv6.
    ///
    /// # Fuzzing
    /// This function always returns `true` when fuzzing.
    pub fn verify_checksum(&self, src_addr: ip::Address, dst_addr: ip::Address) -> bool {
        if cfg!(fuzzing) { return true }

        let data = self.buffer.payload().as_bytes();
        checksum::combine(&[
            checksum::pseudo_header(&src_addr, &dst_addr, ip::Protocol::Tcp,
                                    data.len() as u32),
            checksum::data(data)
        ]) == !0
    }

    /// Return a pointer to the payload.
    #[inline]
    pub fn payload_slice(&self) -> &[u8] {
        let header_len = self.header_len() as usize;
        let data = self.buffer.payload().as_bytes();
        &data[header_len..]
    }
}

impl<'a, T: Payload + ?Sized> Packet<&'a T> {
    /// Return a pointer to the options.
    #[inline]
    pub fn options(&self) -> &'a [u8] {
        let header_len = self.header_len();
        let data = self.buffer.payload().as_bytes();
        &data[field::OPTIONS(header_len)]
    }

    /// Turn into a reference to the payload.
    #[inline]
    pub fn into_payload_slice(&self) -> &'a [u8] {
        let header_len = self.header_len() as usize;
        let data = self.buffer.payload().as_bytes();
        &data[header_len..]
    }
}

impl<T: PayloadMut> Packet<T> {
    /// Set the source port field.
    #[inline]
    pub fn set_src_port(&mut self, value: u16) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_u16(&mut data[field::SRC_PORT], value)
    }

    /// Set the destination port field.
    #[inline]
    pub fn set_dst_port(&mut self, value: u16) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_u16(&mut data[field::DST_PORT], value)
    }

    /// Set the sequence number field.
    #[inline]
    pub fn set_seq_number(&mut self, value: SeqNumber) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_i32(&mut data[field::SEQ_NUM], value.0)
    }

    /// Set the acknowledgement number field.
    #[inline]
    pub fn set_ack_number(&mut self, value: SeqNumber) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_i32(&mut data[field::ACK_NUM], value.0)
    }

    /// Clear the entire flags field.
    #[inline]
    pub fn clear_flags(&mut self) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
        let raw = raw & !0x0fff;
        NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
    }

    /// Set a combination of flags.
    #[inline]
    pub fn set_flags(&mut self, Flags(flags): Flags) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        let field = NetworkEndian::read_u16(&mut data[field::FLAGS]) & !0xfff;
        NetworkEndian::write_u16(&mut data[field::FLAGS], field | (flags & 0x1ff))
    }

    /// Set the header length, in octets.
    #[inline]
    pub fn set_header_len(&mut self, value: u8) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
        let raw = (raw & !0xf000) | ((value as u16) / 4) << 12;
        NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
    }

    /// Return the window size field.
    #[inline]
    pub fn set_window_len(&mut self, value: u16) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_u16(&mut data[field::WIN_SIZE], value)
    }

    /// Set the checksum field.
    #[inline]
    pub fn set_checksum(&mut self, value: u16) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_u16(&mut data[field::CHECKSUM], value)
    }

    /// Set the urgent pointer field.
    #[inline]
    pub fn set_urgent_at(&mut self, value: u16) {
        let data = self.buffer.payload_mut().as_bytes_mut();
        NetworkEndian::write_u16(&mut data[field::URGENT], value)
    }

    /// Compute and fill in the header checksum.
    ///
    /// # Panics
    /// This function panics unless `src_addr` and `dst_addr` belong to the same family,
    /// and that family is IPv4 or IPv6.
    pub fn fill_checksum(&mut self, src_addr: ip::Address, dst_addr: ip::Address) {
        self.set_checksum(0);
        let checksum = {
            let data = self.buffer.payload_mut().as_bytes_mut();
            !checksum::combine(&[
                checksum::pseudo_header(&src_addr, &dst_addr, ip::Protocol::Tcp,
                                        data.len() as u32),
                checksum::data(data)
            ])
        };
        self.set_checksum(checksum)
    }

    /// Return a pointer to the options.
    #[inline]
    pub fn options_mut(&mut self) -> &mut [u8] {
        let header_len = self.header_len();
        let data = self.buffer.payload_mut().as_bytes_mut();
        &mut data[field::OPTIONS(header_len)]
    }

    /// Return a mutable pointer to the payload data.
    #[inline]
    pub fn payload_mut_slice(&mut self) -> &mut [u8] {
        let header_len = self.header_len() as usize;
        let data = self.buffer.payload_mut().as_bytes_mut();
        &mut data[header_len..]
    }
}

impl Flags {
    /// A constant with no flag bit set.
    pub const NONE: Self = Flags(0x0);
    /// A constant with the FIN flag bit set.
    pub const FIN: Self = Flags(0x001);
    /// A constant with the SYN flag bit set.
    pub const SYN: Self = Flags(0x002);
    /// A constant with the RST flag bit set.
    pub const RST: Self = Flags(0x004);
    /// A constant with the PSH flag bit set.
    pub const PSH: Self = Flags(0x008);
    /// A constant with the ACK flag bit set.
    pub const ACK: Self = Flags(0x010);
    /// A constant with the URG flag bit set.
    pub const URG: Self = Flags(0x020);
    /// A constant with the ECE (explicit congestion echo) flag bit set.
    pub const ECE: Self = Flags(0x040);
    /// A constant with the CWR (congestion window reduced) flag bit set.
    pub const CWR: Self = Flags(0x080);
    /// A constant with the experimental NS (nonce sum) flag bit set.
    pub const NS:  Self = Flags(0x100);

    /// Return the FIN flag.
    #[inline]
    pub fn fin(self) -> bool {
        self.0 & Self::FIN.0 != 0
    }

    /// Return the SYN flag.
    #[inline]
    pub fn syn(self) -> bool {
        self.0 & Self::SYN.0 != 0
    }

    /// Return the RST flag.
    #[inline]
    pub fn rst(self) -> bool {
        self.0 & Self::RST.0 != 0
    }

    /// Return the PSH flag.
    #[inline]
    pub fn psh(self) -> bool {
        self.0 & Self::PSH.0 != 0
    }

    /// Return the ACK flag.
    #[inline]
    pub fn ack(self) -> bool {
        self.0 & Self::ACK.0 != 0
    }

    /// Return the URG flag.
    #[inline]
    pub fn urg(self) -> bool {
        self.0 & Self::URG.0 != 0
    }

    /// Return the ECE flag.
    #[inline]
    pub fn ece(self) -> bool {
        self.0 & Self::ECE.0 != 0
    }

    /// Return the CWR flag.
    #[inline]
    pub fn cwr(self) -> bool {
        self.0 & Self::CWR.0 != 0
    }

    /// Return the NS flag.
    #[inline]
    pub fn ns(self) -> bool {
        self.0 & Self::NS.0 != 0
    }

    /// Set the FIN flag.
    #[inline]
    pub fn set_fin(&mut self, value: bool) {
        let flag = if value { Self::FIN.0 } else { 0 };
        let without = self.0 & !Self::FIN.0;
        self.0 = without | flag;
    }

    /// Set the SYN flag.
    #[inline]
    pub fn set_syn(&mut self, value: bool) {
        let flag = if value { Self::SYN.0 } else { 0 };
        let without = self.0 & !Self::SYN.0;
        self.0 = without | flag;
    }

    /// Set the RST flag.
    #[inline]
    pub fn set_rst(&mut self, value: bool) {
        let flag = if value { Self::RST.0 } else { 0 };
        let without = self.0 & !Self::RST.0;
        self.0 = without | flag;
    }

    /// Set the PSH flag.
    #[inline]
    pub fn set_psh(&mut self, value: bool) {
        let flag = if value { Self::PSH.0 } else { 0 };
        let without = self.0 & !Self::PSH.0;
        self.0 = without | flag;
    }

    /// Set the ACK flag.
    #[inline]
    pub fn set_ack(&mut self, value: bool) {
        let flag = if value { Self::ACK.0 } else { 0 };
        let without = self.0 & !Self::ACK.0;
        self.0 = without | flag;
    }

    /// Set the URG flag.
    #[inline]
    pub fn set_urg(&mut self, value: bool) {
        let flag = if value { Self::URG.0 } else { 0 };
        let without = self.0 & !Self::URG.0;
        self.0 = without | flag;
    }

    /// Set the ECE flag.
    #[inline]
    pub fn set_ece(&mut self, value: bool) {
        let flag = if value { Self::ECE.0 } else { 0 };
        let without = self.0 & !Self::ECE.0;
        self.0 = without | flag;
    }

    /// Set the CWR flag.
    #[inline]
    pub fn set_cwr(&mut self, value: bool) {
        let flag = if value { Self::CWR.0 } else { 0 };
        let without = self.0 & !Self::CWR.0;
        self.0 = without | flag;
    }

    /// Set the NS flag.
    #[inline]
    pub fn set_ns(&mut self, value: bool) {
        let flag = if value { Self::NS.0 } else { 0 };
        let without = self.0 & !Self::NS.0;
        self.0 = without | flag;
    }

    /// Return the length of a control flag, in terms of sequence space.
    pub fn sequence_len(self) -> usize {
        // Syn + Fin is actually weird.
        usize::from(self.syn()) + usize::from(self.fin())
    }

    /// Like `BitOr` but const.
    ///
    /// Will be deprecated swiftly once `const impl` is on a path to stable.
    pub const fn const_or(self, other: Self) -> Self {
        Flags(self.0 | other.0)
    }
}

impl ops::BitOr<Self> for Flags {
    type Output = Self;

    fn bitor(self, other: Self) -> Self {
        Flags(self.0 | other.0)
    }
}

impl<T: Payload> AsRef<[u8]> for Packet<T> {
    fn as_ref(&self) -> &[u8] {
        self.buffer.payload().as_bytes()
    }
}

/// A representation of a single TCP option (of those which may be supported).
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum TcpOption<'a> {
    /// Marks the last option. Trailing bytes are ignored.
    EndOfList,
    /// An option without effect.
    NoOperation,
    /// Advise the remote of its maximum segment size to use.
    /// Must only be sent as part of a SYN packet.
    MaxSegmentSize(u16),
    /// Set the window scaling used by all window indications of the sender.
    /// Must only be sent as part of a SYN packet.
    WindowScale(u8),
    /// Signal support for SACK mechanism on an established connection.
    /// Must only be sent as part of a SYN packet.
    SackPermitted,
    /// Specifies the selectively acknowledged ranges.
    /// Should only be sent if the remote sent `SackPermitted` originally.
    SackRange([Option<(u32, u32)>; 3]),
    /// Some user specified option not handled within the library itself.
    Unknown { kind: u8, data: &'a [u8] }
}

impl<'a> TcpOption<'a> {
    /// Split the first option from a buffer.
    ///
    /// The buffer should be part of a larger TCP header.
    pub fn parse(buffer: &'a [u8]) -> Result<(&'a [u8], TcpOption<'a>)> {
        let (length, option): (usize, TcpOption);
        match *buffer.get(0).ok_or(Error::Truncated)? {
            field::OPT_END => {
                length = 1;
                option = TcpOption::EndOfList;
            }
            field::OPT_NOP => {
                length = 1;
                option = TcpOption::NoOperation;
            }
            kind => {
                length = buffer.get(1).copied().ok_or(Error::Truncated)?.into();
                let data = buffer.get(2..length).ok_or(Error::Truncated)?;
                match (kind, length) {
                    (field::OPT_END, _) |
                    (field::OPT_NOP, _) =>
                        unreachable!(),
                    (field::OPT_MSS, 4) =>
                        option = TcpOption::MaxSegmentSize(NetworkEndian::read_u16(data)),
                    (field::OPT_MSS, _) =>
                        return Err(Error::Malformed),
                    (field::OPT_WS, 3) =>
                        option = TcpOption::WindowScale(data[0]),
                    (field::OPT_WS, _) =>
                        return Err(Error::Malformed),
                    (field::OPT_SACKPERM, 2) =>
                        option = TcpOption::SackPermitted,
                    (field::OPT_SACKPERM, _) =>
                        return Err(Error::Malformed),
                    (field::OPT_SACKRNG, n) => {
                        if n < 10 || (n-2) % 8 != 0 {
                            return Err(Error::Malformed)
                        }
                        if n > 26 {
                            // It's possible for a remote to send 4 SACK blocks, but extremely rare.
                            // Better to "lose" that 4th block and save the extra RAM and CPU
                            // cycles in the vastly more common case.
                            //
                            // RFC 2018: SACK option that specifies n blocks will have a length of
                            // 8*n+2 bytes, so the 40 bytes available for TCP options can specify a
                            // maximum of 4 blocks.  It is expected that SACK will often be used in
                            // conjunction with the Timestamp option used for RTTM [...] thus a
                            // maximum of 3 SACK blocks will be allowed in this case.
                            net_debug!("sACK with >3 blocks, truncating to 3");
                        }
                        let mut sack_ranges: [Option<(u32, u32)>; 3] = [None; 3];

                        // RFC 2018: Each contiguous block of data queued at the data receiver is
                        // defined in the SACK option by two 32-bit unsigned integers in network
                        // byte order[...]
                        sack_ranges.iter_mut().enumerate().for_each(|(i, nmut)| {
                            let left = i * 8;
                            *nmut = if left < data.len() {
                                let mid = left + 4;
                                let right = mid + 4;
                                let range_left = NetworkEndian::read_u32(
                                    &data[left..mid]);
                                let range_right = NetworkEndian::read_u32(
                                    &data[mid..right]);
                                Some((range_left, range_right))
                            } else {
                                None
                            };
                        });
                        option = TcpOption::SackRange(sack_ranges);
                    },
                    (_, _) =>
                        option = TcpOption::Unknown { kind: kind, data: data }
                }
            }
        }
        Ok((&buffer[length..], option))
    }

    /// Get the buffer length required to encode this header option.
    pub fn buffer_len(&self) -> usize {
        match self {
            TcpOption::EndOfList => 1,
            TcpOption::NoOperation => 1,
            TcpOption::MaxSegmentSize(_) => 4,
            TcpOption::WindowScale(_) => 3,
            TcpOption::SackPermitted => 2,
            TcpOption::SackRange(s) => s.iter().filter(|s| s.is_some()).count() * 8 + 2,
            TcpOption::Unknown { data, .. } => 2 + data.len()
        }
    }

    /// Write the encoding into the buffer.
    ///
    /// Returns the remaining tail into which no data has been written.
    pub fn emit<'b>(&self, buffer: &'b mut [u8]) -> &'b mut [u8] {
        let length;
        match self {
            TcpOption::EndOfList => {
                length    = 1;
                // There may be padding space which also should be initialized.
                for p in buffer.iter_mut() {
                    *p = field::OPT_END;
                }
            }
            TcpOption::NoOperation => {
                length    = 1;
                buffer[0] = field::OPT_NOP;
            }
            _ => {
                length    = self.buffer_len();
                buffer[1] = length as u8;
                match *self {
                    TcpOption::EndOfList |
                    TcpOption::NoOperation =>
                        unreachable!("Covered by cases above"),
                    TcpOption::MaxSegmentSize(value) => {
                        buffer[0] = field::OPT_MSS;
                        NetworkEndian::write_u16(&mut buffer[2..], value)
                    }
                    TcpOption::WindowScale(value) => {
                        buffer[0] = field::OPT_WS;
                        buffer[2] = value;
                    }
                    TcpOption::SackPermitted => {
                        buffer[0] = field::OPT_SACKPERM;
                    }
                    TcpOption::SackRange(slice) => {
                        buffer[0] = field::OPT_SACKRNG;
                        slice.iter().filter(|s| s.is_some()).enumerate().for_each(|(i, s)| {
                            let (first, second) = *s.as_ref().unwrap();
                            let pos = i * 8 + 2;
                            NetworkEndian::write_u32(&mut buffer[pos..], first);
                            NetworkEndian::write_u32(&mut buffer[pos+4..], second);
                        });
                    }
                    TcpOption::Unknown { kind, data: provided } => {
                        buffer[0] = kind;
                        buffer[2..].copy_from_slice(provided)
                    }
                }
            }
        }
        &mut buffer[length..]
    }
}

/// A high-level representation of a Transmission Control Protocol packet.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Repr {
    /// The remote port from which a packet originated.
    pub src_port:     u16,
    /// The local port to which a packet is sent.
    pub dst_port:     u16,
    /// The collection of flag bits not handled explicitly in other attributes.
    pub flags:        Flags,
    /// The sequence number of the packet itself.
    /// In a SYN packet this identifies the SYN itself, during transmission it identifies the first
    /// byte of a segment in the data stream, and afterwards it is one-past-the-end of the FIN that
    /// was sent last.
    pub seq_number:   SeqNumber,
    /// The acknowledged sequence number.
    /// Tells the remote that the data stream until that point has been completely received.
    pub ack_number:   Option<SeqNumber>,
    /// The packet encoded window scale.
    /// To get the actual window scale one must shift as indicated in the header option set during
    /// the initial connection request.
    pub window_len:   u16,
    /// The window scale header option, if present.
    /// See [`TcpOption::WindowScale`](struct.TcpOption.html#variant.WindowScale).
    pub window_scale: Option<u8>,
    /// The maximum segment size option, if present.
    /// See [`TcpOption::MaxSegmentSize`](struct.TcpOption.html#variant.MaxSegmentSize).
    pub max_seg_size: Option<u16>,
    /// Is true if the SackPermitted option is present.
    /// See [`TcpOption::SackPermitted`](struct.TcpOption.html#variant.SackPermitted).
    pub sack_permitted: bool,
    /// The selective acknowledgement ranges.
    /// See [`TcpOption::SackRange`](struct.TcpOption.html#variant.SackRange).
    pub sack_ranges:  [Option<(u32, u32)>; 3],
    /// The length of the segment carried by the packet.
    pub payload_len:  u16,
}

/// Abstraction for checksum behaviour.
///
/// The checksum requires calculating a pseudo header for the upper layer protocol consisting of
/// src and dst address.
pub enum Checksum {
    /// Always fill the checksum and check if it exists.
    ///
    /// Note that the ip addresses must both have the same kind, IPv4 or IPv6.
    Manual {
        /// The ip source address.
        src_addr: ip::Address,
        /// The ip destination address.
        dst_addr: ip::Address,
    },

    /// Never inspect the checksum.
    ///
    /// This assumes that some layer below has already performed the necessary checks.
    Ignored,
}

impl Repr {
    /// Parse a Transmission Control Protocol packet and return a high-level representation.
    pub fn parse(
        packet: &impl Payload,
        checksum: Checksum,
    ) -> Result<Repr> {
        // FIXME: this is hacky because we know the packet doesn't inspect the repr for the
        // accessor functions below. Before we change it to do we need to introduce the separation
        // into a bytewrapper that the other packet structure enjoy.
        let packet = Packet::new_unchecked(packet, Repr {
            src_port: 0,
            dst_port: 0,
            flags: Flags(0),
            seq_number: SeqNumber(0),
            ack_number: None,
            window_len: 0,
            window_scale: None,
            max_seg_size: None,
            sack_permitted: false,
            sack_ranges: [None; 3],
            payload_len: 0,
        });
        packet.check_len()?;
        // Source and destination ports must be present.
        if packet.src_port() == 0 { return Err(Error::Malformed) }
        if packet.dst_port() == 0 { return Err(Error::Malformed) }

        // Valid checksum may be expected.
        if let Checksum::Manual { src_addr, dst_addr } = checksum {
            if !packet.verify_checksum(src_addr, dst_addr) {
                return Err(Error::WrongChecksum)
            }
        }

        let flags = packet.flags();
        let ack_number = if flags.ack() {
            Some(packet.ack_number())
        } else {
            None
        };
        // The PSH flag is ignored.
        // The URG flag and the urgent field is ignored. This behavior is standards-compliant,
        // however, most deployed systems (e.g. Linux) are *not* standards-compliant, and would
        // cut the byte at the urgent pointer from the stream.

        let mut max_seg_size = None;
        let mut window_scale = None;
        let mut options = packet.options();
        let mut sack_permitted = false;
        let mut sack_ranges = [None, None, None];
        while options.len() > 0 {
            let (next_options, option) = TcpOption::parse(options)?;
            match option {
                TcpOption::EndOfList => break,
                TcpOption::NoOperation => (),
                TcpOption::MaxSegmentSize(value) =>
                    max_seg_size = Some(value),
                TcpOption::WindowScale(value) => {
                    // RFC 1323: Thus, the shift count must be limited to 14 (which allows windows
                    // of 2**30 = 1 Gbyte). If a Window Scale option is received with a shift.cnt
                    // value exceeding 14, the TCP should log the error but use 14 instead of the
                    // specified value.
                    window_scale = if value > 14 {
                        net_debug!("{}: parsed window scaling factor >14, setting to 14");
                        Some(14)
                    } else {
                        Some(value)
                    };
                },
                TcpOption::SackPermitted =>
                    sack_permitted = true,
                TcpOption::SackRange(slice) =>
                    sack_ranges = slice,
                _ => (),
            }
            options = next_options;
        }

        Ok(Repr {
            src_port:     packet.src_port(),
            dst_port:     packet.dst_port(),
            flags:        flags,
            seq_number:   packet.seq_number(),
            ack_number:   ack_number,
            window_len:   packet.window_len(),
            window_scale: window_scale,
            max_seg_size: max_seg_size,
            sack_permitted: sack_permitted,
            sack_ranges:   sack_ranges,
            payload_len:  packet.payload_slice().len() as u16,
        })
    }

    /// Return the length of a header that will be emitted from this high-level representation.
    ///
    /// This should be used for buffer space calculations.
    /// The TCP header length is a multiple of 4.
    pub fn header_len(&self) -> usize {
        let mut length = field::URGENT.end;
        if self.max_seg_size.is_some() {
            length += 4
        }
        if self.window_scale.is_some() {
            length += 3
        }
        if self.sack_permitted {
            length += 2;
        }
        let sack_range_len: usize = self.sack_ranges.iter().map(
            |o| o.map(|_| 8).unwrap_or(0)
            ).sum();
        if sack_range_len > 0 {
            length += sack_range_len + 2;
        }
        if length % 4 != 0 {
            length += 4 - length % 4;
        }
        length
    }

    /// Return the length of the header for the TCP protocol.
    ///
    /// Per RFC 6691, this should be used for MSS calculations. It may be smaller than the buffer
    /// space required to accommodate this packet's data.
    pub fn mss_header_len(&self) -> usize {
        field::URGENT.end
    }

    /// Return the length of a packet that will be emitted from this high-level representation.
    pub fn buffer_len(&self) -> usize {
        usize::from(self.header_len()) + usize::from(self.payload_len)
    }

    /// Emit a high-level representation into a Transmission Control Protocol packet.
    pub fn emit<T>(&self, mut packet: Packet<&mut T>)
            where T: PayloadMut + ?Sized
    {
        packet.set_src_port(self.src_port);
        packet.set_dst_port(self.dst_port);
        packet.set_seq_number(self.seq_number);
        packet.set_ack_number(self.ack_number.unwrap_or(SeqNumber(0)));
        packet.set_window_len(self.window_len);
        packet.set_header_len(self.header_len() as u8);
        let mut flags = self.flags;
        flags.set_ack(self.ack_number.is_some());
        packet.set_flags(flags);
        {
            let mut options = packet.options_mut();
            if let Some(value) = self.window_scale {
                let tmp = options; options = TcpOption::WindowScale(value).emit(tmp);
            }
            if let Some(value) = self.max_seg_size {
                let tmp = options; options = TcpOption::MaxSegmentSize(value).emit(tmp);
            }
            if self.sack_permitted {
                let tmp = options; options = TcpOption::SackPermitted.emit(tmp);
            } else if self.ack_number.is_some() && self.sack_ranges.iter().any(|s| s.is_some()) {
                let tmp = options; options = TcpOption::SackRange(self.sack_ranges).emit(tmp);
            }

            if options.len() > 0 {
                TcpOption::EndOfList.emit(options);
            }
        }
        packet.set_urgent_at(0);
    }

    /// Return the length of the segment, in terms of sequence space.
    pub fn sequence_len(&self) -> usize {
        usize::from(self.payload_len) + self.flags.sequence_len()
    }

    /// Return whether the segment has no flags set (except PSH) and no data.
    pub fn is_empty(&self) -> bool {
        self.payload_len != 0 || {
            (self.flags.syn() | self.flags.fin() | self.flags.rst())
        }
    }
}

impl<'a, T: Payload + ?Sized> fmt::Display for Packet<&'a T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Cannot use Repr::parse because we don't have the IP addresses.
        // FIXME: this is STUPID
        write!(f, "TCP src={} dst={}", self.src_port(), self.dst_port())?;
        let flags = self.flags();
        write!(f, " flags={}", flags)?;
        write!(f, " seq={}", self.seq_number())?;
        if flags.ack() {
            write!(f, " ack={}", self.ack_number())?;
        }
        write!(f, " win={}", self.window_len())?;
        if flags.urg() {
            write!(f, " urg={}", self.urgent_at())?;
        }
        write!(f, " len={}", self.payload_slice().len())?;

        let mut options = self.options();
        while !options.is_empty() {
            let (next_options, option) =
                match TcpOption::parse(options) {
                    Ok(res) => res,
                    Err(err) => return write!(f, " ({})", err)
                };
            match option {
                TcpOption::EndOfList => break,
                TcpOption::NoOperation => (),
                TcpOption::MaxSegmentSize(value) =>
                    write!(f, " mss={}", value)?,
                TcpOption::WindowScale(value) =>
                    write!(f, " ws={}", value)?,
                TcpOption::SackPermitted =>
                    write!(f, " sACK")?,
                TcpOption::SackRange(slice) =>
                    write!(f, " sACKr{:?}", slice)?, // debug print conveniently includes the []s
                TcpOption::Unknown { kind, .. } =>
                    write!(f, " opt({})", kind)?,
            }
            options = next_options;
        }
        Ok(())
    }
}

impl fmt::Display for Repr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "TCP src={} dst={}", self.src_port, self.dst_port)?;
        write!(f, " flags={}", self.flags)?;
        write!(f, " seq={}", self.seq_number)?;
        if let Some(ack_number) = self.ack_number {
            write!(f, " ack={}", ack_number)?;
        }
        write!(f, " win={}", self.window_len)?;
        write!(f, " len={}", self.payload_len)?;
        if let Some(max_seg_size) = self.max_seg_size {
            write!(f, " mss={}", max_seg_size)?;
        }
        Ok(())
    }
}

impl fmt::Display for Flags {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        const SYN_ACK: Flags = Flags::SYN.const_or(Flags::ACK);
        const FIN_ACK: Flags = Flags::FIN.const_or(Flags::ACK);
        const RST_ACK: Flags = Flags::RST.const_or(Flags::ACK);
        const PSH_ACK: Flags = Flags::PSH.const_or(Flags::ACK);
        const PSH_FIN_ACK: Flags = Flags::PSH.const_or(Flags::FIN).const_or(Flags::ACK);

        match *self {
            // Common combinations you would expect to see.
            Flags::SYN => write!(f, "syn")?,
            Flags::FIN => write!(f, "fin")?,
            Flags::RST => write!(f, "rst")?,
            Flags::PSH => write!(f, "psh")?,
            SYN_ACK => write!(f, "syn+ack")?,
            FIN_ACK => write!(f, "fin+ack")?,
            RST_ACK => write!(f, "rst+ack")?,
            PSH_ACK => write!(f, "psh+ack")?,
            PSH_FIN_ACK => write!(f, "psh+fin+ack")?,
            Flags::NONE => write!(f, "none")?,
            // All uncommon or even illegal ones (e.g. PSH without ACK).
            Flags(other) => write!(f, "{:#x}", other)?,
        }

        Ok(())
    }
}

impl<T: Payload> PrettyPrint for Packet<T> {
    fn pretty_print(buffer: &[u8], f: &mut fmt::Formatter,
                    indent: &mut PrettyIndent) -> fmt::Result {
        match Packet::new_checked(buffer, Checksum::Ignored) {
            Err(err)   => write!(f, "{}({})", indent, err),
            Ok(packet) => write!(f, "{}{}", indent, packet)
        }
    }
}

#[cfg(test)]
mod test {
    use crate::wire::ip::v4::Address as Ipv4Address;
    use super::*;

    const SRC_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 1]);
    const DST_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 2]);

    static PACKET_BYTES: [u8; 28] =
        [0xbf, 0x00, 0x00, 0x50,
         0x01, 0x23, 0x45, 0x67,
         0x89, 0xab, 0xcd, 0xef,
         0x60, 0x35, 0x01, 0x23,
         0x01, 0xb6, 0x02, 0x01,
         0x03, 0x03, 0x0c, 0x01,
         0xaa, 0x00, 0x00, 0xff];

    static OPTION_BYTES: [u8; 4] =
        [0x03, 0x03, 0x0c, 0x01];

    static PAYLOAD_BYTES: [u8; 4] =
        [0xaa, 0x00, 0x00, 0xff];

    #[test]
    fn test_deconstruct() {
        let packet = Packet::new_checked(&PACKET_BYTES[..], Checksum::Ignored).unwrap();
        assert_eq!(packet.src_port(), 48896);
        assert_eq!(packet.dst_port(), 80);
        assert_eq!(packet.seq_number(), SeqNumber(0x01234567));
        assert_eq!(packet.ack_number(), SeqNumber(0x89abcdefu32 as i32));
        assert_eq!(packet.header_len(), 24);
        assert_eq!(packet.flags().fin(), true);
        assert_eq!(packet.flags().syn(), false);
        assert_eq!(packet.flags().rst(), true);
        assert_eq!(packet.flags().psh(), false);
        assert_eq!(packet.flags().ack(), true);
        assert_eq!(packet.flags().urg(), true);
        assert_eq!(packet.window_len(), 0x0123);
        assert_eq!(packet.urgent_at(), 0x0201);
        assert_eq!(packet.checksum(), 0x01b6);
        assert_eq!(packet.options(), &OPTION_BYTES[..]);
        assert_eq!(packet.payload_slice(), &PAYLOAD_BYTES[..]);
        assert_eq!(packet.verify_checksum(SRC_ADDR.into(), DST_ADDR.into()), true);
    }

    #[test]
    fn test_construct() {
        let mut bytes = vec![0xa5; PACKET_BYTES.len()];
        // FIXME: Crafts the packet with a fake repr before overwriting everything. This doesn't
        // change the results but we shouldn't need to do this.
        let mut packet = Packet::new_unchecked(&mut bytes, packet_repr());
        packet.set_src_port(48896);
        packet.set_dst_port(80);
        packet.set_seq_number(SeqNumber(0x01234567));
        packet.set_ack_number(SeqNumber(0x89abcdefu32 as i32));
        packet.set_header_len(24);
        let mut flags = Flags::default();
        flags.set_fin(true);
        flags.set_syn(false);
        flags.set_rst(true);
        flags.set_psh(false);
        flags.set_ack(true);
        flags.set_urg(true);
        packet.set_flags(flags);
        packet.set_window_len(0x0123);
        packet.set_urgent_at(0x0201);
        packet.set_checksum(0xEEEE);
        packet.options_mut().copy_from_slice(&OPTION_BYTES[..]);
        packet.payload_mut_slice().copy_from_slice(&PAYLOAD_BYTES[..]);
        packet.fill_checksum(SRC_ADDR.into(), DST_ADDR.into());
        assert_eq!(&packet.into_inner()[..], &PACKET_BYTES[..]);
    }

    #[test]
    fn test_truncated() {
        let packet = Packet::new_checked(&PACKET_BYTES[..23], Checksum::Ignored);
        assert_eq!(packet, Err(Error::Truncated));
    }

    #[test]
    fn test_impossible_len() {
        let mut bytes = vec![0; 20];
        let mut packet = Packet::new_unchecked(&mut bytes, packet_repr());
        packet.set_header_len(10);
        assert_eq!(packet.check_len(), Err(Error::Malformed));
    }

    static SYN_PACKET_BYTES: [u8; 24] =
        [0xbf, 0x00, 0x00, 0x50,
         0x01, 0x23, 0x45, 0x67,
         0x00, 0x00, 0x00, 0x00,
         0x50, 0x02, 0x01, 0x23,
         0x7a, 0x8d, 0x00, 0x00,
         0xaa, 0x00, 0x00, 0xff];

    fn packet_repr() -> Repr {
        Repr {
            src_port:     48896,
            dst_port:     80,
            seq_number:   SeqNumber(0x01234567),
            ack_number:   None,
            window_len:   0x0123,
            window_scale: None,
            flags:        Flags::SYN,
            max_seg_size: None,
            sack_permitted: false,
            sack_ranges:  [None, None, None],
            payload_len:  PAYLOAD_BYTES.len() as _,
        }
    }

    #[test]
    fn test_parse() {
        let packet = Packet::new_checked(
            &SYN_PACKET_BYTES[..],
            Checksum::Manual { src_addr: SRC_ADDR.into(), dst_addr: DST_ADDR.into(), })
        .unwrap();
        assert_eq!(packet.repr(), packet_repr());
        assert_eq!(packet.payload_slice(), &PAYLOAD_BYTES[..]);
    }

    #[test]
    fn test_emit() {
        let repr = packet_repr();
        let mut bytes = vec![0xa5; repr.buffer_len()];
        repr.emit(Packet::new_unchecked(&mut bytes, repr));
        let mut packet = Packet::new_unchecked(&mut bytes, repr);
        packet.payload_mut_slice().copy_from_slice(&PAYLOAD_BYTES);
        packet.fill_checksum(SRC_ADDR.into(), DST_ADDR.into());
        assert_eq!(&packet.into_inner()[..], &SYN_PACKET_BYTES[..]);
    }

    #[test]
    fn test_header_len_multiple_of_4() {
        let mut repr = packet_repr();
        repr.window_scale = Some(0); // This TCP Option needs 3 bytes.
        assert_eq!(repr.header_len() % 4, 0); // Should e.g. be 28 instead of 27.
    }

    macro_rules! assert_option_parses {
        ($opt:expr, $data:expr) => ({
            assert_eq!(TcpOption::parse($data), Ok((&[][..], $opt)));
            let buffer = &mut [0; 40][..$opt.buffer_len()];
            assert_eq!($opt.emit(buffer), &mut []);
            assert_eq!(&*buffer, $data);
        })
    }

    #[test]
    fn test_tcp_options() {
        assert_option_parses!(TcpOption::EndOfList,
                              &[0x00]);
        assert_option_parses!(TcpOption::NoOperation,
                              &[0x01]);
        assert_option_parses!(TcpOption::MaxSegmentSize(1500),
                              &[0x02, 0x04, 0x05, 0xdc]);
        assert_option_parses!(TcpOption::WindowScale(12),
                              &[0x03, 0x03, 0x0c]);
        assert_option_parses!(TcpOption::SackPermitted,
                              &[0x4, 0x02]);
        assert_option_parses!(TcpOption::SackRange([Some((500, 1500)), None, None]),
                              &[0x05, 0x0a,
                                0x00, 0x00, 0x01, 0xf4, 0x00, 0x00, 0x05, 0xdc]);
        assert_option_parses!(TcpOption::SackRange([Some((875, 1225)), Some((1500, 2500)), None]),
                              &[0x05, 0x12,
                                0x00, 0x00, 0x03, 0x6b, 0x00, 0x00, 0x04, 0xc9,
                                0x00, 0x00, 0x05, 0xdc, 0x00, 0x00, 0x09, 0xc4]);
        assert_option_parses!(TcpOption::SackRange([Some((875000, 1225000)),
                                                    Some((1500000, 2500000)),
                                                    Some((876543210, 876654320))]),
                              &[0x05, 0x1a,
                                0x00, 0x0d, 0x59, 0xf8, 0x00, 0x12, 0xb1, 0x28,
                                0x00, 0x16, 0xe3, 0x60, 0x00, 0x26, 0x25, 0xa0,
                                0x34, 0x3e, 0xfc, 0xea, 0x34, 0x40, 0xae, 0xf0]);
        assert_option_parses!(TcpOption::Unknown { kind: 12, data: &[1, 2, 3][..] },
                              &[0x0c, 0x05, 0x01, 0x02, 0x03])
    }

    #[test]
    fn test_malformed_tcp_options() {
        assert_eq!(TcpOption::parse(&[]),
                   Err(Error::Truncated));
        assert_eq!(TcpOption::parse(&[0xc]),
                   Err(Error::Truncated));
        assert_eq!(TcpOption::parse(&[0xc, 0x05, 0x01, 0x02]),
                   Err(Error::Truncated));
        assert_eq!(TcpOption::parse(&[0xc, 0x01]),
                   Err(Error::Truncated));
        assert_eq!(TcpOption::parse(&[0x2, 0x02]),
                   Err(Error::Malformed));
        assert_eq!(TcpOption::parse(&[0x3, 0x02]),
                   Err(Error::Malformed));
    }
}