Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / v1.rs
v1.rs250 lines · 9.6 KiBRaw
| 1 | //! Reading the BSSIDs out of the previous-generation `WPSDB1` stores. |
| 2 | //! |
| 3 | //! The v1 stores that `:networklocation` shipped are still published and hold hundreds of |
| 4 | //! millions of real BSSIDs. That makes them by far the best available crawl seed: there is no |
| 5 | //! open bulk WiFi dump, and the alternatives are a local scan (one metro) or guessing |
| 6 | //! addresses for hours. |
| 7 | //! |
| 8 | //! ## Only the keys |
| 9 | //! |
| 10 | //! The coordinates in a v1 store are **deliberately not read**. v1 quantized every position to |
| 11 | //! a 20 m grid and stored no accuracy at all, so the best that could be said of an imported |
| 12 | //! record is "somewhere within ~14 m of here". Carrying that forward would not merely be |
| 13 | //! imprecise, it would be actively harmful: `quality::reduce` keeps whichever observation |
| 14 | //! reports the better accuracy, and Apple typically reports 20-100 m for WiFi, so a v1 record |
| 15 | //! labelled 20 m would **beat most real crawled measurements** and pin the beacon to its old |
| 16 | //! grid cell. The store would end up more precise-looking and less correct. |
| 17 | //! |
| 18 | //! So v1 contributes identities, not positions. Every coordinate in the new store comes from a |
| 19 | //! source that also said how accurate it was. |
| 20 | //! |
| 21 | //! The format, little-endian throughout with LSB-first bit packing: |
| 22 | //! |
| 23 | //! ```text |
| 24 | //! 0 magic "WPSDB1\0\0" |
| 25 | //! 8 coord_bits:u32 |
| 26 | //! 12 n:u64 |
| 27 | //! 20 n:u64 (repeated), l:u8, universe_bits:u8, high_len_bits:u64 |
| 28 | //! 38 high_len:u64, high[high_len] |
| 29 | //! low_len:u64, low[low_len] |
| 30 | //! clen:u64, coord[clen] (parsed past, never decoded) |
| 31 | //! ``` |
| 32 | |
| 33 | use std::io; |
| 34 | |
| 35 | /// v1 packed coordinates as a 20-bit latitude and 21-bit longitude index. Only used to |
| 36 | /// recognise the format; the coordinates themselves are never decoded. |
| 37 | const V1_COORD_BITS: u32 = 20 + 21; |
| 38 | |
| 39 | /// A decoded v1 store's key set. |
| 40 | pub struct StoreV1 { |
| 41 | /// Key universe width, 48 for WiFi. |
| 42 | pub universe_bits: u8, |
| 43 | /// Keys in ascending order. |
| 44 | pub keys: Vec<u64>, |
| 45 | } |
| 46 | |
| 47 | fn rd_u32(b: &[u8], p: usize) -> io::Result<u32> { |
| 48 | b.get(p..p + 4) |
| 49 | .and_then(|s| s.try_into().ok()) |
| 50 | .map(u32::from_le_bytes) |
| 51 | .ok_or_else(|| bad("truncated header")) |
| 52 | } |
| 53 | |
| 54 | fn rd_u64(b: &[u8], p: usize) -> io::Result<u64> { |
| 55 | b.get(p..p + 8) |
| 56 | .and_then(|s| s.try_into().ok()) |
| 57 | .map(u64::from_le_bytes) |
| 58 | .ok_or_else(|| bad("truncated header")) |
| 59 | } |
| 60 | |
| 61 | fn bad(msg: &str) -> io::Error { |
| 62 | io::Error::new(io::ErrorKind::InvalidData, msg.to_string()) |
| 63 | } |
| 64 | |
| 65 | /// Read `nbits` (<= 64) LSB-first from `buf` starting at bit `bit`. |
| 66 | fn bits(buf: &[u8], bit: u64, nbits: u32) -> u64 { |
| 67 | let mut v = 0u64; |
| 68 | for k in 0..nbits as u64 { |
| 69 | let p = bit + k; |
| 70 | if let Some(&byte) = buf.get((p >> 3) as usize) { |
| 71 | if (byte >> (p & 7)) & 1 == 1 { |
| 72 | v |= 1u64 << k; |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | v |
| 77 | } |
| 78 | |
| 79 | /// Parse a v1 store's key set. |
| 80 | /// |
| 81 | /// Walks the Elias-Fano upper bitvector to recover each key, which is the inverse of the |
| 82 | /// reader's `index()` and independent of it — so this does not inherit any misunderstanding |
| 83 | /// that reader might have had. The coordinate section is bounds-checked but never decoded; |
| 84 | /// see the module docs for why. |
| 85 | pub fn parse(buf: &[u8]) -> io::Result<StoreV1> { |
| 86 | if buf.len() < 46 || &buf[0..8] != b"WPSDB1\x00\x00" { |
| 87 | return Err(bad("not a WPSDB1 store")); |
| 88 | } |
| 89 | let coord_bits = rd_u32(buf, 8)?; |
| 90 | if coord_bits != V1_COORD_BITS { |
| 91 | return Err(bad("unexpected coord width; this is not the 20 m grid format")); |
| 92 | } |
| 93 | let n = rd_u64(buf, 12)?; |
| 94 | let l = *buf.get(28).ok_or_else(|| bad("truncated header"))?; |
| 95 | let universe_bits = *buf.get(29).ok_or_else(|| bad("truncated header"))?; |
| 96 | let high_len_bits = rd_u64(buf, 30)?; |
| 97 | let high_len = rd_u64(buf, 38)? as usize; |
| 98 | |
| 99 | let high = buf.get(46..46 + high_len).ok_or_else(|| bad("truncated high bitvector"))?; |
| 100 | let low_len_off = 46 + high_len; |
| 101 | let low_len = rd_u64(buf, low_len_off)? as usize; |
| 102 | let low_off = low_len_off + 8; |
| 103 | let low = buf.get(low_off..low_off + low_len).ok_or_else(|| bad("truncated low array"))?; |
| 104 | // Checked so a truncated file is rejected rather than silently yielding a partial key set. |
| 105 | let clen_off = low_off + low_len; |
| 106 | let clen = rd_u64(buf, clen_off)? as usize; |
| 107 | let _ = buf.get(clen_off + 8..clen_off + 8 + clen).ok_or_else(|| bad("truncated coords"))?; |
| 108 | |
| 109 | let mut keys = Vec::with_capacity(n as usize); |
| 110 | let mut idx = 0u64; |
| 111 | let mut p = 0u64; |
| 112 | while p < high_len_bits && idx < n { |
| 113 | if (high[(p >> 3) as usize] >> (p & 7)) & 1 == 1 { |
| 114 | let upper = p - idx; |
| 115 | let lo = if l == 0 { 0 } else { bits(low, idx * l as u64, l as u32) }; |
| 116 | keys.push(if l >= 64 { lo } else { (upper << l) | lo }); |
| 117 | idx += 1; |
| 118 | } |
| 119 | p += 1; |
| 120 | } |
| 121 | if idx != n { |
| 122 | return Err(bad("recovered fewer keys than the header declares")); |
| 123 | } |
| 124 | Ok(StoreV1 { universe_bits, keys }) |
| 125 | } |
| 126 | |
| 127 | #[cfg(test)] |
| 128 | mod tests { |
| 129 | use super::*; |
| 130 | |
| 131 | /// Build a v1 store, so the parser is checked against something other than itself. |
| 132 | fn build_v1(universe_bits: u8, entries: &[(u64, u64)]) -> Vec<u8> { |
| 133 | let n = entries.len() as u64; |
| 134 | // With no keys the bucket space must collapse to one, not to the whole universe: an |
| 135 | // `l` of 0 over a 48-bit universe asks for 2^48 padding bits. The real writer has the |
| 136 | // same guard for the same reason. |
| 137 | let mut l = if n == 0 { universe_bits.min(63) } else { 0 }; |
| 138 | if n > 0 { |
| 139 | let u = 1u128 << universe_bits; |
| 140 | while l < 63 && (u >> (l as u32 + 1)) >= n as u128 { |
| 141 | l += 1; |
| 142 | } |
| 143 | } |
| 144 | let push_bits = |buf: &mut Vec<u8>, bitlen: &mut u64, v: u64, nbits: u32| { |
| 145 | for k in 0..nbits as u64 { |
| 146 | if (*bitlen & 7) == 0 { |
| 147 | buf.push(0); |
| 148 | } |
| 149 | if (v >> k) & 1 == 1 { |
| 150 | let p = *bitlen; |
| 151 | buf[(p >> 3) as usize] |= 1 << (p & 7); |
| 152 | } |
| 153 | *bitlen += 1; |
| 154 | } |
| 155 | }; |
| 156 | |
| 157 | let (mut high, mut high_bits) = (Vec::new(), 0u64); |
| 158 | let mut prev_bucket = 0u64; |
| 159 | for &(key, _) in entries { |
| 160 | let bucket = key >> l; |
| 161 | for _ in prev_bucket..bucket { |
| 162 | push_bits(&mut high, &mut high_bits, 0, 1); |
| 163 | } |
| 164 | push_bits(&mut high, &mut high_bits, 1, 1); |
| 165 | prev_bucket = bucket; |
| 166 | } |
| 167 | let buckets = 1u64 << (universe_bits as u32 - l as u32); |
| 168 | for _ in prev_bucket..buckets { |
| 169 | push_bits(&mut high, &mut high_bits, 0, 1); |
| 170 | } |
| 171 | |
| 172 | let (mut low, mut low_bits) = (Vec::new(), 0u64); |
| 173 | for &(key, _) in entries { |
| 174 | push_bits(&mut low, &mut low_bits, key & ((1u64 << l) - 1), l as u32); |
| 175 | } |
| 176 | let (mut coord, mut coord_bits_len) = (Vec::new(), 0u64); |
| 177 | for &(_, c) in entries { |
| 178 | push_bits(&mut coord, &mut coord_bits_len, c, V1_COORD_BITS); |
| 179 | } |
| 180 | |
| 181 | let mut out = b"WPSDB1\x00\x00".to_vec(); |
| 182 | out.extend_from_slice(&V1_COORD_BITS.to_le_bytes()); |
| 183 | out.extend_from_slice(&n.to_le_bytes()); |
| 184 | out.extend_from_slice(&n.to_le_bytes()); |
| 185 | out.push(l); |
| 186 | out.push(universe_bits); |
| 187 | out.extend_from_slice(&high_bits.to_le_bytes()); |
| 188 | out.extend_from_slice(&(high.len() as u64).to_le_bytes()); |
| 189 | out.extend_from_slice(&high); |
| 190 | out.extend_from_slice(&(low.len() as u64).to_le_bytes()); |
| 191 | out.extend_from_slice(&low); |
| 192 | out.extend_from_slice(&(coord.len() as u64).to_le_bytes()); |
| 193 | out.extend_from_slice(&coord); |
| 194 | out |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn a_v1_store_round_trips() { |
| 199 | let entries: Vec<(u64, u64)> = (0..500u64) |
| 200 | .map(|i| (i.wrapping_mul(7_919_401) & 0xFFFF_FFFF_FFFF, (i * 977) & 0x1FF_FFFF_FFFF)) |
| 201 | .collect(); |
| 202 | let mut sorted = entries.clone(); |
| 203 | sorted.sort_unstable_by_key(|e| e.0); |
| 204 | sorted.dedup_by_key(|e| e.0); |
| 205 | |
| 206 | let bytes = build_v1(48, &sorted); |
| 207 | let store = parse(&bytes).unwrap(); |
| 208 | assert_eq!(store.universe_bits, 48); |
| 209 | assert_eq!(store.keys, sorted.iter().map(|e| e.0).collect::<Vec<_>>()); |
| 210 | } |
| 211 | |
| 212 | /// The coordinate section must be present and correctly sized — it is what a truncation |
| 213 | /// check hangs off — but nothing in the output may depend on its contents. |
| 214 | #[test] |
| 215 | fn coordinates_are_never_read() { |
| 216 | let entries: Vec<(u64, u64)> = (0..100u64).map(|i| (i * 1_000_003, i * 12345)).collect(); |
| 217 | let a = parse(&build_v1(48, &entries)).unwrap(); |
| 218 | |
| 219 | // Same keys, completely different coordinates. |
| 220 | let scrambled: Vec<(u64, u64)> = |
| 221 | entries.iter().map(|&(k, c)| (k, c ^ 0x1FF_FFFF_FFFF)).collect(); |
| 222 | let b = parse(&build_v1(48, &scrambled)).unwrap(); |
| 223 | |
| 224 | assert_eq!(a.keys, b.keys, "the key set must not depend on the coordinates"); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn a_foreign_file_is_refused() { |
| 229 | assert!(parse(b"not a store at all............").is_err()); |
| 230 | let mut wrong = b"WPSDB1\x00\x00".to_vec(); |
| 231 | wrong.extend_from_slice(&64u32.to_le_bytes()); |
| 232 | wrong.extend_from_slice(&[0u8; 64]); |
| 233 | assert!(parse(&wrong).is_err(), "a different coord width must be refused"); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn an_empty_store_parses_to_nothing() { |
| 238 | let bytes = build_v1(48, &[]); |
| 239 | assert!(parse(&bytes).unwrap().keys.is_empty()); |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn truncation_is_detected_rather_than_producing_partial_data() { |
| 244 | let entries: Vec<(u64, u64)> = (0..50u64).map(|i| (i * 1_000_003, i)).collect(); |
| 245 | let bytes = build_v1(48, &entries); |
| 246 | for cut in [8, 40, bytes.len() / 2, bytes.len() - 1] { |
| 247 | assert!(parse(&bytes[..cut]).is_err(), "truncation at {cut} must be caught"); |
| 248 | } |
| 249 | } |
| 250 | } |