//! Streaming wordlist reader: line-oriented, bytes-accurate, filters to the //! WPA passphrase length range 8..=63 bytes. use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use anyhow::{Context, Result}; /// Process-wide count of lines skipped by [`open`] iterators: unreadable /// lines and lines outside the WPA passphrase range (8..=63 bytes). /// Lines with invalid UTF-8 are NOT skipped — passphrases are raw bytes /// (rockyou-family lists carry high-bit bytes) and are yielded as read. static SKIPPED_LINES: AtomicU64 = AtomicU64::new(0); /// Cumulative number of wordlist lines skipped since process start. Read /// before and after exhausting an iterator; the delta is that file's /// skipped-line total (undecodable/unreadable + overlong/undersized). pub fn skipped_lines() -> u64 { SKIPPED_LINES.load(Ordering::Relaxed) } struct WordIter { reader: BufReader, } impl Iterator for WordIter { type Item = Vec; fn next(&mut self) -> Option> { let mut buf = Vec::new(); loop { buf.clear(); match self.reader.read_until(b'\n', &mut buf) { Ok(0) => return None, Ok(_) => { // Trim the line terminator only: `\n`, then one `\r` of a // CRLF pair (no whitespace trimming — trailing spaces are // passphrase material). if buf.last() == Some(&b'\n') { buf.pop(); if buf.last() == Some(&b'\r') { buf.pop(); } } if (8..=63).contains(&buf.len()) { return Some(std::mem::take(&mut buf)); } SKIPPED_LINES.fetch_add(1, Ordering::Relaxed); } // Unreadable line: count it and stop. A read error on a // plain file almost always persists; retrying would spin. Err(_) => { SKIPPED_LINES.fetch_add(1, Ordering::Relaxed); return None; } } } } } /// Count lines without parsing: byte-scan for `\n` in 8 MiB chunks /// (fast even on multi-GB lists — the cracker's worst-case candidate /// total). A final line without trailing newline counts too. pub fn line_count(path: &Path) -> Result { use std::io::Read; let mut f = File::open(path).with_context(|| format!("counting lines of {}", path.display()))?; let mut buf = vec![0u8; 1 << 23]; let mut count = 0u64; let mut any = false; let mut ended_with_nl = true; loop { let n = f .read(&mut buf) .with_context(|| format!("counting lines of {}", path.display()))?; if n == 0 { break; } any = true; ended_with_nl = buf[n - 1] == b'\n'; count += buf[..n].iter().filter(|&&b| b == b'\n').count() as u64; } if any && !ended_with_nl { count += 1; } Ok(count) } /// Open a wordlist file as a streaming iterator of passphrase candidates. /// /// Byte-safe: lines are split at `\n` and trimmed of a trailing `\r` (no /// UTF-8 decoding, so high-bit bytes survive — WPA passphrases are raw /// bytes); only candidates of 8..=63 *bytes* are yielded. Skipped lines are /// tallied in [`skipped_lines`]. The iterator is `Send` and does not load /// the file into memory. pub fn open(path: &Path) -> Result> + Send>> { let f = File::open(path).with_context(|| format!("opening wordlist {}", path.display()))?; let reader = BufReader::with_capacity(1 << 20, f); Ok(Box::new(WordIter { reader })) } #[cfg(test)] mod tests { use super::*; use std::io::Write; /// Serializes tests that assert on the process-wide skip counter. /// (parking_lot isn't a direct dependency; recover from poisoning /// instead of unwrapping.) static SKIP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// Lock `SKIP_LOCK`, recovering the guard if a panicked test poisoned it. fn skip_lock() -> std::sync::MutexGuard<'static, ()> { SKIP_LOCK.lock().unwrap_or_else(|e| e.into_inner()) } #[test] fn filters_and_trims() { let _g = skip_lock(); let dir = std::env::temp_dir(); let path = dir.join(format!("wifi_lab-wordlist-test-{}", std::process::id())); { let mut f = File::create(&path).unwrap(); // too short, ok, crlf ok, trailing space kept (too short when // counted), exactly 8, exactly 63, 64 too long, empty line. writeln!(f, "short").unwrap(); writeln!(f, "sup3r-secret").unwrap(); f.write_all(b"crlf-pass\r\n").unwrap(); writeln!(f, "eight88 ").unwrap(); writeln!(f, "eight888").unwrap(); writeln!(f, "{}", "a".repeat(63)).unwrap(); writeln!(f, "{}", "b".repeat(64)).unwrap(); f.write_all(b"\n").unwrap(); } let before = skipped_lines(); let mut it = open(&path).unwrap(); let got: Vec> = std::iter::from_fn(|| it.next()).collect(); // "eight88 " keeps its trailing space: only \r\n is trimmed. assert_eq!( got, vec![ b"sup3r-secret".to_vec(), b"crlf-pass".to_vec(), b"eight88 ".to_vec(), b"eight888".to_vec(), "a".repeat(63).into_bytes(), ] ); // "short", the 64-byte line and the empty line were skipped. assert_eq!(skipped_lines() - before, 3); let _ = std::fs::remove_file(&path); } #[test] fn non_utf8_bytes_are_candidates_not_dropped() { let _g = skip_lock(); let dir = std::env::temp_dir(); let path = dir.join(format!("wifi_lab-wordlist-utf8-{}", std::process::id())); { let mut f = File::create(&path).unwrap(); // rockyou-style high-bit bytes: invalid UTF-8, VALID passphrase. f.write_all(b"p\xe4ssw\xf6rd\n").unwrap(); f.write_all(b"\xff\xfepass\x80\x81\n").unwrap(); // plus noise that must be counted as skipped: f.write_all(b"tiny\n").unwrap(); f.write_all(&[b'x'; 64]).unwrap(); f.write_all(b"\n").unwrap(); } let before = skipped_lines(); let mut it = open(&path).unwrap(); let got: Vec> = std::iter::from_fn(|| it.next()).collect(); assert_eq!( got, vec![b"p\xe4ssw\xf6rd".to_vec(), b"\xff\xfepass\x80\x81".to_vec()] ); // "tiny" and the 64-byte line skipped; the binary lines yielded. assert_eq!(skipped_lines() - before, 2); let _ = std::fs::remove_file(&path); } #[test] fn missing_file_errors() { assert!(open(Path::new("/definitely/not/here.lst")).is_err()); } #[test] fn line_count_edges() { let dir = std::env::temp_dir(); for (name, bytes, want) in [ ("empty", &b""[..], 0u64), ("one-no-nl", b"abc", 1), ("one-nl", b"abc\n", 1), ("two", b"abc\ndef\n", 2), ("trailing-nl-only", b"\n", 1), ("crlf", b"a\r\nb\r\n", 2), ] { let path = dir.join(format!("wifi_lab-lc-{name}-{}", std::process::id())); std::fs::write(&path, bytes).unwrap(); assert_eq!(line_count(&path).unwrap(), want, "{name}"); let _ = std::fs::remove_file(&path); } } }