Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / proto.rs
proto.rs200 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. |
| 13 | pub const WIRE_VARINT: u8 = 0; |
| 14 | /// Wire type 2. |
| 15 | pub const WIRE_LEN: u8 = 2; |
| 16 | |
| 17 | /// Append a base-128 varint. |
| 18 | pub 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). |
| 31 | pub 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. |
| 36 | pub 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. |
| 42 | pub 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)] |
| 50 | pub 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. |
| 60 | pub struct Reader<'a> { |
| 61 | buf: &'a [u8], |
| 62 | pos: usize, |
| 63 | } |
| 64 | |
| 65 | impl<'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 | /// Next `(field number, value)`, or `None` at the end of the message or on malformed |
| 92 | /// input. The two are not distinguished: a truncated response and a complete one are |
| 93 | /// handled the same way, by using whatever was decoded before the cut. |
| 94 | pub fn next(&mut self) -> Option<(u32, Field<'a>)> { |
| 95 | if self.pos >= self.buf.len() { |
| 96 | return None; |
| 97 | } |
| 98 | let tag = self.varint()?; |
| 99 | let field = (tag >> 3) as u32; |
| 100 | match (tag & 7) as u8 { |
| 101 | 0 => Some((field, Field::Varint(self.varint()?))), |
| 102 | 1 => { |
| 103 | let end = self.pos.checked_add(8)?; |
| 104 | let s = self.buf.get(self.pos..end)?; |
| 105 | self.pos = end; |
| 106 | let mut a = [0u8; 8]; |
| 107 | a.copy_from_slice(s); |
| 108 | Some((field, Field::Fixed(u64::from_le_bytes(a)))) |
| 109 | } |
| 110 | 2 => { |
| 111 | let len = self.varint()? as usize; |
| 112 | let end = self.pos.checked_add(len)?; |
| 113 | let s = self.buf.get(self.pos..end)?; |
| 114 | self.pos = end; |
| 115 | Some((field, Field::Bytes(s))) |
| 116 | } |
| 117 | 5 => { |
| 118 | let end = self.pos.checked_add(4)?; |
| 119 | let s = self.buf.get(self.pos..end)?; |
| 120 | self.pos = end; |
| 121 | let mut a = [0u8; 4]; |
| 122 | a.copy_from_slice(s); |
| 123 | Some((field, Field::Fixed(u32::from_le_bytes(a) as u64))) |
| 124 | } |
| 125 | _ => None, |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | #[cfg(test)] |
| 131 | mod tests { |
| 132 | use super::*; |
| 133 | |
| 134 | #[test] |
| 135 | fn varints_round_trip_including_the_ten_byte_negative_form() { |
| 136 | for v in [0i64, 1, 127, 128, 300, -1, -2, i64::MIN, i64::MAX] { |
| 137 | let mut out = Vec::new(); |
| 138 | put_int(&mut out, 3, v); |
| 139 | let mut r = Reader::new(&out); |
| 140 | match r.next() { |
| 141 | Some((3, Field::Varint(raw))) => assert_eq!(raw as i64, v, "{v}"), |
| 142 | other => panic!("unexpected {other:?} for {v}"), |
| 143 | } |
| 144 | assert!(r.next().is_none()); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | #[test] |
| 149 | fn negative_ints_use_the_full_ten_bytes() { |
| 150 | let mut out = Vec::new(); |
| 151 | put_int(&mut out, 1, -1); |
| 152 | // one tag byte + ten payload bytes |
| 153 | assert_eq!(out.len(), 11); |
| 154 | } |
| 155 | |
| 156 | #[test] |
| 157 | fn nested_messages_and_strings_round_trip() { |
| 158 | let mut inner = Vec::new(); |
| 159 | put_bytes(&mut inner, 1, b"aa:bb:cc:dd:ee:ff"); |
| 160 | let mut outer = Vec::new(); |
| 161 | put_bytes(&mut outer, 2, &inner); |
| 162 | put_int(&mut outer, 3, 100); |
| 163 | |
| 164 | let mut r = Reader::new(&outer); |
| 165 | let (f, v) = r.next().unwrap(); |
| 166 | assert_eq!(f, 2); |
| 167 | let Field::Bytes(body) = v else { panic!("expected a nested message") }; |
| 168 | let mut ir = Reader::new(body); |
| 169 | let (bf, bv) = ir.next().unwrap(); |
| 170 | assert_eq!(bf, 1); |
| 171 | let Field::Bytes(s) = bv else { panic!("expected a string") }; |
| 172 | assert_eq!(s, b"aa:bb:cc:dd:ee:ff"); |
| 173 | |
| 174 | assert!(matches!(r.next(), Some((3, Field::Varint(100))))); |
| 175 | assert!(r.next().is_none()); |
| 176 | } |
| 177 | |
| 178 | #[test] |
| 179 | fn unknown_wire_types_and_fields_are_skipped_not_fatal() { |
| 180 | let mut out = Vec::new(); |
| 181 | put_tag(&mut out, 9, 5); // fixed32, a field this schema never sends |
| 182 | out.extend_from_slice(&7u32.to_le_bytes()); |
| 183 | put_int(&mut out, 3, 42); |
| 184 | |
| 185 | let mut r = Reader::new(&out); |
| 186 | assert!(matches!(r.next(), Some((9, Field::Fixed(7))))); |
| 187 | assert!(matches!(r.next(), Some((3, Field::Varint(42))))); |
| 188 | } |
| 189 | |
| 190 | #[test] |
| 191 | fn a_truncated_message_stops_rather_than_panicking() { |
| 192 | let mut out = Vec::new(); |
| 193 | put_bytes(&mut out, 2, &[1, 2, 3, 4, 5, 6]); |
| 194 | for cut in 1..out.len() { |
| 195 | let mut r = Reader::new(&out[..cut]); |
| 196 | // Must terminate and must not index out of bounds. |
| 197 | while r.next().is_some() {} |
| 198 | } |
| 199 | } |
| 200 | } |