Skip to content
File

Blob: firmware/vendor/sctp-proto/src/param/param_requested_hmac_algorithm.rs

rust114 lines
1use super::{param_header::*, param_type::*, *};
2 
3use alloc::string::{String, ToString};
4use alloc::vec::Vec;
5use bytes::BufMut;
6 
7#[derive(Debug, Copy, Clone, PartialEq)]
8#[repr(C)]
9pub(crate) enum HmacAlgorithm {
10 HmacResv1 = 0,
11 HmacSha128 = 1,
12 HmacResv2 = 2,
13 HmacSha256 = 3,
14 Unknown,
15}
16 
17impl fmt::Display for HmacAlgorithm {
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 let s = match *self {
20 HmacAlgorithm::HmacResv1 => "HMAC Reserved (0x00)",
21 HmacAlgorithm::HmacSha128 => "HMAC SHA-128",
22 HmacAlgorithm::HmacResv2 => "HMAC Reserved (0x02)",
23 HmacAlgorithm::HmacSha256 => "HMAC SHA-256",
24 _ => "Unknown HMAC Algorithm",
25 };
26 write!(f, "{}", s)
27 }
28}
29 
30impl From<u16> for HmacAlgorithm {
31 fn from(v: u16) -> HmacAlgorithm {
32 match v {
33 0 => HmacAlgorithm::HmacResv1,
34 1 => HmacAlgorithm::HmacSha128,
35 2 => HmacAlgorithm::HmacResv2,
36 3 => HmacAlgorithm::HmacSha256,
37 _ => HmacAlgorithm::Unknown,
38 }
39 }
40}
41 
42#[derive(Default, Debug, Clone, PartialEq)]
43pub(crate) struct ParamRequestedHmacAlgorithm {
44 pub(crate) available_algorithms: Vec<HmacAlgorithm>,
45}
46 
47impl fmt::Display for ParamRequestedHmacAlgorithm {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(
50 f,
51 "{} {}",
52 self.header(),
53 self.available_algorithms
54 .iter()
55 .map(|ct| ct.to_string())
56 .collect::<Vec<String>>()
57 .join(" "),
58 )
59 }
60}
61 
62impl Param for ParamRequestedHmacAlgorithm {
63 fn header(&self) -> ParamHeader {
64 ParamHeader {
65 typ: ParamType::ReqHmacAlgo,
66 value_length: self.value_length() as u16,
67 }
68 }
69 
70 fn unmarshal(raw: &Bytes) -> Result<Self> {
71 let header = ParamHeader::unmarshal(raw)?;
72 
73 let reader =
74 &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length());
75 
76 let mut available_algorithms = vec![];
77 let mut offset = 0;
78 while offset + 1 < header.value_length() {
79 let a: HmacAlgorithm = reader.get_u16().into();
80 if a == HmacAlgorithm::HmacSha128 || a == HmacAlgorithm::HmacSha256 {
81 available_algorithms.push(a);
82 } else {
83 return Err(Error::ErrInvalidAlgorithmType);
84 }
85 
86 offset += 2;
87 }
88 
89 Ok(ParamRequestedHmacAlgorithm {
90 available_algorithms,
91 })
92 }
93 
94 fn marshal_to(&self, buf: &mut BytesMut) -> Result<usize> {
95 self.header().marshal_to(buf)?;
96 for a in &self.available_algorithms {
97 buf.put_u16(*a as u16);
98 }
99 Ok(buf.len())
100 }
101 
102 fn value_length(&self) -> usize {
103 2 * self.available_algorithms.len()
104 }
105 
106 fn clone_to(&self) -> Box<dyn Param + Send + Sync> {
107 Box::new(self.clone())
108 }
109 
110 fn as_any(&self) -> &(dyn Any + Send + Sync) {
111 self
112 }
113}