aboutsummaryrefslogtreecommitdiffstats
path: root/src/router/device.rs
blob: ec6311147a1ca2c06b792964a2a628275096d09e (plain) (blame)
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
use arraydeque::{ArrayDeque, Saturating, Wrapping};
use lifeguard::{Pool, Recycled};
use treebitmap::IpLookupTable;

use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};

use spin::RwLock;

use super::super::types::KeyPair;
use super::anti_replay::AntiReplay;

use std::u64;

const REJECT_AFTER_MESSAGES: u64 = u64::MAX - (1 << 4);
const MAX_STAGED_PACKETS: usize = 128;

pub struct Device<'a> {
    recv: RwLock<HashMap<u32, Arc<Peer<'a>>>>, // map receiver id -> peer
    ipv4: IpLookupTable<Ipv4Addr, Arc<Peer<'a>>>, // ipv4 trie
    ipv6: IpLookupTable<Ipv6Addr, Arc<Peer<'a>>>, // ipv6 trie
    pool: Pool<Vec<u8>>,                       // message buffer pool
}

struct KeyState(KeyPair, AntiReplay);

struct EncryptionState {
    key: [u8; 32],    // encryption key
    id: u64,          // sender id
    nonce: AtomicU64, // next available nonce
    death: Instant,   // can must the key no longer be used:
                      // (birth + reject-after-time - keepalive-timeout - rekey-timeout)
}

struct KeyWheel {
    next: AtomicPtr<Arc<Option<KeyState>>>, // next key state (unconfirmed)
    current: AtomicPtr<Arc<Option<KeyState>>>, // current key state (used for encryption)
    previous: AtomicPtr<Arc<Option<KeyState>>>, // old key state (used for decryption)
}

pub struct Peer<'a> {
    inorder: Mutex<ArrayDeque<[Option<Recycled<'a, Vec<u8>>>; MAX_STAGED_PACKETS], Saturating>>, // inorder queue
    staged_packets: Mutex<ArrayDeque<[Vec<u8>; MAX_STAGED_PACKETS], Wrapping>>, // packets awaiting handshake
    rx_bytes: AtomicU64,                                                        // received bytes
    tx_bytes: AtomicU64,                                                        // transmitted bytes
    keys: KeyWheel,                                                             // key-wheel
    ekey: AtomicPtr<Arc<EncryptionState>>,                                      // encryption state
    endpoint: AtomicPtr<Arc<Option<SocketAddr>>>,
}

impl<'a> Peer<'a> {
    pub fn set_endpoint(&self, endpoint: SocketAddr) {
        self.endpoint
            .store(&mut Arc::new(Some(endpoint)), Ordering::Relaxed)
    }

    pub fn add_keypair(&self, keypair: KeyPair) {
        let confirmed = keypair.confirmed;
        let mut st_new = Arc::new(Some(KeyState(keypair, AntiReplay::new())));
        let st_previous = self.keys.previous.load(Ordering::Relaxed);
        if confirmed {
            // previous <- current
            self.keys.previous.compare_and_swap(
                st_previous,
                self.keys.current.load(Ordering::Relaxed),
                Ordering::Relaxed,
            );

            // current  <- new
            self.keys.next.store(&mut st_new, Ordering::Relaxed)
        } else {
            // previous <- next
            self.keys.previous.compare_and_swap(
                st_previous,
                self.keys.next.load(Ordering::Relaxed),
                Ordering::Relaxed,
            );

            // next <- new
            self.keys.next.store(&mut st_new, Ordering::Relaxed)
        }
    }

    pub fn rx_bytes(&self) -> u64 {
        self.rx_bytes.load(Ordering::Relaxed)
    }

    pub fn tx_bytes(&self) -> u64 {
        self.tx_bytes.load(Ordering::Relaxed)
    }
}

