gotatun 0.4.1

an implementation of the WireGuard® protocol designed for portability and speed
Documentation
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// This file incorporates work covered by the following copyright and
// permission notice:
//
//   Copyright (c) Mullvad VPN AB. All rights reserved.
//
// SPDX-License-Identifier: MPL-2.0

use futures::{FutureExt, future::pending};
use maybenot::MachineId;
use std::{
    collections::VecDeque,
    sync::{
        Arc,
        atomic::{self, AtomicU32},
    },
};
use tokio::{
    sync::{
        Notify, RwLock,
        mpsc::{self, error::TrySendError},
    },
    time::Instant,
};
use zerocopy::{Immutable, IntoBytes, KnownLayout, TryFromBytes, Unaligned, big_endian};

use crate::packet::{Packet, WgData};

pub(crate) enum ErrorAction {
    Close,
    Ignore(IgnoreReason),
}

pub(crate) enum IgnoreReason {
    NoEndpoint,
    NoSession,
}

impl std::fmt::Display for IgnoreReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IgnoreReason::NoEndpoint => write!(f, "No endpoint"),
            IgnoreReason::NoSession => write!(f, "No session"),
        }
    }
}

pub(crate) type Result<T> = std::result::Result<T, ErrorAction>;

#[derive(TryFromBytes, KnownLayout, Unaligned, Immutable, PartialEq, Eq)]
#[repr(C)]
pub(crate) struct DecoyPacket {
    pub(crate) header: DecoyHeader,
    pub(crate) payload: [u8],
}

#[derive(
    TryFromBytes, IntoBytes, KnownLayout, Unaligned, Immutable, PartialEq, Eq, Clone, Copy,
)]
#[repr(C, packed)]
pub(crate) struct DecoyHeader {
    pub marker: DecoyMarker,
    _reserved: u8,
    pub length: big_endian::U16,
}

#[derive(
    TryFromBytes, IntoBytes, KnownLayout, Unaligned, Immutable, PartialEq, Eq, Clone, Copy,
)]
#[repr(u8)]
pub(crate) enum DecoyMarker {
    Decoy = 0xff,
}

impl DecoyHeader {
    pub(crate) const fn new(length: big_endian::U16) -> Self {
        Self {
            marker: DecoyMarker::Decoy,
            _reserved: 0,
            length,
        }
    }
}

/// Counter for the number of normal packets that have been received on the tunnel interface
/// but not yet sent to the network, and the number of those packets that have replaced
/// decoy packets.
#[derive(Default)]
pub(crate) struct PacketCount {
    outbound_normal: AtomicU32,
}

impl PacketCount {
    pub fn dec(&self, amount: u32) {
        self.outbound_normal
            .fetch_sub(amount, atomic::Ordering::SeqCst);
    }

    pub fn inc(&self, amount: u32) {
        self.outbound_normal
            .fetch_add(amount, atomic::Ordering::SeqCst);
    }

    pub fn outbound(&self) -> u32 {
        self.outbound_normal.load(atomic::Ordering::SeqCst)
    }
}

#[derive(Clone, Copy)]
pub(crate) enum DelayState {
    Inactive,
    Active { bypass: bool, expires_at: Instant },
}

impl DelayState {
    /// Returns `true` if the delay is [`Active`].
    ///
    /// [`Active`]: DelayState::Active
    #[must_use]
    pub(crate) fn is_active(&self) -> bool {
        matches!(self, Self::Active { .. })
    }
}

#[derive(Clone)]
pub struct DelayWatcher {
    pub(super) delay_queue_tx: mpsc::Sender<Packet<WgData>>,
    pub(super) delay_state: Arc<RwLock<DelayState>>,
    delay_abort: Arc<Notify>,
    min_delay_capacity: usize,
}

impl DelayWatcher {
    pub fn new(delay_queue_tx: mpsc::Sender<Packet<WgData>>, min_delay_capacity: usize) -> Self {
        let delay_state = Arc::new(RwLock::new(DelayState::Inactive));
        let delay_abort = Arc::new(Notify::const_new());
        Self {
            delay_queue_tx,
            delay_state,
            delay_abort,
            min_delay_capacity,
        }
    }

