1use crate::wire::Kind;
6use std::collections::BTreeSet;
7use thiserror::Error;
8
9#[cfg(feature = "mqtt")]
10pub mod mqtt;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Role {
15 Backend,
16 LocalDevice,
17}
18
19impl Role {
20 fn peer(self) -> Self {
21 match self {
22 Self::Backend => Self::LocalDevice,
23 Self::LocalDevice => Self::Backend,
24 }
25 }
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
30pub enum Target {
31 Local,
32 Ship(String),
33 Presence,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
38pub enum RouteError {
39 #[error("base topics must be distinct, disjoint MQTT topic trees with nonempty levels")]
40 InvalidBase,
41 #[error("publication is outside the provisioned routes")]
42 Unprovisioned,
43 #[error("invalid or noncanonical SHIP identifier encoding")]
44 InvalidId,
45 #[error("MQTT topic exceeds 65535 bytes")]
46 TooLong,
47 #[error("retain is permitted and required only on the device status topic")]
48 Retain,
49 #[error("message type is invalid for this role or topic")]
50 Direction,
51}
52
53#[derive(Clone, Debug)]
55pub struct Routes {
56 to_device: String,
57 from_device: String,
58 ships: BTreeSet<String>,
59}
60
61impl Routes {
62 pub fn new(
64 to_device: impl Into<String>,
65 from_device: impl Into<String>,
66 ) -> Result<Self, RouteError> {
67 let to_device = to_device.into();
68 let from_device = from_device.into();
69 for base in [&to_device, &from_device] {
70 if base.split('/').any(str::is_empty)
71 || base.contains(['#', '+'])
72 || base.chars().any(char::is_control)
73 || base.starts_with("$share/")
74 {
75 return Err(RouteError::InvalidBase);
76 }
77 if base.len() + "/deviceStatus".len() > u16::MAX as usize {
78 return Err(RouteError::TooLong);
79 }
80 }
81 if to_device == from_device
82 || to_device.starts_with(&format!("{from_device}/"))
83 || from_device.starts_with(&format!("{to_device}/"))
84 {
85 return Err(RouteError::InvalidBase);
86 }
87 Ok(Self {
88 to_device,
89 from_device,
90 ships: BTreeSet::new(),
91 })
92 }
93
94 pub fn with_ship(mut self, id: impl Into<String>) -> Result<Self, RouteError> {
96 let id = id.into();
97 if id.is_empty() {
98 return Err(RouteError::InvalidId);
99 }
100 let budget = usize::from(u16::MAX)
101 - self.to_device.len().max(self.from_device.len())
102 - "/ship/".len();
103 if id.len() > budget
104 || id
105 .bytes()
106 .map(|b| if reserved(b) { 3 } else { 1 })
107 .sum::<usize>()
108 > budget
109 {
110 return Err(RouteError::TooLong);
111 }
112 self.ships.insert(id);
113 Ok(self)
114 }
115
116 fn base(&self, sender: Role) -> &str {
117 match sender {
118 Role::Backend => &self.to_device,
119 Role::LocalDevice => &self.from_device,
120 }
121 }
122
123 pub fn topic(&self, sender: Role, target: &Target) -> Result<String, RouteError> {
125 let base = self.base(sender);
126 match target {
127 Target::Local => Ok(base.to_owned()),
128 Target::Ship(id) if self.ships.contains(id) => {
129 Ok(format!("{base}/ship/{}", encoded(id)))
130 }
131 Target::Ship(_) => Err(RouteError::Unprovisioned),
132 Target::Presence if sender == Role::LocalDevice => Ok(format!("{base}/deviceStatus")),
133 Target::Presence => Err(RouteError::Direction),
134 }
135 }
136
137 pub fn receive(&self, receiver: Role, topic: &str, retain: bool) -> Result<Target, RouteError> {
139 if topic.len() > u16::MAX.into() {
140 return Err(RouteError::TooLong);
141 }
142 let base = self.base(receiver.peer());
143 let target = if topic == base {
144 Target::Local
145 } else {
146 let suffix = topic
147 .strip_prefix(base)
148 .and_then(|s| s.strip_prefix('/'))
149 .ok_or(RouteError::Unprovisioned)?;
150 if receiver == Role::Backend && suffix == "deviceStatus" {
151 Target::Presence
152 } else {
153 let level = suffix
154 .strip_prefix("ship/")
155 .ok_or(RouteError::Unprovisioned)?;
156 let id = decoded(level)?;
157 if !self.ships.contains(&id) {
158 return Err(RouteError::Unprovisioned);
159 }
160 Target::Ship(id)
161 }
162 };
163 if retain != (target == Target::Presence) {
164 return Err(RouteError::Retain);
165 }
166 Ok(target)
167 }
168
169 pub fn check_kind(sender: Role, target: &Target, kind: Kind) -> Result<(), RouteError> {
171 let allowed = match kind {
172 Kind::LocalDeviceStatus => sender == Role::LocalDevice && *target == Target::Presence,
173 _ if *target == Target::Presence => false,
174 Kind::Control => sender == Role::Backend,
175 Kind::State => sender == Role::LocalDevice,
176 Kind::Read | Kind::Ack => true,
177 };
178 if allowed {
179 Ok(())
180 } else {
181 Err(RouteError::Direction)
182 }
183 }
184}
185
186fn reserved(b: u8) -> bool {
187 b < 0x20 || matches!(b, 0x7f | b'#' | b'$' | b'+' | b'/' | b' ' | b'%')
188}
189
190fn encoded(id: &str) -> String {
191 const HEX: &[u8] = b"0123456789ABCDEF";
192 let mut result = String::with_capacity(id.len());
193 for c in id.chars() {
194 if c.is_ascii() && reserved(c as u8) {
195 let b = c as u8;
196 result.push('%');
197 result.push(char::from(HEX[usize::from(b >> 4)]));
198 result.push(char::from(HEX[usize::from(b & 15)]));
199 } else {
200 result.push(c);
201 }
202 }
203 result
204}
205
206fn decoded(level: &str) -> Result<String, RouteError> {
207 fn hex(b: u8) -> Result<u8, RouteError> {
208 match b {
209 b'0'..=b'9' => Ok(b - b'0'),
210 b'A'..=b'F' => Ok(b - b'A' + 10),
211 _ => Err(RouteError::InvalidId),
212 }
213 }
214 if level.is_empty() {
215 return Err(RouteError::InvalidId);
216 }
217 let mut result = Vec::with_capacity(level.len());
218 let mut bytes = level.bytes();
219 while let Some(b) = bytes.next() {
220 if b == b'%' {
221 let high = hex(bytes.next().ok_or(RouteError::InvalidId)?)?;
222 let low = hex(bytes.next().ok_or(RouteError::InvalidId)?)?;
223 let value = high << 4 | low;
224 if !reserved(value) {
225 return Err(RouteError::InvalidId);
226 }
227 result.push(value);
228 } else if reserved(b) {
229 return Err(RouteError::InvalidId);
230 } else {
231 result.push(b);
232 }
233 }
234 String::from_utf8(result).map_err(|_| RouteError::InvalidId)
235}