summaryrefslogtreecommitdiffhomepage
path: root/talpid-core/src/offline/mod.rs
blob: 71cc01d463778fed23362fa47013c52b6adf58dd (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
#[cfg(target_os = "android")]
use crate::connectivity_listener::ConnectivityListener;
use futures::channel::mpsc::UnboundedSender;
use std::sync::LazyLock;
#[cfg(not(target_os = "android"))]
use talpid_routing::RouteManagerHandle;
use talpid_types::{ErrorExt, net::Connectivity};

#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod imp;

#[cfg(target_os = "windows")]
#[path = "windows.rs"]
mod imp;

#[cfg(target_os = "linux")]
#[path = "linux.rs"]
mod imp;

#[cfg(target_os = "android")]
#[path = "android.rs"]
mod imp;

/// Disables offline monitor
static FORCE_DISABLE_OFFLINE_MONITOR: LazyLock<bool> = LazyLock::new(|| {
    std::env::var("TALPID_DISABLE_OFFLINE_MONITOR")
        .map(|v| v != "0")
        .unwrap_or(false)
});

pub struct MonitorHandle(Option<imp::MonitorHandle>);

impl MonitorHandle {
    pub async fn connectivity(&self) -> Connectivity {
        match self.0.as_ref() {
            Some(monitor) => monitor.connectivity().await,
            None => Connectivity::PresumeOnline,
        }
    }
}

pub async fn spawn_monitor(
    sender: UnboundedSender<Connectivity>,
    #[cfg(not(target_os = "android"))] route_manager: RouteManagerHandle,
    #[cfg(target_os = "linux")] fwmark: Option<u32>,
    #[cfg(target_os = "android")] connectivity_listener: ConnectivityListener,
) -> MonitorHandle {
    let monitor = if *FORCE_DISABLE_OFFLINE_MONITOR {
        None
    } else {
        imp::spawn_monitor(
            sender,
            #[cfg(not(target_os = "android"))]
            route_manager,
            #[cfg(target_os = "linux")]
            fwmark,
            #[cfg(target_os = "android")]
            connectivity_listener,
        )
        .await
        .inspect_err(|error| {
            log::warn!(
                "{}",
                error.display_chain_with_msg("Failed to spawn offline monitor")
            );
        })
        .ok()
    };

    MonitorHandle(monitor)
}