1use crate::protobuf::{self as p, Field, Value};
9use anyhow::{bail, ensure, Result};
10
11pub const MAX_SIGNALING_BYTES: usize = 1024 * 1024;
13const MAX_FIELDS: usize = 1024;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum CallOperation {
18 Create,
19 Join,
20 Acknowledge,
21 Reject,
22 Cancel,
23 Exit,
24 SwitchAv,
25}
26
27impl CallOperation {
28 pub const fn command_id(self) -> u32 {
29 match self {
30 Self::Create => 3066,
31 Self::Join => 3361,
32 Self::Acknowledge => 3007,
33 Self::Reject => 3095,
34 Self::Cancel => 3310,
35 Self::Exit => 3380,
36 Self::SwitchAv => 3197,
37 }
38 }
39
40 pub const fn path(self) -> &'static str {
41 match self {
42 Self::Create => "/cloudim/cloud-bin/cloudvoipmtcreate",
43 Self::Join => "/cloudim/cloud-bin/cloudvoipmtjoin",
44 Self::Acknowledge => "/cloudim/cloud-bin/cloudvoipmtack",
45 Self::Reject => "/cloudim/cloud-bin/cloudvoipmtreject",
46 Self::Cancel => "/cloudim/cloud-bin/cloudvoipmtcancel",
47 Self::Exit => "/cloudim/cloud-bin/cloudvoipmtexit",
48 Self::SwitchAv => "/cloudim/cloud-bin/cloudvoipmtswitchav",
49 }
50 }
51
52 pub fn from_parts(command_id: u32, path: &str) -> Result<Self> {
53 for operation in [
54 Self::Create,
55 Self::Join,
56 Self::Acknowledge,
57 Self::Reject,
58 Self::Cancel,
59 Self::Exit,
60 Self::SwitchAv,
61 ] {
62 if command_id == operation.command_id() && path == operation.path() {
63 return Ok(operation);
64 }
65 }
66 bail!("Unsupported call command/path pair")
67 }
68}
69
70#[derive(Default)]
76pub struct CloudRequest {
77 pub task_id: Option<u32>,
78 pub body: Option<Vec<u8>>,
79 pub command_id: Option<u32>,
80 pub path: Option<String>,
81 pub longpolling: Option<bool>,
82 pub longpolling_timeout: Option<u32>,
84 pub unknown_fields: Vec<Field>,
85}
86
87impl CloudRequest {
88 pub fn for_operation(task_id: u32, operation: CallOperation, body: Vec<u8>) -> Self {
89 Self {
90 task_id: Some(task_id),
91 body: Some(body),
92 command_id: Some(operation.command_id()),
93 path: Some(operation.path().to_owned()),
94 ..Self::default()
95 }
96 }
97
98 pub fn operation(&self) -> Result<CallOperation> {
101 CallOperation::from_parts(
102 self.command_id
103 .ok_or_else(|| anyhow::anyhow!("Missing call command"))?,
104 self.path
105 .as_deref()
106 .ok_or_else(|| anyhow::anyhow!("Missing call path"))?,
107 )
108 }
109
110 pub fn encode(&self) -> Result<Vec<u8>> {
111 self.validate()?;
112 let mut fields = Vec::new();
113 append_u32(&mut fields, 1, self.task_id);
114 append_data(&mut fields, 2, self.body.as_deref());
115 append_u32(&mut fields, 3, self.command_id);
116 append_data(&mut fields, 4, self.path.as_deref().map(str::as_bytes));
117 append_u32(&mut fields, 5, self.longpolling.map(u32::from));
118 append_u32(&mut fields, 6, self.longpolling_timeout);
119 finish(fields, &self.unknown_fields, 6)
120 }
121
122 pub fn decode(input: &[u8]) -> Result<Self> {
123 let fields = decode_fields(input)?;
124 let value = Self {
125 task_id: optional_u32(&fields, 1)?,
126 body: p::optional_data(&fields, 2)?.map(Vec::from),
127 command_id: optional_u32(&fields, 3)?,
128 path: p::optional_data(&fields, 4)?
129 .map(|value| String::from_utf8(value.to_vec()))
130 .transpose()?,
131 longpolling: match optional_u32(&fields, 5)? {
132 None => None,
133 Some(0) => Some(false),
134 Some(1) => Some(true),
135 _ => bail!("Invalid call boolean"),
136 },
137 longpolling_timeout: optional_u32(&fields, 6)?,
138 unknown_fields: unknown_fields(fields, 6),
139 };
140 value.validate()?;
141 Ok(value)
142 }
143
144 fn validate(&self) -> Result<()> {
145 if let Some(body) = &self.body {
146 ensure!(body.len() <= MAX_SIGNALING_BYTES, "Call body too large");
147 }
148 if let Some(path) = &self.path {
149 ensure!(
150 path.len() <= 128 && !path.contains('\0'),
151 "Invalid call path"
152 );
153 }
154 if let (Some(command), Some(path)) = (self.command_id, self.path.as_deref()) {
155 CallOperation::from_parts(command, path)?;
156 }
157 Ok(())
158 }
159}
160
161#[derive(Default)]
165pub struct CommonRequest {
166 pub base_request: Option<Vec<u8>>,
167 pub body: Option<Vec<u8>>,
168 pub unknown_fields: Vec<Field>,
169}
170
171impl CommonRequest {
172 pub fn encode(&self) -> Result<Vec<u8>> {
173 if let Some(base) = &self.base_request {
174 validate_base_request(base)?;
175 }
176 encode_common(
177 self.base_request.as_deref(),
178 self.body.as_deref(),
179 &self.unknown_fields,
180 )
181 }
182
183 pub fn decode(input: &[u8]) -> Result<Self> {
184 let (base_request, body, unknown_fields) = decode_common(input)?;
185 if let Some(base) = &base_request {
186 validate_base_request(base)?;
187 }
188 Ok(Self {
189 base_request,
190 body,
191 unknown_fields,
192 })
193 }
194}
195
196#[derive(Default)]
199pub struct CommonResponse {
200 pub base_response: Option<Vec<u8>>,
201 pub body: Option<Vec<u8>>,
202 pub unknown_fields: Vec<Field>,
203}
204
205impl CommonResponse {
206 pub fn encode(&self) -> Result<Vec<u8>> {
207 if let Some(base) = &self.base_response {
208 validate_base_response(base)?;
209 }
210 encode_common(
211 self.base_response.as_deref(),
212 self.body.as_deref(),
213 &self.unknown_fields,
214 )
215 }
216
217 pub fn decode(input: &[u8]) -> Result<Self> {
218 let (base_response, body, unknown_fields) = decode_common(input)?;
219 if let Some(base) = &base_response {
220 validate_base_response(base)?;
221 }
222 Ok(Self {
223 base_response,
224 body,
225 unknown_fields,
226 })
227 }
228
229 pub fn return_code(&self) -> Result<i32> {
231 let base = self
232 .base_response
233 .as_deref()
234 .ok_or_else(|| anyhow::anyhow!("Missing call base response"))?;
235 optional_i32(&decode_fields(base)?, 1)?
236 .ok_or_else(|| anyhow::anyhow!("Missing call return code"))
237 }
238}
239
240fn validate_base_request(input: &[u8]) -> Result<()> {
241 let fields = decode_fields(input)?;
242 p::optional_data(&fields, 1)?;
243 optional_u32(&fields, 2)?;
244 p::optional_data(&fields, 3)?;
245 optional_i32(&fields, 4)?;
246 p::optional_data(&fields, 5)?;
247 optional_u32(&fields, 6)?;
248 Ok(())
249}
250
251fn validate_base_response(input: &[u8]) -> Result<()> {
252 let fields = decode_fields(input)?;
253 optional_i32(&fields, 1)?;
254 if let Some(message) = p::optional_data(&fields, 2)? {
255 let message = decode_fields(message)?;
256 if let Some(text) = p::optional_data(&message, 1)? {
257 std::str::from_utf8(text)?;
258 }
259 }
260 Ok(())
261}
262
263pub fn decode_fields(input: &[u8]) -> Result<Vec<Field>> {
265 ensure!(
266 input.len() <= MAX_SIGNALING_BYTES,
267 "Call envelope too large"
268 );
269 let fields = p::decode(input)?;
270 ensure!(fields.len() <= MAX_FIELDS, "Too many call fields");
271 Ok(fields)
272}
273
274pub(super) fn optional_u32(fields: &[Field], number: u32) -> Result<Option<u32>> {
275 match p::optional(fields, number)? {
276 None => Ok(None),
277 Some(Value::Varint(value)) => Ok(Some(u32::try_from(*value)?)),
278 _ => bail!("Invalid call scalar field {number}"),
279 }
280}
281
282fn optional_i32(fields: &[Field], number: u32) -> Result<Option<i32>> {
283 match p::optional(fields, number)? {
284 None => Ok(None),
285 Some(Value::Varint(value)) => Ok(Some(i32::try_from(*value as i64)?)),
286 _ => bail!("Invalid call signed scalar field {number}"),
287 }
288}
289
290pub(super) fn unknown_fields(fields: Vec<Field>, last_known: u32) -> Vec<Field> {
291 fields
292 .into_iter()
293 .filter(|field| field.number > last_known)
294 .collect()
295}
296
297fn append_u32(output: &mut Vec<Vec<u8>>, number: u32, value: Option<u32>) {
298 if let Some(value) = value {
299 output.push(p::uint(number, u64::from(value)));
300 }
301}
302
303fn append_data(output: &mut Vec<Vec<u8>>, number: u32, value: Option<&[u8]>) {
304 if let Some(value) = value {
305 output.push(p::bytes(number, value));
306 }
307}
308
309fn finish(mut fields: Vec<Vec<u8>>, unknown: &[Field], last_known: u32) -> Result<Vec<u8>> {
310 ensure!(
311 fields.len() + unknown.len() <= MAX_FIELDS,
312 "Too many call fields"
313 );
314 let mut total = fields.iter().try_fold(0usize, |total, field| {
315 total
316 .checked_add(field.len())
317 .ok_or_else(|| anyhow::anyhow!("Call length overflow"))
318 })?;
319 ensure!(total <= MAX_SIGNALING_BYTES, "Call envelope too large");
320 for field in unknown {
321 ensure!(
322 field.number > last_known && field.number < 1 << 29,
323 "Unknown call field collides with a known or invalid field"
324 );
325 let wire = match &field.value {
326 Value::Varint(_) => 0,
327 Value::Fixed64(_) => 1,
328 Value::Bytes(_) => 2,
329 Value::Fixed32(_) => 5,
330 };
331 let mut encoded = p::varint(u64::from(field.number) * 8 + wire);
332 let value_len = match &field.value {
333 Value::Varint(value) => p::varint(*value).len(),
334 Value::Fixed64(_) => 8,
335 Value::Fixed32(_) => 4,
336 Value::Bytes(value) => {
337 ensure!(value.len() <= MAX_SIGNALING_BYTES, "Call field too large");
338 p::varint(value.len() as u64).len() + value.len()
339 }
340 };
341 total = total
342 .checked_add(encoded.len() + value_len)
343 .ok_or_else(|| anyhow::anyhow!("Call length overflow"))?;
344 ensure!(total <= MAX_SIGNALING_BYTES, "Call envelope too large");
345 match &field.value {
346 Value::Varint(value) => encoded.extend(p::varint(*value)),
347 Value::Fixed64(value) => encoded.extend(value),
348 Value::Fixed32(value) => encoded.extend(value),
349 Value::Bytes(value) => {
350 encoded.extend(p::varint(value.len() as u64));
351 encoded.extend(value);
352 }
353 }
354 fields.push(encoded);
355 }
356 p::message(&fields)
357}
358
359fn encode_common(base: Option<&[u8]>, body: Option<&[u8]>, unknown: &[Field]) -> Result<Vec<u8>> {
360 if let Some(body) = body {
361 ensure!(body.len() <= MAX_SIGNALING_BYTES, "Call body too large");
362 }
363 let mut fields = Vec::new();
364 append_data(&mut fields, 1, base);
365 append_data(&mut fields, 2, body);
366 finish(fields, unknown, 2)
367}
368
369type CommonParts = (Option<Vec<u8>>, Option<Vec<u8>>, Vec<Field>);
370fn decode_common(input: &[u8]) -> Result<CommonParts> {
371 let fields = decode_fields(input)?;
372 let base = p::optional_data(&fields, 1)?.map(Vec::from);
373 let body = p::optional_data(&fields, 2)?.map(Vec::from);
374 Ok((base, body, unknown_fields(fields, 2)))
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 #[test]
382 fn callback_has_independent_wire_vector() {
383 let expected = hex::decode(concat!(
385 "08071202080118fa172224",
386 "2f636c6f7564696d2f636c6f75642d62696e2f636c6f7564766f69706d74637265617465",
387 "280030e0d403"
388 ))
389 .unwrap();
390 let request = CloudRequest {
391 longpolling: Some(false),
392 longpolling_timeout: Some(60_000),
393 ..CloudRequest::for_operation(7, CallOperation::Create, vec![8, 1])
394 };
395 assert_eq!(request.encode().unwrap(), expected);
396 let decoded = CloudRequest::decode(&expected).unwrap();
397 assert_eq!(decoded.task_id, Some(7));
398 assert_eq!(decoded.body.as_deref(), Some([8, 1].as_slice()));
399 assert_eq!(decoded.operation().unwrap(), CallOperation::Create);
400 assert_eq!(decoded.longpolling, Some(false));
401 assert_eq!(decoded.longpolling_timeout, Some(60_000));
402 }
403
404 #[test]
405 fn nested_bases_and_duplicate_bodies_are_checked() {
406 for input in [
407 vec![8, 0],
408 vec![10, 0, 10, 0],
409 vec![18, 0, 18, 0],
410 vec![10, 2, 8, 0],
411 vec![10, 2, 18, 0],
412 ] {
413 assert!(CommonRequest::decode(&input).is_err());
414 }
415 for input in [
416 vec![10, 2, 10, 0],
417 vec![10, 2, 16, 0],
418 vec![10, 4, 8, 0, 8, 0],
419 vec![10, 4, 18, 2, 8, 0],
420 ] {
421 assert!(CommonResponse::decode(&input).is_err());
422 }
423 }
424}