1 use super::*; 2 use crate::error::Error; 3 4 type Result<T> = std::result::Result<T, util::Error>; 5 6 const CHANNEL_TYPE_RELIABLE: u8 = 0x00; 7 const CHANNEL_TYPE_RELIABLE_UNORDERED: u8 = 0x80; 8 const CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT: u8 = 0x01; 9 const CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT_UNORDERED: u8 = 0x81; 10 const CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED: u8 = 0x02; 11 const CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED_UNORDERED: u8 = 0x82; 12 const CHANNEL_TYPE_LEN: usize = 1; 13 14 /// ChannelPriority 15 pub const CHANNEL_PRIORITY_BELOW_NORMAL: u16 = 128; 16 pub const CHANNEL_PRIORITY_NORMAL: u16 = 256; 17 pub const CHANNEL_PRIORITY_HIGH: u16 = 512; 18 pub const CHANNEL_PRIORITY_EXTRA_HIGH: u16 = 1024; 19 20 #[derive(Eq, PartialEq, Copy, Clone, Debug)] 21 pub enum ChannelType { 22 // `Reliable` determines the Data Channel provides a 23 // reliable in-order bi-directional communication. 24 Reliable, 25 // `ReliableUnordered` determines the Data Channel 26 // provides a reliable unordered bi-directional communication. 27 ReliableUnordered, 28 // `PartialReliableRexmit` determines the Data Channel 29 // provides a partially-reliable in-order bi-directional communication. 30 // User messages will not be retransmitted more times than specified in the Reliability Parameter. 31 PartialReliableRexmit, 32 // `PartialReliableRexmitUnordered` determines 33 // the Data Channel provides a partial reliable unordered bi-directional communication. 34 // User messages will not be retransmitted more times than specified in the Reliability Parameter. 35 PartialReliableRexmitUnordered, 36 // `PartialReliableTimed` determines the Data Channel 37 // provides a partial reliable in-order bi-directional communication. 38 // User messages might not be transmitted or retransmitted after 39 // a specified life-time given in milli- seconds in the Reliability Parameter. 40 // This life-time starts when providing the user message to the protocol stack. 41 PartialReliableTimed, 42 // The Data Channel provides a partial reliable unordered bi-directional 43 // communication. User messages might not be transmitted or retransmitted 44 // after a specified life-time given in milli- seconds in the Reliability Parameter. 45 // This life-time starts when providing the user message to the protocol stack. 46 PartialReliableTimedUnordered, 47 } 48 49 impl Default for ChannelType { default() -> Self50 fn default() -> Self { 51 Self::Reliable 52 } 53 } 54 55 impl MarshalSize for ChannelType { marshal_size(&self) -> usize56 fn marshal_size(&self) -> usize { 57 CHANNEL_TYPE_LEN 58 } 59 } 60 61 impl Marshal for ChannelType { marshal_to(&self, mut buf: &mut [u8]) -> Result<usize>62 fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> { 63 let required_len = self.marshal_size(); 64 if buf.remaining_mut() < required_len { 65 return Err(Error::UnexpectedEndOfBuffer { 66 expected: required_len, 67 actual: buf.remaining_mut(), 68 } 69 .into()); 70 } 71 72 let byte = match self { 73 Self::Reliable => CHANNEL_TYPE_RELIABLE, 74 Self::ReliableUnordered => CHANNEL_TYPE_RELIABLE_UNORDERED, 75 Self::PartialReliableRexmit => CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT, 76 Self::PartialReliableRexmitUnordered => CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT_UNORDERED, 77 Self::PartialReliableTimed => CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED, 78 Self::PartialReliableTimedUnordered => CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED_UNORDERED, 79 }; 80 81 buf.put_u8(byte); 82 83 Ok(1) 84 } 85 } 86 87 impl Unmarshal for ChannelType { unmarshal<B>(buf: &mut B) -> Result<Self> where Self: Sized, B: Buf,88 fn unmarshal<B>(buf: &mut B) -> Result<Self> 89 where 90 Self: Sized, 91 B: Buf, 92 { 93 let required_len = CHANNEL_TYPE_LEN; 94 if buf.remaining() < required_len { 95 return Err(Error::UnexpectedEndOfBuffer { 96 expected: required_len, 97 actual: buf.remaining(), 98 } 99 .into()); 100 } 101 102 let b0 = buf.get_u8(); 103 104 match b0 { 105 CHANNEL_TYPE_RELIABLE => Ok(Self::Reliable), 106 CHANNEL_TYPE_RELIABLE_UNORDERED => Ok(Self::ReliableUnordered), 107 CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT => Ok(Self::PartialReliableRexmit), 108 CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT_UNORDERED => { 109 Ok(Self::PartialReliableRexmitUnordered) 110 } 111 CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED => Ok(Self::PartialReliableTimed), 112 CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED_UNORDERED => { 113 Ok(Self::PartialReliableTimedUnordered) 114 } 115 _ => Err(Error::InvalidChannelType(b0).into()), 116 } 117 } 118 } 119 120 const CHANNEL_OPEN_HEADER_LEN: usize = 11; 121 122 /// The data-part of an data-channel OPEN message without the message type. 123 /// 124 /// # Memory layout 125 /// 126 /// ```plain 127 /// 0 1 2 3 128 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 129 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 130 /// | (Message Type)| Channel Type | Priority | 131 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 132 /// | Reliability Parameter | 133 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 134 /// | Label Length | Protocol Length | 135 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 136 /// | | 137 /// | Label | 138 /// | | 139 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 140 /// | | 141 /// | Protocol | 142 /// | | 143 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 144 /// ``` 145 #[derive(Eq, PartialEq, Clone, Debug)] 146 pub struct DataChannelOpen { 147 pub channel_type: ChannelType, 148 pub priority: u16, 149 pub reliability_parameter: u32, 150 pub label: Vec<u8>, 151 pub protocol: Vec<u8>, 152 } 153 154 impl MarshalSize for DataChannelOpen { marshal_size(&self) -> usize155 fn marshal_size(&self) -> usize { 156 let label_len = self.label.len(); 157 let protocol_len = self.protocol.len(); 158 159 CHANNEL_OPEN_HEADER_LEN + label_len + protocol_len 160 } 161 } 162 163 impl Marshal for DataChannelOpen { marshal_to(&self, mut buf: &mut [u8]) -> Result<usize>164 fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> { 165 let required_len = self.marshal_size(); 166 if buf.remaining_mut() < required_len { 167 return Err(Error::UnexpectedEndOfBuffer { 168 expected: required_len, 169 actual: buf.remaining_mut(), 170 } 171 .into()); 172 } 173 174 let n = self.channel_type.marshal_to(buf)?; 175 buf = &mut buf[n..]; 176 buf.put_u16(self.priority); 177 buf.put_u32(self.reliability_parameter); 178 buf.put_u16(self.label.len() as u16); 179 buf.put_u16(self.protocol.len() as u16); 180 buf.put_slice(self.label.as_slice()); 181 buf.put_slice(self.protocol.as_slice()); 182 Ok(self.marshal_size()) 183 } 184 } 185 186 impl Unmarshal for DataChannelOpen { unmarshal<B>(buf: &mut B) -> Result<Self> where B: Buf,187 fn unmarshal<B>(buf: &mut B) -> Result<Self> 188 where 189 B: Buf, 190 { 191 let required_len = CHANNEL_OPEN_HEADER_LEN; 192 if buf.remaining() < required_len { 193 return Err(Error::UnexpectedEndOfBuffer { 194 expected: required_len, 195 actual: buf.remaining(), 196 } 197 .into()); 198 } 199 200 let channel_type = ChannelType::unmarshal(buf)?; 201 let priority = buf.get_u16(); 202 let reliability_parameter = buf.get_u32(); 203 let label_len = buf.get_u16() as usize; 204 let protocol_len = buf.get_u16() as usize; 205 206 let required_len = label_len + protocol_len; 207 if buf.remaining() < required_len { 208 return Err(Error::UnexpectedEndOfBuffer { 209 expected: required_len, 210 actual: buf.remaining(), 211 } 212 .into()); 213 } 214 215 let mut label = vec![0; label_len]; 216 let mut protocol = vec![0; protocol_len]; 217 218 buf.copy_to_slice(&mut label[..]); 219 buf.copy_to_slice(&mut protocol[..]); 220 221 Ok(Self { 222 channel_type, 223 priority, 224 reliability_parameter, 225 label, 226 protocol, 227 }) 228 } 229 } 230 231 #[cfg(test)] 232 mod tests { 233 use super::*; 234 use bytes::{Bytes, BytesMut}; 235 236 #[test] test_channel_type_unmarshal_success() -> Result<()>237 fn test_channel_type_unmarshal_success() -> Result<()> { 238 let mut bytes = Bytes::from_static(&[0x00]); 239 let channel_type = ChannelType::unmarshal(&mut bytes)?; 240 241 assert_eq!(channel_type, ChannelType::Reliable); 242 Ok(()) 243 } 244 245 #[test] test_channel_type_unmarshal_invalid() -> Result<()>246 fn test_channel_type_unmarshal_invalid() -> Result<()> { 247 let mut bytes = Bytes::from_static(&[0x11]); 248 match ChannelType::unmarshal(&mut bytes) { 249 Ok(_) => panic!("expected Error, but got Ok"), 250 Err(err) => { 251 if let Some(&Error::InvalidChannelType(0x11)) = err.downcast_ref::<Error>() { 252 return Ok(()); 253 } 254 panic!( 255 "unexpected err {:?}, want {:?}", 256 err, 257 Error::InvalidMessageType(0x01) 258 ); 259 } 260 } 261 } 262 263 #[test] test_channel_type_unmarshal_unexpected_end_of_buffer() -> Result<()>264 fn test_channel_type_unmarshal_unexpected_end_of_buffer() -> Result<()> { 265 let mut bytes = Bytes::from_static(&[]); 266 match ChannelType::unmarshal(&mut bytes) { 267 Ok(_) => panic!("expected Error, but got Ok"), 268 Err(err) => { 269 if let Some(&Error::UnexpectedEndOfBuffer { 270 expected: 1, 271 actual: 0, 272 }) = err.downcast_ref::<Error>() 273 { 274 return Ok(()); 275 } 276 panic!( 277 "unexpected err {:?}, want {:?}", 278 err, 279 Error::InvalidMessageType(0x01) 280 ); 281 } 282 } 283 } 284 285 #[test] test_channel_type_marshal_size() -> Result<()>286 fn test_channel_type_marshal_size() -> Result<()> { 287 let channel_type = ChannelType::Reliable; 288 let marshal_size = channel_type.marshal_size(); 289 290 assert_eq!(marshal_size, 1); 291 Ok(()) 292 } 293 294 #[test] test_channel_type_marshal() -> Result<()>295 fn test_channel_type_marshal() -> Result<()> { 296 let mut buf = BytesMut::with_capacity(1); 297 buf.resize(1, 0u8); 298 let channel_type = ChannelType::Reliable; 299 let bytes_written = channel_type.marshal_to(&mut buf)?; 300 assert_eq!(bytes_written, channel_type.marshal_size()); 301 302 let bytes = buf.freeze(); 303 assert_eq!(&bytes[..], &[0x00]); 304 Ok(()) 305 } 306 307 static MARSHALED_BYTES: [u8; 24] = [ 308 0x00, // channel type 309 0x0f, 0x35, // priority 310 0x00, 0xff, 0x0f, 0x35, // reliability parameter 311 0x00, 0x05, // label length 312 0x00, 0x08, // protocol length 313 0x6c, 0x61, 0x62, 0x65, 0x6c, // label 314 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, // protocol 315 ]; 316 317 #[test] test_channel_open_unmarshal_success() -> Result<()>318 fn test_channel_open_unmarshal_success() -> Result<()> { 319 let mut bytes = Bytes::from_static(&MARSHALED_BYTES); 320 321 let channel_open = DataChannelOpen::unmarshal(&mut bytes)?; 322 323 assert_eq!(channel_open.channel_type, ChannelType::Reliable); 324 assert_eq!(channel_open.priority, 3893); 325 assert_eq!(channel_open.reliability_parameter, 16715573); 326 assert_eq!(channel_open.label, b"label"); 327 assert_eq!(channel_open.protocol, b"protocol"); 328 Ok(()) 329 } 330 331 #[test] test_channel_open_unmarshal_invalid_channel_type() -> Result<()>332 fn test_channel_open_unmarshal_invalid_channel_type() -> Result<()> { 333 let mut bytes = Bytes::from_static(&[ 334 0x11, // channel type 335 0x0f, 0x35, // priority 336 0x00, 0xff, 0x0f, 0x35, // reliability parameter 337 0x00, 0x05, // label length 338 0x00, 0x08, // protocol length 339 ]); 340 match DataChannelOpen::unmarshal(&mut bytes) { 341 Ok(_) => panic!("expected Error, but got Ok"), 342 Err(err) => { 343 if let Some(&Error::InvalidChannelType(0x11)) = err.downcast_ref::<Error>() { 344 return Ok(()); 345 } 346 panic!( 347 "unexpected err {:?}, want {:?}", 348 err, 349 Error::InvalidMessageType(0x01) 350 ); 351 } 352 } 353 } 354 355 #[test] test_channel_open_unmarshal_unexpected_end_of_buffer() -> Result<()>356 fn test_channel_open_unmarshal_unexpected_end_of_buffer() -> Result<()> { 357 let mut bytes = Bytes::from_static(&[0x00; 5]); 358 match DataChannelOpen::unmarshal(&mut bytes) { 359 Ok(_) => panic!("expected Error, but got Ok"), 360 Err(err) => { 361 if let Some(&Error::UnexpectedEndOfBuffer { 362 expected: 11, 363 actual: 5, 364 }) = err.downcast_ref::<Error>() 365 { 366 return Ok(()); 367 } 368 panic!( 369 "unexpected err {:?}, want {:?}", 370 err, 371 Error::InvalidMessageType(0x01) 372 ); 373 } 374 } 375 } 376 377 #[test] test_channel_open_unmarshal_unexpected_length_mismatch() -> Result<()>378 fn test_channel_open_unmarshal_unexpected_length_mismatch() -> Result<()> { 379 let mut bytes = Bytes::from_static(&[ 380 0x01, // channel type 381 0x00, 0x00, // priority 382 0x00, 0x00, 0x00, 0x00, // Reliability parameter 383 0x00, 0x05, // Label length 384 0x00, 0x08, // Protocol length 385 ]); 386 match DataChannelOpen::unmarshal(&mut bytes) { 387 Ok(_) => panic!("expected Error, but got Ok"), 388 Err(err) => { 389 if let Some(&Error::UnexpectedEndOfBuffer { 390 expected: 13, 391 actual: 0, 392 }) = err.downcast_ref::<Error>() 393 { 394 return Ok(()); 395 } 396 panic!( 397 "unexpected err {:?}, want {:?}", 398 err, 399 Error::InvalidMessageType(0x01) 400 ); 401 } 402 } 403 } 404 405 #[test] test_channel_open_marshal_size() -> Result<()>406 fn test_channel_open_marshal_size() -> Result<()> { 407 let channel_open = DataChannelOpen { 408 channel_type: ChannelType::Reliable, 409 priority: 3893, 410 reliability_parameter: 16715573, 411 label: b"label".to_vec(), 412 protocol: b"protocol".to_vec(), 413 }; 414 415 let marshal_size = channel_open.marshal_size(); 416 417 assert_eq!(marshal_size, 11 + 5 + 8); 418 Ok(()) 419 } 420 421 #[test] test_channel_open_marshal() -> Result<()>422 fn test_channel_open_marshal() -> Result<()> { 423 let channel_open = DataChannelOpen { 424 channel_type: ChannelType::Reliable, 425 priority: 3893, 426 reliability_parameter: 16715573, 427 label: b"label".to_vec(), 428 protocol: b"protocol".to_vec(), 429 }; 430 431 let mut buf = BytesMut::with_capacity(11 + 5 + 8); 432 buf.resize(11 + 5 + 8, 0u8); 433 let bytes_written = channel_open.marshal_to(&mut buf).unwrap(); 434 let bytes = buf.freeze(); 435 436 assert_eq!(bytes_written, channel_open.marshal_size()); 437 assert_eq!(&bytes[..], &MARSHALED_BYTES); 438 Ok(()) 439 } 440 } 441