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

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

proto.rs204 lines · 6.5 KiBRaw
1//! The slice of protobuf the gs-loc protocol uses, hand-rolled.
2//!
3//! Four message types with a dozen scalar fields between them does not justify a codegen
4//! dependency, and the same reasoning produced `proto.rs` in `scripts/maps/osm_ingest`. The
5//! schema this implements is `reference/apple_wps.proto`.
6//!
7//! Only what the protocol needs: varints, length-delimited fields, and enough of the wire
8//! format to skip everything else. Signed fields are plain `int32`/`int64`, not zigzag, so a
9//! negative value arrives as a ten-byte varint and is reinterpreted rather than decoded
10//! specially.
11
12/// Wire type 0.
13pub const WIRE_VARINT: u8 = 0;
14/// Wire type 2.
15pub const WIRE_LEN: u8 = 2;
16
17/// Append a base-128 varint.
18pub fn put_varint(out: &mut Vec<u8>, mut v: u64) {
19 loop {
20 let byte = (v & 0x7F) as u8;
21 v >>= 7;
22 if v == 0 {
23 out.push(byte);
24 return;
25 }
26 out.push(byte | 0x80);
27 }
28}
29
30/// Append a tag (field number + wire type).
31pub fn put_tag(out: &mut Vec<u8>, field: u32, wire: u8) {
32 put_varint(out, ((field as u64) << 3) | wire as u64);
33}
34
35/// Append a varint field. `int32`/`int64` sign-extend to ten bytes, as proto2 requires.
36pub fn put_int(out: &mut Vec<u8>, field: u32, v: i64) {
37 put_tag(out, field, WIRE_VARINT);
38 put_varint(out, v as u64);
39}
40
41/// Append a length-delimited field.
42pub fn put_bytes(out: &mut Vec<u8>, field: u32, body: &[u8]) {
43 put_tag(out, field, WIRE_LEN);
44 put_varint(out, body.len() as u64);
45 out.extend_from_slice(body);
46}
47
48/// One field of a message, as it appears on the wire.
49#[derive(Debug, Clone, Copy)]
50pub enum Field<'a> {
51 /// Wire type 0.
52 Varint(u64),
53 /// Wire type 2: a nested message, string or byte string.
54 Bytes(&'a [u8]),
55 /// Wire types 1 and 5, which this schema does not use but must still be skipped over.
56 Fixed(u64),
57}
58
59/// Cursor over a serialized message.
60pub struct Reader<'a> {
61 buf: &'a [u8],
62 pos: usize,
63}
64
65impl<'a> Reader<'a> {
66 /// Start reading `buf`.
67 pub fn new(buf: &'a [u8]) -> Reader<'a> {
68 Reader { buf, pos: 0 }
69 }
70
71 fn varint(&mut self) -> Option<u64> {
72 let mut v = 0u64;
73 let mut shift = 0u32;
74 loop {
75 let b = *self.buf.get(self.pos)?;
76 self.pos += 1;
77 if shift < 64 {
78 v |= ((b & 0x7F) as u64) << shift;
79 }
80 if b & 0x80 == 0 {
81 return Some(v);
82 }
83 shift += 7;
84 // A varint is at most ten bytes; anything longer is corrupt, not merely large.
85 if shift > 63 && b & 0x80 != 0 && shift > 70 {
86 return None;
87 }
88 }
89 }
90}
91
92impl<'a> Iterator for Reader<'a> {
93 type Item = (u32, Field<'a>);
94
95 /// Next `(field number, value)`, or `None` at the end of the message or on malformed
96 /// input. The two are not distinguished: a truncated response and a complete one are
97 /// handled the same way, by using whatever was decoded before the cut.
98 fn next(&mut self) -> Option<Self::Item> {
99 if self.pos >= self.buf.len() {
100 return None;
101 }
102 let tag = self.varint()?;
103 let field = (tag >> 3) as u32;
104 match (tag & 7) as u8 {
105 0 => Some((field, Field::Varint(self.varint()?))),
106 1 => {
107 let end = self.pos.checked_add(8)?;
108 let s = self.buf.get(self.pos..end)?;
109 self.pos = end;
110 let mut a = [0u8; 8];
111 a.copy_from_slice(s);
112 Some((field, Field::Fixed(u64::from_le_bytes(a))))
113 }
114 2 => {
115 let len = self.varint()? as usize;
116 let end = self.pos.checked_add(len)?;
117 let s = self.buf.get(self.pos..end)?;
118 self.pos = end;
119 Some((field, Field::Bytes(s)))
120 }
121 5 => {
122 let end = self.pos.checked_add(4)?;
123 let s = self.buf.get(self.pos..end)?;
124 self.pos = end;
125 let mut a = [0u8; 4];
126 a.copy_from_slice(s);
127 Some((field, Field::Fixed(u32::from_le_bytes(a) as u64)))
128 }
129 _ => None,
130 }
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137
138 #[test]
139 fn varints_round_trip_including_the_ten_byte_negative_form() {
140 for v in [0i64, 1, 127, 128, 300, -1, -2, i64::MIN, i64::MAX] {
141 let mut out = Vec::new();
142 put_int(&mut out, 3, v);
143 let mut r = Reader::new(&out);
144 match r.next() {
145 Some((3, Field::Varint(raw))) => assert_eq!(raw as i64, v, "{v}"),
146 other => panic!("unexpected {other:?} for {v}"),
147 }
148 assert!(r.next().is_none());
149 }
150 }
151
152 #[test]
153 fn negative_ints_use_the_full_ten_bytes() {
154 let mut out = Vec::new();
155 put_int(&mut out, 1, -1);
156 // one tag byte + ten payload bytes
157 assert_eq!(out.len(), 11);
158 }
159
160 #[test]
161 fn nested_messages_and_strings_round_trip() {
162 let mut inner = Vec::new();
163 put_bytes(&mut inner, 1, b"aa:bb:cc:dd:ee:ff");
164 let mut outer = Vec::new();
165 put_bytes(&mut outer, 2, &inner);
166 put_int(&mut outer, 3, 100);
167
168 let mut r = Reader::new(&outer);
169 let (f, v) = r.next().unwrap();
170 assert_eq!(f, 2);
171 let Field::Bytes(body) = v else { panic!("expected a nested message") };
172 let mut ir = Reader::new(body);
173 let (bf, bv) = ir.next().unwrap();
174 assert_eq!(bf, 1);
175 let Field::Bytes(s) = bv else { panic!("expected a string") };
176 assert_eq!(s, b"aa:bb:cc:dd:ee:ff");
177
178 assert!(matches!(r.next(), Some((3, Field::Varint(100)))));
179 assert!(r.next().is_none());
180 }
181
182 #[test]
183 fn unknown_wire_types_and_fields_are_skipped_not_fatal() {
184 let mut out = Vec::new();
185 put_tag(&mut out, 9, 5); // fixed32, a field this schema never sends
186 out.extend_from_slice(&7u32.to_le_bytes());
187 put_int(&mut out, 3, 42);
188
189 let mut r = Reader::new(&out);
190 assert!(matches!(r.next(), Some((9, Field::Fixed(7)))));
191 assert!(matches!(r.next(), Some((3, Field::Varint(42)))));
192 }
193
194 #[test]
195 fn a_truncated_message_stops_rather_than_panicking() {
196 let mut out = Vec::new();
197 put_bytes(&mut out, 2, &[1, 2, 3, 4, 5, 6]);
198 for cut in 1..out.len() {
199 let mut r = Reader::new(&out[..cut]);
200 // Must terminate and must not index out of bounds.
201 while r.next().is_some() {}
202 }
203 }
204}