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

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

gsloc.rs343 lines · 12.6 KiBRaw
1//! Client for Apple's location service at `gs-loc.apple.com/clls/wloc`.
2//!
3//! Ported from the Kotlin client this app used to carry, recovered in
4//! `reference/ApplePositioningService.kt.txt`; the wire schema is `reference/apple_wps.proto`.
5//!
6//! Apple does not return a device position. Given beacon identifiers it returns each beacon's
7//! own coordinates and horizontal accuracy — which is precisely a beacon database lookup, and
8//! why this makes a store builder rather than a positioning client.
9//!
10//! It also returns **more beacons than were asked for**: a query for one BSSID comes back with
11//! a few hundred others in the same area. That is what makes a crawl possible at all, since
12//! every response both answers the query and extends the frontier.
13//!
14//! ## This talks to somebody else's service
15//!
16//! Requests are serialized through one client and rate-limited by [`Client::min_interval`],
17//! defaulting to something a person could plausibly generate. Errors back off rather than
18//! retrying hard. Doing otherwise would be both rude and self-defeating.
19
20use std::time::{Duration, Instant};
21
22use crate::proto::{self, Field};
23
24const ENDPOINT: &str = "https://gs-loc.apple.com/clls/wloc";
25
26/// Apple prefixes the response protobuf with a fixed-size header.
27const RESPONSE_HEADER_BYTES: usize = 10;
28
29/// OS version string in the request envelope. Must be 10 bytes to match the hardcoded length.
30const OS_VERSION: &str = "17.5.21F79";
31
32/// Coordinates arrive as integer degrees x 1e8, which is exactly what the store keeps.
33pub const COORD_SCALE: i64 = 100_000_000;
34
35/// What Apple returns for a beacon it does not know: -180 degrees, in both axes.
36const NOT_FOUND_E8: i64 = -18_000_000_000;
37
38// Field numbers within `AppleWLoc`, from wtfps's `src/apple.proto`.
39const F_WIFI_DEVICES: u32 = 2;
40const F_CELL_RESPONSE: u32 = 22;
41const F_CELL_REQUEST: u32 = 25;
42
43/// Altitude (Apple's `location.5`) meaning "not reported": Apple sends -1.
44pub const ALT_NOT_REPORTED: i64 = -1;
45
46/// Clamp a source-reported altitude into the store's `i16` metres, mapping Apple's -1
47/// "not reported" to [`crate::record::ALT_UNKNOWN`]. Saturates rather than wrapping: nothing
48/// real sits outside ±32 km, so saturation can only trigger on garbage, which then reads as
49/// extreme rather than plausible.
50pub fn clamp_altitude(metres: i64) -> i16 {
51 if metres == ALT_NOT_REPORTED {
52 i16::MIN
53 } else {
54 metres.clamp(i16::MIN as i64 + 1, i16::MAX as i64) as i16
55 }
56}
57
58/// A beacon Apple knows the location of.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct WifiFix {
61 /// Lowercase `aa:bb:cc:dd:ee:ff`, as echoed back.
62 pub bssid: String,
63 /// Latitude in degrees x 1e8.
64 pub lat_e8: i64,
65 /// Longitude in degrees x 1e8.
66 pub lon_e8: i64,
67 /// Horizontal accuracy in metres.
68 pub accuracy_m: i32,
69 /// Altitude in metres, or [`crate::record::ALT_UNKNOWN`]. Present on essentially every
70 /// WiFi fix (Apple's `location.5`); cell responses have no altitude field at all.
71 pub altitude_m: i16,
72}
73
74/// A cell tower Apple knows the location of.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct CellFix {
77 /// Mobile country code.
78 pub mcc: i32,
79 /// Mobile network code.
80 pub mnc: i32,
81 /// Cell id as Apple reports it.
82 pub cell_id: i64,
83 /// TAC or LAC.
84 pub area: i32,
85 /// Latitude in degrees x 1e8.
86 pub lat_e8: i64,
87 /// Longitude in degrees x 1e8.
88 pub lon_e8: i64,
89 /// Horizontal accuracy in metres.
90 pub accuracy_m: i32,
91}
92
93/// What went wrong with a request. Callers distinguish these because they back off
94/// differently: a transport hiccup is worth retrying, a refusal is not.
95#[derive(Debug)]
96pub enum Error {
97 /// The request never completed.
98 Transport(String),
99 /// A non-200 response.
100 Status(u16),
101 /// A 200 that did not contain a parseable body.
102 Malformed(&'static str),
103}
104
105impl std::fmt::Display for Error {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 match self {
108 Error::Transport(e) => write!(f, "transport: {e}"),
109 Error::Status(c) => write!(f, "HTTP {c}"),
110 Error::Malformed(m) => write!(f, "malformed response: {m}"),
111 }
112 }
113}
114
115impl std::error::Error for Error {}
116
117/// A rate-limited gs-loc client.
118pub struct Client {
119 agent: ureq::Agent,
120 /// Minimum wall time between two requests from this client.
121 pub min_interval: Duration,
122 last: Option<Instant>,
123}
124
125impl Client {
126 /// Build a client.
127 ///
128 /// A global timeout is not optional: without one a stalled connection hangs the crawl
129 /// indefinitely, and the service does sometimes accept a connection and then never answer.
130 pub fn new(min_interval: Duration) -> Client {
131 let config = ureq::Agent::config_builder()
132 .timeout_global(Some(Duration::from_secs(20)))
133 .timeout_connect(Some(Duration::from_secs(10)))
134 .build();
135 Client { agent: config.into(), min_interval, last: None }
136 }
137
138 fn throttle(&mut self) {
139 if let Some(last) = self.last {
140 let elapsed = last.elapsed();
141 if elapsed < self.min_interval {
142 std::thread::sleep(self.min_interval - elapsed);
143 }
144 }
145 self.last = Some(Instant::now());
146 }
147
148 /// Ask for the locations of `bssids`.
149 ///
150 /// The response carries far more devices than were sent — Apple volunteers the neighbours
151 /// of anything it recognises, which is the whole basis of the crawl. There is no field
152 /// asking for that; it is simply what the service does.
153 pub fn query_wifi(&mut self, bssids: &[String]) -> Result<Vec<WifiFix>, Error> {
154 if bssids.is_empty() {
155 return Ok(Vec::new());
156 }
157 let mut body = Vec::new();
158 for b in bssids {
159 let mut dev = Vec::new();
160 proto::put_bytes(&mut dev, 1, b.as_bytes());
161 proto::put_bytes(&mut body, F_WIFI_DEVICES, &dev);
162 }
163 let resp = self.post(&body)?;
164 Ok(parse_wifi(&resp))
165 }
166
167 /// Ask for the location of one cell tower.
168 ///
169 /// `AppleWLoc` carries a single `cell_tower_request` (field 25) and answers in a repeated
170 /// `cell_tower_response` (field 22), so unlike WiFi this is one tower per request.
171 pub fn query_cell(
172 &mut self,
173 mcc: u32,
174 mnc: u32,
175 cell_id: u32,
176 tac: u32,
177 ) -> Result<Vec<CellFix>, Error> {
178 let mut tower = Vec::new();
179 proto::put_int(&mut tower, 1, mcc as i64);
180 proto::put_int(&mut tower, 2, mnc as i64);
181 proto::put_int(&mut tower, 3, cell_id as i64);
182 proto::put_int(&mut tower, 4, tac as i64);
183 let mut body = Vec::new();
184 proto::put_bytes(&mut body, F_CELL_REQUEST, &tower);
185
186 let resp = self.post(&body)?;
187 Ok(parse_cells(&resp))
188 }
189
190 fn post(&mut self, payload: &[u8]) -> Result<Vec<u8>, Error> {
191 self.throttle();
192 let framed = frame(payload);
193 let mut resp = self
194 .agent
195 .post(ENDPOINT)
196 .header("Content-Type", "application/x-www-form-urlencoded")
197 .header("Accept", "*/*")
198 .header("Accept-Charset", "utf-8")
199 .header("Accept-Language", "en-us")
200 .header("User-Agent", "locationd/1753.17 CFNetwork/711.1.12 Darwin/14.0.0")
201 .send(&framed[..])
202 .map_err(|e| match e {
203 ureq::Error::StatusCode(code) => Error::Status(code),
204 other => Error::Transport(other.to_string()),
205 })?;
206
207 let raw = resp
208 .body_mut()
209 .with_config()
210 .limit(64 * 1024 * 1024)
211 .read_to_vec()
212 .map_err(|e| Error::Transport(e.to_string()))?;
213 if raw.len() <= RESPONSE_HEADER_BYTES {
214 return Err(Error::Malformed("shorter than the response header"));
215 }
216 Ok(raw[RESPONSE_HEADER_BYTES..].to_vec())
217 }
218}
219
220/// Wrap `payload` in Apple's request envelope.
221///
222/// Byte-for-byte from `joelkoen/wtfps` (`src/fetch.rs`), which is a working client. The
223/// envelope recovered from this app's old Kotlin implementation was **wrong** in three ways
224/// and produced an empty response every time:
225///
226/// * its trailer was eight bytes (`00 00 00 01` then `00 00 00 00`); the real one is **seven**;
227/// * it length-prefixed the body with a big-endian `u16`; the real one uses a protobuf
228/// **varint**, which for a short body is a single byte — so the two together put two spurious
229/// zero bytes in front of every request;
230/// * it sent the body once. The real one sends it **twice**, length-delimited and then again.
231///
232/// The duplicate looks like a mistake and may well be one, but it is what the working client
233/// does and this is not the place to find out whether Apple tolerates its absence.
234pub fn frame(payload: &[u8]) -> Vec<u8> {
235 let mut out = Vec::with_capacity(payload.len() * 2 + 64);
236 out.extend_from_slice(&[0x00, 0x01, 0x00, 0x05]);
237 out.extend_from_slice(b"en_US");
238 out.extend_from_slice(&[0x00, 0x13]);
239 out.extend_from_slice(b"com.apple.locationd");
240 out.extend_from_slice(&[0x00, 0x0a]);
241 out.extend_from_slice(OS_VERSION.as_bytes());
242 out.extend_from_slice(&[0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00]);
243 proto::put_varint(&mut out, payload.len() as u64);
244 out.extend_from_slice(payload);
245 out.extend_from_slice(payload);
246 out
247}
248
249/// A location submessage. `None` when the beacon is unknown, which Apple signals by returning
250/// -180 degrees in both axes rather than by omitting the field.
251///
252/// Returns `(lat, lon, accuracy_m, altitude_m)`. Only WiFi carries fields 5/6 (altitude and
253/// vertical accuracy); cell locations top out at field 4, so their altitude reads as
254/// "not reported" without any special-casing.
255fn parse_location(body: &[u8]) -> Option<(i64, i64, i32, i16)> {
256 let mut lat = None;
257 let mut lon = None;
258 let mut acc: i64 = -1;
259 let mut alt: i64 = ALT_NOT_REPORTED;
260 let r = proto::Reader::new(body);
261 for (field, v) in r {
262 if let Field::Varint(raw) = v {
263 match field {
264 1 => lat = Some(raw as i64),
265 2 => lon = Some(raw as i64),
266 3 => acc = raw as i64,
267 5 => alt = raw as i64,
268 _ => {}
269 }
270 }
271 }
272 let (lat, lon) = (lat?, lon?);
273 if lat == NOT_FOUND_E8 || lon == NOT_FOUND_E8 {
274 return None;
275 }
276 // Accuracy is int64 on the wire but only ever a plausible radius in metres; clamp rather
277 // than truncate so a hostile or garbled value cannot wrap into something small and
278 // confident-looking.
279 Some((lat, lon, acc.clamp(-1, i32::MAX as i64) as i32, clamp_altitude(alt)))
280}
281
282fn parse_wifi(body: &[u8]) -> Vec<WifiFix> {
283 let mut out = Vec::new();
284 let r = proto::Reader::new(body);
285 for (field, v) in r {
286 let Field::Bytes(dev) = v else { continue };
287 if field != F_WIFI_DEVICES {
288 continue;
289 }
290 let mut bssid = None;
291 let mut loc = None;
292 let dr = proto::Reader::new(dev);
293 for (df, dv) in dr {
294 match (df, dv) {
295 (1, Field::Bytes(s)) => bssid = std::str::from_utf8(s).ok(),
296 (2, Field::Bytes(b)) => loc = parse_location(b),
297 _ => {}
298 }
299 }
300 if let (Some(bssid), Some((lat_e8, lon_e8, accuracy_m, altitude_m))) = (bssid, loc) {
301 out.push(WifiFix {
302 bssid: bssid.to_ascii_lowercase(),
303 lat_e8,
304 lon_e8,
305 accuracy_m,
306 altitude_m,
307 });
308 }
309 }
310 out
311}
312
313fn parse_cells(body: &[u8]) -> Vec<CellFix> {
314 let mut out = Vec::new();
315 let r = proto::Reader::new(body);
316 for (field, v) in r {
317 let Field::Bytes(tower) = v else { continue };
318 if field != F_CELL_RESPONSE {
319 continue;
320 }
321 let (mut mcc, mut mnc, mut cell_id, mut area) = (None, None, None, None);
322 let mut loc = None;
323 let tr = proto::Reader::new(tower);
324 for (tf, tv) in tr {
325 match (tf, tv) {
326 (1, Field::Varint(x)) => mcc = Some(x as i64 as i32),
327 (2, Field::Varint(x)) => mnc = Some(x as i64 as i32),
328 (3, Field::Varint(x)) => cell_id = Some(x as i64),
329 (4, Field::Varint(x)) => area = Some(x as i64 as i32),
330 (5, Field::Bytes(b)) => loc = parse_location(b),
331 _ => {}
332 }
333 }
334 if let (Some(mcc), Some(mnc), Some(cell_id), Some(area), Some((lat_e8, lon_e8, acc, _))) =
335 (mcc, mnc, cell_id, area, loc)
336 {
337 out.push(CellFix { mcc, mnc, cell_id, area, lat_e8, lon_e8, accuracy_m: acc });
338 }
339 }
340 out
341}
342
343include!("gsloc_s1.rs");