Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Desktop: Connection Doctor
Bee9995332de13f
diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 687de62..a04bcbb 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -25,6 +25,7 @@ const QML: &[&str] = &["qml/components/Chip.qml","qml/components/CodeDigits.qml","qml/components/Divider.qml",+ "qml/components/DoctorSheet.qml","qml/components/HistoryItem.qml","qml/components/Icon.qml","qml/components/IconButton.qml",diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qmlindex 8f89d62..6785abc 100644--- a/desktop/app/qml/MainWindow.qml+++ b/desktop/app/qml/MainWindow.qml@@ -246,6 +246,12 @@ NativeWindow {anchors.right: parent.right}+ DoctorSheet { id: doctorSheet }+ Connections {+ target: AppController+ function onDoctorRequested() { doctorSheet.open() }+ }+Toast { id: toast }Connections {target: AppControllerdiff --git a/desktop/app/qml/components/DoctorSheet.qml b/desktop/app/qml/components/DoctorSheet.qmlnew file mode 100644index 0000000..7be5b6c--- /dev/null+++ b/desktop/app/qml/components/DoctorSheet.qml@@ -0,0 +1,129 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import app.nectarlink++// The Connection Doctor: what stands between the phone and this PC, worst+// first, each with a fix when one can be made from here.+Sheet {+ id: sheet+ cardWidth: 520++ readonly property var checks: { try { return JSON.parse(AppController.doctorChecks) } catch (e) { return [] } }+ readonly property bool allWell: checks.length > 0 && checks.every(c => c.outcome === "ok")++ function fixLabel(fix) {+ switch (fix) {+ case "firewall": return qsTr("Allow")+ case "network-settings": return qsTr("Open settings")+ case "reconnect": return qsTr("Reconnect")+ default: return ""+ }+ }++ Column {+ width: parent.width+ spacing: 16++ Item {+ width: parent.width+ height: Math.max(heading.height, busy.height)+ Txt {+ id: heading+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Connection Doctor")+ role: "headline"+ }+ Spinner {+ id: busy+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ visible: AppController.doctorBusy+ }+ }+ Txt {+ width: parent.width+ wrapMode: Text.WordWrap+ role: "body"+ muted: true+ text: AppController.doctorBusy && sheet.checks.length === 0+ ? qsTr("Checking this PC's network and firewall…")+ : sheet.allWell+ ? qsTr("Everything looks right. If your phone still can't connect, open Nectarlink on it and keep both on the same network.")+ : qsTr("Here's what may keep your phone from reaching this PC.")+ }++ Column {+ width: parent.width+ spacing: 2+ opacity: AppController.doctorBusy ? 0.55 : 1+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }+ Repeater {+ model: sheet.checks+ delegate: Item {+ id: row+ required property var modelData+ width: parent.width+ height: Math.max(badge.height, words.height, fixButton.height) + 20++ Rectangle {+ id: badge+ x: 0; y: 12+ width: 28; height: 28+ radius: 14+ color: row.modelData.outcome === "ok" ? Theme.secondaryContainer+ : row.modelData.outcome === "warn" ? Qt.alpha(Theme.warning, 0.18)+ : Qt.alpha(Theme.error, 0.16)+ Icon {+ anchors.centerIn: parent+ width: 16; height: 16+ path: row.modelData.outcome === "ok" ? Icons.check : Icons.warning+ color: row.modelData.outcome === "ok" ? Theme.secondaryContainerContent+ : row.modelData.outcome === "warn" ? Theme.warning : Theme.error+ }+ }+ Column {+ id: words+ anchors.left: badge.right+ anchors.leftMargin: 14+ anchors.right: fixButton.visible ? fixButton.left : parent.right+ anchors.rightMargin: fixButton.visible ? 12 : 0+ y: 12+ spacing: 3+ Txt { width: parent.width; text: row.modelData.title; role: "title"; size: 14; wrapMode: Text.WordWrap }+ Txt {+ width: parent.width+ visible: row.modelData.detail.length > 0+ text: row.modelData.detail+ role: "bodySmall"+ muted: true+ wrapMode: Text.WordWrap+ }+ }+ Button {+ id: fixButton+ anchors.right: parent.right+ y: 10+ visible: row.modelData.fix !== undefined+ enabled: !AppController.doctorBusy+ variant: row.modelData.outcome === "fail" ? "fill" : "tonal"+ size: "sm"+ text: sheet.fixLabel(row.modelData.fix)+ onClicked: AppController.doctorFix(row.modelData.fix)+ }+ }+ }+ }++ Row {+ anchors.right: parent.right+ spacing: 10+ Button {+ variant: "text"+ text: qsTr("Check again")+ enabled: !AppController.doctorBusy+ onClicked: AppController.runDoctor()+ }+ Button { text: qsTr("Done"); onClicked: sheet.close() }+ }+ }+}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex dd323c4..7ec4627 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -534,6 +534,13 @@ Item {: qsTr("Open Nectarlink on %1. They connect on their own when both are on the same network.").arg(home.name)}+ Button {+ visible: !home.online+ variant: "tonal"+ size: "sm"+ text: qsTr("Check the connection")+ onClicked: AppController.runDoctor()+ }}}Card {diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex de76d77..2b0aaa6 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -191,6 +191,24 @@ Item {}}+ // ---- Connection ----+ Txt { text: qsTr("Connection"); role: "label"; muted: true }+ Card {+ width: parent.width+ ListRow {+ width: parent.width+ iconPath: Icons.wifi+ title: qsTr("Connection Doctor")+ description: qsTr("Finds what keeps your phone from reaching this PC (the firewall, the network, a VPN) and fixes what it can.")+ Button {+ variant: "tonal"+ size: "sm"+ text: qsTr("Check")+ onClicked: AppController.runDoctor()+ }+ }+ }+// ---- Notifications ----Txt { text: qsTr("Notifications"); role: "label"; muted: true }Card {diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex b4e4996..b34fda1 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -60,6 +60,11 @@ pub mod qobject {/// Whether Windows shows this app's notifications.#[qproperty(bool, toasts_enabled)]#[qproperty(QString, version)]+ /// The Connection Doctor's findings, as JSON: [{ id, outcome:+ /// "ok" | "warn" | "fail", title, detail, fix? }].+ #[qproperty(QString, doctor_checks)]+ /// Checking, or fixing.+ #[qproperty(bool, doctor_busy)]type AppController = super::AppControllerRust;/// Asks a paired device to ring (or stop).@@ -96,6 +101,14 @@ pub mod qobject {#[cxx_name = "refreshToastsEnabled"]fn refresh_toasts_enabled(self: Pin<&mut AppController>);+ /// Opens the Connection Doctor and checks the connection.+ #[qinvokable]+ fn run_doctor(self: Pin<&mut AppController>);+ /// Runs one of the Doctor's fixes ("firewall", "network-settings",+ /// "reconnect"), then checks again.+ #[qinvokable]+ fn doctor_fix(self: Pin<&mut AppController>, fix: &QString);+/// The folder with the app's logs, as a file URL.#[qinvokable]fn logs_url(self: &AppController) -> QString;@@ -109,6 +122,9 @@ pub mod qobject {/// The user chose Quit in the tray.#[qsignal]fn quit_requested(self: Pin<&mut AppController>);+ /// Show the Connection Doctor.+ #[qsignal]+ fn doctor_requested(self: Pin<&mut AppController>);}impl cxx_qt::Threading for AppController {}@@ -130,6 +146,8 @@ pub struct AppControllerRust {wallpaper_colors: QString,toasts_enabled: bool,version: QString,+ doctor_checks: QString,+ doctor_busy: bool,tray: Option<tray::Tray>,}@@ -137,6 +155,37 @@ pub struct AppControllerRust {/// reach it.static CONTROLLER: OnceLock<Mutex<Option<CxxQtThread<qobject::AppController>>>> = OnceLock::new();+/// Runs a Doctor fix (if any), then the checks, off the UI thread; the+/// findings land in `doctor_checks`.+fn diagnose_in_background(mut object: Pin<&mut qobject::AppController>, fix: Option<String>) {+ if object.doctor_busy {+ return;+ }+ object.as_mut().set_doctor_busy(true);+ let qt = object.qt_thread();+ let spawned = std::thread::Builder::new().name("doctor".into()).spawn(move || {+ if let Some(fix) = fix {+ crate::doctor::fix(&fix);+ // A reconnect needs a moment to show.+ if fix == "reconnect" {+ std::thread::sleep(std::time::Duration::from_secs(3));+ }+ }+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_secs() as i64);+ let checks = crate::doctor::diagnose(&crate::doctor::gather(), now);+ let json = serde_json::to_string(&checks).unwrap_or_else(|_| "[]".into());+ let _ = qt.queue(move |mut object| {+ object.as_mut().set_doctor_checks(QString::from(&json));+ object.set_doctor_busy(false);+ });+ });+ if spawned.is_err() {+ object.set_doctor_busy(false);+ }+}+fn controller() -> Option<CxxQtThread<qobject::AppController>> {CONTROLLER.get()?.lock().unwrap_or_else(|e| e.into_inner()).clone()}@@ -375,6 +424,15 @@ impl qobject::AppController {self.as_mut().set_toggles_revision(revision);}+ pub fn run_doctor(mut self: Pin<&mut Self>) {+ self.as_mut().doctor_requested();+ diagnose_in_background(self, None);+ }++ pub fn doctor_fix(self: Pin<&mut Self>, fix: &QString) {+ diagnose_in_background(self, Some(String::from(fix)));+ }+pub fn logs_url(&self) -> QString {let dir = crate::logging::logs_dir(&core_host::host().data_dir);QString::from(&format!("file:///{}", dir.to_string_lossy().replace('\\', "/")))diff --git a/desktop/app/src/doctor.rs b/desktop/app/src/doctor.rsnew file mode 100644index 0000000..7ea7fac--- /dev/null+++ b/desktop/app/src/doctor.rs@@ -0,0 +1,316 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! The Connection Doctor: why a phone can't reach this PC, in plain words,+//! and a button to fix what can be fixed from here (the firewall, the+//! network's profile, reconnecting).+//!+//! Checks run on a worker thread (they ask Windows a few slow questions)+//! and come back as a list for the UI.++use nectarlink_core::{ConnectionPath, LinkState};+use serde::Serialize;++use crate::{core_host, win::doctor as windows_checks};++/// How a check came out.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum Outcome {+ Ok,+ Warn,+ Fail,+}++/// One finding, as the UI shows it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct Check {+ pub id: String,+ pub outcome: Outcome,+ pub title: String,+ pub detail: String,+ /// What the fix button does (see [`fix`]), if there's one.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub fix: Option<&'static str>,+}++/// What Windows said, gathered first so the wording can be tested.+#[derive(Debug, Clone, Default)]+pub struct Facts {+ pub local_address: bool,+ pub vpn: bool,+ /// Connected networks: name, and whether it's private or domain.+ pub networks: Vec<(String, bool)>,+ /// `None` when the firewall couldn't be read.+ pub firewall: Option<windows_checks::Firewall>,+ /// Paired devices: name and link.+ pub devices: Vec<(String, LinkState)>,+}++/// Asks Windows and the core (blocking; call on a worker thread).+pub fn gather() -> Facts {+ let adapters = windows_checks::adapters();+ let networks = windows_checks::networks()+ .map(|list| list.into_iter().map(|n| (network_name(&n.name), n.trusted)).collect())+ .unwrap_or_default();+ let firewall = std::env::current_exe().ok().and_then(|exe| windows_checks::firewall(&exe).ok());+ let devices = core_host::host()+ .hub+ .read(|s| s.devices.iter().map(|d| (d.info.name.clone(), d.link.clone())).collect());+ Facts { local_address: adapters.local_address, vpn: adapters.vpn, networks, firewall, devices }+}++/// A network's name as people say it. While Windows is still identifying+/// a network it calls it "Loading..." (or "Identifying..."), which says+/// nothing.+fn network_name(name: &str) -> String {+ let name = name.trim();+ if name.is_empty() || name.ends_with("...") || name.ends_with('…') {+ "This network".into()+ } else {+ name.to_owned()+ }+}++fn check(+ id: &str,+ outcome: Outcome,+ title: impl Into<String>,+ detail: impl Into<String>,+ fix: Option<&'static str>,+) -> Check {+ Check { id: id.into(), outcome, title: title.into(), detail: detail.into(), fix }+}++/// The findings, most important first.+pub fn diagnose(facts: &Facts, now_secs: i64) -> Vec<Check> {+ let mut checks = Vec::new();++ // The network itself.+ if !facts.local_address {+ checks.push(check(+ "network",+ Outcome::Fail,+ "This PC isn't on a network",+ "Connect it to the same Wi-Fi or wired network as your phone.",+ None,+ ));+ } else {+ let title = match facts.networks.first() {+ Some((name, _)) if name != "This network" => format!("Connected to {name}"),+ _ => "Connected to a network".into(),+ };+ checks.push(check("network", Outcome::Ok, title, "", None));+ }+ if let Some((name, _)) = facts.networks.iter().find(|(_, trusted)| !trusted) {+ checks.push(check(+ "profile",+ Outcome::Warn,+ format!("{name} is set as a public network"),+ "On public networks Windows keeps other devices from finding this PC. If it's your home or work \+ network, set it to Private.",+ Some("network-settings"),+ ));+ }++ // The firewall.+ match facts.firewall {+ None => {}+ Some(f) if !f.on => {+ checks.push(check("firewall", Outcome::Ok, "Windows Firewall is off for this network", "", None));+ }+ Some(f) if f.blocked => checks.push(check(+ "firewall",+ Outcome::Fail,+ "Windows Firewall blocks Nectarlink",+ "Someone chose not to allow it when Windows asked. Allow it, and your phone can connect.",+ Some("firewall"),+ )),+ Some(f) if !f.allowed => checks.push(check(+ "firewall",+ Outcome::Warn,+ "Nectarlink isn't allowed through Windows Firewall",+ "Your phone may not be able to connect. Allow it once here.",+ Some("firewall"),+ )),+ Some(_) => {+ checks.push(check("firewall", Outcome::Ok, "Windows Firewall lets your phone connect", "", None))+ }+ }++ if facts.vpn {+ checks.push(check(+ "vpn",+ Outcome::Warn,+ "A VPN is on",+ "VPNs often keep devices on your network from reaching this PC. If your phone can't connect, try \+ turning it off.",+ None,+ ));+ }++ // Each phone.+ for (i, (name, link)) in facts.devices.iter().enumerate() {+ let id = format!("device{i}");+ let finding = match link {+ LinkState::Online { path, rtt_ms } => {+ let how = match path {+ ConnectionPath::Lan => "On this network",+ _ => "While away",+ };+ check(&id, Outcome::Ok, format!("{name} is connected"), format!("{how} · {rtt_ms} ms"), None)+ }+ LinkState::Connecting => check(+ &id,+ Outcome::Warn,+ format!("Connecting to {name}…"),+ "This usually takes a few seconds.",+ None,+ ),+ LinkState::Offline { last_seen } => {+ let seen = last_seen.map_or_else(+ || "It hasn't connected yet.".to_owned(),+ |at| format!("Last seen {}.", ago(now_secs - at)),+ );+ check(+ &id,+ Outcome::Warn,+ format!("{name} isn't connected"),+ format!(+ "{seen} Open Nectarlink on the phone and keep both on the same network. If the phone \+ asks to run in the background, allow it."+ ),+ Some("reconnect"),+ )+ }+ };+ checks.push(finding);+ }++ // Failures first, then warnings, then what's fine (stable within each).+ checks.sort_by_key(|c| match c.outcome {+ Outcome::Fail => 0,+ Outcome::Warn => 1,+ Outcome::Ok => 2,+ });+ checks+}++fn ago(seconds: i64) -> String {+ let minutes = seconds / 60;+ match minutes {+ ..=0 => "just now".into(),+ 1 => "a minute ago".into(),+ 2..=59 => format!("{minutes} minutes ago"),+ 60..=119 => "an hour ago".into(),+ 120..=1439 => format!("{} hours ago", minutes / 60),+ _ => format!("{} days ago", minutes / 1440),+ }+}++/// Runs a fix (blocking: the firewall one waits for Windows' prompt).+/// Returns whether anything was done.+pub fn fix(id: &str) -> bool {+ match id {+ "firewall" => {+ let Ok(exe) = std::env::current_exe() else { return false };+ match windows_checks::fix_firewall(&exe) {+ Ok(done) => done,+ Err(e) => {+ tracing::warn!(error = %e, "can't change the firewall");+ false+ }+ }+ }+ "network-settings" => crate::win::shell::open_url("ms-settings:network-status").is_ok(),+ "reconnect" => {+ if let Some(node) = core_host::node() {+ core_host::spawn(async move { node.refresh().await });+ }+ true+ }+ _ => false,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts() -> Facts {+ Facts {+ local_address: true,+ vpn: false,+ networks: vec![("Home".into(), true)],+ firewall: Some(windows_checks::Firewall { on: true, allowed: true, blocked: false }),+ devices: vec![("Pixel".into(), LinkState::Online { path: ConnectionPath::Lan, rtt_ms: 4 })],+ }+ }++ fn outcomes(checks: &[Check]) -> Vec<(&str, Outcome)> {+ checks.iter().map(|c| (c.id.as_str(), c.outcome)).collect()+ }++ #[test]+ fn all_well() {+ let checks = diagnose(&facts(), 0);+ assert!(checks.iter().all(|c| c.outcome == Outcome::Ok), "{checks:?}");+ assert_eq!(checks[0].title, "Connected to Home");+ assert_eq!(checks.last().unwrap().detail, "On this network · 4 ms");+ }++ #[test]+ fn problems_come_first_with_fixes() {+ let mut f = facts();+ f.networks = vec![("Cafe".into(), false)];+ f.firewall = Some(windows_checks::Firewall { on: true, allowed: true, blocked: true });+ f.vpn = true;+ f.devices = vec![("Pixel".into(), LinkState::Offline { last_seen: Some(1_000) })];+ let checks = diagnose(&f, 1_000 + 3 * 3600);+ assert_eq!(+ outcomes(&checks),+ [+ ("firewall", Outcome::Fail),+ ("profile", Outcome::Warn),+ ("vpn", Outcome::Warn),+ ("device0", Outcome::Warn),+ ("network", Outcome::Ok)+ ]+ );+ assert_eq!(checks[0].fix, Some("firewall"));+ assert_eq!(checks[1].fix, Some("network-settings"));+ assert!(checks[3].detail.starts_with("Last seen 3 hours ago."), "{}", checks[3].detail);+ assert_eq!(checks[3].fix, Some("reconnect"));+ }++ #[test]+ fn no_network_and_no_allow_rule() {+ let mut f = facts();+ f.local_address = false;+ f.firewall = Some(windows_checks::Firewall { on: true, allowed: false, blocked: false });+ let checks = diagnose(&f, 0);+ assert_eq!(checks[0].title, "This PC isn't on a network");+ assert_eq!(checks[1].outcome, Outcome::Warn);+ assert_eq!(checks[1].fix, Some("firewall"));+ }++ #[test]+ fn networks_being_identified_get_a_plain_name() {+ assert_eq!(network_name("Loading..."), "This network");+ assert_eq!(network_name("Identifying…"), "This network");+ assert_eq!(network_name("Home 5G"), "Home 5G");+ let mut f = facts();+ f.networks = vec![("This network".into(), false)];+ let checks = diagnose(&f, 0);+ assert_eq!(checks[0].title, "This network is set as a public network");+ let network = checks.iter().find(|c| c.id == "network").unwrap();+ assert_eq!(network.title, "Connected to a network");+ }++ #[test]+ fn times_read_naturally() {+ assert_eq!(ago(10), "just now");+ assert_eq!(ago(90), "a minute ago");+ assert_eq!(ago(600), "10 minutes ago");+ assert_eq!(ago(5400), "an hour ago");+ assert_eq!(ago(3 * 86400), "3 days ago");+ }+}diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 9bb697b..db7b885 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -11,6 +11,7 @@mod bridge;mod clipboard;mod core_host;+mod doctor;mod icons;mod launch;mod links;diff --git a/desktop/app/src/win/doctor.rs b/desktop/app/src/win/doctor.rsnew file mode 100644index 0000000..e1e13f8--- /dev/null+++ b/desktop/app/src/win/doctor.rs@@ -0,0 +1,267 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! What the Connection Doctor looks at on Windows: the firewall's rules for+//! this app, the network's profile (Public networks hide the PC), whether+//! there's a network at all, and VPNs, which often keep phones out.++use std::path::Path;++use windows::{+ Win32::{+ Foundation::{CloseHandle, WAIT_OBJECT_0},+ NetworkManagement::{+ IpHelper::{+ GAA_FLAG_SKIP_ANYCAST, GAA_FLAG_SKIP_MULTICAST, GetAdaptersAddresses, IP_ADAPTER_ADDRESSES_LH,+ },+ WindowsFirewall::{+ INetFwPolicy2, INetFwRule, NET_FW_ACTION_ALLOW, NET_FW_ACTION_BLOCK, NET_FW_RULE_DIR_IN,+ NetFwPolicy2,+ },+ },+ Networking::{+ NetworkListManager::{+ INetwork, INetworkListManager, NLM_ENUM_NETWORK_CONNECTED,+ NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED, NLM_NETWORK_CATEGORY_PRIVATE, NetworkListManager,+ },+ WinSock::AF_UNSPEC,+ },+ System::{+ Com::{CLSCTX_INPROC_SERVER, CoCreateInstance},+ Ole::IEnumVARIANT,+ Threading::{INFINITE, WaitForSingleObject},+ Variant::{VARIANT, VariantClear},+ },+ UI::{+ Shell::{SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, ShellExecuteExW},+ WindowsAndMessaging::SW_HIDE,+ },+ },+ core::{HSTRING, IUnknown, Interface, PCWSTR, w},+};++use super::with_com;++/// The firewall's view of this app, for incoming connections.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct Firewall {+ /// The firewall is on for the current network's profile.+ pub on: bool,+ /// An enabled rule lets the app in on the current profile.+ pub allowed: bool,+ /// An enabled rule blocks the app (Windows adds one when someone+ /// cancels its "allow access" prompt), which wins over allow rules.+ pub blocked: bool,+}++/// How Windows treats the network the PC is on.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Network {+ pub name: String,+ /// Private or domain: devices on it can find this PC.+ pub trusted: bool,+}++/// The firewall's rules for `exe`.+pub fn firewall(exe: &Path) -> windows::core::Result<Firewall> {+ let exe = exe.to_string_lossy().to_lowercase();+ with_com(|| {+ // SAFETY: COM calls on live objects; every VARIANT is cleared.+ unsafe {+ let policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER)?;+ let profiles = policy.CurrentProfileTypes()?;+ let mut on = false;+ for bit in [1, 2, 4] {+ if profiles & bit != 0+ && policy+ .get_FirewallEnabled(+ windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_PROFILE_TYPE2(bit),+ )?+ .as_bool()+ {+ on = true;+ }+ }+ let mut result = Firewall { on, ..Firewall::default() };+ let rules = policy.Rules()?;+ let all: IEnumVARIANT = rules._NewEnum()?.cast()?;+ loop {+ let mut item = [VARIANT::default()];+ let mut fetched = 0;+ if all.Next(&mut item, &mut fetched).is_err() || fetched == 0 {+ break;+ }+ let rule = IUnknown::try_from(&item[0]).ok().and_then(|u| u.cast::<INetFwRule>().ok());+ let _ = VariantClear(&mut item[0]);+ let Some(rule) = rule else { continue };+ let applies = rule.Enabled().is_ok_and(|e| e.as_bool())+ && rule.Direction().is_ok_and(|d| d == NET_FW_RULE_DIR_IN)+ && rule.Profiles().is_ok_and(|p| p & profiles != 0)+ && rule.ApplicationName().is_ok_and(|a| a.to_string().to_lowercase() == exe);+ if !applies {+ continue;+ }+ match rule.Action() {+ Ok(a) if a == NET_FW_ACTION_ALLOW => result.allowed = true,+ Ok(a) if a == NET_FW_ACTION_BLOCK => result.blocked = true,+ _ => {}+ }+ }+ Ok(result)+ }+ })+}++/// The networks the PC is connected to.+pub fn networks() -> windows::core::Result<Vec<Network>> {+ with_com(|| {+ // SAFETY: COM calls on live objects.+ unsafe {+ let manager: INetworkListManager =+ CoCreateInstance(&NetworkListManager, None, CLSCTX_INPROC_SERVER)?;+ let list = manager.GetNetworks(NLM_ENUM_NETWORK_CONNECTED)?;+ let mut networks = Vec::new();+ loop {+ let mut item: [Option<INetwork>; 1] = [None];+ let mut fetched = 0;+ if list.Next(&mut item, Some(&mut fetched)).is_err() || fetched == 0 {+ break;+ }+ let Some(network) = item[0].take() else { break };+ let category = network.GetCategory()?;+ networks.push(Network {+ name: network.GetName().map(|n| n.to_string()).unwrap_or_default(),+ trusted: category == NLM_NETWORK_CATEGORY_PRIVATE+ || category == NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED,+ });+ }+ Ok(networks)+ }+ })+}++/// What the network adapters say: whether one has a local address, and+/// whether a VPN is up.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct Adapters {+ pub local_address: bool,+ pub vpn: bool,+}++pub fn adapters() -> Adapters {+ const IF_TYPE_PPP: u32 = 23;+ const IF_TYPE_TUNNEL: u32 = 131;+ const IF_TYPE_SOFTWARE_LOOPBACK: u32 = 24;+ let mut found = Adapters::default();+ let mut size: u32 = 32 * 1024;+ let mut buffer = vec![0u8; size as usize];+ // SAFETY: the buffer is sized as GetAdaptersAddresses asks (retried+ // once when too small) and only read as the linked list it fills in.+ unsafe {+ let flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST;+ let mut status = GetAdaptersAddresses(+ u32::from(AF_UNSPEC.0),+ flags,+ None,+ Some(buffer.as_mut_ptr().cast()),+ &mut size,+ );+ if status == 111 {+ // ERROR_BUFFER_OVERFLOW+ buffer = vec![0u8; size as usize];+ status = GetAdaptersAddresses(+ u32::from(AF_UNSPEC.0),+ flags,+ None,+ Some(buffer.as_mut_ptr().cast()),+ &mut size,+ );+ }+ if status != 0 {+ return found;+ }+ let mut adapter = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();+ while let Some(a) = adapter.as_ref() {+ let up = a.OperStatus.0 == 1;+ let description = a.Description.to_string().unwrap_or_default().to_lowercase();+ let kind = a.IfType;+ if up && kind != IF_TYPE_SOFTWARE_LOOPBACK {+ let vpn_like = kind == IF_TYPE_PPP+ || kind == IF_TYPE_TUNNEL+ || ["vpn", "wireguard", "tap-windows", "openvpn", "tailscale", "zerotier"]+ .iter()+ .any(|word| description.contains(word));+ if vpn_like {+ found.vpn = true;+ } else {+ let mut unicast = a.FirstUnicastAddress;+ while let Some(u) = unicast.as_ref() {+ let addr = u.Address.lpSockaddr;+ // AF_INET with a non link-local address.+ if !addr.is_null() && (*addr).sa_family.0 == 2 {+ let bytes = &(*addr).sa_data;+ let first = bytes[2] as u8;+ let second = bytes[3] as u8;+ if !(first == 169 && second == 254) && first != 127 {+ found.local_address = true;+ }+ }+ unicast = u.Next;+ }+ }+ }+ adapter = a.Next;+ }+ }+ found+}++/// Lets `exe` through the firewall on private and domain networks, removing+/// rules that block it. Asks for administrator rights (the UAC prompt) and+/// waits until it's done; `Ok(false)` if the user said no.+pub fn fix_firewall(exe: &Path) -> windows::core::Result<bool> {+ let exe = exe.to_string_lossy();+ let script = format!(+ "/c netsh advfirewall firewall delete rule name=all dir=in program=\"{exe}\" & \+ netsh advfirewall firewall add rule name=\"Nectarlink\" dir=in action=allow program=\"{exe}\" \+ enable=yes profile=private,domain"+ );+ let parameters = HSTRING::from(script);+ let mut info = SHELLEXECUTEINFOW {+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,+ fMask: SEE_MASK_NOCLOSEPROCESS,+ lpVerb: w!("runas"),+ lpFile: w!("cmd.exe"),+ lpParameters: PCWSTR(parameters.as_ptr()),+ nShow: SW_HIDE.0,+ ..Default::default()+ };+ // SAFETY: the structure and its strings outlive the call; the process+ // handle is waited on and closed.+ unsafe {+ if ShellExecuteExW(&mut info).is_err() {+ // Most often: the user declined the prompt.+ return Ok(false);+ }+ if !info.hProcess.is_invalid() {+ let waited = WaitForSingleObject(info.hProcess, INFINITE);+ let _ = CloseHandle(info.hProcess);+ if waited != WAIT_OBJECT_0 {+ return Ok(false);+ }+ }+ }+ Ok(true)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_the_firewall_and_networks() {+ // Whatever this machine's state, the questions get answers.+ let exe = std::env::current_exe().unwrap();+ firewall(&exe).expect("firewall rules");+ networks().expect("networks");+ let _ = adapters();+ }+}diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rsindex db72d0b..8e8b20f 100644--- a/desktop/app/src/win/mod.rs+++ b/desktop/app/src/win/mod.rs@@ -7,6 +7,7 @@pub mod autostart;pub mod clipboard;+pub mod doctor;pub mod icon;pub mod image;pub mod media_sessions;