Files
os/crates/sf-remote/src/wake.rs
2026-10-25 14:11:49 +01:00

203 lines
7.5 KiB
Rust

//! Waking the machine from suspend with the remote.
//!
//! Two things have to be in place:
//! 1. The Bluetooth controller may wake the system: `power/wakeup = enabled`
//! on its USB device and the ports above it.
//! 2. The kernel keeps scanning for the remote while suspended. It does that
//! for devices on its connect list that carry the "remote wakeup" flag.
//! BlueZ sets both only through its HID plugins, which Fennec OS disables
//! (they drop the Siri Remote's reports), so we send the two management
//! commands ourselves: Add Device (auto-connect) and Set Device Flags.
//!
//! The remote advertises with a rotating private address. Without controller
//! side address resolution (kernel "LL privacy") the kernel can't filter for
//! it while suspended and accepts every advert, so other Bluetooth devices
//! nearby may wake the machine too; the launcher puts it back to sleep then.
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::path::Path;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
/// The remote as the kernel knows it.
#[derive(Debug, Clone, Copy)]
pub struct Target {
/// Controller index (hci0 -> 0).
pub index: u16,
/// Address as printed ("10:B9:..." -> [0x10, 0xB9, ...]).
pub addr: [u8; 6],
/// true: LE public identity address, false: LE random (static).
pub public: bool,
}
/// Enables wakeup on every Bluetooth controller's device and its parents
/// (USB device, hub, xHCI). Returns how many files were switched on.
pub fn enable_controller_wakeup() -> usize {
let mut changed = 0;
let Ok(entries) = std::fs::read_dir("/sys/class/bluetooth") else { return 0 };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if !name.starts_with("hci") || name.contains(':') {
continue;
}
let Ok(dev) = std::fs::canonicalize(e.path().join("device")) else { continue };
for dir in dev.ancestors().take_while(|d| d.starts_with("/sys/devices")) {
changed += enable(&dir.join("power/wakeup")) as usize;
}
}
changed
}
fn enable(file: &Path) -> bool {
match std::fs::read_to_string(file) {
Ok(v) if v.trim() == "disabled" => match std::fs::write(file, "enabled") {
Ok(()) => {
log::info!("wake: enabled {}", file.display());
true
}
Err(e) => {
log::warn!("wake: {}: {e}", file.display());
false
}
},
_ => false,
}
}
// ---- kernel Bluetooth management interface ---------------------------------------
const AF_BLUETOOTH: libc::c_int = 31;
const BTPROTO_HCI: libc::c_int = 1;
const HCI_CHANNEL_CONTROL: u16 = 3;
const HCI_DEV_NONE: u16 = 0xffff;
const MGMT_OP_ADD_DEVICE: u16 = 0x0033;
const MGMT_OP_SET_DEVICE_FLAGS: u16 = 0x0050;
const MGMT_EV_CMD_COMPLETE: u16 = 0x0001;
const MGMT_EV_CMD_STATUS: u16 = 0x0002;
const ADDR_LE_PUBLIC: u8 = 1;
const ADDR_LE_RANDOM: u8 = 2;
/// Add Device action: connect automatically whenever it advertises.
const ACTION_AUTO_CONNECT: u8 = 2;
const DEVICE_FLAG_REMOTE_WAKEUP: u32 = 1;
#[repr(C)]
struct SockaddrHci {
family: libc::sa_family_t,
dev: u16,
channel: u16,
}
struct Mgmt(OwnedFd);
impl Mgmt {
fn open() -> Result<Self> {
// SAFETY: plain socket/bind calls; the fd is owned right away.
unsafe {
let fd = libc::socket(AF_BLUETOOTH, libc::SOCK_RAW | libc::SOCK_CLOEXEC, BTPROTO_HCI);
if fd < 0 {
bail!("mgmt socket: {}", std::io::Error::last_os_error());
}
let fd = OwnedFd::from_raw_fd(fd);
let addr = SockaddrHci { family: AF_BLUETOOTH as _, dev: HCI_DEV_NONE, channel: HCI_CHANNEL_CONTROL };
let len = std::mem::size_of::<SockaddrHci>() as libc::socklen_t;
if libc::bind(fd.as_raw_fd(), &addr as *const _ as *const libc::sockaddr, len) < 0 {
bail!("mgmt bind: {}", std::io::Error::last_os_error());
}
Ok(Mgmt(fd))
}
}
/// Sends a command and waits for its completion; Err on a non-zero status.
fn call(&self, op: u16, index: u16, params: &[u8]) -> Result<()> {
let mut msg = Vec::with_capacity(6 + params.len());
msg.extend_from_slice(&op.to_le_bytes());
msg.extend_from_slice(&index.to_le_bytes());
msg.extend_from_slice(&(params.len() as u16).to_le_bytes());
msg.extend_from_slice(params);
// SAFETY: writing an initialised buffer to our own socket.
let n = unsafe { libc::write(self.0.as_raw_fd(), msg.as_ptr().cast(), msg.len()) };
if n != msg.len() as isize {
bail!("mgmt write: {}", std::io::Error::last_os_error());
}
let deadline = Instant::now() + Duration::from_secs(2);
let mut buf = [0u8; 512];
loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
bail!("mgmt {op:#06x}: no reply");
}
let mut pfd = libc::pollfd { fd: self.0.as_raw_fd(), events: libc::POLLIN, revents: 0 };
// SAFETY: one valid pollfd.
if unsafe { libc::poll(&mut pfd, 1, left.as_millis() as libc::c_int) } <= 0 {
continue;
}
// SAFETY: reading into our own buffer.
let n = unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
if n < 9 {
continue;
}
let ev = u16::from_le_bytes([buf[0], buf[1]]);
let ev_index = u16::from_le_bytes([buf[2], buf[3]]);
let opcode = u16::from_le_bytes([buf[6], buf[7]]);
let status = buf[8];
if (ev == MGMT_EV_CMD_COMPLETE || ev == MGMT_EV_CMD_STATUS) && opcode == op && ev_index == index {
if status != 0 {
bail!("mgmt {op:#06x}: status {status:#04x}{}", status_name(status));
}
return Ok(());
}
}
}
}
fn status_name(status: u8) -> &'static str {
match status {
0x01 => " (unknown command: kernel too old)",
0x0b => " (rejected)",
0x0c => " (not supported)",
0x0d => " (invalid parameters)",
0x11 => " (invalid index)",
_ => "",
}
}
/// mgmt_addr_info: address in little-endian byte order plus its type.
fn addr_info(t: &Target) -> [u8; 7] {
let mut out = [0u8; 7];
for (i, b) in t.addr.iter().rev().enumerate() {
out[i] = *b;
}
out[6] = if t.public { ADDR_LE_PUBLIC } else { ADDR_LE_RANDOM };
out
}
/// Lets the remote wake the machine: on the kernel's connect list, flagged
/// for remote wakeup. Safe to repeat.
pub fn allow_remote_wakeup(t: &Target) -> Result<()> {
let mgmt = Mgmt::open().context("Bluetooth management socket (needs root)")?;
let addr = addr_info(t);
let mut add = addr.to_vec();
add.push(ACTION_AUTO_CONNECT);
mgmt.call(MGMT_OP_ADD_DEVICE, t.index, &add).context("Add Device")?;
let mut flags = addr.to_vec();
flags.extend_from_slice(&DEVICE_FLAG_REMOTE_WAKEUP.to_le_bytes());
mgmt.call(MGMT_OP_SET_DEVICE_FLAGS, t.index, &flags).context("Set Device Flags (remote wakeup)")?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn address_is_little_endian() {
let t = Target { index: 0, addr: [0x10, 0xB9, 0xC4, 0x17, 0xC0, 0x0F], public: true };
assert_eq!(addr_info(&t), [0x0F, 0xC0, 0x17, 0xC4, 0xB9, 0x10, ADDR_LE_PUBLIC]);
}
}