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

Modern-Apps.git / third_party / betocore / np_adv / src / extended / mod.rs

mod.rs180 lines · 5.4 KiBRaw
1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! V1 advertisement support.
16use crate::DeLengthOutOfRange;
17use array_view::ArrayView;
18use crypto_provider::CryptoRng;
19
20pub mod data_elements;
21pub mod de_type;
22pub mod deserialize;
23pub mod salt;
24pub mod serialize;
25
26use serialize::section::header::SECTION_HEADER_MAX_LEN;
27
28// TODO make this easy to use w/ configurable arena size
29/// Maximum size of an NP advertisement, including the adv header
30pub const BLE_5_ADV_SVC_MAX_CONTENT_LEN: usize = 254
31 // length and type bytes for svc data TLV
32 - 1 - 1
33 // NP UUID
34 - 2;
35
36/// Maximum number of sections in an advertisement
37pub const NP_V1_ADV_MAX_SECTION_COUNT: usize = 8;
38
39/// Maximum size of a NP section, including its header
40pub const NP_ADV_MAX_SECTION_LEN: usize =
41 SECTION_HEADER_MAX_LEN + 1 + NP_ADV_MAX_SECTION_CONTENTS_LEN;
42
43/// Maximum hypothetical size of a NP section's contents, excluding its header.
44/// This is longer than can fit in a BLE 5 extended adv, but other media
45/// could fit it, like mDNS.
46const NP_ADV_MAX_SECTION_CONTENTS_LEN: usize = 255;
47
48/// Size of a V1 identity token
49pub const V1_IDENTITY_TOKEN_LEN: usize = 16;
50
51// 4-bit encoding ids
52/// Encoding ID for unencrypted sections with no salt
53pub const V1_ENCODING_UNENCRYPTED: EncodingType = EncodingType(0x00);
54/// Encoding ID for encrypted sections with a MIC and a short salt
55pub const V1_ENCODING_ENCRYPTED_MIC_WITH_SHORT_SALT_AND_TOKEN: EncodingType = EncodingType(0x01);
56/// Encoding ID for encrypted sections with a MIC and an extended salt
57pub const V1_ENCODING_ENCRYPTED_MIC_WITH_EXTENDED_SALT_AND_TOKEN: EncodingType = EncodingType(0x02);
58
59// The maximum de length that fits into a non-extended de header
60const MAX_NON_EXTENDED_LEN: u8 = 7;
61// The maximum type code that fits into a non-extended de header
62const MAX_NON_EXTENDED_TYPE_CODE: u32 = 15;
63
64/// The type of encoding employed for a section, which
65/// may be any 4-bit unsigned integer.
66#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
67pub struct EncodingType(pub(crate) u8);
68
69impl EncodingType {
70 /// Gets the single-byte representation of this encoding-type,
71 /// with all four high bits set to zero (reserved).
72 pub fn byte_value(&self) -> u8 {
73 self.0
74 }
75}
76
77fn de_requires_extended_bit(type_code: u32, de_len: u8) -> bool {
78 de_len > MAX_NON_EXTENDED_LEN || type_code > MAX_NON_EXTENDED_TYPE_CODE
79}
80
81/// 16-byte plaintext identity token.
82///
83/// Identity tokens are present in encrypted form in a section's header.
84#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
85pub struct V1IdentityToken([u8; V1_IDENTITY_TOKEN_LEN]);
86
87impl From<[u8; V1_IDENTITY_TOKEN_LEN]> for V1IdentityToken {
88 fn from(value: [u8; V1_IDENTITY_TOKEN_LEN]) -> Self {
89 Self(value)
90 }
91}
92
93impl V1IdentityToken {
94 /// Returns a reference to the inner byte array
95 pub fn bytes(&self) -> &[u8; V1_IDENTITY_TOKEN_LEN] {
96 &self.0
97 }
98
99 /// Returns the inner byte array
100 pub const fn into_bytes(self) -> [u8; V1_IDENTITY_TOKEN_LEN] {
101 self.0
102 }
103
104 /// Returns the token bytes as a slice
105 pub fn as_slice(&self) -> &[u8] {
106 &self.0
107 }
108}
109
110impl AsRef<[u8]> for V1IdentityToken {
111 fn as_ref(&self) -> &[u8] {
112 &self.0
113 }
114}
115
116impl crypto_provider::FromCryptoRng for V1IdentityToken {
117 fn new_random<R: CryptoRng>(rng: &mut R) -> Self {
118 Self(rng.gen())
119 }
120}
121
122/// Max V1 DE length (7 bit length field).
123pub(crate) const MAX_DE_LEN: usize = 127;
124
125/// Length of a DE's content -- must be in `[0, 127]`
126#[derive(Debug, PartialEq, Eq, Clone, Copy)]
127pub struct DeLength {
128 len: u8,
129}
130
131impl DeLength {
132 /// A convenient constant for zero length.
133 pub const ZERO: DeLength = DeLength { len: 0 };
134
135 fn as_u8(&self) -> u8 {
136 self.len
137 }
138}
139
140impl TryFrom<u8> for DeLength {
141 type Error = DeLengthOutOfRange;
142
143 fn try_from(value: u8) -> Result<Self, Self::Error> {
144 if usize::from(value) <= MAX_DE_LEN {
145 Ok(Self { len: value })
146 } else {
147 Err(DeLengthOutOfRange {})
148 }
149 }
150}
151
152impl TryFrom<usize> for DeLength {
153 type Error = DeLengthOutOfRange;
154
155 fn try_from(value: usize) -> Result<Self, Self::Error> {
156 value.try_into().map_err(|_e| DeLengthOutOfRange).and_then(|num: u8| num.try_into())
157 }
158}
159
160/// Convert a tinyvec into an equivalent ArrayView
161pub(crate) fn to_array_view<T, const N: usize>(vec: tinyvec::ArrayVec<[T; N]>) -> ArrayView<T, N>
162where
163 [T; N]: tinyvec::Array,
164{
165 let len = vec.len();
166 ArrayView::try_from_array(vec.into_inner(), len).expect("len is from original vec")
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use rand::{distributions, Rng};
173
174 // support randomly generating tokens just for tests
175 impl distributions::Distribution<V1IdentityToken> for distributions::Standard {
176 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> V1IdentityToken {
177 V1IdentityToken::from(rng.gen::<[u8; V1_IDENTITY_TOKEN_LEN]>())
178 }
179 }
180}