vpncloud/src/ip.rs

163 lines
5.8 KiB
Rust
Raw Normal View History

// VpnCloud - Peer-to-Peer VPN
2017-07-22 14:49:53 +00:00
// Copyright (C) 2015-2017 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
2015-11-22 23:49:58 +00:00
use std::net::SocketAddr;
2015-11-21 15:50:50 +00:00
use std::collections::{hash_map, HashMap};
2016-03-29 08:45:54 +00:00
use std::hash::BuildHasherDefault;
use fnv::FnvHasher;
2015-11-22 18:47:28 +00:00
2015-11-23 00:04:30 +00:00
use super::types::{Protocol, Error, Table, Address};
2015-11-22 18:47:28 +00:00
2016-06-26 17:18:38 +00:00
/// An IP packet dissector
///
/// This dissector is able to extract the source and destination ip addresses of ipv4 packets and
/// ipv6 packets.
2015-11-22 19:02:02 +00:00
#[allow(dead_code)]
2015-11-23 00:40:47 +00:00
pub struct Packet;
2015-11-22 16:28:04 +00:00
2015-11-23 00:40:47 +00:00
impl Protocol for Packet {
2016-06-26 17:18:38 +00:00
/// Parses an ip packet and extracts the source and destination addresses
///
/// # Errors
/// This method will fail when the given data is not a valid ipv4 and ipv6 packet.
2015-11-22 23:49:58 +00:00
fn parse(data: &[u8]) -> Result<(Address, Address), Error> {
2015-11-22 18:00:56 +00:00
if data.len() < 1 {
2016-07-06 19:14:09 +00:00
return Err(Error::Parse("Empty header"));
2015-11-22 18:00:56 +00:00
}
let version = data[0] >> 4;
match version {
4 => {
if data.len() < 20 {
2016-07-06 19:14:09 +00:00
return Err(Error::Parse("Truncated IPv4 header"));
}
2015-11-26 09:45:25 +00:00
let src = try!(Address::read_from_fixed(&data[12..], 4));
let dst = try!(Address::read_from_fixed(&data[16..], 4));
Ok((src, dst))
2015-11-22 18:00:56 +00:00
},
6 => {
if data.len() < 40 {
2016-07-06 19:14:09 +00:00
return Err(Error::Parse("Truncated IPv6 header"));
}
2015-11-26 09:45:25 +00:00
let src = try!(Address::read_from_fixed(&data[8..], 16));
let dst = try!(Address::read_from_fixed(&data[24..], 16));
Ok((src, dst))
2015-11-22 18:00:56 +00:00
},
2016-07-06 19:14:09 +00:00
_ => Err(Error::Parse("Invalid version"))
2015-11-22 18:00:56 +00:00
}
2015-11-22 16:28:04 +00:00
}
}
2015-11-21 15:50:50 +00:00
struct RoutingEntry {
address: SocketAddr,
bytes: [u8; 16],
2015-11-21 15:50:50 +00:00
prefix_len: u8
}
2016-03-29 08:45:54 +00:00
type Hash = BuildHasherDefault<FnvHasher>;
2016-06-26 17:18:38 +00:00
/// A prefix-based routing table
///
/// This table contains a mapping of prefixes associated with peer addresses.
/// To speed up lookup, prefixes are grouped into full bytes and map to a list of prefixes with
/// more fine grained prefixes.
2016-06-27 13:43:30 +00:00
#[derive(Default)]
pub struct RoutingTable(HashMap<[u8; 16], Vec<RoutingEntry>, Hash>);
2015-11-21 15:50:50 +00:00
impl RoutingTable {
2016-06-26 17:18:38 +00:00
/// Creates a new empty routing table
2015-11-21 15:50:50 +00:00
pub fn new() -> Self {
2016-03-29 08:45:54 +00:00
RoutingTable(HashMap::default())
2015-11-21 15:50:50 +00:00
}
2015-11-22 23:49:58 +00:00
}
2015-11-21 15:50:50 +00:00
2015-11-22 23:49:58 +00:00
impl Table for RoutingTable {
2016-06-26 17:18:38 +00:00
/// Learns the given address, inserting it in the hash map
2015-11-22 23:49:58 +00:00
fn learn(&mut self, addr: Address, prefix_len: Option<u8>, address: SocketAddr) {
2016-06-26 17:18:38 +00:00
// If prefix length is not set, treat the whole addess as significant
2015-11-22 23:49:58 +00:00
let prefix_len = match prefix_len {
Some(val) => val,
2015-11-26 09:45:25 +00:00
None => addr.len * 8
2015-11-22 23:49:58 +00:00
};
2015-11-26 21:16:51 +00:00
info!("New routing entry: {}/{} => {}", addr, prefix_len, address);
2016-06-26 17:18:38 +00:00
// Round the prefix length down to the next multiple of 8 and extraxt a prefix of that
// length.
2015-11-26 21:16:51 +00:00
let group_len = prefix_len as usize / 8;
assert!(group_len <= 16);
let mut group_bytes = [0; 16];
group_bytes[..group_len].copy_from_slice(&addr.data[..group_len]);
2016-06-26 17:18:38 +00:00
// Create an entry
2015-11-26 09:45:25 +00:00
let routing_entry = RoutingEntry{address: address, bytes: addr.data, prefix_len: prefix_len};
2016-06-26 17:18:38 +00:00
// Add the entry to the routing table, creating a new list of the prefix group is empty.
2015-11-21 15:50:50 +00:00
match self.0.entry(group_bytes) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(routing_entry),
hash_map::Entry::Vacant(entry) => { entry.insert(vec![routing_entry]); () }
}
}
2016-06-26 17:18:38 +00:00
/// Retrieves a peer for an address if it is inside the routing table
#[allow(unknown_lints, needless_range_loop)]
2015-11-25 18:23:25 +00:00
fn lookup(&mut self, addr: &Address) -> Option<SocketAddr> {
2015-11-26 21:16:51 +00:00
let len = addr.len as usize;
let mut found = None;
let mut found_len: isize = -1;
2016-06-26 17:18:38 +00:00
// Iterate over the prefix length from longest prefix group to shortest (empty) prefix
// group
let mut group_bytes = addr.data;
for i in len..16 {
group_bytes[i] = 0;
}
for i in (0..len+1).rev() {
if i < len {
group_bytes[i] = 0;
}
if let Some(group) = self.0.get(&group_bytes) {
2016-06-26 17:18:38 +00:00
// If the group is not empty, check every entry
2015-11-21 15:50:50 +00:00
for entry in group {
2016-06-26 17:18:38 +00:00
// Calculate the match length of the address and the prefix
2015-11-21 15:50:50 +00:00
let mut match_len = 0;
2015-11-26 09:45:25 +00:00
for j in 0..addr.len as usize {
let b = addr.data[j] ^ entry.bytes[j];
2015-11-21 15:50:50 +00:00
if b == 0 {
match_len += 8;
} else {
match_len += b.leading_zeros();
break;
}
}
2016-06-26 17:18:38 +00:00
// If the full prefix matches and the match is longer than the longest prefix
// found so far, remember the peer
if match_len as u8 >= entry.prefix_len && entry.prefix_len as isize > found_len {
2015-11-26 21:16:51 +00:00
found = Some(entry.address);
found_len = entry.prefix_len as isize;
2015-11-21 15:50:50 +00:00
}
}
}
}
2016-06-26 17:18:38 +00:00
// Return the longest match found (if any).
2015-11-26 21:16:51 +00:00
found
2015-11-21 15:50:50 +00:00
}
2015-11-22 18:00:56 +00:00
2016-06-26 17:18:38 +00:00
/// This method does not do anything.
2015-11-22 18:00:56 +00:00
fn housekeep(&mut self) {
//nothing to do
2015-11-22 18:00:56 +00:00
}
2015-11-22 21:00:34 +00:00
2016-06-26 17:18:38 +00:00
/// Removes an address from the map and returns whether something has been removed
#[inline]
fn remove(&mut self, _addr: &Address) -> bool {
// Do nothing, removing single address from prefix-based routing tables does not make sense
false
}
2016-06-26 17:18:38 +00:00
/// Removed all addresses associated with a certain peer
fn remove_all(&mut self, addr: &SocketAddr) {
2017-05-04 05:11:23 +00:00
for entry in &mut self.0.values_mut() {
entry.retain(|entr| &entr.address != addr);
}
2015-11-22 21:00:34 +00:00
}
2015-11-22 18:00:56 +00:00
}