Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / networklocation / wps_harvest / src / frontier.rs

frontier.rs386 lines · 13.3 KiBRaw
1//! Resumable crawl state: which BSSIDs have been seen, and which are still to be queried.
2//!
3//! A planet crawl runs for weeks and will be interrupted — by a reboot, a network outage, or
4//! somebody pressing Ctrl-C. Losing the frontier would mean restarting from the seed, so both
5//! halves of the state are on disk and both are safe to reload mid-run.
6//!
7//! ## Why the seen-set is approximate
8//!
9//! An exact set of a billion 48-bit keys is tens of gigabytes of hash table. A Bloom filter of
10//! the same cardinality is about 1.2 GB at a 1% false-positive rate, and the cost of a false
11//! positive here is that one BSSID never gets queried directly. That is nearly free: the
12//! crawl reaches almost every AP as a *neighbour* in somebody else's response, so a skipped
13//! query loses a small amount of expansion, not the beacon. Trading a rare missed query for
14//! twenty times less memory is the right way round.
15//!
16//! Records themselves are never deduplicated here — that is `wps_build`'s job, working over
17//! the sorted whole, where it can be exact.
18
19use std::fs::{File, OpenOptions};
20use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
21use std::path::{Path, PathBuf};
22
23/// Bits per expected element, giving roughly a 1% false-positive rate at two hashes.
24const BITS_PER_ELEMENT: u64 = 10;
25
26const SEEN_MAGIC: &[u8; 8] = b"WPSSEEN1";
27const QUEUE_MAGIC: &[u8; 8] = b"WPSQUE01";
28
29fn mix(mut z: u64) -> u64 {
30 z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
31 z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
32 z ^ (z >> 31)
33}
34
35/// Approximate membership over the BSSIDs the crawl has already encountered.
36pub struct SeenSet {
37 bits: Vec<u64>,
38 nbits: u64,
39 inserted: u64,
40 path: PathBuf,
41}
42
43impl SeenSet {
44 /// Size for `expected` elements, or reload from `path` if it already holds a filter of the
45 /// same size. A size change starts a fresh filter rather than misreading the old one.
46 pub fn open(path: &Path, expected: u64) -> io::Result<SeenSet> {
47 let nbits = (expected.max(1) * BITS_PER_ELEMENT).next_power_of_two();
48 let words = (nbits / 64) as usize;
49
50 if path.exists() {
51 let mut f = BufReader::new(File::open(path)?);
52 let mut head = [0u8; 24];
53 if f.read_exact(&mut head).is_ok() && &head[0..8] == SEEN_MAGIC {
54 let stored_bits = u64::from_le_bytes(
55 head[8..16].try_into().map_err(|_| bad("short seen header"))?,
56 );
57 let inserted = u64::from_le_bytes(
58 head[16..24].try_into().map_err(|_| bad("short seen header"))?,
59 );
60 if stored_bits == nbits {
61 let mut bits = vec![0u64; words];
62 let mut buf = [0u8; 8];
63 for w in bits.iter_mut() {
64 f.read_exact(&mut buf)?;
65 *w = u64::from_le_bytes(buf);
66 }
67 return Ok(SeenSet { bits, nbits, inserted, path: path.to_path_buf() });
68 }
69 }
70 }
71 Ok(SeenSet { bits: vec![0u64; words], nbits, inserted: 0, path: path.to_path_buf() })
72 }
73
74 fn positions(&self, key: u64) -> (u64, u64) {
75 let h1 = mix(key);
76 let h2 = mix(key ^ 0x9E3779B97F4A7C15) | 1;
77 (h1 % self.nbits, h2 % self.nbits)
78 }
79
80 /// Whether `key` has probably been seen. False positives are possible, false negatives are
81 /// not, which is the direction that keeps the crawl from looping.
82 pub fn contains(&self, key: u64) -> bool {
83 let (a, b) = self.positions(key);
84 self.get(a) && self.get(b)
85 }
86
87 /// Record `key`. Returns whether it was new.
88 pub fn insert(&mut self, key: u64) -> bool {
89 let (a, b) = self.positions(key);
90 let had = self.get(a) && self.get(b);
91 self.set(a);
92 self.set(b);
93 if !had {
94 self.inserted += 1;
95 }
96 !had
97 }
98
99 fn get(&self, bit: u64) -> bool {
100 self.bits.get((bit >> 6) as usize).is_some_and(|w| (w >> (bit & 63)) & 1 == 1)
101 }
102
103 fn set(&mut self, bit: u64) {
104 if let Some(w) = self.bits.get_mut((bit >> 6) as usize) {
105 *w |= 1 << (bit & 63);
106 }
107 }
108
109 /// How many distinct keys have been inserted, as the filter counts them.
110 pub fn len(&self) -> u64 {
111 self.inserted
112 }
113
114 /// Whether nothing has been inserted.
115 pub fn is_empty(&self) -> bool {
116 self.inserted == 0
117 }
118
119 /// Estimated false-positive rate at the current load, for the crawl's status line.
120 pub fn false_positive_rate(&self) -> f64 {
121 let k = 2.0;
122 let exp = -(k * self.inserted as f64) / self.nbits as f64;
123 (1.0 - exp.exp()).powf(k)
124 }
125
126 /// Write the filter out. Writes to a sibling temp file and renames, so an interrupted
127 /// checkpoint leaves the previous one intact rather than a half-written filter that would
128 /// load as garbage.
129 pub fn checkpoint(&self) -> io::Result<()> {
130 let tmp = self.path.with_extension("tmp");
131 {
132 let mut f = BufWriter::new(File::create(&tmp)?);
133 f.write_all(SEEN_MAGIC)?;
134 f.write_all(&self.nbits.to_le_bytes())?;
135 f.write_all(&self.inserted.to_le_bytes())?;
136 for w in &self.bits {
137 f.write_all(&w.to_le_bytes())?;
138 }
139 f.flush()?;
140 }
141 std::fs::rename(&tmp, &self.path)
142 }
143}
144
145/// The queue of BSSIDs still to be queried: an append-only file plus a read cursor.
146///
147/// Append-only because the crawl's whole shape is "every answer adds more questions", and a
148/// file that only grows at one end and is consumed at the other never needs rewriting. The
149/// cursor is a separate small file so checkpointing it is atomic on its own.
150pub struct Frontier {
151 file: File,
152 path: PathBuf,
153 cursor_path: PathBuf,
154 /// Index of the next entry to hand out.
155 cursor: u64,
156 /// Number of entries appended.
157 len: u64,
158}
159
160impl Frontier {
161 /// Open or create the queue at `path`, restoring the cursor from `path.cursor`.
162 pub fn open(path: &Path) -> io::Result<Frontier> {
163 let cursor_path = path.with_extension("cursor");
164 let mut file =
165 OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)?;
166 let size = file.seek(SeekFrom::End(0))?;
167
168 if size == 0 {
169 file.write_all(QUEUE_MAGIC)?;
170 } else {
171 let _ = file.seek(SeekFrom::Start(0))?;
172 let mut magic = [0u8; 8];
173 file.read_exact(&mut magic)?;
174 if &magic != QUEUE_MAGIC {
175 return Err(bad("frontier file is not a crawl queue"));
176 }
177 }
178 let len = size.saturating_sub(8) / 8;
179
180 let cursor = std::fs::read(&cursor_path)
181 .ok()
182 .and_then(|b| b.get(0..8).map(|s| s.to_vec()))
183 .and_then(|b| b.try_into().ok())
184 .map_or(0, u64::from_le_bytes)
185 .min(len);
186
187 Ok(Frontier { file, path: path.to_path_buf(), cursor_path, cursor, len })
188 }
189
190 /// Append one BSSID.
191 pub fn push(&mut self, mac: u64) -> io::Result<()> {
192 let _ = self.file.seek(SeekFrom::End(0))?;
193 self.file.write_all(&mac.to_le_bytes())?;
194 self.len += 1;
195 Ok(())
196 }
197
198 /// Take up to `n` BSSIDs, advancing the cursor.
199 pub fn take(&mut self, n: usize) -> io::Result<Vec<u64>> {
200 let available = (self.len - self.cursor).min(n as u64) as usize;
201 if available == 0 {
202 return Ok(Vec::new());
203 }
204 let _ = self.file.seek(SeekFrom::Start(8 + self.cursor * 8))?;
205 let mut buf = vec![0u8; available * 8];
206 self.file.read_exact(&mut buf)?;
207 self.cursor += available as u64;
208
209 let mut out = Vec::with_capacity(available);
210 for chunk in buf.chunks_exact(8) {
211 let mut a = [0u8; 8];
212 a.copy_from_slice(chunk);
213 out.push(u64::from_le_bytes(a));
214 }
215 Ok(out)
216 }
217
218 /// Entries not yet handed out.
219 pub fn pending(&self) -> u64 {
220 self.len - self.cursor
221 }
222
223 /// Entries appended over the queue's whole life.
224 pub fn total(&self) -> u64 {
225 self.len
226 }
227
228 /// Flush the queue and persist the cursor.
229 ///
230 /// The queue is flushed *before* the cursor is written, so a crash between the two
231 /// re-queries some BSSIDs rather than skipping them. Re-querying is harmless; skipping
232 /// loses a branch of the crawl permanently.
233 pub fn checkpoint(&mut self) -> io::Result<()> {
234 self.file.sync_data()?;
235 let tmp = self.cursor_path.with_extension("cursor.tmp");
236 std::fs::write(&tmp, self.cursor.to_le_bytes())?;
237 std::fs::rename(&tmp, &self.cursor_path)
238 }
239
240 /// Path of the queue file, for status output.
241 pub fn path(&self) -> &Path {
242 &self.path
243 }
244}
245
246fn bad(msg: &str) -> io::Error {
247 io::Error::new(io::ErrorKind::InvalidData, msg.to_string())
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 struct TempDir(PathBuf);
255 impl TempDir {
256 fn new(tag: &str) -> TempDir {
257 let p = std::env::temp_dir().join(format!("wpsfront-{tag}-{}", std::process::id()));
258 let _ = std::fs::remove_dir_all(&p);
259 std::fs::create_dir_all(&p).unwrap();
260 TempDir(p)
261 }
262 }
263 impl Drop for TempDir {
264 fn drop(&mut self) {
265 let _ = std::fs::remove_dir_all(&self.0);
266 }
267 }
268
269 #[test]
270 fn seen_set_never_reports_a_false_negative() {
271 let d = TempDir::new("seen");
272 let mut s = SeenSet::open(&d.0.join("seen.bin"), 10_000).unwrap();
273 let keys: Vec<u64> = (0..5000).map(|i| mix(i) & 0xFFFF_FFFF_FFFF).collect();
274 for &k in &keys {
275 let _ = s.insert(k);
276 }
277 for &k in &keys {
278 assert!(s.contains(k), "{k:#x} was inserted but reads as absent");
279 }
280 assert!(s.len() > 4900, "insert count should track distinct keys");
281 }
282
283 #[test]
284 fn seen_set_false_positive_rate_stays_near_the_design_point() {
285 let d = TempDir::new("fp");
286 let mut s = SeenSet::open(&d.0.join("seen.bin"), 20_000).unwrap();
287 for i in 0..20_000u64 {
288 let _ = s.insert(mix(i));
289 }
290 let mut fp = 0;
291 for i in 0..20_000u64 {
292 if s.contains(mix(i ^ 0xDEAD_BEEF_0000_0000)) {
293 fp += 1;
294 }
295 }
296 let rate = fp as f64 / 20_000.0;
297 assert!(rate < 0.05, "false-positive rate {rate} is too high to be useful");
298 }
299
300 #[test]
301 fn seen_set_survives_a_checkpoint_and_reload() {
302 let d = TempDir::new("reload");
303 let path = d.0.join("seen.bin");
304 let keys: Vec<u64> = (0..1000).map(mix).collect();
305 {
306 let mut s = SeenSet::open(&path, 10_000).unwrap();
307 for &k in &keys {
308 let _ = s.insert(k);
309 }
310 s.checkpoint().unwrap();
311 }
312 let s = SeenSet::open(&path, 10_000).unwrap();
313 assert_eq!(s.len(), 1000);
314 for &k in &keys {
315 assert!(s.contains(k));
316 }
317 }
318
319 #[test]
320 fn resizing_starts_a_fresh_filter_rather_than_misreading_the_old_one() {
321 let d = TempDir::new("resize");
322 let path = d.0.join("seen.bin");
323 {
324 let mut s = SeenSet::open(&path, 10_000).unwrap();
325 let _ = s.insert(42);
326 s.checkpoint().unwrap();
327 }
328 let s = SeenSet::open(&path, 10_000_000).unwrap();
329 assert_eq!(s.len(), 0);
330 assert!(s.is_empty());
331 }
332
333 #[test]
334 fn frontier_hands_out_entries_in_order_and_resumes() {
335 let d = TempDir::new("queue");
336 let path = d.0.join("frontier.bin");
337 {
338 let mut f = Frontier::open(&path).unwrap();
339 for i in 0..100u64 {
340 f.push(i).unwrap();
341 }
342 assert_eq!(f.take(10).unwrap(), (0..10).collect::<Vec<_>>());
343 assert_eq!(f.pending(), 90);
344 f.checkpoint().unwrap();
345 }
346 let mut f = Frontier::open(&path).unwrap();
347 assert_eq!(f.total(), 100);
348 assert_eq!(f.pending(), 90);
349 assert_eq!(f.take(5).unwrap(), (10..15).collect::<Vec<_>>());
350 }
351
352 #[test]
353 fn an_uncheckpointed_cursor_repeats_work_rather_than_losing_it() {
354 let d = TempDir::new("nocheck");
355 let path = d.0.join("frontier.bin");
356 {
357 let mut f = Frontier::open(&path).unwrap();
358 for i in 0..20u64 {
359 f.push(i).unwrap();
360 }
361 f.checkpoint().unwrap();
362 // Consume without checkpointing, then "crash".
363 assert_eq!(f.take(8).unwrap().len(), 8);
364 }
365 let mut f = Frontier::open(&path).unwrap();
366 assert_eq!(f.take(1).unwrap(), vec![0], "must re-query, not skip past");
367 }
368
369 #[test]
370 fn taking_from_an_exhausted_frontier_yields_nothing() {
371 let d = TempDir::new("drained");
372 let mut f = Frontier::open(&d.0.join("frontier.bin")).unwrap();
373 f.push(1).unwrap();
374 assert_eq!(f.take(10).unwrap(), vec![1]);
375 assert_eq!(f.take(10).unwrap(), Vec::<u64>::new());
376 assert_eq!(f.pending(), 0);
377 }
378
379 #[test]
380 fn a_foreign_file_is_refused() {
381 let d = TempDir::new("foreign");
382 let path = d.0.join("frontier.bin");
383 std::fs::write(&path, b"not a queue at all").unwrap();
384 assert!(Frontier::open(&path).is_err());
385 }
386}