Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Wake-on-LAN: wake a sleeping PC from the phone
Bee62676644921c
diff --git a/README.md b/README.mdindex 5fa4af0..ab13dd1 100644--- a/README.md+++ b/README.md@@ -71,9 +71,11 @@ tests; there are no releases yet.power level.- **Find my device** in both directions. The phone rings on the alarm stream,even in silent mode.-- **Lock or sleep the PC** from the phone, and **links** both ways: share a- link from any phone app to open it on the PC, or send a copied link from the- PC's tray to the phone.+- **Lock, sleep or wake the PC** from the phone (when the PC is offline, Wake+ sends Wake-on-LAN magic packets to its stored network addresses, and the PC's+ Settings shows whether its adapter has Wake on Magic Packet turned on), and+ **links** both ways: share a link from any phone app to open it on the PC, or+ send a copied link from the PC's tray to the phone.- **Notifications** from the phone on the PC, as Windows notifications and ina feed in the app, with the app's icon. Reply inline, run their actions(such as "Mark as read") or dismiss them from the PC; what's cleared on onediff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex 86a17aa..bb229cc 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt@@ -147,6 +147,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerprivate var node: NectarlinkNode? = nullprivate var startJob: Job? = nullprivate var networkChange: Job? = null+ private val wakeTimers = java.util.concurrent.ConcurrentHashMap<String, Job>()private val battery = BatteryMonitor(this.context) { battery ->node?.let { scope.launch { it.updateBattery(battery) } }@@ -331,11 +332,13 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerif (event.link is Link.Offline) {pcMedia.update(event.id, "", emptyList())} else if (event.link is Link.Online) {+ wakeTimers.remove(event.id)?.cancel()retryWaitingRecordings(event.id)}}is Event.DeviceAdded -> ConnectionService.start(context)is Event.DeviceRemoved -> {+ wakeTimers.remove(event.id)?.cancel()pcMedia.update(event.id, "", emptyList())if (_state.value.devices.isEmpty()) ConnectionService.stop(context)}@@ -663,6 +666,48 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}}+ /**+ * Sends Wake-on-LAN magic packets to a sleeping or shut-down PC and waits+ * up to ~60 s for it to connect before showing troubleshooting tips.+ */+ fun wake(id: String) {+ val node = node ?: return+ wakeTimers.remove(id)?.cancel()+ _state.update { it.withWakeState(id, WakeState.Waking) }+ val timer = scope.launch(Dispatchers.IO) {+ repeat(15) {+ delay(4_000)+ val dev = _state.value.device(id)+ if (dev == null || dev.online || dev.wakeState != WakeState.Waking) return@launch+ runCatching { node.refresh() }+ }+ _state.update { s ->+ val dev = s.device(id)+ if (dev != null && !dev.online && dev.wakeState == WakeState.Waking) {+ s.withWakeState(id, WakeState.TimedOut)+ } else {+ s+ }+ }+ }+ wakeTimers[id] = timer+ scope.launch(Dispatchers.IO) {+ try {+ node.wake(id)+ node.refresh()+ } catch (e: NectarlinkException) {+ wakeTimers.remove(id)?.cancel()+ _state.update { it.withWakeState(id, WakeState.Idle) }+ val name = _state.value.nameOf(id).orEmpty()+ val msg = when (e) {+ is NectarlinkException.Unsupported -> context.getString(R.string.wake_not_ready, name)+ else -> describe(e)+ }+ _messages.tryEmit(msg)+ }+ }+ }+/** Opens a link on a PC; returns what to tell the user. */suspend fun openLinkOnPc(id: String, url: String): String {startJob?.join()diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex a14e4e8..2717fb7 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -32,6 +32,15 @@ sealed interface PairingState {data class Failed(val failure: PairingFailure) : PairingState}+/** Wake-on-LAN progress for an offline PC. */+enum class WakeState {+ Idle,+ /** Magic packets sent; waiting up to ~60 s for the PC to connect. */+ Waking,+ /** ~60 s passed without the PC connecting; show what to check. */+ TimedOut,+}+/** A paired device as the UI shows it. */data class Device(val id: String,@@ -40,6 +49,8 @@ data class Device(val model: String?,val pairedAt: Long,val link: Link,+ val canWake: Boolean = false,+ val wakeState: WakeState = WakeState.Idle,val battery: app.nectarlink.core.Battery? = null,val power: PowerLevel = PowerLevel.NOT_APPLICABLE,val features: List<Feature> = emptyList(),@@ -95,6 +106,9 @@ data class CoreState(fun withDevices(paired: List<PairedDevice>): CoreState =copy(devices = paired.map { it.toDevice() }.sortedBy { it.pairedAt })+ fun withWakeState(id: String, state: WakeState): CoreState =+ update(id) { it.copy(wakeState = state) }+/** Folds one core event into the state. */fun reduce(event: Event): CoreState = when (event) {is Event.DeviceAdded -> {@@ -105,11 +119,22 @@ data class CoreState(devices = devices.filterNot { it.id == event.id },ringingFrom = if (ringingFrom == nameOf(event.id)) null else ringingFrom,)- is Event.LinkChanged -> update(event.id) { it.copy(link = event.link) }+ is Event.LinkChanged -> update(event.id) {+ it.copy(+ link = event.link,+ wakeState = if (event.link is Link.Online) WakeState.Idle else it.wakeState,+ )+ }is Event.PeerInfoChanged -> update(event.id) {it.copy(name = event.info.name, kind = event.info.kind, model = event.info.model)}is Event.PeerPowerChanged -> update(event.id) { it.copy(power = event.power) }+ is Event.WakeInfoChanged -> update(event.id) {+ it.copy(+ canWake = event.canWake,+ wakeState = if (!event.canWake) WakeState.Idle else it.wakeState,+ )+ }is Event.Battery -> update(event.id) { it.copy(battery = event.battery) }is Event.Capabilities -> update(event.id) { it.copy(features = event.features) }is Event.Ring -> copy(ringingFrom = if (event.on) nameOf(event.id) ?: "" else null)@@ -168,4 +193,5 @@ internal fun PairedDevice.toDevice() = Device(model = info.model,pairedAt = pairedAt,link = link,+ canWake = canWake,)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.ktindex d90dfd2..95355b3 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt@@ -325,6 +325,7 @@ private fun App(onPairNew = { pairing = true },onRefresh = core::refresh,onPower = core::pcPower,+ onWake = core::wake,onRemote = { id ->remoteInitialMode = RemoteMode.TouchpadremotePcId = iddiff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktindex 8868136..528e082 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -53,6 +53,7 @@ import app.nectarlink.android.core.BackgroundAccessimport app.nectarlink.android.core.LocalNetworkimport app.nectarlink.android.core.CoreStateimport app.nectarlink.android.core.Device+import app.nectarlink.android.core.WakeStateimport app.nectarlink.android.files.transferTitleimport app.nectarlink.android.calls.PhoneCallsimport app.nectarlink.android.contacts.PhoneContacts@@ -81,6 +82,7 @@ fun HomeScreen(onPairNew: () -> Unit,onRefresh: () -> Unit,onPower: (pcId: String, sleep: Boolean) -> Unit,+ onWake: (pcId: String) -> Unit,onRemote: (pcId: String) -> Unit,onRecord: (pcId: String) -> Unit,updater: AppUpdater,@@ -199,7 +201,7 @@ fun HomeScreen(}}items(state.devices, key = { it.id }) { device ->- PcCard(device, onRing, onSendFiles, onSendFolder, onPower, onRemote, onRecord)+ PcCard(device, onRing, onSendFiles, onSendFolder, onPower, onWake, onRemote, onRecord)}if (state.transfers.isNotEmpty()) {item { TransfersCard(state, onCancelTransfer) }@@ -243,6 +245,7 @@ private fun PcCard(onSendFiles: (String, List<Uri>) -> Unit,onSendFolder: (String, Uri) -> Unit,onPower: (String, Boolean) -> Unit,+ onWake: (String) -> Unit,onRemote: (String) -> Unit,onRecord: (String) -> Unit,) {@@ -270,7 +273,14 @@ private fun PcCard() {}}Spacer(Modifier.width(8.dp))- Text(linkText(device.link), style = MaterialTheme.typography.labelLarge)+ Text(+ if (!device.online && device.wakeState == WakeState.Waking) {+ stringResource(R.string.wake_waking, device.name)+ } else {+ linkText(device.link)+ },+ style = MaterialTheme.typography.labelLarge,+ )}Spacer(Modifier.height(12.dp))Text(device.name, style = MaterialTheme.typography.headlineLarge)@@ -304,6 +314,17 @@ private fun PcCard(val outlined = ButtonDefaults.outlinedButtonColors(contentColor = ink, disabledContentColor = ink.copy(alpha = 0.38f))val outline = BorderStroke(1.dp, ink.copy(alpha = if (device.online) 0.45f else 0.15f))FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ if (!device.online && device.canWake) {+ Button(+ enabled = device.wakeState != WakeState.Waking,+ onClick = { onWake(device.id) },+ ) {+ Text(+ if (device.wakeState == WakeState.Waking) stringResource(R.string.wake_waking, device.name)+ else stringResource(R.string.action_wake_pc),+ )+ }+ }Button(enabled = device.online,onClick = {@@ -347,6 +368,29 @@ private fun PcCard(}}}+ if (!device.online && device.wakeState == WakeState.Waking) {+ Spacer(Modifier.height(14.dp))+ LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ } else if (!device.online && device.wakeState == WakeState.TimedOut) {+ Spacer(Modifier.height(16.dp))+ Surface(+ shape = MaterialTheme.shapes.large,+ color = ink.copy(alpha = 0.08f),+ contentColor = ink,+ ) {+ Column(Modifier.fillMaxWidth().padding(16.dp)) {+ Text(+ stringResource(R.string.wake_timeout_title, device.name),+ style = MaterialTheme.typography.titleSmall,+ )+ Spacer(Modifier.height(4.dp))+ Text(+ stringResource(R.string.wake_timeout_text, device.name),+ style = MaterialTheme.typography.bodySmall,+ )+ }+ }+ }}}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.ktindex 132726b..aa551ec 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.kt@@ -43,6 +43,7 @@ import androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.FilledTonalButtonimport androidx.compose.material3.FilterChip+import androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.OutlinedTextField@@ -82,6 +83,7 @@ import androidx.core.content.ContextCompatimport app.nectarlink.android.Rimport app.nectarlink.android.core.Coreimport app.nectarlink.android.core.Device+import app.nectarlink.android.core.WakeStateimport kotlinx.coroutines.delayimport kotlin.math.absimport kotlin.math.hypot@@ -191,9 +193,9 @@ fun RemoteScreen(// Status banner when offline, denied, or unsupportedwhen {- !device.online || access == Core.RemoteAccess.Offline -> StatusBanner(- title = null,- text = stringResource(R.string.remote_offline_text, device.name),+ !device.online || access == Core.RemoteAccess.Offline -> OfflineWakeBanner(+ device = device,+ onWake = { core.wake(device.id) },)access == Core.RemoteAccess.Denied -> StatusBanner(title = stringResource(R.string.remote_denied_title, device.name),@@ -235,6 +237,65 @@ fun RemoteScreen(}}+@Composable+private fun OfflineWakeBanner(device: Device, onWake: () -> Unit) {+ Surface(+ shape = MaterialTheme.shapes.large,+ color = MaterialTheme.colorScheme.secondaryContainer,+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer,+ ) {+ Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {+ when {+ !device.canWake -> {+ Text(+ stringResource(R.string.remote_offline_text, device.name),+ style = MaterialTheme.typography.bodySmall,+ )+ }+ device.wakeState == WakeState.Waking -> {+ Text(+ stringResource(R.string.wake_waking, device.name),+ style = MaterialTheme.typography.titleSmall,+ )+ Spacer(Modifier.height(8.dp))+ LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ }+ device.wakeState == WakeState.TimedOut -> {+ Text(+ stringResource(R.string.wake_timeout_title, device.name),+ style = MaterialTheme.typography.titleSmall,+ )+ Spacer(Modifier.height(4.dp))+ Text(+ stringResource(R.string.wake_timeout_text, device.name),+ style = MaterialTheme.typography.bodySmall,+ )+ Spacer(Modifier.height(10.dp))+ Button(onClick = onWake) {+ Text(stringResource(R.string.action_wake_pc))+ }+ }+ else -> {+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ stringResource(R.string.remote_offline_text, device.name),+ style = MaterialTheme.typography.bodySmall,+ modifier = Modifier.weight(1f),+ )+ Spacer(Modifier.width(12.dp))+ Button(onClick = onWake) {+ Text(stringResource(R.string.action_wake_pc))+ }+ }+ }+ }+ }+ }+}+@Composableprivate fun StatusBanner(title: String?, text: String) {Surface(diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex ace15d6..a9b5c64 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -200,6 +200,11 @@<string name="update_check_failed">Couldn’t check for updates. Check your internet connection.</string><string name="action_lock_pc">Lock PC</string><string name="action_sleep_pc">Sleep</string>+ <string name="action_wake_pc">Wake</string>+ <string name="wake_waking">Waking %1$s…</string>+ <string name="wake_timeout_title">%1$s hasn\'t woken up yet</string>+ <string name="wake_timeout_text">Check that:\n• Wake-on-LAN is enabled in BIOS/UEFI and in the network adapter\'s settings in Windows (Power Management and Wake on Magic Packet).\n• %1$s is on Ethernet if it was shut down (Wi-Fi wake rarely works from shutdown).\n• This phone is on the same network as %1$s.</string>+ <string name="wake_not_ready">Connect to %1$s once so this phone learns its network address.</string><string name="pc_locked">%1$s is locked.</string><string name="pc_sleeping">%1$s is going to sleep.</string><string name="pc_actions_off">Locking and sleep are turned off for this phone on %1$s.</string>diff --git a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.ktindex c74f20a..57108d0 100644--- a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt+++ b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt@@ -16,11 +16,12 @@ import org.junit.Assert.assertTrueimport org.junit.Testclass CoreStateTest {- private fun pc(id: String, name: String, pairedAt: Long) = PairedDevice(+ private fun pc(id: String, name: String, pairedAt: Long, canWake: Boolean = false) = PairedDevice(id = id,info = DeviceInfo(name, DeviceKind.DESKTOP, "windows", "10.0.26200", null, null),pairedAt = pairedAt,link = Link.Offline(null),+ canWake = canWake,)@Test@@ -30,9 +31,15 @@ class CoreStateTest {.reduce(Event.DeviceAdded(pc("a", "Desk", 10)))assertEquals(listOf("Desk", "Laptop"), state.devices.map { it.name })+ state = state.reduce(Event.WakeInfoChanged("a", true))+ .withWakeState("a", WakeState.Waking)+ assertTrue(state.device("a")!!.canWake)+ assertEquals(WakeState.Waking, state.device("a")!!.wakeState)+state = state.reduce(Event.LinkChanged("a", Link.Online(false, 5u))).reduce(Event.Battery("a", Battery(42u, true, "ac")))assertTrue(state.device("a")!!.online)+ assertEquals(WakeState.Idle, state.device("a")!!.wakeState)assertEquals(42.toUByte(), state.device("a")!!.battery!!.level)// Unknown devices are ignored; removal drops the device.diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex e278cda..5621664 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -181,6 +181,8 @@ enum Command {#[arg(value_enum)]action: PowerArg,},+ /// Wake a paired PC using its stored Wake-on-LAN addresses.+ Wake { device: String },/// Open a web link on a paired device.Open { device: String, url: String },/// Browse a paired phone's gallery (albums, photos, thumbnails, download),@@ -1778,12 +1780,19 @@ async fn start_node(cli: &Cli) -> Result<Node> {if !cli.as_phone {config.capabilities.push(nectarlink_core::RECORDER.into());config.capabilities.push(nectarlink_core::TOGGLES_SHOW.into());+ config.capabilities.push(nectarlink_core::PC_WAKE.into());}let extra_caps = config.capabilities.clone();let node = Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")?;if cli.as_phone {let _ = TOGGLES_NODE.set(node.clone());let _ = node.toggles_changed(sample_toggles()).await;+ } else {+ node.set_wake_info(nectarlink_core::PcWakeInfo {+ macs: vec!["02:42:ac:11:00:02".into()],+ broadcasts: vec!["192.168.31.255".into()],+ })+ .await;}if !cli.offers.is_empty() {let mut offers = extra_caps;@@ -2709,6 +2718,39 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.pc_power(id, action).await.context("the PC didn't do it")?;println!("Done.");}+ Command::Wake { device } => {+ let id = resolve(node, device)?;+ if node.wake_info(id)?.is_none() {+ let mut events = node.events();+ let _ = tokio::time::timeout(Duration::from_secs(3), async {+ loop {+ if let Ok(NodeEvent::WakeInfoChanged { device: d, can_wake: true }) =+ events.recv().await+ && d == id+ {+ break;+ }+ }+ })+ .await;+ }+ let info = node.wake_info(id)?.context(+ "no Wake-on-LAN addresses stored for this PC (connect to it once with `pc_actions` on)",+ )?;+ node.wake(id).await.context("wake failed")?;+ let bcasts = if info.broadcasts.is_empty() {+ "255.255.255.255".to_owned()+ } else {+ format!("{}, 255.255.255.255", info.broadcasts.join(", "))+ };+ println!(+ "Sent Wake-on-LAN magic packets for {} ({} adapter{} -> {}).",+ device,+ info.macs.len(),+ if info.macs.len() == 1 { "" } else { "s" },+ bcasts,+ );+ }Command::Open { device, url } => {let id = resolve(node, device)?;wait_until_online(node, id).await?;@@ -3339,6 +3381,22 @@ fn print_event(node: &Node, event: &NodeEvent) {NodeEvent::PhoneToggles { device, toggles } => {println!("{}: toggles {}", name(device), summarize_toggles(toggles));}+ NodeEvent::WakeInfoChanged { device, can_wake } => {+ let detail = node+ .wake_info(*device)+ .ok()+ .flatten()+ .map(|w| {+ let b = if w.broadcasts.is_empty() {+ "255.255.255.255".to_owned()+ } else {+ w.broadcasts.join(", ")+ };+ format!(" ({} adapter(s), broadcasts: {b})", w.macs.len())+ })+ .unwrap_or_default();+ println!("{}: Wake-on-LAN {}{detail}", name(device), if *can_wake { "ready" } else { "cleared" });+ }NodeEvent::RemoteInputRequested { device } => println!("{}: asked to control mouse and keyboard (allow with: nectarlink toggle {} remote_input on)",name(device),@@ -3565,7 +3623,14 @@ fn power_name(level: PowerLevel) -> &'static str {}fn print_device(d: &PairedDevice) {- println!("{:<24} {:<10} {} {}", d.info.name, format!("{:?}", d.info.kind), describe_link(&d.link), d.id);+ let wake = if d.can_wake { " [wake]" } else { "" };+ println!(+ "{:<24} {:<10} {} {}{wake}",+ d.info.name,+ format!("{:?}", d.info.kind),+ describe_link(&d.link),+ d.id+ );}fn describe_link(link: &LinkState) -> String {diff --git a/core/nectarlink-core/src/actions.rs b/core/nectarlink-core/src/actions.rsindex 72cf497..e2307d8 100644--- a/core/nectarlink-core/src/actions.rs+++ b/core/nectarlink-core/src/actions.rs@@ -2,22 +2,121 @@//! One-shot actions on a paired device (docs/protocol/actions.md): lock or//! sleep a PC, and open a link on the other device.-use std::sync::Arc;+use std::{+ net::{Ipv4Addr, SocketAddrV4},+ sync::{Arc, Mutex},+ time::Duration,+};use nectarlink_protocol::{DeviceId, Envelope, ErrorCode,- messages::{LinkOpen, PcPower, types},+ messages::{LinkOpen, PcPower, PcWakeInfo, magic_packet, parse_mac, types, wake},};-use crate::{Error, Result, node::Shared, session::Session};+use crate::{Error, NodeEvent, Result, node::Shared, session::Session};-/// The device toggle that lets a phone lock or sleep this PC.+/// The device toggle that lets a phone lock, sleep or wake this PC.pub(crate) const POWER_TOGGLE: &str = "pc_actions";/// Offered by PCs that lock and sleep on request.pub(crate) const POWER: &str = "pc.power";+/// Offered by PCs that share their Wake-on-LAN adapter addresses.+pub const PC_WAKE: &str = wake::CAP;/// Offered by devices that open links sent to them.pub(crate) const LINKS: &str = "link.open";+/// This PC's current Wake-on-LAN adapter addresses, sent to paired phones on+/// connect and whenever network adapters change.+#[derive(Debug, Default)]+pub(crate) struct CurrentWakeInfo(Mutex<Option<PcWakeInfo>>);++impl CurrentWakeInfo {+ pub(crate) fn set(&self, info: PcWakeInfo) -> PcWakeInfo {+ let clean = info.sanitized();+ *self.0.lock().unwrap() = Some(clean.clone());+ clean+ }++ pub(crate) fn get(&self) -> Option<PcWakeInfo> {+ self.0.lock().unwrap().clone()+ }+}++/// Sends this PC's `pc.wake_info` to a connected phone session. When the user+/// turned `pc_actions` off for that phone, sends an empty `PcWakeInfo` so the+/// phone clears any stored wake addresses for this PC.+pub(crate) async fn send_wake_info(shared: &Arc<Shared>, session: &Session) {+ let Some(info) = shared.wake_info.get() else {+ return;+ };+ let payload = if shared.toggle_on(&session.peer, POWER_TOGGLE) { info } else { PcWakeInfo::default() };+ if let Ok(env) = Envelope::new(types::PC_WAKE_INFO, &payload) {+ let _ = session.send(env).await;+ }+}++/// Sends Wake-on-LAN magic packets (`6 × 0xFF` + 16 × MAC) over UDP to the+/// stored subnet broadcasts and `255.255.255.255` on `ports`, repeated `bursts`+/// times separated by `interval`.+pub(crate) async fn wake(+ shared: &Arc<Shared>,+ peer: &DeviceId,+ ports: &[u16],+ extra_targets: &[Ipv4Addr],+ bursts: usize,+ interval: Duration,+) -> Result<()> {+ let record = shared.store.get_peer(peer)?.ok_or(Error::NotPaired)?;+ let Some(info) = record.wake_info.filter(|w| !w.macs.is_empty()) else {+ return Err(Error::Unsupported);+ };+ let packets: Vec<[u8; wake::MAGIC_PACKET_BYTES]> =+ info.macs.iter().filter_map(|m| parse_mac(m)).map(|m| magic_packet(&m)).collect();+ if packets.is_empty() {+ return Err(Error::Unsupported);+ }++ let mut targets: Vec<Ipv4Addr> = Vec::new();+ for b in &info.broadcasts {+ if let Ok(ip) = b.parse::<Ipv4Addr>()+ && !targets.contains(&ip)+ {+ targets.push(ip);+ }+ }+ if !targets.contains(&Ipv4Addr::BROADCAST) {+ targets.push(Ipv4Addr::BROADCAST);+ }+ for &ip in extra_targets {+ if !targets.contains(&ip) {+ targets.push(ip);+ }+ }++ let sock = tokio::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))+ .await+ .map_err(|e| Error::Internal(format!("can't bind Wake-on-LAN UDP socket: {e}")))?;+ let _ = sock.set_broadcast(true);++ shared.nudge_reconnect();+ let bursts = bursts.max(1);+ for burst in 0..bursts {+ if burst > 0 {+ tokio::time::sleep(interval).await;+ }+ for pkt in &packets {+ for &ip in &targets {+ for &port in ports {+ if let Err(e) = sock.send_to(pkt, SocketAddrV4::new(ip, port)).await {+ tracing::debug!(%ip, port, error = %e, "Wake-on-LAN UDP send failed");+ }+ }+ }+ }+ }+ shared.nudge_reconnect();+ Ok(())+}+/// What a phone can ask a PC to do.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PowerAction {@@ -78,10 +177,25 @@ pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: StriOk(())}-/// Handles `pc.power` and `link.open`. Returns false for other types.+/// Handles `pc.power`, `pc.wake_info` and `link.open`. Returns false for other types.pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {let peer = session.peer;let reply = match env.t.as_str() {+ types::PC_WAKE_INFO => {+ let info: PcWakeInfo = env.body()?;+ if !info.is_valid() {+ tracing::debug!(%peer, "ignoring invalid pc.wake_info");+ return Ok(true);+ }+ let info = info.sanitized();+ let stored = (!info.macs.is_empty()).then_some(info);+ let can_wake = stored.is_some();+ if let Err(e) = shared.store.update_wake_info(&peer, stored.as_ref()) {+ tracing::warn!(%peer, error = %e, "couldn't store wake info");+ }+ shared.emit(NodeEvent::WakeInfoChanged { device: peer, can_wake });+ return Ok(true);+ }types::PC_POWER => {let PcPower { action } = env.body()?;if !shared.local_capabilities().iter().any(|c| c == POWER) {diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 9bb99c8..5398416 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -33,6 +33,9 @@ pub struct PairedDevice {/// Unix seconds.pub paired_at: i64,pub link: LinkState,+ /// Whether a stored Wake-on-LAN address (`pc.wake_info`) is available+ /// for this device.+ pub can_wake: bool,}/// A device found on the local network that could be paired with.@@ -174,4 +177,9 @@ pub enum NodeEvent {device: DeviceId,toggles: crate::PhoneToggles,},+ /// A paired PC's stored Wake-on-LAN info arrived, changed, or was cleared.+ WakeInfoChanged {+ device: DeviceId,+ can_wake: bool,+ },}diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 4dd6168..8754fc0 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -28,7 +28,7 @@ mod store;pub mod toggles;mod transfer;-pub use actions::PowerAction;+pub use actions::{PC_WAKE, PowerAction};pub use calls::CallCommand;pub use config::{NodeConfig, NoopPlatform, Platform};pub use error::{Error, Result, Side};@@ -47,22 +47,22 @@ pub use nectarlink_protocol::{messages::{Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState, Contact, ContactNumber, DeviceInfo,DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorStart,- Notification, NotificationAction, PhoneApp, PhoneToggleSet, PhoneToggleValue, PhoneToggles,- PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, SmsMessage, SmsPart, SmsThread,- TouchAction,+ Notification, NotificationAction, PcWakeInfo, PhoneApp, PhoneToggleSet, PhoneToggleValue,+ PhoneToggles, PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, SmsMessage, SmsPart,+ SmsThread, TouchAction,calls::{CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,SHOW as CALLS_SHOW, STATE as CALLS_STATE,},contacts::{READ as CONTACTS_READ, SHOW as CONTACTS_SHOW},- is_package_name,+ format_mac, ipv4_broadcast, is_package_name, magic_packet,mirror::{AUDIO as MIRROR_AUDIO, AUDIO_PLAYBACK as MIRROR_AUDIO_PLAYBACK, CAPTURE as MIRROR_CAPTURE,INPUT as MIRROR_INPUT, LISTEN as MIRROR_LISTEN, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES,PCM as MIRROR_PCM, SCREEN as MIRROR_SCREEN, VIEW as MIRROR_VIEW,VIRTUAL_DISPLAY as MIRROR_VIRTUAL_DISPLAY,},- mirror_keys,+ mirror_keys, parse_mac,photos::{MAX_GET_ITEMS as PHOTO_MAX_GET_ITEMS, MAX_PAGE as PHOTO_MAX_PAGE,MAX_THUMB_BATCH as PHOTO_MAX_THUMB_BATCH, MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES,diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 11aec24..edbcc53 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -122,6 +122,8 @@ pub(crate) struct Shared {pub(crate) calls: crate::calls::Current,/// This phone's quick settings state (docs/protocol/toggles.md).pub(crate) toggles: crate::toggles::Current,+ /// This PC's Wake-on-LAN adapter addresses (docs/protocol/actions.md).+ pub(crate) wake_info: crate::actions::CurrentWakeInfo,/// Stop signals for phone screens shown here, by phone.pub(crate) mirror_stops: Mutex<HashMap<MirrorStop, Arc<tokio::sync::Notify>>>,/// Per-peer rate limiters and prompt state for remote input.@@ -151,6 +153,12 @@ impl Shared {let _ = self.events.send(event);}+ pub(crate) fn nudge_reconnect(&self) {+ for supervisor in lock(&self.supervisors).values() {+ supervisor.wake.notify_one();+ }+ }+/// Where partly received files wait until complete.pub fn incoming_dir(&self) -> std::path::PathBuf {self.data_dir.join("incoming")@@ -279,7 +287,13 @@ impl Shared {let paired_at = crate::now_unix();self.store.upsert_peer(&peer, &info, paired_at)?;tracing::info!(peer = %peer.short(), "paired");- let device = PairedDevice { id: peer, info, paired_at, link: LinkState::Offline { last_seen: None } };+ let device = PairedDevice {+ id: peer,+ info,+ paired_at,+ link: LinkState::Offline { last_seen: None },+ can_wake: false,+ };self.emit(NodeEvent::DeviceAdded(device.clone()));self.emit(NodeEvent::Pairing(PairingEvent::Paired(device)));lock(&self.discovered).remove(&peer);@@ -369,6 +383,7 @@ impl Shared {shared.send_media_state(&s).await;shared.send_call_state(&s).await;shared.send_toggles_state(&s).await;+ crate::actions::send_wake_info(&shared, &s).await;});Some(session)}@@ -627,6 +642,7 @@ impl Node {players: Default::default(),calls: Default::default(),toggles: Default::default(),+ wake_info: Default::default(),mirror_stops: Mutex::new(HashMap::new()),remote: Mutex::new(Default::default()),data_dir: config.data_dir.clone(),@@ -733,9 +749,7 @@ impl Node {/// away instead of after their backoff. Harmless when nothing changed.pub async fn network_changed(&self) {self.shared.endpoint.network_change().await;- for supervisor in lock(&self.shared.supervisors).values() {- supervisor.wake.notify_one();- }+ self.shared.nudge_reconnect();}/// What a "refresh" button does: reconnects to devices that aren't@@ -750,6 +764,7 @@ impl Node {self.shared.send_notification_snapshot(&session).await;self.shared.send_media_state(&session).await;self.shared.send_toggles_state(&session).await;+ crate::actions::send_wake_info(&self.shared, &session).await;}}@@ -768,6 +783,7 @@ impl Node {.into_iter().map(|p| PairedDevice {link: self.shared.link(&p.id, p.last_seen),+ can_wake: p.wake_info.as_ref().is_some_and(|w| !w.macs.is_empty()),id: p.id,info: p.info,paired_at: p.paired_at,@@ -858,6 +874,14 @@ impl Node {if toggle == crate::toggles::TOGGLE {self.shared.toggles_toggled(peer, enabled);}+ if toggle == crate::actions::POWER_TOGGLE+ && let Some(session) = self.shared.session(&peer)+ {+ let shared = self.shared.clone();+ self.shared.runtime.spawn(async move {+ crate::actions::send_wake_info(&shared, &session).await;+ });+ }Ok(())}@@ -951,6 +975,49 @@ impl Node {crate::actions::pc_power(&self.shared, &session, action).await}+ /// Sets this PC's Wake-on-LAN adapter addresses (`pc.wake_info`) and sends+ /// them to every connected phone when they changed.+ pub async fn set_wake_info(&self, info: nectarlink_protocol::messages::PcWakeInfo) {+ let prev = self.shared.wake_info.get();+ let clean = self.shared.wake_info.set(info);+ if prev.as_ref() != Some(&clean) {+ for session in self.shared.live_sessions() {+ crate::actions::send_wake_info(&self.shared, &session).await;+ }+ }+ }++ /// Returns the stored Wake-on-LAN addresses for a paired PC, if any.+ pub fn wake_info(&self, peer: DeviceId) -> Result<Option<nectarlink_protocol::messages::PcWakeInfo>> {+ Ok(self.shared.store.get_peer(&peer)?.ok_or(Error::NotPaired)?.wake_info)+ }++ /// Sends Wake-on-LAN magic packets for a paired PC over UDP to its stored+ /// subnet broadcasts and `255.255.255.255` on ports 9 and 7, repeated a+ /// few times over ~2 s.+ pub async fn wake(&self, peer: DeviceId) -> Result<()> {+ crate::actions::wake(+ &self.shared,+ &peer,+ nectarlink_protocol::messages::wake::DEFAULT_PORTS,+ &[],+ 4,+ Duration::from_millis(650),+ )+ .await+ }++ /// Sends Wake-on-LAN magic packets for a paired PC on custom UDP ports and+ /// additional target IPv4 addresses (used by tests).+ pub async fn wake_on_ports(+ &self,+ peer: DeviceId,+ ports: &[u16],+ extra_targets: &[std::net::Ipv4Addr],+ ) -> Result<()> {+ crate::actions::wake(&self.shared, &peer, ports, extra_targets, 2, Duration::from_millis(40)).await+ }+/// Opens a web link on a paired device.pub async fn open_link(&self, peer: DeviceId, url: String) -> Result<()> {let session = self.connected(&peer)?;diff --git a/core/nectarlink-core/src/store.rs b/core/nectarlink-core/src/store.rsindex 20917cb..569b3e0 100644--- a/core/nectarlink-core/src/store.rs+++ b/core/nectarlink-core/src/store.rs@@ -11,7 +11,7 @@ use std::{use nectarlink_protocol::{DeviceId,- messages::{DeviceInfo, DeviceKind, PowerLevel},+ messages::{DeviceInfo, DeviceKind, PcWakeInfo, PowerLevel},};use rusqlite::{Connection, OptionalExtension, params};@@ -44,6 +44,8 @@ const MIGRATIONS: &[&str] = &[enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),PRIMARY KEY (peer, toggle)) STRICT;",+ // v3: Wake-on-LAN adapter MAC and subnet broadcast addresses per paired PC.+ "ALTER TABLE peers ADD COLUMN wake_info TEXT NOT NULL DEFAULT '';",];/// A paired device as stored on disk.@@ -57,6 +59,8 @@ pub(crate) struct PeerRecord {/// Capabilities from the device's last `hello`.pub caps: BTreeSet<String>,pub power: PowerLevel,+ /// Wake-on-LAN addresses from a paired PC's last `pc.wake_info`.+ pub wake_info: Option<PcWakeInfo>,}#[derive(Debug)]@@ -161,6 +165,18 @@ impl Store {})}+ /// Records or clears the Wake-on-LAN addresses reported by a paired PC.+ pub fn update_wake_info(&self, id: &DeviceId, info: Option<&PcWakeInfo>) -> Result<()> {+ let encoded = info.map(PcWakeInfo::to_storage_string).unwrap_or_default();+ self.with(|c| {+ c.execute(+ "UPDATE peers SET wake_info = ?2 WHERE id = ?1",+ params![id.as_bytes().as_slice(), encoded],+ )+ .map(drop)+ })+ }+/// The per-device toggles the user has set. Unset toggles are absent;/// callers apply the defaults.pub fn toggles(&self, id: &DeviceId) -> Result<HashMap<String, bool>> {@@ -209,7 +225,7 @@ impl Store {}const SELECT: &str = "SELECT id, name, kind, os, os_ver, model, accent, paired_at, last_seen, last_addrs, \- caps, power FROM peers";+ caps, power, wake_info FROM peers";fn row_to_peer(row: &rusqlite::Row<'_>) -> rusqlite::Result<PeerRecord> {let id: Vec<u8> = row.get(0)?;@@ -221,6 +237,7 @@ fn row_to_peer(row: &rusqlite::Row<'_>) -> rusqlite::Result<PeerRecord> {let addrs: String = row.get(9)?;let caps: String = row.get(10)?;let power: String = row.get(11)?;+ let wake_info: String = row.get(12)?;Ok(PeerRecord {id: DeviceId(id),info: DeviceInfo {@@ -237,6 +254,7 @@ fn row_to_peer(row: &rusqlite::Row<'_>) -> rusqlite::Result<PeerRecord> {last_addrs: addrs.split(',').filter_map(|a| a.parse().ok()).collect(),caps: caps.split(',').filter(|c| !c.is_empty()).map(str::to_owned).collect(),power: power_from_str(&power),+ wake_info: PcWakeInfo::from_storage_str(&wake_info),})}@@ -408,4 +426,24 @@ mod tests {conn.pragma_update(None, "user_version", 99).unwrap();assert!(matches!(Store::init(conn), Err(Error::Storage(_))));}++ #[test]+ fn wake_info_persists_across_reopen() {+ let dir = tempfile::tempdir().unwrap();+ let id = DeviceId([7; 32]);+ let wake =+ PcWakeInfo { macs: vec!["38:a7:46:37:2e:64".into()], broadcasts: vec!["192.168.1.255".into()] };+ {+ let store = Store::open(dir.path()).unwrap();+ store.upsert_peer(&id, &info("Studio"), 42).unwrap();+ assert_eq!(store.get_peer(&id).unwrap().unwrap().wake_info, None);+ store.update_wake_info(&id, Some(&wake)).unwrap();+ }+ {+ let store = Store::open(dir.path()).unwrap();+ assert_eq!(store.get_peer(&id).unwrap().unwrap().wake_info, Some(wake));+ store.update_wake_info(&id, None).unwrap();+ assert_eq!(store.get_peer(&id).unwrap().unwrap().wake_info, None);+ }+ }}diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex c3d37d6..928aa76 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -2457,3 +2457,93 @@ async fn phone_toggles_arrive_on_connect_change_and_respect_capabilities_and_togErr(Error::Denied)));}++#[tokio::test(flavor = "multi_thread")]+async fn wake_info_syncs_persists_respects_toggle_and_sends_magic_packet() {+ use nectarlink_core::{PC_WAKE, PcWakeInfo, magic_packet};+ use std::net::Ipv4Addr;++ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[PC_WAKE]).await;+ let mut phone = device("Pixel", DeviceKind::Phone).await;++ pc.node+ .set_wake_info(PcWakeInfo {+ macs: vec!["38:A7:46:37:2E:64".into()],+ broadcasts: vec!["192.168.1.255".into()],+ })+ .await;++ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ // Initial wake info arrives on connect and is stored on the phone.+ wait_for(&mut phone, "initial wake info", |e| match e {+ NodeEvent::WakeInfoChanged { device, can_wake: true } if *device == pc_id => Some(()),+ _ => None,+ })+ .await;+ assert_eq!(+ phone.node.wake_info(pc_id).unwrap(),+ Some(PcWakeInfo { macs: vec!["38:a7:46:37:2e:64".into()], broadcasts: vec!["192.168.1.255".into()] })+ );+ assert!(phone.node.paired_devices().unwrap().iter().any(|d| d.id == pc_id && d.can_wake));++ // Adapter change on the PC updates connected phones immediately.+ pc.node+ .set_wake_info(PcWakeInfo {+ macs: vec!["38:A7:46:37:2E:64".into(), "aa-bb-cc-dd-ee-ff".into()],+ broadcasts: vec!["192.168.1.255".into(), "10.0.0.255".into()],+ })+ .await;+ let phone_node = phone.node.clone();+ wait_for(&mut phone, "updated wake info", |e| match e {+ NodeEvent::WakeInfoChanged { device, can_wake: true }+ if *device == pc_id+ && phone_node+ .wake_info(pc_id)+ .ok()+ .flatten()+ .is_some_and(|w| w.macs.len() == 2 && w.broadcasts.len() == 2) =>+ {+ Some(())+ }+ _ => None,+ })+ .await;++ // Turning `pc_actions` off on the PC clears the phone's stored wake info; turning it back on restores it.+ pc.node.set_device_toggle(phone_id, "pc_actions", false).unwrap();+ wait_for(&mut phone, "wake info cleared", |e| match e {+ NodeEvent::WakeInfoChanged { device, can_wake: false } if *device == pc_id => Some(()),+ _ => None,+ })+ .await;+ assert_eq!(phone.node.wake_info(pc_id).unwrap(), None);+ assert!(matches!(phone.node.wake(pc_id).await, Err(Error::Unsupported)));++ pc.node.set_device_toggle(phone_id, "pc_actions", true).unwrap();+ wait_for(&mut phone, "wake info restored", |e| match e {+ NodeEvent::WakeInfoChanged { device, can_wake: true } if *device == pc_id => Some(()),+ _ => None,+ })+ .await;++ // The PC goes offline and the phone restarts: stored wake info survives across restarts.+ pc.node.shutdown().await;+ phone.node.shutdown().await;+ let TestDevice { node, dir, .. } = phone;+ drop(node);+ let phone = start_in(dir, "Pixel", DeviceKind::Phone).await;+ assert!(phone.node.paired_devices().unwrap().iter().any(|d| d.id == pc_id && d.can_wake));++ // Waking the offline PC sends the 102-byte magic packet over UDP.+ let listener = tokio::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ phone.node.wake_on_ports(pc_id, &[port], &[Ipv4Addr::LOCALHOST]).await.unwrap();++ let mut buf = [0u8; 256];+ let (n, _) = with_timeout("receive magic packet", listener.recv_from(&mut buf)).await.unwrap();+ assert_eq!(n, 102);+ assert_eq!(&buf[..102], &magic_packet(&[0x38, 0xA7, 0x46, 0x37, 0x2E, 0x64])[..]);+ phone.node.shutdown().await;+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 0b081d9..1d183b6 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -82,6 +82,8 @@ pub struct PairedDevice {/// Unix seconds.pub paired_at: i64,pub link: Link,+ /// Whether this phone has stored Wake-on-LAN addresses for this PC.+ pub can_wake: bool,}#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]@@ -479,6 +481,11 @@ pub enum Event {id: String,toggles: PhoneToggles,},+ /// A paired PC's stored Wake-on-LAN addresses changed (phones only).+ WakeInfoChanged {+ id: String,+ can_wake: bool,+ },}/// This phone's quick settings state (docs/protocol/toggles.md).@@ -1085,6 +1092,7 @@ impl From<core::PairedDevice> for PairedDevice {info: d.info.into(),paired_at: d.paired_at,link: d.link.into(),+ can_wake: d.can_wake,}}}@@ -1313,6 +1321,9 @@ impl From<NodeEvent> for Event {NodeEvent::PhoneToggles { device, toggles } => {Event::PhoneToggles { id: device.to_string(), toggles: toggles.into() }}+ NodeEvent::WakeInfoChanged { device, can_wake } => {+ Event::WakeInfoChanged { id: device.to_string(), can_wake }+ }}}}@@ -2030,6 +2041,15 @@ impl NectarlinkNode {self.run(async move { Ok(node.pc_power(id, action).await?) }).await}+ /// Sends Wake-on-LAN magic packets for a paired PC over UDP to its stored+ /// subnet broadcasts and `255.255.255.255` on ports 9 and 7, repeated a+ /// few times over ~2 s.+ pub async fn wake(&self, id: String) -> Result<()> {+ let id = parse_id(&id)?;+ let node = self.node.clone();+ self.run(async move { Ok(node.wake(id).await?) }).await+ }+/// Opens a web link on a paired PC.pub async fn open_link(&self, id: String, url: String) -> Result<()> {let id = parse_id(&id)?;diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex bf49164..a15663c 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -39,6 +39,7 @@ pub mod types {pub const MEDIA_SYNC: &str = "media.sync";pub const MEDIA_COMMAND: &str = "media.command";pub const PC_POWER: &str = "pc.power";+ pub const PC_WAKE_INFO: &str = "pc.wake_info";pub const LINK_OPEN: &str = "link.open";pub const PHOTOS_NEW: &str = "photos.new";pub const PHOTOS_ALBUMS: &str = "photos.albums";@@ -485,6 +486,175 @@ pub struct PcPower {/// The longest link sent, in bytes.pub const LINK_MAX_BYTES: usize = 4096;+/// Constants and limits for Wake-on-LAN (`docs/protocol/actions.md` §2.3).+pub mod wake {+ /// Offered by PCs that share their adapter addresses (`pc.wake_info`).+ pub const CAP: &str = "pc.wake";+ /// Maximum hardware addresses in a `pc.wake_info` message.+ pub const MAX_ADAPTERS: usize = 8;+ /// Maximum directed subnet broadcast addresses in a `pc.wake_info` message.+ pub const MAX_BROADCASTS: usize = 16;+ /// Size of a standard Wake-on-LAN magic packet (`6 + 16 * 6`).+ pub const MAGIC_PACKET_BYTES: usize = 102;+ /// Standard UDP ports for Wake-on-LAN magic packets.+ pub const DEFAULT_PORTS: &[u16] = &[9, 7];+}++/// Parses a 6-byte hardware (MAC) address written as `"aa:bb:cc:dd:ee:ff"` or+/// `"AA-BB-CC-DD-EE-FF"`. Rejects all-zero (`00:00:00:00:00:00`) and broadcast+/// (`ff:ff:ff:ff:ff:ff`) addresses.+pub fn parse_mac(s: &str) -> Option<[u8; 6]> {+ let s = s.trim();+ let sep = if s.contains(':') { ':' } else { '-' };+ let mut bytes = [0u8; 6];+ let mut parts = s.split(sep);+ for slot in &mut bytes {+ let part = parts.next()?;+ if part.len() != 2 || !part.bytes().all(|b| b.is_ascii_hexdigit()) {+ return None;+ }+ *slot = u8::from_str_radix(part, 16).ok()?;+ }+ if parts.next().is_some() || bytes == [0; 6] || bytes == [0xff; 6] {+ return None;+ }+ Some(bytes)+}++/// Formats a 6-byte hardware (MAC) address as lowercase `"aa:bb:cc:dd:ee:ff"`.+pub fn format_mac(mac: &[u8; 6]) -> String {+ format!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])+}++/// Builds the standard 102-byte Wake-on-LAN magic packet: 6 bytes of `0xFF`+/// followed by `mac` repeated 16 times.+pub fn magic_packet(mac: &[u8; 6]) -> [u8; wake::MAGIC_PACKET_BYTES] {+ let mut pkt = [0xffu8; wake::MAGIC_PACKET_BYTES];+ for i in 0..16 {+ let start = 6 + i * 6;+ pkt[start..start + 6].copy_from_slice(mac);+ }+ pkt+}++/// Computes the directed IPv4 subnet broadcast address (`ip | !mask`) from an+/// adapter's IPv4 address and on-link prefix length (`1..=30`). Rejects+/// unspecified, loopback, link-local (`169.254.0.0/16`), multicast and+/// broadcast addresses.+pub fn ipv4_broadcast(ip: std::net::Ipv4Addr, prefix_len: u8) -> Option<std::net::Ipv4Addr> {+ if !(1..=30).contains(&prefix_len)+ || ip.is_unspecified()+ || ip.is_loopback()+ || ip.is_link_local()+ || ip.is_multicast()+ || ip.is_broadcast()+ {+ return None;+ }+ let mask = u32::MAX << (32 - u32::from(prefix_len));+ let bcast = std::net::Ipv4Addr::from(u32::from(ip) | !mask);+ (!bcast.is_unspecified() && !bcast.is_loopback() && !bcast.is_multicast()).then_some(bcast)+}++fn parse_wake_broadcast(s: &str) -> Option<std::net::Ipv4Addr> {+ let ip: std::net::Ipv4Addr = s.trim().parse().ok()?;+ if ip.is_unspecified() || ip.is_loopback() || ip.is_link_local() || ip.is_multicast() {+ return None;+ }+ Some(ip)+}++/// Body of `pc.wake_info` (`docs/protocol/actions.md` §2.3): the PC's+/// wake-capable adapter MAC addresses and directed subnet broadcast addresses.+#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PcWakeInfo {+ /// Hardware addresses (`"aa:bb:cc:dd:ee:ff"`), preferred adapter first.+ /// Empty when the user turned `pc_actions` off for this phone.+ #[serde(default)]+ pub macs: Vec<String>,+ /// Directed IPv4 subnet broadcast addresses (e.g. `"192.168.1.255"`).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub broadcasts: Vec<String>,+}++/// Never prints hardware or IP addresses in logs (protocol v0 §11).+impl std::fmt::Debug for PcWakeInfo {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PcWakeInfo")+ .field("macs", &self.macs.len())+ .field("broadcasts", &self.broadcasts.len())+ .finish()+ }+}++impl PcWakeInfo {+ pub fn is_valid(&self) -> bool {+ self.macs.len() <= wake::MAX_ADAPTERS+ && self.broadcasts.len() <= wake::MAX_BROADCASTS+ && self.macs.iter().all(|m| parse_mac(m).is_some())+ && self.broadcasts.iter().all(|b| parse_wake_broadcast(b).is_some())+ }++ /// Normalizes MAC addresses to lowercase `"aa:bb:cc:dd:ee:ff"`, filters out+ /// invalid entries, deduplicates preserving order, and enforces protocol+ /// bounds.+ pub fn sanitized(self) -> Self {+ let mut macs = Vec::new();+ for m in self.macs {+ if let Some(bytes) = parse_mac(&m) {+ let norm = format_mac(&bytes);+ if !macs.contains(&norm) {+ macs.push(norm);+ if macs.len() >= wake::MAX_ADAPTERS {+ break;+ }+ }+ }+ }+ if macs.is_empty() {+ return Self::default();+ }+ let mut broadcasts = Vec::new();+ for b in self.broadcasts {+ if let Some(ip) = parse_wake_broadcast(&b) {+ let norm = ip.to_string();+ if !broadcasts.contains(&norm) {+ broadcasts.push(norm);+ if broadcasts.len() >= wake::MAX_BROADCASTS {+ break;+ }+ }+ }+ }+ Self { macs, broadcasts }+ }++ /// Encodes as `"mac1,mac2|bcast1,bcast2"` for the `peers.wake_info` column.+ pub fn to_storage_string(&self) -> String {+ let clean = self.clone().sanitized();+ if clean.macs.is_empty() {+ String::new()+ } else {+ format!("{}|{}", clean.macs.join(","), clean.broadcasts.join(","))+ }+ }++ /// Decodes from the `peers.wake_info` column (`None` when empty or invalid).+ pub fn from_storage_str(s: &str) -> Option<Self> {+ let s = s.trim();+ if s.is_empty() {+ return None;+ }+ let (macs_part, bcasts_part) = s.split_once('|').unwrap_or((s, ""));+ let info = Self {+ macs: macs_part.split(',').filter(|p| !p.is_empty()).map(str::to_owned).collect(),+ broadcasts: bcasts_part.split(',').filter(|p| !p.is_empty()).map(str::to_owned).collect(),+ }+ .sanitized();+ (!info.macs.is_empty()).then_some(info)+ }+}+// ---- Screen mirroring (docs/protocol/mirror.md) ----pub mod mirror {@@ -2526,4 +2696,87 @@ mod tests {);assert!(!PhoneToggleSet { id: "airplane".into(), value: PhoneToggleValue::Bool(true) }.is_valid());}++ #[test]+ fn magic_packet_has_sync_header_and_sixteen_mac_copies() {+ let mac = parse_mac("38-A7-46-37-2E-64").unwrap();+ assert_eq!(mac, [0x38, 0xa7, 0x46, 0x37, 0x2e, 0x64]);+ assert_eq!(format_mac(&mac), "38:a7:46:37:2e:64");+ let pkt = magic_packet(&mac);+ assert_eq!(pkt.len(), 102);+ assert_eq!(&pkt[..6], &[0xff; 6]);+ for i in 0..16 {+ assert_eq!(&pkt[6 + i * 6..12 + i * 6], &mac);+ }+ }++ #[test]+ fn ipv4_broadcast_from_ip_and_prefix() {+ use std::net::Ipv4Addr;+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(192, 168, 1, 42), 24), Some(Ipv4Addr::new(192, 168, 1, 255)));+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(10, 0, 12, 5), 16), Some(Ipv4Addr::new(10, 0, 255, 255)));+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(172, 16, 5, 10), 20), Some(Ipv4Addr::new(172, 16, 15, 255)));+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(192, 168, 10, 1), 30), Some(Ipv4Addr::new(192, 168, 10, 3)));+ // Invalid prefix lengths or non-routable LAN addresses.+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(192, 168, 1, 42), 0), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(192, 168, 1, 42), 31), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(192, 168, 1, 42), 32), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::UNSPECIFIED, 24), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::LOCALHOST, 8), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(169, 254, 10, 20), 16), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::new(224, 0, 0, 1), 24), None);+ assert_eq!(ipv4_broadcast(Ipv4Addr::BROADCAST, 24), None);+ }++ #[test]+ fn wake_info_validates_sanitizes_and_round_trips() {+ let info = PcWakeInfo {+ macs: vec!["38:a7:46:37:2e:64".into(), "24:b2:b9:c6:a4:81".into()],+ broadcasts: vec!["192.168.1.255".into()],+ };+ assert!(info.is_valid());+ let debug = format!("{info:?}");+ assert!(!debug.contains("38:a7") && !debug.contains("192.168"), "{debug}");++ let env = Envelope::new(types::PC_WAKE_INFO, &info).unwrap();+ let back: PcWakeInfo = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back, info);++ let stored = info.to_storage_string();+ assert_eq!(PcWakeInfo::from_storage_str(&stored), Some(info.clone()));+ assert_eq!(PcWakeInfo::from_storage_str(""), None);++ // Empty wake_info (sent when pc_actions is turned off) is valid on the wire.+ let empty = PcWakeInfo::default();+ assert!(empty.is_valid());+ assert_eq!(empty.to_storage_string(), "");++ // Invalid MACs and broadcast addresses are rejected by is_valid and stripped by sanitized.+ for bad_mac in [+ "",+ "00:00:00:00:00:00",+ "ff:ff:ff:ff:ff:ff",+ "FF-FF-FF-FF-FF-FF",+ "38:a7:46:37:2e",+ "38:a7:46:37:2e:64:00",+ "38:a7:46:37:2e:zz",+ ] {+ assert!(!PcWakeInfo { macs: vec![bad_mac.into()], broadcasts: vec![] }.is_valid(), "{bad_mac}");+ }+ for bad_ip in ["", "0.0.0.0", "127.0.0.1", "169.254.1.255", "224.0.0.251", "not-an-ip"] {+ assert!(+ !PcWakeInfo { macs: vec!["38:a7:46:37:2e:64".into()], broadcasts: vec![bad_ip.into()] }+ .is_valid(),+ "{bad_ip}"+ );+ }++ let messy = PcWakeInfo {+ macs: vec!["38-A7-46-37-2E-64".into(), "38:a7:46:37:2e:64".into(), "00:00:00:00:00:00".into()],+ broadcasts: vec!["192.168.1.255".into(), "192.168.1.255".into(), "127.0.0.1".into()],+ }+ .sanitized();+ assert_eq!(messy.macs, vec!["38:a7:46:37:2e:64"]);+ assert_eq!(messy.broadcasts, vec!["192.168.1.255"]);+ }}diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 35c2fdb..b687158 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -29,7 +29,7 @@ Item {media: qsTr("Media playing on either device"),photos: qsTr("Photos"),toggles: qsTr("Phone controls"),- pc_actions: qsTr("Lock and sleep this PC"),+ pc_actions: qsTr("Lock, sleep and wake this PC"),remote_input: qsTr("Control this PC's mouse and keyboard"),remote_files: qsTr("Browse this PC's files while away")})@@ -280,6 +280,38 @@ Item {}}+ // ---- This PC ----+ Txt { text: qsTr("This PC"); role: "label"; muted: true }+ Card {+ width: parent.width+ ListRow {+ width: parent.width+ iconPath: Icons.power+ title: qsTr("Wake from your phone")+ description: {+ const adapter = AppController.wakeAdapter+ const state = AppController.wakeState+ const wired = AppController.wakeWired+ if (state === "none" || adapter.length === 0)+ return qsTr("No active Ethernet or Wi-Fi adapter found. Connect this PC to your network so your phone can learn how to wake it.")+ if (state === "enabled") {+ return wired+ ? qsTr("%1 · Wake on Magic Packet is on. If this PC still won't wake from sleep or shutdown, check that Wake-on-LAN is enabled in BIOS/UEFI.").arg(adapter)+ : qsTr("%1 · Wake on Magic Packet is on. Wi-Fi wake usually works from sleep, not full shutdown; use Ethernet for shutdown wake.").arg(adapter)+ }+ const wifiNote = wired ? "" : qsTr(" Wi-Fi wake rarely works from shutdown.")+ return qsTr("%1 · To wake this PC while it sleeps or is shut down, enable Wake on Magic Packet in Device Manager → Network adapters → %1 → Properties (Advanced tab → Wake on Magic Packet → Enabled; Power Management tab → Allow this device to wake the computer, Only allow a magic packet), and enable Wake-on-LAN in BIOS/UEFI.%2").arg(adapter).arg(wifiNote)+ }+ Chip {+ selected: AppController.wakeState === "enabled"+ text: AppController.wakeState === "enabled" ? qsTr("Ready")+ : AppController.wakeState === "disabled" ? qsTr("Off in Windows")+ : AppController.wakeState === "unknown" ? qsTr("Check settings")+ : qsTr("No adapter")+ }+ }+ }+// ---- 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 d8e00b8..1ffc587 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -82,6 +82,12 @@ pub mod qobject {#[qproperty(bool, laser_active)]#[qproperty(f32, laser_x)]#[qproperty(f32, laser_y)]+ /// Primary physical adapter used for Wake-on-LAN ("" when none).+ #[qproperty(QString, wake_adapter)]+ /// `"enabled"`, `"disabled"`, `"unknown"`, or `"none"`.+ #[qproperty(QString, wake_state)]+ /// True when `wake_adapter` is wired Ethernet, false for Wi-Fi or none.+ #[qproperty(bool, wake_wired)]type AppController = super::AppControllerRust;/// Asks a paired device to ring (or stop).@@ -196,6 +202,9 @@ pub struct AppControllerRust {laser_active: bool,laser_x: f32,laser_y: f32,+ wake_adapter: QString,+ wake_state: QString,+ wake_wired: bool,tray: Option<tray::Tray>,}@@ -401,35 +410,53 @@ fn ring_device(device: DeviceId, on: bool) {impl qobject::AppController {fn refresh(mut self: Pin<&mut Self>) {let hub = &core_host::host().hub;- let (status, devices, ringing, online, caps_version, toggles_version, battery, remote_prompt, laser) =- hub.read(|s| {- let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();- let remote_prompt = s.remote_prompt.map(|id| {- let name = s.name_of(&id).unwrap_or_else(|| id.short());- (id.to_string(), name)- });- let connected: Vec<_> =- s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).collect();- // With one phone connected, the tray shows its battery.- let battery = match connected.as_slice() {- [one] => one.battery.as_ref().map(|b| {- let charging = if b.charging { ", charging" } else { "" };- format!("{} · {}%{charging}", one.info.name, b.level)- }),- _ => None,- };- (- s.core_status(),- s.devices.len(),- ringing,- connected.len(),- s.matrices_version,- s.toggles_version,- battery,- remote_prompt,- s.laser,- )+ let (+ status,+ devices,+ ringing,+ online,+ caps_version,+ toggles_version,+ battery,+ remote_prompt,+ laser,+ wake_adapter,+ wake_state,+ wake_wired,+ ) = hub.read(|s| {+ let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();+ let remote_prompt = s.remote_prompt.map(|id| {+ let name = s.name_of(&id).unwrap_or_else(|| id.short());+ (id.to_string(), name)});+ let connected: Vec<_> =+ s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).collect();+ // With one phone connected, the tray shows its battery.+ let battery = match connected.as_slice() {+ [one] => one.battery.as_ref().map(|b| {+ let charging = if b.charging { ", charging" } else { "" };+ format!("{} · {}%{charging}", one.info.name, b.level)+ }),+ _ => None,+ };+ let wake_adapter = s.wake.primary().map(|a| a.label.clone()).unwrap_or_default();+ let wake_state = s.wake.state_str();+ let wake_wired = s.wake.primary().is_some_and(|a| a.wired);+ (+ s.core_status(),+ s.devices.len(),+ ringing,+ connected.len(),+ s.matrices_version,+ s.toggles_version,+ battery,+ remote_prompt,+ s.laser,+ wake_adapter,+ wake_state,+ wake_wired,+ )+ });let (status_text, error) = match &status {CoreStatus::Starting => ("starting", String::new()),CoreStatus::Ready { device_id, name } => {@@ -456,6 +483,9 @@ impl qobject::AppController {self.as_mut().set_laser_active(false);}}+ self.as_mut().set_wake_adapter(QString::from(&wake_adapter));+ self.as_mut().set_wake_state(QString::from(wake_state));+ self.as_mut().set_wake_wired(wake_wired);// Truncation is fine: QML only compares revisions for equality.self.as_mut().set_caps_revision(caps_version as i32);self.as_mut().set_phone_toggles_revision(toggles_version as i32);@@ -489,6 +519,7 @@ impl qobject::AppController {pub fn refresh_toasts_enabled(self: Pin<&mut Self>) {self.set_toasts_enabled(win::toast::enabled());+ core_host::spawn(core_host::refresh_wake());}pub fn ring(self: Pin<&mut Self>, device: &QString, on: bool) {diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 4bfa0e4..1f9d7ec 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -92,12 +92,14 @@ pub fn start(data_dir: PathBuf, platform: Arc<dyn Platform>) -> std::io::Result<async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {let host = host();+ let wake = crate::win::wol::query_wake_status();let mut config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));config.downloads_dir = Some(downloads_dir());// This PC's own players, for phones (crate::win::media_sessions).config.capabilities = vec!["media.control".into(),"pc.power".into(),+ nectarlink_core::PC_WAKE.into(),nectarlink_core::PHOTOS_SHOW.into(),nectarlink_core::CALLS_SHOW.into(),nectarlink_core::CONTACTS_SHOW.into(),@@ -120,6 +122,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {return;}};+ node.set_wake_info(wake.info.clone()).await;// Subscribe before reading the initial state so no event is missed.let mut events = node.events();let devices = node.paired_devices().unwrap_or_else(|e| {@@ -146,6 +149,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {changes |= s.set_toggles(id, Some(t));}s.status = Some(status);+ s.wake = wake;changes |= Changes::STATUS | Changes::CAPABILITIES;changes});@@ -210,6 +214,17 @@ fn this_device() -> DeviceInfo {}}+/// Re-reads physical network adapters and their Wake-on-LAN settings, updates+/// the UI state, and sends updated `pc.wake_info` to connected phones if changed.+pub async fn refresh_wake() {+ let wake = crate::win::wol::query_wake_status();+ let info = wake.info.clone();+ host().hub.update(|s| s.set_wake(wake));+ if let Some(node) = node() {+ node.set_wake_info(info).await;+ }+}+/// Stops the node (telling connected devices) and the runtime.pub fn shutdown() {let Some(host) = HOST.get() else { return };diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex d7843d7..f822f82 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -164,6 +164,7 @@ fn watch_network() {core_host::spawn(async {tokio::time::sleep(Duration::from_secs(1)).await;PENDING.store(false, Ordering::Release);+ core_host::refresh_wake().await;if let Some(node) = core_host::node() {tracing::debug!("network changed");node.network_changed().await;diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex 7af993b..461a4a8 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -250,6 +250,8 @@ pub struct AppState {pub remote_prompt: Option<DeviceId>,/// Active laser pointer overlay (`(device, x, y)` in `0.0..=1.0`).pub laser: Option<(DeviceId, f32, f32)>,+ /// This PC's physical adapters and Wake-on-LAN readiness.+ pub wake: crate::win::wol::WakeStatus,}impl AppState {@@ -432,7 +434,8 @@ impl AppState {| NodeEvent::CallLogChanged { .. }| NodeEvent::ContactsChanged { .. }| NodeEvent::SmsChanged { .. }- | NodeEvent::Mirroring { .. } => Changes::NONE,+ | NodeEvent::Mirroring { .. }+ | NodeEvent::WakeInfoChanged { .. } => Changes::NONE,// The gallery's own downloads (for its viewer, or the clipboard)// aren't files the user keeps.NodeEvent::Transfer(transfer) if crate::photos::is_private(&transfer.id) => {@@ -678,6 +681,14 @@ impl AppState {self.pairing = next;Changes::PAIRING}++ pub fn set_wake(&mut self, next: crate::win::wol::WakeStatus) -> Changes {+ if self.wake == next {+ return Changes::NONE;+ }+ self.wake = next;+ Changes::STATUS+ }}/// A Qt object interested in some parts of the state. `notify` schedules a@@ -759,6 +770,7 @@ mod tests {},paired_at: at,link: LinkState::Offline { last_seen: None },+ can_wake: false,}}diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rsindex dfe5b34..57c540b 100644--- a/desktop/app/src/win/mod.rs+++ b/desktop/app/src/win/mod.rs@@ -24,6 +24,7 @@ pub mod sound;pub mod toast;pub mod tray;pub mod wallpaper;+pub mod wol;use windows::{Win32::{diff --git a/desktop/app/src/win/wol.rs b/desktop/app/src/win/wol.rsnew file mode 100644index 0000000..a4591ac--- /dev/null+++ b/desktop/app/src/win/wol.rs@@ -0,0 +1,385 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! Reads this PC's physical Ethernet and Wi-Fi adapters with+//! `GetAdaptersAddresses` and checks (read-only) whether Wake on Magic Packet+//! is enabled in the network adapter class registry. Never modifies any+//! adapter or power settings.++use std::net::Ipv4Addr;++use nectarlink_core::{PcWakeInfo, format_mac, ipv4_broadcast, parse_mac};+use windows::{+ Win32::{+ Foundation::ERROR_SUCCESS,+ NetworkManagement::IpHelper::{+ GAA_FLAG_SKIP_ANYCAST, GAA_FLAG_SKIP_MULTICAST, GetAdaptersAddresses, IP_ADAPTER_ADDRESSES_LH,+ },+ Networking::WinSock::AF_UNSPEC,+ System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegGetValueW},+ },+ core::HSTRING,+};++const IF_TYPE_ETHERNET_CSMACD: u32 = 6;+const IF_TYPE_IEEE80211: u32 = 71;++const NET_CLASS_KEY: &str = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}";++/// NCF_VIRTUAL = 0x1, NCF_PHYSICAL = 0x4.+const NCF_VIRTUAL: u32 = 0x01;+const NCF_PHYSICAL: u32 = 0x04;+/// In `PnPCapabilities`, bit 0x10 means "Allow this device to wake the computer" is unchecked.+const PNP_DISABLE_WAKE: u32 = 0x10;++/// Whether Wake on Magic Packet is enabled on a physical adapter.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum WakeSupport {+ Enabled,+ Disabled,+ Unknown,+}++impl WakeSupport {+ pub fn as_str(self) -> &'static str {+ match self {+ WakeSupport::Enabled => "enabled",+ WakeSupport::Disabled => "disabled",+ WakeSupport::Unknown => "unknown",+ }+ }+}++/// One physical Ethernet or Wi-Fi adapter that is currently up.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct WakeAdapter {+ /// Friendly name + description, e.g. `"Ethernet (Realtek PCIe GbE Family Controller)"`.+ pub label: String,+ /// True for wired Ethernet (`IfType == 6`), false for Wi-Fi (`IfType == 71`).+ pub wired: bool,+ /// Normalized MAC (`"aa:bb:cc:dd:ee:ff"`).+ pub mac: String,+ /// Directed IPv4 subnet broadcast addresses on this adapter.+ pub broadcasts: Vec<String>,+ /// Whether Magic Packet wake is enabled according to the registry.+ pub support: WakeSupport,+}++/// Summary of this PC's Wake-on-LAN readiness and the `pc.wake_info` payload+/// to send to paired phones.+#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub struct WakeStatus {+ pub info: PcWakeInfo,+ pub adapters: Vec<WakeAdapter>,+}++impl WakeStatus {+ /// The preferred adapter (wired Ethernet first), if any.+ pub fn primary(&self) -> Option<&WakeAdapter> {+ self.adapters.first()+ }++ /// `"enabled"`, `"disabled"`, `"unknown"`, or `"none"`.+ pub fn state_str(&self) -> &'static str {+ match self.primary() {+ Some(a) => a.support.as_str(),+ None => "none",+ }+ }+}++#[derive(Debug, Default)]+struct RegAdapterInfo {+ net_cfg_id: String,+ characteristics: Option<u32>,+ device_instance_id: Option<String>,+ wake_on_magic_packet: Option<bool>,+ pnp_wake_allowed: Option<bool>,+}++impl RegAdapterInfo {+ fn is_physical_hardware(&self) -> bool {+ if let Some(chars) = self.characteristics+ && ((chars & NCF_VIRTUAL) != 0 || (chars & NCF_PHYSICAL) == 0)+ {+ return false;+ }+ if let Some(inst) = &self.device_instance_id {+ let upper = inst.to_ascii_uppercase();+ if upper.starts_with("ROOT\\") || upper.starts_with("SWD\\") || upper.starts_with("UMB\\") {+ return false;+ }+ }+ true+ }++ fn wake_support(&self) -> WakeSupport {+ if self.pnp_wake_allowed == Some(false) || self.wake_on_magic_packet == Some(false) {+ return WakeSupport::Disabled;+ }+ if self.wake_on_magic_packet == Some(true) {+ return WakeSupport::Enabled;+ }+ WakeSupport::Unknown+ }+}++fn reg_dword(subkey: &str, value: &str) -> Option<u32> {+ let mut data = 0u32;+ let mut size = std::mem::size_of::<u32>() as u32;+ // SAFETY: data/size describe a live u32 buffer.+ let status = unsafe {+ RegGetValueW(+ HKEY_LOCAL_MACHINE,+ &HSTRING::from(subkey),+ &HSTRING::from(value),+ RRF_RT_REG_DWORD,+ None,+ Some(std::ptr::from_mut(&mut data).cast()),+ Some(&mut size),+ )+ };+ (status == ERROR_SUCCESS).then_some(data)+}++fn reg_string(subkey: &str, value: &str) -> Option<String> {+ let mut buf = [0u16; 256];+ let mut size = std::mem::size_of_val(&buf) as u32;+ // SAFETY: buf/size describe a live UTF-16 buffer.+ let status = unsafe {+ RegGetValueW(+ HKEY_LOCAL_MACHINE,+ &HSTRING::from(subkey),+ &HSTRING::from(value),+ RRF_RT_REG_SZ,+ None,+ Some(buf.as_mut_ptr().cast()),+ Some(&mut size),+ )+ };+ if status != ERROR_SUCCESS {+ return None;+ }+ let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());+ Some(String::from_utf16_lossy(&buf[..len]))+}++fn reg_bool_flag(subkey: &str, value: &str) -> Option<bool> {+ if let Some(s) = reg_string(subkey, value) {+ return match s.trim().to_ascii_lowercase().as_str() {+ "1" | "enabled" | "true" => Some(true),+ "0" | "disabled" | "false" => Some(false),+ _ => None,+ };+ }+ reg_dword(subkey, value).map(|v| v != 0)+}++fn read_registry_adapters() -> Vec<RegAdapterInfo> {+ let mut out = Vec::new();+ for idx in 0..100 {+ let subkey = format!(r"{NET_CLASS_KEY}\{idx:04}");+ let Some(net_cfg_id) = reg_string(&subkey, "NetCfgInstanceId") else {+ continue;+ };+ let characteristics = reg_dword(&subkey, "Characteristics");+ let device_instance_id = reg_string(&subkey, "DeviceInstanceID");+ let wake_on_magic_packet = reg_bool_flag(&subkey, "*WakeOnMagicPacket")+ .or_else(|| reg_bool_flag(&subkey, "WakeOnMagicPacket"));+ let pnp_wake_allowed = reg_dword(&subkey, "PnPCapabilities").map(|pnp| (pnp & PNP_DISABLE_WAKE) == 0);+ out.push(RegAdapterInfo {+ net_cfg_id,+ characteristics,+ device_instance_id,+ wake_on_magic_packet,+ pnp_wake_allowed,+ });+ }+ out+}++fn looks_virtual_name(friendly: &str, description: &str) -> bool {+ let f = friendly.to_ascii_lowercase();+ let d = description.to_ascii_lowercase();+ const VIRTUAL_WORDS: &[&str] = &[+ "virtual",+ "vethernet",+ "hyper-v",+ "wsl",+ "vmware",+ "virtualbox",+ "vbox",+ "loopback",+ "tap-",+ "tap-windows",+ "tuntap",+ "wintun",+ "vpn",+ "wireguard",+ "openvpn",+ "tailscale",+ "zerotier",+ "bluetooth",+ "wan miniport",+ "ndis",+ "teredo",+ "isatap",+ "docker",+ "npcap",+ "wi-fi direct",+ "hosted network",+ ];+ VIRTUAL_WORDS.iter().any(|w| f.contains(w) || d.contains(w))+}++/// Reads physical, up Ethernet and Wi-Fi adapters and their Wake-on-LAN status.+pub fn query_wake_status() -> WakeStatus {+ let reg_entries = read_registry_adapters();+ let mut size: u32 = 32 * 1024;+ let mut buffer = vec![0u8; size as usize];+ let mut adapters: Vec<WakeAdapter> = Vec::new();++ // SAFETY: `buffer` is sized as `GetAdaptersAddresses` requests and walked+ // via its `Next` and `FirstUnicastAddress` pointers while alive.+ 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 WakeStatus::default();+ }++ let mut ptr = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();+ while let Some(a) = ptr.as_ref() {+ ptr = a.Next;++ // Only operational (Up) Ethernet or Wi-Fi adapters with a 6-byte MAC.+ if a.OperStatus.0 != 1 {+ continue;+ }+ let wired = match a.IfType {+ IF_TYPE_ETHERNET_CSMACD => true,+ IF_TYPE_IEEE80211 => false,+ _ => continue,+ };+ if a.PhysicalAddressLength != 6 {+ continue;+ }+ let mut raw_mac = [0u8; 6];+ raw_mac.copy_from_slice(&a.PhysicalAddress[..6]);+ let mac = format_mac(&raw_mac);+ if parse_mac(&mac).is_none() {+ continue;+ }++ let guid = a.AdapterName.to_string().unwrap_or_default();+ let friendly = a.FriendlyName.to_string().unwrap_or_default();+ let description = a.Description.to_string().unwrap_or_default();+ if looks_virtual_name(&friendly, &description) {+ continue;+ }++ let reg = reg_entries.iter().find(|r| r.net_cfg_id.eq_ignore_ascii_case(&guid));+ if let Some(reg) = reg+ && !reg.is_physical_hardware()+ {+ continue;+ }+ let support = reg.map_or(WakeSupport::Unknown, RegAdapterInfo::wake_support);++ let mut broadcasts = Vec::new();+ let mut unicast = a.FirstUnicastAddress;+ while let Some(u) = unicast.as_ref() {+ unicast = u.Next;+ let addr = u.Address.lpSockaddr;+ if !addr.is_null() && (*addr).sa_family.0 == 2 {+ let bytes = &(*addr).sa_data;+ let ip = Ipv4Addr::new(bytes[2] as u8, bytes[3] as u8, bytes[4] as u8, bytes[5] as u8);+ if let Some(bcast) = ipv4_broadcast(ip, u.OnLinkPrefixLength) {+ let s = bcast.to_string();+ if !broadcasts.contains(&s) {+ broadcasts.push(s);+ }+ }+ }+ }++ let label = match (friendly.trim(), description.trim()) {+ ("", d) => d.to_owned(),+ (f, "") => f.to_owned(),+ (f, d) if f.eq_ignore_ascii_case(d) => f.to_owned(),+ (f, d) => format!("{f} ({d})"),+ };++ adapters.push(WakeAdapter { label, wired, mac, broadcasts, support });+ }+ }++ // Prefer wired Ethernet over Wi-Fi, then adapters with an IPv4 broadcast,+ // then adapters where Wake on Magic Packet is enabled.+ adapters.sort_by_key(|a| {+ (+ !a.wired,+ a.broadcasts.is_empty(),+ match a.support {+ WakeSupport::Enabled => 0u8,+ WakeSupport::Unknown => 1,+ WakeSupport::Disabled => 2,+ },+ )+ });++ let mut macs = Vec::new();+ let mut broadcasts = Vec::new();+ for a in &adapters {+ if !macs.contains(&a.mac) {+ macs.push(a.mac.clone());+ }+ for b in &a.broadcasts {+ if !broadcasts.contains(b) {+ broadcasts.push(b.clone());+ }+ }+ }+ let info = PcWakeInfo { macs, broadcasts }.sanitized();++ WakeStatus { info, adapters }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn filters_virtual_adapter_names() {+ assert!(looks_virtual_name("vEthernet (WSL (Hyper-V firewall))", "Hyper-V Virtual Ethernet Adapter"));+ assert!(looks_virtual_name("Tailscale", "Tailscale Tunnel"));+ assert!(looks_virtual_name("Ethernet 2", "VMware Virtual Ethernet Adapter for VMnet1"));+ assert!(!looks_virtual_name("Ethernet", "Realtek PCIe GbE Family Controller"));+ assert!(!looks_virtual_name("Wi-Fi", "Intel(R) Wi-Fi 6E AX211 160MHz"));+ }++ #[test]+ fn queries_wake_status_without_admin() {+ let status = query_wake_status();+ assert!(status.info.is_valid());+ for a in &status.adapters {+ assert!(parse_mac(&a.mac).is_some());+ assert!(!a.label.is_empty());+ }+ }+}diff --git a/docs/PLAN.md b/docs/PLAN.mdindex 5d6c21f..8f2d98e 100644--- a/docs/PLAN.md+++ b/docs/PLAN.md@@ -207,7 +207,7 @@ current Android. Talking through the PC comes with the HFP item above.| **Flow**: move the PC mouse off the screen edge onto the phone/tablet and back, with clipboard following | P2 🟣 || Phone toggles from PC: Wi-Fi, BT, DND, ringer, flashlight, volume, brightness ✅ (the hotspot has no shell command to switch it; see Instant Hotspot) | P1 (partly 🟣) || PC actions from phone: lock, sleep, shutdown, mute, custom commands/scripts | P0 (lock/sleep), P1 (custom, off by default) |-| Wake-on-LAN | P1 |+| Wake-on-LAN ✅ | P1 || **Unlock PC with phone fingerprint**: the PC lock screen offers "Unlock with phone" → the phone shows a biometric prompt → a signed challenge unlocks Windows. Built as a Windows credential provider. Keys live in Android Keystore (StrongBox where available) and are bound to biometrics. Works only when paired and nearby (BLE proximity + LAN). Rate-limited, revocable, and **external security review before release** | P2 (dedicated workstream) |### 3.11 Ambient & signature experiences (what makes Nectarlink special)diff --git a/docs/protocol/actions.md b/docs/protocol/actions.mdindex 49863e9..ead4c66 100644--- a/docs/protocol/actions.md+++ b/docs/protocol/actions.md@@ -3,14 +3,16 @@> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are> allowed until v1. License: CC BY 4.0.-One-shot requests from one paired device to another: a phone locks its PC-or puts it to sleep, and either device opens a web link on the other.+One-shot requests from one paired device to another: a phone locks its PC,+puts it to sleep, or wakes it over the local network with Wake-on-LAN, and+either device opens a web link on the other.## 1. Capabilities| ID | Offered by | Meaning ||---|---|---|| `pc.power` | PC | Locks or sleeps when a paired phone asks |+| `pc.wake` | PC | Shares its network adapter MAC and subnet broadcast addresses (`pc.wake_info`) so a paired phone can wake it || `link.open` | both | Opens web links a paired device sends |Senders check the other device's capabilities first and don't send a@@ -18,12 +20,14 @@ request it doesn't offer.## 2. Messages-All on the control stream, each answered with `ok` or `error`.+All on the control stream. `pc.power` and `link.open` are requests answered+with `ok` or `error`; `pc.wake_info` is a one-way event (no `id`, no reply).```-t = "pc.power" id = n b = { action: "lock" | "sleep" }-t = "link.open" id = n b = { url: text }-t = "ok" re = n+t = "pc.power" id = n b = { action: "lock" | "sleep" }+t = "link.open" id = n b = { url: text }+t = "ok" re = n+t = "pc.wake_info" b = { macs: [text, ...], broadcasts?: [text, ...] }```### 2.1 `pc.power`@@ -51,6 +55,34 @@ notification the user taps to open it, since Android doesn't let apps inthe background open screens. `INTERNAL` means it couldn't be opened orshown.+### 2.3 `pc.wake_info` (Wake-on-LAN)++Sent by a PC to a paired phone on session startup and whenever the PC's+network adapters or IPv4 addresses change:++- `macs`: up to 8 6-byte hardware addresses of the PC's physical Ethernet+ and Wi-Fi adapters that are currently up, formatted as lowercase+ `"aa:bb:cc:dd:ee:ff"`, with wired Ethernet listed first. All-zero+ (`00:00:00:00:00:00`) and broadcast (`ff:ff:ff:ff:ff:ff`) addresses are+ invalid.+- `broadcasts` *(optional)*: up to 16 directed IPv4 subnet broadcast+ addresses (e.g. `"192.168.1.255"`) computed from those adapters' current+ IPv4 addresses and prefix lengths (`ip | !mask` for prefix lengths+ `1..=30`).++When the user turns the `pc_actions` device toggle off for a phone, the PC+sends `pc.wake_info` with an empty `macs` list so the phone clears any+stored wake info for that PC.++The phone persists the latest `pc.wake_info` per PC in its store so it+survives restarts. To wake an offline PC, the phone sends the standard+102-byte Wake-on-LAN magic packet (`6 × 0xFF` followed by the 6-byte MAC+repeated 16 times) over UDP to ports `9` and `7`, addressed to each stored+subnet broadcast address and `255.255.255.255`, repeated a few times over+~2 seconds.+## 3. Rules-- Implementations **MUST NOT** log links (v0 §11).+- Implementations **MUST NOT** log links or hardware/IP addresses in+ `pc.wake_info` debug output (v0 §11).+diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex ddfd437..e27eaf9 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -66,6 +66,7 @@ capability is missing.| ID | Meaning | Unlocked by ||---|---|---|| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update |+| `pc.wake` | Shares network adapter addresses (`pc.wake_info`) so a paired phone can wake it with Wake-on-LAN ([actions](actions.md)) | app update || `photos.show` | Shows a phone's new photos and gallery ([photos](photos.md)) | app update || `call.show` | Shows a phone's calls, recent calls and dialer ([calls](calls.md)) | app update || `contacts.show` | Shows a phone's contacts ([contacts](contacts.md)) | app update |