forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

app.rs1198 lines, 47.5 KiBHistoryRawDownload
1//!//! Root view: nav rail, header bar (interface picker, privilege badge,
2//! monitor/capture toggle), page content, status line, and the background
3//! task that polls the service event channel.
4
5/// Word-wrap toast text. gpuikit toasts render their message on one line,
6/// so a long message (the deauth-storm alert carries two MACs) stretches
7/// the 360 px toast box past the window edge. 36 chars ≈ the usable width
8/// at text_sm once icon, padding and the close button are subtracted.
9fn wrap_toast_text(msg: &str) -> String {
10 const LIMIT: usize = 36;
11 let mut out = String::with_capacity(msg.len() + 4);
12 let mut col = 0usize;
13 for word in msg.split(' ') {
14 if col > 0 && col + 1 + word.len() > LIMIT {
15 out.push('\n');
16 col = 0;
17 } else if col > 0 {
18 out.push(' ');
19 col += 1;
20 }
21 out.push_str(word);
22 col += word.len();
23 // Unbreakable token longer than one line (e.g. a file path in an
24 // error): hard-split it so it can never stretch the box.
25 while col > LIMIT {
26 let start = out.len() - col;
27 let cut = start
28 + out[start..]
29 .char_indices()
30 .nth(LIMIT)
31 .map(|(i, _)| i)
32 .unwrap_or(col);
33 out.insert(cut, '\n');
34 col -= LIMIT;
35 }
36 }
37 out
38}
39
40use std::collections::BTreeMap;
41use std::sync::Arc;
42use std::sync::atomic::{AtomicBool, Ordering};
43use std::time::{Duration, Instant};
44
45use crossbeam_channel::{Receiver, Sender};
46use gpui::{
47 App, AppContext, Context, Entity, FocusHandle, FontWeight, InteractiveElement, IntoElement,
48 KeyBinding, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window,
49 actions, div, prelude::FluentBuilder, px,
50};
51use gpuikit::elements::badge::badge;
52use gpuikit::elements::button::button;
53use gpuikit::elements::select::{SelectState, select};
54use gpuikit::elements::table::SortDescriptor;
55use gpuikit::elements::toast::ToastExt;
56use gpuikit::input::InputState;
57use gpuikit::layout::{h_stack, v_stack};
58use gpuikit::theme::{ActiveTheme, Themeable};
59use gpuikit::traits::disableable::Disableable;
60
61use crate::common::{AccessPoint, Cmd, Event, MacAddr};
62use crate::service::ServiceClient;
63use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState};
64
65/// How often the UI drains the service event channel.
66const EVENT_POLL: Duration = Duration::from_millis(100);
67
68actions!(
69 wifi_lab,
70 [
71 /// ctrl-q: quit the app (the release hook stops UI-process jobs
72 /// and shuts the service down).
73 QuitApp,
74 /// ctrl-1: switch to the Networks page.
75 ShowNetworksPage,
76 /// ctrl-2: switch to the Attacks page.
77 ShowAttacksPage,
78 /// ctrl-3: switch to the Cracker page.
79 ShowCrackerPage,
80 /// ctrl-4: switch to the Log page.
81 ShowLogPage,
82 ]
83);
84
85/// Global (window-level) keybindings: quit + page switches. Registered
86/// once at app start (see [`crate::ui::run_app`]); the matching
87/// `.on_action` handlers live on the root view so the bindings fire
88/// regardless of which page or control is focused. No per-page bindings
89/// here — pages register their own (e.g. the cracker page's Enter).
90pub fn bind_app_keys(cx: &mut App) {
91 cx.bind_keys([
92 KeyBinding::new("ctrl-q", QuitApp, None),
93 KeyBinding::new("ctrl-1", ShowNetworksPage, None),
94 KeyBinding::new("ctrl-2", ShowAttacksPage, None),
95 KeyBinding::new("ctrl-3", ShowCrackerPage, None),
96 KeyBinding::new("ctrl-4", ShowLogPage, None),
97 ]);
98}
99
100/// Left nav destinations.
101#[derive(Clone, Copy, PartialEq, Eq)]
102pub enum Page {
103 Networks,
104 Attacks,
105 Cracker,
106 Log,
107}
108
109impl Page {
110 const ALL: [Page; 4] = [Page::Networks, Page::Attacks, Page::Cracker, Page::Log];
111
112 fn label(self) -> &'static str {
113 match self {
114 Page::Networks => "Networks",
115 Page::Attacks => "Attacks",
116 Page::Cracker => "Cracker",
117 Page::Log => "Log",
118 }
119 }
120
121 /// Startup page override (`WIFI_LAB_PAGE=attacks`) — dev/visual-verification
122 /// hook; unknown values fall through to Networks.
123 fn from_name(name: &str) -> Option<Page> {
124 Page::ALL
125 .iter()
126 .copied()
127 .find(|p| p.label().eq_ignore_ascii_case(name))
128 }
129}
130
131pub struct AppRoot {
132 pub state: AppState,
133 /// Service event channel (mock thread or service reader thread).
134 pub rx: Receiver<Event>,
135 /// UI-triggered actions are injected into the same pipeline.
136 pub tx: Sender<Event>,
137 pub page: Page,
138 /// UI-process privilege ([`crate::iface::is_root`]); the header badge
139 /// combines this with `service` presence to show the SERVICE's
140 /// privilege state — any running service is root (direct spawn or
141 /// pkexec).
142 pub is_root: bool,
143 /// Privileged radio service client (owns the child process). `None`
144 /// in mock mode or before the first "Start capture". Kept across
145 /// stop/start cycles. NOT involved in cracking — crack jobs are
146 /// UI-process threads tracked via [`AppRoot::crack_stop`].
147 pub service: Option<ServiceClient>,
148 /// Mock data mode (`--mock` / `WIFI_LAB_MOCK=1`): never touches devices.
149 pub is_mock: bool,
150 /// Target BSSID picked on the Networks page (AP row or client row).
151 pub selected: Option<MacAddr>,
152 /// Last-known AP row for [`AppRoot::selected`], snapshotted at click
153 /// time and refreshed whenever the live record updates. The Attacks
154 /// page builds its target card from this even when the live row is
155 /// momentarily absent (host-capture mode never re-scans: a target
156 /// picked before the lock may have no AP row at all).
157 pub selected_ap: Option<AccessPoint>,
158 /// Client station picked on the Networks page; deauth targets it
159 /// instead of the broadcast address when set (AP stays `selected`).
160 pub selected_client: Option<MacAddr>,
161 /// Message bitmask (see [`Event::HandshakeProgress`]) per in-flight
162 /// 4-way capture, keyed by (AP, client).
163 pub hs_progress: BTreeMap<(MacAddr, MacAddr), u8>,
164 /// "Spinner shown" flags for attack buttons awaiting results.
165 pub attacking_handshake: bool,
166 pub attacking_pmkid: bool,
167 /// Channels the scanner is parked on for attacks (restricted StartScan
168 /// plan; several entries cover dual-band targets). `None` = full hop
169 /// list. Blanket spectrum-wide hopping makes capture/PMKID/deauth
170 /// mostly deaf and blind to one band.
171 pub parked_channels: Option<Vec<u8>>,
172 /// Stop flag of the running crack job (UI-process thread, see
173 /// [`crate::attack`]); flipped by Stop and on window close.
174 pub crack_stop: Option<Arc<AtomicBool>>,
175 /// Stop flag of the running rainbow-table build job.
176 pub rainbow_stop: Option<Arc<AtomicBool>>,
177 /// Throttle for resume-session writes (see [`AppRoot::maybe_save_crack_session`]).
178 pub last_session_save: Instant,
179 /// Toasts queued by the event loop (no Window there) — shown on the
180 /// next render pass. Capped (oldest dropped) so a burst of alerts
181 /// can't bury the window.
182 pub pending_toast: std::collections::VecDeque<SharedString>,
183 /// NetworkManager seen active when capture started (fights channels).
184 pub nm_active: bool,
185 /// Used to invalidate stale cracker simulation ticks after Stop/re-Start.
186 pub crack_epoch: u64,
187 pub ap_sort: Option<SortDescriptor>,
188 pub client_sort: Option<SortDescriptor>,
189 pub focus_handle: FocusHandle,
190 pub iface_select: Entity<SelectState<String>>,
191 /// Cracker target picker; the VALUE is the stable index into
192 /// `state.capture_descs()` (mirrors [`state::CrackerState::target`]),
193 /// the LABEL is the display description.
194 pub target_select: Entity<SelectState<usize>>,
195 pub wordlist_input: Entity<InputState>,
196 /// Cracker attack-mode picker ([`crate::attack::Attack`]: wordlist /
197 /// bruteforce / rainbow).
198 pub attack_select: Entity<SelectState<String>>,
199 /// Selected attack mode value ("wordlist" | "bruteforce" | "rainbow").
200 pub attack_mode: String,
201 /// Bruteforce preset chips ([`crate::attack::charset`]): unioned with
202 /// the custom field into the effective charset.
203 pub cs_lower: bool,
204 pub cs_upper: bool,
205 pub cs_digits: bool,
206 pub cs_special: bool,
207 /// Bruteforce mode inputs: charset and min/max word length.
208 pub charset_input: Entity<InputState>,
209 pub len_min_input: Entity<InputState>,
210 pub len_max_input: Entity<InputState>,
211 /// Rainbow mode: PMK table path; the build job writes it, the run
212 /// reads it.
213 pub rainbow_input: Entity<InputState>,
214 pub deauth_input: Entity<InputState>,
215 /// Networks-page label editor; the labels themselves live in
216 /// `state.labels` ([`crate::store`]).
217 pub label_input: Entity<InputState>,
218 /// Log page body: read-only multiline input so log text is
219 /// mouse-selectable / Ctrl-C-copyable (plain text widgets aren't).
220 pub log_input: Entity<InputState>,
221 /// Rules-attack mode: hashcat-style rule file path.
222 pub rules_input: Entity<InputState>,
223 /// Crack-time estimator candidate (how strong might the password be).
224 pub strength_input: Entity<InputState>,
225 /// Hybrid mode: appended-suffix length bounds.
226 pub hyb_min_input: Entity<InputState>,
227 pub hyb_max_input: Entity<InputState>,
228 /// Bruteforce charset ordering: most-common characters first.
229 pub freq_order: bool,
230 /// A throughput benchmark run is in flight.
231 pub bench_running: bool,
232 /// A capture-file import is in flight.
233 pub import_busy: bool,
234 /// Target count behind the "Deauth all clients (N)" button label
235 /// (0 = hidden); computed during attack-page render prep.
236 pub deauth_all_targets: usize,
237 /// Saved cracking presets + recent wordlists (~/wifi_lab/profiles.json).
238 pub profiles: crate::store::Profiles,
239}
240
241impl AppRoot {
242 pub fn new(
243 window: &mut Window,
244 cx: &mut Context<Self>,
245 tx: Sender<Event>,
246 rx: Receiver<Event>,
247 is_mock: bool,
248 ifaces: Vec<String>,
249 selected_iface: String,
250 ) -> Self {
251 let view = cx.entity();
252
253 let iface_select = cx.new(|_cx| {
254 SelectState::new(
255 select(
256 "iface-select",
257 "Interface",
258 ifaces
259 .iter()
260 .map(|i| (i.clone(), i.clone()))
261 .collect::<Vec<_>>(),
262 )
263 .selected(selected_iface.clone())
264 .on_change({
265 let view = view.clone();
266 move |ifname, _window, cx| {
267 view.update(cx, |app, cx| {
268 app.state.ifname = ifname.clone();
269 app.state.push_log(format!("iface: selected {ifname}"));
270 cx.notify();
271 });
272 }
273 }),
274 )
275 });
276
277 let wordlist_input = cx.new(InputState::new_singleline);
278 wordlist_input.update(cx, |input, cx| {
279 input.set_content("/usr/share/wordlists/rockyou.txt", cx);
280 });
281
282 let deauth_input = cx.new(InputState::new_singleline);
283 deauth_input.update(cx, |input, cx| {
284 input.set_content("16", cx);
285 });
286
287 let label_input = cx.new(InputState::new_singleline);
288 let log_input = cx.new(|cx| InputState::new_multiline(cx).read_only(true));
289
290 let attack_select = cx.new(|_cx| {
291 SelectState::new(
292 select(
293 "cracker-attack",
294 "Attack",
295 vec![
296 ("wordlist".to_string(), "wordlist".to_string()),
297 ("rules".to_string(), "rules".to_string()),
298 ("hybrid".to_string(), "hybrid".to_string()),
299 ("bruteforce".to_string(), "bruteforce".to_string()),
300 ("rainbow".to_string(), "rainbow".to_string()),
301 ],
302 )
303 .selected("wordlist".to_string())
304 .on_change({
305 let view = view.clone();
306 move |mode, _window, cx| {
307 view.update(cx, |app, cx| {
308 app.attack_mode = mode;
309 cx.notify();
310 });
311 }
312 }),
313 )
314 });
315 let charset_input = cx.new(InputState::new_singleline);
316 let len_min_input = cx.new(InputState::new_singleline);
317 len_min_input.update(cx, |input, cx| input.set_content("8", cx));
318 let len_max_input = cx.new(InputState::new_singleline);
319 len_max_input.update(cx, |input, cx| input.set_content("10", cx));
320 let rainbow_input = cx.new(InputState::new_singleline);
321 let rules_input = cx.new(InputState::new_singleline);
322 rules_input.update(cx, |input, cx| {
323 input.set_content("/path/to/rules (e.g. best64.rule)", cx);
324 });
325 let strength_input = cx.new(InputState::new_singleline);
326 let hyb_min_input = cx.new(InputState::new_singleline);
327 hyb_min_input.update(cx, |input, cx| input.set_content("1", cx));
328 let hyb_max_input = cx.new(InputState::new_singleline);
329 hyb_max_input.update(cx, |input, cx| input.set_content("2", cx));
330
331 // Focus the root view at startup so the window-level keybindings
332 // (ctrl-q, ctrl-1..4) dispatch through it before any control
333 // grabs focus. Rendered with `.track_focus` on the root div.
334 let root_focus = cx.focus_handle();
335 window.focus(&root_focus, cx);
336
337 let mut this = AppRoot {
338 state: AppState::new(&selected_iface),
339 rx,
340 tx,
341 page: std::env::var("WIFI_LAB_PAGE")
342 .ok()
343 .and_then(|p| Page::from_name(&p))
344 .unwrap_or(Page::Networks),
345 is_root: crate::iface::is_root(),
346 service: None,
347 is_mock,
348 selected: None,
349 selected_ap: None,
350 selected_client: None,
351 hs_progress: BTreeMap::new(),
352 attacking_handshake: false,
353 attacking_pmkid: false,
354 parked_channels: None,
355 crack_stop: None,
356 rainbow_stop: None,
357 last_session_save: Instant::now(),
358 pending_toast: std::collections::VecDeque::new(),
359 nm_active: false,
360 crack_epoch: 0,
361 ap_sort: None,
362 client_sort: None,
363 focus_handle: root_focus,
364 iface_select,
365 target_select: cx.new(|_cx| {
366 let empty: Vec<(usize, String)> = Vec::new();
367 SelectState::new(select("cracker-target", "Crack target", empty))
368 }),
369 wordlist_input,
370 attack_select,
371 attack_mode: "wordlist".to_string(),
372 cs_lower: false,
373 cs_upper: false,
374 cs_digits: true,
375 cs_special: false,
376 charset_input,
377 len_min_input,
378 len_max_input,
379 rainbow_input,
380 deauth_input,
381 label_input,
382 log_input,
383 rules_input,
384 strength_input,
385 hyb_min_input,
386 hyb_max_input,
387 freq_order: true,
388 bench_running: false,
389 import_busy: false,
390 deauth_all_targets: 0,
391 // Mock mode is hermetic: it must never read the user's real
392 // on-disk state (labels, captures, profiles) — it exists for
393 // development and screenshots, and showing real network names
394 // there defeats the point.
395 profiles: if is_mock {
396 crate::store::Profiles::default()
397 } else {
398 match crate::store::load_profiles() {
399 Ok(p) => p,
400 Err(e) => {
401 eprintln!("profiles: load failed, starting empty: {e:#}");
402 crate::store::Profiles::default()
403 }
404 }
405 },
406 };
407 if !is_mock {
408 match crate::store::load() {
409 Ok(labels) => {
410 let n = labels.len();
411 this.state.labels = labels;
412 this.state
413 .push_log(format!("labels: {n} loaded from ~/wifi_lab/labels.json"));
414 }
415 Err(e) => this
416 .state
417 .push_log(format!("labels: load failed, starting empty: {e:#}")),
418 }
419 }
420 // Restore previous captures so the cracker can keep working across
421 // restarts without re-running attacks.
422 if !is_mock {
423 match crate::store::load_captures() {
424 Ok(caps) => {
425 let n = caps.len();
426 for cap in caps {
427 match cap {
428 crate::store::StoredCapture::Handshake(h) => {
429 // Route restored partials through the
430 // partial path so they land in
431 // `state.partials` with the [partial]
432 // picker marker (append-only restore keeps
433 // stored index order).
434 if h.partial {
435 this.state.apply(Event::HandshakePartial(Box::new(h)));
436 } else {
437 this.state.apply(Event::HandshakeComplete(Box::new(h)));
438 }
439 }
440 crate::store::StoredCapture::Pmkid(p) => {
441 this.state.apply(Event::PmkidCaptured(p));
442 }
443 }
444 }
445 if n > 0 {
446 this.state.push_log(format!(
447 "captures: {n} restored from ~/wifi_lab/captures.jsonl"
448 ));
449 }
450 }
451 Err(e) => this
452 .state
453 .push_log(format!("captures: restore failed: {e:#}")),
454 }
455 }
456 this.rebuild_target_select(cx);
457 if !is_mock {
458 this.restore_crack_session();
459 }
460 this.state.push_log(if is_mock {
461 "wifi_lab UI started (mock backend)".to_string()
462 } else {
463 format!(
464 "wifi_lab UI started (REAL backend, iface {selected_iface}) — Start capture spawns the privileged service (polkit) and brings up monitor mode"
465 )
466 });
467
468 cx.on_release(|this, _cx| {
469 // Window closed → root view released → stop UI-process jobs
470 // (crack + rainbow build) and shut the service down (it stops
471 // workers, restores managed mode, exits).
472 for flag in [this.crack_stop.take(), this.rainbow_stop.take()]
473 .into_iter()
474 .flatten()
475 {
476 flag.store(true, Ordering::Relaxed);
477 }
478 if let Some(svc) = this.service.take() {
479 svc.shutdown();
480 }
481 })
482 .detach();
483
484 if !this.is_root && !this.is_mock {
485 cx.toast("not root — polkit will ask for authentication when you start capture")
486 .show(window, cx);
487 }
488
489 // Poll the service event channel: wait on the background executor,
490 // then reduce everything queued into state on the main thread. The
491 // service reader thread never touches gpui types.
492 cx.spawn(async move |this, cx| {
493 loop {
494 cx.background_executor().timer(EVENT_POLL).await;
495 match this.update(cx, |app, cx| app.drain_events(cx)) {
496 Ok(()) => {}
497 // Entity gone (window closed) — stop polling.
498 Err(_) => break,
499 }
500 }
501 })
502 .detach();
503
504 window.focus(&this.focus_handle, cx);
505 this
506 }
507
508 /// Header "Start/Stop capture" behaviour.
509 ///
510 /// Real mode: lazily spawn the privileged service (polkit-elevated
511 /// when needed) which switches the interface to monitor mode and runs
512 /// the scanner; Stop only ends the scan session — the service stays
513 /// alive for the cracker page and later scans. Mock mode: pure UI
514 /// flips (the mock generator runs independently).
515 pub fn toggle_monitor(&mut self, cx: &mut Context<Self>) {
516 if self.is_mock {
517 self.state.iface_running = !self.state.iface_running;
518 let on = self.state.iface_running;
519 self.state.push_log(format!(
520 "iface {}: monitor mode {} (mock)",
521 self.state.ifname,
522 if on { "on" } else { "off" }
523 ));
524 cx.notify();
525 return;
526 }
527 if self.state.iface_running {
528 // STOP: end the scan session but KEEP the service alive — the
529 // cracker needs it, and a later Start reuses it.
530 if let Some(svc) = &self.service {
531 self.state
532 .push_log("ui: stopping capture, service restores managed mode…");
533 svc.stop_scan();
534 }
535 // Stopping also kills every attack worker — un-spin buttons.
536 self.state.iface_running = false;
537 self.parked_channels = None;
538 self.attacking_handshake = false;
539 self.attacking_pmkid = false;
540 cx.notify();
541 } else {
542 // NetworkManager fight: pin-to-connected-channel makes ONLY the
543 // associated network (e.g. testnet) visible during the hop.
544 if crate::iface::networkmanager_active() {
545 self.nm_active = true;
546 self.state.push_log(
547 "ui: WARNING NetworkManager is active — it pins the card to the connected \
548 network's channel; you will likely see ONLY that SSID. Use \"Stop NM\" in the header."
549 .to_string(),
550 );
551 self.queue_toast(
552 "NetworkManager is active — only your connected network may be visible; stop it from the header",
553 );
554 }
555 let ifname = self.state.ifname.clone();
556 if let Some(svc) = &self.service {
557 // Service already up (from an earlier session): just ask
558 // for a fresh scan session.
559 svc.cmd(&Cmd::StartScan {
560 ifname: ifname.clone(),
561 channels: None,
562 spool: Some(crate::store::data_dir().join("spool.pcap")),
563 fresh_spool: true,
564 });
565 self.state.iface_running = true;
566 self.parked_channels = None;
567 self.state
568 .push_log(format!("ui: capture started on {ifname}"));
569 cx.notify();
570 return;
571 }
572 match ServiceClient::start(&ifname, self.tx.clone()) {
573 Ok(svc) => {
574 self.service = Some(svc);
575 self.state.iface_running = true;
576 self.state
577 .push_log(format!("ui: capture started on {ifname}"));
578 }
579 Err(e) => {
580 self.state
581 .push_log(format!("ERROR: start capture on {ifname}: {e:#}"));
582 self.queue_toast(format!("start capture failed: {e:#}"));
583 }
584 }
585 cx.notify();
586 }
587 }
588
589 /// Stop NetworkManager via the privileged service so it stops pinning
590 /// the radio to the connected network's channel.
591 pub fn stop_nm(&mut self, cx: &mut Context<Self>) {
592 match &self.service {
593 Some(svc) => {
594 svc.cmd(&Cmd::StopNetworkManager);
595 self.state
596 .push_log("ui: asking service to stop NetworkManager…");
597 }
598 None => {
599 self.state.push_log(
600 "ui: NM stop needs the privileged service — Start capture first".to_string(),
601 );
602 }
603 }
604 cx.notify();
605 }
606
607 /// Queue a toast for the next render pass (the event loop has no
608 /// Window). Capped at 3 — oldest dropped first.
609 pub fn queue_toast(&mut self, msg: impl Into<SharedString>) {
610 if self.pending_toast.len() == 3 {
611 self.pending_toast.pop_front();
612 }
613 self.pending_toast
614 .push_back(wrap_toast_text(&msg.into()).into());
615 }
616
617 /// Drain every queued event, track handshake progress, refresh widgets
618 /// derived from the capture set.
619 fn drain_events(&mut self, cx: &mut Context<Self>) {
620 let mut changed = false;
621 let mut captures_changed = false;
622 while let Ok(event) = self.rx.try_recv() {
623 changed = true;
624 match &event {
625 Event::HandshakeProgress { ap, client, have } => {
626 self.hs_progress.insert((*ap, *client), *have);
627 }
628 Event::HandshakeComplete(cap) => {
629 self.hs_progress.remove(&(cap.ap, cap.client));
630 self.attacking_handshake = false;
631 // Mock captures are fabrications — never write them into
632 // the real capture store.
633 if !self.is_mock
634 && let Err(e) = crate::store::append_capture(
635 &crate::store::StoredCapture::Handshake(cap.as_ref().clone()),
636 )
637 {
638 self.state.push_log(format!("capture save FAILED: {e:#}"));
639 }
640 }
641 Event::HandshakePartial(cap) => {
642 self.hs_progress.remove(&(cap.ap, cap.client));
643 self.attacking_handshake = false;
644 // Partial M2+M3 material is hashcat-exportable crack
645 // material — persist it exactly like a complete
646 // capture (the `partial` flag rides serde).
647 if !self.is_mock
648 && let Err(e) = crate::store::append_capture(
649 &crate::store::StoredCapture::Handshake(cap.as_ref().clone()),
650 )
651 {
652 self.state.push_log(format!("capture save FAILED: {e:#}"));
653 }
654 }
655 Event::PmkidCaptured(cap) => {
656 self.attacking_pmkid = false;
657 if !self.is_mock
658 && let Err(e) = crate::store::append_capture(
659 &crate::store::StoredCapture::Pmkid(cap.clone()),
660 )
661 {
662 self.state.push_log(format!("capture save FAILED: {e:#}"));
663 }
664 }
665 // Service child died (EOF seen by the reader thread):
666 // un-flip every running flag and drop the client so the
667 // next Start spawns a fresh, alive service.
668 Event::Error(line) if line == "service terminated" => {
669 self.attacking_handshake = false;
670 self.attacking_pmkid = false;
671 self.state.iface_running = false;
672 // Crack jobs are independent UI-process threads —
673 // `state.cracker.running` stays as the worker left it.
674 if let Some(svc) = self.service.take() {
675 svc.shutdown(); // reaps the corpse, restores iface
676 }
677 }
678 // Any worker error, or a terminal log from an attack
679 // worker (prefixed by the service; scanner logs are
680 // excluded), un-spins attack buttons so the UI is never
681 // stuck "working…".
682 Event::Error(_) => {
683 self.attacking_handshake = false;
684 self.attacking_pmkid = false;
685 }
686 // Terminal attack-worker log lines un-spin the buttons.
687 // NOT a generic prefix match: "handshake: listening for
688 // 4-way…" fires right at worker start and would instantly
689 // kill the spinner while the worker runs.
690 Event::Log(line)
691 if line.starts_with("handshake: capture ended")
692 || line.starts_with("pmkid: no PMKID") =>
693 {
694 self.attacking_handshake = false;
695 self.attacking_pmkid = false;
696 }
697 // Service-side NM result: `nm: stopped` / `nm: stop failed …`.
698 Event::Log(line) if line.starts_with("nm:") => {
699 if line == "nm: stopped" {
700 self.nm_active = false;
701 self.queue_toast(
702 "NetworkManager stopped — all networks become visible as the hopper cycles",
703 );
704 }
705 }
706 Event::CrackProgress { .. } => {
707 self.maybe_save_crack_session();
708 }
709 Event::CrackStopped { found } => {
710 self.crack_stop = None;
711 self.finalize_crack_session(*found);
712 }
713 // Backend failure (GPU lost, dispatch timeout, worker
714 // panic): settle like a user-stop with room left — save
715 // the resume position and arm the banner — but NEVER
716 // clear the saved session; the run is resumable. The
717 // AppState side (log line, running=false, activity
718 // mirror) happens in `apply` below.
719 Event::CrackError { .. } => {
720 self.crack_stop = None;
721 self.last_session_save = Instant::now();
722 self.save_crack_session();
723 self.state.cracker.active_attack = None;
724 }
725 Event::RainbowBuilt { .. } => {
726 self.rainbow_stop = None;
727 }
728 Event::CrackFound { password } => {
729 self.queue_toast(format!("password recovered: {password}"));
730 // Best-effort desktop notification; headless/no-D-Bus
731 // just drops the error.
732 let _ = notify_rust::Notification::new()
733 .summary("wifi_lab: password found")
734 .body(&format!("password recovered: {password}"))
735 .show();
736 }
737 Event::CaptureImported(cap) if !self.is_mock => {
738 let stored = match cap {
739 crate::common::ImportedCapture::Handshake(h) => {
740 crate::store::StoredCapture::Handshake(h.as_ref().clone())
741 }
742 crate::common::ImportedCapture::Pmkid(p) => {
743 crate::store::StoredCapture::Pmkid(p.clone())
744 }
745 };
746 if let Err(e) = crate::store::append_capture(&stored) {
747 self.state
748 .push_log(format!("import: capture save FAILED: {e:#}"));
749 }
750 }
751 Event::BenchmarkDone { .. } => {
752 self.bench_running = false;
753 }
754 _ => {}
755 }
756 captures_changed |= self.state.apply(event);
757 if let Some(m) = self.state.deauth_alert.take() {
758 self.queue_toast(m);
759 }
760 if let Some(m) = self.state.rogue_alert.take() {
761 self.queue_toast(m);
762 }
763 if let Some(m) = self.state.ident_alert.take() {
764 self.queue_toast(m);
765 }
766 }
767 // Stale-client backstop sweep, ONCE per drain tick (not per
768 // event — the per-event form allocated a full `clients` snapshot
769 // at 10 Hz+ probe volumes). 100 ms cadence is far tighter than
770 // the 60 s expiry, so ClientLost-equivalent removal stays
771 // observably identical.
772 self.state.sweep_stale_clients();
773 // Keep the target snapshot in lockstep with the live AP row (a
774 // click-time-only snapshot goes stale: channel jumps, beacon
775 // counts, security updates). Also self-heals after service
776 // restarts, when only the live row exists.
777 if let Some(live) = self.selected.and_then(|b| self.state.aps.get(&b).cloned()) {
778 self.selected_ap = Some(live);
779 }
780 // Mock-only convenience: pre-select the first heard AP so the
781 // Attacks page shows its target card without a manual click —
782 // invaluable for headless UI verification. Never in real mode.
783 if self.is_mock
784 && self.selected.is_none()
785 && let Some((&b, _)) = self.state.aps.first_key_value()
786 {
787 self.selected = Some(b);
788 self.selected_ap = self.state.aps.get(&b).cloned();
789 }
790 if captures_changed {
791 self.rebuild_target_select(cx);
792 }
793 if changed {
794 cx.notify();
795 }
796 }
797
798 /// Persist the interrupted crack run (resume file), throttled to one
799 /// write per 2 s of progress events. UI-thread only (called from the
800 /// event drain).
801 fn maybe_save_crack_session(&mut self) {
802 if self.last_session_save.elapsed() < Duration::from_secs(2) {
803 return;
804 }
805 self.last_session_save = Instant::now();
806 self.save_crack_session();
807 }
808
809 /// Write the current run to ~/wifi_lab/crack-session.json. No-op when
810 /// nothing resumable is in flight (mock runs never persist).
811 fn save_crack_session(&mut self) {
812 let (Some(attack), Some(idx)) = (
813 self.state.cracker.active_attack.clone(),
814 self.state.cracker.target,
815 ) else {
816 return;
817 };
818 let done = self.state.cracker.tried;
819 if done == 0 {
820 return;
821 }
822 // The target is already the capture index — no description-string
823 // round trip (a rebuilt index space would never mis-key the run).
824 let Some(capture) = self.state.stored_capture_at(idx) else {
825 return;
826 };
827 let total = self.state.cracker.total;
828 let session = crate::store::CrackSession::new(capture, attack, done, total);
829 if let Err(e) = crate::store::save_session(&session) {
830 self.state
831 .push_log(format!("cracker: session save failed: {e:#}"));
832 return;
833 }
834 // The just-saved run is resumable right now (same session or the
835 // next start): keep the banner in sync.
836 let target_desc = self
837 .state
838 .capture_descs()
839 .into_iter()
840 .nth(idx)
841 .unwrap_or_default();
842 self.state.cracker.resume = Some(crate::ui::state::ResumeInfo {
843 target_idx: idx,
844 target_desc,
845 attack: session.attack,
846 done,
847 total,
848 });
849 }
850
851 /// Settle the session file when a run ends: found/exhausted → delete
852 /// (nothing left to resume); stopped mid-way → final save + banner.
853 fn finalize_crack_session(&mut self, found: bool) {
854 let done = self.state.cracker.tried;
855 let total = self.state.cracker.total;
856 let exhausted = !found && total.is_some_and(|t| done >= t);
857 if found || exhausted {
858 if let Err(e) = crate::store::clear_session() {
859 self.state
860 .push_log(format!("cracker: session clear failed: {e:#}"));
861 }
862 self.state.cracker.resume = None;
863 } else if self.state.cracker.active_attack.is_some() {
864 // User-stopped (or worker-ended) with room left: persist the
865 // position — this is the whole point of the feature.
866 self.last_session_save = Instant::now();
867 self.save_crack_session();
868 }
869 self.state.cracker.active_attack = None;
870 }
871
872 /// Match a saved session against the loaded captures on startup:
873 /// a match arms the resume banner on the cracker page.
874 fn restore_crack_session(&mut self) {
875 let session = match crate::store::load_session() {
876 Ok(Some(s)) => s,
877 Ok(None) => return,
878 Err(e) => {
879 self.state
880 .push_log(format!("cracker: saved session unreadable: {e:#}"));
881 return;
882 }
883 };
884 let descs = self.state.capture_descs();
885 let hit = descs
886 .iter()
887 .enumerate()
888 .find(|(i, _)| self.state.stored_capture_at(*i).as_ref() == Some(&session.capture));
889 match hit {
890 Some((idx, d)) => {
891 let done = session.done;
892 self.state.cracker.resume = Some(crate::ui::state::ResumeInfo {
893 target_idx: idx,
894 target_desc: d.clone(),
895 attack: session.attack,
896 done,
897 total: session.total,
898 });
899 self.state.push_log(format!(
900 "cracker: resumable saved run restored ({d}, {done} tried)"
901 ));
902 }
903 None => self
904 .state
905 .push_log("cracker: saved session ignored — its capture is gone".to_string()),
906 }
907 }
908
909 /// The cracker target dropdown mirrors `state.capture_descs()`; the
910 /// option VALUES are the stable capture indices (the description
911 /// strings are labels only, so selection never keys on regenerated
912 /// display text). Indices are append-only (`capture_descs` is
913 /// arrival-ordered), so a live selection survives new captures
914 /// arriving mid-run. With no captures the select is disabled so its
915 /// (empty) popup cannot open.
916 pub fn rebuild_target_select(&mut self, cx: &mut Context<Self>) {
917 let descs = self.state.capture_descs();
918 let n = descs.len();
919 // Keep the current choice while its index is still in range.
920 let keep = self.state.cracker.target.take().filter(|&i| i < n);
921 let view = cx.entity();
922 let mut builder = select(
923 "cracker-target",
924 "Crack target",
925 descs.into_iter().enumerate().collect::<Vec<_>>(),
926 )
927 .placeholder(if n == 0 {
928 "no captures yet — capture a handshake or PMKID first"
929 } else {
930 "Select a capture…"
931 })
932 .disabled(n == 0)
933 .on_change(move |idx, _window, cx| {
934 view.update(cx, |app, cx| {
935 app.state.cracker.target = Some(idx);
936 cx.notify();
937 });
938 });
939 if let Some(cur) = keep {
940 builder = builder.selected(cur);
941 self.state.cracker.target = Some(cur);
942 }
943 self.target_select = cx.new(|_cx| SelectState::new(builder));
944 }
945
946 /// Keyboard page switch (ctrl-1..4) — the same destination set the
947 /// nav-rail clicks use.
948 fn show_page(&mut self, page: Page, cx: &mut Context<Self>) {
949 self.page = page;
950 cx.notify();
951 }
952
953 fn nav_item(&self, page: Page, view: &Entity<AppRoot>, cx: &App) -> gpui::Stateful<gpui::Div> {
954 let theme = cx.theme().clone();
955 let active = self.page == page;
956 let view = view.clone();
957 div()
958 .id(ElementKey::Nav(page as u8).id())
959 .px_3()
960 .py_2()
961 .rounded_md()
962 .cursor_pointer()
963 .when(active, |el| el.bg(theme.accent_bg()))
964 .when(!active, |el| {
965 let hover = theme.accent_bg().alpha(0.35);
966 el.hover(move |style| style.bg(hover))
967 })
968 .text_sm()
969 .child(page.label())
970 .on_click(move |_, _window, cx| {
971 view.update(cx, |app, cx| {
972 app.page = page;
973 cx.notify();
974 });
975 })
976 }
977
978 fn header(&self, view: &Entity<AppRoot>, cx: &App) -> gpui::Div {
979 let theme = cx.theme().clone();
980 let running = self.state.iface_running;
981
982 // Status of the SERVICE process (the thing that actually touches
983 // the radio): any running service is root — spawned directly when
984 // the UI is root, via pkexec (root by definition) otherwise.
985 let privilege = if self.is_mock {
986 badge("not root (mock)").secondary()
987 } else if self.service.is_some() {
988 badge("service: root").secondary()
989 } else if self.is_root {
990 badge("ui: root · service not started").secondary()
991 } else {
992 badge("ui: user · service not started").secondary()
993 };
994
995 let toggle = button(
996 "monitor-toggle",
997 if running {
998 "Stop capture"
999 } else if self.is_mock {
1000 "Start capture (mock)"
1001 } else {
1002 "Start capture (monitor)"
1003 },
1004 )
1005 // Stopping capture (or starting a new one) while a crack streams
1006 // would kill the crack job: radio access is exclusive.
1007 .disabled(!self.is_mock && self.state.cracker.running)
1008 .on_click({
1009 let view = view.clone();
1010 move |_, _window, cx| {
1011 view.update(cx, |app, cx| app.toggle_monitor(cx));
1012 }
1013 });
1014
1015 let nm_badge = (self.nm_active && !self.is_mock)
1016 .then(|| badge("NM active — channels pinned").destructive());
1017 let nm_btn = (self.nm_active && !self.is_mock).then(|| {
1018 button("stop-nm", "Stop NM").on_click({
1019 let view = view.clone();
1020 move |_, _window, cx| {
1021 view.update(cx, |app, cx| app.stop_nm(cx));
1022 }
1023 })
1024 });
1025
1026 h_stack()
1027 .w_full()
1028 .px_4()
1029 .py_2()
1030 .gap_3()
1031 .items_center()
1032 .border_b_1()
1033 .border_color(theme.border())
1034 .bg(theme.surface())
1035 .child(
1036 div()
1037 .text_lg()
1038 .font_weight(FontWeight::BOLD)
1039 .child("wifi_lab"),
1040 )
1041 .child(privilege)
1042 .child(div().w(px(220.)).child(self.iface_select.clone()))
1043 .children(nm_badge)
1044 .children(nm_btn)
1045 .child(toggle)
1046 .child(div().flex_1())
1047 .child(
1048 div()
1049 .text_xs()
1050 .text_color(theme.fg_muted())
1051 .child(SharedString::from(format!(
1052 "channel hopper active · {}",
1053 self.state.ifname
1054 ))),
1055 )
1056 }
1057
1058 fn status_line(&self, cx: &App) -> gpui::Div {
1059 let theme = cx.theme().clone();
1060 div()
1061 .w_full()
1062 .px_4()
1063 .py_1()
1064 .border_t_1()
1065 .border_color(theme.border())
1066 .bg(theme.surface())
1067 .text_xs()
1068 .text_color(theme.fg_muted())
1069 .child(format!(
1070 "{} APs · {} clients · {} handshakes · {} PMKIDs · {} · capture {} · {}",
1071 self.state.aps.len(),
1072 self.state.clients.len(),
1073 self.state.handshakes.len(),
1074 self.state.pmkids.len(),
1075 self.state.ifname,
1076 if self.state.iface_running {
1077 "running"
1078 } else {
1079 "stopped"
1080 },
1081 if self.is_mock { "MOCK DATA" } else { "LIVE" }
1082 ))
1083 }
1084}
1085
1086/// Stable element ids that aren't string keys.
1087enum ElementKey {
1088 Nav(u8),
1089}
1090
1091impl ElementKey {
1092 fn id(self) -> SharedString {
1093 match self {
1094 ElementKey::Nav(n) => SharedString::from(format!("nav-{n}")),
1095 }
1096 }
1097}
1098
1099impl Render for AppRoot {
1100 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1101 let theme = cx.theme().clone();
1102 let view = cx.entity();
1103
1104 // Flush toasts queued by the event-drain loop (which has no Window).
1105 while let Some(msg) = self.pending_toast.pop_front() {
1106 cx.toast(msg).show(_window, cx);
1107 }
1108
1109 let nav = v_stack()
1110 .w(px(170.))
1111 .h_full()
1112 .gap_1()
1113 .p_2()
1114 .border_r_1()
1115 .border_color(theme.border())
1116 .bg(theme.surface_secondary())
1117 .children(
1118 Page::ALL
1119 .into_iter()
1120 .map(|page| self.nav_item(page, &view, cx)),
1121 );
1122
1123 let content = match self.page {
1124 Page::Networks => networks::render(self, &view, _window, cx),
1125 Page::Attacks => attacks::render(self, &view, _window, cx),
1126 Page::Cracker => cracker::render(self, &view, _window, cx),
1127 Page::Log => log_view::render(self, &view, _window, cx),
1128 };
1129
1130 // Window-level shortcuts (see [`bind_app_keys`]): handlers on the
1131 // root div catch the actions wherever focus sits inside the
1132 // window; `.track_focus` keeps the startup focus on the root.
1133 div()
1134 .flex()
1135 .size_full()
1136 .track_focus(&self.focus_handle)
1137 .on_action(cx.listener(|_this, _: &QuitApp, _window, cx| cx.quit()))
1138 .on_action(cx.listener(|this, _: &ShowNetworksPage, _window, cx| {
1139 this.show_page(Page::Networks, cx);
1140 }))
1141 .on_action(cx.listener(|this, _: &ShowAttacksPage, _window, cx| {
1142 this.show_page(Page::Attacks, cx);
1143 }))
1144 .on_action(cx.listener(|this, _: &ShowCrackerPage, _window, cx| {
1145 this.show_page(Page::Cracker, cx);
1146 }))
1147 .on_action(cx.listener(|this, _: &ShowLogPage, _window, cx| {
1148 this.show_page(Page::Log, cx);
1149 }))
1150 .bg(theme.bg())
1151 .text_color(theme.fg())
1152 .child(nav)
1153 .child(
1154 v_stack()
1155 .flex_1()
1156 .h_full()
1157 .min_w_0()
1158 .child(self.header(&view, cx))
1159 .child(div().flex_1().min_h_0().child(content))
1160 .child(self.status_line(cx)),
1161 )
1162 // Toast overlay lives at the root so it floats over any page.
1163 .child(cx.toast_manager().clone())
1164 }
1165}
1166#[cfg(test)]
1167mod tests {
1168 use super::wrap_toast_text;
1169
1170 #[test]
1171 fn toast_wrap_keeps_lines_within_box() {
1172 let msg = "DEAUTH STORM: aa:bb:cc:dd:ee:ff → ff:ff:ff:ff:ff:ff x64";
1173 let wrapped = wrap_toast_text(msg);
1174 assert!(
1175 wrapped.lines().all(|l| l.chars().count() <= 36),
1176 "line over toast width:\n{wrapped}"
1177 );
1178 // Same words, same order — wrapping only inserts breaks.
1179 assert_eq!(
1180 wrapped.split_whitespace().collect::<Vec<_>>(),
1181 msg.split_whitespace().collect::<Vec<_>>()
1182 );
1183 }
1184
1185 #[test]
1186 fn toast_wrap_splits_unbreakable_tokens() {
1187 let long = format!("error: couldn't open {}", "/very/long/path/".repeat(4));
1188 for line in wrap_toast_text(&long).lines() {
1189 assert!(line.chars().count() <= 36, "overlong line: {line:?}");
1190 }
1191 }
1192
1193 #[test]
1194 fn toast_wrap_leaves_short_messages_alone() {
1195 let msg = "captures: 3 restored";
1196 assert_eq!(wrap_toast_text(msg), msg);
1197 }
1198}