mirror of https://github.com/dswd/vpncloud.git
Traits and major rework
This commit is contained in:
parent
2fe004c074
commit
b6bde39c3b
|
@ -5,6 +5,7 @@ use std::net::UdpSocket;
|
|||
use std::io::Read;
|
||||
use std::fmt;
|
||||
use std::os::unix::io::AsRawFd;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use time::{Duration, SteadyTime, precise_time_ns};
|
||||
use epoll;
|
||||
|
@ -15,16 +16,6 @@ use super::ethernet::MacTable;
|
|||
use super::tuntap::{TunTapDevice, DeviceType};
|
||||
|
||||
|
||||
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Mac(pub [u8; 6]);
|
||||
|
||||
impl fmt::Debug for Mac {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
write!(formatter, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
|
||||
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5])
|
||||
}
|
||||
}
|
||||
|
||||
pub type NetworkId = u64;
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -32,7 +23,7 @@ pub enum Error {
|
|||
ParseError(&'static str),
|
||||
WrongNetwork(Option<NetworkId>),
|
||||
SocketError(&'static str),
|
||||
TapdevError(&'static str),
|
||||
TunTapDevError(&'static str),
|
||||
}
|
||||
|
||||
|
||||
|
@ -103,11 +94,29 @@ impl PeerList {
|
|||
}
|
||||
}
|
||||
|
||||
pub trait Table {
|
||||
type Address;
|
||||
fn learn(&mut self, Self::Address, SocketAddr);
|
||||
fn lookup(&self, Self::Address) -> Option<SocketAddr>;
|
||||
fn housekeep(&mut self);
|
||||
}
|
||||
|
||||
pub struct EthCloud {
|
||||
pub trait InterfaceMessage {
|
||||
type Address;
|
||||
fn src(&self) -> Self::Address;
|
||||
fn dst(&self) -> Self::Address;
|
||||
}
|
||||
|
||||
pub trait VirtualInterface {
|
||||
type Message: InterfaceMessage;
|
||||
fn read(&mut self) -> Result<Self::Message, Error>;
|
||||
fn write(&mut self, Self::Message) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
pub struct EthCloud<A, T: Table<Address=A>, M: InterfaceMessage<Address=A>, I: VirtualInterface<Message=M>> {
|
||||
peers: PeerList,
|
||||
reconnect_peers: Vec<SocketAddr>,
|
||||
mactable: MacTable,
|
||||
table: MacTable,
|
||||
socket: UdpSocket,
|
||||
tapdev: TunTapDevice,
|
||||
network_id: Option<NetworkId>,
|
||||
|
@ -115,9 +124,12 @@ pub struct EthCloud {
|
|||
update_freq: Duration,
|
||||
buffer_out: [u8; 64*1024],
|
||||
next_housekeep: SteadyTime,
|
||||
_dummy_t: PhantomData<T>,
|
||||
_dummy_m: PhantomData<M>,
|
||||
_dummy_i: PhantomData<I>,
|
||||
}
|
||||
|
||||
impl EthCloud {
|
||||
impl<A, T: Table<Address=A>, M: InterfaceMessage<Address=A>, I: VirtualInterface<Message=M>> EthCloud<A, T, M, I> {
|
||||
pub fn new(device: &str, listen: String, network_id: Option<NetworkId>, mac_timeout: Duration, peer_timeout: Duration) -> Self {
|
||||
let socket = match UdpSocket::bind(&listen as &str) {
|
||||
Ok(socket) => socket,
|
||||
|
@ -131,18 +143,21 @@ impl EthCloud {
|
|||
EthCloud{
|
||||
peers: PeerList::new(peer_timeout),
|
||||
reconnect_peers: Vec::new(),
|
||||
mactable: MacTable::new(mac_timeout),
|
||||
table: MacTable::new(mac_timeout),
|
||||
socket: socket,
|
||||
tapdev: tapdev,
|
||||
network_id: network_id,
|
||||
next_peerlist: SteadyTime::now(),
|
||||
update_freq: peer_timeout/2,
|
||||
buffer_out: [0; 64*1024],
|
||||
next_housekeep: SteadyTime::now()
|
||||
next_housekeep: SteadyTime::now(),
|
||||
_dummy_t: PhantomData,
|
||||
_dummy_m: PhantomData,
|
||||
_dummy_i: PhantomData
|
||||
}
|
||||
}
|
||||
|
||||
fn send_msg<A: ToSocketAddrs + fmt::Display>(&mut self, addr: A, msg: &Message) -> Result<(), Error> {
|
||||
fn send_msg<Addr: ToSocketAddrs+fmt::Display>(&mut self, addr: Addr, msg: &Message) -> Result<(), Error> {
|
||||
debug!("Sending {:?} to {}", msg, addr);
|
||||
let mut options = Options::default();
|
||||
options.network_id = self.network_id;
|
||||
|
@ -157,7 +172,7 @@ impl EthCloud {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn connect<A: ToSocketAddrs + fmt::Display>(&mut self, addr: A, reconnect: bool) -> Result<(), Error> {
|
||||
pub fn connect<Addr: ToSocketAddrs+fmt::Display>(&mut self, addr: Addr, reconnect: bool) -> Result<(), Error> {
|
||||
if let Ok(mut addrs) = addr.to_socket_addrs() {
|
||||
while let Some(addr) = addrs.next() {
|
||||
if self.peers.contains(&addr) {
|
||||
|
@ -176,7 +191,7 @@ impl EthCloud {
|
|||
fn housekeep(&mut self) -> Result<(), Error> {
|
||||
debug!("Running housekeeping...");
|
||||
self.peers.timeout();
|
||||
self.mactable.timeout();
|
||||
self.table.housekeep();
|
||||
if self.next_peerlist <= SteadyTime::now() {
|
||||
debug!("Send peer list to all peers");
|
||||
let mut peer_num = self.peers.len();
|
||||
|
@ -199,15 +214,15 @@ impl EthCloud {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_ethernet_frame(&mut self, frame: ethernet::Frame) -> Result<(), Error> {
|
||||
fn handle_interface_data(&mut self, frame: ethernet::Frame) -> Result<(), Error> {
|
||||
debug!("Read ethernet frame from tap {:?}", frame);
|
||||
match self.mactable.lookup(frame.dst, frame.vlan) {
|
||||
match self.table.lookup(frame.dst()) {
|
||||
Some(addr) => {
|
||||
debug!("Found destination for {:?} (vlan {}) => {}", frame.dst, frame.vlan, addr);
|
||||
debug!("Found destination for {:?} => {}", frame.dst(), addr);
|
||||
try!(self.send_msg(addr, &Message::Frame(frame)))
|
||||
},
|
||||
None => {
|
||||
debug!("No destination for {:?} (vlan {}) found, broadcasting", frame.dst, frame.vlan);
|
||||
debug!("No destination for {:?} found, broadcasting", frame.dst());
|
||||
let msg = Message::Frame(frame);
|
||||
for addr in &self.peers.as_vec() {
|
||||
try!(self.send_msg(addr, &msg));
|
||||
|
@ -233,11 +248,11 @@ impl EthCloud {
|
|||
Ok(()) => (),
|
||||
Err(e) => {
|
||||
error!("Failed to send via tap device {:?}", e);
|
||||
return Err(Error::TapdevError("Failed to write to tap device"));
|
||||
return Err(Error::TunTapDevError("Failed to write to tap device"));
|
||||
}
|
||||
}
|
||||
self.peers.add(&peer);
|
||||
self.mactable.learn(frame.src, frame.vlan, &peer);
|
||||
self.table.learn(frame.src, peer);
|
||||
},
|
||||
Message::Peers(peers) => {
|
||||
self.peers.add(&peer);
|
||||
|
@ -285,7 +300,7 @@ impl EthCloud {
|
|||
},
|
||||
&1 => match self.tapdev.read(&mut buffer) {
|
||||
Ok(size) => {
|
||||
match ethernet::decode(&mut buffer[..size]).and_then(|frame| self.handle_ethernet_frame(frame)) {
|
||||
match ethernet::decode(&mut buffer[..size]).and_then(|frame| self.handle_interface_data(frame)) {
|
||||
Ok(_) => (),
|
||||
Err(e) => error!("Error: {:?}", e)
|
||||
}
|
||||
|
|
|
@ -1,27 +1,69 @@
|
|||
use std::{mem, ptr, fmt};
|
||||
use std::net::SocketAddr;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::ethcloud::{Mac, Error};
|
||||
use super::ethcloud::{Error, Table, InterfaceMessage, VirtualInterface};
|
||||
use super::util::{as_bytes, as_obj};
|
||||
|
||||
use time::{Duration, SteadyTime};
|
||||
|
||||
|
||||
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Mac(pub [u8; 6]);
|
||||
|
||||
impl fmt::Debug for Mac {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
write!(formatter, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
|
||||
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5])
|
||||
}
|
||||
}
|
||||
|
||||
pub type VlanId = u16;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct EthAddr {
|
||||
pub mac: Mac,
|
||||
pub vlan: VlanId
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub struct Frame<'a> {
|
||||
pub vlan: VlanId,
|
||||
pub src: &'a Mac,
|
||||
pub dst: &'a Mac,
|
||||
pub src: EthAddr,
|
||||
pub dst: EthAddr,
|
||||
pub payload: &'a [u8]
|
||||
}
|
||||
|
||||
impl<'a> fmt::Debug for Frame<'a> {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
write!(formatter, "src: {:?}, dst: {:?}, vlan: {}, payload: {} bytes",
|
||||
self.src, self.dst, self.vlan, self.payload.len())
|
||||
self.src.mac, self.dst.mac, self.src.vlan, self.payload.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> InterfaceMessage for Frame<'a> {
|
||||
type Address = EthAddr;
|
||||
|
||||
fn src(&self) -> Self::Address {
|
||||
self.src
|
||||
}
|
||||
|
||||
fn dst(&self) -> Self::Address {
|
||||
self.dst
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TapDevice<'a>(PhantomData<&'a ()>);
|
||||
|
||||
impl<'a> VirtualInterface for TapDevice<'a> {
|
||||
type Message = Frame<'a>;
|
||||
|
||||
fn read(&mut self) -> Result<Self::Message, Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn write(&mut self, msg: Self::Message) -> Result<(), Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -30,9 +72,9 @@ pub fn decode(data: &[u8]) -> Result<Frame, Error> {
|
|||
return Err(Error::ParseError("Frame is too short"));
|
||||
}
|
||||
let mut pos = 0;
|
||||
let dst = unsafe { as_obj::<Mac>(&data[pos..]) };
|
||||
let dst = *unsafe { as_obj::<Mac>(&data[pos..]) };
|
||||
pos += mem::size_of::<Mac>();
|
||||
let src = unsafe { as_obj::<Mac>(&data[pos..]) };
|
||||
let src = *unsafe { as_obj::<Mac>(&data[pos..]) };
|
||||
pos += mem::size_of::<Mac>();
|
||||
let mut vlan = 0;
|
||||
let mut payload = &data[pos..];
|
||||
|
@ -45,23 +87,23 @@ pub fn decode(data: &[u8]) -> Result<Frame, Error> {
|
|||
pos += 2;
|
||||
payload = &data[pos..];
|
||||
}
|
||||
Ok(Frame{vlan: vlan, src: src, dst: dst, payload: payload})
|
||||
Ok(Frame{src: EthAddr{mac: src, vlan: vlan}, dst: EthAddr{mac: dst, vlan: vlan}, payload: payload})
|
||||
}
|
||||
|
||||
pub fn encode(frame: &Frame, buf: &mut [u8]) -> usize {
|
||||
assert!(buf.len() >= 16 + frame.payload.len());
|
||||
let mut pos = 0;
|
||||
unsafe {
|
||||
let dst_dat = as_bytes::<Mac>(frame.dst);
|
||||
let dst_dat = as_bytes::<Mac>(&frame.dst.mac);
|
||||
ptr::copy_nonoverlapping(dst_dat.as_ptr(), buf[pos..].as_mut_ptr(), dst_dat.len());
|
||||
pos += dst_dat.len();
|
||||
let src_dat = as_bytes::<Mac>(frame.src);
|
||||
let src_dat = as_bytes::<Mac>(&frame.src.mac);
|
||||
ptr::copy_nonoverlapping(src_dat.as_ptr(), buf[pos..].as_mut_ptr(), src_dat.len());
|
||||
pos += src_dat.len();
|
||||
if frame.vlan != 0 {
|
||||
if frame.src.vlan != 0 {
|
||||
buf[pos] = 0x81; buf[pos+1] = 0x00;
|
||||
pos += 2;
|
||||
let vlan_dat = mem::transmute::<u16, [u8; 2]>(frame.vlan.to_be());
|
||||
let vlan_dat = mem::transmute::<u16, [u8; 2]>(frame.src.vlan.to_be());
|
||||
ptr::copy_nonoverlapping(vlan_dat.as_ptr(), buf[pos..].as_mut_ptr(), vlan_dat.len());
|
||||
pos += vlan_dat.len();
|
||||
}
|
||||
|
@ -72,19 +114,13 @@ pub fn encode(frame: &Frame, buf: &mut [u8]) -> usize {
|
|||
}
|
||||
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct MacTableKey {
|
||||
mac: Mac,
|
||||
vlan: VlanId
|
||||
}
|
||||
|
||||
struct MacTableValue {
|
||||
address: SocketAddr,
|
||||
timeout: SteadyTime
|
||||
}
|
||||
|
||||
pub struct MacTable {
|
||||
table: HashMap<MacTableKey, MacTableValue>,
|
||||
table: HashMap<EthAddr, MacTableValue>,
|
||||
timeout: Duration
|
||||
}
|
||||
|
||||
|
@ -92,10 +128,14 @@ impl MacTable {
|
|||
pub fn new(timeout: Duration) -> MacTable {
|
||||
MacTable{table: HashMap::new(), timeout: timeout}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn timeout(&mut self) {
|
||||
impl Table for MacTable {
|
||||
type Address = EthAddr;
|
||||
|
||||
fn housekeep(&mut self) {
|
||||
let now = SteadyTime::now();
|
||||
let mut del: Vec<MacTableKey> = Vec::new();
|
||||
let mut del: Vec<Self::Address> = Vec::new();
|
||||
for (&key, val) in &self.table {
|
||||
if val.timeout < now {
|
||||
del.push(key);
|
||||
|
@ -107,18 +147,14 @@ impl MacTable {
|
|||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn learn(&mut self, mac: &Mac, vlan: VlanId, addr: &SocketAddr) {
|
||||
let key = MacTableKey{mac: *mac, vlan: vlan};
|
||||
let value = MacTableValue{address: *addr, timeout: SteadyTime::now()+self.timeout};
|
||||
fn learn(&mut self, key: Self::Address, addr: SocketAddr) {
|
||||
let value = MacTableValue{address: addr, timeout: SteadyTime::now()+self.timeout};
|
||||
if self.table.insert(key, value).is_none() {
|
||||
info!("Learned mac: {:?} (vlan {}) => {}", mac, vlan, addr);
|
||||
info!("Learned mac: {:?} (vlan {}) => {}", key.mac, key.vlan, addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn lookup(&self, mac: &Mac, vlan: VlanId) -> Option<SocketAddr> {
|
||||
let key = MacTableKey{mac: *mac, vlan: vlan};
|
||||
fn lookup(&self, key: Self::Address) -> Option<SocketAddr> {
|
||||
match self.table.get(&key) {
|
||||
Some(value) => Some(value.address),
|
||||
None => None
|
||||
|
@ -133,7 +169,7 @@ fn without_vlan() {
|
|||
let dst = Mac([6,5,4,3,2,1]);
|
||||
let payload = [1,2,3,4,5,6,7,8];
|
||||
let mut buf = [0u8; 1024];
|
||||
let frame = Frame{src: &src, dst: &dst, vlan: 0, payload: &payload};
|
||||
let frame = Frame{src: EthAddr{mac: src, vlan: 0}, dst: EthAddr{mac: dst, vlan: 0}, payload: &payload};
|
||||
let size = encode(&frame, &mut buf);
|
||||
assert_eq!(size, 20);
|
||||
assert_eq!(&buf[..size], &[6,5,4,3,2,1,1,2,3,4,5,6,1,2,3,4,5,6,7,8]);
|
||||
|
@ -147,7 +183,7 @@ fn with_vlan() {
|
|||
let dst = Mac([6,5,4,3,2,1]);
|
||||
let payload = [1,2,3,4,5,6,7,8];
|
||||
let mut buf = [0u8; 1024];
|
||||
let frame = Frame{src: &src, dst: &dst, vlan: 1234, payload: &payload};
|
||||
let frame = Frame{src: EthAddr{mac: src, vlan: 0}, dst: EthAddr{mac: dst, vlan: 0}, payload: &payload};
|
||||
let size = encode(&frame, &mut buf);
|
||||
assert_eq!(size, 24);
|
||||
assert_eq!(&buf[..size], &[6,5,4,3,2,1,1,2,3,4,5,6,0x81,0,4,210,1,2,3,4,5,6,7,8]);
|
||||
|
|
|
@ -81,7 +81,7 @@ fn main() {
|
|||
Box::new(SimpleLogger)
|
||||
}).unwrap();
|
||||
debug!("Args: {:?}", args);
|
||||
let mut tapcloud = EthCloud::new(
|
||||
let mut tapcloud = EthCloud::<ethernet::EthAddr, ethernet::MacTable, ethernet::Frame, ethernet::TapDevice>::new(
|
||||
&args.flag_device,
|
||||
args.flag_listen,
|
||||
args.flag_network_id.map(|name| {
|
||||
|
|
|
@ -25,7 +25,11 @@ impl TunTapDevice {
|
|||
ifname_string.push_str(ifname);
|
||||
ifname_string.push('\0');
|
||||
let mut ifname_c = ifname_string.into_bytes();
|
||||
match unsafe { setup_tap_device(fd.as_raw_fd(), ifname_c.as_mut_ptr()) } {
|
||||
let res = match iftype {
|
||||
DeviceType::TapDevice => unsafe { setup_tap_device(fd.as_raw_fd(), ifname_c.as_mut_ptr()) },
|
||||
DeviceType::TunDevice => unsafe { setup_tun_device(fd.as_raw_fd(), ifname_c.as_mut_ptr()) }
|
||||
};
|
||||
match res {
|
||||
0 => Ok(TunTapDevice{fd: fd, ifname: String::from_utf8(ifname_c).unwrap(), iftype: iftype}),
|
||||
_ => Err(IoError::last_os_error())
|
||||
}
|
||||
|
|
|
@ -181,12 +181,13 @@ pub fn encode(options: &Options, msg: &Message, buf: &mut [u8]) -> usize {
|
|||
|
||||
#[test]
|
||||
fn encode_message_packet() {
|
||||
use super::ethcloud::Mac;
|
||||
use super::ethernet::Mac;
|
||||
let options = Options::default();
|
||||
let src = Mac([1,2,3,4,5,6]);
|
||||
let dst = Mac([7,8,9,10,11,12]);
|
||||
let payload = [1,2,3,4,5];
|
||||
let msg = Message::Frame(ethernet::Frame{src: &src, dst: &dst, vlan: 0, payload: &payload});
|
||||
let frame = ethernet::Frame{src: ethernet::EthAddr{mac: src, vlan: 0}, dst: ethernet::EthAddr{mac: dst, vlan: 0}, payload: &payload};
|
||||
let msg = Message::Frame(frame);
|
||||
let mut buf = [0; 1024];
|
||||
let size = encode(&options, &msg, &mut buf[..]);
|
||||
assert_eq!(size, 25);
|
||||
|
|
Loading…
Reference in New Issue