forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

store.rs686 lines, 25.4 KiBHistoryRawDownload
1//! Persistent UI-side data under `~/wifi_lab`:
2//! - `labels.json` — user-assigned names by MAC (APs and clients share one
3//! namespace; a MAC is unique).
4//! - `captures.jsonl` — every complete handshake / PMKID capture, one JSON
5//! line each, appended as they arrive and reloaded at startup (the
6//! cracker keeps working across restarts without re-attacking).
7//!
8//! UI-only data — the privileged service never touches it.
9
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13use anyhow::{Context, Result};
14use serde::{Deserialize, Serialize};
15
16use crate::common::{HandshakeCapture, MacAddr, PmkidCapture};
17
18/// `~/wifi_lab`. When HOME is unset the store lives under the system temp
19/// dir (stable absolute path, independent of the caller's cwd) and a
20/// warning is logged.
21pub fn data_dir() -> PathBuf {
22 data_dir_impl(std::env::var_os("HOME").as_deref(), &std::env::temp_dir())
23}
24
25/// Split out of [`data_dir`] for tests: `home` is the raw HOME value,
26/// `tmp` the fallback base when HOME is unset/empty.
27fn data_dir_impl(home: Option<&std::ffi::OsStr>, tmp: &Path) -> PathBuf {
28 let base = match home {
29 Some(h) if !h.is_empty() => PathBuf::from(h),
30 _ => {
31 eprintln!(
32 "wifi_lab: HOME is unset — data dir is {} (stable path, but outside any home)",
33 tmp.join("wifi_lab").display()
34 );
35 return tmp.join("wifi_lab");
36 }
37 };
38 let new = base.join("wifi_lab");
39 let old = base.join("wifilab");
40 // One-time move from the pre-rename location. Racing instances (or a
41 // partial earlier migration) can make the target appear between the
42 // check and the rename: rename unconditionally and treat "target
43 // exists" as a finished migration, not an error.
44 if old.exists() {
45 match std::fs::rename(&old, &new) {
46 Ok(()) => {}
47 Err(e) if new.exists() => {
48 let _ = e; // lost the race — the target is the live store
49 }
50 Err(e) => eprintln!(
51 "wifi_lab: could not migrate {} → {} ({e}); starting fresh at the new path",
52 old.display(),
53 new.display()
54 ),
55 }
56 }
57 new
58}
59
60/// Atomically replace `path` with `body`: write to a unique sibling tmp
61/// file (`<name>.tmp.<pid>-<nanos>`), fsync the file, rename over the
62/// target, then fsync the containing directory so the rename itself is
63/// durable. A crash between the steps can leave the tmp file behind —
64/// [`cleanup_stale_tmp`] removes it on the next load.
65fn write_atomic(path: &Path, body: &str) -> Result<()> {
66 use std::io::Write as _;
67
68 let dir = path.parent().expect("store path has a parent");
69 std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
70 let nanos = std::time::SystemTime::now()
71 .duration_since(std::time::UNIX_EPOCH)
72 .map(|d| d.as_nanos())
73 .unwrap_or(0);
74 let name = path
75 .file_name()
76 .and_then(|n| n.to_str())
77 .expect("store path has a file name");
78 let tmp = path.with_file_name(format!("{name}.tmp.{}-{nanos}", std::process::id()));
79 let write_result = (|| -> Result<()> {
80 let mut f =
81 std::fs::File::create(&tmp).with_context(|| format!("creating {}", tmp.display()))?;
82 f.write_all(body.as_bytes())
83 .with_context(|| format!("writing {}", tmp.display()))?;
84 f.sync_all()
85 .with_context(|| format!("fsyncing {}", tmp.display()))?;
86 Ok(())
87 })();
88 if let Err(e) = write_result {
89 let _ = std::fs::remove_file(&tmp);
90 return Err(e);
91 }
92 std::fs::rename(&tmp, path)
93 .with_context(|| format!("renaming {} → {}", tmp.display(), path.display()))?;
94 std::fs::File::open(dir)
95 .and_then(|d| d.sync_all())
96 .with_context(|| format!("fsyncing {}", dir.display()))?;
97 Ok(())
98}
99
100/// Remove stale `<name>.tmp.*` siblings of `path` left over from a crashed
101/// atomic write. Called on every load; failures are ignored (a read-only
102/// dir must not break loading).
103fn cleanup_stale_tmp(path: &Path) {
104 let Some(dir) = path.parent() else { return };
105 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
106 return;
107 };
108 let prefix = format!("{name}.tmp.");
109 let Ok(entries) = std::fs::read_dir(dir) else {
110 return;
111 };
112 for entry in entries.flatten() {
113 let stale = entry
114 .file_name()
115 .to_str()
116 .is_some_and(|n| n.starts_with(&prefix));
117 if stale {
118 let _ = std::fs::remove_file(entry.path());
119 }
120 }
121}
122
123fn labels_path() -> PathBuf {
124 data_dir().join("labels.json")
125}
126
127fn captures_path() -> PathBuf {
128 data_dir().join("captures.jsonl")
129}
130
131fn session_path() -> PathBuf {
132 data_dir().join("crack-session.json")
133}
134
135/// One persisted capture (tagged JSON line in `captures.jsonl`).
136#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(tag = "kind", rename_all = "lowercase")]
138pub enum StoredCapture {
139 Handshake(HandshakeCapture),
140 Pmkid(PmkidCapture),
141}
142
143impl StoredCapture {
144 /// Display identity used for dedup on load.
145 fn id(&self) -> String {
146 match self {
147 StoredCapture::Handshake(h) => format!("hs:{}:{}", h.ap, h.client),
148 StoredCapture::Pmkid(p) => format!("pmkid:{}", p.ap),
149 }
150 }
151}
152
153fn load_labels_from(path: &Path) -> Result<BTreeMap<MacAddr, String>> {
154 cleanup_stale_tmp(path);
155 let raw = match std::fs::read_to_string(path) {
156 Ok(s) => s,
157 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
158 return Ok(BTreeMap::new());
159 }
160 Err(e) => return Err(e).context("reading labels.json"),
161 };
162 let by_str: BTreeMap<String, String> =
163 serde_json::from_str(&raw).context("parsing labels.json")?;
164 let mut out = BTreeMap::new();
165 for (mac, label) in by_str {
166 let mac: MacAddr = mac
167 .parse()
168 .with_context(|| format!("bad MAC key {mac:?}"))?;
169 if !label.is_empty() {
170 out.insert(mac, label);
171 }
172 }
173 Ok(out)
174}
175
176/// Load all labels; a missing file is an empty store, a corrupt one is an
177/// error (callers log it and start empty rather than clobbering).
178pub fn load() -> Result<BTreeMap<MacAddr, String>> {
179 load_labels_from(&labels_path())
180}
181
182fn save_labels_to(path: &Path, labels: &BTreeMap<MacAddr, String>) -> Result<()> {
183 let by_str: BTreeMap<String, &String> =
184 labels.iter().map(|(mac, l)| (mac.to_string(), l)).collect();
185 let body = serde_json::to_string_pretty(&by_str).expect("string map serialization");
186 write_atomic(path, &body)
187}
188
189/// Persist the whole label map (labels are few; rewriting is cheap, made
190/// crash-safe by [`write_atomic`]).
191pub fn save(labels: &BTreeMap<MacAddr, String>) -> Result<()> {
192 save_labels_to(&labels_path(), labels)
193}
194
195fn append_capture_to(path: &Path, cap: &StoredCapture) -> Result<()> {
196 let dir = path.parent().expect("captures path has a parent");
197 std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
198 use std::io::Write as _;
199 let mut f = std::fs::OpenOptions::new()
200 .create(true)
201 .append(true)
202 .open(path)
203 .with_context(|| format!("opening {}", path.display()))?;
204 let line = serde_json::to_string(cap).context("serializing capture")?;
205 writeln!(f, "{line}").with_context(|| format!("appending to {}", path.display()))
206}
207
208/// Append one capture to `captures.jsonl`. Called the moment a capture
209/// arrives — the file survives a crash right after.
210pub fn append_capture(cap: &StoredCapture) -> Result<()> {
211 append_capture_to(&captures_path(), cap)
212}
213
214fn load_captures_from(path: &Path) -> Result<Vec<StoredCapture>> {
215 let raw = match std::fs::read_to_string(path) {
216 Ok(s) => s,
217 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
218 Err(e) => return Err(e).context("reading captures.jsonl"),
219 };
220 let mut seen = std::collections::BTreeSet::new();
221 let mut out = Vec::new();
222 for (n, line) in raw.lines().enumerate() {
223 let line = line.trim();
224 if line.is_empty() {
225 continue;
226 }
227 match serde_json::from_str::<StoredCapture>(line) {
228 Ok(cap) => {
229 if seen.insert(cap.id()) {
230 out.push(cap);
231 }
232 }
233 // One corrupt line must not kill the whole archive.
234 Err(e) => eprintln!(
235 "wifi_lab: skipping corrupt captures.jsonl line {}: {e}",
236 n + 1
237 ),
238 }
239 }
240 Ok(out)
241}
242
243/// Load every stored capture (deduped by AP/client identity). A corrupt
244/// FILE is an error; individual corrupt lines are skipped.
245pub fn load_captures() -> Result<Vec<StoredCapture>> {
246 load_captures_from(&captures_path())
247}
248
249// ---------------------------------------------------------------------------
250// Crack session (resume): the interrupted run's position, so a later start
251// — in this or a future session — continues instead of restarting.
252// ---------------------------------------------------------------------------
253
254/// Current on-disk session format. v2: `done` is an exact RAW stream
255/// position — resume seeks/skips past exactly the already-verified
256/// candidates for every attack mode (see `attack.rs` position plumbing).
257pub const SESSION_VERSION: u32 = 2;
258
259/// Older files carry no `version` field: they are v1.
260fn default_version() -> u32 {
261 1
262}
263
264/// A stopped (not finished) crack run: which capture, which attack, how
265/// far it had gotten. Written throttle-throttled on progress and once on
266/// stop; deleted when the run finds the password or exhausts the space.
267///
268/// Version semantics: v1 (no `version` field) counted YIELDED candidates
269/// in `done`, which drifted from the raw stream once the PMK cache skipped
270/// entries or rules/hybrid filtered candidates — resuming best-effort may
271/// REDO some work but never skips untried candidates. v2 counts exact raw
272/// positions; resume is exact (`never redo, never skip`) for wordlist /
273/// rules / hybrid / bruteforce / rainbow.
274#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
275pub struct CrackSession {
276 /// File format version; [`SESSION_VERSION`] for newly written files.
277 #[serde(default = "default_version")]
278 pub version: u32,
279 pub capture: StoredCapture,
280 pub attack: crate::attack::Attack,
281 /// Candidates verified so far (resume seeks/skips past these); a raw
282 /// stream position in v2 files (see above).
283 pub done: u64,
284 /// Worst-case total of the run (see the ETA plumbing), when countable.
285 pub total: Option<u64>,
286}
287
288impl CrackSession {
289 /// A v2 session for the interrupted run.
290 pub fn new(
291 capture: StoredCapture,
292 attack: crate::attack::Attack,
293 done: u64,
294 total: Option<u64>,
295 ) -> Self {
296 CrackSession {
297 version: SESSION_VERSION,
298 capture,
299 attack,
300 done,
301 total,
302 }
303 }
304}
305
306fn save_session_to(path: &Path, session: &CrackSession) -> Result<()> {
307 let json = serde_json::to_string_pretty(session).context("serializing crack session")?;
308 write_atomic(path, &json)
309}
310
311/// Persist the session (crash-safe via [`write_atomic`]).
312pub fn save_session(session: &CrackSession) -> Result<()> {
313 save_session_to(&session_path(), session)
314}
315
316fn load_session_from(path: &Path) -> Result<Option<CrackSession>> {
317 cleanup_stale_tmp(path);
318 match std::fs::read_to_string(path) {
319 Ok(s) => Ok(Some(
320 serde_json::from_str(&s).context("parsing crack-session.json")?,
321 )),
322 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
323 Err(e) => Err(e).context("reading crack-session.json"),
324 }
325}
326
327/// Load the saved session; `None` when no run was interrupted. A corrupt
328/// file is an error (callers log it and start fresh rather than resuming
329/// garbage).
330pub fn load_session() -> Result<Option<CrackSession>> {
331 load_session_from(&session_path())
332}
333
334/// Drop the saved session (run found/exhausted, or user discarded).
335/// Missing file is fine.
336pub fn clear_session() -> Result<()> {
337 match std::fs::remove_file(session_path()) {
338 Ok(()) => Ok(()),
339 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
340 Err(e) => Err(e).context("removing crack-session.json"),
341 }
342}
343
344// ---------------------------------------------------------------------------
345// Per-SSID PMK cache: `~/wifi_lab/cache/<ssid-hex>.pmk` in rainbow text
346// format — PMKs computed on earlier CPU runs are reusable for ANY capture
347// of the same SSID without re-running PBKDF2.
348// ---------------------------------------------------------------------------
349
350/// `~/wifi_lab/cache` — created on use by the cache readers/writers.
351pub fn cache_dir() -> PathBuf {
352 data_dir().join("cache")
353}
354
355/// Cache table path for one SSID: lowercase hex of the raw SSID bytes +
356/// `.pmk` (filesystem-safe for arbitrary SSID encodings).
357pub fn cache_file(ssid: &str) -> PathBuf {
358 let hex: String = ssid.bytes().map(|b| format!("{b:02x}")).collect();
359 cache_dir().join(format!("{hex}.pmk"))
360}
361
362// ---------------------------------------------------------------------------
363// Crack profiles + recent wordlists (`~/wifi_lab/profiles.json`): user-saved
364// attack setups for one-click reuse on the cracker page.
365// ---------------------------------------------------------------------------
366
367/// One saved attack setup (mode/wl/rules as the cracker page fields).
368#[derive(Clone, Debug, Default, Serialize, Deserialize)]
369pub struct CrackProfile {
370 pub name: String,
371 pub mode: String,
372 pub wordlist: String,
373 pub rules: Option<String>,
374}
375
376/// The whole profiles file: saved presets + MRU wordlist list (cap 5).
377#[derive(Clone, Debug, Default, Serialize, Deserialize)]
378pub struct Profiles {
379 pub profiles: Vec<CrackProfile>,
380 pub recent_wordlists: Vec<String>,
381}
382
383fn profiles_path() -> PathBuf {
384 data_dir().join("profiles.json")
385}
386
387fn load_profiles_from(path: &Path) -> Result<Profiles> {
388 cleanup_stale_tmp(path);
389 match std::fs::read_to_string(path) {
390 Ok(s) => match serde_json::from_str::<Profiles>(&s) {
391 Ok(p) => Ok(p),
392 Err(e) => {
393 eprintln!("wifi_lab: profiles.json unreadable ({e}), starting fresh");
394 Ok(Profiles::default())
395 }
396 },
397 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Profiles::default()),
398 Err(e) => Err(e).context("reading profiles.json"),
399 }
400}
401
402/// Load profiles; missing or unparseable file starts empty (never clobbers).
403pub fn load_profiles() -> Result<Profiles> {
404 load_profiles_from(&profiles_path())
405}
406
407fn save_profiles_to(path: &Path, p: &Profiles) -> Result<()> {
408 let body = serde_json::to_string_pretty(p).context("serializing profiles")?;
409 write_atomic(path, &body)
410}
411
412/// Persist profiles (crash-safe via [`write_atomic`]).
413pub fn save_profiles(p: &Profiles) -> Result<()> {
414 save_profiles_to(&profiles_path(), p)
415}
416
417/// MRU-insert a wordlist path at the front of `recent_wordlists`, deduped,
418/// capped at 5.
419pub fn remember_wordlist(p: &mut Profiles, path: &str) {
420 p.recent_wordlists.retain(|w| w != path);
421 p.recent_wordlists.insert(0, path.to_string());
422 p.recent_wordlists.truncate(5);
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428
429 fn tmp(name: &str) -> PathBuf {
430 std::env::temp_dir().join(format!("wifi_lab-store-test-{}-{name}", std::process::id()))
431 }
432
433 #[test]
434 fn labels_roundtrip() {
435 let dir = tmp("labels");
436 let path = dir.join("labels.json");
437 let mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap();
438 let mut labels = BTreeMap::new();
439 labels.insert(mac, "living room".to_string());
440 save_labels_to(&path, &labels).unwrap();
441 let back = load_labels_from(&path).unwrap();
442 assert_eq!(back.get(&mac).map(String::as_str), Some("living room"));
443 let _ = std::fs::remove_dir_all(&dir);
444 }
445
446 #[test]
447 fn labels_missing_file_is_empty() {
448 let back = load_labels_from(&tmp("nope").join("labels.json")).unwrap();
449 assert!(back.is_empty());
450 }
451
452 #[test]
453 fn session_roundtrip_and_missing() {
454 let dir = tmp("session");
455 let path = dir.join("crack-session.json");
456 assert!(load_session_from(&path).unwrap().is_none());
457 let session = CrackSession::new(
458 StoredCapture::Pmkid(PmkidCapture {
459 ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(),
460 client: "11:22:33:44:55:66".parse().unwrap(),
461 essid: "testnet".into(),
462 pmkid: [7u8; 16],
463 }),
464 crate::attack::Attack::Bruteforce {
465 charset: b"01".to_vec(),
466 min: 8,
467 max: 10,
468 freq_order: true,
469 },
470 12_345,
471 Some(1_114_100),
472 );
473 assert_eq!(session.version, SESSION_VERSION);
474 save_session_to(&path, &session).unwrap();
475 let back = load_session_from(&path).unwrap().expect("saved");
476 assert_eq!(back, session);
477 let _ = std::fs::remove_dir_all(&dir);
478 }
479
480 #[test]
481 fn session_v1_file_loads_with_version_1() {
482 // Files written before the version field existed (no "version"
483 // key) must still parse: best-effort resume (may redo some work,
484 // never skips untried candidates).
485 let dir = tmp("session-v1");
486 let path = dir.join("crack-session.json");
487 std::fs::create_dir_all(&dir).unwrap();
488 // Field shapes are what the current serializers emit (v1 and v2
489 // differ ONLY in the added `version` key): MACs serialize as
490 // 6-byte arrays, Attack as an externally-tagged enum.
491 let v1 = serde_json::json!({
492 "capture": {
493 "kind": "pmkid",
494 "ap": [170, 187, 204, 221, 238, 255],
495 "client": [17, 34, 51, 68, 85, 102],
496 "essid": "testnet",
497 "pmkid": [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
498 },
499 "attack": { "Bruteforce": { "charset": [48, 49], "min": 8, "max": 10, "freq_order": false } },
500 "done": 4242u64,
501 "total": null,
502 });
503 std::fs::write(&path, serde_json::to_string(&v1).unwrap()).unwrap();
504 let back = load_session_from(&path).unwrap().expect("v1 parses");
505 assert_eq!(back.version, 1);
506 assert_eq!(back.done, 4242);
507 assert_eq!(back.total, None);
508 let _ = std::fs::remove_dir_all(&dir);
509 }
510
511 #[test]
512 fn stale_tmp_files_cleaned_on_load() {
513 let dir = tmp("tmpc");
514 let path = dir.join("labels.json");
515 let mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap();
516 let mut labels = BTreeMap::new();
517 labels.insert(mac, "x".to_string());
518 save_labels_to(&path, &labels).unwrap();
519 // No tmp file survives a successful save.
520 let left: Vec<_> = std::fs::read_dir(&dir)
521 .unwrap()
522 .flatten()
523 .map(|e| e.file_name().to_string_lossy().into_owned())
524 .collect();
525 assert_eq!(left, vec!["labels.json"], "save leaves no tmp: {left:?}");
526 // Crashed-write leftovers are removed by the next load, labels
527 // still load fine, and unrelated files are untouched.
528 std::fs::write(dir.join("labels.json.tmp.1-2"), "partial junk").unwrap();
529 std::fs::write(dir.join("other.tmp.1-2"), "not ours").unwrap();
530 let back = load_labels_from(&path).unwrap();
531 assert_eq!(back.get(&mac).map(String::as_str), Some("x"));
532 let left: Vec<_> = std::fs::read_dir(&dir)
533 .unwrap()
534 .flatten()
535 .map(|e| e.file_name().to_string_lossy().into_owned())
536 .collect();
537 assert!(left.contains(&"labels.json".to_string()));
538 assert!(
539 left.contains(&"other.tmp.1-2".to_string()),
540 "unrelated kept"
541 );
542 assert!(
543 !left.iter().any(|n| n.starts_with("labels.json.tmp.")),
544 "stale gone: {left:?}"
545 );
546 let _ = std::fs::remove_dir_all(&dir);
547 }
548
549 #[test]
550 fn data_dir_home_unset_uses_tmp_base() {
551 let got = data_dir_impl(None, Path::new("/tmpbase"));
552 assert_eq!(got, PathBuf::from("/tmpbase/wifi_lab"));
553 let got = data_dir_impl(Some(std::ffi::OsStr::new("")), Path::new("/tmpbase"));
554 assert_eq!(got, PathBuf::from("/tmpbase/wifi_lab"));
555 }
556
557 #[test]
558 fn data_dir_migration_and_race() {
559 let dir = tmp("datadir");
560 let home = dir.join("home");
561 // Migration: old `wifilab` moves to `wifi_lab`.
562 std::fs::create_dir_all(home.join("wifilab/sub")).unwrap();
563 std::fs::write(home.join("wifilab/sub/f.json"), "{}").unwrap();
564 let got = data_dir_impl(Some(home.as_os_str()), Path::new("/tmpbase"));
565 assert_eq!(got, home.join("wifi_lab"));
566 assert!(home.join("wifi_lab/sub/f.json").is_file());
567 assert!(!home.join("wifilab").exists());
568 // Race: both exist (a second instance already created the target).
569 // The rename fails; the target wins, no error, old dir left alone.
570 std::fs::create_dir_all(home.join("wifilab")).unwrap();
571 std::fs::write(home.join("wifilab/stale.marker"), "x").unwrap();
572 let got = data_dir_impl(Some(home.as_os_str()), Path::new("/tmpbase"));
573 assert_eq!(got, home.join("wifi_lab"));
574 assert!(home.join("wifi_lab").is_dir());
575 // Neither outcome is an error; the function must not panic.
576 let _ = std::fs::remove_dir_all(&dir);
577 }
578
579 #[test]
580 fn captures_append_and_load_dedups() {
581 let dir = tmp("caps");
582 let path = dir.join("captures.jsonl");
583 let pm = PmkidCapture {
584 ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(),
585 client: "11:22:33:44:55:66".parse().unwrap(),
586 essid: "testnet".into(),
587 pmkid: [7u8; 16],
588 };
589 let hs = HandshakeCapture::new(
590 "aa:bb:cc:dd:ee:ff".parse().unwrap(),
591 "11:22:33:44:55:66".parse().unwrap(),
592 "testnet".into(),
593 [1u8; 32],
594 [2u8; 32],
595 [3u8; 16],
596 vec![9u8; 8],
597 2,
598 );
599 let cap_pm = StoredCapture::Pmkid(pm.clone());
600 let cap_hs = StoredCapture::Handshake(hs.clone());
601 append_capture_to(&path, &cap_pm).unwrap();
602 append_capture_to(&path, &cap_pm).unwrap(); // duplicate line on disk
603 append_capture_to(&path, &cap_hs).unwrap();
604 // One corrupt line must not kill the rest.
605 std::fs::write(
606 &path,
607 format!("{}{{not json}}\n", std::fs::read_to_string(&path).unwrap()),
608 )
609 .unwrap();
610 let back = load_captures_from(&path).unwrap();
611 assert_eq!(back, vec![cap_pm, cap_hs]);
612 let _ = std::fs::remove_dir_all(&dir);
613 }
614
615 #[test]
616 fn captures_missing_file_is_empty() {
617 let back = load_captures_from(&tmp("nope").join("captures.jsonl")).unwrap();
618 assert!(back.is_empty());
619 }
620
621 #[test]
622 fn profiles_roundtrip_and_missing() {
623 let dir = tmp("profiles");
624 let path = dir.join("profiles.json");
625 // Missing file = empty store.
626 assert_eq!(load_profiles_from(&path).unwrap().profiles.len(), 0);
627 let mut p = Profiles {
628 profiles: vec![
629 CrackProfile {
630 name: "wl:rockyou".into(),
631 mode: "wordlist".into(),
632 wordlist: "/usr/share/wordlists/rockyou.txt".into(),
633 rules: None,
634 },
635 CrackProfile {
636 name: "rules:corp".into(),
637 mode: "rules".into(),
638 wordlist: "/home/x/wl.txt".into(),
639 rules: Some("/home/x/best64.rule".into()),
640 },
641 ],
642 recent_wordlists: vec!["/a.txt".into(), "/b.txt".into()],
643 };
644 p.recent_wordlists.insert(0, "/c.txt".into());
645 save_profiles_to(&path, &p).unwrap();
646 let back = load_profiles_from(&path).unwrap();
647 assert_eq!(back.profiles.len(), 2);
648 assert_eq!(back.profiles[0].name, "wl:rockyou");
649 assert_eq!(
650 back.profiles[1].rules.as_deref(),
651 Some("/home/x/best64.rule")
652 );
653 assert_eq!(back.recent_wordlists, p.recent_wordlists);
654 // Unparseable file = empty store, no error (never clobbered).
655 std::fs::write(&path, "{{not json").unwrap();
656 let back = load_profiles_from(&path).unwrap();
657 assert!(back.profiles.is_empty() && back.recent_wordlists.is_empty());
658 let _ = std::fs::remove_dir_all(&dir);
659 }
660
661 #[test]
662 fn remember_wordlist_front_insert_dedup_cap5() {
663 let mut p = Profiles::default();
664 for w in ["/a", "/b", "/c", "/d", "/e", "/a"] {
665 remember_wordlist(&mut p, w);
666 }
667 // "/a" re-remembered: moves to front, no duplicate.
668 assert_eq!(p.recent_wordlists, vec!["/a", "/e", "/d", "/c", "/b"]);
669 // Sixth distinct path evicts the oldest.
670 remember_wordlist(&mut p, "/f");
671 assert_eq!(p.recent_wordlists, vec!["/f", "/a", "/e", "/d", "/c"]);
672 }
673
674 #[test]
675 fn cache_file_hex_naming() {
676 let p = cache_file("testnet");
677 assert_eq!(
678 p.file_name().unwrap().to_str().unwrap(),
679 "746573746e6574.pmk"
680 );
681 // Hex is lowercase and 2 chars per byte; non-ASCII bytes safe.
682 let p2 = cache_file("aé");
683 assert_eq!(p2.file_name().unwrap().to_str().unwrap(), "61c3a9.pmk");
684 assert_eq!(p.parent().unwrap(), cache_dir());
685 }
686}