sector-f-linux

Sector F Linux
git clone https://git.sectorflabs.com/sector-f-linux.git
Log | Files | Refs | README | LICENSE

commit 0404951ea7dfd27ef1bbf1f2a5896063e7268116
parent afd6e9da6034530e3a9c66cc97e6f2dd8f02b07b
Author: Divan Visagie <me@divanv.com>
Date:   Sat, 28 Nov 2026 00:43:59 +0100

greeter: a Wi-Fi step at the start of the first-run setup (ADR-0019)

What the user will see: on a machine with Wi-Fi, the setup opens on "Connect to Wi-Fi, so this
computer has the network from the start." with the networks in range, one per name and the strongest
first, each marked Open or Secured with its signal. Pick one; a secured one shows a password field;
Connect joins it and goes on, and an error ("the password was not accepted") stays on the screen
with the box emptied. Skip is there for a cable or for later. On a machine with no Wi-Fi the step is
not there at all and the steps count from the clock ("Step 1 of 3" instead of "of 4").

Why first: the network is what the rest of the setup (and the first login) benefits from, and the
keyboard step that will come before it is deferred.

How:
- Backend: Network {ssid, strength, security} and wifi_available(), wifi_networks(), wifi_connect().
  The mock has four networks (a duplicate name, a hidden one and a weaker copy to tidy) and takes the
  password "sectorf". The real one talks to NetworkManager over D-Bus: finds the Wi-Fi device,
  RequestScan and GetAccessPoints for the list, AddAndActivateConnection to join (saved system-wide so
  the account made next has it too), then polls the connection's state for up to 30 s; a network that
  did not come up is deleted again so a mistyped password is not kept.
- Which networks are offered is decided from the access point's flags (ap_security): open, WPA/WPA2
  personal, WPA3 personal (SAE); WEP, a work network with its own login and opportunistic encryption
  are left out, since this screen cannot join them. A WPA2/WPA3 network is joined as WPA2.
- The password is typed into the greeter's own secret field (the same one the account and login use,
  which wipes itself), not egui's text box, so it does not linger in an undo history.
- The steps are now a list per machine rather than a constant: Step::next/previous became methods on
  the app, and the Wi-Fi step is inserted first when the hardware is there.

Tests: 43 pass (8 new): a machine with Wi-Fi starts on the step and one without does not; the networks
are one per name, strongest first; an open network joins without a password; a secured one cannot
until its password is typed, and what is typed does not reach the account form; the right password
joins and is gone from the box; a wrong one is shown and the step stays; Skip and Back pass through
the step; the access point flags are classified as listed above (own test); the network list is
tidied (own test). Clippy and fmt are clean.

Not done: the real NetworkManager calls have only been compiled, not run against a real one. That
test (a virtual radio and an access point in the VM) comes next, as its own change.

Diffstat:
Mdocs/adr/0019-the-first-run-setup-is-several-steps.md | 8++++++++
Mgreeter/src/app.rs | 348++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mgreeter/src/backend.rs | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mgreeter/src/main.rs | 2+-
Mgreeter/src/system.rs | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
5 files changed, 653 insertions(+), 35 deletions(-)

