Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / README.md
| 1 | # wps_harvest — offline beacon store builder |
| 2 | |
| 3 | Builds `wifi-v3.wpsdb` and `cells-v3.wpsdb`, the offline WiFi and cell beacon databases that |
| 4 | `:networklocation` resolves scan results against. |
| 5 | |
| 6 | Replaces `wtfps-experiment/store.py`, which lived outside the repo and no longer exists. |
| 7 | `SUPPLY_CHAIN_RISKS.md` recorded that as the app's one unresolved-provenance dependency: the |
| 8 | shipped stores were built by code nobody could read. This is that code, in the tree. |
| 9 | |
| 10 | ## Pipeline |
| 11 | |
| 12 | ``` |
| 13 | v1 wifi.wpsdb ── wps_extract ──► seed-bssids.txt ─┐ |
| 14 | (BSSIDs only) │ |
| 15 | ├─ wps_crawl ──► *.shard ─┐ |
| 16 | (or a local scan, or random probing) ─────────────┘ (gs-loc snowball) │ |
| 17 | ├─ wps_build ──► wifi-v3.wpsdb |
| 18 | OpenCelliD ────── wps_seed ──────────────────────────────► *.shard ─────────┘ cells-v3.wpsdb |
| 19 | ``` |
| 20 | |
| 21 | Shards are the interchange format: fixed-width, unsorted, append-only. The stages are separate |
| 22 | processes because they have nothing in common operationally — a seed ingest is minutes, a |
| 23 | planet crawl is weeks, a build is hours of IO — and because passing shards means a crawl can be |
| 24 | interrupted, resumed, extended, or merged with a newer dump without any stage knowing about the |
| 25 | others. |
| 26 | |
| 27 | ## What "accuracy first" actually means here |
| 28 | |
| 29 | The store this writes keeps, per beacon: |
| 30 | |
| 31 | - **coordinates as integer degrees x 1e8** — bit-exact against what the source reported, since |
| 32 | gs-loc returns e8 integers and the CSV dumps are parsed as exact decimals rather than through |
| 33 | `f64`; |
| 34 | - **its own horizontal accuracy**, in metres; |
| 35 | - **its altitude**, in metres, when the source reports one. Apple's WiFi fixes carry it |
| 36 | (`location.5`; essentially always present, -1 when not). Cell responses have no altitude |
| 37 | field at all (verified on the wire: cell locations carry only fields 1–4, 11, 12), so cell |
| 38 | records always read as unknown. The payload is kind 2: lat(35) | lon(36) | acc(16) | alt(16) |
| 39 | = 103 bits; kind-1 stores (87 bits, no altitude) stay readable and report NaN altitude. |
| 40 | |
| 41 | The format it replaces quantized to a **20 m grid** and stored **no accuracy at all**, so the |
| 42 | device substituted one constant for every beacon. That mattered more than it sounds: the |
| 43 | solver's uncertainty weighting is fully implemented — `jni.rs` turns accuracy into each |
| 44 | measurement's `six_sigma_squared`, `lib.rs` sorts and seeds RANSAC by it and uses it as the |
| 45 | inlier threshold, `multilateration.rs` uses it as a per-axis dead-band and weight — and with |
| 46 | every beacon reporting the same number it all reduced to an unweighted centroid. |
| 47 | |
| 48 | Coverage comes from the crawl. What makes a fix *good* is `quality.rs`, which drops: |
| 49 | |
| 50 | - **movers** — a BSSID seen in two places kilometres apart is a phone hotspot, a travel router, |
| 51 | or an AP on a bus. Recording either position is worse than recording none, because the device |
| 52 | gets confidently placed somewhere it is not. This is also the standard privacy mitigation for |
| 53 | a dataset of this shape, since a moving AP's history is a person's history; |
| 54 | - **randomized and multicast MACs**, which are not stable identifiers for a place; |
| 55 | - **identities that do not fit the key layout**, rather than truncating them into a collision. |
| 56 | |
| 57 | `NearbyWifi.kt` mirrors the randomized-MAC filter so the device does not spend a store probe on |
| 58 | a key the builder deliberately excluded. |
| 59 | |
| 60 | ## The gs-loc protocol |
| 61 | |
| 62 | The envelope is byte-for-byte from [`joelkoen/wtfps`](https://codeberg.org/joelkoen/wtfps), |
| 63 | which is a working client. The version recovered from this app's own deleted Kotlin |
| 64 | implementation (`reference/`) was **wrong in three ways** and produced an empty response every |
| 65 | time: |
| 66 | |
| 67 | | | Recovered Kotlin | Actual | |
| 68 | | --- | --- | --- | |
| 69 | | Trailer | `00 00 00 01` + `00 00 00 00` (8 bytes) | `00 00 00 01 00 00 00` (**7**) | |
| 70 | | Body length prefix | big-endian `u16` | protobuf **varint** | |
| 71 | | Body | sent once | sent **twice** | |
| 72 | | OS string | `8.4.1.12H321` | `17.5.21F79` | |
| 73 | |
| 74 | The first two together put two spurious zero bytes in front of every request. The duplicated |
| 75 | body looks like a mistake in wtfps and may well be one, but it is what the working client does. |
| 76 | |
| 77 | The schema also differs from the recovered `.proto`: there is one `AppleWLoc` message, not |
| 78 | separate WiFi and cell ones. WiFi devices are field 2, cell responses field 22, and a cell |
| 79 | *request* is a single tower in field 25 — so unlike WiFi, cells are one tower per request. |
| 80 | "Not found" is `-18000000000` (-180 degrees) in both coordinates, **not** a negative accuracy; |
| 81 | treating a missing accuracy as "not found", as the old client did, discarded real fixes. |
| 82 | |
| 83 | ## Building |
| 84 | |
| 85 | ```sh |
| 86 | cd scripts/networklocation/wps_harvest |
| 87 | cargo build --release |
| 88 | ``` |
| 89 | |
| 90 | Detached from the repo-root workspace, like `scripts/maps/osm_ingest`: these are host binaries, |
| 91 | so the build never pulls the aarch64-android toolchain or the app crates' lints. `ureq` is the |
| 92 | one dependency that breaks the other host tools' "pure Rust, no C toolchain" rule, via rustls' |
| 93 | `ring` backend; it is allowed because nothing here cross-compiles and the alternative is |
| 94 | shelling out to curl once per request. |
| 95 | |
| 96 | ## Running |
| 97 | |
| 98 | ### 1. Seed the crawl |
| 99 | |
| 100 | **There is no open bulk WiFi dump to seed from.** beaconDB's homepage and README both say |
| 101 | dumps "will be" published — they are announced, not released — and Mozilla Location Services |
| 102 | was never able to publish its WiFi data at all, for legal and privacy reasons. WiGLE has the |
| 103 | data but its terms forbid redistributing it in bulk. |
| 104 | |
| 105 | The best seed is the previous-generation store, which is still published and holds hundreds of |
| 106 | millions of real BSSIDs: |
| 107 | |
| 108 | ```sh |
| 109 | curl -O https://data.maproj.org/wps/wifi.wpsdb |
| 110 | ./target/release/wps_extract wifi.wpsdb --out seed-bssids.txt |
| 111 | ``` |
| 112 | |
| 113 | **Identities only — v1 positions are never imported.** v1 quantized to a 20 m grid and stored |
| 114 | no accuracy, so bringing a position forward would mean inventing one. It would also be worse |
| 115 | than useless: `quality::reduce` keeps whichever observation claims the better accuracy, and |
| 116 | Apple typically reports 20-100 m for WiFi, so a v1 position labelled 20 m would **beat most |
| 117 | real crawled measurements** and pin the beacon to its old grid cell. Every coordinate in the |
| 118 | new store comes from a source that also said how accurate it was. |
| 119 | |
| 120 | Extracting the real store yields ~189 M BSSIDs — and drops ~98 M (34%) randomized or |
| 121 | locally-administered addresses that v1 never filtered. |
| 122 | |
| 123 | Failing that, a local WiFi scan gives a seed for one metro: |
| 124 | |
| 125 | ```powershell |
| 126 | netsh wlan show networks mode=bssid | Select-String 'BSSID' > seed-bssids.txt |
| 127 | ``` |
| 128 | |
| 129 | ```sh |
| 130 | nmcli -f BSSID device wifi list > seed-bssids.txt # Linux |
| 131 | ``` |
| 132 | |
| 133 | ### 2. Crawl |
| 134 | |
| 135 | ```sh |
| 136 | ./target/release/wps_crawl \ |
| 137 | --state ./crawl-state \ |
| 138 | --out wifi-gsloc.shard \ |
| 139 | --seed seed-bssids.txt \ |
| 140 | --interval 1000 \ |
| 141 | --expected 1000000000 |
| 142 | ``` |
| 143 | |
| 144 | Kill it whenever. Rerun the same command to resume — the frontier, its cursor and the seen-set |
| 145 | all live in `--state`, and the shard is appended to. `--max-queries` bounds a trial run. |
| 146 | |
| 147 | **One BSSID per request.** Apple answers HTTP 400 to a request carrying more than one WiFi |
| 148 | device, verified live: a single BSSID returns ~108 neighbours, eight returns 400 every time. |
| 149 | `--batch` therefore defaults to 1 and exists only so the limit can be re-tested if the service |
| 150 | changes. The surplus results are not asked for — there is no `num_results` field, Apple simply |
| 151 | volunteers the neighbours of anything it recognises, and that is the whole basis of the crawl. |
| 152 | |
| 153 | #### Cold start with no seed at all |
| 154 | |
| 155 | When the frontier is empty, `wps_crawl` guesses addresses until one lands (`--probe`). This |
| 156 | works because only ~37 000 of the 16.7 million possible OUIs are assigned to anyone, so |
| 157 | drawing from assigned OUI space is roughly 450x better than drawing uniformly. It learns: |
| 158 | every BSSID in any response contributes its OUI to a frequency-weighted reservoir, so the hit |
| 159 | rate climbs as it runs. See `probe.rs` for the arithmetic. |
| 160 | |
| 161 | Be realistic about the cold start, though — at one guess per request and one request per |
| 162 | second: |
| 163 | |
| 164 | | Starting from | Rough hit rate | Expected time to first hit | |
| 165 | | --- | --- | --- | |
| 166 | | Nothing at all | ~1 in 140 000 | ~39 hours | |
| 167 | | An OUI list (`--oui-file`) | ~1 in 300 | ~5 minutes | |
| 168 | | One real BSSID (`--seed`) | — | immediate | |
| 169 | |
| 170 | So `--probe` is a genuine fallback, not the intended path. A single BSSID from a local WiFi |
| 171 | scan is worth more than a day of guessing: |
| 172 | |
| 173 | ```sh |
| 174 | ./target/release/wps_crawl --state ./crawl-state --out wifi-gsloc.shard \ |
| 175 | --oui-file oui.csv # the IEEE registry, or any WiFi scan output |
| 176 | ``` |
| 177 | |
| 178 | ### 3. Seed the cell store from the open dumps |
| 179 | |
| 180 | Cells are unaffected by any of the above — OpenCelliD publishes a full CSV, and this step works |
| 181 | today. The parser is driven by the header row rather than fixed column positions, so a renamed |
| 182 | column fails loudly instead of quietly reading longitude out of the accuracy field. Compressed |
| 183 | dumps are piped in rather than decompressed in process. |
| 184 | |
| 185 | ```sh |
| 186 | gunzip -c cell_towers.csv.gz | \ |
| 187 | ./target/release/wps_seed --kind cell --source opencellid --out cells-ocid.shard - |
| 188 | ``` |
| 189 | |
| 190 | **This talks to somebody else's service, at length.** Requests are serialized through one |
| 191 | client with a minimum interval, and failures back off geometrically to a five-minute ceiling. |
| 192 | `analysis/server-inventory-raw.md` already flags the endpoint as a terms-of-service concern; |
| 193 | running the crawl faster is both rude and self-defeating. |
| 194 | |
| 195 | ### Crawl cells from gs-loc |
| 196 | |
| 197 | OpenCelliD misses cells, and a phone whose serving cell is missing gets no fix at all: LTE |
| 198 | neighbour reports carry only a PCI, so the serving cell is usually the only one with a full |
| 199 | identity. `wps_cellcrawl` fills the gap from gs-loc. An LTE cell request returns the asked-for |
| 200 | cell plus about 120 surrounding LTE cells, so seeding it with a phone's cells covers the area |
| 201 | around it: |
| 202 | |
| 203 | ```sh |
| 204 | ./target/release/wps_cellcrawl --out cells-gsloc.shard \ |
| 205 | --seed 310,260,14570,21206278 --max-queries 30 --radius-km 15 |
| 206 | ``` |
| 207 | |
| 208 | Seeds are `MCC,MNC,TAC,CID`. Cells nearest the first resolved seed are queried first. LTE only: |
| 209 | gs-loc's cell request is the LTE tower field. |
| 210 | |
| 211 | ### 3. Build |
| 212 | |
| 213 | ```sh |
| 214 | ./target/release/wps_build --kind wifi --out wifi-v3.wpsdb \ |
| 215 | --scratch /var/tmp/wps wifi-bdb.shard wifi-gsloc.shard |
| 216 | |
| 217 | ./target/release/wps_build --kind cell --out cells-v3.wpsdb \ |
| 218 | --scratch /var/tmp/wps cells-ocid.shard cells-bdb.shard |
| 219 | ``` |
| 220 | |
| 221 | `--scratch` needs roughly twice the finished store's size. Nothing proportional to the record |
| 222 | count is held in memory at any stage: the sort spills fixed-size runs, the merge streams, and |
| 223 | the writer streams its three sections to scratch files before concatenating them. |
| 224 | |
| 225 | The build prints what it discarded and why, then reads the store back and checks every record. |
| 226 | The read-back walks the Elias-Fano bitvector directly rather than using `select0`, so a shared |
| 227 | misunderstanding between two `index()` implementations cannot hide behind it. `--no-verify` |
| 228 | exists but there is no good reason to use it. |
| 229 | |
| 230 | ### 4. Publish |
| 231 | |
| 232 | ```sh |
| 233 | sha256sum wifi-v3.wpsdb cells-v3.wpsdb |
| 234 | ../../maps/publish_r2.sh wifi-v3.wpsdb cells-v3.wpsdb |
| 235 | ``` |
| 236 | |
| 237 | Put the hashes into `OfflineDatabases.sha256For` in the app. They are load-bearing: a store is |
| 238 | several gigabytes fetched in resumable chunks, and a truncated file is non-empty, so without a |
| 239 | checksum it reads as installed and then fails its magic check on every open, forever. |
| 240 | |
| 241 | ## Cell key layout |
| 242 | |
| 243 | ``` |
| 244 | mcc(10) | mnc(10) | radio(4) | area(24) | cid(36) = 84 bits |
| 245 | ``` |
| 246 | |
| 247 | The previous layout was `mcc(10) | mnc(10) | tac(16) | cid(28)`, exactly 64 bits with nothing |
| 248 | spare, which cost two things. 5G's NCI is 36 bits and was **truncated to 28**, aliasing distinct |
| 249 | gNB cells. And there was **no radio-type discriminator**, so an LTE ECI and a GSM CID — the same |
| 250 | number in the same network and area code — mapped to one key. Fixing either requires more than |
| 251 | 64 bits, which is why the store's keys are 128-bit and the JNI boundary passes a `(hi, lo)` pair. |
| 252 | |
| 253 | ## Keeping the two sides in step |
| 254 | |
| 255 | `keys.rs` and `BeaconKeys.kt` must agree exactly. A mismatch does not throw or log — it makes |
| 256 | every lookup miss, which is indistinguishable from a database that does not know the beacon. |
| 257 | The test vectors in `keys.rs` are transcribed from `BeaconKeysTest.kt`; change them together. |
| 258 | |
| 259 | Likewise `store.rs` writes the format `networklocation/src/main/rust/src/wpsdb.rs` reads, and |
| 260 | that file's fixture tests build a store with a transcription of this writer, so a divergence |
| 261 | fails on the reader side too. |
| 262 | |
| 263 | ## Tests |
| 264 | |
| 265 | ```sh |
| 266 | cargo test |
| 267 | ``` |
| 268 | |
| 269 | Everything is covered without a real dump or a network: exact decimal parsing against the cases |
| 270 | where `f64` disagrees, header resolution for both dumps' spellings, mover and randomized-MAC |
| 271 | rejection, external sort across many runs, frontier resume semantics, store round-trip at both |
| 272 | key widths, and gs-loc request framing against the recovered Kotlin client byte for byte. |