118 lines
2.6 KiB
Rust
118 lines
2.6 KiB
Rust
//! Core VPN Share engine primitives.
|
|
|
|
pub mod dns;
|
|
pub mod lease;
|
|
pub mod mtu;
|
|
pub mod nat;
|
|
pub mod packet;
|
|
|
|
use std::time::Instant;
|
|
|
|
pub use dns::{DnsPolicy, DnsRequest};
|
|
pub use lease::{Lease, LeaseAllocator, PeerId};
|
|
pub use mtu::MtuPolicy;
|
|
pub use nat::{FlowKey, FlowTable, TransportProtocol};
|
|
pub use packet::{IpPacket, PacketError};
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum GatewayState {
|
|
Stopped,
|
|
Starting,
|
|
Running,
|
|
Failed,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct GatewayConfig {
|
|
pub max_peers: usize,
|
|
pub default_mtu: u16,
|
|
pub ipv6_enabled: bool,
|
|
}
|
|
|
|
impl Default for GatewayConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
max_peers: 4,
|
|
default_mtu: 1280,
|
|
ipv6_enabled: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct VpnStatus {
|
|
pub active: bool,
|
|
pub interface_name: Option<String>,
|
|
pub supports_ipv4: bool,
|
|
pub supports_ipv6: bool,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct GatewayEngine {
|
|
state: GatewayState,
|
|
config: GatewayConfig,
|
|
leases: LeaseAllocator,
|
|
flows: FlowTable,
|
|
started_at: Option<Instant>,
|
|
}
|
|
|
|
impl GatewayEngine {
|
|
pub fn new(config: GatewayConfig) -> Self {
|
|
Self {
|
|
state: GatewayState::Stopped,
|
|
leases: LeaseAllocator::new(config.default_mtu),
|
|
flows: FlowTable::default(),
|
|
config,
|
|
started_at: None,
|
|
}
|
|
}
|
|
|
|
pub fn start(&mut self, now: Instant) {
|
|
self.state = GatewayState::Running;
|
|
self.started_at = Some(now);
|
|
}
|
|
|
|
pub fn stop(&mut self) {
|
|
self.state = GatewayState::Stopped;
|
|
self.started_at = None;
|
|
self.flows.clear();
|
|
self.leases.clear();
|
|
}
|
|
|
|
pub fn state(&self) -> GatewayState {
|
|
self.state
|
|
}
|
|
|
|
pub fn config(&self) -> &GatewayConfig {
|
|
&self.config
|
|
}
|
|
|
|
pub fn leases(&mut self) -> &mut LeaseAllocator {
|
|
&mut self.leases
|
|
}
|
|
|
|
pub fn flows(&mut self) -> &mut FlowTable {
|
|
&mut self.flows
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn gateway_start_stop_clears_runtime_state() {
|
|
let mut engine = GatewayEngine::new(GatewayConfig::default());
|
|
engine.start(Instant::now());
|
|
assert_eq!(engine.state(), GatewayState::Running);
|
|
|
|
let peer = PeerId::from_u128(1);
|
|
engine.leases().allocate(peer).unwrap();
|
|
assert_eq!(engine.leases().active_count(), 1);
|
|
|
|
engine.stop();
|
|
assert_eq!(engine.state(), GatewayState::Stopped);
|
|
assert_eq!(engine.leases().active_count(), 0);
|
|
}
|
|
}
|