forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

service.rs1314 lines, 52.3 KiBHistoryRawDownload
1//! Privileged service + UI-side client, replacing the old monolithic
2//! `Backend`.
3//!
4//! Architecture: the UI process never needs root. All radio work runs in a
5//! privileged SERVICE — the same binary re-spawned as a child with the
6//! hidden flag `--privileged-worker` (directly when the UI is already root,
7//! via `pkexec` otherwise). The two halves speak JSON lines: `Cmd` on the
8//! child's stdin, `Event` on its stdout (stdout is reserved EXCLUSIVELY for
9//! events; diagnostics go to stderr).
10//!
11//! Concurrency notes (service side):
12//! - The scanner and any attack worker can coexist (deauth while capturing
13//! is the whole point). They arbitrate the RF channel through ONE shared
14//! [`iface::ChannelPin`]: the capture worker holds it for its target
15//! band, a deauth worker briefly overrides it per band and settles back
16//! afterwards, and the scanner dwells on the pinned frequency instead of
17//! hopping. Attack workers open their OWN [`RawSocket`] on the monitor
18//! interface; concurrent attacks should target the SAME network — this
19//! matches the UI, which implies a single target.
20//! - `to_monitor` may create a `<orig>mon` vif; the actual monitor ifname
21//! is remembered and passed to [`iface::to_managed`] on stop/shutdown
22//! (it deletes the vif or flips the interface back, as appropriate).
23
24use std::io::{BufRead, BufReader, Write};
25use std::process::{Child, ChildStdin, Command, Stdio};
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::sync::{Arc, Mutex};
28use std::thread::JoinHandle;
29use std::time::{Duration, Instant};
30
31use anyhow::{Context, Result, bail};
32use crossbeam_channel::Sender;
33
34use crate::common::{Cmd, Event, MacAddr};
35use crate::rawsock::RawSocket;
36use crate::{deauth, dot11, handshake, iface, pmkid, radiotap, scanner};
37
38/// Exact banner the service prints on stdout before any event line. The
39/// client prefix-matches lines against this while waiting (pkexec may
40/// prepend its own chatter).
41pub const READY_LINE: &str = "WIFI_LAB-SVC-READY";
42
43/// How long the client waits for the service's READY banner (the polkit
44/// dialog can block on a slow human).
45const READY_TIMEOUT: Duration = Duration::from_secs(60);
46
47fn send(tx: &Sender<Event>, ev: Event) {
48 let _ = tx.send(ev);
49}
50
51fn log(tx: &Sender<Event>, msg: impl Into<String>) {
52 send(tx, Event::Log(msg.into()));
53}
54
55fn log_err(tx: &Sender<Event>, msg: impl Into<String>) {
56 send(tx, Event::Error(msg.into()));
57}
58
59/// Byte-count-bounded truncation that NEVER straddles a multi-byte UTF-8
60/// character: a naive `&s[..s.len().min(n)]` PANICS when byte `n` lands
61/// inside a multi-byte char — a UTF-8 garbage command line or a UTF-8
62/// ESSID in a malformed event line would kill the privileged service's
63/// command loop (interface left in monitor mode) or the UI's reader
64/// thread respectively.
65fn truncate_utf8(s: &str, max: usize) -> &str {
66 if s.len() <= max {
67 return s;
68 }
69 let mut end = max;
70 while !s.is_char_boundary(end) {
71 end -= 1;
72 }
73 &s[..end]
74}
75
76/// Human-readable content of a panic payload (`catch_unwind`/`join` Err).
77fn panic_message(payload: &(dyn std::any::Any + Send + 'static)) -> String {
78 if let Some(s) = payload.downcast_ref::<&str>() {
79 (*s).to_string()
80 } else if let Some(s) = payload.downcast_ref::<String>() {
81 s.clone()
82 } else {
83 "<non-string panic payload>".to_string()
84 }
85}
86
87/// Join one worker handle; a panic inside the worker must surface on the
88/// event pipe instead of dying silently (the UI otherwise waits forever
89/// on a "running" job whose thread is gone).
90fn join_worker(h: JoinHandle<()>, tx: &Sender<Event>, what: &str) {
91 if let Err(payload) = h.join() {
92 log_err(
93 tx,
94 format!(
95 "{what}: worker thread panicked: {}",
96 panic_message(&*payload)
97 ),
98 );
99 }
100}
101
102/// RAII release of a [`iface::ChannelPin::hold`] — the capture worker's
103/// channel hold is released on EVERY worker exit path (normal, error,
104/// early return), never leaving the scanner pinned forever.
105struct PinGuard {
106 pin: Arc<iface::ChannelPin>,
107 mhz: u16,
108}
109
110impl Drop for PinGuard {
111 fn drop(&mut self) {
112 self.pin.release(self.mhz);
113 }
114}
115
116/// Wildcard-probe canary: broadcast probe requests on `mon` (already
117/// tuned to the channel it will work on) and look for ANY probe response
118/// (mgmt subtype 5) on the air. Why this exists: mt76/mt7921e's
119/// monitor-TX path wedges silently — `send()` succeeds and RX stays
120/// perfectly healthy (scans look normal), but injected frames never
121/// radiate until the driver is reloaded (verified on the lab MT7922: 0
122/// probe responses when wedged, 7 after `modprobe -r mt7921e` + reload).
123/// ~1.2 s; Ok(false) = wedge detected, Err = canary itself inconclusive.
124fn injection_canary(mon: &str) -> Result<bool> {
125 let sock = RawSocket::open(mon).context("canary socket")?;
126 sock.set_timeout(100)?;
127 let sa = iface::mac_of(mon)?;
128 let mut frame = radiotap::INJECT_HDR.to_vec();
129 frame.extend_from_slice(&dot11::build_probe_req(&[], &sa));
130 let mut buf = [0u8; crate::rawsock::RECV_BUFSZ];
131 let deadline = Instant::now() + Duration::from_millis(1200);
132 // ~10 probes across the window. A send() error is a SOCKET-level
133 // failure (ENXIO/ENODEV: interface gone, ring broken) — the exact
134 // opposite of the silent wedge (send succeeds, nothing radiates), so
135 // it must abort WITH the error, letting the caller report instead of
136 // reloading a driver that was never at fault.
137 while Instant::now() < deadline {
138 let n = sock
139 .send(&frame)
140 .context("canary send failed (socket-level TX error — not a driver wedge)")?;
141 debug_assert!(n == frame.len(), "short canary send: {n} bytes");
142 match sock.recv_msg(&mut buf) {
143 // A truncated frame is never a valid probe response.
144 Ok(m) if !m.truncated() && is_probe_response(&buf[..m.len]) => return Ok(true),
145 Ok(_) => {}
146 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
147 Err(e) => return Err(e).context("canary recv"),
148 }
149 }
150 Ok(false)
151}
152
153/// radiotap-wrapped 802.11 frame → is it a probe response (mgmt, st 5)?
154fn is_probe_response(f: &[u8]) -> bool {
155 let Some(rt_len) = f
156 .get(2..4)
157 .map(|b| u16::from_le_bytes([b[0], b[1]]) as usize)
158 else {
159 return false;
160 };
161 let Some(fc) = f
162 .get(rt_len..rt_len + 2)
163 .map(|b| u16::from_le_bytes([b[0], b[1]]))
164 else {
165 return false;
166 };
167 (fc >> 2) & 3 == 0 && (fc >> 4) & 0xF == 5
168}
169
170// ---------------------------------------------------------------------------
171// Privileged half — runs as the `--privileged-worker` child process.
172// ---------------------------------------------------------------------------
173
174/// Radio-side state owned by the service process. Mirrors the old
175/// `Backend` minus the cracker (which moved into the UI process).
176struct RadioService {
177 stop: Arc<AtomicBool>,
178 handles: Mutex<Vec<JoinHandle<()>>>,
179 /// Name of the interface currently in monitor mode (`None` if the
180 /// mode switch failed at StartScan — nothing to restore then).
181 mon_ifname: Option<String>,
182 /// Interface the UI asked for; restored to managed mode on stop/
183 /// shutdown when it differs from `mon_ifname`.
184 orig_ifname: Option<String>,
185 /// Event pipe: the forwarder thread owns the receiving end and
186 /// serializes one JSON line per event onto stdout.
187 tx: Sender<Event>,
188 /// Channel arbitration shared with the scanner (see
189 /// [`iface::ChannelPin`]): capture workers hold it, deauth briefly
190 /// overrides it, the scanner dwells on it instead of hopping.
191 pin: Arc<iface::ChannelPin>,
192 /// BSSIDs of APs we are actively deauthenticating: the scanner's
193 /// foreign-deauth detector suppresses frames sourced from these (our
194 /// blasts carry the AP's BSSID as transmitter).
195 deauth_suppress: Arc<Mutex<std::collections::HashSet<MacAddr>>>,
196 /// Live pcap spool: `(path, shared writer)`. The writer is reused
197 /// across scans while the path matches and `fresh_spool` is unset.
198 spool: Option<(std::path::PathBuf, Arc<Mutex<crate::pcapout::PcapWriter>>)>,
199 /// Set when this session stopped NetworkManager — shutdown restarts
200 /// it (best-effort) so the box is left the way we found it.
201 stopped_nm: Arc<AtomicBool>,
202}
203
204impl RadioService {
205 fn new(tx: Sender<Event>) -> Self {
206 RadioService {
207 stop: Arc::new(AtomicBool::new(false)),
208 handles: Mutex::new(Vec::new()),
209 mon_ifname: None,
210 orig_ifname: None,
211 tx,
212 pin: Arc::new(iface::ChannelPin::default()),
213 deauth_suppress: Arc::new(Mutex::new(std::collections::HashSet::new())),
214 spool: None,
215 stopped_nm: Arc::new(AtomicBool::new(false)),
216 }
217 }
218
219 fn mon(&self) -> Option<String> {
220 self.mon_ifname.clone().or_else(|| self.orig_ifname.clone())
221 }
222
223 /// Verify injected frames actually radiate; on failure reload the
224 /// NIC's driver (the only known cure for the mt76 monitor-TX wedge)
225 /// and recreate the monitor vif. Returns the monitor ifname to use —
226 /// unchanged unless a recovery happened.
227 fn ensure_injection(&self, base: &str, mon: String) -> String {
228 match injection_canary(&mon) {
229 Ok(true) => {
230 log(
231 &self.tx,
232 "injection canary: probe responses seen — TX path OK",
233 );
234 mon
235 }
236 Ok(false) => {
237 log_err(
238 &self.tx,
239 format!(
240 "injection canary: NO probe responses on {mon} — injected frames are \
241 NOT radiating (driver TX wedge); reloading the wifi driver"
242 ),
243 );
244 match iface::reset_driver(base).and_then(|_| iface::to_monitor(base)) {
245 Ok(new_mon) => {
246 log(
247 &self.tx,
248 format!(
249 "driver reloaded, monitor vif {new_mon} recreated — re-running canary"
250 ),
251 );
252 match injection_canary(&new_mon) {
253 Ok(true) => log(&self.tx, "injection canary after recovery: OK"),
254 Ok(false) => log_err(
255 &self.tx,
256 "injection STILL dead after driver reload — scanning works but \
257 deauth/PMKID will not; check for a kernel/firmware update",
258 ),
259 Err(e) => log_err(
260 &self.tx,
261 format!("post-recovery canary inconclusive: {e:#}"),
262 ),
263 }
264 new_mon
265 }
266 Err(e) => {
267 log_err(
268 &self.tx,
269 format!(
270 "driver reload recovery failed: {e:#} — keeping {mon}; deauth/PMKID may not work"
271 ),
272 );
273 mon
274 }
275 }
276 }
277 Err(e) => {
278 log(
279 &self.tx,
280 format!("injection canary inconclusive on {mon}: {e:#} — proceeding"),
281 );
282 mon
283 }
284 }
285 }
286
287 /// Switch `ifname` to monitor mode and start the scanner (full hop
288 /// list when `channels` is empty, else parked on the given channels).
289 /// Restart-safe: a running session's workers (scanner AND attacks) are
290 /// stopped first, and the monitor interface is reused when it's
291 /// already up for the same `ifname`. On any failure an [`Event::Error`]
292 /// is emitted, the interface is put back into managed mode (best
293 /// effort).
294 fn start_scan(
295 &mut self,
296 ifname: &str,
297 channels: &[u8],
298 spool: Option<std::path::PathBuf>,
299 fresh_spool: bool,
300 ) {
301 // Stop the CURRENT worker set first (scanner + attack workers): a
302 // re-StartScan while running must not leak the old scanner thread —
303 // it held the old stop flag and would keep hopping forever,
304 // fighting the new channel plan. When the monitor interface already
305 // exists for the SAME ifname it is reused (no managed↔monitor
306 // churn); only the channel plan/workers change.
307 let reuse_mon = self.orig_ifname.as_deref() == Some(ifname) && self.mon_ifname.is_some();
308 self.stop.store(true, Ordering::Release);
309 let old = std::mem::take(&mut *self.handles.lock().expect("handles poisoned"));
310 let old_tx = self.tx.clone();
311 for h in old {
312 join_worker(h, &old_tx, "previous scan session");
313 }
314 self.stop = Arc::new(AtomicBool::new(false));
315 self.orig_ifname = Some(ifname.to_string());
316
317 // Resolve the spool writer BEFORE workers spawn: same path +
318 // non-fresh reuses the open writer (truncating mid-scan would
319 // interleave frame bytes with the just-rewritten header of the
320 // old handle); a fresh flag or a new path reopens. Failures log
321 // once and the scan simply runs without a spool.
322 let spool_writer: Option<Arc<Mutex<crate::pcapout::PcapWriter>>> = match spool {
323 Some(path) => {
324 let reusable = match &self.spool {
325 Some((p, w)) if !fresh_spool && *p == path => Some(w.clone()),
326 _ => None,
327 };
328 match reusable {
329 Some(w) => {
330 self.spool = Some((path, w.clone()));
331 Some(w)
332 }
333 None => {
334 let opened = if fresh_spool {
335 crate::pcapout::create(&path)
336 } else {
337 crate::pcapout::from_path_append(&path)
338 };
339 match opened {
340 Ok(w) => {
341 let w = Arc::new(Mutex::new(w));
342 self.spool = Some((path, w.clone()));
343 Some(w)
344 }
345 Err(e) => {
346 log_err(
347 &self.tx,
348 format!("pcap spool at {} disabled: {e}", path.display()),
349 );
350 self.spool = None;
351 None
352 }
353 }
354 }
355 }
356 }
357 None => {
358 self.spool = None;
359 None
360 }
361 };
362
363 let mon_ifname = if reuse_mon {
364 self.mon_ifname.clone().expect("reuse_mon ⇒ mon_ifname set")
365 } else {
366 self.mon_ifname = None;
367 match iface::to_monitor(ifname) {
368 Ok(name) => name,
369 Err(e) => {
370 log_err(&self.tx, format!("monitor mode on {ifname} failed: {e:#}"));
371 // Best effort: leave the box the way we found it.
372 let _ = iface::teardown_monitor(ifname);
373 self.orig_ifname = None;
374 return;
375 }
376 }
377 };
378 // Injection canary BEFORE any worker spawns: a wedged TX path
379 // would leave scans healthy while deauth/PMKID silently do
380 // nothing. Recovery (driver reload + vif recreate) swaps the
381 // monitor ifname.
382 let mon_ifname = self.ensure_injection(ifname, mon_ifname);
383 self.mon_ifname = Some(mon_ifname.clone());
384 if reuse_mon {
385 log(
386 &self.tx,
387 format!(
388 "scanner restarted on {mon_ifname} ({} channel(s))",
389 channels.len().max(1)
390 ),
391 );
392 } else {
393 log(
394 &self.tx,
395 format!("monitor mode up on {mon_ifname} (was {ifname})"),
396 );
397 }
398
399 // Own MAC on the monitor vif: deauth frames we transmit never
400 // loop back into the RX path on most cards, but when they do the
401 // storm detector must not cry wolf. Unresolvable → ZERO (matches
402 // nothing real).
403 let own_mac = iface::mac_of(&mon_ifname).unwrap_or(MacAddr::ZERO);
404
405 // Parked-diagnostic channel numbers (2.4/5 GHz) map to frequencies;
406 // empty = full default hop list incl. 6 GHz PSC.
407 let freqs: Vec<u16> = channels
408 .iter()
409 .filter_map(|&ch| crate::common::freq_of_channel(ch))
410 .collect();
411 let cfg = scanner::ScannerConfig {
412 ifname: mon_ifname,
413 freqs,
414 dwell_ms: 100,
415 rssi_floor: -95,
416 pin: self.pin.clone(),
417 own_mac,
418 deauth_suppress: self.deauth_suppress.clone(),
419 spool: spool_writer,
420 };
421 let stop = self.stop.clone();
422 let tx = self.tx.clone();
423 match std::thread::Builder::new()
424 .name("wifi_lab-scanner".into())
425 .spawn(move || {
426 let panic_tx = tx.clone();
427 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
428 if let Err(e) = scanner::run(cfg, tx.clone(), stop) {
429 log_err(&tx, format!("scanner stopped: {e:#}"));
430 }
431 }));
432 if let Err(payload) = r {
433 log_err(
434 &panic_tx,
435 format!(
436 "scanner: worker panicked: {} — scan ended",
437 panic_message(&*payload)
438 ),
439 );
440 }
441 }) {
442 Ok(h) => self.handles.lock().expect("handles poisoned").push(h),
443 Err(e) => {
444 log_err(&self.tx, format!("scanner: spawn failed: {e}"));
445 // Leave the UI consistent: nothing runs but the interface
446 // is in monitor mode — flip it back.
447 if self.mon_ifname.take().is_some()
448 && let Some(orig) = &self.orig_ifname
449 {
450 let _ = iface::teardown_monitor(orig);
451 }
452 }
453 }
454 }
455
456 /// Stop the scanner + all attack workers and restore managed mode.
457 /// The service stays alive for a subsequent StartScan. Idempotent.
458 fn stop_scan(&mut self) {
459 self.stop.store(true, Ordering::Release);
460 let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned"));
461 let stop_tx = self.tx.clone();
462 for h in handles {
463 join_worker(h, &stop_tx, "scan session");
464 }
465 // Flush the pcap spool now that the scanner thread is joined: an
466 // Export .pcap copies the file from disk and must see every frame.
467 // The writer stays open for reuse by the next StartScan.
468 if let Some((_, w)) = &self.spool
469 && let Ok(mut w) = w.lock()
470 && let Err(e) = w.finish()
471 {
472 log_err(&self.tx, format!("pcap spool flush failed: {e:#}"));
473 }
474 let orig = self.orig_ifname.take();
475 if let Some(orig) = &orig
476 && self.mon_ifname.take().is_some()
477 && let Err(e) = iface::teardown_monitor(orig)
478 {
479 eprintln!("wifi_lab-svc: teardown_monitor({orig}) failed: {e:#}");
480 }
481 self.restore_check(orig.as_deref());
482 }
483
484 /// Post-teardown hygiene: a surviving `<orig>mon` vif means the driver
485 /// refused our delete (or teardown never ran) — the user is left with
486 /// no working wifi and needs the exact recovery command. Then restart
487 /// NetworkManager if we stopped it this session. Idempotent (the NM
488 /// flag is consumed), so the shutdown tail can re-run it safely; the
489 /// monitor check is skipped when no scan session ever ran.
490 fn restore_check(&self, orig: Option<&str>) {
491 if let Some(orig) = orig
492 && !iface::monitor_gone(orig)
493 {
494 log_err(
495 &self.tx,
496 format!("interface left in monitor mode; fix: sudo iw dev {orig}mon del"),
497 );
498 }
499 if self.stopped_nm.swap(false, Ordering::AcqRel) {
500 match iface::start_networkmanager() {
501 Ok(()) => log(&self.tx, "nm: NetworkManager restarted"),
502 Err(e) => log_err(&self.tx, format!("nm: restart failed: {e:#}")),
503 }
504 }
505 }
506
507 /// Register a worker thread; on spawn failure the error is reported on
508 /// the event pipe. A PANIC inside the worker is caught here and
509 /// reported as [`Event::Error`] with the payload — a silently dead
510 /// worker leaves the UI believing a job is still running (join() only
511 /// ever sees Err AFTER the thread is already gone).
512 fn spawn(
513 &self,
514 name: &str,
515 what: &str,
516 f: impl FnOnce(Sender<Event>) + Send + 'static,
517 ) -> bool {
518 let worker_tx = self.tx.clone();
519 let what_owned = what.to_string();
520 match std::thread::Builder::new()
521 .name(name.to_string())
522 .spawn(move || {
523 let panic_tx = worker_tx.clone();
524 let r =
525 std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || f(worker_tx)));
526 if let Err(payload) = r {
527 log_err(
528 &panic_tx,
529 format!(
530 "{what_owned}: worker panicked: {} — job aborted",
531 panic_message(&*payload)
532 ),
533 );
534 }
535 }) {
536 Ok(h) => {
537 self.handles.lock().expect("handles poisoned").push(h);
538 true
539 }
540 Err(e) => {
541 log_err(&self.tx, format!("{what}: spawn failed: {e}"));
542 false
543 }
544 }
545 }
546
547 /// Deauth worker: opens its own raw socket on the monitor interface,
548 /// then for each `(bssid, channel)` in `aps` tunes the channel and
549 /// blasts `count` rounds at `target` (broadcast allowed). Multi-entry
550 /// lists cover dual-band targets — the client picks the band, we don't
551 /// get to. Emits DeauthSent progress (via [`deauth::blast`]) per band.
552 ///
553 /// Channel arbitration: each band first moves the shared pin
554 /// (`override_freq` — the scanner re-asserts it, so the radio stays on
555 /// the band across the whole blast instead of being hopped away
556 /// mid-burst), with one immediate `set_channel` so TX starts now.
557 /// Afterwards `settle` hands the channel back to a held capture (or
558 /// free hop). The blast honors the stop flag per round, so a scan
559 /// restart's stop-join does not block the command loop.
560 fn deauth(&self, aps: Vec<(MacAddr, u8)>, target: MacAddr, count: u32) {
561 let Some(mon) = self.mon() else {
562 log_err(&self.tx, "deauth: no scan session — StartScan first");
563 return;
564 };
565 let pin = self.pin.clone();
566 let stop = self.stop.clone();
567 // Own frames must not trip the foreign-deauth detector: our blasts
568 // carry each AP's BSSID as transmitter (addr2).
569 if let Ok(mut s) = self.deauth_suppress.lock() {
570 for (bssid, _) in &aps {
571 s.insert(*bssid);
572 }
573 }
574 let suppress = self.deauth_suppress.clone();
575 let bssids: Vec<MacAddr> = aps.iter().map(|(b, _)| *b).collect();
576 let spawned = self.spawn("wifi_lab-deauth", "deauth", move |tx| {
577 deauth_worker(&mon, &aps, target, count, &pin, &stop, &tx);
578 // Whatever happened above (early error return included): hand
579 // the channel back to the capture hold, else free hop.
580 pin.settle();
581 if let Ok(mut s) = suppress.lock() {
582 for (bssid, _) in &aps {
583 s.remove(bssid);
584 }
585 }
586 });
587 if !spawned {
588 // Worker never started — un-suppress or the foreign-deauth
589 // storm detector would ignore real attacks on these BSSIDs
590 // forever (same spawned-check as capture_hs).
591 if let Ok(mut s) = self.deauth_suppress.lock() {
592 for bssid in &bssids {
593 s.remove(bssid);
594 }
595 }
596 }
597 }
598
599 /// Multi-client deauth: one worker pins `ap`'s channel and blasts
600 /// `count` rounds at each target in turn, finishing with one
601 /// broadcast blast (catches clients we haven't seen). Per-target
602 /// errors are logged and skipped; the pin settles at the end
603 /// regardless.
604 fn deauth_all(&self, ap: MacAddr, channel: u8, targets: Vec<MacAddr>, count: u32) {
605 let Some(mon) = self.mon() else {
606 log_err(&self.tx, "deauth-all: no scan session — StartScan first");
607 return;
608 };
609 let pin = self.pin.clone();
610 let stop = self.stop.clone();
611 if let Ok(mut s) = self.deauth_suppress.lock() {
612 s.insert(ap);
613 }
614 let suppress = self.deauth_suppress.clone();
615 let spawned = self.spawn("wifi_lab-deauth-all", "deauth-all", move |tx| {
616 let sock = match RawSocket::open(&mon) {
617 Ok(s) => s,
618 Err(e) => {
619 log_err(&tx, format!("deauth-all: raw socket on {mon} failed: {e}"));
620 pin.settle();
621 if let Ok(mut s) = suppress.lock() {
622 s.remove(&ap);
623 }
624 return;
625 }
626 };
627 // Move the pin first (scanner re-asserts this band, not the
628 // hop plan), then one immediate tune so TX starts this instant.
629 if let Some(mhz) = crate::common::freq_of_channel(channel) {
630 pin.override_freq(mhz);
631 }
632 if let Err(e) = iface::set_channel(&mon, channel) {
633 log(
634 &tx,
635 format!("deauth-all: set_channel {channel} failed: {e:#}"),
636 );
637 }
638 for target in &targets {
639 if stop.load(Ordering::Relaxed) {
640 break;
641 }
642 match deauth::blast(&sock, &ap, target, count, &tx, &stop) {
643 Ok(sent) => log(
644 &tx,
645 format!("deauth-all: {sent} frames → {target} (AP {ap}, ch {channel})"),
646 ),
647 Err(e) => log_err(&tx, format!("deauth-all: {target}: {e:#}")),
648 }
649 }
650 if !stop.load(Ordering::Relaxed) {
651 match deauth::blast(&sock, &ap, &MacAddr::BROADCAST, count, &tx, &stop) {
652 Ok(sent) => log(
653 &tx,
654 format!("deauth-all: {sent} frames → broadcast (AP {ap}, ch {channel})"),
655 ),
656 Err(e) => log_err(&tx, format!("deauth-all: broadcast: {e:#}")),
657 }
658 }
659 pin.settle();
660 if let Ok(mut s) = suppress.lock() {
661 s.remove(&ap);
662 }
663 });
664 if !spawned {
665 // Worker never started — un-suppress or the storm detector
666 // would ignore real deauth attacks on this AP forever.
667 if let Ok(mut s) = self.deauth_suppress.lock() {
668 s.remove(&ap);
669 }
670 }
671 }
672
673 /// PMKID grab worker: single client-less auth+assoc attempt against
674 /// `ap`, impersonating the monitor interface's own MAC. Emits
675 /// PmkidCaptured or a "no PMKID" log line.
676 ///
677 /// Channel arbitration: without a [`override_freq`](iface::ChannelPin::override_freq)
678 /// the scanner re-asserts its hop plan one dwell (100 ms) later and
679 /// the 3 s grab window listens on the WRONG channel (flaky "no
680 /// PMKID"); pin the band first, then tune immediately so TX starts
681 /// now, and settle back afterwards (mirrors deauth_all).
682 fn pmkid(&self, ap: MacAddr, channel: u8, essid: String) {
683 let Some(mon) = self.mon() else {
684 log_err(&self.tx, "pmkid: no scan session — StartScan first");
685 return;
686 };
687 let pin = self.pin.clone();
688 self.spawn("wifi_lab-pmkid", "pmkid", move |tx| {
689 let sta = match iface::mac_of(&mon) {
690 Ok(m) => m,
691 Err(e) => {
692 log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}"));
693 pin.settle();
694 return;
695 }
696 };
697 let sock = match RawSocket::open(&mon) {
698 Ok(s) => s,
699 Err(e) => {
700 log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}"));
701 pin.settle();
702 return;
703 }
704 };
705 // Move the pin first (scanner re-asserts this band, not the
706 // hop plan), then one immediate tune so TX starts this instant.
707 if let Some(mhz) = crate::common::freq_of_channel(channel) {
708 pin.override_freq(mhz);
709 }
710 if let Err(e) = iface::set_channel(&mon, channel) {
711 log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}"));
712 }
713 match pmkid::grab(&sock, &ap, &sta, &essid, &tx) {
714 Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)),
715 Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")),
716 Err(e) => log_err(&tx, format!("pmkid: {e:#}")),
717 }
718 pin.settle();
719 });
720 }
721
722 /// 4-way capture worker over every `(bssid, channel)` in `targets`
723 /// (dual-band aware; `targets[0]` is the selected BSSID — the UI puts
724 /// its band first and that's where a deauthed client will re-auth, so
725 /// that's the band we hold). Opens its own raw socket and runs
726 /// [`handshake::capture_loop`] (stop flag checked every 250 ms frame
727 /// poll). [`Event::HandshakeComplete`] is emitted from inside the loop
728 /// when a crackable pair completes.
729 ///
730 /// Channel arbitration: the pin is HELD synchronously here — before
731 /// the worker spawns — so a concurrently-arriving Deauth command sees
732 /// the capture as owner deterministically. The worker's [`PinGuard`]
733 /// releases on every exit path; the scanner dwells on the held
734 /// frequency instead of hopping, so M1/M2 can't land in different
735 /// dwell windows.
736 fn capture_hs(&self, targets: Vec<(MacAddr, u8)>, essid: String) {
737 let Some(mon) = self.mon() else {
738 log_err(&self.tx, "handshake: no scan session — StartScan first");
739 return;
740 };
741 let hold = targets
742 .first()
743 .and_then(|(_, ch)| crate::common::freq_of_channel(*ch));
744 if let Some(mhz) = hold {
745 self.pin.hold(mhz);
746 log(&self.tx, format!("handshake: channel held at {mhz} MHz"));
747 }
748 let pin = self.pin.clone();
749 let stop = self.stop.clone();
750 let spawned = self.spawn("wifi_lab-capture", "handshake", move |tx| {
751 let _guard = hold.map(|mhz| PinGuard { pin, mhz });
752 let bssids: Vec<MacAddr> = targets.iter().map(|(b, _)| *b).collect();
753 let mut channels: Vec<u8> = targets.iter().map(|(_, c)| *c).collect();
754 channels.sort_unstable();
755 channels.dedup();
756 if channels.len() == 1 {
757 // Apply immediately; the scanner re-asserts the same held
758 // frequency from now on.
759 if let Err(e) = iface::set_channel(&mon, channels[0]) {
760 log_err(
761 &tx,
762 format!("handshake: set_channel {} on {mon}: {e:#}", channels[0]),
763 );
764 return;
765 }
766 }
767 let sock = match RawSocket::open(&mon) {
768 Ok(s) => s,
769 Err(e) => {
770 log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}"));
771 return;
772 }
773 };
774 match handshake::capture_loop(&sock, &bssids, &essid, &tx, &stop) {
775 Ok((complete, partials)) => {
776 if !complete {
777 log(
778 &tx,
779 format!(
780 "handshake: capture ended without a pair ({essid}, {} bssid(s))",
781 bssids.len()
782 ),
783 );
784 }
785 // Session teardown: the tracker's M2+M3 material that
786 // never completed an M1+M2 pair is still crackable —
787 // hand each to the UI as a partial capture. The
788 // tracker only ever ingests frames for THIS session's
789 // target BSSIDs, so every partial here belongs to a
790 // targeted AP/client.
791 for cap in partials {
792 send(&tx, Event::HandshakePartial(Box::new(cap)));
793 }
794 }
795 Err(e) => log_err(&tx, format!("handshake: {e:#}")),
796 }
797 });
798 if !spawned {
799 // Worker never started — nobody else will release the hold.
800 if let Some(mhz) = hold {
801 self.pin.release(mhz);
802 }
803 }
804 }
805
806 fn stop_networkmanager(&self) {
807 match iface::stop_networkmanager() {
808 Ok(()) => {
809 self.stopped_nm.store(true, Ordering::Release);
810 log(&self.tx, "nm: stopped");
811 }
812 Err(e) => log(&self.tx, format!("nm: stop failed: {e:#}")),
813 }
814 }
815}
816
817/// Body of the deauth worker (early returns on socket/TX errors; the
818/// caller settles the pin afterwards regardless).
819fn deauth_worker(
820 mon: &str,
821 aps: &[(MacAddr, u8)],
822 target: MacAddr,
823 count: u32,
824 pin: &iface::ChannelPin,
825 stop: &AtomicBool,
826 tx: &Sender<Event>,
827) {
828 let sock = match RawSocket::open(mon) {
829 Ok(s) => s,
830 Err(e) => {
831 log_err(tx, format!("deauth: raw socket on {mon} failed: {e}"));
832 return;
833 }
834 };
835 for (ap, channel) in aps {
836 if stop.load(Ordering::Relaxed) {
837 return;
838 }
839 // Move the pin first (scanner re-asserts this band, not the hop
840 // plan), then one immediate tune so TX starts this instant.
841 if let Some(mhz) = crate::common::freq_of_channel(*channel) {
842 pin.override_freq(mhz);
843 }
844 if let Err(e) = iface::set_channel(mon, *channel) {
845 log(tx, format!("deauth: set_channel {channel} failed: {e:#}"));
846 }
847 match deauth::blast(&sock, ap, &target, count, tx, stop) {
848 Ok(sent) => log(
849 tx,
850 format!("deauth: done, {sent} frames → {target} (AP {ap}, ch {channel})"),
851 ),
852 Err(e) => {
853 log_err(tx, format!("deauth: {e:#}"));
854 return;
855 }
856 }
857 }
858}
859
860/// Service entry point: never returns (process exits from inside).
861///
862/// stdout carries exactly one READY banner and then one JSON-serialized
863/// [`Event`] per line — nothing else. stderr is free for diagnostics.
864pub fn run_service() -> ! {
865 let code = service_main();
866 std::process::exit(code);
867}
868
869fn service_main() -> i32 {
870 let stdout = std::io::stdout();
871 // Buffered writer handed to the forwarder thread; the banner uses the
872 // same lock discipline by printing through a dedicated line with an
873 // explicit flush BEFORE the forwarder starts.
874 {
875 let mut out = stdout.lock();
876 let _ = out.write_all(READY_LINE.as_bytes());
877 let _ = out.write_all(b"\n");
878 let _ = out.flush();
879 }
880
881 // Single writer to stdout: every event — scanner, attacks, errors,
882 // logs — funnels through this channel and gets serialized by ONE
883 // forwarder thread, so lines never interleave.
884 let (tx, rx) = crossbeam_channel::unbounded::<Event>();
885 let forwarder = std::thread::Builder::new()
886 .name("wifi_lab-svc-fwd".into())
887 .spawn(move || {
888 let stdout = std::io::stdout();
889 let mut out = std::io::BufWriter::new(stdout.lock());
890 // Bounded drain: when the channel closes (main loop out of
891 // scope) we finish queued events and exit.
892 while let Ok(ev) = rx.recv() {
893 match serde_json::to_string(&ev) {
894 Ok(line) => {
895 if out.write_all(line.as_bytes()).is_err()
896 || out.write_all(b"\n").is_err()
897 || out.flush().is_err()
898 {
899 return; // parent gone
900 }
901 }
902 Err(e) => eprintln!("wifi_lab-svc: event serialization failed: {e}"),
903 }
904 }
905 })
906 .expect("spawning service forwarder thread");
907
908 let mut radio = RadioService::new(tx.clone());
909 let stdin = std::io::stdin();
910 let mut lines = BufReader::new(stdin.lock()).lines();
911 loop {
912 let line = match lines.next() {
913 Some(Ok(l)) => l,
914 Some(Err(e)) => {
915 eprintln!("wifi_lab-svc: stdin read failed: {e}");
916 break; // treat as EOF
917 }
918 None => break, // EOF: parent closed the pipe
919 };
920 if line.trim().is_empty() {
921 continue;
922 }
923 let cmd: Cmd = match serde_json::from_str(&line) {
924 Ok(c) => c,
925 Err(e) => {
926 log_err(
927 &tx,
928 format!(
929 "service: bad command line ({}): {e}",
930 truncate_utf8(&line, 80)
931 ),
932 );
933 continue;
934 }
935 };
936 match cmd {
937 Cmd::StartScan {
938 ifname,
939 channels,
940 spool,
941 fresh_spool,
942 } => radio.start_scan(
943 &ifname,
944 channels.as_deref().unwrap_or(&[]),
945 spool,
946 fresh_spool,
947 ),
948 Cmd::StopScan => radio.stop_scan(),
949 Cmd::Deauth { aps, target, count } => radio.deauth(aps, target, count),
950 Cmd::DeauthAll {
951 ap,
952 channel,
953 targets,
954 count,
955 } => radio.deauth_all(ap, channel, targets, count),
956 Cmd::Pmkid { ap, channel, essid } => radio.pmkid(ap, channel, essid),
957 Cmd::CaptureHs { targets, essid } => radio.capture_hs(targets, essid),
958 Cmd::StopNetworkManager => radio.stop_networkmanager(),
959 Cmd::Shutdown => break,
960 }
961 }
962
963 // Stop everything, restore the interface, drain the event pipe so the
964 // last error lines still reach the UI, and exit. stop_scan runs the
965 // monitor-mode restore-check (a surviving `<if>mon` vif → an explicit
966 // fix command on the event pipe) and restarts NetworkManager when this
967 // session stopped it.
968 radio.stop_scan();
969 drop(radio);
970 drop(tx);
971 let _ = forwarder.join();
972 0
973}
974
975// ---------------------------------------------------------------------------
976// UI-side half — owns the child process.
977// ---------------------------------------------------------------------------
978
979/// Client handle for the privileged service. Lives across scan sessions:
980/// "Stop capture" only sends [`Cmd::StopScan`]; the child stays up for
981/// later scans and for `StopNetworkManager`. (The cracker is NOT tracked
982/// here: it is a pure UI-process job — see [`crate::attack`].)
983pub struct ServiceClient {
984 stdin: Arc<Mutex<ChildStdin>>,
985 reader: Option<JoinHandle<()>>,
986 child: Child,
987}
988
989/// Child argv: same binary, hidden worker flag. Root → spawn directly;
990/// non-root → wrap in pkexec (polkit prompt appears once per session).
991fn spawn_service_child() -> Result<Child> {
992 let exe = std::env::current_exe().context("resolving current_exe for service spawn")?;
993 if iface::is_root() {
994 Command::new(exe)
995 .arg("--privileged-worker")
996 .stdin(Stdio::piped())
997 .stdout(Stdio::piped())
998 .stderr(Stdio::inherit())
999 .spawn()
1000 .context("spawning privileged service")
1001 } else {
1002 if !iface::pkexec_available() {
1003 bail!("pkexec not available — cannot elevate the privileged service");
1004 }
1005 Command::new("pkexec")
1006 .arg(exe)
1007 .arg("--privileged-worker")
1008 .stdin(Stdio::piped())
1009 .stdout(Stdio::piped())
1010 .stderr(Stdio::inherit())
1011 .spawn()
1012 .context("spawning pkexec — polkit not installed or no agent running")
1013 }
1014}
1015
1016impl ServiceClient {
1017 /// Spawn the privileged service and start the channel-hopping scanner
1018 /// on `ifname`. All service events land on `tx`. A pkexec refusal /
1019 /// missing READY / immediate child death surfaces as `Err` (never a
1020 /// panic); later events flow asynchronously.
1021 pub fn start(ifname: &str, tx: Sender<Event>) -> Result<Self> {
1022 let mut child = spawn_service_child()?;
1023 let stdin = child
1024 .stdin
1025 .take()
1026 .context("service child stdin not piped")?;
1027 let stdout = child
1028 .stdout
1029 .take()
1030 .context("service child stdout not piped")?;
1031
1032 let (ready_tx, ready_rx) = crossbeam_channel::bounded::<Result<()>>(1);
1033 let reader = std::thread::Builder::new()
1034 .name("wifi_lab-svc-reader".into())
1035 .spawn(move || {
1036 let mut lines = BufReader::new(stdout).lines();
1037 let mut ready = false;
1038 let deadline = Instant::now() + READY_TIMEOUT;
1039 // READY phase: prefix-match so pkexec chatter on stdout
1040 // can't trip us; hard cap at READY_TIMEOUT.
1041 while Instant::now() < deadline {
1042 match lines.next() {
1043 Some(Ok(line)) if !ready => {
1044 if line.starts_with(READY_LINE) {
1045 ready = true;
1046 let _ = ready_tx.try_send(Ok(()));
1047 break;
1048 }
1049 // Pre-ready garbage (pkexec notes etc.): ignore.
1050 }
1051 Some(Ok(_)) => break,
1052 Some(Err(e)) => {
1053 let _ = ready_tx
1054 .try_send(Err(anyhow::anyhow!("service stdout read failed: {e}")));
1055 return;
1056 }
1057 None => {
1058 let _ = ready_tx.try_send(Err(anyhow::anyhow!(
1059 "service exited before READY (polkit dismissed or spawn failed)"
1060 )));
1061 return;
1062 }
1063 }
1064 }
1065 if !ready {
1066 let _ = ready_tx.try_send(Err(anyhow::anyhow!(
1067 "service READY banner not seen within {} s",
1068 READY_TIMEOUT.as_secs()
1069 )));
1070 return;
1071 }
1072 // Event phase: one JSON event per stdout line, until EOF.
1073 for line in lines {
1074 let line = match line {
1075 Ok(l) => l,
1076 Err(e) => {
1077 send(
1078 &tx,
1079 Event::Error(format!("service stdout read failed: {e}")),
1080 );
1081 break;
1082 }
1083 };
1084 if line.trim().is_empty() {
1085 continue;
1086 }
1087 match serde_json::from_str::<Event>(&line) {
1088 Ok(ev) => send(&tx, ev),
1089 Err(e) => send(
1090 &tx,
1091 Event::Error(format!(
1092 "service: bad event line ({}): {e}",
1093 truncate_utf8(&line, 80)
1094 )),
1095 ),
1096 }
1097 }
1098 // EOF: child died. UI uses this pair to un-flip flags.
1099 send(&tx, Event::Log("service exited".to_string()));
1100 send(&tx, Event::Error("service terminated".to_string()));
1101 })
1102 .context("spawning service reader thread")?;
1103
1104 // Wait for READY here (bounded), so spawn/config failures surface
1105 // synchronously instead of as a late async surprise.
1106 match ready_rx.recv_timeout(READY_TIMEOUT) {
1107 Ok(Ok(())) => {}
1108 Ok(Err(e)) => {
1109 let _ = child.kill();
1110 let _ = child.wait();
1111 let _ = reader.join();
1112 return Err(e);
1113 }
1114 Err(_) => {
1115 let _ = child.kill();
1116 let _ = child.wait();
1117 let _ = reader.join();
1118 bail!("service READY banner wait timed out");
1119 }
1120 }
1121
1122 let client = ServiceClient {
1123 stdin: Arc::new(Mutex::new(stdin)),
1124 reader: Some(reader),
1125 child,
1126 };
1127 client.cmd(&Cmd::StartScan {
1128 ifname: ifname.to_string(),
1129 channels: None,
1130 spool: None,
1131 fresh_spool: false,
1132 });
1133 Ok(client)
1134 }
1135
1136 /// Ship one command line to the service. BrokenPipe (service already
1137 /// dead) is ignored — the reader thread reported the death.
1138 pub fn cmd(&self, c: &Cmd) {
1139 let Ok(line) = serde_json::to_string(c) else {
1140 return;
1141 };
1142 let mut guard = self.stdin.lock().expect("service stdin poisoned");
1143 let _ = guard.write_all(line.as_bytes());
1144 let _ = guard.write_all(b"\n");
1145 let _ = guard.flush();
1146 }
1147
1148 /// Stop the scan session (scanner + attack workers) but KEEP the
1149 /// service alive for later scans and for `StopNetworkManager`.
1150 pub fn stop_scan(&self) {
1151 self.cmd(&Cmd::StopScan);
1152 }
1153
1154 /// Tear down: tell the service to stop everything + exit, give it a
1155 /// grace period, then kill and reap. The UI-side crack job is stopped
1156 /// separately by the owner of its stop flag (AppRoot).
1157 pub fn shutdown(mut self) {
1158 self.cmd(&Cmd::Shutdown);
1159 // 2 s grace for the service to restore managed mode + exit.
1160 let deadline = Instant::now() + Duration::from_secs(2);
1161 loop {
1162 match self.child.try_wait() {
1163 Ok(Some(_)) => break,
1164 Ok(None) if Instant::now() < deadline => {
1165 std::thread::sleep(Duration::from_millis(25));
1166 }
1167 Ok(None) => {
1168 let _ = self.child.kill();
1169 break;
1170 }
1171 Err(_) => break,
1172 }
1173 }
1174 let _ = self.child.wait();
1175 if let Some(reader) = self.reader.take() {
1176 let _ = reader.join();
1177 }
1178 }
1179}
1180
1181impl Drop for ServiceClient {
1182 /// Panic-safe mirror of [`ServiceClient::shutdown`]: the service gets
1183 /// a chance to restore the interface even if the UI dies.
1184 fn drop(&mut self) {
1185 self.cmd(&Cmd::Shutdown);
1186 let deadline = Instant::now() + Duration::from_secs(2);
1187 loop {
1188 match self.child.try_wait() {
1189 Ok(Some(_)) => break,
1190 Ok(None) if Instant::now() < deadline => {
1191 std::thread::sleep(Duration::from_millis(25));
1192 }
1193 Ok(None) => {
1194 let _ = self.child.kill();
1195 break;
1196 }
1197 Err(_) => break,
1198 }
1199 }
1200 let _ = self.child.wait();
1201 if let Some(reader) = self.reader.take() {
1202 let _ = reader.join();
1203 }
1204 }
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209 use super::*;
1210
1211 #[test]
1212 fn truncate_utf8_short_string_unchanged() {
1213 assert_eq!(truncate_utf8("hello", 80), "hello");
1214 assert_eq!(truncate_utf8("", 80), "");
1215 }
1216
1217 #[test]
1218 fn truncate_utf8_ascii_cuts_at_limit() {
1219 let s: String = "a".repeat(200);
1220 assert_eq!(truncate_utf8(&s, 80).len(), 80);
1221 }
1222
1223 #[test]
1224 fn truncate_utf8_never_splits_multibyte_char() {
1225 // Old code `&s[..s.len().min(80)]` panicked when byte 80 landed
1226 // inside a multi-byte char; the service command loop (monitor
1227 // mode left up) and the UI reader thread died on UTF-8 lines.
1228 // 79 ASCII bytes + '€' (3 bytes): byte 80 is inside the char.
1229 let mut s: String = "a".repeat(79);
1230 s.push('€'); // bytes 79..82
1231 s.push('€');
1232 let t = truncate_utf8(&s, 80);
1233 assert_eq!(t.len(), 79, "must back off to the char boundary");
1234 assert!(t.chars().all(|c| c == 'a'));
1235 // Boundary exactly at the char start: keep the char.
1236 let t = truncate_utf8(&s, 82);
1237 assert_eq!(t.chars().count(), 80, "79 'a' + one '€'");
1238 // A string of nothing but multi-byte chars at an odd cutoff.
1239 let s: String = "€".repeat(50); // 150 bytes
1240 let t = truncate_utf8(&s, 80);
1241 assert_eq!(t.len(), 78); // 26 chars × 3 bytes
1242 }
1243
1244 #[test]
1245 fn truncate_utf8_exact_limit_keeps_string() {
1246 let s: String = "é".repeat(40); // 80 bytes, exactly at limit
1247 assert_eq!(truncate_utf8(&s, 80), s.as_str());
1248 }
1249
1250 #[test]
1251 fn panic_message_extracts_str_and_string() {
1252 let r = std::panic::catch_unwind(|| panic!("explicit &str payload"));
1253 let payload = r.expect_err("must panic");
1254 assert_eq!(panic_message(&*payload), "explicit &str payload");
1255
1256 let r = std::panic::catch_unwind(|| panic!("{}", "owned String"));
1257 let payload = r.expect_err("must panic");
1258 assert_eq!(panic_message(&*payload), "owned String");
1259 }
1260
1261 #[test]
1262 fn join_worker_reports_panics_via_event() {
1263 let (tx, rx) = crossbeam_channel::unbounded();
1264 let h = std::thread::spawn(|| panic!("scanner boom"));
1265 join_worker(h, &tx, "scanner");
1266 match rx.try_recv() {
1267 Ok(Event::Error(msg)) => {
1268 assert!(msg.contains("scanner"), "message names the worker: {msg}");
1269 assert!(
1270 msg.contains("scanner boom"),
1271 "message carries the payload: {msg}"
1272 );
1273 }
1274 other => panic!("expected Event::Error with panic payload, got {other:?}"),
1275 }
1276 }
1277
1278 #[test]
1279 fn join_worker_quiet_on_clean_exit() {
1280 let (tx, rx) = crossbeam_channel::unbounded();
1281 let h = std::thread::spawn(|| {});
1282 join_worker(h, &tx, "scanner");
1283 assert!(rx.try_recv().is_err(), "no event for a clean exit");
1284 }
1285
1286 #[test]
1287 fn wrapped_worker_panic_becomes_error_event() {
1288 // The spawn() catch_unwind discipline, exercised standalone: a
1289 // panicking worker converts to ONE Event::Error and the handle
1290 // joins Ok — never a silently dead thread.
1291 let (tx, rx) = crossbeam_channel::unbounded::<Event>();
1292 let panic_tx = tx.clone();
1293 let h = std::thread::spawn(move || {
1294 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> bool {
1295 panic!("deauth exploded")
1296 }));
1297 if let Err(payload) = r {
1298 log_err(
1299 &panic_tx,
1300 format!(
1301 "deauth: worker panicked: {} — job aborted",
1302 panic_message(&*payload)
1303 ),
1304 );
1305 }
1306 });
1307 h.join().expect("caught panic ⇒ clean join");
1308 match rx.try_recv() {
1309 Ok(Event::Error(msg)) => assert!(msg.contains("deauth exploded"), "{msg}"),
1310 other => panic!("expected Event::Error, got {other:?}"),
1311 }
1312 assert!(rx.try_recv().is_err(), "exactly one error event");
1313 }
1314}