forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

cracker.rs1810 lines, 67.1 KiBHistoryRawDownload
1//! Cracker page: target dropdown (fed by captures), attack-mode select
2//! (wordlist / bruteforce / rainbow PMK table) with per-mode inputs,
3//! backend label, Start/Stop, live throughput/progress, rainbow-table
4//! build controls, recent-activity log, found-password banner.
5//!
6//! Cracking is a plain UI-process job ([`crate::attack`]): it does NOT
7//! need the privileged radio service and is completely independent of
8//! capture state — a run may be started while a capture is live.
9//! In mock mode Start runs a deterministic simulation on a gpui
10//! background task instead (same event sequence; the attack mode is
11//! ignored there).
12
13use std::path::PathBuf;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::time::Duration;
16
17use gpui::{
18 Context, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement,
19 Styled, Window, div, prelude::FluentBuilder, px,
20};
21use gpuikit::elements::button::button;
22use gpuikit::elements::loading_indicator::loading_indicator;
23use gpuikit::elements::progress::progress;
24use gpuikit::elements::text_field::text_field;
25use gpuikit::elements::typography::{h3, small, text};
26use gpuikit::layout::{h_stack, v_stack};
27use gpuikit::theme::{ActiveTheme, Themeable};
28
29use crate::attack::Attack;
30use crate::common::Event;
31use crate::ui::app::AppRoot;
32
33/// Mock run length: this many "candidates" before the password turns up.
34const WORDLIST_TOTAL: u64 = 1_000_000;
35/// Mock GPU throughput (guesses/second).
36const MOCK_HPS: f64 = 1_250_000.0;
37const MOCK_PASSWORD: &str = "testnet2024!";
38/// Label for the backend column: real runs detect GPU-vs-CPU inside the
39/// worker and log it ("cracker: GPU backend: … / CPU fallback").
40const fn backend_label(is_mock: bool) -> &'static str {
41 if is_mock {
42 "GPU (wgpu) · mock"
43 } else {
44 "GPU (wgpu) → CPU"
45 }
46}
47
48fn fmt_hps(hps: f64) -> String {
49 if hps >= 1.0e6 {
50 format!("{:.2} MH/s", hps / 1.0e6)
51 } else if hps >= 1.0e3 {
52 format!("{:.1} kH/s", hps / 1.0e3)
53 } else {
54 format!("{hps:.0} H/s")
55 }
56}
57
58/// Human duration for worst-case ETAs ("3d 4h", "2h 05m", "3m 12s", "12s").
59fn fmt_dur(secs: f64) -> String {
60 if !secs.is_finite() || secs < 1.0 {
61 return "<1s".to_string();
62 }
63 let s = secs.round() as u64;
64 let (d, h, m, sec) = (s / 86400, s / 3600 % 24, s / 60 % 60, s % 60);
65 if d > 0 {
66 format!("{d}d {h}h")
67 } else if h > 0 {
68 format!("{h}h {m:02}m")
69 } else if m > 0 {
70 format!("{m}m {sec:02}s")
71 } else {
72 format!("{sec}s")
73 }
74}
75
76/// Worst-case remaining time: every not-yet-tried candidate at the
77/// current rate. Empty when the total or the rate is unknown.
78fn fmt_worst_case(done: u64, hps: f64, total: Option<u64>) -> Option<String> {
79 let t = total?;
80 if hps <= 0.0 || done >= t {
81 return None;
82 }
83 Some(format!(
84 "worst case left: ~{}",
85 fmt_dur((t - done) as f64 / hps)
86 ))
87}
88
89/// Build the [`Attack`] selected by `app.attack_mode` from the page's
90/// input fields. Returns `None` (after logging the reason) when an input
91/// is empty or fails to parse.
92fn selected_attack(app: &mut AppRoot, cx: &mut gpui::App) -> Option<Attack> {
93 match app.attack_mode.as_str() {
94 "bruteforce" => {
95 let custom = app
96 .charset_input
97 .read(cx)
98 .content()
99 .trim_end_matches(['\r', '\n'])
100 .as_bytes()
101 .to_vec();
102 // Union of the checked preset chips + the custom field.
103 let charset = crate::attack::charset::compose(
104 app.cs_lower,
105 app.cs_upper,
106 app.cs_digits,
107 app.cs_special,
108 &custom,
109 );
110 if charset.is_empty() {
111 app.state
112 .push_log("cracker: empty charset — pick a preset chip or type custom chars");
113 return None;
114 }
115 let min_s = app.len_min_input.read(cx).content().trim().to_string();
116 let max_s = app.len_max_input.read(cx).content().trim().to_string();
117 let min = match min_s.parse::<usize>() {
118 Ok(v) => v,
119 Err(_) => {
120 app.state
121 .push_log(format!("cracker: bad min length '{min_s}'"));
122 return None;
123 }
124 };
125 let max = match max_s.parse::<usize>() {
126 Ok(v) => v,
127 Err(_) => {
128 app.state
129 .push_log(format!("cracker: bad max length '{max_s}'"));
130 return None;
131 }
132 };
133 Some(Attack::Bruteforce {
134 charset,
135 min,
136 max,
137 freq_order: app.freq_order,
138 })
139 }
140 "rules" => {
141 let wl = app.wordlist_input.read(cx).content().trim().to_string();
142 if wl.is_empty() {
143 app.state.push_log("cracker: wordlist path is empty");
144 return None;
145 }
146 let rules = app.rules_input.read(cx).content().trim().to_string();
147 if rules.is_empty() {
148 app.state.push_log("cracker: rules path is empty");
149 return None;
150 }
151 Some(Attack::Rules {
152 wordlist: PathBuf::from(wl),
153 rules: PathBuf::from(rules),
154 })
155 }
156 "hybrid" => {
157 let wl = app.wordlist_input.read(cx).content().trim().to_string();
158 if wl.is_empty() {
159 app.state.push_log("cracker: wordlist path is empty");
160 return None;
161 }
162 let custom = app
163 .charset_input
164 .read(cx)
165 .content()
166 .trim_end_matches(['\r', '\n'])
167 .as_bytes()
168 .to_vec();
169 let charset = crate::attack::charset::compose(
170 app.cs_lower,
171 app.cs_upper,
172 app.cs_digits,
173 app.cs_special,
174 &custom,
175 );
176 if charset.is_empty() {
177 app.state
178 .push_log("cracker: empty charset — pick a preset chip or type custom chars");
179 return None;
180 }
181 let min_s = app.hyb_min_input.read(cx).content().trim().to_string();
182 let max_s = app.hyb_max_input.read(cx).content().trim().to_string();
183 let min = match min_s.parse::<usize>() {
184 Ok(v) => v.clamp(1, 4),
185 Err(_) => {
186 app.state
187 .push_log(format!("cracker: bad hybrid min '{min_s}'"));
188 return None;
189 }
190 };
191 let max = match max_s.parse::<usize>() {
192 Ok(v) => v.clamp(1, 4),
193 Err(_) => {
194 app.state
195 .push_log(format!("cracker: bad hybrid max '{max_s}'"));
196 return None;
197 }
198 };
199 if min > max {
200 app.state
201 .push_log(format!("cracker: hybrid min {min} > max {max}"));
202 return None;
203 }
204 Some(Attack::Hybrid {
205 wordlist: PathBuf::from(wl),
206 charset,
207 min,
208 max,
209 })
210 }
211 "rainbow" => {
212 let path = app.rainbow_input.read(cx).content().trim().to_string();
213 if path.is_empty() {
214 app.state.push_log("cracker: PMK table path is empty");
215 return None;
216 }
217 Some(Attack::Rainbow(PathBuf::from(path)))
218 }
219 _ => {
220 let path = app.wordlist_input.read(cx).content().trim().to_string();
221 if path.is_empty() {
222 app.state.push_log("cracker: wordlist path is empty");
223 return None;
224 }
225 Some(Attack::Wordlist(PathBuf::from(path)))
226 }
227 }
228}
229
230/// Start a crack run on the selected capture.
231///
232/// Real mode: builds the selected [`Attack`], validates it (files
233/// opened, charset/lengths checked) BEFORE any flag is set, then hands
234/// the stored [`crate::crypto::CrackTarget`] (no hc22000 re-parse) to
235/// `crate::attack::spawn_crack`; progress and termination arrive as
236/// CrackProgress/CrackFound/CrackStopped events and land in state via
237/// `AppState::apply`. No radio or service involvement.
238/// Mock mode: a deterministic generator drives the SAME event sequence.
239fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
240 view.update(cx, |app, cx| {
241 if app.state.cracker.running || app.bench_running {
242 return;
243 }
244 let Some(idx) = app.state.cracker.target else {
245 app.state.push_log("cracker: no target selected");
246 cx.notify();
247 return;
248 };
249 // The index addresses `capture_descs()`/`crack_target_at()`: no
250 // string re-resolution. A stale index (capture removed since the
251 // dropdown rebuilt) is the "capture no longer exists" guard.
252 let Some(desc) = app.state.capture_descs().get(idx).cloned() else {
253 app.state
254 .push_log("ERROR: cracker: capture no longer exists");
255 cx.notify();
256 return;
257 };
258
259 // Validate everything that can fail BEFORE marking the run active,
260 // so a refused start never leaves stale flags behind.
261 let real = if !app.is_mock {
262 let Some(attack) = selected_attack(app, cx) else {
263 cx.notify();
264 return;
265 };
266 if let Err(e) = attack.validate() {
267 app.state.push_log(format!("ERROR: cracker: {e:#}"));
268 cx.notify();
269 return;
270 }
271 match app.state.crack_target_at(idx) {
272 Some(t) => Some((t, attack)),
273 None => {
274 app.state
275 .push_log("ERROR: cracker: capture no longer exists");
276 cx.notify();
277 return;
278 }
279 }
280 } else {
281 None
282 };
283
284 app.crack_epoch += 1; // invalidate any stale mock generator ticks
285 let wordlist = app.wordlist_input.read(cx).content().trim().to_string();
286 let cr = &mut app.state.cracker;
287 cr.wordlist = Some(wordlist.clone());
288 cr.found = None;
289 cr.tried = 0;
290 cr.hps = 0.0;
291 cr.total = None;
292 // A fresh foreground start supersedes any saved resume position.
293 cr.resume = None;
294 // `running` is the single source of truth for "run in flight"
295 // (the old `crack_inflight` double is gone): set here, settled by
296 // CrackStopped/CrackError alike.
297 cr.running = true;
298 // Fresh run: the throughput curve belongs to it, not the last run.
299 app.state.hps_hist.clear();
300 cx.notify();
301
302 if !app.is_mock {
303 let Some((target, attack)) = real else { return };
304 app.state.push_log(format!(
305 "cracker: starting on {desc} — {}",
306 attack.describe()
307 ));
308 // Remember the wordlist path in the MRU list (wordlist-family
309 // attacks only) so it shows up as a one-click chip later.
310 let wl_path: Option<String> = match &attack {
311 Attack::Wordlist(p) => Some(p.display().to_string()),
312 Attack::Rules { wordlist, .. } | Attack::Hybrid { wordlist, .. } => {
313 Some(wordlist.display().to_string())
314 }
315 _ => None,
316 };
317 if let Some(wl_path) = wl_path {
318 crate::store::remember_wordlist(&mut app.profiles, &wl_path);
319 if let Err(e) = crate::store::save_profiles(&app.profiles) {
320 app.state.push_log(format!("profiles: save FAILED: {e:#}"));
321 }
322 }
323 // Track the live attack for the resume session file
324 // (throttle-saved on progress, finalized on stop).
325 app.state.cracker.active_attack = Some(attack.clone());
326 cx.notify();
327 app.crack_stop = Some(crate::attack::spawn_crack(
328 target.describe(),
329 target,
330 attack,
331 0,
332 app.tx.clone(),
333 false,
334 ));
335 return;
336 }
337
338 // ---- mock path: same events, fabricated numbers ----
339 app.state
340 .push_log(format!("cracker: {desc} via {wordlist} [mock run]"));
341 cx.notify();
342 let tx = app.tx.clone();
343 let epoch = app.crack_epoch;
344 cx.spawn(async move |this, cx| {
345 let mut done = 0u64;
346 loop {
347 cx.background_executor()
348 .timer(Duration::from_millis(100))
349 .await;
350 let live = this
351 .update(cx, |app, _cx| {
352 app.crack_epoch == epoch && app.state.cracker.running
353 })
354 .unwrap_or(false);
355 if !live {
356 break;
357 }
358 done += (MOCK_HPS / 10.0) as u64 + done / 977 % 8_000;
359 let hps = MOCK_HPS * (0.92 + (done / 331 % 15) as f64 / 100.0);
360 let _ = tx.send(Event::CrackProgress {
361 done,
362 hps,
363 total: Some(WORDLIST_TOTAL),
364 });
365 if done >= WORDLIST_TOTAL {
366 let _ = tx.send(Event::CrackFound {
367 password: MOCK_PASSWORD.to_string(),
368 });
369 let _ = tx.send(Event::CrackStopped { found: true });
370 break;
371 }
372 }
373 })
374 .detach();
375 });
376}
377
378/// Stop the active run.
379///
380/// Real mode flips the crack job's stop flag (the worker breaks at the
381/// next batch and emits CrackStopped{found:false}, which settles the UI
382/// and clears `app.crack_stop`). Mock mode invalidates the generator
383/// epoch AND emits the same CrackStopped{found:false} terminator through
384/// the mock event channel — the drain then finalizes the session exactly
385/// like a real stop (running=false, active_attack cleared,
386/// finalize_crack_session runs), instead of leaving `active_attack`
387/// state behind.
388fn stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
389 view.update(cx, |app, cx| {
390 if !app.state.cracker.running {
391 return;
392 }
393 app.crack_epoch += 1;
394 if app.is_mock {
395 // Settle the visible run state right away (Stop button greys
396 // out immediately; apply() re-setting these on the event is
397 // idempotent), then let the normal drain path do the
398 // real-mode-identical finalization.
399 app.state.cracker.running = false;
400 app.state.cracker.hps = 0.0;
401 app.state.push_log("cracker: stopped by user");
402 cx.notify();
403 let _ = app.tx.send(Event::CrackStopped { found: false });
404 return;
405 }
406 if let Some(flag) = &app.crack_stop {
407 flag.store(true, Ordering::Relaxed);
408 app.state.push_log("cracker: stop requested");
409 }
410 cx.notify();
411 });
412}
413
414/// Start a rainbow PMK-table build for the selected capture's SSID.
415///
416/// Validates both paths (wordlist must open, table path must be given)
417/// BEFORE marking the build active; progress arrives as
418/// RainbowProgress, termination as RainbowBuilt — the latter settles
419/// `rainbow_building` and `app.rainbow_stop`.
420fn build(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
421 view.update(cx, |app, cx| {
422 if app.state.cracker.rainbow_building || app.state.cracker.running || app.bench_running {
423 return;
424 }
425 let Some(idx) = app.state.cracker.target else {
426 app.state.push_log("rainbow: no target selected");
427 cx.notify();
428 return;
429 };
430 let Some(target) = app.state.crack_target_at(idx) else {
431 app.state
432 .push_log("ERROR: rainbow: capture no longer exists");
433 cx.notify();
434 return;
435 };
436 let ssid = target.essid().to_string();
437
438 let wl = app.wordlist_input.read(cx).content().trim().to_string();
439 if wl.is_empty() {
440 app.state.push_log("rainbow: wordlist path is empty");
441 cx.notify();
442 return;
443 }
444 if let Err(e) = std::fs::File::open(&wl) {
445 app.state
446 .push_log(format!("ERROR: rainbow: cannot open wordlist {wl}: {e}"));
447 cx.notify();
448 return;
449 }
450 let out = app.rainbow_input.read(cx).content().trim().to_string();
451 if out.is_empty() {
452 app.state.push_log("rainbow: PMK table path is empty");
453 cx.notify();
454 return;
455 }
456
457 app.state.cracker.rainbow_building = true;
458 app.state.cracker.rainbow_done = 0;
459 app.state.cracker.rainbow_hps = 0.0;
460 app.state.cracker.rainbow_total = None;
461 app.state.push_log(format!(
462 "rainbow: building table {out} for ssid \"{ssid}\" from {wl}"
463 ));
464 cx.notify();
465 app.rainbow_stop = Some(crate::attack::spawn_rainbow_build(
466 ssid,
467 PathBuf::from(wl),
468 PathBuf::from(out),
469 app.tx.clone(),
470 ));
471 });
472}
473
474/// Stop the running rainbow-table build: flip the job's stop flag; the
475/// terminating RainbowBuilt event settles the UI.
476fn build_stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
477 view.update(cx, |app, cx| {
478 if let Some(flag) = &app.rainbow_stop {
479 flag.store(true, Ordering::Relaxed);
480 app.state.push_log("rainbow: stop requested");
481 cx.notify();
482 }
483 });
484}
485
486/// Resume the saved run shown in the banner: same capture, same attack,
487/// continuing at the saved candidate offset.
488fn resume_saved(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
489 view.update(cx, |app, cx| {
490 if app.state.cracker.running || app.state.cracker.rainbow_building || app.bench_running {
491 return;
492 }
493 let Some(r) = app.state.cracker.resume.clone() else {
494 return;
495 };
496 // Files may have vanished since the run was saved — refuse with a
497 // visible reason, keep the session file + banner untouched.
498 if let Err(e) = r.attack.validate() {
499 app.state
500 .push_log(format!("ERROR: cracker: saved run no longer valid: {e:#}"));
501 cx.notify();
502 return;
503 }
504 // ResumeInfo already carries the capture INDEX (resolved against
505 // the loaded captures when the session was armed): no string
506 // re-matching. The bounds check is the "no longer exists" guard.
507 let Some(target) = app.state.crack_target_at(r.target_idx) else {
508 app.state
509 .push_log("ERROR: cracker: saved run's capture no longer exists");
510 cx.notify();
511 return;
512 };
513
514 app.crack_epoch += 1;
515 let cr = &mut app.state.cracker;
516 cr.found = None;
517 cr.tried = r.done;
518 cr.hps = 0.0;
519 cr.total = r.total;
520 cr.active_attack = Some(r.attack.clone());
521 cr.resume = None;
522 // The dropdown selection follows the resumed capture (throttle-
523 // saves for THIS run key off `target`).
524 cr.target = Some(r.target_idx);
525 cr.running = true;
526 app.state.hps_hist.clear();
527 // The select ENTITY bakes its `.selected()` in at construction,
528 // so a programmatic target change must rebuild it (keeps the just-
529 // set index pre-marked).
530 app.rebuild_target_select(cx);
531 // The new run's throttle-saves supersede the old session file;
532 // clear eagerly so a crash cannot doubly arm the banner.
533 if let Err(e) = crate::store::clear_session() {
534 app.state
535 .push_log(format!("cracker: session clear failed: {e:#}"));
536 }
537 app.state.push_log(format!(
538 "cracker: resuming saved run — {} at {}{}",
539 r.attack.describe(),
540 r.done,
541 r.total.map(|t| format!("/{t}")).unwrap_or_default()
542 ));
543 cx.notify();
544 app.crack_stop = Some(crate::attack::spawn_crack(
545 target.describe(),
546 target,
547 r.attack,
548 r.done,
549 app.tx.clone(),
550 false,
551 ));
552 });
553}
554
555/// Delete the saved session file and dismiss the banner.
556fn discard_saved(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
557 view.update(cx, |app, cx| {
558 if let Err(e) = crate::store::clear_session() {
559 app.state
560 .push_log(format!("cracker: session clear failed: {e:#}"));
561 }
562 app.state.cracker.resume = None;
563 app.state.push_log("cracker: saved run discarded");
564 cx.notify();
565 });
566}
567
568/// Save the current mode + paths as a named preset in `app.profiles`
569/// (name auto-derived as `{mode}:{basename(wordlist)}`; a same-name
570/// preset is replaced). Persisted via [`crate::store::save_profiles`].
571fn save_preset(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
572 view.update(cx, |app, cx| {
573 let mode = app.attack_mode.clone();
574 if mode == "rainbow" {
575 app.state
576 .push_log("profiles: rainbow presets are not saved");
577 cx.notify();
578 return;
579 }
580 let wordlist = app.wordlist_input.read(cx).content().trim().to_string();
581 if wordlist.is_empty() {
582 app.state
583 .push_log("profiles: wordlist path is empty — nothing to save");
584 cx.notify();
585 return;
586 }
587 let rules = match mode.as_str() {
588 "rules" => {
589 let r = app.rules_input.read(cx).content().trim().to_string();
590 if r.is_empty() {
591 app.state
592 .push_log("profiles: rules path is empty — nothing to save");
593 cx.notify();
594 return;
595 }
596 Some(r)
597 }
598 _ => None,
599 };
600 let base = std::path::Path::new(&wordlist)
601 .file_name()
602 .map(|n| n.to_string_lossy().into_owned())
603 .unwrap_or_else(|| wordlist.clone());
604 let name = format!("{mode}:{base}");
605 let profile = crate::store::CrackProfile {
606 name: name.clone(),
607 mode,
608 wordlist,
609 rules,
610 };
611 app.profiles.profiles.retain(|p| p.name != name);
612 app.profiles.profiles.push(profile);
613 match crate::store::save_profiles(&app.profiles) {
614 Ok(()) => app.state.push_log(format!("profiles: saved preset {name}")),
615 Err(e) => app.state.push_log(format!("profiles: save FAILED: {e:#}")),
616 }
617 cx.notify();
618 });
619}
620
621/// Apply a saved preset: switch the attack mode and prefill the
622/// wordlist/rules input fields.
623fn apply_preset(profile: crate::store::CrackProfile, view: &Entity<AppRoot>, cx: &mut gpui::App) {
624 view.update(cx, |app, cx| {
625 app.attack_mode = profile.mode.clone();
626 app.attack_select.update(cx, |sel, cx| {
627 sel.set_selected(Some(profile.mode.clone()), cx);
628 });
629 let wl = profile.wordlist.clone();
630 app.wordlist_input.update(cx, |input, cx| {
631 input.set_content(wl, cx);
632 });
633 if let Some(rules) = &profile.rules {
634 let r = rules.clone();
635 app.rules_input.update(cx, |input, cx| {
636 input.set_content(r, cx);
637 });
638 }
639 app.state
640 .push_log(format!("profiles: applied preset {}", profile.name));
641 cx.notify();
642 });
643}
644
645/// Import captures from .cap/.pcap files (via [`crate::pcapin::extract`])
646/// or .hc22000 text files (via [`crate::crypto::parse_hc22000`]). Each
647/// extracted capture arrives as a CaptureImported event; the heavy parse
648/// runs on a worker thread streaming events like the crack threads do.
649/// `import_busy` is cleared at the very end, after all chosen files.
650fn import_captures(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
651 let prompt = cx.prompt_for_paths(gpui::PathPromptOptions {
652 files: true,
653 directories: false,
654 multiple: true,
655 prompt: None,
656 });
657 view.update(cx, |app, cx| {
658 app.import_busy = true;
659 cx.notify();
660 });
661 let weak = view.downgrade();
662 cx.spawn(async move |cx| {
663 // oneshot recv err OR platform dialog err OR explicit cancel all
664 // land here as "no file chosen".
665 let picked: Option<Vec<PathBuf>> = match prompt.await {
666 Ok(Ok(paths)) => paths,
667 _ => None,
668 };
669 let Some(paths) = picked else {
670 let _ = weak.update(cx, |app, cx| {
671 app.import_busy = false;
672 app.state.push_log("import: no file chosen");
673 cx.notify();
674 });
675 return;
676 };
677 // Heavy parsing (multi-GB pcaps) must not block the UI executor:
678 // stream results from a plain thread like the crack workers do.
679 let tx = match weak.update(cx, |app, _cx| app.tx.clone()) {
680 Ok(tx) => tx,
681 Err(_) => return, // view gone — nothing to report to
682 };
683 // At the very end (after all files) the worker signals completion
684 // on this channel; the gpui continuation below clears import_busy
685 // (a bare std thread cannot touch gpui state).
686 let (done_tx, done_rx) = crossbeam_channel::bounded::<()>(1);
687 std::thread::Builder::new()
688 .name("wifi_lab-import".into())
689 .spawn(move || {
690 for path in paths {
691 let disp = path.display().to_string();
692 let is_hc22000 = disp.contains("22000")
693 || std::fs::read_to_string(&path)
694 .map(|s| {
695 s.lines()
696 .take(8)
697 .any(|l| l.starts_with("WPA*01") || l.starts_with("WPA*02"))
698 })
699 .unwrap_or(false);
700 if is_hc22000 {
701 match std::fs::read_to_string(&path) {
702 Ok(text) => {
703 let mut n = 0usize;
704 let mut m = 0usize;
705 for line in text.lines() {
706 let line = line.trim();
707 if line.is_empty() {
708 continue;
709 }
710 let bare = line.strip_prefix("WPA*").unwrap_or(line);
711 match crate::crypto::parse_hc22000(bare) {
712 Ok(crate::crypto::CrackTarget::Handshake(h)) => {
713 let _ = tx.send(Event::CaptureImported(
714 crate::common::ImportedCapture::Handshake(
715 Box::new(h),
716 ),
717 ));
718 n += 1;
719 }
720 Ok(crate::crypto::CrackTarget::Pmkid(p)) => {
721 let _ = tx.send(Event::CaptureImported(
722 crate::common::ImportedCapture::Pmkid(p),
723 ));
724 n += 1;
725 }
726 Err(_) => m += 1,
727 }
728 }
729 let _ = tx.send(Event::Log(format!(
730 "import: {disp}: {n} captures ({m} skipped)"
731 )));
732 }
733 Err(e) => {
734 let _ = tx.send(Event::Error(format!("import: {disp}: {e}")));
735 }
736 }
737 } else {
738 match crate::pcapin::extract(&path) {
739 Ok(caps) => {
740 let n = caps.len();
741 for cap in caps {
742 let _ = tx.send(Event::CaptureImported(cap));
743 }
744 let _ = tx.send(Event::Log(format!(
745 "import: {disp}: {n} captures (0 skipped)"
746 )));
747 }
748 Err(e) => {
749 let _ = tx.send(Event::Error(format!("import: {disp}: {e:#}")));
750 }
751 }
752 }
753 }
754 let _ = done_tx.send(());
755 })
756 .expect("spawn import thread");
757 // Wait for completion on the background executor, then clear the
758 // busy flag on the gpui side.
759 let bg = cx.background_executor().clone();
760 bg.spawn(async move {
761 let _ = done_rx.recv();
762 })
763 .await;
764 let _ = weak.update(cx, |app, cx| {
765 app.import_busy = false;
766 cx.notify();
767 });
768 })
769 .detach();
770}
771
772/// Run a 3 s H/s benchmark (GPU if available, CPU always). Results
773/// arrive as one BenchmarkDone event; `bench_running` is cleared on the
774/// app drain side. Mock mode fabricates a fixed result after ~1.5 s.
775fn benchmark(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
776 view.update(cx, |app, cx| {
777 if app.bench_running || app.state.cracker.running || app.state.cracker.rainbow_building {
778 return;
779 }
780 app.bench_running = true;
781 app.state.push_log("benchmark: measuring crack speed (3s)…");
782 cx.notify();
783 if !app.is_mock {
784 // The worker holds its own Arc; the flag is never flipped by
785 // the UI, so dropping our copy is safe.
786 drop(crate::attack::spawn_benchmark(3, app.tx.clone()));
787 return;
788 }
789 // Mock: fabricate a BenchmarkDone after ~1.5 s. No epoch
790 // invalidation: bench_running already blocks a concurrent second
791 // click, and a crack started meanwhile does not invalidate a
792 // machine-speed measurement.
793 let tx = app.tx.clone();
794 cx.spawn(async move |this, cx| {
795 cx.background_executor()
796 .timer(Duration::from_millis(1500))
797 .await;
798 let live = this
799 .update(cx, |app, _cx| app.bench_running)
800 .unwrap_or(false);
801 if live {
802 let _ = tx.send(Event::BenchmarkDone {
803 gpu_hps: Some(MOCK_HPS),
804 cpu_hps: 310_000.0,
805 });
806 }
807 })
808 .detach();
809 });
810}
811
812/// Single-flight guard for the async estimate count: true while a
813/// wordlist line_count runs on the background executor (the Estimate
814/// button greys out; clicks are deduped).
815static ESTIMATE_INFLIGHT: AtomicBool = AtomicBool::new(false);
816/// Generation of the newest claimed count. A completion whose generation
817/// has been superseded is a stale result and must be dropped.
818static ESTIMATE_GEN: AtomicU64 = AtomicU64::new(0);
819
820/// Claim the estimator slot for one background count. Returns the
821/// generation stamped onto that count's result, or `None` when a count
822/// is already running (button-disabled is the normal gate; this is the
823/// race-proof backstop).
824fn estimate_claim() -> Option<u64> {
825 if ESTIMATE_INFLIGHT.swap(true, Ordering::AcqRel) {
826 None
827 } else {
828 Some(ESTIMATE_GEN.fetch_add(1, Ordering::AcqRel) + 1)
829 }
830}
831
832/// Release the estimator slot; reports whether `est_gen` is still the newest
833/// claim (`false` → a newer count started, drop the stale result). A stale
834/// completion must NOT free the slot — the newer count still owns it.
835fn estimate_release(est_gen: u64) -> bool {
836 if est_gen != ESTIMATE_GEN.load(Ordering::Acquire) {
837 return false;
838 }
839 ESTIMATE_INFLIGHT.store(false, Ordering::Release);
840 true
841}
842
843/// True while an estimate count runs (render greys the Estimate button).
844fn estimate_busy() -> bool {
845 ESTIMATE_INFLIGHT.load(Ordering::Acquire)
846}
847
848/// (a) wordlist-family estimate lines: pure worker math over the
849/// click-time snapshot. Empty wordlist path means the mock-size count;
850/// `rules_path` applies only in rules mode. This is the part that walks
851/// multi-GB files, so it runs on the background executor — never on the
852/// UI thread.
853fn estimate_wordlist_lines(wl: &str, rules_path: Option<&str>, hps: f64) -> Vec<String> {
854 let wl_space: Option<u128> = if wl.is_empty() {
855 Some(WORDLIST_TOTAL as u128)
856 } else {
857 match crate::wordlist::line_count(std::path::Path::new(wl)) {
858 Ok(n) => Some(n as u128),
859 Err(e) => return vec![format!("estimate: wordlist unreadable: {e:#}")],
860 }
861 };
862 let mut lines = Vec::new();
863 if let Some(mut space) = wl_space {
864 let mut what = format!(
865 "wordlist {}",
866 if wl.is_empty() { "(mock-size)" } else { wl }
867 );
868 // `Some(path)` ⇔ rules mode at click time (path may still be
869 // empty — same "rules unreadable" outcome as the old sync code).
870 if let Some(rp) = rules_path {
871 match crate::attack::rule_count(std::path::Path::new(rp)) {
872 Ok(r) if r > 0 => {
873 space = space.saturating_mul(r as u128);
874 what = format!("{what} × {r} rules");
875 }
876 Ok(_) => {}
877 Err(e) => {
878 lines.push(format!("estimate: rules unreadable: {e:#}"));
879 space = 0;
880 }
881 }
882 }
883 if space > 0 {
884 lines.push(format!(
885 "estimate: {what}: {space} candidates, worst case ~{} @ {}",
886 fmt_dur(space as f64 / hps),
887 fmt_hps(hps)
888 ));
889 }
890 }
891 lines
892}
893
894/// Estimate worst-case crack durations from the measured benchmark rate
895/// and the current input fields; results go to the activity log as
896/// "estimate:" lines (candidate-space math always, times only when a
897/// benchmark has run).
898///
899/// The (a) wordlist line count can walk many GB, so it runs on gpui's
900/// background executor (same `cx.spawn`/`background_executor` pattern as
901/// the Import button) and lands back via `view.update`; bruteforce space
902/// and candidate entropy are trivial arithmetic and are still computed
903/// from the click-time input snapshot. One click claims the estimator
904/// slot (button greyed meanwhile); a completion older than the newest
905/// claim is dropped.
906fn estimate(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
907 let Some(est_gen) = estimate_claim() else {
908 return; // a count is already in flight
909 };
910 // Snapshot the input fields NOW (they may change while the count
911 // runs); (b)/(c) lines are cheap enough to build on the spot.
912 let (snap_wl, snap_rules, hps, tail_lines) = view.update(cx, |app, cx| {
913 let hps = match (app.state.bench_gpu, app.state.bench_cpu) {
914 (Some(g), Some(c)) => Some(g.max(c)),
915 (Some(g), None) => Some(g),
916 (None, Some(c)) => Some(c),
917 (None, None) => None,
918 };
919 let Some(hps) = hps.filter(|h| *h > 0.0) else {
920 app.state
921 .push_log("estimate: run Benchmark for times; candidate-space math only");
922 cx.notify();
923 return (String::new(), None, 0.0, Vec::new());
924 };
925
926 let wl = app.wordlist_input.read(cx).content().trim().to_string();
927 // Rule count applies to the wordlist only in rules mode; capture
928 // the path (Some ⇔ rules mode at click time) rather than a flag.
929 let rules: Option<String> = if app.attack_mode == "rules" {
930 Some(app.rules_input.read(cx).content().trim().to_string())
931 } else {
932 None
933 };
934
935 // (b) bruteforce space at best rate.
936 let custom = app
937 .charset_input
938 .read(cx)
939 .content()
940 .trim_end_matches(['\r', '\n'])
941 .as_bytes()
942 .to_vec();
943 let charset = crate::attack::charset::compose(
944 app.cs_lower,
945 app.cs_upper,
946 app.cs_digits,
947 app.cs_special,
948 &custom,
949 );
950 let mut tail: Vec<String> = Vec::new();
951 if charset.is_empty() {
952 tail.push("estimate: empty charset — bruteforce space n/a".to_string());
953 } else {
954 let min = app
955 .len_min_input
956 .read(cx)
957 .content()
958 .trim()
959 .parse::<usize>()
960 .unwrap_or(8);
961 let max = app
962 .len_max_input
963 .read(cx)
964 .content()
965 .trim()
966 .parse::<usize>()
967 .unwrap_or(10);
968 match crate::attack::BruteForce::new(charset.clone(), min, max, false) {
969 Ok(bf) => {
970 let space = bf.space();
971 tail.push(format!(
972 "estimate: bruteforce {min}..={max}: {space} candidates, worst case ~{} @ {}",
973 fmt_dur(space as f64 / hps),
974 fmt_hps(hps)
975 ));
976 }
977 Err(e) => tail.push(format!("estimate: bruteforce range invalid: {e:#}")),
978 }
979 }
980
981 // (c) entropy of the strength-input candidate against the current
982 // charset union: bits ≈ len × log2(charset size).
983 let candidate = app.strength_input.read(cx).content().trim().to_string();
984 if !candidate.is_empty() && !charset.is_empty() {
985 let csize = charset.len() as f64;
986 let bits = candidate.len() as f64 * csize.log2();
987 let guess_s = 2f64.powf(bits - 1.0) / hps;
988 tail.push(format!(
989 "estimate: {} chars × log2({}) ≈ {bits:.0} bits — avg crack ~{} @ {}",
990 candidate.len(),
991 charset.len(),
992 fmt_dur(guess_s),
993 fmt_hps(hps)
994 ));
995 } else if candidate.is_empty() {
996 tail.push("estimate: type a candidate for its entropy line".to_string());
997 }
998 cx.notify();
999 (wl, rules, hps, tail)
1000 });
1001 if hps <= 0.0 {
1002 // No benchmark yet: the early-return log above already landed.
1003 estimate_release(est_gen);
1004 return;
1005 }
1006
1007 // Heavy part off-thread: count the wordlist (+ rules) like the Import
1008 // button's executor hop, then deliver the lines through view.update.
1009 let weak = view.downgrade();
1010 cx.spawn(async move |cx| {
1011 let wl = snap_wl.clone();
1012 let rules = snap_rules.clone();
1013 let mut lines = cx
1014 .background_executor()
1015 .spawn(async move { estimate_wordlist_lines(&wl, rules.as_deref(), hps) })
1016 .await;
1017 lines.extend(tail_lines);
1018 let applied = weak.update(cx, |app, cx| {
1019 let fresh = estimate_release(est_gen);
1020 if fresh {
1021 for line in lines {
1022 app.state.push_log(line);
1023 }
1024 }
1025 cx.notify();
1026 fresh
1027 });
1028 if applied.is_err() {
1029 // The view is gone — still free the slot behind the button.
1030 estimate_release(est_gen);
1031 }
1032 })
1033 .detach();
1034}
1035
1036/// One bruteforce charset preset chip. Toggling flips the app flag;
1037/// [`crate::attack::charset::compose`] unions the active chips with the
1038/// custom field at Start.
1039fn charset_chip(
1040 id: &'static str,
1041 label: &'static str,
1042 active: bool,
1043 view: &Entity<AppRoot>,
1044 cx: &gpui::App,
1045 flag: fn(&mut AppRoot) -> &mut bool,
1046) -> gpui::Stateful<gpui::Div> {
1047 let theme = cx.theme().clone();
1048 let hover = theme.accent_bg();
1049 div()
1050 .id(gpui::SharedString::from(id))
1051 .px_2()
1052 .py_1()
1053 .rounded_md()
1054 .border_1()
1055 .border_color(theme.border())
1056 .cursor_pointer()
1057 .text_xs()
1058 .when(active, |el| el.bg(theme.accent_bg()))
1059 .when(!active, |el| el.hover(move |style| style.bg(hover)))
1060 .child(label)
1061 .on_click({
1062 let view = view.clone();
1063 move |_, _window, cx| {
1064 view.update(cx, |app, cx| {
1065 let f = flag(app);
1066 *f = !*f;
1067 cx.notify();
1068 });
1069 }
1070 })
1071}
1072
1073/// Throughput curve of the current run: one bar per progress sample,
1074/// right-aligned (newest at the right edge), height scaled to the run's
1075/// own maximum so a CPU-scale run doesn't render as a flat line next to
1076/// GPU-scale history.
1077fn hps_curve(
1078 hist: &std::collections::VecDeque<f64>,
1079 accent: gpui::Hsla,
1080) -> Option<gpui::AnyElement> {
1081 if hist.len() < 2 {
1082 return None;
1083 }
1084 const COLUMNS: usize = 40;
1085 const MAX_H: f32 = 14.0;
1086 let max = hist.iter().copied().fold(0.0f64, f64::max).max(1.0);
1087 let mut cols: Vec<gpui::Div> = Vec::with_capacity(COLUMNS);
1088 let shown: Vec<f64> = hist.iter().copied().rev().take(COLUMNS).collect();
1089 for _ in 0..COLUMNS.saturating_sub(shown.len()) {
1090 cols.push(div().w(px(6.)).h(px(1.)));
1091 }
1092 for h in shown.iter().rev() {
1093 let hpx = (2.0 + MAX_H * (*h as f32 / max as f32)).min(MAX_H + 2.0);
1094 cols.push(div().w(px(6.)).h(px(hpx)).bg(accent));
1095 }
1096 Some(
1097 h_stack()
1098 .gap_1()
1099 .items_end()
1100 .children(cols)
1101 .into_any_element(),
1102 )
1103}
1104
1105pub fn render(
1106 app: &mut AppRoot,
1107 view: &Entity<AppRoot>,
1108 _window: &mut Window,
1109 cx: &mut Context<AppRoot>,
1110) -> gpui::Div {
1111 let theme = cx.theme().clone();
1112 let cracker = &app.state.cracker;
1113 // `running` is set at Start and settled by CrackStopped/CrackError;
1114 // it is now the single source of truth (no separate in-flight flag).
1115 let running = cracker.running;
1116 let rainbow_building = cracker.rainbow_building;
1117 // Coverage fraction: mock is bounded by construction; real runs get
1118 // their worst-case total from the worker (wordlist lines, brute
1119 // space, table entries) when countable.
1120 let effective_total = if app.is_mock {
1121 Some(WORDLIST_TOTAL)
1122 } else {
1123 cracker.total.filter(|t| *t > 0)
1124 };
1125 let frac = effective_total
1126 .map(|t| (cracker.tried as f64 / t as f64).clamp(0.0, 1.0))
1127 .unwrap_or(0.0);
1128 let candidates = if let Some(t) = effective_total {
1129 format!("candidates: {} / {t}", cracker.tried)
1130 } else {
1131 format!("candidates: {}", cracker.tried)
1132 };
1133 // Worst-case remaining time (real runs): every untried candidate at
1134 // the current measured rate.
1135 let eta = (!app.is_mock && running)
1136 .then(|| fmt_worst_case(cracker.tried, cracker.hps, cracker.total))
1137 .flatten();
1138
1139 // Per-mode inputs, swapped under the attack-mode dropdown.
1140 let mode_inputs: gpui::AnyElement = match app.attack_mode.as_str() {
1141 "bruteforce" => h_stack()
1142 .gap_2()
1143 .items_center()
1144 .child(charset_chip(
1145 "cs-lower",
1146 "a-z",
1147 app.cs_lower,
1148 view,
1149 cx,
1150 |a| &mut a.cs_lower,
1151 ))
1152 .child(charset_chip(
1153 "cs-upper",
1154 "A-Z",
1155 app.cs_upper,
1156 view,
1157 cx,
1158 |a| &mut a.cs_upper,
1159 ))
1160 .child(charset_chip(
1161 "cs-digits",
1162 "0-9",
1163 app.cs_digits,
1164 view,
1165 cx,
1166 |a| &mut a.cs_digits,
1167 ))
1168 .child(charset_chip(
1169 "cs-special",
1170 "!@#…",
1171 app.cs_special,
1172 view,
1173 cx,
1174 |a| &mut a.cs_special,
1175 ))
1176 .child(charset_chip(
1177 "cs-freq-order",
1178 "freq-order",
1179 app.freq_order,
1180 view,
1181 cx,
1182 |a| &mut a.freq_order,
1183 ))
1184 .child(
1185 div().w(px(160.)).child(
1186 text_field(&app.charset_input, cx)
1187 .placeholder("custom chars")
1188 .full_width(true),
1189 ),
1190 )
1191 .child(
1192 div().w(px(64.)).child(
1193 text_field(&app.len_min_input, cx)
1194 .placeholder("min")
1195 .full_width(true),
1196 ),
1197 )
1198 .child(
1199 div().w(px(64.)).child(
1200 text_field(&app.len_max_input, cx)
1201 .placeholder("max")
1202 .full_width(true),
1203 ),
1204 )
1205 .child(
1206 small("chips + custom · min..max len · freq-order: common characters first")
1207 .muted(),
1208 )
1209 .into_any_element(),
1210 "rules" => h_stack()
1211 .gap_2()
1212 .items_end()
1213 .child(
1214 div().w(px(320.)).child(
1215 text_field(&app.wordlist_input, cx)
1216 .placeholder("/path/to/wordlist")
1217 .full_width(true),
1218 ),
1219 )
1220 .child(
1221 div().w(px(320.)).child(
1222 text_field(&app.rules_input, cx)
1223 .placeholder("/path/to/rules (hashcat-subset)")
1224 .full_width(true),
1225 ),
1226 )
1227 .child(small("word × mutation rules").muted())
1228 .into_any_element(),
1229 "hybrid" => h_stack()
1230 .gap_2()
1231 .items_center()
1232 .child(
1233 div().w(px(280.)).child(
1234 text_field(&app.wordlist_input, cx)
1235 .placeholder("/path/to/wordlist")
1236 .full_width(true),
1237 ),
1238 )
1239 .child(charset_chip(
1240 "cs-lower",
1241 "a-z",
1242 app.cs_lower,
1243 view,
1244 cx,
1245 |a| &mut a.cs_lower,
1246 ))
1247 .child(charset_chip(
1248 "cs-upper",
1249 "A-Z",
1250 app.cs_upper,
1251 view,
1252 cx,
1253 |a| &mut a.cs_upper,
1254 ))
1255 .child(charset_chip(
1256 "cs-digits",
1257 "0-9",
1258 app.cs_digits,
1259 view,
1260 cx,
1261 |a| &mut a.cs_digits,
1262 ))
1263 .child(charset_chip(
1264 "cs-special",
1265 "!@#…",
1266 app.cs_special,
1267 view,
1268 cx,
1269 |a| &mut a.cs_special,
1270 ))
1271 .child(
1272 div().w(px(120.)).child(
1273 text_field(&app.charset_input, cx)
1274 .placeholder("custom chars")
1275 .full_width(true),
1276 ),
1277 )
1278 .child(
1279 div().w(px(56.)).child(
1280 text_field(&app.hyb_min_input, cx)
1281 .placeholder("min")
1282 .full_width(true),
1283 ),
1284 )
1285 .child(
1286 div().w(px(56.)).child(
1287 text_field(&app.hyb_max_input, cx)
1288 .placeholder("max")
1289 .full_width(true),
1290 ),
1291 )
1292 .child(small("word + charset suffix len min..max (1..=4)").muted())
1293 .into_any_element(),
1294 "rainbow" => h_stack()
1295 .gap_2()
1296 .items_end()
1297 .child(
1298 div().w(px(360.)).child(
1299 text_field(&app.rainbow_input, cx)
1300 .placeholder("/path/to/pmk-table")
1301 .full_width(true),
1302 ),
1303 )
1304 .child(
1305 div().w(px(280.)).child(
1306 text_field(&app.wordlist_input, cx)
1307 .placeholder("wordlist to build from")
1308 .full_width(true),
1309 ),
1310 )
1311 .child(
1312 button("btn-rainbow-build", "Build table")
1313 .disabled(rainbow_building || running)
1314 .on_click({
1315 let view = view.clone();
1316 move |_, window, cx| build(&view, window, cx)
1317 }),
1318 )
1319 .into_any_element(),
1320 _ => div()
1321 .w(px(360.))
1322 .child(
1323 text_field(&app.wordlist_input, cx)
1324 .placeholder("/path/to/wordlist")
1325 .full_width(true),
1326 )
1327 .into_any_element(),
1328 };
1329
1330 // Recent cracker activity: surfaces errors, estimates, import and
1331 // benchmark results that would otherwise only be visible on the Log
1332 // page.
1333 let activity: Vec<String> = app
1334 .state
1335 .log
1336 .iter()
1337 .filter(|line| {
1338 line.starts_with("cracker:")
1339 || line.starts_with("crack FAILED") // backend-failure reason, set by apply()
1340 || line.starts_with("rainbow:")
1341 || line.starts_with("estimate:")
1342 || line.starts_with("benchmark:")
1343 || line.starts_with("import:")
1344 || line.starts_with("pmk cache")
1345 || line.starts_with("profiles:")
1346 || line.contains("PASSWORD")
1347 })
1348 .rev()
1349 .take(5)
1350 .cloned()
1351 .collect::<Vec<_>>()
1352 .into_iter()
1353 .rev()
1354 .collect();
1355
1356 // Presets + recent wordlists: one-click chips applied to the
1357 // wordlist/rules fields and (for presets) the attack-mode select.
1358 let hover_bg = theme.accent_bg();
1359 let mut preset_row = h_stack().gap_2().items_center();
1360 let has_presets =
1361 !app.profiles.profiles.is_empty() || !app.profiles.recent_wordlists.is_empty();
1362 for p in &app.profiles.profiles {
1363 let profile = p.clone();
1364 preset_row = preset_row.child(
1365 div()
1366 .id(gpui::SharedString::from(format!("preset-{}", p.name)))
1367 .px_2()
1368 .py_1()
1369 .rounded_md()
1370 .border_1()
1371 .border_color(theme.border())
1372 .cursor_pointer()
1373 .text_xs()
1374 .hover(move |style| style.bg(hover_bg))
1375 .child(p.name.clone())
1376 .on_click({
1377 let view = view.clone();
1378 move |_, _window, cx| apply_preset(profile.clone(), &view, cx)
1379 }),
1380 );
1381 }
1382 if !app.profiles.profiles.is_empty() {
1383 preset_row = preset_row.child(button("btn-preset-save", "Save preset").on_click({
1384 let view = view.clone();
1385 move |_, window, cx| save_preset(&view, window, cx)
1386 }));
1387 }
1388 let mut recent_row = h_stack().gap_2().items_center();
1389 for wl in &app.profiles.recent_wordlists {
1390 let wl_path = wl.clone();
1391 let base = std::path::Path::new(wl)
1392 .file_name()
1393 .map(|n| n.to_string_lossy().into_owned())
1394 .unwrap_or_else(|| wl.clone());
1395 recent_row = recent_row.child(
1396 div()
1397 .id(gpui::SharedString::from(format!("recent-{wl}")))
1398 .px_2()
1399 .py_1()
1400 .rounded_md()
1401 .border_1()
1402 .border_color(theme.border())
1403 .cursor_pointer()
1404 .text_xs()
1405 .hover(move |style| style.bg(hover_bg))
1406 .child(base)
1407 .on_click({
1408 let view = view.clone();
1409 move |_, _window, cx| {
1410 let wl = wl_path.clone();
1411 view.update(cx, |app, cx| {
1412 app.wordlist_input.update(cx, |input, cx| {
1413 input.set_content(wl, cx);
1414 });
1415 cx.notify();
1416 });
1417 }
1418 }),
1419 );
1420 }
1421
1422 // Benchmark card lines (below the Start/Stop row).
1423 let bench_gpu_line = match app.state.bench_gpu {
1424 Some(g) => format!("GPU: {}", fmt_hps(g)),
1425 None => {
1426 if app.state.bench_cpu.is_some() {
1427 "GPU: none (CPU only)".to_string()
1428 } else {
1429 "not measured — run Benchmark".to_string()
1430 }
1431 }
1432 };
1433 let bench_cpu_line = app
1434 .state
1435 .bench_cpu
1436 .map(|c| format!("CPU: {}", fmt_hps(c)))
1437 .unwrap_or_default();
1438 let bench_disabled = app.bench_running || cracker.running || cracker.rainbow_building;
1439
1440 let mut page = v_stack()
1441 .size_full()
1442 .gap_3()
1443 .p_4()
1444 .child(
1445 h_stack()
1446 .items_center()
1447 .gap_3()
1448 .child(h3("Handshake Cracker"))
1449 .child(small("PBKDF2-SHA1 · WPA/WPA2"))
1450 .child(div().flex_1())
1451 .child(
1452 button("btn-import", "Import .cap/.pcap/.hc22000")
1453 .disabled(app.import_busy)
1454 .on_click({
1455 let view = view.clone();
1456 move |_, window, cx| import_captures(&view, window, cx)
1457 }),
1458 ),
1459 )
1460 .when(has_presets, |el| {
1461 el.child(preset_row).when(
1462 !app.profiles.recent_wordlists.is_empty() || !app.profiles.profiles.is_empty(),
1463 |el2| el2.child(recent_row),
1464 )
1465 })
1466 .when(!has_presets, |el| {
1467 // No saved state yet — still offer one-click saving of the
1468 // current setup.
1469 el.child(h_stack().gap_2().items_center().child(
1470 button("btn-preset-save", "Save preset").on_click({
1471 let view = view.clone();
1472 move |_, window, cx| save_preset(&view, window, cx)
1473 }),
1474 ))
1475 })
1476 .child(
1477 h_stack()
1478 .gap_3()
1479 .items_end()
1480 .child(div().w(px(360.)).child(app.target_select.clone()))
1481 .child(div().w(px(200.)).child(app.attack_select.clone()))
1482 .child(mode_inputs)
1483 .child(text(backend_label(app.is_mock)).small().muted()),
1484 )
1485 .child(
1486 h_stack()
1487 .gap_3()
1488 .items_center()
1489 .child(
1490 button("btn-crack-start", "Start")
1491 .disabled(running || app.bench_running)
1492 .on_click({
1493 let view = view.clone();
1494 move |_, window, cx| start(&view, window, cx)
1495 }),
1496 )
1497 .child(
1498 button("btn-crack-stop", "Stop")
1499 .destructive()
1500 .disabled(!running)
1501 .on_click({
1502 let view = view.clone();
1503 move |_, window, cx| stop(&view, window, cx)
1504 }),
1505 )
1506 .when(running, |el| el.child(loading_indicator().small())),
1507 )
1508 .child(gpuikit::elements::separator::separator())
1509 .child(
1510 h_stack()
1511 .gap_4()
1512 .child(small(format!(
1513 "rate: {}",
1514 fmt_hps(if running { cracker.hps } else { 0.0 })
1515 )))
1516 .child(small(candidates))
1517 .child(small({
1518 // Coverage % whenever a total exists; ETA needs a
1519 // live run too.
1520 let pct = effective_total.map(|_| format!("{:.1}%", frac * 100.0));
1521 match (pct, &eta) {
1522 (Some(p), Some(e)) => format!("{p} · {e}"),
1523 (Some(p), None) => p,
1524 (None, Some(e)) => e.clone(),
1525 (None, None) => String::new(),
1526 }
1527 })),
1528 )
1529 .child(progress(frac as f32).width(px(520.)))
1530 .children(hps_curve(&app.state.hps_hist, theme.accent()).map(|curve| {
1531 v_stack()
1532 .gap_1()
1533 .child(small("rate over time (one bar per progress sample)").muted())
1534 .child(curve)
1535 }))
1536 .child(
1537 // Benchmark card: measured crack speed on this machine.
1538 h_stack()
1539 .gap_3()
1540 .items_center()
1541 .p_3()
1542 .rounded_md()
1543 .border_1()
1544 .border_color(theme.border())
1545 .child(small("crack speed on this machine"))
1546 .child(
1547 button("btn-benchmark", "Benchmark (3s)")
1548 .disabled(bench_disabled)
1549 .on_click({
1550 let view = view.clone();
1551 move |_, window, cx| benchmark(&view, window, cx)
1552 }),
1553 )
1554 .when(app.bench_running, |el| {
1555 el.child(loading_indicator().small())
1556 })
1557 .child(small(bench_gpu_line).muted())
1558 .child(small(bench_cpu_line).muted()),
1559 )
1560 .child(
1561 // Estimator card: worst-case times from the measured rate.
1562 h_stack()
1563 .gap_3()
1564 .items_center()
1565 .p_3()
1566 .rounded_md()
1567 .border_1()
1568 .border_color(theme.border())
1569 .child(small("candidate strength / time estimate"))
1570 .child(
1571 div().w(px(220.)).child(
1572 text_field(&app.strength_input, cx)
1573 .placeholder("type a candidate password")
1574 .full_width(true),
1575 ),
1576 )
1577 .child(
1578 button("btn-estimate", "Estimate")
1579 // Greyed while the background wordlist count runs
1580 // (double-click dedupe) and during a benchmark.
1581 .disabled(app.bench_running || estimate_busy())
1582 .on_click({
1583 let view = view.clone();
1584 move |_, window, cx| estimate(&view, window, cx)
1585 }),
1586 )
1587 .when(estimate_busy(), |el| el.child(loading_indicator().small()))
1588 .child(small("results land in recent activity below").muted()),
1589 );
1590
1591 // Recent captures: the newest few crackable targets, so the page shows
1592 // what material exists without opening the dropdown. Newest last in
1593 // state → reversed for display.
1594 let recent_caps: Vec<String> = app
1595 .state
1596 .capture_descs()
1597 .into_iter()
1598 .rev()
1599 .take(4)
1600 .collect();
1601 if !recent_caps.is_empty() {
1602 page = page.child(
1603 v_stack()
1604 .gap_1()
1605 .child(small("recent captures (all of them are in the target dropdown)").muted())
1606 .children(
1607 recent_caps
1608 .into_iter()
1609 .map(|d| text(d).code().small().into_any_element()),
1610 )
1611 .into_any_element(),
1612 );
1613 }
1614
1615 if let Some(found) = &cracker.found {
1616 page = page.child(
1617 h_stack()
1618 .gap_3()
1619 .items_center()
1620 .w(px(520.))
1621 .p_3()
1622 .rounded_md()
1623 .bg(theme.warning())
1624 .text_color(theme.bg())
1625 .child(text(format!("PASSWORD FOUND: {found}")).bold())
1626 .into_any_element(),
1627 );
1628 }
1629
1630 // Interrupted-run resume banner (saved session file matched to a
1631 // loaded capture; hidden while anything runs).
1632 if !running
1633 && !rainbow_building
1634 && !app.is_mock
1635 && let Some(r) = &cracker.resume
1636 {
1637 let status = match r.total {
1638 Some(t) => format!("{} / {t} tried", r.done),
1639 None => format!("{} tried", r.done),
1640 };
1641 page = page.child(
1642 h_stack()
1643 .gap_3()
1644 .items_center()
1645 .p_3()
1646 .rounded_md()
1647 .border_1()
1648 .border_color(theme.border())
1649 .bg(theme.accent_bg())
1650 .child(small(format!(
1651 "saved run: {} — {} · {status}",
1652 r.target_desc,
1653 r.attack.describe()
1654 )))
1655 .child(button("btn-crack-resume", "Resume").on_click({
1656 let view = view.clone();
1657 move |_, window, cx| resume_saved(&view, window, cx)
1658 }))
1659 .child(
1660 button("btn-crack-discard", "Discard")
1661 .destructive()
1662 .on_click({
1663 let view = view.clone();
1664 move |_, window, cx| discard_saved(&view, window, cx)
1665 }),
1666 ),
1667 );
1668 }
1669
1670 if !activity.is_empty() {
1671 let mut block = v_stack().gap_1();
1672 for line in activity {
1673 block = block.child(small(line).muted());
1674 }
1675 page = page.child(block);
1676 }
1677
1678 if rainbow_building {
1679 page = page.child(
1680 h_stack()
1681 .gap_3()
1682 .items_center()
1683 .child(loading_indicator().small())
1684 .child(small(format!(
1685 "rainbow build: {} PMKs · {} · {}",
1686 cracker.rainbow_done,
1687 fmt_hps(cracker.rainbow_hps),
1688 fmt_worst_case(
1689 cracker.rainbow_done,
1690 cracker.rainbow_hps,
1691 cracker.rainbow_total
1692 )
1693 .unwrap_or_default()
1694 )))
1695 .child(
1696 button("btn-rainbow-stop", "Stop build")
1697 .destructive()
1698 .on_click({
1699 let view = view.clone();
1700 move |_, window, cx| build_stop(&view, window, cx)
1701 }),
1702 ),
1703 );
1704 }
1705
1706 page
1707}
1708
1709#[cfg(test)]
1710mod tests {
1711 //! Regression tests for the async-estimate single-flight/stale-drop
1712 //! guard and the pure worker-side estimate line formatting. UI glue
1713 //! (gpui entities, event drains) is exercised by clicking in the app;
1714 //! the defect here — a second click racing an in-flight 14 GB count,
1715 //! or a stale completion overwriting newer state — lives entirely in
1716 //! these two functions.
1717 use super::*;
1718
1719 /// All guard tests share the module statics, so they run as ONE test
1720 /// function (cargo would otherwise interleave them across threads).
1721 #[test]
1722 fn estimate_guard_single_flight_and_stale_drop() {
1723 // First click claims the slot; a concurrent second click is a
1724 // no-op (the button is also disabled while busy).
1725 let first = estimate_claim().expect("slot must be free");
1726 assert!(
1727 estimate_claim().is_none(),
1728 "second click while a count runs must be deduped"
1729 );
1730 assert!(estimate_busy(), "button must read busy");
1731
1732 // A completion carrying the newest generation is applied.
1733 assert!(estimate_release(first), "newest completion is fresh");
1734 assert!(!estimate_busy(), "slot freed after completion");
1735
1736 // After release a new click gets a NEW, higher generation — a
1737 // completion from the older generation landing late is stale and
1738 // must be dropped WITHOUT freeing the newer claim's slot.
1739 let second = estimate_claim().expect("slot free after release");
1740 assert!(second > first, "generations tick upward");
1741 assert!(
1742 !estimate_release(first),
1743 "older generation landing after a newer claim is stale"
1744 );
1745 assert!(
1746 estimate_busy(),
1747 "stale completion must not free the newer claim's slot"
1748 );
1749 // The real completion of the newer count still applies and frees.
1750 assert!(estimate_release(second));
1751 assert!(!estimate_busy());
1752 }
1753
1754 #[test]
1755 fn estimate_wordlist_lines_mock_and_real_counts() {
1756 // Empty path = mock size, no file touched.
1757 let lines = estimate_wordlist_lines("", None, 1_000_000.0);
1758 assert_eq!(lines.len(), 1);
1759 assert!(
1760 lines[0].contains("(mock-size)") && lines[0].contains("1000000 candidates"),
1761 "expected mock-size candidate line, got {:?}",
1762 lines[0]
1763 );
1764
1765 // A real (tiny) wordlist is counted by line.
1766 let dir = std::env::temp_dir();
1767 let wl = dir.join(format!("wifi_lab-est-{}-a.lst", std::process::id()));
1768 std::fs::write(&wl, b"alpha\nbeta\ngamma\n").expect("write wordlist");
1769 let lines = estimate_wordlist_lines(&wl.display().to_string(), None, 1_000_000.0);
1770 assert_eq!(lines.len(), 1);
1771 assert!(
1772 lines[0].contains(&format!("{}: 3 candidates", wl.display())),
1773 "expected 3-line count, got {:?}",
1774 lines[0]
1775 );
1776
1777 // Rules mode multiplies the space by the rule count.
1778 let rules = dir.join(format!("wifi_lab-est-{}-a.rule", std::process::id()));
1779 std::fs::write(&rules, b":\n$1\n# comment\n\n$2\n").expect("write rules");
1780 let lines = estimate_wordlist_lines(
1781 &wl.display().to_string(),
1782 Some(rules.display().to_string()).as_deref(),
1783 1_000_000.0,
1784 );
1785 assert_eq!(lines.len(), 1);
1786 assert!(
1787 lines[0].contains("× 3 rules") && lines[0].contains("9 candidates"),
1788 "expected 3 lines × 3 rules = 9, got {:?}",
1789 lines[0]
1790 );
1791
1792 // A missing wordlist yields the error line instead of guessing.
1793 let lines = estimate_wordlist_lines("/nonexistent/nope.lst", None, 1_000_000.0);
1794 assert_eq!(lines.len(), 1);
1795 assert!(lines[0].starts_with("estimate: wordlist unreadable:"));
1796
1797 // Rules mode with an unreadable rules file reports the error and
1798 // suppresses the (unknown) space line — same as the old sync code.
1799 let lines = estimate_wordlist_lines(
1800 &wl.display().to_string(),
1801 Some("/nonexistent/nope.rule"),
1802 1_000_000.0,
1803 );
1804 assert_eq!(lines.len(), 1);
1805 assert!(lines[0].starts_with("estimate: rules unreadable:"));
1806
1807 let _ = std::fs::remove_file(&wl);
1808 let _ = std::fs::remove_file(&rules);
1809 }
1810}