    /// Wait until the delay timer expires, or until `delay_abort` is notified.
    ///
    /// When this future resolves, delayed packets should be flushed.
    pub async fn wait_delay_ended(&self) {
        if let DelayState::Active { expires_at, .. } = &*self.delay_state.read().await {
            futures::select! {
                () = tokio::time::sleep_until(*expires_at).fuse() => {},
                () = self.delay_abort.notified().fuse() => {
                    log::trace!("Delay aborted with remaining capacity {}", self.delay_queue_tx.capacity());
                },
            }
        } else {
            pending().await
        }
    }

    /// Add the packet to the delay queue if the delay state is active, otherwise return it to be
    /// sent immediately.
    ///
    /// Returns `None` if the packet was added to the delay queue.
    ///
    /// Returns `Some(packet)` if the packet should be sent immediately.
    /// This happens if the delay state is inactive, or if the delay queue is full/closed.
    pub fn maybe_delay_packet(&self, packet: Packet<WgData>) -> Option<Packet<WgData>> {
        if let Ok(delay) = self.delay_state.try_read()
            && delay.is_active()
        {
            // Notify the delay handler to abort the delay state when the capacity is low
            if self.delay_queue_tx.capacity() < self.min_delay_capacity {
                self.delay_abort.notify_one();
            }

            if let Err(TrySendError::Closed(packet) | TrySendError::Full(packet)) =
                self.delay_queue_tx.try_send(packet)
            {
                log::trace!("Packet sent as it couldn't be delayed");
                // If the queue is closed or full, we can't delay anymore, so we
                // send the packet anyway.
                // TODO: this would be an out of order packet, not ideal.
                // Should we drop the packet instead?
                Some(packet)
            } else {
                None
            }
        } else {
            Some(packet)
        }
    }
}

/// Queue of timers for each machine.
///
/// Use [`MachineTimers::wait_next_timer`] to wait for the next time expiration.
// INVARIANT: VecDeque is sorted by Instant, which represents the time of expiration.
// INVARIANT: Only one internal and one action timer per machine can exist at a time.
pub(crate) struct MachineTimers(VecDeque<(Instant, MachineId, MachineTimer)>);

#[derive(Clone, Copy, Debug)]
pub(crate) enum Action {
    Decoy {
        replace: bool,
        bypass: bool,
    },
    Delay {
        replace: bool,
        bypass: bool,
        duration: std::time::Duration,
    },
}

/// Type of timer for a machine, see [`MachineTimers`].
#[derive(Clone, Copy, Debug)]
pub(crate) enum MachineTimer {
    /// The internal timer does not trigger any action directly, but is used to
    /// trigger [`maybenot::TriggerEvent::TimerEnd`], giving the machine a way
    /// to know when the time has passed.
    Internal,
    /// The action timer triggers a [`Action`], which can be either sending
    /// decoy packets or delay outgoing packets.
    Action(Action),
}

impl MachineTimers {
    pub(crate) fn new(cap: usize) -> Self {
        Self(VecDeque::with_capacity(cap))
    }

    pub(crate) fn remove_action(&mut self, machine: &MachineId) {
        self.0
            .retain(|&(_, m, t)| !(m == *machine && matches!(t, MachineTimer::Action(_))));
    }

    pub(crate) fn remove_internal(&mut self, machine: &MachineId) {
        self.0
            .retain(|&(_, m, t)| !(m == *machine && matches!(t, MachineTimer::Internal)));
    }

    pub(crate) fn remove_all(&mut self, machine: &MachineId) {
        self.0.retain(|&(_, m, _)| m != *machine);
    }

    /// Schedule decoy timer according to [`maybenot::TriggerAction::SendPadding`].
    pub(crate) fn schedule_decoy(
        &mut self,
        machine: MachineId,
        timeout: std::time::Duration,
        replace: bool,
        bypass: bool,
    ) {
        self.remove_action(&machine);
        let expiration_time = Instant::now() + timeout;
        let insert_at = self
            .0
            .binary_search_by_key(&expiration_time, |&(time, _, _)| time)
            .unwrap_or_else(|e| e);
        self.0.insert(
            insert_at,
            (
                expiration_time,
                machine,
                MachineTimer::Action(Action::Decoy { replace, bypass }),
            ),
        );
        debug_assert!(self.0.iter().is_sorted_by_key(|(time, _, _)| *time));
    }

