From 57a8357dd713558b10cb349974b391df291bdeb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20M=C3=A4user?= Date: Thu, 5 Nov 2026 14:15:31 +0100 Subject: [PATCH] first commit --- .gitignore | 1 + Cargo.lock | 1083 ++++++++++++++++++++++++++++++++ Cargo.toml | 22 + config.toml.example | 38 ++ src/config.rs | 158 +++++ src/locker.rs | 81 +++ src/main.rs | 79 +++ src/policy.rs | 265 ++++++++ src/scanner/bluez.rs | 318 ++++++++++ src/scanner/mod.rs | 3 + systemd/btle-proximity.service | 14 + 11 files changed, 2062 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 config.toml.example create mode 100644 src/config.rs create mode 100644 src/locker.rs create mode 100644 src/main.rs create mode 100644 src/policy.rs create mode 100644 src/scanner/bluez.rs create mode 100644 src/scanner/mod.rs create mode 100644 systemd/btle-proximity.service diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..b25d58f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1083 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "btle-proximity" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "sd-notify", + "serde", + "tokio", + "tokio-stream", + "toml", + "tracing", + "tracing-subscriber", + "zbus", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.18+spec-1.1.0", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "sd-notify" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b943eadf71d8b69e661330cb0e2656e31040acf21ee7708e2c238a0ec6af2bf4" +dependencies = [ + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "tracing", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.18+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" +dependencies = [ + "indexmap", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tokio", + "tracing", + "uds_windows", + "uuid", + "windows-sys", + "winnow 1.0.5", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.5", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.5", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.5", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9292dd1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "btle-proximity" +version = "0.1.0" +edition = "2021" +description = "BLE proximity screen locker: locks the desktop session when your phone leaves Bluetooth range" +license = "MIT" + +[dependencies] +anyhow = "1" +clap = { version = "4", features = ["derive"] } +sd-notify = "0.4" +serde = { version = "1", features = ["derive"] } +tokio = { version = "1", features = ["macros", "process", "rt-multi-thread", "signal", "time"] } +tokio-stream = "0.1" +toml = "0.8" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +zbus = { version = "5", default-features = false, features = ["tokio"] } + +[profile.release] +lto = true +strip = true diff --git a/config.toml.example b/config.toml.example new file mode 100644 index 0000000..825dff2 --- /dev/null +++ b/config.toml.example @@ -0,0 +1,38 @@ +# MAC address of the paired phone to watch. +# Run `btle-proximity list-paired` to see candidates. +device_mac = "AA:BB:CC:DD:EE:FF" + +# Bluetooth adapter to use, e.g. "hci0". First available if unset. +#adapter = "hci0" + +# Lock the session after this long without strong evidence of presence. +missing_after_secs = 30 + +# Advertisement updates newer than this count as "recently seen". +presence_timeout_secs = 15 + +# Discovery only reports devices at or above this RSSI (dBm). +rssi_floor = -90 + +# At or below this RSSI the device counts as out of range (dBm). +rssi_lock = -80 + +# Scan duty cycle per state: radio on for window_ms, then rest until +# interval_ms has elapsed. window_ms/interval_ms is the radio duty cycle. +[duty.present] +window_ms = 100 # ~2% radio duty while the phone is around +interval_ms = 5000 + +[duty.suspect] +window_ms = 200 # aggressive probing while confirming absence +interval_ms = 1000 + +[duty.locked] +window_ms = 100 # rarely polling for the phone's return +interval_ms = 30000 + +# Optional: command to run instead of `loginctl lock-session`. +#lock_command = "swaylock -f" + +# Optional: log lock actions instead of executing them (for testing). +#dry_run = false diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..cd3a299 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,158 @@ +use anyhow::{ensure, Context, Result}; +use serde::Deserialize; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +fn presence_timeout_secs() -> u64 { + 15 +} +fn missing_after_secs() -> u64 { + 30 +} +fn rssi_floor() -> i16 { + -90 +} +fn rssi_lock() -> i16 { + -80 +} + +fn present_duty() -> Duty { + Duty { + window_ms: 100, + interval_ms: 5000, + } +} +fn suspect_duty() -> Duty { + Duty { + window_ms: 200, + interval_ms: 1000, + } +} +fn locked_duty() -> Duty { + Duty { + window_ms: 100, + interval_ms: 30_000, + } +} + +/// One scan duty cycle: radio on for `window_ms`, then rest until `interval_ms`. +#[derive(Debug, Clone, Copy, Deserialize)] +pub struct Duty { + pub window_ms: u64, + pub interval_ms: u64, +} + +#[derive(Debug, Clone, Copy, Deserialize)] +pub struct DutyConfig { + #[serde(default = "present_duty")] + pub present: Duty, + #[serde(default = "suspect_duty")] + pub suspect: Duty, + #[serde(default = "locked_duty")] + pub locked: Duty, +} + +impl Default for DutyConfig { + fn default() -> Self { + DutyConfig { + present: present_duty(), + suspect: suspect_duty(), + locked: locked_duty(), + } + } +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Config { + /// Identity MAC address of the paired phone to watch. + pub device_mac: String, + /// Bluetooth adapter to use, e.g. "hci0". First available if unset. + #[serde(default)] + pub adapter: Option, + /// Command to run instead of `loginctl lock-session`. + #[serde(default)] + pub lock_command: Option, + /// Advertisement updates newer than this count as "recently seen". + #[serde(default = "presence_timeout_secs")] + pub presence_timeout_secs: u64, + /// Lock the session after this long without strong evidence of presence. + #[serde(default = "missing_after_secs")] + pub missing_after_secs: u64, + /// Discovery filter: only devices at or above this RSSI are reported (dBm). + #[serde(default = "rssi_floor")] + pub rssi_floor: i16, + /// At or below this RSSI the device counts as out of range (dBm). + #[serde(default = "rssi_lock")] + pub rssi_lock: i16, + #[serde(default)] + pub duty: DutyConfig, + /// Log lock actions instead of executing them. + #[serde(default)] + pub dry_run: bool, +} + +impl Config { + pub fn load(path: &Path) -> Result { + let raw = std::fs::read_to_string(path) + .with_context(|| format!("reading config file {}", path.display()))?; + let cfg: Config = toml::from_str(&raw) + .with_context(|| format!("parsing config file {}", path.display()))?; + cfg.validate()?; + Ok(cfg) + } + + pub fn validate(&self) -> Result<()> { + ensure!( + self.normalized_mac().len() == 12, + "device_mac must be a MAC address (got {:?})", + self.device_mac + ); + ensure!( + self.missing_after_secs > self.presence_timeout_secs, + "missing_after_secs must be greater than presence_timeout_secs" + ); + ensure!( + self.rssi_lock > self.rssi_floor, + "rssi_lock must be greater than rssi_floor" + ); + for (name, d) in [ + ("present", &self.duty.present), + ("suspect", &self.duty.suspect), + ("locked", &self.duty.locked), + ] { + ensure!(d.window_ms > 0, "{name}.window_ms must be > 0"); + ensure!( + d.interval_ms >= d.window_ms, + "{name}.interval_ms must be >= {name}.window_ms" + ); + } + Ok(()) + } + + pub fn normalized_mac(&self) -> String { + normalize_mac(&self.device_mac) + } + + pub fn presence_timeout(&self) -> Duration { + Duration::from_secs(self.presence_timeout_secs) + } + + pub fn missing_after(&self) -> Duration { + Duration::from_secs(self.missing_after_secs) + } +} + +/// Uppercase hex digits only, separators removed: "aa:bb:cc" -> "AABBCC". +pub fn normalize_mac(s: &str) -> String { + s.chars() + .filter(|c| c.is_ascii_hexdigit()) + .map(|c| c.to_ascii_uppercase()) + .collect() +} + +pub fn default_path() -> Option { + let base = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?; + Some(base.join("btle-proximity").join("config.toml")) +} diff --git a/src/locker.rs b/src/locker.rs new file mode 100644 index 0000000..da9926e --- /dev/null +++ b/src/locker.rs @@ -0,0 +1,81 @@ +use anyhow::{bail, Context, Result}; +use tracing::{info, warn}; + +/// Lock the desktop session. Tries, in order: +/// 1. `lock_command` from config, if set +/// 2. `loginctl lock-session` (logind notifies the session's screen locker) +/// 3. org.freedesktop.login1.Manager.Lock over the system bus +pub async fn lock_screen(lock_command: Option<&str>, dry_run: bool) -> Result<()> { + if dry_run { + info!("dry-run: would lock the screen now"); + return Ok(()); + } + if let Some(cmd) = lock_command { + return run_shell(cmd).await; + } + match loginctl_lock().await { + Ok(()) => { + info!("screen locked via loginctl lock-session"); + Ok(()) + } + Err(e) => { + warn!("loginctl failed ({e:#}), falling back to logind D-Bus"); + logind_dbus_lock().await + } + } +} + +async fn run_shell(cmd: &str) -> Result<()> { + let out = tokio::process::Command::new("sh") + .arg("-c") + .arg(cmd) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .output() + .await + .with_context(|| format!("spawning lock command {cmd:?}"))?; + if out.status.success() { + info!(command = cmd, "screen locked"); + Ok(()) + } else { + bail!( + "lock command {cmd:?} failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + ) + } +} + +async fn loginctl_lock() -> Result<()> { + let out = tokio::process::Command::new("loginctl") + .arg("lock-session") + .output() + .await + .context("spawning loginctl")?; + if out.status.success() { + Ok(()) + } else { + bail!( + "loginctl lock-session failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + ) + } +} + +async fn logind_dbus_lock() -> Result<()> { + let conn = zbus::Connection::system() + .await + .context("connecting to the system D-Bus")?; + let proxy = zbus::Proxy::new( + &conn, + "org.freedesktop.login1", + "/org/freedesktop/login1", + "org.freedesktop.login1.Manager", + ) + .await?; + proxy + .call::<_, _, ()>("Lock", &()) + .await + .context("calling org.freedesktop.login1.Manager.Lock")?; + info!("screen locked via logind D-Bus"); + Ok(()) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..b1b83a9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,79 @@ +mod config; +mod locker; +mod policy; +mod scanner; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command( + name = "btle-proximity", + version, + about = "Locks the desktop session when your phone leaves Bluetooth range" +)] +struct Cli { + /// Path to the TOML config file + #[arg(long, short, value_name = "FILE")] + config: Option, + /// Log lock actions instead of executing them + #[arg(long)] + dry_run: bool, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Run the daemon (default) + Run, + /// List paired Bluetooth devices and exit + ListPaired, +} + +#[tokio::main] +async fn main() -> Result<()> { + let cli = Cli::parse(); + + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); + + match cli.command.as_ref().unwrap_or(&Command::Run) { + Command::ListPaired => { + for dev in scanner::list_paired().await? { + println!( + "{} {:20} {}", + dev.address, + dev.alias, + if dev.connected { "connected" } else { "" } + ); + } + Ok(()) + } + Command::Run => run(cli).await, + } +} + +async fn run(cli: Cli) -> Result<()> { + let path = cli.config.or_else(config::default_path).context( + "no config file found: pass --config or install one at \ + $XDG_CONFIG_HOME/btle-proximity/config.toml", + )?; + let mut cfg = config::Config::load(&path)?; + if cli.dry_run { + cfg.dry_run = true; + } + scanner::run(cfg).await +} + +pub fn notify_ready() { + let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Ready]); +} + +pub fn notify_stopping() { + let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Stopping]); +} diff --git a/src/policy.rs b/src/policy.rs new file mode 100644 index 0000000..5eda261 --- /dev/null +++ b/src/policy.rs @@ -0,0 +1,265 @@ +use crate::config::{Duty, DutyConfig}; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + /// Started, waiting for the first sighting of the target device. + Bootstrapping, + /// Fresh, strong evidence that the device is nearby. + Present, + /// No fresh strong evidence; probing aggressively. + Suspect, + /// Screen has been locked; waiting for the device to return. + Locked, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Action { + Lock, +} + +pub struct Policy { + presence_timeout: Duration, + missing_after: Duration, + rssi_lock: i16, + state: State, + last_event: Option, + last_rssi: Option, + connected: bool, + weak_since: Option, +} + +impl Policy { + pub fn new(presence_timeout: Duration, missing_after: Duration, rssi_lock: i16) -> Self { + Policy { + presence_timeout, + missing_after, + rssi_lock, + state: State::Bootstrapping, + last_event: None, + last_rssi: None, + connected: false, + weak_since: None, + } + } + + pub fn state(&self) -> State { + self.state + } + + pub fn last_rssi(&self) -> Option { + self.last_rssi + } + + /// Feed an observed update about the target device (advertisement + /// property change, connect/disconnect, ...). + pub fn note_event(&mut self, now: Instant, rssi: Option, connected: Option) { + if let Some(c) = connected { + self.connected = c; + } + if let Some(r) = rssi { + self.last_rssi = Some(r); + } + self.last_event = Some(now); + } + + /// The screen was locked successfully. + pub fn mark_locked(&mut self) { + if self.state == State::Suspect { + self.state = State::Locked; + } + } + + /// Evaluate the state machine. Returns Some(Action::Lock) for as long as + /// the screen should be locked; call mark_locked() once it succeeded. + pub fn on_tick(&mut self, now: Instant) -> Option { + let fresh = self + .last_event + .is_some_and(|t| now.duration_since(t) <= self.presence_timeout); + let strong = self.last_rssi.is_some_and(|r| r > self.rssi_lock); + + if self.state == State::Bootstrapping { + // Arming: never lock before the target was seen at least once, + // so the daemon can start with the phone already away. + if fresh { + self.state = State::Present; + } + return None; + } + + let present = self.connected || (fresh && strong); + if present { + self.state = State::Present; + self.weak_since = None; + return None; + } + + if self.state == State::Present { + self.state = State::Suspect; + } + if self.state != State::Suspect { + return None; + } + + // Word from the device stopped arriving entirely. + let stale = self + .last_event + .is_none_or(|t| now.duration_since(t) >= self.missing_after); + if stale { + return Some(Action::Lock); + } + + // Word still arriving, but the signal is too weak to trust. + if !strong { + let since = *self.weak_since.get_or_insert(now); + if now.duration_since(since) >= self.missing_after { + return Some(Action::Lock); + } + } else { + self.weak_since = None; + } + None + } + + pub fn duty(&self, cfg: &DutyConfig) -> Duty { + match self.state { + State::Bootstrapping | State::Suspect => cfg.suspect, + State::Present => cfg.present, + State::Locked => cfg.locked, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn policy() -> Policy { + Policy::new(Duration::from_secs(15), Duration::from_secs(30), -80) + } + + fn t(secs: u64) -> Instant { + Instant::now() + Duration::from_secs(secs) + } + + #[test] + fn never_locks_before_first_sighting() { + let mut p = policy(); + for s in 0..300 { + assert_eq!(p.on_tick(t(s)), None); + } + assert_eq!(p.state(), State::Bootstrapping); + } + + #[test] + fn arms_on_first_sighting() { + let mut p = policy(); + p.note_event(t(10), Some(-50), None); + p.on_tick(t(11)); + assert_eq!(p.state(), State::Present); + } + + #[test] + fn stays_present_while_events_fresh_and_strong() { + let mut p = policy(); + p.note_event(t(0), Some(-50), None); + for s in 1..=60 { + p.note_event(t(s), Some(-52), None); + assert_eq!(p.on_tick(t(s)), None, "locked at {s}s"); + assert_eq!(p.state(), State::Present); + } + } + + #[test] + fn locks_after_signal_goes_stale() { + let mut p = policy(); + p.note_event(t(0), Some(-50), None); + assert_eq!(p.on_tick(t(1)), None); + assert_eq!(p.state(), State::Present); + // Last event at t=0: presence expires at 15s, lock at 30s. + assert_eq!(p.on_tick(t(20)), None); + assert_eq!(p.state(), State::Suspect); + assert_eq!(p.on_tick(t(29)), None); + assert_eq!(p.on_tick(t(30)), Some(Action::Lock)); + p.mark_locked(); + assert_eq!(p.state(), State::Locked); + assert_eq!(p.on_tick(t(300)), None); + assert_eq!(p.state(), State::Locked); + } + + #[test] + fn lock_is_retried_until_confirmed() { + let mut p = policy(); + p.note_event(t(0), Some(-50), None); + p.on_tick(t(1)); // armed by the first sighting + assert_eq!(p.on_tick(t(30)), Some(Action::Lock)); + assert_eq!(p.state(), State::Suspect); + assert_eq!(p.on_tick(t(31)), Some(Action::Lock)); + p.mark_locked(); + assert_eq!(p.on_tick(t(32)), None); + } + + #[test] + fn weak_signal_locks_only_after_missing_after() { + let mut p = policy(); + p.note_event(t(0), Some(-50), None); + p.on_tick(t(1)); // armed + for s in 2..31 { + p.note_event(t(s), Some(-90), None); + assert_eq!(p.on_tick(t(s)), None, "locked at {s}s"); + assert_eq!(p.state(), State::Suspect); + } + // Weak continuously since t=2 -> locks at t=32. + p.note_event(t(31), Some(-90), None); + assert_eq!(p.on_tick(t(31)), None); + p.note_event(t(32), Some(-90), None); + assert_eq!(p.on_tick(t(32)), Some(Action::Lock)); + } + + #[test] + fn strong_signal_recovers_from_suspect() { + let mut p = policy(); + p.note_event(t(0), Some(-50), None); + p.on_tick(t(1)); + p.note_event(t(20), Some(-95), None); + p.on_tick(t(20)); + assert_eq!(p.state(), State::Suspect); + p.note_event(t(25), Some(-55), None); + p.on_tick(t(25)); + assert_eq!(p.state(), State::Present); + // Weak/stale clocks were reset by the recovery. + p.note_event(t(40), Some(-90), None); + p.on_tick(t(40)); + assert_eq!(p.on_tick(t(50)), None); + p.note_event(t(70), Some(-90), None); + assert_eq!(p.on_tick(t(70)), Some(Action::Lock)); + } + + #[test] + fn connected_device_counts_as_present() { + let mut p = policy(); + p.note_event(t(0), None, Some(true)); + p.on_tick(t(1)); + assert_eq!(p.state(), State::Present); + assert_eq!(p.on_tick(t(400)), None); + assert_eq!(p.state(), State::Present); + p.note_event(t(401), None, Some(false)); + assert_eq!(p.on_tick(t(402)), None); + assert_eq!(p.state(), State::Suspect); + assert_eq!(p.on_tick(t(431)), Some(Action::Lock)); + } + + #[test] + fn resight_after_lock_returns_to_present_without_unlock() { + let mut p = policy(); + p.note_event(t(0), Some(-50), None); + p.on_tick(t(1)); + assert_eq!(p.on_tick(t(30)), Some(Action::Lock)); + p.mark_locked(); + assert_eq!(p.state(), State::Locked); + p.note_event(t(100), Some(-50), None); + p.on_tick(t(100)); + assert_eq!(p.state(), State::Present); + } +} diff --git a/src/scanner/bluez.rs b/src/scanner/bluez.rs new file mode 100644 index 0000000..b74c312 --- /dev/null +++ b/src/scanner/bluez.rs @@ -0,0 +1,318 @@ +use crate::config::{normalize_mac, Config}; +use crate::policy::{Action, Policy}; +use crate::{notify_ready, notify_stopping}; +use anyhow::{Context, Result}; +use std::collections::HashMap; +use std::time::{Duration, Instant}; +use tokio_stream::StreamExt; +use tracing::{debug, error, info, warn}; +use zbus::message::Type as MsgType; +use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; +use zbus::{Connection, MatchRule, Message, MessageStream, Proxy}; + +const BLUEZ: &str = "org.bluez"; +const DEVICE_IFACE: &str = "org.bluez.Device1"; +const ADAPTER_IFACE: &str = "org.bluez.Adapter1"; +const PROPS_IFACE: &str = "org.freedesktop.DBus.Properties"; +const OBJMGR_IFACE: &str = "org.freedesktop.DBus.ObjectManager"; +const OBJMGR_PATH: &str = "/"; + +type Props = HashMap; +type InterfacesAndProps = HashMap; +type ManagedObjects = HashMap; + +pub struct PairedDevice { + pub address: String, + pub alias: String, + pub connected: bool, +} + +pub async fn list_paired() -> Result> { + let conn = connect().await?; + let objects = managed_objects(&conn).await?; + let mut devices = Vec::new(); + for (path, ifaces) in objects { + let Some(props) = ifaces.get(DEVICE_IFACE) else { + continue; + }; + if !get_bool(props, "Paired").unwrap_or(false) { + continue; + } + devices.push(PairedDevice { + address: get_str(props, "Address").unwrap_or_else(|| path.as_str().to_owned()), + alias: get_str(props, "Alias").unwrap_or_default(), + connected: get_bool(props, "Connected").unwrap_or(false), + }); + } + devices.sort_by(|a, b| a.alias.cmp(&b.alias)); + Ok(devices) +} + +pub async fn run(cfg: Config) -> Result<()> { + let conn = connect().await?; + let objects = managed_objects(&conn).await?; + + let adapter_path = find_adapter(&objects, cfg.adapter.as_deref()) + .context("no usable Bluetooth adapter found")?; + let adapter = Proxy::new(&conn, BLUEZ, adapter_path.clone(), ADAPTER_IFACE).await?; + ensure_powered(&adapter).await?; + set_discovery_filter(&adapter, cfg.rssi_floor).await?; + + let target_mac = cfg.normalized_mac(); + // A device object may already exist from pairing or an earlier scan. We + // only use its path to route signal events; presence is decided from live + // events only (cached properties like RSSI go stale). + let target = find_device_path(&objects, &target_mac).map(|path| Target { path }); + if let Some(t) = &target { + debug!(path = %t.path, "target device object known to BlueZ"); + } + let mut target = target; + + info!(adapter = %adapter_path, device = %cfg.device_mac, "watching for device"); + + // PropertiesChanged from any BlueZ object (filtered to the target in + // code), plus InterfacesAdded so the target is recognized the first time + // it advertises after daemon start. + let props_rule = MatchRule::builder() + .msg_type(MsgType::Signal) + .sender(BLUEZ)? + .path_namespace(OBJMGR_PATH)? + .interface(PROPS_IFACE)? + .member("PropertiesChanged")? + .build(); + let added_rule = MatchRule::builder() + .msg_type(MsgType::Signal) + .sender(BLUEZ)? + .path(OBJMGR_PATH)? + .interface(OBJMGR_IFACE)? + .member("InterfacesAdded")? + .build(); + let mut props_stream = MessageStream::for_match_rule(props_rule, &conn, None).await?; + let mut added_stream = MessageStream::for_match_rule(added_rule, &conn, None).await?; + + let mut policy = Policy::new(cfg.presence_timeout(), cfg.missing_after(), cfg.rssi_lock); + let mut last_state = policy.state(); + let mut radio_on = false; + // Fire immediately: open the first scan window right away. + let mut next_toggle = tokio::time::Instant::now(); + + let mut tick = tokio::time::interval(Duration::from_secs(1)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; + + notify_ready(); + + loop { + tokio::select! { + _ = tokio::time::sleep_until(next_toggle) => { + if radio_on { + stop_discovery(&adapter).await; + radio_on = false; + let d = policy.duty(&cfg.duty); + let off = Duration::from_millis(d.interval_ms - d.window_ms); + next_toggle = tokio::time::Instant::now() + off; + } else { + if let Err(e) = start_discovery(&adapter).await { + warn!("StartDiscovery failed: {e:#}; re-checking adapter power"); + if let Err(e) = ensure_powered(&adapter).await { + error!("adapter is unusable: {e:#}"); + } + } + radio_on = true; + let window = Duration::from_millis(policy.duty(&cfg.duty).window_ms); + next_toggle = tokio::time::Instant::now() + window; + } + } + Some(msg) = props_stream.next() => match msg { + Ok(m) => handle_props_changed(&mut policy, &mut target, &target_mac, m), + Err(e) => warn!("D-Bus signal error: {e}"), + }, + Some(msg) = added_stream.next() => match msg { + Ok(m) => handle_interfaces_added(&mut policy, &mut target, &target_mac, m), + Err(e) => warn!("D-Bus signal error: {e}"), + }, + _ = tick.tick() => { + if let Some(Action::Lock) = policy.on_tick(Instant::now()) { + match crate::locker::lock_screen(cfg.lock_command.as_deref(), cfg.dry_run).await { + Ok(()) => { + info!("screen locked"); + policy.mark_locked(); + } + Err(e) => error!("locking the screen failed: {e:#}"), + } + } + let s = policy.state(); + if s != last_state { + info!(state = ?s, rssi = ?policy.last_rssi(), "state change"); + last_state = s; + } + } + _ = tokio::signal::ctrl_c() => break, + _ = term.recv() => break, + } + } + + stop_discovery(&adapter).await; + notify_stopping(); + info!("bye"); + Ok(()) +} + +struct Target { + path: OwnedObjectPath, +} + +/// Extract the MAC from a device object path such as +/// "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF". +fn path_mac(path: &str) -> Option { + let idx = path.rfind("dev_")?; + Some(normalize_mac(&path[idx + 4..])) +} + +fn handle_props_changed( + policy: &mut Policy, + target: &mut Option, + target_mac: &str, + msg: Message, +) { + let Ok((iface, changed, _invalidated)) = + msg.body().deserialize::<(String, Props, Vec)>() + else { + return; + }; + if iface != DEVICE_IFACE { + return; + } + let header = msg.header(); + let Some(path) = header.path() else { + return; + }; + let known = target + .as_ref() + .is_some_and(|t| t.path.as_str() == path.as_str()); + if !known { + if path_mac(path.as_str()).as_deref() != Some(target_mac) { + return; + } + *target = Some(Target { + path: path.to_owned().into(), + }); + } + let rssi = get_i16(&changed, "RSSI"); + let connected = get_bool(&changed, "Connected"); + debug!(path = %path, ?rssi, ?connected, "target update"); + policy.note_event(Instant::now(), rssi, connected); +} + +fn handle_interfaces_added( + policy: &mut Policy, + target: &mut Option, + target_mac: &str, + msg: Message, +) { + let Ok((path, ifaces)) = msg + .body() + .deserialize::<(OwnedObjectPath, InterfacesAndProps)>() + else { + return; + }; + let Some(props) = ifaces.get(DEVICE_IFACE) else { + return; + }; + if path_mac(path.as_str()).as_deref() != Some(target_mac) { + return; + } + *target = Some(Target { path: path.clone() }); + let rssi = get_i16(props, "RSSI"); + let connected = get_bool(props, "Connected"); + debug!(path = %path, ?rssi, ?connected, "target appeared"); + policy.note_event(Instant::now(), rssi, connected); +} + +async fn connect() -> Result { + Connection::system() + .await + .context("connecting to the system D-Bus (is BlueZ running?)") +} + +async fn managed_objects(conn: &Connection) -> Result { + let om = Proxy::new(conn, BLUEZ, OBJMGR_PATH, OBJMGR_IFACE).await?; + om.call("GetManagedObjects", &()) + .await + .context("calling org.bluez ObjectManager.GetManagedObjects") +} + +fn find_adapter(objects: &ManagedObjects, wanted: Option<&str>) -> Option { + let mut adapters: Vec<&OwnedObjectPath> = objects + .iter() + .filter(|(_, ifaces)| ifaces.contains_key(ADAPTER_IFACE)) + .map(|(path, _)| path) + .collect(); + if let Some(w) = wanted { + let suffix = format!("/{}", w.trim_start_matches('/')); + adapters.retain(|p| p.as_str().ends_with(&suffix)); + } + adapters.into_iter().next().cloned() +} + +fn find_device_path(objects: &ManagedObjects, target_mac: &str) -> Option { + objects + .iter() + .find(|(path, ifaces)| { + ifaces.contains_key(DEVICE_IFACE) + && path_mac(path.as_str()).as_deref() == Some(target_mac) + }) + .map(|(path, _)| path.clone()) +} + +async fn ensure_powered(adapter: &Proxy<'_>) -> Result<()> { + let powered: bool = adapter.get_property("Powered").await.unwrap_or(false); + if !powered { + info!("powering on Bluetooth adapter"); + adapter + .set_property("Powered", true) + .await + .context("failed to power on the Bluetooth adapter")?; + } + Ok(()) +} + +async fn set_discovery_filter(adapter: &Proxy<'_>, rssi_floor: i16) -> Result<()> { + let mut filter: HashMap<&str, Value<'static>> = HashMap::new(); + filter.insert("Transport", Value::from("le")); + filter.insert("DuplicateData", Value::from(true)); + filter.insert("RSSI", Value::from(rssi_floor)); + adapter + .call::<_, _, ()>("SetDiscoveryFilter", &(&filter,)) + .await + .context("setting the BLE discovery filter")?; + Ok(()) +} + +async fn start_discovery(adapter: &Proxy<'_>) -> Result<()> { + adapter + .call::<_, _, ()>("StartDiscovery", &()) + .await + .context("StartDiscovery")?; + Ok(()) +} + +async fn stop_discovery(adapter: &Proxy<'_>) { + if let Err(e) = adapter.call::<_, _, ()>("StopDiscovery", &()).await { + debug!("StopDiscovery failed: {e:#}"); + } +} + +fn get_str(props: &Props, key: &str) -> Option { + props + .get(key) + .and_then(|v| String::try_from(v.clone()).ok()) +} + +fn get_bool(props: &Props, key: &str) -> Option { + props.get(key).and_then(|v| bool::try_from(v.clone()).ok()) +} + +fn get_i16(props: &Props, key: &str) -> Option { + props.get(key).and_then(|v| i16::try_from(v.clone()).ok()) +} diff --git a/src/scanner/mod.rs b/src/scanner/mod.rs new file mode 100644 index 0000000..5f18e9d --- /dev/null +++ b/src/scanner/mod.rs @@ -0,0 +1,3 @@ +pub mod bluez; + +pub use bluez::{list_paired, run}; diff --git a/systemd/btle-proximity.service b/systemd/btle-proximity.service new file mode 100644 index 0000000..ae27527 --- /dev/null +++ b/systemd/btle-proximity.service @@ -0,0 +1,14 @@ +[Unit] +Description=BLE proximity screen locker +Wants=bluetooth.service +After=bluetooth.service +PartOf=graphical-session.target + +[Service] +Type=notify +ExecStart=%h/.cargo/bin/btle-proximity --config %h/.config/btle-proximity/config.toml +Restart=on-failure +RestartSec=5s + +[Install] +WantedBy=graphical-session.target