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

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

keys.rs259 lines · 8.6 KiBRaw
1//! Beacon identity → 128-bit store key.
2//!
3//! Every function here has a counterpart in
4//! `networklocation/src/main/java/com/vayunmathur/networklocation/BeaconKeys.kt`, and the two
5//! must agree exactly. A mismatch is silent: the store is built with one packing, the device
6//! probes with another, every lookup misses, and that is indistinguishable from a database
7//! that simply does not know the beacon. The test vectors at the bottom of this file are
8//! transcribed verbatim from `BeaconKeysTest.kt` for exactly that reason.
9
10/// A BSSID is 48 bits, so the high half of a WiFi key is always zero.
11pub const WIFI_UNIVERSE_BITS: u8 = 48;
12
13/// Cell keys are 84 bits, laid out MSB-first as:
14///
15/// ```text
16/// mcc(10) | mnc(10) | radio(4) | area(24) | cid(36)
17/// ```
18///
19/// 36 bits of cell id covers 5G's NCI; 24 bits of area code covers 5G's TAC. The radio type is
20/// part of the identity because an LTE ECI and a GSM CID are otherwise indistinguishable
21/// numbers within the same network and area code.
22pub const CELL_UNIVERSE_BITS: u8 = 84;
23
24const CID_BITS: u32 = 36;
25const AREA_BITS: u32 = 24;
26const CID_MASK: u64 = (1u64 << CID_BITS) - 1;
27const AREA_MASK: u64 = (1u64 << AREA_BITS) - 1;
28
29/// Cellular access technology. Wire values are baked into every cell key, so this is
30/// append-only and must match `RadioType` in `PositioningData.kt`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub enum RadioType {
33 /// 2G.
34 Gsm = 1,
35 /// 3G.
36 Umts = 2,
37 /// 4G.
38 Lte = 3,
39 /// 5G.
40 Nr = 4,
41}
42
43impl RadioType {
44 /// Parse the spellings the open datasets use in their `radio` column.
45 pub fn parse(s: &str) -> Option<RadioType> {
46 match s.trim().to_ascii_uppercase().as_str() {
47 "GSM" | "2G" | "CDMA" => (s.trim().to_ascii_uppercase() != "CDMA").then_some(RadioType::Gsm),
48 "UMTS" | "WCDMA" | "3G" | "HSPA" => Some(RadioType::Umts),
49 "LTE" | "4G" => Some(RadioType::Lte),
50 "NR" | "5G" | "NRNSA" => Some(RadioType::Nr),
51 _ => None,
52 }
53 }
54}
55
56/// A cell tower's identity, before packing.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct CellId {
59 /// Mobile country code, 0..=999.
60 pub mcc: u16,
61 /// Mobile network code, 0..=999.
62 pub mnc: u16,
63 /// Access technology.
64 pub radio: RadioType,
65 /// Cell id: NR NCI (36 bits), LTE ECI (28), UMTS CID (28) or GSM CID (16).
66 pub cell_id: u64,
67 /// LTE/NR TAC or GSM/UMTS LAC.
68 pub area: u32,
69}
70
71/// Parse `"aa:bb:cc:dd:ee:ff"` to a 48-bit key, big-endian (OUI in the high bits).
72pub fn parse_mac(bssid: &str) -> Option<u64> {
73 let mut v = 0u64;
74 let mut groups = 0;
75 for part in bssid.split(':') {
76 if part.len() != 2 {
77 return None;
78 }
79 let b = u8::from_str_radix(part, 16).ok()?;
80 v = (v << 8) | b as u64;
81 groups += 1;
82 }
83 (groups == 6).then_some(v)
84}
85
86/// Whether `mac` is locally administered or multicast.
87///
88/// Randomized client addresses, virtual interfaces and multicast addresses are not stable
89/// identifiers for a place: the same address turns up somewhere else tomorrow. An entry for
90/// one is worse than no entry, so the builder drops them and the client skips probing them.
91pub fn is_randomized_mac(mac: u64) -> bool {
92 ((mac >> 40) & 0x03) != 0
93}
94
95/// Full 128-bit store key for a WiFi AP.
96pub fn wifi_key(mac: u64) -> u128 {
97 mac as u128
98}
99
100/// Full 128-bit store key for a cell tower.
101pub fn cell_key(id: &CellId) -> u128 {
102 let hi = ((id.mcc as u64 & 0x3FF) << 10) | (id.mnc as u64 & 0x3FF);
103 let lo = ((id.radio as u64 & 0xF) << (CID_BITS + AREA_BITS))
104 | ((id.area as u64 & AREA_MASK) << CID_BITS)
105 | (id.cell_id & CID_MASK);
106 ((hi as u128) << 64) | lo as u128
107}
108
109/// Whether `id` survives packing unchanged. A tower whose identity does not fit the key
110/// layout would be stored under a truncated key that a different tower also maps to, so it is
111/// dropped rather than aliased.
112pub fn cell_fits(id: &CellId) -> bool {
113 id.mcc <= 999
114 && id.mnc <= 999
115 && (id.area as u64) <= AREA_MASK
116 && id.cell_id <= CID_MASK
117 && id.cell_id > 0
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123
124 // These expectations are transcribed from `BeaconKeysTest.kt`. Change them here only
125 // together with that file.
126
127 #[test]
128 fn mac_parses_big_endian_with_the_oui_in_the_high_bits() {
129 assert_eq!(parse_mac("00:11:22:33:44:55"), Some(0x001122334455));
130 assert_eq!(parse_mac("aa:bb:cc:dd:ee:ff"), Some(0xAABBCCDDEEFF));
131 assert_eq!(parse_mac("AA:BB:CC:DD:EE:FF"), Some(0xAABBCCDDEEFF));
132 assert_eq!(parse_mac("00:00:00:00:00:00"), Some(0));
133 assert_eq!(parse_mac("ff:ff:ff:ff:ff:ff"), Some(0xFFFFFFFFFFFF));
134 }
135
136 #[test]
137 fn malformed_macs_are_rejected() {
138 for bad in [
139 "",
140 "00:11:22:33:44",
141 "00:11:22:33:44:55:66",
142 "00-11-22-33-44-55",
143 "zz:11:22:33:44:55",
144 "0:11:22:33:44:55",
145 "-1:11:22:33:44:55",
146 ] {
147 assert_eq!(parse_mac(bad), None, "{bad:?} must not parse");
148 }
149 }
150
151 #[test]
152 fn locally_administered_and_multicast_macs_are_excluded() {
153 assert!(is_randomized_mac(0xAABBCCDDEEFF));
154 assert!(is_randomized_mac(0x020000000000));
155 assert!(is_randomized_mac(0x010000000000));
156 assert!(!is_randomized_mac(0x001122334455));
157 assert!(!is_randomized_mac(0xFCFBFB000000));
158 assert!(!is_randomized_mac(0x00FFFFFFFFFF));
159 }
160
161 #[test]
162 fn cell_key_layout_is_mcc10_mnc10_radio4_area24_cid36() {
163 let id = CellId {
164 mcc: 310,
165 mnc: 260,
166 radio: RadioType::Lte,
167 cell_id: 0xABCDEF123,
168 area: 12345,
169 };
170 let key = cell_key(&id);
171 assert_eq!((key >> 64) as u64, 0x4D904);
172 assert_eq!(key as u64, 0x3003039ABCDEF123);
173 }
174
175 #[test]
176 fn radio_type_discriminates_otherwise_identical_cells() {
177 let base = CellId {
178 mcc: 234,
179 mnc: 15,
180 radio: RadioType::Gsm,
181 cell_id: 4242,
182 area: 999,
183 };
184 let mut keys: Vec<u128> = [RadioType::Gsm, RadioType::Umts, RadioType::Lte, RadioType::Nr]
185 .iter()
186 .map(|&r| cell_key(&CellId { radio: r, ..base }))
187 .collect();
188 keys.sort_unstable();
189 keys.dedup();
190 assert_eq!(keys.len(), 4, "each radio type must produce its own key");
191 }
192
193 #[test]
194 fn full_36_bit_nci_survives_packing() {
195 let id = CellId {
196 mcc: 1,
197 mnc: 1,
198 radio: RadioType::Nr,
199 cell_id: 0xFFFFFFFFF,
200 area: 0,
201 };
202 assert_eq!(cell_key(&id) as u64 & 0xFFFFFFFFF, 0xFFFFFFFFF);
203 let truncated = CellId { cell_id: 0x0FFFFFFF, ..id };
204 assert_ne!(cell_key(&id), cell_key(&truncated));
205 }
206
207 #[test]
208 fn wide_5g_tac_survives_packing() {
209 let id = CellId {
210 mcc: 505,
211 mnc: 1,
212 radio: RadioType::Nr,
213 cell_id: 1,
214 area: 0xFFFFFF,
215 };
216 assert_eq!((cell_key(&id) as u64 >> 36) & 0xFFFFFF, 0xFFFFFF);
217 }
218
219 #[test]
220 fn keys_stay_inside_their_declared_universe() {
221 let widest = CellId {
222 mcc: 999,
223 mnc: 999,
224 radio: RadioType::Nr,
225 cell_id: 0xFFFFFFFFF,
226 area: 0xFFFFFF,
227 };
228 assert!(cell_key(&widest) < (1u128 << CELL_UNIVERSE_BITS));
229 assert!(wifi_key(0xFFFFFFFFFFFF) < (1u128 << WIFI_UNIVERSE_BITS));
230 }
231
232 #[test]
233 fn identities_that_do_not_fit_are_rejected_not_truncated() {
234 let ok = CellId {
235 mcc: 310,
236 mnc: 260,
237 radio: RadioType::Lte,
238 cell_id: 42,
239 area: 7,
240 };
241 assert!(cell_fits(&ok));
242 assert!(!cell_fits(&CellId { mcc: 1000, ..ok }));
243 assert!(!cell_fits(&CellId { mnc: 1000, ..ok }));
244 assert!(!cell_fits(&CellId { area: 0x1000000, ..ok }));
245 assert!(!cell_fits(&CellId { cell_id: 1 << 36, ..ok }));
246 assert!(!cell_fits(&CellId { cell_id: 0, ..ok }));
247 }
248
249 #[test]
250 fn radio_parse_covers_the_dataset_spellings() {
251 assert_eq!(RadioType::parse("GSM"), Some(RadioType::Gsm));
252 assert_eq!(RadioType::parse("umts"), Some(RadioType::Umts));
253 assert_eq!(RadioType::parse("LTE"), Some(RadioType::Lte));
254 assert_eq!(RadioType::parse("NR"), Some(RadioType::Nr));
255 // CDMA has no MCC/MNC/LAC/CID identity of this shape and is not carried.
256 assert_eq!(RadioType::parse("CDMA"), None);
257 assert_eq!(RadioType::parse("banana"), None);
258 }
259}