-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathip4.rs
558 lines (510 loc) · 16.4 KB
/
ip4.rs
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
use crate::errors::Error;
use core::ops::Deref;
/// List of all private subnets.
///
/// An IP is considered public if it is not part of a private range. Private ranges are considered
/// to be:
///
/// - 0.0.0.0/8 - current network
/// - 10.0.0.0/8 - private network
/// - 100.64.0.0/10 - carrier grade NAT
/// - 127.0.0.0/8 - loopback addresses
/// - 169.254.0.0/16 - link-local addresses
/// - 172.16.0.0/12 - private network
/// - 192.0.2.0/24 - TEST-NET-1, documentation and examples
/// - 192.168.0.0/16 - private network
/// - 198.18.0.0/15 - private -network - benchmark testing inter-networking
/// - 198.51.100.0/24 - TEST-NET-2, documentation and examples
/// - 203.0.113.0/24 - TEST-NET-3, documentation and examples
/// - 255.255.255.255/32 - Limited broadcast range
const PRIVATE_IP4_SUBNETS: [CIDR; 12] = [
CIDR::new(Ip::new([0, 0, 0, 0]), 8),
CIDR::new(Ip::new([10, 0, 0, 0]), 8),
CIDR::new(Ip::new([100, 64, 0, 0]), 10),
CIDR::new(Ip::new([127, 0, 0, 0]), 8),
CIDR::new(Ip::new([169, 254, 0, 0]), 16),
CIDR::new(Ip::new([172, 16, 0, 0]), 12),
CIDR::new(Ip::new([192, 0, 2, 0]), 24),
CIDR::new(Ip::new([192, 168, 0, 0]), 16),
CIDR::new(Ip::new([198, 18, 0, 0]), 15),
CIDR::new(Ip::new([198, 51, 100, 0]), 24),
CIDR::new(Ip::new([203, 0, 113, 0]), 24),
CIDR::new(Ip::new([255, 255, 255, 255]), 32),
];
/// A plain IPv4 address without network mask.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct Ip {
octets: [u8; 4],
}
/// A CIDR represented by a prefix and a mask
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CIDR {
ip: Ip,
mask: u8,
}
impl Ip {
/// Create a new IPv4 address with the given octets.
#[inline]
pub const fn new(octets: [u8; 4]) -> Ip {
Ip { octets }
}
/// Extracts the octets from the IP as a byte array.
#[inline]
pub const fn as_octets(&self) -> [u8; 4] {
self.octets
}
/// Interpret the IP address as the bit sequence
#[inline]
pub const fn as_bits(&self) -> u32 {
(self.octets[0] as u32) << 24
| (self.octets[1] as u32) << 16
| (self.octets[2] as u32) << 8
| (self.octets[3] as u32)
}
/// Checks if an IP is unicast or not.
///
/// Technically this can still be an anycast IP, for instance 1.1.1.1 or 8.8.8.8, but there is
/// no functional difference from the client perspective.
#[inline]
pub const fn is_unicast(&self) -> bool {
// 224.0.0.0/4 -> multicast range.
// 240.0.0.0/4 -> reserved for future use.
// Hence we consider all the remaining to be unicast.
self.octets[0] < 224
}
/// Checks if an IP is in the public ranges or not.
pub fn is_public(&self) -> bool {
for pip in &PRIVATE_IP4_SUBNETS {
// Ensure only part of the prefix is set
if self.as_bits() & pip.as_bitmask() == pip.as_prefix().as_bits() {
return false;
}
}
true
}
/// Parses ACII input bytes to an IPv4 address.
pub fn parse(input: &[u8]) -> Result<Ip, Error> {
if input.len() < 7 {
return Err(Error::InputTooShort);
}
if input.len() > 15 {
return Err(Error::InputTooLong);
}
let mut sections = 0;
// See below why this is true
let mut last_char_was_dot = true;
let mut octets = [0, 0, 0, 0];
// Use a u8 accumulator since octests are u8. This way we can use checked operations, and if we
// have an overflow we know there is an invalid value;
let mut accumulator: u8 = 0;
for c in input {
match c {
b'0'..=b'9' => {
// Don't allow leading digits 0.
// Need to allow single 0 digits though. Instead if doing a look ahead for a '.'
// character, we fail if accumulator is at 0 and the last char was not a dot.
// This works because we start with the last_char_was_dot flag set to true.
if accumulator == 0 && !last_char_was_dot {
return Err(Error::LeadingZero);
}
accumulator = if let Some(a) = accumulator.checked_mul(10) {
a
} else {
return Err(Error::OctetOverflow);
};
accumulator = if let Some(a) = accumulator.checked_add(c - b'0') {
a
} else {
return Err(Error::OctetOverflow);
};
// clear flag
last_char_was_dot = false;
}
b'.' => {
if last_char_was_dot {
return Err(Error::MissingOctet);
}
// set octet value
octets[sections] = accumulator;
// advance section
sections += 1;
accumulator = 0;
// shield if there are too many sections
if sections > 3 {
return Err(Error::TooManyOctets);
}
// set flag
last_char_was_dot = true;
}
_ => return Err(Error::IllegalCharacter),
}
}
// At this point the last section can't be saved yet
octets[sections] = accumulator;
// Sections must only be 3 here since we have 0 based indexing
if sections < 3 {
Err(Error::InsufficientOctets)
} else if last_char_was_dot {
Err(Error::MissingOctet)
} else {
Ok(Ip { octets })
}
}
}
impl Deref for Ip {
type Target = [u8; 4];
fn deref(&self) -> &Self::Target {
&self.octets
}
}
impl CIDR {
/// Create a new CIDR from octets and a mask.
///
/// # Panics
///
/// This function panics if mask is higher than 32.
#[inline]
pub const fn new(ip: Ip, mask: u8) -> CIDR {
if mask > 32 {
panic!("CIDR mask can't be higher than 32");
}
CIDR { ip, mask }
}
/// Extracts the prefix from the CIDR as a byte array.
#[inline]
pub const fn as_prefix(&self) -> Ip {
self.ip
}
/// Extracts the mask from the CIDR as a byte.
#[inline]
pub const fn as_mask(&self) -> u8 {
self.mask
}
/// Checks if an IP is unicast or not.
///
/// Technically this can still be an anycast IP, for instance 1.1.1.1 or 8.8.8.8, but there is
/// no functional difference from the client perspective.
#[inline]
pub const fn is_unicast(&self) -> bool {
self.ip.is_unicast()
}
/// Get the mask value as bitmask with the fixed bits set (111...000).
#[inline]
pub const fn as_bitmask(&self) -> u32 {
// u64 so we don't have overflow on /32
// TODO: benchmark if looping with shifts is faster
!((2_u64.pow(32 - self.mask as u32) - 1) as u32)
}
/// Checks if an IP is in the public ranges or not.
#[inline]
pub fn is_public(&self) -> bool {
self.ip.is_public()
}
/// Parses ASCII input bytes to an IPv4 in CIDR notation.
pub fn parse(input: &[u8]) -> Result<CIDR, Error> {
// Input can be at most 18 bytes.
if input.len() > 18 {
return Err(Error::InputTooLong);
}
let sep_pos = if let Some(pos) = input.iter().position(|c| c == &b'/') {
pos
} else {
return Err(Error::MissingMask);
};
let ip = Ip::parse(&input[..sep_pos])?;
let mask_input = &input[sep_pos + 1..];
if mask_input.len() > 2 {
return Err(Error::InputTooLong);
}
if mask_input.is_empty() {
return Err(Error::InputTooShort);
}
let mut mask: u8 = 0;
for c in mask_input {
match c {
b'0'..=b'9' => {
// only 2 digits max so we can never overflow a u8, no need for checked mul and add.
mask *= 10;
mask += c - b'0';
}
_ => return Err(Error::IllegalCharacter),
}
}
// 32 bits max in an IPv4, also if mask is 0 it must be single digit.
if mask > 32 {
return Err(Error::MaskOverflow);
}
if mask == 0 && mask_input.len() > 1 {
return Err(Error::LeadingZero);
}
Ok(CIDR { ip, mask })
}
/// Checks if an [`Ip`] is contained in this subnet.
#[inline]
pub const fn contains(&self, ip: Ip) -> bool {
let mask_bits = self.as_bitmask();
ip.as_bits() & mask_bits == self.ip.as_bits() & mask_bits
}
}
#[cfg(test)]
mod tests {
use crate::errors::Error;
#[test]
fn parse_valid_ips() {
assert_eq!(
super::Ip::parse("1.1.1.1".as_bytes()),
Ok(super::Ip::new([1, 1, 1, 1]))
);
assert_eq!(
super::Ip::parse("100.200.10.0".as_bytes()),
Ok(super::Ip::new([100, 200, 10, 0]))
);
assert_eq!(
super::Ip::parse("255.255.255.255".as_bytes()),
Ok(super::Ip::new([255, 255, 255, 255]))
);
assert_eq!(
super::Ip::parse("0.0.0.0".as_bytes()),
Ok(super::Ip::new([0, 0, 0, 0]))
);
}
#[test]
fn reject_invalid_ips() {
assert_eq!(
super::Ip::parse("1.1.1.1.".as_bytes()),
Err(Error::TooManyOctets)
);
assert_eq!(
super::Ip::parse("1.1.1.1.1".as_bytes()),
Err(Error::TooManyOctets)
);
assert_eq!(
super::Ip::parse("1.1.1.".as_bytes()),
Err(Error::InputTooShort)
);
assert_eq!(
super::Ip::parse("1.1.1".as_bytes()),
Err(Error::InputTooShort)
);
assert_eq!(
super::Ip::parse("100.100.1".as_bytes()),
Err(Error::InsufficientOctets)
);
assert_eq!(
super::Ip::parse("100.100.1.".as_bytes()),
Err(Error::MissingOctet)
);
assert_eq!(
super::Ip::parse("255.255.255.256".as_bytes()),
Err(Error::OctetOverflow)
);
assert_eq!(
super::Ip::parse("256.255.255.255".as_bytes()),
Err(Error::OctetOverflow)
);
assert_eq!(
super::Ip::parse("1.10.100.1000".as_bytes()),
Err(Error::OctetOverflow)
);
assert_eq!(
super::Ip::parse("1000.100.10.1".as_bytes()),
Err(Error::OctetOverflow)
);
assert_eq!(
super::Ip::parse("af.fe.ff.ac".as_bytes()),
Err(Error::IllegalCharacter)
);
assert_eq!(
super::Ip::parse("00.0.0.0".as_bytes()),
Err(Error::LeadingZero)
);
assert_eq!(
super::Ip::parse("1.01.2.3".as_bytes()),
Err(Error::LeadingZero)
);
assert_eq!(
super::Ip::parse("1:1:1:1".as_bytes()),
Err(Error::IllegalCharacter)
);
assert_eq!(
super::Ip::parse("1.1.2_.3".as_bytes()),
Err(Error::IllegalCharacter)
);
}
#[test]
fn public_ip() {
// Technically unicast but yeah
assert_eq!(
super::Ip::parse("1.1.1.1".as_bytes()).unwrap().is_public(),
true
);
assert_eq!(
super::Ip::parse("10.10.100.254".as_bytes())
.unwrap()
.is_public(),
false
);
assert_eq!(
super::Ip::parse("10.10.100.254".as_bytes())
.unwrap()
.is_public(),
false
);
assert_eq!(
super::Ip::parse("172.10.100.254".as_bytes())
.unwrap()
.is_public(),
true
);
assert_eq!(
super::Ip::parse("172.20.100.254".as_bytes())
.unwrap()
.is_public(),
false
);
}
#[test]
fn create_new_cidr() {
super::CIDR::new(super::Ip::new([1, 1, 1, 1]), 15);
}
#[test]
#[should_panic]
fn reject_large_mask() {
super::CIDR::new(super::Ip::new([1, 1, 1, 1]), 33);
}
#[test]
fn accept_valid_cidr() {
assert_eq!(
super::CIDR::parse("1.1.1.1/32".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([1, 1, 1, 1]), 32))
);
assert_eq!(
super::CIDR::parse("1.1.1.1/1".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([1, 1, 1, 1]), 1))
);
assert_eq!(
super::CIDR::parse("255.255.255.255/32".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([255, 255, 255, 255]), 32))
);
assert_eq!(
super::CIDR::parse("255.255.255.129/25".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([255, 255, 255, 129]), 25))
);
assert_eq!(
super::CIDR::parse("128.0.0.0/1".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([128, 0, 0, 0,]), 1))
);
assert_eq!(
super::CIDR::parse("32.40.50.24/29".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([32, 40, 50, 24]), 29))
);
assert_eq!(
super::CIDR::parse("10.0.0.1/8".as_bytes()),
Ok(super::CIDR::new(super::Ip::new([10, 0, 0, 1]), 8))
);
}
#[test]
fn reject_invalid_cidr() {
assert_eq!(
super::CIDR::parse("1.1.1.1/33".as_bytes()),
Err(Error::MaskOverflow)
);
assert_eq!(
super::CIDR::parse("255.255.255.255/00".as_bytes()),
Err(Error::LeadingZero)
);
assert_eq!(
super::CIDR::parse("1.1.1.1//1".as_bytes()),
Err(Error::IllegalCharacter)
);
assert_eq!(
super::CIDR::parse("50.40.50.23/160".as_bytes()),
Err(Error::InputTooLong)
);
assert_eq!(
super::CIDR::parse("1.1.1.1/".as_bytes()),
Err(Error::InputTooShort)
);
assert_eq!(
super::CIDR::parse("1.111.1.1/".as_bytes()),
Err(Error::InputTooShort)
);
assert_eq!(
super::CIDR::parse("1.1.1.1/000".as_bytes()),
Err(Error::InputTooLong)
);
assert_eq!(
super::CIDR::parse("1.1.1.1/99".as_bytes()),
Err(Error::MaskOverflow)
);
assert_eq!(
super::CIDR::parse("1.1.1.1".as_bytes()),
Err(Error::MissingMask)
);
assert_eq!(
super::CIDR::parse("100.1.1.1".as_bytes()),
Err(Error::MissingMask)
);
assert_eq!(
super::CIDR::parse("1.1.1.1032".as_bytes()),
Err(Error::MissingMask)
);
assert_eq!(
super::CIDR::parse("1.1.1.1032/".as_bytes()),
Err(Error::OctetOverflow)
);
assert_eq!(
super::CIDR::parse("1.1.1.1/.".as_bytes()),
Err(Error::IllegalCharacter)
);
}
#[test]
fn ip_in_cidr() {
assert_eq!(
super::CIDR::parse("34.0.0.1/24".as_bytes())
.unwrap()
.contains(super::Ip::parse("34.0.0.254".as_bytes()).unwrap()),
true,
);
assert_eq!(
super::CIDR::parse("34.0.1.1/24".as_bytes())
.unwrap()
.contains(super::Ip::parse("34.0.0.254".as_bytes()).unwrap()),
false
);
}
#[test]
fn public_ip_cidr() {
// Technically unicast but yeah
assert_eq!(
super::CIDR::parse("1.1.1.1/32".as_bytes())
.unwrap()
.is_public(),
true,
);
assert_eq!(
super::CIDR::parse("10.10.100.254/24".as_bytes())
.unwrap()
.is_public(),
false,
);
assert_eq!(
super::CIDR::parse("10.10.100.254/24".as_bytes())
.unwrap()
.is_public(),
false,
);
assert_eq!(
super::CIDR::parse("172.10.100.254/24".as_bytes())
.unwrap()
.is_public(),
true,
);
assert_eq!(
super::CIDR::parse("172.20.100.254/24".as_bytes())
.unwrap()
.is_public(),
false,
);
}
}