summaryrefslogtreecommitdiffhomepage
path: root/talpid-core/src/offline/windows.rs
blob: eeccac6fe7f0249d24443b7a93832ac3f0e0da1f (plain)
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
use crate::window::{PowerManagementEvent, PowerManagementListener};
use futures::channel::mpsc::UnboundedSender;
use parking_lot::Mutex;
use std::{
    io,
    sync::{Arc, Weak},
    time::Duration,
};
use talpid_routing::{CallbackHandle, EventType, RouteManagerHandle, get_best_default_route};
use talpid_types::{ErrorExt, net::Connectivity};
use talpid_windows::net::AddressFamily;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Unable to create listener thread")]
    ThreadCreationError(#[from] io::Error),
    #[error("Failed to start connectivity monitor")]
    ConnectivityMonitorError(#[from] talpid_routing::Error),
}

pub struct BroadcastListener {
    system_state: Arc<Mutex<SystemState>>,
    _callback_handle: CallbackHandle,
    _notify_tx: Arc<UnboundedSender<Connectivity>>,
}

impl BroadcastListener {
    pub async fn start(
        notify_tx: UnboundedSender<Connectivity>,
        route_manager: RouteManagerHandle,
        mut power_mgmt_rx: PowerManagementListener,
    ) -> Result<Self, Error> {
        let notify_tx = Arc::new(notify_tx);
        let (ipv4, ipv6) = Self::check_initial_connectivity();
        let connectivity = ConnectivityInner {
            ipv4,
            ipv6,
            suspended: false,
        };
        log::info!("Initial connectivity: {}", connectivity.into_connectivity());
        let system_state = Arc::new(Mutex::new(SystemState {
            connectivity,
            notify_tx: Arc::downgrade(&notify_tx),
        }));

        let state = system_state.clone();
        tokio::spawn(async move {
            while let Some(event) = power_mgmt_rx.next().await {
                match event {
                    PowerManagementEvent::Suspend => {
                        log::debug!("Machine is preparing to enter sleep mode");
                        apply_system_state_change(state.clone(), StateChange::Suspended(true));
                    }
                    PowerManagementEvent::ResumeAutomatic => {
                        let state_copy = state.clone();
                        tokio::spawn(async move {
                            // Tunnel will be unavailable for approximately 2 seconds on a healthy
                            // machine.
                            tokio::time::sleep(Duration::from_secs(5)).await;
                            log::debug!("Tunnel device is presumed to have been re-initialized");
                            apply_system_state_change(state_copy, StateChange::Suspended(false));
                        });
                    }
                    _ => (),
                }
            }
        });

        let callback_handle =
            Self::setup_network_connectivity_listener(system_state.clone(), route_manager).await?;

        Ok(BroadcastListener {
            system_state,
            _callback_handle: callback_handle,
            _notify_tx: notify_tx,
        })
    }

    fn check_initial_connectivity() -> (bool, bool) {
        let v4_connectivity = get_best_default_route(AddressFamily::Ipv4)
            .map(|route| route.is_some())
            .unwrap_or_else(|error| {
                log::error!(
                    "{}",
                    error.display_chain_with_msg("Failed to check initial IPv4 connectivity")
                );
                true
            });
        let v6_connectivity = get_best_default_route(AddressFamily::Ipv6)
            .map(|route| route.is_some())
            .unwrap_or_else(|error| {
                log::error!(
                    "{}",
                    error.display_chain_with_msg("Failed to check initial IPv6 connectivity")
                );
                true
            });
        (v4_connectivity, v6_connectivity)
    }

    /// The caller must make sure the `system_state` reference is valid
    /// until after `WinNet_DeactivateConnectivityMonitor` has been called.
    async fn setup_network_connectivity_listener(
        system_state: Arc<Mutex<SystemState>>,
        route_manager: RouteManagerHandle,
    ) -> Result<CallbackHandle, Error> {
        let change_handle = route_manager
            .add_default_route_change_callback(Box::new(move |event, addr_family| {
                Self::connectivity_callback(event, addr_family, &system_state)
            }))
            .await
            .map_err(Error::ConnectivityMonitorError)?;
        Ok(change_handle)
    }

    fn connectivity_callback(
        event_type: EventType<'_>,
        family: AddressFamily,
        state_lock: &Arc<Mutex<SystemState>>,
    ) {
        use talpid_routing::EventType::*;

        if matches!(event_type, UpdatedDetails(_)) {
            // ignore changes that don't affect the route
            return;
        }

        let connectivity = event_type != Removed;
        let change = match family {
            AddressFamily::Ipv4 => StateChange::NetworkV4Connectivity(connectivity),
            AddressFamily::Ipv6 => StateChange::NetworkV6Connectivity(connectivity),
        };
        let mut state = state_lock.lock();
        state.apply_change(change);
    }

    #[allow(clippy::unused_async)]
    pub async fn connectivity(&self) -> Connectivity {
        let state = self.system_state.lock();
        state.connectivity.into_connectivity()
    }
}

#[derive(Debug)]
enum StateChange {
    NetworkV4Connectivity(bool),
    NetworkV6Connectivity(bool),
    Suspended(bool),
}

struct SystemState {
    connectivity: ConnectivityInner,
    notify_tx: Weak<UnboundedSender<Connectivity>>,
}

impl SystemState {
    fn apply_change(&mut self, change: StateChange) {
        let old_state = self.connectivity.into_connectivity();
        match change {
            StateChange::NetworkV4Connectivity(connectivity) => {
                self.connectivity.ipv4 = connectivity;
            }
            StateChange::NetworkV6Connectivity(connectivity) => {
                self.connectivity.ipv6 = connectivity;
            }
            StateChange::Suspended(suspended) => {
                self.connectivity.suspended = suspended;
            }
        };

        let new_state = self.connectivity.into_connectivity();
        if old_state != new_state {
            log::info!("Connectivity changed: {new_state}");
            if let Some(notify_tx) = self.notify_tx.upgrade() {
                if let Err(e) = notify_tx.unbounded_send(self.connectivity.into_connectivity()) {
                    log::error!("Failed to send new offline state to daemon: {}", e);
                }
            }
        }
    }
}

pub type MonitorHandle = BroadcastListener;

pub async fn spawn_monitor(
    sender: UnboundedSender<Connectivity>,
    route_manager: RouteManagerHandle,
) -> Result<MonitorHandle, Error> {
    let power_mgmt_rx = crate::window::PowerManagementListener::new();
    BroadcastListener::start(sender, route_manager, power_mgmt_rx).await
}

fn apply_system_state_change(state: Arc<Mutex<SystemState>>, change: StateChange) {
    let mut state = state.lock();
    state.apply_change(change);
}

#[derive(Clone, Copy, Debug)]
struct ConnectivityInner {
    /// Whether IPv4 connectivity seems to be available on the host.
    ipv4: bool,
    /// Whether IPv6 connectivity seems to be available on the host.
    ipv6: bool,
    /// The host is suspended.
    suspended: bool,
}

impl ConnectivityInner {
    /// Map [`ConnectivityInner`] to the public [`Connectivity`].
    ///
    /// # Note
    ///
    /// If the host is suspended, there is a great likelihood that we should
    /// consider the host to be offline. We synthesize this by setting both
    /// `ipv4` and `ipv6` availability to `false`.
    fn into_connectivity(self) -> Connectivity {
        if self.suspended {
            Connectivity::Offline
        } else {
            Connectivity::new(self.ipv4, self.ipv6)
        }
    }
}