impl<'a> Device<'a> {
    pub fn new() -> Device<'a> {
        Device {
            recv: RwLock::new(HashMap::new()),
            ipv4: IpLookupTable::new(),
            ipv6: IpLookupTable::new(),
            pool: Pool::with_size_and_max(0, MAX_STAGED_PACKETS * 2),
        }
    }

    pub fn subnets(&self, peer: Arc<Peer<'a>>) -> Vec<(IpAddr, u32)> {
        let mut subnets = Vec::new();

        // extract ipv4 entries
        for subnet in self.ipv4.iter() {
            let (ip, masklen, p) = subnet;
            if Arc::ptr_eq(&peer, p) {
                subnets.push((IpAddr::V4(ip), masklen))
            }
        }

        // extract ipv6 entries
        for subnet in self.ipv6.iter() {
            let (ip, masklen, p) = subnet;
            if Arc::ptr_eq(&peer, p) {
                subnets.push((IpAddr::V6(ip), masklen))
            }
        }

        subnets
    }

    /// Adds a new peer to the device
    ///
    /// # Returns
    ///
    /// A atomic ref. counted peer (with liftime matching the device)
    pub fn add(&mut self) -> Arc<Peer<'a>> {
        Arc::new(Peer {
            inorder: Mutex::new(ArrayDeque::new()),
            staged_packets: Mutex::new(ArrayDeque::new()),
            rx_bytes: AtomicU64::new(0),
            tx_bytes: AtomicU64::new(0),
            keys: KeyWheel {
                next: AtomicPtr::new(&mut Arc::new(None)),
                current: AtomicPtr::new(&mut Arc::new(None)),
                previous: AtomicPtr::new(&mut Arc::new(None)),
            },
            // long expired encryption key
            ekey: AtomicPtr::new(&mut Arc::new(EncryptionState {
                key: [0u8; 32],
                id: 0,
                nonce: AtomicU64::new(REJECT_AFTER_MESSAGES),
                death: Instant::now() - Duration::from_secs(31536000),
            })),
            endpoint: AtomicPtr::new(&mut Arc::new(None)),
        })
    }

    pub fn get_buffer(&self) -> Recycled<Vec<u8>> {
        self.pool.new()
    }

    /// Cryptkey routes and sends a plaintext message (IP packet)
    ///
    /// # Arguments
    ///
    /// - pt_msg: IP packet to cryptkey route
    ///
    /// # Returns
    ///
    /// A peer reference for the peer if no key-pair is currently valid for the destination.
    /// This indicates that a handshake should be initated (see the handshake module).
    /// If this occurs the packet is copied to an internal buffer
    /// and retransmission can be attempted using send_run_queue
    pub fn send(&self, pt_msg: &mut [u8]) -> Arc<Peer> {
        unimplemented!();
    }

    /// Sends a message directly to the peer.
    /// The router device takes care of discovering/managing the endpoint.
    /// This is used for handshake initiation/response messages
    ///
    /// # Arguments
    ///
    /// - peer: Reference to the destination peer
    /// - msg: Message to transmit
    pub fn send_raw(&self, peer: Arc<Peer>, msg: &mut [u8]) {
        unimplemented!();
    }

    /// Flush the queue of buffered messages awaiting transmission
    ///
    /// # Arguments
    ///
    /// - peer: Reference for the peer to flush
    pub fn flush_queue(&self, peer: Arc<Peer>) {
        unimplemented!();
    }

    /// Attempt to route, encrypt and send all elements buffered in the queue
    ///
    /// # Arguments
    ///
    /// # Returns
    ///
    /// A boolean indicating whether packages where sent.
    /// Note: This is used for implicit confirmation of handshakes.
    pub fn send_run_queue(&self, peer: Arc<Peer>) -> bool {
        unimplemented!();
    }

    /// Receive an encrypted transport message
    ///
    /// # Arguments
    ///
    /// - ct_msg: Encrypted transport message
    pub fn recv(&self, ct_msg: &mut [u8]) {
        unimplemented!();
    }

    /// Returns the current endpoint known for the peer
    ///
    /// # Arguments
    ///
    /// - peer: The peer to retrieve the endpoint for
    pub fn get_endpoint(&self, peer: Arc<Peer>) -> SocketAddr {
        unimplemented!();
    }

    pub fn set_endpoint(&self, peer: Arc<Peer>, endpoint: SocketAddr) {
        unimplemented!();
    }

    pub fn new_keypair(&self, peer: Arc<Peer>, keypair: KeyPair) {
        unimplemented!();
    }
}