    /// Schedule delay timer according to [`maybenot::TriggerAction::BlockOutgoing`].
    pub(crate) fn schedule_delay(
        &mut self,
        machine: MachineId,
        timeout: std::time::Duration,
        duration: std::time::Duration,
        replace: bool,
        bypass: bool,
    ) {
        self.remove_action(&machine);
        let expiration_time = Instant::now() + timeout;
        let insert_at = self
            .0
            .binary_search_by_key(&expiration_time, |&(time, _, _)| time)
            .unwrap_or_else(|e| e);
        self.0.insert(
            insert_at,
            (
                expiration_time,
                machine,
                MachineTimer::Action(Action::Delay {
                    replace,
                    bypass,
                    duration,
                }),
            ),
        );
        debug_assert!(self.0.iter().is_sorted_by_key(|(time, _, _)| *time));
    }

    /// Schedule internal timer according to [`maybenot::TriggerAction::UpdateTimer`].
    pub(crate) fn schedule_internal_timer(
        &mut self,
        machine: MachineId,
        duration: std::time::Duration,
        replace: bool,
    ) -> bool {
        let expiry = Instant::now() + duration;
        let idx = self
            .0
            .iter()
            .position(|&(_, m, t)| m == machine && matches!(t, MachineTimer::Internal));
        let should_update = match idx {
            Some(i) => {
                let (cur_expiry, _, _) = self.0[i];
                if replace || expiry > cur_expiry {
                    self.0.remove(i);
                    true
                } else {
                    false
                }
            }
            None => true,
        };
        if should_update {
            let insert_at = self
                .0
                .binary_search_by_key(&expiry, |&(time, _, _)| time)
                .unwrap_or_else(|e| e);
            self.0
                .insert(insert_at, (expiry, machine, MachineTimer::Internal));
            debug_assert!(self.0.iter().is_sorted_by_key(|(time, _, _)| *time));
        }
        should_update
    }

    /// Wait until the next timer expires and returns it.
    ///
    /// ## Cancel safety
    /// This function is cancellation safe, i.e. the timer will not
    /// be removed if the function is cancelled.
    pub(crate) async fn wait_next_timer(&mut self) -> (MachineId, MachineTimer) {
        if let Some((time, _, _)) = self.0.front() {
            tokio::time::sleep_until(*time).await;
            self.0
                .pop_front()
                .map(|(_, m, t)| (m, t))
                .expect("Front exists because we peeked it")
        } else {
            futures::future::pending().await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::device::daita::types;

    #[test]
    fn test_machine_timers_schedule_and_remove() {
        let mut timers = types::MachineTimers::new(4);
        let machine = MachineId::from_raw(1);
        timers.schedule_decoy(machine, std::time::Duration::from_secs(1), false, false);
        assert_eq!(timers.0.len(), 1);
        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(1), false);
        assert_eq!(timers.0.len(), 2);
        timers.remove_action(&machine);
        assert_eq!(timers.0.len(), 1);
        timers.remove_internal(&machine);
        assert_eq!(timers.0.len(), 0);
    }

    #[test]
    fn test_internal_machine_timer_replace() {
        let mut timers = types::MachineTimers::new(4);
        let machine = MachineId::from_raw(1);

        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(1), false);
        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(2), false);
        assert_eq!(timers.0.len(), 1);
        let i = timers.0.front().unwrap().0;
        assert!(
            i.duration_since(Instant::now()) > std::time::Duration::from_secs(1),
            "The longer timer should be kept"
        );

        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(2), false);
        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(1), false);

        assert_eq!(timers.0.len(), 1);
        let i = timers.0.front().unwrap().0;
        assert!(
            i.duration_since(Instant::now()) > std::time::Duration::from_secs(1),
            "The longer timer should be kept"
        );

        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(2), true);
        timers.schedule_internal_timer(machine, std::time::Duration::from_secs(1), true);

        assert_eq!(timers.0.len(), 1);
        let i = timers.0.front().unwrap().0;
        assert!(
            i.duration_since(Instant::now()) < std::time::Duration::from_secs(2),
            "The last timer should be kept"
        );
    }
}