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

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

keys.rs232 lines · 8.3 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" => {
48 (!s.trim().eq_ignore_ascii_case("CDMA")).then_some(RadioType::Gsm)
49 }
50 "UMTS" | "WCDMA" | "3G" | "HSPA" => Some(RadioType::Umts),
51 "LTE" | "4G" => Some(RadioType::Lte),
52 "NR" | "5G" | "NRNSA" => Some(RadioType::Nr),
53 _ => None,
54 }
55 }
56}
57
58/// A cell tower's identity, before packing.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub struct CellId {
61 /// Mobile country code, 0..=999.
62 pub mcc: u16,
63 /// Mobile network code, 0..=999.
64 pub mnc: u16,
65 /// Access technology.
66 pub radio: RadioType,
67 /// Cell id: NR NCI (36 bits), LTE ECI (28), UMTS CID (28) or GSM CID (16).
68 pub cell_id: u64,
69 /// LTE/NR TAC or GSM/UMTS LAC.
70 pub area: u32,
71}
72
73/// Parse `"aa:bb:cc:dd:ee:ff"` to a 48-bit key, big-endian (OUI in the high bits).
74pub fn parse_mac(bssid: &str) -> Option<u64> {
75 let mut v = 0u64;
76 let mut groups = 0;
77 for part in bssid.split(':') {
78 if part.len() != 2 {
79 return None;
80 }
81 let b = u8::from_str_radix(part, 16).ok()?;
82 v = (v << 8) | b as u64;
83 groups += 1;
84 }
85 (groups == 6).then_some(v)
86}
87
88/// Whether `mac` is locally administered or multicast.
89///
90/// Randomized client addresses, virtual interfaces and multicast addresses are not stable
91/// identifiers for a place: the same address turns up somewhere else tomorrow. An entry for
92/// one is worse than no entry, so the builder drops them and the client skips probing them.
93pub fn is_randomized_mac(mac: u64) -> bool {
94 ((mac >> 40) & 0x03) != 0
95}
96
97/// Full 128-bit store key for a WiFi AP.
98pub fn wifi_key(mac: u64) -> u128 {
99 mac as u128
100}
101
102/// Full 128-bit store key for a cell tower.
103pub fn cell_key(id: &CellId) -> u128 {
104 let hi = ((id.mcc as u64 & 0x3FF) << 10) | (id.mnc as u64 & 0x3FF);
105 let lo = ((id.radio as u64 & 0xF) << (CID_BITS + AREA_BITS))
106 | ((id.area as u64 & AREA_MASK) << CID_BITS)
107 | (id.cell_id & CID_MASK);
108 ((hi as u128) << 64) | lo as u128
109}
110
111/// Whether `id` survives packing unchanged. A tower whose identity does not fit the key
112/// layout would be stored under a truncated key that a different tower also maps to, so it is
113/// dropped rather than aliased.
114pub fn cell_fits(id: &CellId) -> bool {
115 id.mcc <= 999
116 && id.mnc <= 999
117 && (id.area as u64) <= AREA_MASK
118 && id.cell_id <= CID_MASK
119 && id.cell_id > 0
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125
126 // These expectations are transcribed from `BeaconKeysTest.kt`. Change them here only
127 // together with that file.
128
129 #[test]
130 fn mac_parses_big_endian_with_the_oui_in_the_high_bits() {
131 assert_eq!(parse_mac("00:11:22:33:44:55"), Some(0x001122334455));
132 assert_eq!(parse_mac("aa:bb:cc:dd:ee:ff"), Some(0xAABBCCDDEEFF));
133 assert_eq!(parse_mac("AA:BB:CC:DD:EE:FF"), Some(0xAABBCCDDEEFF));
134 assert_eq!(parse_mac("00:00:00:00:00:00"), Some(0));
135 assert_eq!(parse_mac("ff:ff:ff:ff:ff:ff"), Some(0xFFFFFFFFFFFF));
136 }
137
138 #[test]
139 fn malformed_macs_are_rejected() {
140 for bad in [
141 "",
142 "00:11:22:33:44",
143 "00:11:22:33:44:55:66",
144 "00-11-22-33-44-55",
145 "zz:11:22:33:44:55",
146 "0:11:22:33:44:55",
147 "-1:11:22:33:44:55",
148 ] {
149 assert_eq!(parse_mac(bad), None, "{bad:?} must not parse");
150 }
151 }
152
153 #[test]
154 fn locally_administered_and_multicast_macs_are_excluded() {
155 assert!(is_randomized_mac(0xAABBCCDDEEFF));
156 assert!(is_randomized_mac(0x020000000000));
157 assert!(is_randomized_mac(0x010000000000));
158 assert!(!is_randomized_mac(0x001122334455));
159 assert!(!is_randomized_mac(0xFCFBFB000000));
160 assert!(!is_randomized_mac(0x00FFFFFFFFFF));
161 }
162
163 #[test]
164 fn cell_key_layout_is_mcc10_mnc10_radio4_area24_cid36() {
165 let id =
166 CellId { mcc: 310, mnc: 260, radio: RadioType::Lte, cell_id: 0xABCDEF123, area: 12345 };
167 let key = cell_key(&id);
168 assert_eq!((key >> 64) as u64, 0x4D904);
169 assert_eq!(key as u64, 0x3003039ABCDEF123);
170 }
171
172 #[test]
173 fn radio_type_discriminates_otherwise_identical_cells() {
174 let base = CellId { mcc: 234, mnc: 15, radio: RadioType::Gsm, cell_id: 4242, area: 999 };
175 let mut keys: Vec<u128> = [RadioType::Gsm, RadioType::Umts, RadioType::Lte, RadioType::Nr]
176 .iter()
177 .map(|&r| cell_key(&CellId { radio: r, ..base }))
178 .collect();
179 keys.sort_unstable();
180 keys.dedup();
181 assert_eq!(keys.len(), 4, "each radio type must produce its own key");
182 }
183
184 #[test]
185 fn full_36_bit_nci_survives_packing() {
186 let id = CellId { mcc: 1, mnc: 1, radio: RadioType::Nr, cell_id: 0xFFFFFFFFF, area: 0 };
187 assert_eq!(cell_key(&id) as u64 & 0xFFFFFFFFF, 0xFFFFFFFFF);
188 let truncated = CellId { cell_id: 0x0FFFFFFF, ..id };
189 assert_ne!(cell_key(&id), cell_key(&truncated));
190 }
191
192 #[test]
193 fn wide_5g_tac_survives_packing() {
194 let id = CellId { mcc: 505, mnc: 1, radio: RadioType::Nr, cell_id: 1, area: 0xFFFFFF };
195 assert_eq!((cell_key(&id) as u64 >> 36) & 0xFFFFFF, 0xFFFFFF);
196 }
197
198 #[test]
199 fn keys_stay_inside_their_declared_universe() {
200 let widest = CellId {
201 mcc: 999,
202 mnc: 999,
203 radio: RadioType::Nr,
204 cell_id: 0xFFFFFFFFF,
205 area: 0xFFFFFF,
206 };
207 assert!(cell_key(&widest) < (1u128 << CELL_UNIVERSE_BITS));
208 assert!(wifi_key(0xFFFFFFFFFFFF) < (1u128 << WIFI_UNIVERSE_BITS));
209 }
210
211 #[test]
212 fn identities_that_do_not_fit_are_rejected_not_truncated() {
213 let ok = CellId { mcc: 310, mnc: 260, radio: RadioType::Lte, cell_id: 42, area: 7 };
214 assert!(cell_fits(&ok));
215 assert!(!cell_fits(&CellId { mcc: 1000, ..ok }));
216 assert!(!cell_fits(&CellId { mnc: 1000, ..ok }));
217 assert!(!cell_fits(&CellId { area: 0x1000000, ..ok }));
218 assert!(!cell_fits(&CellId { cell_id: 1 << 36, ..ok }));
219 assert!(!cell_fits(&CellId { cell_id: 0, ..ok }));
220 }
221
222 #[test]
223 fn radio_parse_covers_the_dataset_spellings() {
224 assert_eq!(RadioType::parse("GSM"), Some(RadioType::Gsm));
225 assert_eq!(RadioType::parse("umts"), Some(RadioType::Umts));
226 assert_eq!(RadioType::parse("LTE"), Some(RadioType::Lte));
227 assert_eq!(RadioType::parse("NR"), Some(RadioType::Nr));
228 // CDMA has no MCC/MNC/LAC/CID identity of this shape and is not carried.
229 assert_eq!(RadioType::parse("CDMA"), None);
230 assert_eq!(RadioType::parse("banana"), None);
231 }
232}