rvoip-rtp-core 0.1.3

RTP packet encoding/decoding, RTCP support for rvoip
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! DTLS extension types
//!
//! This module contains the extension types used in DTLS.

use bytes::{Bytes, BytesMut, Buf, BufMut};
use std::io::Cursor;

use crate::dtls::Result;

/// DTLS extension type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum ExtensionType {
    /// Server Name Indication
    ServerName = 0,
    
    /// Maximum Fragment Length
    MaxFragmentLength = 1,
    
    /// Client Certificate URL
    ClientCertificateUrl = 2,
    
    /// Trusted CA Keys
    TrustedCaKeys = 3,
    
    /// Truncated HMAC
    TruncatedHmac = 4,
    
    /// Status Request
    StatusRequest = 5,
    
    /// User Mapping
    UserMapping = 6,
    
    /// Client Authentication
    ClientAuthz = 7,
    
    /// Server Authentication
    ServerAuthz = 8,
    
    /// Cert Type
    CertType = 9,
    
    /// Supported Groups
    SupportedGroups = 10,
    
    /// EC Point Formats
    EcPointFormats = 11,
    
    /// SRP
    Srp = 12,
    
    /// Signature Algorithms
    SignatureAlgorithms = 13,
    
    /// Use SRTP (RFC 5764)
    UseSrtp = 14,
    
    /// Heartbeat
    Heartbeat = 15,
    
    /// Application Layer Protocol Negotiation
    Alpn = 16,
    
    /// Signed Certificate Timestamp
    SignedCertificateTimestamp = 18,
    
    /// Client Certificate Type
    ClientCertificateType = 19,
    
    /// Server Certificate Type
    ServerCertificateType = 20,
    
    /// Padding
    Padding = 21,
    
    /// Encrypt-then-MAC
    EncryptThenMac = 22,
    
    /// Extended Master Secret
    ExtendedMasterSecret = 23,
    
    /// Token Binding
    TokenBinding = 24,
    
    /// Cache Info
    CacheInfo = 25,
    
    /// Renegotiation Info
    RenegotiationInfo = 0xff01,
    
    /// Unknown extension type
    Unknown(u16),
}

impl From<u16> for ExtensionType {
    fn from(value: u16) -> Self {
        match value {
            0 => ExtensionType::ServerName,
            1 => ExtensionType::MaxFragmentLength,
            2 => ExtensionType::ClientCertificateUrl,
            3 => ExtensionType::TrustedCaKeys,
            4 => ExtensionType::TruncatedHmac,
            5 => ExtensionType::StatusRequest,
            6 => ExtensionType::UserMapping,
            7 => ExtensionType::ClientAuthz,
            8 => ExtensionType::ServerAuthz,
            9 => ExtensionType::CertType,
            10 => ExtensionType::SupportedGroups,
            11 => ExtensionType::EcPointFormats,
            12 => ExtensionType::Srp,
            13 => ExtensionType::SignatureAlgorithms,
            14 => ExtensionType::UseSrtp,
            15 => ExtensionType::Heartbeat,
            16 => ExtensionType::Alpn,
            18 => ExtensionType::SignedCertificateTimestamp,
            19 => ExtensionType::ClientCertificateType,
            20 => ExtensionType::ServerCertificateType,
            21 => ExtensionType::Padding,
            22 => ExtensionType::EncryptThenMac,
            23 => ExtensionType::ExtendedMasterSecret,
            24 => ExtensionType::TokenBinding,
            25 => ExtensionType::CacheInfo,
            0xff01 => ExtensionType::RenegotiationInfo,
            _ => ExtensionType::Unknown(value),
        }
    }
}