diff --git a/docs/adr/0019-the-first-run-setup-is-several-steps.md b/docs/adr/0019-the-first-run-setup-is-several-steps.md @@ -79,6 +79,14 @@ The layout that localed writes has to reach two compositors, and today neither w (`sectorf`), checked as a host name (letters, numbers and hyphens, 63 at most, case folded) before Continue is allowed; set through hostnamed's `SetStaticHostname`. After the clock, before the account. +- **The Wi-Fi step** (2026-11-28), first in the order on a machine that has Wi-Fi (NetworkManager lists + a wireless device) and left out on one that does not: the networks in range, one per name, strongest + first, asked again every few seconds; a password field (the greeter's own secret field, wiped + when sent) for a secured one; Connect saves the connection for every user through + `AddAndActivateConnection` and waits for it to be up, and takes a network that would not join back + out. WPA2, WPA3 and open networks are offered; WEP and a work network with its own login are not. + The mock and the pure parts are tested; **not yet run against a real NetworkManager.** + ## Open questions - Whether the clock should offer a guess when there is a network by then (Wi-Fi comes first). diff --git a/greeter/src/app.rs b/greeter/src/app.rs @@ -14,7 +14,7 @@ use std::time::{Duration, Instant}; use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, pos2, vec2}; use patina::skin::{self, Skin}; -use crate::backend::{Backend, LoginError, Power, User}; +use crate::backend::{Backend, LoginError, Network, Power, User}; use crate::field::{self, Field, Tone}; use crate::model::{self, SetupForm}; @@ -36,27 +36,12 @@ pub enum Screen { /// setup changes on the system is changed in the steps before it. #[derive(Clone, Copy, PartialEq, Debug)] pub enum Step { + Wifi, Clock, Name, Account, } -impl Step { - const ALL: [Step; 3] = [Step::Clock, Step::Name, Step::Account]; - - fn index(self) -> usize { - Self::ALL.iter().position(|s| *s == self).unwrap_or(0) - } - - fn next(self) -> Option<Step> { - Self::ALL.get(self.index() + 1).copied() - } - - fn previous(self) -> Option<Step> { - self.index().checked_sub(1).map(|i| Self::ALL[i]) - } -} - /// The zones whose name has every word of `query` in it, in the order given. `stock` finds /// `Europe/Stockholm`; `new york` finds `America/New_York`; nothing typed finds them all. fn zones_matching<'a>(zones: &'a [String], query: &str) -> Vec<&'a String> { @@ -103,6 +88,8 @@ enum Done { Created(Result<(), String>), Zone(Result<(), String>), Name(Result<(), String>), + Networks(Vec<Network>), + Wifi(Result<(), String>), } struct Screenshot { @@ -128,7 +115,16 @@ pub struct App { rx: Receiver<Done>, /// The new account's user name, between making it and logging it in. new_user: Option<String>, + /// The steps this machine has, in order (no Wi-Fi step without Wi-Fi), and the one showing. + steps: Vec<Step>, step: Step, + /// The Wi-Fi step: the networks in range, the one picked, the password typed for it, and + /// when the list was last asked for. + networks: Vec<Network>, + wifi_pick: Option<String>, + wifi_field: Field, + wifi_asked: Option<Instant>, + wifi_scanning: bool, /// The clock step: every zone, the one chosen, what is typed to search, and whether the list /// has been scrolled to the chosen one yet. zones: Vec<String>, @@ -171,7 +167,13 @@ impl App { tx, rx, new_user: None, + steps: vec![Step::Clock, Step::Name, Step::Account], step: Step::Clock, + networks: Vec::new(), + wifi_pick: None, + wifi_field: Field::new("Password", true), + wifi_asked: None, + wifi_scanning: false, zones: Vec::new(), zone: String::new(), zone_filter: String::new(), @@ -194,6 +196,10 @@ impl App { self.zones = self.backend.timezones(); self.zone = self.backend.timezone(); self.host = self.backend.hostname(); + if self.backend.wifi_available() { + self.steps.insert(0, Step::Wifi); + } + self.step = self.steps[0]; } Screen::Setup } else { @@ -221,6 +227,19 @@ impl App { self.login.text.clear(); self.status = Status::Wrong; } + (Screen::Setup, "wifi") => { + self.networks = self.backend.wifi_networks(); + self.wifi_asked = Some(Instant::now()); + self.wifi_pick = Some("Home-5G".into()); + } + (Screen::Setup, "wifi-problem") => { + self.networks = self.backend.wifi_networks(); + self.wifi_asked = Some(Instant::now()); + self.wifi_pick = Some("Home-5G".into()); + self.wifi_field.text = "not it".into(); + self.status = + Status::Problem("could not join Home-5G: the password was not accepted".into()); + } (Screen::Setup, "name") => { self.step = Step::Name; self.host = "alices-laptop".into(); @@ -330,9 +349,62 @@ impl App { self.spawn(move |backend| Done::Name(backend.set_hostname(&name))); } + /// Asks for the networks in range, unless that is already being done. + fn scan(&mut self) { + if self.wifi_scanning { + return; + } + self.wifi_scanning = true; + self.wifi_asked = Some(Instant::now()); + self.spawn(|backend| Done::Networks(backend.wifi_networks())); + } + + fn picked_network(&self) -> Option<&Network> { + let ssid = self.wifi_pick.as_deref()?; + self.networks.iter().find(|n| n.ssid == ssid) + } + + /// Whether Connect can be pressed: a network picked, and its password if it has one. + fn wifi_ready(&self) -> bool { + self.picked_network() + .is_some_and(|n| !n.secured() || !self.wifi_field.text.is_empty()) + } + + fn submit_wifi(&mut self) { + if self.status == Status::Checking || !self.wifi_ready() { + return; + } + let Some(network) = self.picked_network().cloned() else { + return; + }; + let mut password = std::mem::replace( + &mut self.wifi_field.text, + String::with_capacity(model::MAX_PASSWORD), + ); + self.status = Status::Checking; + self.spawn(move |backend| { + let result = backend.wifi_connect(&network.ssid, &password); + model::wipe(&mut password); + Done::Wifi(result) + }); + } + + fn step_index(&self) -> usize { + self.steps.iter().position(|s| *s == self.step).unwrap_or(0) + } + + fn next_step(&self) -> Option<Step> { + self.steps.get(self.step_index() + 1).copied() + } + + fn previous_step(&self) -> Option<Step> { + self.step_index().checked_sub(1).map(|i| self.steps[i]) + } + /// Continue, on whichever step this is. fn submit_step(&mut self) { match self.step { + Step::Wifi => self.submit_wifi(), Step::Clock => self.submit_clock(), Step::Name => self.submit_name(), Step::Account => self.submit_setup(), @@ -342,7 +414,7 @@ impl App { /// To the next step, with nothing left over from this one. fn go_on(&mut self) { self.status = Status::Typing; - if let Some(next) = self.step.next() { + if let Some(next) = self.next_step() { self.step = next; } } @@ -352,7 +424,7 @@ impl App { return; } self.status = Status::Typing; - if let Some(previous) = self.step.previous() { + if let Some(previous) = self.previous_step() { self.step = previous; } } @@ -404,6 +476,18 @@ impl App { Done::Zone(Ok(())) => self.go_on(), Done::Zone(Err(e)) | Done::Name(Err(e)) => self.status = Status::Problem(e), Done::Name(Ok(())) => self.go_on(), + Done::Networks(list) => { + self.wifi_scanning = false; + self.networks = list; + if self.picked_network().is_none() { + self.wifi_pick = None; + } + } + Done::Wifi(Ok(())) => { + model::wipe(&mut self.wifi_field.text); + self.go_on(); + } + Done::Wifi(Err(e)) => self.status = Status::Problem(e), } } } @@ -449,6 +533,13 @@ impl App { fn setup_event(&mut self, event: &egui::Event) { if self.step != Step::Account { + // The Wi-Fi password is typed into the greeter's own secret field. + if self.step == Step::Wifi + && self.picked_network().is_some_and(Network::secured) + && self.wifi_field.type_into(std::slice::from_ref(event)) + { + self.status = Status::Typing; + } // The other steps are drawn with egui's own widgets, which take what is typed; // Enter is Continue. if let egui::Event::Key { @@ -640,6 +731,7 @@ impl App { ); ui.add_space(4.0); let subtitle = match self.step { + Step::Wifi => "Connect to Wi-Fi, so this computer has the network from the start.", Step::Clock => "Choose your time zone, so the clock is right.", Step::Name => "Give this computer a name.", Step::Account => "Let's set up this computer.", @@ -651,6 +743,7 @@ impl App { ); ui.add_space(28.0); match self.step { + Step::Wifi => self.draw_wifi(ui), Step::Clock => self.draw_clock(ui), Step::Name => self.draw_name(ui), Step::Account => self.draw_account(ui), @@ -751,6 +844,71 @@ impl App { self.status_line(ui, &hint); } + /// Wi-Fi (ADR-0019): the networks in range, a password for a secured one, and Connect. + fn draw_wifi(&mut self, ui: &mut Ui) { + let checking = self.status == Status::Checking; + // The list is asked for when the step opens and every few seconds after. + if self + .wifi_asked + .is_none_or(|t| t.elapsed() > Duration::from_secs(8)) + { + self.scan(); + } + let weak = ui.visuals().weak_text_color(); + ui.allocate_ui_with_layout( + vec2(field::SIZE.x, 190.0), + egui::Layout::top_down(egui::Align::Min), + |ui| { + egui::ScrollArea::vertical() + .max_height(190.0) + .auto_shrink([false, false]) + .show(ui, |ui| { + if self.networks.is_empty() { + let text = if self.wifi_scanning { + "Looking for networks…" + } else { + "No networks found" + }; + ui.label(RichText::new(text).color(weak)); + } + for network in self.networks.clone() { + let chosen = self.wifi_pick.as_deref() == Some(&network.ssid); + let detail = format!( + "{} {}%", + if network.secured() { "Secured" } else { "Open" }, + network.strength + ); + if list_row(ui, &network.ssid, &detail, chosen).clicked() && !checking { + if !chosen { + model::wipe(&mut self.wifi_field.text); + } + self.wifi_pick = Some(network.ssid.clone()); + self.status = Status::Typing; + } + } + }); + }, + ); + ui.add_space(10.0); + if self.picked_network().is_some_and(Network::secured) { + let tone = if checking { Tone::Busy } else { Tone::Normal }; + self.wifi_field.show(ui, field::SIZE, !checking, tone, 0.0); + ui.add_space(10.0); + } + let ready = self.wifi_ready() && !checking; + let label = if checking { "Connecting…" } else { "Connect" }; + if wide_button(ui, label, ready, false).clicked() && ready { + self.submit_wifi(); + } + ui.add_space(10.0); + let hint = if self.wifi_pick.is_none() { + "Pick a network. Using a cable? Skip this." + } else { + "" + }; + self.status_line(ui, hint); + } + /// The computer's name (ADR-0019): how it shows up on a network. fn draw_name(&mut self, ui: &mut Ui) { let checking = self.status == Status::Checking; @@ -786,8 +944,8 @@ impl App { ui.label( RichText::new(format!( "Step {} of {}", - self.step.index() + 1, - Step::ALL.len() + self.step_index() + 1, + self.steps.len() )) .color(weak), ); @@ -797,7 +955,7 @@ impl App { vec2(field::SIZE.x, 28.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { - if self.step.previous().is_some() + if self.previous_step().is_some() && ui.add(egui::Button::new("Back").frame(false)).clicked() { back = true; @@ -941,6 +1099,12 @@ fn avatar(ui: &mut Ui, name: &str, side: f32, chosen: bool) -> egui::Response { /// One time zone in the list: the chosen one on the accent, the one under the pointer lightly. fn zone_row(ui: &mut Ui, text: &str, chosen: bool) -> egui::Response { + list_row(ui, text, "", chosen) +} + +/// A row of a list: the text in the middle, or at the left with `detail` at the right; the chosen +/// one on the accent, the one under the pointer lightly. +fn list_row(ui: &mut Ui, text: &str, detail: &str, chosen: bool) -> egui::Response { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click()); let v = ui.visuals().clone(); if response.hovered() { @@ -962,13 +1126,30 @@ fn zone_row(ui: &mut Ui, text: &str, chosen: bool) -> egui::Response { } else { v.text_color() }; - painter.text( - rect.center(), - Align2::CENTER_CENTER, - text, - FontId::proportional(15.0), - ink, - ); + if detail.is_empty() { + painter.text( + rect.center(), + Align2::CENTER_CENTER, + text, + FontId::proportional(15.0), + ink, + ); + } else { + painter.text( + rect.left_center() + vec2(14.0, 0.0), + Align2::LEFT_CENTER, + text, + FontId::proportional(15.0), + ink, + ); + painter.text( + rect.right_center() - vec2(14.0, 0.0), + Align2::RIGHT_CENTER, + detail, + FontId::proportional(13.0), + ink.gamma_multiply(0.7), + ); + } response } @@ -1334,6 +1515,113 @@ mod tests { ); } + /// A fresh machine with Wi-Fi: it opens on the Wi-Fi step. + fn with_wifi() -> App { + app(Mock::new(&[], Duration::ZERO).with_wifi()) + } + + /// Polls as frames would until the list of networks is there. + fn wait_for_networks(a: &mut App) { + a.scan(); + for _ in 0..400 { + a.poll(); + if !a.wifi_scanning { + return; + } + std::thread::sleep(Duration::from_millis(5)); + } + panic!("the scan never answered"); + } + + #[test] + fn a_machine_with_wifi_starts_on_it_and_one_without_does_not() { + let a = with_wifi(); + assert_eq!(a.step, Step::Wifi); + assert_eq!(a.steps.len(), 4); + assert_eq!(quick(&[]).step, Step::Clock, "no Wi-Fi, no Wi-Fi step"); + assert_eq!(quick(&[]).steps.len(), 3); + } + + #[test] + fn the_networks_come_one_per_name_strongest_first() { + let mut a = with_wifi(); + wait_for_networks(&mut a); + let names: Vec<&str> = a.networks.iter().map(|n| n.ssid.as_str()).collect(); + assert_eq!( + names, + ["Home-5G", "CoffeeShop", "Neighbour", "Office-Guest"] + ); + assert_eq!( + a.networks[0].strength, 92, + "the stronger of the two Home-5G" + ); + } + + #[test] + fn an_open_network_joins_without_a_password_and_goes_on() { + let mut a = with_wifi(); + wait_for_networks(&mut a); + a.wifi_pick = Some("CoffeeShop".into()); + assert!(a.wifi_ready()); + a.handle_keys(&[key(egui::Key::Enter, false)]); + assert_eq!(a.status, Status::Checking); + settle(&mut a); + assert_eq!(a.step, Step::Clock); + } + + #[test] + fn a_secured_network_needs_its_password_before_it_can_be_joined() { + let mut a = with_wifi(); + wait_for_networks(&mut a); + a.wifi_pick = Some("Home-5G".into()); + assert!(!a.wifi_ready(), "no password yet"); + a.handle_keys(&[typed(MOCK_PASSWORD)]); + assert!(a.wifi_ready()); + assert!( + a.fields.iter().all(|f| f.text.is_empty()), + "what is typed here does not reach the account form" + ); + } + + #[test] + fn the_right_password_joins_and_the_password_is_gone() { + let mut a = with_wifi(); + wait_for_networks(&mut a); + a.wifi_pick = Some("Home-5G".into()); + a.handle_keys(&[typed(MOCK_PASSWORD), key(egui::Key::Enter, false)]); + assert!( + a.wifi_field.text.is_empty(), + "it left the box when it was sent" + ); + settle(&mut a); + assert_eq!(a.step, Step::Clock); + assert!(a.wifi_field.text.is_empty()); + } + + #[test] + fn a_wrong_password_is_shown_and_the_step_stays_with_the_box_empty() { + let mut a = with_wifi(); + wait_for_networks(&mut a); + a.wifi_pick = Some("Home-5G".into()); + a.handle_keys(&[typed("nope"), key(egui::Key::Enter, false)]); + settle(&mut a); + assert_eq!(a.step, Step::Wifi); + assert!(matches!(&a.status, Status::Problem(e) if e.contains("password was not accepted"))); + assert!(a.wifi_field.text.is_empty()); + assert!(!a.wifi_ready(), "the password has to be typed again"); + } + + #[test] + fn skip_and_back_pass_through_the_wifi_step() { + let mut a = with_wifi(); + a.go_on(); + assert_eq!(a.step, Step::Clock); + a.go_back(); + assert_eq!(a.step, Step::Wifi); + a.go_back(); + assert_eq!(a.step, Step::Wifi, "nothing before the first step"); + } + /// A fresh machine, on the name step. fn at_name() -> App { let mut a = quick(&[]); @@ -1410,6 +1698,8 @@ mod tests { "clock", "name", "name-problem", + "wifi", + "wifi-problem", ] { a.demo(what); let _ = ctx.run_ui(egui::RawInput::default(), |ui| a.draw(ui)); diff --git a/greeter/src/backend.rs b/greeter/src/backend.rs @@ -26,6 +26,40 @@ pub enum LoginError { Problem(String), } +/// How a Wi-Fi network is secured, as far as the setup can join it: open, or with a password +/// (WPA or WPA2 personal, or WPA3's SAE). Networks it cannot join (WEP, a work network with its own +/// login) are not offered. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Security { + Open, + Psk, + Sae, +} + +/// A Wi-Fi network in range. +#[derive(Debug, Clone, PartialEq)] +pub struct Network { + pub ssid: String, + /// 0 to 100. + pub strength: u8, + pub security: Security, +} + +impl Network { + pub fn secured(&self) -> bool { + self.security != Security::Open + } +} + +/// The networks to show: one per name, the strongest, strongest first, hidden ones (no name) left out. +pub fn tidy(mut networks: Vec<Network>) -> Vec<Network> { + networks.retain(|n| !n.ssid.is_empty()); + networks.sort_by(|a, b| b.strength.cmp(&a.strength).then(a.ssid.cmp(&b.ssid))); + let mut seen = std::collections::HashSet::new(); + networks.retain(|n| seen.insert(n.ssid.clone())); + networks +} + /// Called from worker threads, since PAM and D-Bus can take seconds (a wrong password costs a /// delay by design), so a backend is shared and answers `&self`. pub trait Backend: Send + Sync { @@ -53,6 +87,13 @@ pub trait Backend: Send + Sync { fn hostname(&self) -> String; /// Sets it, through hostnamed, which polkit lets the greeter do only on the first run. fn set_hostname(&self, name: &str) -> Result<(), String>; + /// Whether this machine has Wi-Fi: without it the setup has no Wi-Fi step. + fn wifi_available(&self) -> bool; + /// Asks for a new scan and returns the networks in range (`tidy`), which can take a moment. + fn wifi_networks(&self) -> Vec<Network>; + /// Joins a network and saves it for every user (polkit lets the greeter only on the first run); + /// returns when it is up, or says why not. + fn wifi_connect(&self, ssid: &str, password: &str) -> Result<(), String>; } /// A backend with accounts in memory, for the screens and the tests. The password that works is @@ -62,6 +103,7 @@ pub struct Mock { delay: Duration, zone: Mutex<String>, host: Mutex<String>, + wifi: bool, } /// The zones the mock knows, as a few of the real ones. @@ -99,6 +141,7 @@ impl Mock { delay, zone: Mutex::new("UTC".into()), host: Mutex::new("sectorf".into()), + wifi: false, } } @@ -110,9 +153,15 @@ impl Mock { ) } - /// A machine fresh from the install: nobody can log in. + /// A machine fresh from the install: nobody can log in, and it has Wi-Fi. pub fn first_run() -> Self { - Self::new(&[], Duration::from_millis(700)) + Self::new(&[], Duration::from_millis(700)).with_wifi() + } + + /// The same, with Wi-Fi: four networks in range. + pub fn with_wifi(mut self) -> Self { + self.wifi = true; + self } } @@ -190,6 +239,40 @@ impl Backend for Mock { *self.host.lock().unwrap() = name.into(); Ok(()) } + + fn wifi_available(&self) -> bool { + self.wifi + } + + fn wifi_networks(&self) -> Vec<Network> { + let net = |ssid: &str, strength, security| Network { + ssid: ssid.into(), + strength, + security, + }; + tidy(vec![ + net("Neighbour", 38, Security::Psk), + net("Home-5G", 92, Security::Psk), + net("CoffeeShop", 71, Security::Open), + net("Home-5G", 55, Security::Psk), + net("", 60, Security::Psk), + net("Office-Guest", 24, Security::Sae), + ]) + } + + /// Open networks join; a secured one wants the password `sectorf`. + fn wifi_connect(&self, ssid: &str, password: &str) -> Result<(), String> { + std::thread::sleep(self.delay); + let Some(network) = self.wifi_networks().into_iter().find(|n| n.ssid == ssid) else { + return Err(format!("could not join {ssid}: it is out of range")); + }; + if network.secured() && password != MOCK_PASSWORD { + return Err(format!( + "could not join {ssid}: the password was not accepted" + )); + } + Ok(()) + } } #[cfg(test)] @@ -212,6 +295,27 @@ mod tests { } #[test] + fn the_networks_are_one_per_name_strongest_first_and_hidden_ones_left_out() { + let net = |ssid: &str, strength| Network { + ssid: ssid.into(), + strength, + security: Security::Psk, + }; + let shown = tidy(vec![ + net("b", 40), + net("a", 40), + net("", 99), + net("a", 80), + net("c", 10), + ]); + let names: Vec<_> = shown + .iter() + .map(|n| (n.ssid.as_str(), n.strength)) + .collect(); + assert_eq!(names, [("a", 80), ("b", 40), ("c", 10)]); + } + + #[test] fn logging_in_checks_the_password_and_the_user() { let m = quick(&[("alice", "Alice Example")]); assert_eq!(m.login("alice", MOCK_PASSWORD), Ok(())); diff --git a/greeter/src/main.rs b/greeter/src/main.rs @@ -20,7 +20,7 @@ For trying the screens without greetd, on a mock whose password is `sectorf`: PATINA_GREETER_MOCK=login a machine with accounts (alice and bob) PATINA_GREETER_MOCK=setup a machine fresh from the install, with none PATINA_GREETER_SIZE=1280x800 a window of that size, not full screen - PATINA_GREETER_DEMO=... fills a screen in: login: typing, wrong, problem; setup: clock, filled, problem + PATINA_GREETER_DEMO=... fills a screen in: login: typing, wrong, problem; setup: wifi, wifi-problem, clock, name, name-problem, filled, problem PATINA_GREETER_SCREENSHOT=file.png saves the screen to a file and quits PATINA_SKIN=name another skin"; diff --git a/greeter/src/system.rs b/greeter/src/system.rs @@ -4,10 +4,12 @@ use std::os::unix::net::UnixStream; use greetd_ipc::{AuthMessageType, ErrorType, Request, Response, codec::SyncCodec}; +use std::collections::HashMap; + use zbus::blocking::{Connection, Proxy}; -use zbus::zvariant::OwnedObjectPath; +use zbus::zvariant::{OwnedObjectPath, Value}; -use crate::backend::{Backend, LoginError, Power, User}; +use crate::backend::{Backend, LoginError, Network, Power, Security, User, tidy}; const ACCOUNTS: &str = "org.freedesktop.Accounts"; const ACCOUNTS_PATH: &str = "/org/freedesktop/Accounts"; @@ -16,6 +18,35 @@ const TIMEDATE: &str = "org.freedesktop.timedate1"; const TIMEDATE_PATH: &str = "/org/freedesktop/timedate1"; const HOSTNAME: &str = "org.freedesktop.hostname1"; const HOSTNAME_PATH: &str = "/org/freedesktop/hostname1"; +const NM: &str = "org.freedesktop.NetworkManager"; +const NM_PATH: &str = "/org/freedesktop/NetworkManager"; +const NM_DEVICE: &str = "org.freedesktop.NetworkManager.Device"; +const NM_WIRELESS: &str = "org.freedesktop.NetworkManager.Device.Wireless"; +const NM_AP: &str = "org.freedesktop.NetworkManager.AccessPoint"; +/// NetworkManager's NM_DEVICE_TYPE_WIFI. +const NM_DEVICE_TYPE_WIFI: u32 = 2; + +// NetworkManager's access point flags. +const AP_PRIVACY: u32 = 0x1; +const KEY_MGMT_PSK: u32 = 0x100; +const KEY_MGMT_SAE: u32 = 0x400; + +/// How an access point is secured, from its three flag words, or `None` for what cannot be joined +/// here: WEP (privacy and no key management), a work network with its own login (802.1X), and the +/// rest. A network that offers both WPA2 and WPA3 is joined as WPA2, which every router takes. +pub fn ap_security(flags: u32, wpa: u32, rsn: u32) -> Option<Security> { + let key_mgmt = wpa | rsn; + if key_mgmt == 0 { + return (flags & AP_PRIVACY == 0).then_some(Security::Open); + } + if key_mgmt & KEY_MGMT_PSK != 0 { + Some(Security::Psk) + } else if key_mgmt & KEY_MGMT_SAE != 0 { + Some(Security::Sae) + } else { + None + } +} /// The first human uid, as in /etc/login.defs. const FIRST_UID: u32 = 1000; @@ -47,6 +78,56 @@ impl System { Proxy::new(bus, dest, path, iface).map_err(|e| e.to_string()) } + /// The first Wi-Fi device NetworkManager has, if it has one. + fn wifi_device(bus: &Connection) -> Result<Option<OwnedObjectPath>, String> { + let nm = Self::proxy(bus, NM, NM_PATH, NM)?; + let devices: Vec<OwnedObjectPath> = + nm.call("GetDevices", &()).map_err(|e| e.to_string())?; + for path in devices { + let kind = Self::proxy(bus, NM, path.as_str(), NM_DEVICE)? + .get_property::<u32>("DeviceType") + .map_err(|e| e.to_string())?; + if kind == NM_DEVICE_TYPE_WIFI { + return Ok(Some(path)); + } + } + Ok(None) + } + + /// The access points in range, each with its object path (so one can be joined), unfiltered. + fn access_points( + bus: &Connection, + device: &OwnedObjectPath, + ) -> Result<Vec<(OwnedObjectPath, Network)>, String> { + let wireless = Self::proxy(bus, NM, device.as_str(), NM_WIRELESS)?; + let paths: Vec<OwnedObjectPath> = wireless + .call("GetAccessPoints", &()) + .map_err(|e| e.to_string())?; + let mut found = Vec::new(); + for path in paths { + // Read in a block of its own, so the proxy's borrow of the path has ended before the + // path is kept. + let network = { + let ap = Self::proxy(bus, NM, path.as_str(), NM_AP)?; + let get_u32 = |name: &str| ap.get_property::<u32>(name).unwrap_or(0); + ap_security(get_u32("Flags"), get_u32("WpaFlags"), get_u32("RsnFlags")).map( + |security| { + let ssid: Vec<u8> = ap.get_property("Ssid").unwrap_or_default(); + Network { + ssid: String::from_utf8_lossy(&ssid).into_owned(), + strength: ap.get_property::<u8>("Strength").unwrap_or(0), + security, + } + }, + ) + }; + if let Some(network) = network { + found.push((path, network)); + } + } + Ok(found) + } + /// Whether AccountsService says the account is locked (no password set yet). If it cannot be /// asked, not: the login is then shown, and greetd decides. fn locked(bus: &Connection, name: &str) -> bool { @@ -262,6 +343,103 @@ impl Backend for System { get().unwrap_or_default() } + fn wifi_available(&self) -> bool { + Self::bus() + .and_then(|bus| Self::wifi_device(&bus)) + .is_ok_and(|device| device.is_some()) + } + + fn wifi_networks(&self) -> Vec<Network> { + let list = || -> Result<Vec<Network>, String> { + let bus = Self::bus()?; + let Some(device) = Self::wifi_device(&bus)? else { + return Ok(Vec::new()); + }; + // A scan takes seconds, and the list is what is known now; the setup asks again. + let options: HashMap<&str, Value> = HashMap::new(); + Self::proxy(&bus, NM, device.as_str(), NM_WIRELESS)? + .call::<_, _, ()>("RequestScan", &(options,)) + .ok(); + Ok(tidy( + Self::access_points(&bus, &device)? + .into_iter() + .map(|(_, network)| network) + .collect(), + )) + }; + list().unwrap_or_default() + } + + fn wifi_connect(&self, ssid: &str, password: &str) -> Result<(), String> { + let bus = Self::bus()?; + let device = Self::wifi_device(&bus)?.ok_or("this computer has no Wi-Fi")?; + let ap = Self::access_points(&bus, &device)? + .into_iter() + .find(|(_, n)| n.ssid == ssid) + .ok_or_else(|| format!("could not join {ssid}: it is out of range"))?; + + let mut wireless: HashMap<&str, Value> = HashMap::new(); + wireless.insert("ssid", Value::from(ssid.as_bytes().to_vec())); + wireless.insert("mode", Value::from("infrastructure")); + let mut connection: HashMap<&str, Value> = HashMap::new(); + connection.insert("id", Value::from(ssid)); + connection.insert("type", Value::from("802-11-wireless")); + let mut settings: HashMap<&str, HashMap<&str, Value>> = HashMap::new(); + settings.insert("connection", connection); + settings.insert("802-11-wireless", wireless); + let key_mgmt = match ap.1.security { + Security::Open => None, + Security::Psk => Some("wpa-psk"), + Security::Sae => Some("sae"), + }; + if let Some(key_mgmt) = key_mgmt { + let mut security: HashMap<&str, Value> = HashMap::new(); + security.insert("key-mgmt", Value::from(key_mgmt)); + security.insert("psk", Value::from(password)); + settings.insert("802-11-wireless-security", security); + } + + let nm = Self::proxy(&bus, NM, NM_PATH, NM)?; + // "/" for the access point: NetworkManager picks the best one for the name. + let any = OwnedObjectPath::try_from("/").map_err(|e| e.to_string())?; + let (saved, active): (OwnedObjectPath, OwnedObjectPath) = nm + .call("AddAndActivateConnection", &(settings, &device, &any)) + .map_err(|e| format!("could not join {ssid}: {e}"))?; + + // Up, or failed: a wrong password ends as deactivated. The state is polled for half a minute. + let active = Self::proxy( + &bus, + NM, + active.as_str(), + "org.freedesktop.NetworkManager.Connection.Active", + )?; + for _ in 0..60 { + match active.get_property::<u32>("State") { + Ok(2) => return Ok(()), + // Deactivating or deactivated: it did not work. + Ok(3 | 4) | Err(_) => break, + Ok(_) => std::thread::sleep(std::time::Duration::from_millis(500)), + } + } + // Do not keep a network that would not join (a mistyped password) on the machine. + Self::proxy( + &bus, + NM, + saved.as_str(), + "org.freedesktop.NetworkManager.Settings.Connection", + ) + .and_then(|c| c.call::<_, _, ()>("Delete", &()).map_err(|e| e.to_string())) + .ok(); + Err(format!( + "could not join {ssid}: {}", + if key_mgmt.is_some() { + "the password was not accepted, or the network did not answer" + } else { + "the network did not answer" + } + )) + } + fn set_hostname(&self, name: &str) -> Result<(), String> { let bus = Self::bus()?; Self::proxy(&bus, HOSTNAME, HOSTNAME_PATH, HOSTNAME)? @@ -272,7 +450,45 @@ impl Backend for System { #[cfg(test)] mod tests { - use super::human_accounts; + use super::{ap_security, human_accounts}; + use crate::backend::Security; + + #[test] + fn access_points_are_open_or_with_a_password_or_not_joinable() { + // (flags, wpa, rsn) + assert_eq!(ap_security(0, 0, 0), Some(Security::Open)); + assert_eq!( + ap_security(1, 0, 0), + None, + "privacy with no key management is WEP" + ); + assert_eq!( + ap_security(1, 0, 0x100), + Some(Security::Psk), + "WPA2 personal" + ); + assert_eq!( + ap_security(1, 0x100, 0), + Some(Security::Psk), + "WPA personal" + ); + assert_eq!( + ap_security(1, 0, 0x400), + Some(Security::Sae), + "WPA3 personal" + ); + assert_eq!( + ap_security(1, 0, 0x100 | 0x400), + Some(Security::Psk), + "WPA2/WPA3 joins as WPA2" + ); + assert_eq!( + ap_security(1, 0, 0x200), + None, + "a work network with its own login" + ); + assert_eq!(ap_security(1, 0, 0x800), None, "opportunistic encryption"); + } #[test] fn only_people_who_can_log_in() {