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

Modern-Apps.git / scripts / networklocation / wps_harvest / README.md

README.md12.8 KiBRenderedCodeRaw
1# wps_harvest — offline beacon store builder
2
3Builds `wifi-v3.wpsdb` and `cells-v3.wpsdb`, the offline WiFi and cell beacon databases that
4`:networklocation` resolves scan results against.
5
6Replaces `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
8shipped stores were built by code nobody could read. This is that code, in the tree.
9
10## Pipeline
11
12```
13v1 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
18OpenCelliD ────── wps_seed ──────────────────────────────► *.shard ─────────┘ cells-v3.wpsdb
19```
20
21Shards are the interchange format: fixed-width, unsorted, append-only. The stages are separate
22processes because they have nothing in common operationally — a seed ingest is minutes, a
23planet crawl is weeks, a build is hours of IO — and because passing shards means a crawl can be
24interrupted, resumed, extended, or merged with a newer dump without any stage knowing about the
25others.
26
27## What "accuracy first" actually means here
28
29The 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
41The format it replaces quantized to a **20 m grid** and stored **no accuracy at all**, so the
42device substituted one constant for every beacon. That mattered more than it sounds: the
43solver's uncertainty weighting is fully implemented — `jni.rs` turns accuracy into each
44measurement's `six_sigma_squared`, `lib.rs` sorts and seeds RANSAC by it and uses it as the
45inlier threshold, `multilateration.rs` uses it as a per-axis dead-band and weight — and with
46every beacon reporting the same number it all reduced to an unweighted centroid.
47
48Coverage 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
58a key the builder deliberately excluded.
59
60## The gs-loc protocol
61
62The envelope is byte-for-byte from [`joelkoen/wtfps`](https://codeberg.org/joelkoen/wtfps),
63which is a working client. The version recovered from this app's own deleted Kotlin
64implementation (`reference/`) was **wrong in three ways** and produced an empty response every
65time:
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
74The first two together put two spurious zero bytes in front of every request. The duplicated
75body looks like a mistake in wtfps and may well be one, but it is what the working client does.
76
77The schema also differs from the recovered `.proto`: there is one `AppleWLoc` message, not
78separate 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;
81treating a missing accuracy as "not found", as the old client did, discarded real fixes.
82
83## Building
84
85```sh
86cd scripts/networklocation/wps_harvest
87cargo build --release
88```
89
90Detached from the repo-root workspace, like `scripts/maps/osm_ingest`: these are host binaries,
91so the build never pulls the aarch64-android toolchain or the app crates' lints. `ureq` is the
92one 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
94shelling 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
101dumps "will be" published — they are announced, not released — and Mozilla Location Services
102was never able to publish its WiFi data at all, for legal and privacy reasons. WiGLE has the
103data but its terms forbid redistributing it in bulk.
104
105The best seed is the previous-generation store, which is still published and holds hundreds of
106millions of real BSSIDs:
107
108```sh
109curl -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
114no accuracy, so bringing a position forward would mean inventing one. It would also be worse
115than useless: `quality::reduce` keeps whichever observation claims the better accuracy, and
116Apple typically reports 20-100 m for WiFi, so a v1 position labelled 20 m would **beat most
117real crawled measurements** and pin the beacon to its old grid cell. Every coordinate in the
118new store comes from a source that also said how accurate it was.
119
120Extracting the real store yields ~189 M BSSIDs — and drops ~98 M (34%) randomized or
121locally-administered addresses that v1 never filtered.
122
123Failing that, a local WiFi scan gives a seed for one metro:
124
125```powershell
126netsh wlan show networks mode=bssid | Select-String 'BSSID' > seed-bssids.txt
127```
128
129```sh
130nmcli -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
144Kill it whenever. Rerun the same command to resume — the frontier, its cursor and the seen-set
145all 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
148device, 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
150changes. The surplus results are not asked for — there is no `num_results` field, Apple simply
151volunteers 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
155When the frontier is empty, `wps_crawl` guesses addresses until one lands (`--probe`). This
156works because only ~37 000 of the 16.7 million possible OUIs are assigned to anyone, so
157drawing from assigned OUI space is roughly 450x better than drawing uniformly. It learns:
158every BSSID in any response contributes its OUI to a frequency-weighted reservoir, so the hit
159rate climbs as it runs. See `probe.rs` for the arithmetic.
160
161Be realistic about the cold start, though — at one guess per request and one request per
162second:
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
170So `--probe` is a genuine fallback, not the intended path. A single BSSID from a local WiFi
171scan 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
180Cells are unaffected by any of the above — OpenCelliD publishes a full CSV, and this step works
181today. The parser is driven by the header row rather than fixed column positions, so a renamed
182column fails loudly instead of quietly reading longitude out of the accuracy field. Compressed
183dumps are piped in rather than decompressed in process.
184
185```sh
186gunzip -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
191client 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;
193running the crawl faster is both rude and self-defeating.
194
195### Crawl cells from gs-loc
196
197OpenCelliD misses cells, and a phone whose serving cell is missing gets no fix at all: LTE
198neighbour reports carry only a PCI, so the serving cell is usually the only one with a full
199identity. `wps_cellcrawl` fills the gap from gs-loc. An LTE cell request returns the asked-for
200cell plus about 120 surrounding LTE cells, so seeding it with a phone's cells covers the area
201around 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
208Seeds are `MCC,MNC,TAC,CID`. Cells nearest the first resolved seed are queried first. LTE only:
209gs-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
222count is held in memory at any stage: the sort spills fixed-size runs, the merge streams, and
223the writer streams its three sections to scratch files before concatenating them.
224
225The build prints what it discarded and why, then reads the store back and checks every record.
226The read-back walks the Elias-Fano bitvector directly rather than using `select0`, so a shared
227misunderstanding between two `index()` implementations cannot hide behind it. `--no-verify`
228exists but there is no good reason to use it.
229
230### 4. Publish
231
232```sh
233sha256sum wifi-v3.wpsdb cells-v3.wpsdb
234../../maps/publish_r2.sh wifi-v3.wpsdb cells-v3.wpsdb
235```
236
237Put the hashes into `OfflineDatabases.sha256For` in the app. They are load-bearing: a store is
238several gigabytes fetched in resumable chunks, and a truncated file is non-empty, so without a
239checksum it reads as installed and then fails its magic check on every open, forever.
240
241## Cell key layout
242
243```
244mcc(10) | mnc(10) | radio(4) | area(24) | cid(36) = 84 bits
245```
246
247The previous layout was `mcc(10) | mnc(10) | tac(16) | cid(28)`, exactly 64 bits with nothing
248spare, which cost two things. 5G's NCI is 36 bits and was **truncated to 28**, aliasing distinct
249gNB cells. And there was **no radio-type discriminator**, so an LTE ECI and a GSM CID — the same
250number in the same network and area code — mapped to one key. Fixing either requires more than
25164 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
256every lookup miss, which is indistinguishable from a database that does not know the beacon.
257The test vectors in `keys.rs` are transcribed from `BeaconKeysTest.kt`; change them together.
258
259Likewise `store.rs` writes the format `networklocation/src/main/rust/src/wpsdb.rs` reads, and
260that file's fixture tests build a store with a transcription of this writer, so a divergence
261fails on the reader side too.
262
263## Tests
264
265```sh
266cargo test
267```
268
269Everything is covered without a real dump or a network: exact decimal parsing against the cases
270where `f64` disagrees, header resolution for both dumps' spellings, mover and randomized-MAC
271rejection, external sort across many runs, frontier resume semantics, store round-trip at both
272key widths, and gs-loc request framing against the recovered Kotlin client byte for byte.