impl From<ExtensionType> for u16 {
    fn from(value: ExtensionType) -> Self {
        match value {
            ExtensionType::ServerName => 0,
            ExtensionType::MaxFragmentLength => 1,
            ExtensionType::ClientCertificateUrl => 2,
            ExtensionType::TrustedCaKeys => 3,
            ExtensionType::TruncatedHmac => 4,
            ExtensionType::StatusRequest => 5,
            ExtensionType::UserMapping => 6,
            ExtensionType::ClientAuthz => 7,
            ExtensionType::ServerAuthz => 8,
            ExtensionType::CertType => 9,
            ExtensionType::SupportedGroups => 10,
            ExtensionType::EcPointFormats => 11,
            ExtensionType::Srp => 12,
            ExtensionType::SignatureAlgorithms => 13,
            ExtensionType::UseSrtp => 14,
            ExtensionType::Heartbeat => 15,
            ExtensionType::Alpn => 16,
            ExtensionType::SignedCertificateTimestamp => 18,
            ExtensionType::ClientCertificateType => 19,
            ExtensionType::ServerCertificateType => 20,
            ExtensionType::Padding => 21,
            ExtensionType::EncryptThenMac => 22,
            ExtensionType::ExtendedMasterSecret => 23,
            ExtensionType::TokenBinding => 24,
            ExtensionType::CacheInfo => 25,
            ExtensionType::RenegotiationInfo => 0xff01,
            ExtensionType::Unknown(value) => value,
        }
    }
}

/// DTLS extension
#[derive(Debug, Clone)]
pub enum Extension {
    /// Use SRTP extension (RFC 5764)
    UseSrtp(UseSrtpExtension),
    
    /// Unknown extension
    Unknown {
        /// Extension type
        typ: u16,
        
        /// Extension data
        data: Bytes,
    },
}

impl Extension {
    /// Get the extension type
    pub fn extension_type(&self) -> ExtensionType {
        match self {
            Self::UseSrtp(_) => ExtensionType::UseSrtp,
            Self::Unknown { typ, .. } => ExtensionType::from(*typ),
        }
    }
    
    /// Serialize the extension to bytes
    pub fn serialize(&self) -> Result<Bytes> {
        let mut buf = BytesMut::new();
        
        // Extension type (2 bytes)
        let typ: u16 = self.extension_type().into();
        buf.put_u16(typ);
        
        // Extension data
        match self {
            Self::UseSrtp(ext) => {
                let data = ext.serialize()?;
                
                // Extension length (2 bytes)
                buf.put_u16(data.len() as u16);
                
                // Extension data
                buf.extend_from_slice(&data);
            }
            Self::Unknown { data, .. } => {
                // Extension length (2 bytes)
                buf.put_u16(data.len() as u16);
                
                // Extension data
                buf.extend_from_slice(data);
            }
        }
        
        Ok(buf.freeze())
    }
    
    /// Parse an extension from bytes
    pub fn parse(data: &[u8]) -> Result<(Self, usize)> {
        if data.len() < 4 {
            return Err(crate::error::Error::PacketTooShort);
        }
        
        let mut cursor = Cursor::new(data);
        
        // Extension type (2 bytes)
        let typ = cursor.get_u16();
        
        // Extension length (2 bytes)
        let length = cursor.get_u16() as usize;
        
        if data.len() < 4 + length {
            return Err(crate::error::Error::PacketTooShort);
        }
        
        let ext_data = &data[4..4 + length];
        
        let extension = match ExtensionType::from(typ) {
            ExtensionType::UseSrtp => {
                let use_srtp = UseSrtpExtension::parse(ext_data)?;
                Extension::UseSrtp(use_srtp)
            }
            _ => Extension::Unknown {
                typ,
                data: Bytes::copy_from_slice(ext_data),
            },
        };
        
        Ok((extension, 4 + length))
    }
}

/// SRTP protection profile identifiers
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum SrtpProtectionProfile {
    /// SRTP_AES128_CM_HMAC_SHA1_80 (RFC 5764)
    Aes128CmSha1_80 = 0x0001,
    
    /// SRTP_AES128_CM_HMAC_SHA1_32 (RFC 5764)
    Aes128CmSha1_32 = 0x0002,
    
    /// SRTP_AEAD_AES_128_GCM (RFC 7714)
    AeadAes128Gcm = 0x0007,
    
    /// SRTP_AEAD_AES_256_GCM (RFC 7714)
    AeadAes256Gcm = 0x0008,
    
    /// Unknown profile
    Unknown(u16),
}

