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
use super::super::*;
use std::net::Ipv4Addr;
use std::fmt::{Debug, Formatter};
use std::slice::from_raw_parts;
#[derive(Clone)]
pub struct Ipv4Header {
pub differentiated_services_code_point: u8,
pub explicit_congestion_notification: u8,
pub payload_len: u16,
pub identification: u16,
pub dont_fragment: bool,
pub more_fragments: bool,
pub fragments_offset: u16,
pub time_to_live: u8,
pub protocol: u8,
pub header_checksum: u16,
pub source: [u8;4],
pub destination: [u8;4],
options_len: u8,
options_buffer: [u8;40]
}
impl SerializedSize for Ipv4Header {
const SERIALIZED_SIZE:usize = 20;
}
const IPV4_MAX_OPTIONS_LENGTH: usize = 10*4;
impl Ipv4Header {
pub fn new(payload_len: u16, time_to_live: u8, protocol: IpNumber, source: [u8;4], destination: [u8;4]) -> Ipv4Header {
Ipv4Header {
differentiated_services_code_point: 0,
explicit_congestion_notification: 0,
payload_len,
identification: 0,
dont_fragment: true,
more_fragments: false,
fragments_offset: 0,
time_to_live,
protocol: protocol as u8,
header_checksum: 0,
source,
destination,
options_len: 0,
options_buffer: [0;40]
}
}
pub fn ihl(&self) -> u8 {
(self.options_len/4) + 5
}
pub fn options(&self) -> &[u8] {
&self.options_buffer[..usize::from(self.options_len)]
}
#[inline]
pub fn header_len(&self) -> usize {
Ipv4Header::SERIALIZED_SIZE + usize::from(self.options_len)
}
pub fn total_len(&self) -> u16 {
self.payload_len + (Ipv4Header::SERIALIZED_SIZE as u16) + u16::from(self.options_len)
}
pub fn set_payload_len(&mut self, value: usize) -> Result<(), ValueError> {
if usize::from(self.max_payload_len()) < value {
use crate::ValueError::*;
Err(Ipv4PayloadLengthTooLarge(value))
} else {
self.payload_len = value as u16;
Ok(())
}
}
pub fn max_payload_len(&self) -> u16 {
std::u16::MAX - u16::from(self.options_len) - (Ipv4Header::SERIALIZED_SIZE as u16)
}
pub fn set_options(&mut self, data: &[u8]) -> Result<(), ValueError> {
use crate::ValueError::*;
if (IPV4_MAX_OPTIONS_LENGTH < data.len()) ||
(0 != data.len() % 4)
{
Err(Ipv4OptionsLengthBad(data.len()))
} else {
self.options_buffer[..data.len()].copy_from_slice(data);
self.options_len = data.len() as u8;
Ok(())
}
}
#[deprecated(
since = "0.10.1",
note = "Renamed to `Ipv4Header::from_slice`"
)]
#[inline]
pub fn read_from_slice(slice: &[u8]) -> Result<(Ipv4Header, &[u8]), ReadError> {
Ipv4Header::from_slice(slice)
}
pub fn from_slice(slice: &[u8]) -> Result<(Ipv4Header, &[u8]), ReadError> {
let header = Ipv4HeaderSlice::from_slice(slice)?.to_header();
let rest = &slice[header.header_len()..];
Ok((
header,
rest
))
}
pub fn read<T: io::Read + io::Seek + Sized>(reader: &mut T) -> Result<Ipv4Header, ReadError> {
let mut first_byte : [u8;1] = [0;1];
reader.read_exact(&mut first_byte)?;
let version = first_byte[0] >> 4;
if 4 != version {
return Err(ReadError::Ipv4UnexpectedVersion(version));
}
Ipv4Header::read_without_version(reader, first_byte[0])
}
pub fn read_without_version<T: io::Read + io::Seek + Sized>(reader: &mut T, first_byte: u8) -> Result<Ipv4Header, ReadError> {
let mut header_raw : [u8;20] = [0;20];
header_raw[0] = first_byte;
reader.read_exact(&mut header_raw[1..])?;
let ihl = header_raw[0] & 0xf;
if ihl < 5 {
use crate::ReadError::*;
return Err(Ipv4HeaderLengthBad(ihl));
}
let (dscp, ecn) = {
let value = header_raw[1];
(value >> 2, value & 0x3)
};
let header_length = u16::from(ihl)*4;
let total_length = u16::from_be_bytes([header_raw[2], header_raw[3]]);
if total_length < header_length {
use crate::ReadError::*;
return Err(Ipv4TotalLengthTooSmall(total_length));
}
let identification = u16::from_be_bytes([header_raw[4], header_raw[5]]);
let (dont_fragment, more_fragments, fragments_offset) = (
0 != (header_raw[6] & 0b0100_0000),
0 != (header_raw[6] & 0b0010_0000),
u16::from_be_bytes(
[header_raw[6] & 0b0001_1111, header_raw[7]]
)
);
Ok(Ipv4Header{
differentiated_services_code_point: dscp,
explicit_congestion_notification: ecn,
payload_len: total_length - header_length,
identification,
dont_fragment,
more_fragments,
fragments_offset,
time_to_live: header_raw[8],
protocol: header_raw[9],
header_checksum: u16::from_be_bytes([header_raw[10], header_raw[11]]),
source: [header_raw[12], header_raw[13], header_raw[14], header_raw[15]],
destination: [header_raw[16], header_raw[17], header_raw[18], header_raw[19]],
options_len: (ihl - 5)*4,
options_buffer: {
let mut values: [u8;40] = [0;40];
let options_len = usize::from(ihl - 5)*4;
if options_len > 0 {
reader.read_exact(&mut values[..options_len])?;
}
values
},
})
}
pub fn check_ranges(&self) -> Result<(), ValueError> {
use crate::ErrorField::*;
max_check_u8(self.differentiated_services_code_point, 0x3f, Ipv4Dscp)?;
max_check_u8(self.explicit_congestion_notification, 0x3, Ipv4Ecn)?;
max_check_u16(self.fragments_offset, 0x1fff, Ipv4FragmentsOffset)?;
max_check_u16(self.payload_len, self.max_payload_len(), Ipv4PayloadLength)?;
Ok(())
}
pub fn write<T: io::Write + Sized>(&self, writer: &mut T) -> Result<(), WriteError> {
self.check_ranges()?;
self.write_ipv4_header_internal(writer, self.calc_header_checksum_unchecked())
}
pub fn write_raw<T: io::Write + Sized>(&self, writer: &mut T) -> Result<(), WriteError> {
self.check_ranges()?;
self.write_ipv4_header_internal(writer, self.header_checksum)
}
fn write_ipv4_header_internal<T: io::Write>(&self, write: &mut T, header_checksum: u16) -> Result<(), WriteError> {
let total_len_be = self.total_len().to_be_bytes();
let id_be = self.identification.to_be_bytes();
let frag_and_flags = {
let frag_be: [u8;2] = self.fragments_offset.to_be_bytes();
let flags = {
let mut result = 0;
if self.dont_fragment {
result |= 64;
}
if self.more_fragments {
result |= 32;
}
result
};
[
flags | (frag_be[0] & 0x1f),
frag_be[1],
]
};
let header_checksum_be = header_checksum.to_be_bytes();
let header_raw = [
(4 << 4) | self.ihl(),
(self.differentiated_services_code_point << 2) | self.explicit_congestion_notification,
total_len_be[0],
total_len_be[1],
id_be[0],
id_be[1],
frag_and_flags[0],
frag_and_flags[1],
self.time_to_live,
self.protocol,
header_checksum_be[0],
header_checksum_be[1],
self.source[0],
self.source[1],
self.source[2],
self.source[3],
self.destination[0],
self.destination[1],
self.destination[2],
self.destination[3],
];
write.write_all(&header_raw)?;
write.write_all(self.options())?;
Ok(())
}
pub fn calc_header_checksum(&self) -> Result<u16, ValueError> {
self.check_ranges()?;
Ok(self.calc_header_checksum_unchecked())
}
fn calc_header_checksum_unchecked(&self) -> u16 {
checksum::Sum16BitWords::new()
.add_2bytes(
[
(4 << 4) | self.ihl(),
(self.differentiated_services_code_point << 2) | self.explicit_congestion_notification
]
)
.add_2bytes(self.total_len().to_be_bytes())
.add_2bytes(self.identification.to_be_bytes())
.add_2bytes(
{
let frag_off_be = self.fragments_offset.to_be_bytes();
let flags = {
let mut result = 0;
if self.dont_fragment {
result |= 64;
}
if self.more_fragments {
result |= 32;
}
result
};
[
flags | (frag_off_be[0] & 0x1f),
frag_off_be[1]
]
}
)
.add_2bytes([self.time_to_live, self.protocol])
.add_4bytes(self.source)
.add_4bytes(self.destination)
.add_slice(self.options())
.ones_complement()
.to_be()
}
#[inline]
pub fn is_fragmenting_payload(&self) -> bool {
self.more_fragments ||
(0 != self.fragments_offset)
}
}
impl Default for Ipv4Header {
fn default() -> Ipv4Header {
Ipv4Header {
differentiated_services_code_point: 0,
explicit_congestion_notification: 0,
payload_len: 0,
identification: 0,
dont_fragment: true,
more_fragments: false,
fragments_offset: 0,
time_to_live: 0,
protocol: 0,
header_checksum: 0,
source: [0;4],
destination: [0;4],
options_len: 0,
options_buffer: [0;40]
}
}
}
impl Debug for Ipv4Header {
fn fmt(&self, fotmatter: &mut Formatter) -> Result<(), std::fmt::Error> {
write!(fotmatter, "Ipv4Header {{ ihl: {}, differentiated_services_code_point: {}, explicit_congestion_notification: {}, payload_len: {}, identification: {}, dont_fragment: {}, more_fragments: {}, fragments_offset: {}, time_to_live: {}, protocol: {}, header_checksum: {}, source: {:?}, destination: {:?}, options: {:?} }}",
self.ihl(),
self.differentiated_services_code_point,
self.explicit_congestion_notification,
self.payload_len,
self.identification,
self.dont_fragment,
self.more_fragments,
self.fragments_offset,
self.time_to_live,
self.protocol,
self.header_checksum,
self.source,
self.destination,
self.options())
}
}
impl std::cmp::PartialEq for Ipv4Header {
fn eq(&self, other: &Ipv4Header) -> bool {
self.differentiated_services_code_point == other.differentiated_services_code_point &&
self.explicit_congestion_notification == other.explicit_congestion_notification &&
self.payload_len == other.payload_len &&
self.identification == other.identification &&
self.dont_fragment == other.dont_fragment &&
self.more_fragments == other.more_fragments &&
self.fragments_offset == other.fragments_offset &&
self.time_to_live == other.time_to_live &&
self.protocol == other.protocol &&
self.header_checksum == other.header_checksum &&
self.source == other.source &&
self.destination == other.destination &&
self.options_len == other.options_len &&
self.options() == other.options()
}
}
impl std::cmp::Eq for Ipv4Header {}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv4HeaderSlice<'a> {
slice: &'a [u8]
}
impl<'a> Ipv4HeaderSlice<'a> {
pub fn from_slice(slice: &'a[u8]) -> Result<Ipv4HeaderSlice<'a>, ReadError> {
use crate::ReadError::*;
if slice.len() < Ipv4Header::SERIALIZED_SIZE {
return Err(UnexpectedEndOfSlice(Ipv4Header::SERIALIZED_SIZE));
}
let (version, ihl) = unsafe {
let value = slice.get_unchecked(0);
(value >> 4, value & 0xf)
};
if 4 != version {
return Err(Ipv4UnexpectedVersion(version));
}
if ihl < 5 {
use crate::ReadError::*;
return Err(Ipv4HeaderLengthBad(ihl));
}
let header_length = (usize::from(ihl))*4;
if slice.len() < header_length {
return Err(UnexpectedEndOfSlice(header_length));
}
let total_length = unsafe {
get_unchecked_be_u16(slice.as_ptr().add(2))
};
if total_length < header_length as u16 {
return Err(Ipv4TotalLengthTooSmall(total_length))
}
Ok(Ipv4HeaderSlice {
slice: unsafe {
from_raw_parts(
slice.as_ptr(),
header_length
)
}
})
}
#[inline]
pub fn slice(&self) -> &'a [u8] {
self.slice
}
#[inline]
pub fn version(&self) -> u8 {
unsafe {
*self.slice.get_unchecked(0) >> 4
}
}
#[inline]
pub fn ihl(&self) -> u8 {
unsafe {
*self.slice.get_unchecked(0) & 0xf
}
}
#[inline]
pub fn dcp(&self) -> u8 {
unsafe {
*self.slice.get_unchecked(1) >> 2
}
}
#[inline]
pub fn ecn(&self) -> u8 {
unsafe {
*self.slice.get_unchecked(1) & 0x3
}
}
#[inline]
pub fn total_len(&self) -> u16 {
unsafe {
get_unchecked_be_u16(self.slice.as_ptr().add(2))
}
}
#[inline]
pub fn payload_len(&self) -> u16 {
self.total_len() - u16::from(self.ihl())*4
}
#[inline]
pub fn identification(&self) -> u16 {
unsafe {
get_unchecked_be_u16(self.slice.as_ptr().add(4))
}
}
#[inline]
pub fn dont_fragment(&self) -> bool {
unsafe {
0 != (*self.slice.get_unchecked(6) & 0x40)
}
}
#[inline]
pub fn more_fragments(&self) -> bool {
unsafe {
0 != (*self.slice.get_unchecked(6) & 0x20)
}
}
#[inline]
pub fn fragments_offset(&self) -> u16 {
u16::from_be_bytes(
unsafe {
[
*self.slice.get_unchecked(6) & 0x1f,
*self.slice.get_unchecked(7)
]
}
)
}
#[inline]
pub fn ttl(&self) -> u8 {
unsafe {
*self.slice.get_unchecked(8)
}
}
#[inline]
pub fn protocol(&self) -> u8 {
unsafe {
*self.slice.get_unchecked(9)
}
}
#[inline]
pub fn header_checksum(&self) -> u16 {
unsafe {
get_unchecked_be_u16(self.slice.as_ptr().add(10))
}
}
#[inline]
pub fn source(&self) -> [u8;4] {
unsafe {
get_unchecked_4_byte_array(self.slice.as_ptr().add(12))
}
}
pub fn source_addr(&self) -> Ipv4Addr {
Ipv4Addr::from(self.source())
}
#[inline]
pub fn destination(&self) -> [u8;4] {
unsafe {
get_unchecked_4_byte_array(self.slice.as_ptr().add(16))
}
}
pub fn destination_addr(&self) -> Ipv4Addr {
Ipv4Addr::from(self.destination())
}
#[inline]
pub fn options(&self) -> &'a [u8] {
unsafe {
from_raw_parts(
self.slice.as_ptr().add(20),
self.slice.len() - 20
)
}
}
#[inline]
pub fn is_fragmenting_payload(&self) -> bool {
self.more_fragments() ||
(0 != self.fragments_offset())
}
pub fn to_header(&self) -> Ipv4Header {
let options = self.options();
Ipv4Header {
differentiated_services_code_point: self.dcp(),
explicit_congestion_notification: self.ecn(),
payload_len: self.payload_len(),
identification: self.identification(),
dont_fragment: self.dont_fragment(),
more_fragments: self.more_fragments(),
fragments_offset: self.fragments_offset(),
time_to_live: self.ttl(),
protocol: self.protocol(),
header_checksum: self.header_checksum(),
source: self.source(),
destination: self.destination(),
options_len: options.len() as u8,
options_buffer: {
let mut result: [u8;40] = [0;40];
result[..options.len()].copy_from_slice(options);
result
}
}
}
}