Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / bin / wps_crawl.rs
wps_crawl.rs451 lines · 17.5 KiBRaw
| 1 | //! `wps_crawl --state DIR --out SHARD [options]` |
| 2 | //! |
| 3 | //! Expand a set of known BSSIDs into a beacon database by asking Apple's location service |
| 4 | //! where they are. Each response answers the query *and* returns a few hundred neighbouring |
| 5 | //! APs with their own coordinates, so the answers are also the next set of questions. |
| 6 | //! |
| 7 | //! ## Built to be interrupted |
| 8 | //! |
| 9 | //! A planet crawl runs for weeks. Everything that would be expensive to lose lives in |
| 10 | //! `--state`: the frontier queue, its cursor, and the approximate set of BSSIDs already seen. |
| 11 | //! State is checkpointed every `--checkpoint` requests and the output shard is append-only, so |
| 12 | //! killing the process is a supported way to stop it. Restarting with the same arguments picks |
| 13 | //! up from the last checkpoint; at worst the requests since then are repeated, and `wps_build` |
| 14 | //! deduplicates those anyway. |
| 15 | //! |
| 16 | //! ## Politeness is not optional |
| 17 | //! |
| 18 | //! This talks to somebody else's service, at length. Requests are serialized through one |
| 19 | //! client with a minimum interval between them, and errors back off rather than retrying hard. |
| 20 | //! Running it faster is both rude and self-defeating. |
| 21 | |
| 22 | use std::fs::OpenOptions; |
| 23 | use std::io::{BufRead, BufWriter, Write}; |
| 24 | use std::path::PathBuf; |
| 25 | use std::process::ExitCode; |
| 26 | use std::time::Duration; |
| 27 | |
| 28 | use wps_harvest::frontier::{Frontier, SeenSet}; |
| 29 | use wps_harvest::gsloc::{self, Client}; |
| 30 | use wps_harvest::keys; |
| 31 | use wps_harvest::probe::Prober; |
| 32 | use wps_harvest::progress::{FailKind, Progress}; |
| 33 | use wps_harvest::quality::clamp_accuracy; |
| 34 | use wps_harvest::record::{Record, RecordWriter, Source}; |
| 35 | |
| 36 | /// Frontier checkpoints between seen-set checkpoints. The seen-set is rewritten whole, which |
| 37 | /// is gigabytes at planet scale, and losing it only costs repeated requests. |
| 38 | const SEEN_CHECKPOINT_EVERY: u32 = 25; |
| 39 | |
| 40 | /// Stop after this many failures in a row. At the 300 s backoff ceiling that is over an hour |
| 41 | /// of being refused, which is not a blip. |
| 42 | const MAX_CONSECUTIVE_FAILURES: u32 = 20; |
| 43 | |
| 44 | const USAGE: &str = "\ |
| 45 | Usage: wps_crawl --state DIR --out SHARD [options] |
| 46 | |
| 47 | --state directory holding the frontier, its cursor and the seen-set (resumable) |
| 48 | --out record shard to append to |
| 49 | --seed FILE newline-separated BSSIDs to enqueue before starting (repeatable) |
| 50 | --probe N when the frontier is empty, guess N random BSSIDs per request to find a |
| 51 | starting point (default 1; 0 disables). Learns which OUIs are productive |
| 52 | from every response, so the hit rate climbs as it runs. |
| 53 | --oui-file FILE OUIs to seed the guesser with: the IEEE registry, or any WiFi scan output. |
| 54 | Worth far more than guessing blind - see probe.rs. |
| 55 | --probe-seed N RNG seed for the guesser, so a run can be reproduced (default 1) |
| 56 | --batch N BSSIDs per request (default 1). Apple answers HTTP 400 to more than one, |
| 57 | so raising this stops the crawl working at all; it exists only so the |
| 58 | limit can be re-tested if the service changes. |
| 59 | --interval MS minimum milliseconds between requests (default 1000) |
| 60 | --max-queries N stop after N requests (default: until the frontier empties) |
| 61 | --expected N expected distinct BSSIDs, which sizes the seen-set (default 200000000) |
| 62 | --checkpoint N checkpoint state every N requests (default 200) |
| 63 | --status-secs N seconds between status lines (default 30). Timed rather than counted, so |
| 64 | a stalled crawl keeps reporting instead of going quiet. |
| 65 | |
| 66 | On Windows, a free real seed: netsh wlan show networks mode=bssid"; |
| 67 | |
| 68 | struct Args { |
| 69 | state: PathBuf, |
| 70 | out: PathBuf, |
| 71 | seeds: Vec<PathBuf>, |
| 72 | oui_files: Vec<PathBuf>, |
| 73 | probe: usize, |
| 74 | probe_seed: u64, |
| 75 | batch: usize, |
| 76 | interval: Duration, |
| 77 | max_queries: Option<u64>, |
| 78 | expected: u64, |
| 79 | checkpoint_every: u64, |
| 80 | status_secs: u64, |
| 81 | } |
| 82 | |
| 83 | fn parse_args(argv: &[String]) -> Result<Args, String> { |
| 84 | let mut state = None; |
| 85 | let mut out = None; |
| 86 | let mut seeds = Vec::new(); |
| 87 | let mut oui_files = Vec::new(); |
| 88 | let mut probe = 1usize; |
| 89 | let mut probe_seed = 1u64; |
| 90 | let mut batch = 1usize; |
| 91 | let mut interval_ms = 1000u64; |
| 92 | let mut max_queries = None; |
| 93 | let mut expected = 200_000_000u64; |
| 94 | let mut checkpoint_every = 200u64; |
| 95 | let mut status_secs = 30u64; |
| 96 | |
| 97 | let mut i = 0; |
| 98 | while i < argv.len() { |
| 99 | let a = argv[i].as_str(); |
| 100 | let value = || argv.get(i + 1).cloned().ok_or_else(|| format!("{a} needs a value")); |
| 101 | match a { |
| 102 | "--state" => { |
| 103 | state = Some(PathBuf::from(value()?)); |
| 104 | i += 2; |
| 105 | } |
| 106 | "--out" => { |
| 107 | out = Some(PathBuf::from(value()?)); |
| 108 | i += 2; |
| 109 | } |
| 110 | "--seed" => { |
| 111 | seeds.push(PathBuf::from(value()?)); |
| 112 | i += 2; |
| 113 | } |
| 114 | "--oui-file" => { |
| 115 | oui_files.push(PathBuf::from(value()?)); |
| 116 | i += 2; |
| 117 | } |
| 118 | "--probe" => { |
| 119 | probe = value()?.parse().map_err(|_| "--probe must be a number")?; |
| 120 | i += 2; |
| 121 | } |
| 122 | "--probe-seed" => { |
| 123 | probe_seed = value()?.parse().map_err(|_| "--probe-seed must be a number")?; |
| 124 | i += 2; |
| 125 | } |
| 126 | "--batch" => { |
| 127 | batch = value()?.parse().map_err(|_| "--batch must be a number")?; |
| 128 | i += 2; |
| 129 | } |
| 130 | "--interval" => { |
| 131 | interval_ms = value()?.parse().map_err(|_| "--interval must be a number")?; |
| 132 | i += 2; |
| 133 | } |
| 134 | "--max-queries" => { |
| 135 | max_queries = Some(value()?.parse().map_err(|_| "--max-queries must be a number")?); |
| 136 | i += 2; |
| 137 | } |
| 138 | "--expected" => { |
| 139 | expected = value()?.parse().map_err(|_| "--expected must be a number")?; |
| 140 | i += 2; |
| 141 | } |
| 142 | "--checkpoint" => { |
| 143 | checkpoint_every = value()?.parse().map_err(|_| "--checkpoint must be a number")?; |
| 144 | i += 2; |
| 145 | } |
| 146 | "--status-secs" => { |
| 147 | status_secs = value()?.parse().map_err(|_| "--status-secs must be a number")?; |
| 148 | i += 2; |
| 149 | } |
| 150 | "-h" | "--help" => return Err("help".to_string()), |
| 151 | other => return Err(format!("unknown option: {other}")), |
| 152 | } |
| 153 | } |
| 154 | Ok(Args { |
| 155 | state: state.ok_or("--state is required")?, |
| 156 | out: out.ok_or("--out is required")?, |
| 157 | seeds, |
| 158 | oui_files, |
| 159 | probe, |
| 160 | probe_seed, |
| 161 | batch: batch.max(1), |
| 162 | interval: Duration::from_millis(interval_ms), |
| 163 | max_queries, |
| 164 | expected, |
| 165 | checkpoint_every: checkpoint_every.max(1), |
| 166 | status_secs: status_secs.max(1), |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | fn to_record(fix: &gsloc::WifiFix) -> Option<Record> { |
| 171 | let mac = keys::parse_mac(&fix.bssid)?; |
| 172 | // Randomized and multicast addresses are not places. Dropping them at the source keeps |
| 173 | // them out of the frontier as well as out of the shard. |
| 174 | if keys::is_randomized_mac(mac) { |
| 175 | return None; |
| 176 | } |
| 177 | let r = Record { |
| 178 | key: keys::wifi_key(mac), |
| 179 | lat_e8: fix.lat_e8, |
| 180 | lon_e8: fix.lon_e8, |
| 181 | accuracy_m: clamp_accuracy(fix.accuracy_m), |
| 182 | altitude_m: fix.altitude_m, |
| 183 | source: Source::Gsloc, |
| 184 | }; |
| 185 | r.in_range().then_some(r) |
| 186 | } |
| 187 | |
| 188 | fn run(args: &Args) -> std::io::Result<()> { |
| 189 | std::fs::create_dir_all(&args.state)?; |
| 190 | let mut frontier = Frontier::open(&args.state.join("frontier.bin"))?; |
| 191 | let mut seen = SeenSet::open(&args.state.join("seen.bin"), args.expected)?; |
| 192 | |
| 193 | for seed_path in &args.seeds { |
| 194 | let file = std::io::BufReader::new(std::fs::File::open(seed_path)?); |
| 195 | let mut added = 0u64; |
| 196 | for line in file.lines() { |
| 197 | let line = line?; |
| 198 | let Some(mac) = keys::parse_mac(line.trim().to_ascii_lowercase().as_str()) else { |
| 199 | continue; |
| 200 | }; |
| 201 | if keys::is_randomized_mac(mac) || !seen.insert(mac) { |
| 202 | continue; |
| 203 | } |
| 204 | frontier.push(mac)?; |
| 205 | added += 1; |
| 206 | } |
| 207 | println!("Seeded {added} BSSID(s) from {}", seed_path.display()); |
| 208 | } |
| 209 | frontier.checkpoint()?; |
| 210 | seen.checkpoint()?; |
| 211 | |
| 212 | let mut prober = Prober::new(args.probe_seed); |
| 213 | for path in &args.oui_files { |
| 214 | let text = std::fs::read_to_string(path)?; |
| 215 | let added = prober.load_ouis(&text); |
| 216 | println!("Loaded {added} OUI(s) from {}", path.display()); |
| 217 | } |
| 218 | |
| 219 | if frontier.pending() == 0 && args.probe == 0 { |
| 220 | eprintln!( |
| 221 | "error: nothing to crawl and --probe 0. Seed the frontier with --seed, or allow \ |
| 222 | random probing." |
| 223 | ); |
| 224 | return Ok(()); |
| 225 | } |
| 226 | if frontier.pending() == 0 { |
| 227 | println!( |
| 228 | "Frontier empty: guessing {} BSSID(s) per request until one lands. {} OUI(s) known.", |
| 229 | args.probe, |
| 230 | prober.known_ouis() |
| 231 | ); |
| 232 | } |
| 233 | |
| 234 | // Append rather than truncate: a resumed crawl adds to the same shard, and `wps_build` |
| 235 | // deduplicates. Truncating would silently throw away the previous run's work. |
| 236 | let out = OpenOptions::new().create(true).append(true).open(&args.out)?; |
| 237 | let mut writer = RecordWriter::new(BufWriter::with_capacity(1 << 20, out)); |
| 238 | let mut client = Client::new(args.interval); |
| 239 | |
| 240 | let mut progress = Progress::new(Duration::from_secs(args.status_secs)); |
| 241 | let mut backoff = args.interval; |
| 242 | let mut since_seen_checkpoint = 0u32; |
| 243 | let mut consecutive_failures = 0u32; |
| 244 | |
| 245 | loop { |
| 246 | if args.max_queries.is_some_and(|m| progress.queries >= m) { |
| 247 | println!("Reached --max-queries {}", progress.queries); |
| 248 | break; |
| 249 | } |
| 250 | // Counted separately from successes: without this a crawl whose requests all fail |
| 251 | // loops forever, doubling its backoff and never reaching any stopping condition. |
| 252 | if args.max_queries.is_some_and(|m| progress.attempts >= m.saturating_mul(4) + 10) { |
| 253 | eprintln!( |
| 254 | "error: giving up after {} attempt(s) for {} success(es)", |
| 255 | progress.attempts, progress.queries |
| 256 | ); |
| 257 | break; |
| 258 | } |
| 259 | if consecutive_failures >= MAX_CONSECUTIVE_FAILURES { |
| 260 | eprintln!( |
| 261 | "error: {consecutive_failures} consecutive failures; stopping rather than \ |
| 262 | hammering a service that is clearly refusing us" |
| 263 | ); |
| 264 | break; |
| 265 | } |
| 266 | // Real frontier entries always come first; guessing is only for the cold start, and |
| 267 | // stops as soon as a response gives the crawl somewhere real to go. |
| 268 | let batch = frontier.take(args.batch)?; |
| 269 | let probing = batch.is_empty(); |
| 270 | let batch = if probing { |
| 271 | if args.probe == 0 { |
| 272 | println!("Frontier exhausted after {} quer(ies)", progress.queries); |
| 273 | break; |
| 274 | } |
| 275 | prober.candidates(args.probe) |
| 276 | } else { |
| 277 | batch |
| 278 | }; |
| 279 | let bssids: Vec<String> = batch.iter().map(|&m| format_mac(m)).collect(); |
| 280 | |
| 281 | match client.query_wifi(&bssids) { |
| 282 | Ok(fixes) => { |
| 283 | backoff = args.interval; |
| 284 | consecutive_failures = 0; |
| 285 | if probing && !fixes.is_empty() { |
| 286 | prober.hits += 1; |
| 287 | println!( |
| 288 | "Probe landed after {} guess(es): {} result(s), hit rate {:.4}%", |
| 289 | prober.probes, |
| 290 | fixes.len(), |
| 291 | prober.hit_rate() * 100.0 |
| 292 | ); |
| 293 | } |
| 294 | let (mut observations, mut discovered) = (0u64, 0u64); |
| 295 | for fix in &fixes { |
| 296 | let Some(record) = to_record(fix) else { continue }; |
| 297 | writer.push(&record)?; |
| 298 | observations += 1; |
| 299 | // Every real address teaches the guesser which vendors exist, so the cold |
| 300 | // start gets cheaper even while the frontier is doing the work. |
| 301 | let mac = record.key as u64; |
| 302 | let _ = prober.observe(mac); |
| 303 | // Only unseen neighbours extend the frontier; the seen-set is what keeps |
| 304 | // the crawl from walking in circles. |
| 305 | if seen.insert(mac) { |
| 306 | frontier.push(mac)?; |
| 307 | discovered += 1; |
| 308 | } |
| 309 | } |
| 310 | progress.success(observations, discovered); |
| 311 | } |
| 312 | Err(e) => { |
| 313 | let kind = match &e { |
| 314 | gsloc::Error::Status(400) => FailKind::BadRequest, |
| 315 | gsloc::Error::Status(_) => FailKind::Status, |
| 316 | gsloc::Error::Transport(_) => FailKind::Transport, |
| 317 | gsloc::Error::Malformed(_) => FailKind::Malformed, |
| 318 | }; |
| 319 | progress.failure(kind); |
| 320 | consecutive_failures += 1; |
| 321 | // Back off geometrically to a ceiling. A refusal usually means "slow down", |
| 322 | // and hammering through it would make the crawl worse, not faster. |
| 323 | backoff = (backoff * 2).min(Duration::from_secs(300)); |
| 324 | eprintln!( |
| 325 | "query failed ({e}) on {} BSSID(s){}; backing off {:?}", |
| 326 | bssids.len(), |
| 327 | if probing { " (probe)" } else { "" }, |
| 328 | backoff |
| 329 | ); |
| 330 | std::thread::sleep(backoff); |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // Checkpointing is tied to query count; status output is tied to the clock, so a |
| 335 | // crawl that has stalled keeps saying so instead of going quiet. |
| 336 | if progress.queries > 0 && progress.queries % args.checkpoint_every == 0 { |
| 337 | // Flush the shard first: records that were never flushed are lost outright, |
| 338 | // whereas a stale frontier cursor only costs a few repeated requests. |
| 339 | writer.flush()?; |
| 340 | frontier.checkpoint()?; |
| 341 | // The seen-set is a whole-file rewrite — 2 GB at --expected 1e9 — so it is |
| 342 | // checkpointed far less often than the frontier. Losing it costs re-queries of |
| 343 | // BSSIDs already visited, not data, which is worth trading for not writing |
| 344 | // gigabytes every few minutes. |
| 345 | since_seen_checkpoint += 1; |
| 346 | if since_seen_checkpoint >= SEEN_CHECKPOINT_EVERY { |
| 347 | seen.checkpoint()?; |
| 348 | since_seen_checkpoint = 0; |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | if progress.should_print() { |
| 353 | println!("{}", progress.line(frontier.pending(), seen.false_positive_rate())); |
| 354 | if prober.probes > 0 { |
| 355 | println!( |
| 356 | " probes {}, hits {}, rate {:.4}%, {} OUI(s) known", |
| 357 | prober.probes, |
| 358 | prober.hits, |
| 359 | prober.hit_rate() * 100.0, |
| 360 | prober.known_ouis() |
| 361 | ); |
| 362 | } |
| 363 | progress.reset_window(); |
| 364 | // Nothing downstream reads this until the process exits, and a crawl is normally |
| 365 | // watched through a redirected log, so keep the file current. |
| 366 | let _ = std::io::stdout().flush(); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | let _ = writer.finish()?; |
| 371 | frontier.checkpoint()?; |
| 372 | seen.checkpoint()?; |
| 373 | |
| 374 | println!("{}", progress.summary(frontier.pending())); |
| 375 | println!("Resume with the same --state to continue (drop --seed; the frontier persists)."); |
| 376 | Ok(()) |
| 377 | } |
| 378 | |
| 379 | /// Render a 48-bit key back to the `aa:bb:cc:dd:ee:ff` form the protocol sends. |
| 380 | fn format_mac(mac: u64) -> String { |
| 381 | let b = mac.to_be_bytes(); |
| 382 | format!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", b[2], b[3], b[4], b[5], b[6], b[7]) |
| 383 | } |
| 384 | |
| 385 | fn main() -> ExitCode { |
| 386 | let argv: Vec<String> = std::env::args().skip(1).collect(); |
| 387 | let args = match parse_args(&argv) { |
| 388 | Ok(a) => a, |
| 389 | Err(e) => { |
| 390 | if e != "help" { |
| 391 | eprintln!("error: {e}"); |
| 392 | } |
| 393 | eprintln!("{USAGE}"); |
| 394 | return if e == "help" { ExitCode::SUCCESS } else { ExitCode::FAILURE }; |
| 395 | } |
| 396 | }; |
| 397 | match run(&args) { |
| 398 | Ok(()) => ExitCode::SUCCESS, |
| 399 | Err(e) => { |
| 400 | eprintln!("error: {e}"); |
| 401 | ExitCode::FAILURE |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | #[cfg(test)] |
| 407 | mod tests { |
| 408 | use super::*; |
| 409 | |
| 410 | #[test] |
| 411 | fn macs_round_trip_through_the_wire_format() { |
| 412 | for s in ["00:11:22:33:44:55", "aa:bb:cc:dd:ee:ff", "00:00:00:00:00:01"] { |
| 413 | let mac = keys::parse_mac(s).unwrap(); |
| 414 | assert_eq!(format_mac(mac), s); |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | #[test] |
| 419 | fn randomized_and_out_of_range_fixes_never_enter_the_shard() { |
| 420 | let good = gsloc::WifiFix { |
| 421 | bssid: "00:11:22:33:44:55".to_string(), |
| 422 | lat_e8: 37_77493000, |
| 423 | lon_e8: -122_41942000, |
| 424 | accuracy_m: 35, |
| 425 | altitude_m: 44, |
| 426 | }; |
| 427 | assert_eq!(to_record(&good).unwrap().accuracy_m, 35); |
| 428 | assert_eq!(to_record(&good).unwrap().altitude_m, 44); |
| 429 | |
| 430 | let randomized = gsloc::WifiFix { bssid: "aa:bb:cc:dd:ee:ff".to_string(), ..good.clone() }; |
| 431 | assert_eq!(to_record(&randomized), None); |
| 432 | |
| 433 | let out_of_range = gsloc::WifiFix { lat_e8: 91_00000000, ..good.clone() }; |
| 434 | assert_eq!(to_record(&out_of_range), None); |
| 435 | |
| 436 | let unparseable = gsloc::WifiFix { bssid: "nonsense".to_string(), ..good.clone() }; |
| 437 | assert_eq!(to_record(&unparseable), None); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn an_absurd_accuracy_saturates_rather_than_wrapping() { |
| 442 | let fix = gsloc::WifiFix { |
| 443 | bssid: "00:11:22:33:44:55".to_string(), |
| 444 | lat_e8: 0, |
| 445 | lon_e8: 0, |
| 446 | accuracy_m: 10_000_000, |
| 447 | altitude_m: 0, |
| 448 | }; |
| 449 | assert_eq!(to_record(&fix).unwrap().accuracy_m, 65534); |
| 450 | } |
| 451 | } |