impl From<u16> for SrtpProtectionProfile {
    fn from(value: u16) -> Self {
        match value {
            0x0001 => SrtpProtectionProfile::Aes128CmSha1_80,
            0x0002 => SrtpProtectionProfile::Aes128CmSha1_32,
            0x0007 => SrtpProtectionProfile::AeadAes128Gcm,
            0x0008 => SrtpProtectionProfile::AeadAes256Gcm,
            _ => SrtpProtectionProfile::Unknown(value),
        }
    }
}

impl From<SrtpProtectionProfile> for u16 {
    fn from(value: SrtpProtectionProfile) -> Self {
        match value {
            SrtpProtectionProfile::Aes128CmSha1_80 => 0x0001,
            SrtpProtectionProfile::Aes128CmSha1_32 => 0x0002,
            SrtpProtectionProfile::AeadAes128Gcm => 0x0007,
            SrtpProtectionProfile::AeadAes256Gcm => 0x0008,
            SrtpProtectionProfile::Unknown(value) => value,
        }
    }
}

/// Use SRTP extension (RFC 5764)
#[derive(Debug, Clone)]
pub struct UseSrtpExtension {
    /// SRTP protection profiles
    pub profiles: Vec<SrtpProtectionProfile>,
    
    /// MKI (Master Key Identifier) value
    pub mki: Bytes,
}

impl UseSrtpExtension {
    /// Create a new Use SRTP extension
    pub fn new(profiles: Vec<SrtpProtectionProfile>, mki: Bytes) -> Self {
        Self {
            profiles,
            mki,
        }
    }
    
    /// Create a new Use SRTP extension with no MKI
    pub fn with_profiles(profiles: Vec<SrtpProtectionProfile>) -> Self {
        Self {
            profiles,
            mki: Bytes::new(),
        }
    }
    
    /// Serialize the extension to bytes
    pub fn serialize(&self) -> Result<Bytes> {
        // Calculate profiles length (2 bytes per profile)
        let profiles_len = self.profiles.len() * 2;
        
        // Calculate total length
        let total_len = 2 + profiles_len + 1 + self.mki.len();
        
        let mut buf = BytesMut::with_capacity(total_len);
        
        // Profiles length (2 bytes)
        buf.put_u16(profiles_len as u16);
        
        // Profiles
        for profile in &self.profiles {
            buf.put_u16((*profile).into());
        }
        
        // MKI length (1 byte)
        buf.put_u8(self.mki.len() as u8);
        
        // MKI value
        if !self.mki.is_empty() {
            buf.extend_from_slice(&self.mki);
        }
        
        Ok(buf.freeze())
    }
    
    /// Parse a Use SRTP extension from bytes
    pub fn parse(data: &[u8]) -> Result<Self> {
        if data.len() < 3 {
            return Err(crate::error::Error::PacketTooShort);
        }
        
        let mut cursor = Cursor::new(data);
        
        // Profiles length (2 bytes)
        let profiles_len = cursor.get_u16() as usize;
        
        if profiles_len % 2 != 0 {
            return Err(crate::error::Error::InvalidPacket(
                "SRTP profiles length must be a multiple of 2".to_string()
            ));
        }
        
        if data.len() < 3 + profiles_len {
            return Err(crate::error::Error::PacketTooShort);
        }
        
        // Profiles
        let mut profiles = Vec::with_capacity(profiles_len / 2);
        for _ in 0..(profiles_len / 2) {
            let profile_id = cursor.get_u16();
            profiles.push(SrtpProtectionProfile::from(profile_id));
        }
        
        // MKI length (1 byte)
        let mki_len = cursor.get_u8() as usize;
        
        if data.len() < 3 + profiles_len + mki_len {
            return Err(crate::error::Error::PacketTooShort);
        }
        
        // MKI value
        let mki = if mki_len > 0 {
            let offset = 3 + profiles_len;
            Bytes::copy_from_slice(&data[offset..offset + mki_len])
        } else {
            Bytes::new()
        };
        
        Ok(Self {
            profiles,
            mki,
        })
    }
}