rvoip-rtp-core 0.2.3

RTP/RTCP protocol implementation for the rvoip stack
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Default implementation of client security context
//!
//! This module contains the DefaultClientSecurityContext struct and its implementation
//! of the ClientSecurityContext trait.

use async_trait::async_trait;
use std::any::Any;
use std::net::SocketAddr;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tracing::{debug, error};

use crate::api::client::security::{ClientSecurityConfig, ClientSecurityContext};
use crate::api::common::config::{SecurityInfo, SrtpProfile};
use crate::api::common::error::SecurityError;
use crate::api::server::security::SocketHandle;
use crate::dtls::DtlsConnection;
use crate::srtp::SrtpContext;

// Import module functions
use crate::api::client::security::dtls::{connection, handshake, transport};
use crate::api::client::security::fingerprint::verify;
use crate::api::client::security::packet::processor;

/// Default implementation of the ClientSecurityContext trait
#[derive(Clone)]
#[allow(dead_code)] // retained (liveness/Drop hold or reserved); not read
pub struct DefaultClientSecurityContext {
    /// Security configuration
    config: ClientSecurityConfig,
    /// DTLS connection for handshake
    connection: Arc<Mutex<Option<DtlsConnection>>>,
    /// SRTP context for secure media
    srtp_context: Arc<Mutex<Option<SrtpContext>>>,
    /// Remote address
    remote_addr: Arc<Mutex<Option<SocketAddr>>>,
    /// Remote fingerprint from SDP
    remote_fingerprint: Arc<Mutex<Option<String>>>,
    /// Socket for DTLS
    socket: Arc<Mutex<Option<SocketHandle>>>,
    /// Handshake completed flag
    handshake_completed: Arc<Mutex<bool>>,
    /// Remote fingerprint algorithm (if set)
    remote_fingerprint_algorithm: Arc<Mutex<Option<String>>>,
    /// Flag to indicate if handshake monitor is running
    #[allow(dead_code)] // retained (liveness/Drop hold or reserved); not read
    handshake_monitor_running: Arc<AtomicBool>,
}

impl DefaultClientSecurityContext {
    /// Create a new DefaultClientSecurityContext
    pub async fn new(config: ClientSecurityConfig) -> Result<Arc<Self>, SecurityError> {
        // Create context
        let ctx = Self {
            config,
            connection: Arc::new(Mutex::new(None)),
            srtp_context: Arc::new(Mutex::new(None)),
            remote_addr: Arc::new(Mutex::new(None)),
            remote_fingerprint: Arc::new(Mutex::new(None)),
            socket: Arc::new(Mutex::new(None)),
            handshake_completed: Arc::new(Mutex::new(false)),
            remote_fingerprint_algorithm: Arc::new(Mutex::new(None)),
            handshake_monitor_running: Arc::new(AtomicBool::new(false)),
        };

        Ok(Arc::new(ctx))
    }

    /// Initialize DTLS connection
    async fn init_connection(&self) -> Result<(), SecurityError> {
        connection::init_connection(&self.config, &self.socket, &self.connection).await
    }
}

#[async_trait]
impl ClientSecurityContext for DefaultClientSecurityContext {
    async fn initialize(&self) -> Result<(), SecurityError> {
        debug!("Initializing client security context");

        // Initialize DTLS connection if security is enabled
        if self.config.security_mode.is_enabled() {
            self.init_connection().await?;
        }

        Ok(())
    }

    /// Start DTLS handshake with the server
    async fn start_handshake(&self) -> Result<(), SecurityError> {
        debug!("Starting DTLS handshake");

        // Get the client socket
        let socket_guard = self.socket.lock().await;
        let _socket = socket_guard.clone().ok_or_else(|| {
            SecurityError::Configuration("No socket set for client security context".to_string())
        })?;
        drop(socket_guard);

        // Get remote address
        let remote_addr_guard = self.remote_addr.lock().await;
        let remote_addr = remote_addr_guard.ok_or_else(|| {
            SecurityError::Configuration(
                "Remote address not set for client security context".to_string(),
            )
        })?;
        drop(remote_addr_guard);

        debug!("Starting DTLS handshake with remote {}", remote_addr);

        // Make sure connection is initialized
        let mut conn_guard = self.connection.lock().await;
        if conn_guard.is_none() {
            debug!("Connection not initialized, initializing now...");
            // Initialize connection
            self.init_connection().await?;

            // Refresh the guard
            conn_guard = self.connection.lock().await;
        }

        // Get the connection (which should exist now)
        if let Some(conn) = conn_guard.as_mut() {
            // Start handshake and send ClientHello - this will begin the entire handshake process
            debug!("Calling start_handshake on DTLS connection");
            if let Err(e) = conn.start_handshake(remote_addr).await {
                error!("Failed to start DTLS handshake: {}", e);
                return Err(SecurityError::Handshake(format!(
                    "Failed to start DTLS handshake: {}",
                    e
                )));
            }

            debug!("DTLS handshake started successfully");

            // The rest of the handshake will be handled by the wait_for_handshake method
            // and automatic packet processing through the transport

            Ok(())
        } else {
            Err(SecurityError::Internal(
                "Failed to get DTLS connection after initialization".to_string(),
            ))
        }
    }

    async fn is_handshake_complete(&self) -> Result<bool, SecurityError> {
        let handshake_complete = *self.handshake_completed.lock().await;
        Ok(handshake_complete)
    }

    async fn set_remote_address(&self, addr: SocketAddr) -> Result<(), SecurityError> {
        // Store address
        let mut remote_addr = self.remote_addr.lock().await;
        *remote_addr = Some(addr);

        Ok(())
    }

    async fn set_socket(&self, socket: SocketHandle) -> Result<(), SecurityError> {
        transport::setup_transport(&socket, &self.connection).await?;

        // Store socket
        let mut socket_lock = self.socket.lock().await;
        *socket_lock = Some(socket.clone());

        // Set remote address if available
        if let Some(remote_addr) = socket.remote_addr {
            let mut remote_addr_guard = self.remote_addr.lock().await;
            *remote_addr_guard = Some(remote_addr);
        }

        // Start packet handler
        let remote_addr = self.remote_addr.lock().await.unwrap_or_else(|| {
            // Use a default if not set - this shouldn't happen in practice
            SocketAddr::from(([127, 0, 0, 1], 8000))
        });

        // Create a context reference for the packet handler
        let context = Arc::new(self.clone()) as Arc<dyn ClientSecurityContext>;

        // Start the packet handler in the background
        transport::start_packet_handler(&socket, remote_addr, context).await?;

        Ok(())
    }

    async fn set_remote_fingerprint(
        &self,
        fingerprint: &str,
        algorithm: &str,
    ) -> Result<(), SecurityError> {
        // Store fingerprint
        let mut remote_fingerprint = self.remote_fingerprint.lock().await;
        *remote_fingerprint = Some(fingerprint.to_string());

        let mut remote_fingerprint_algorithm = self.remote_fingerprint_algorithm.lock().await;
        *remote_fingerprint_algorithm = Some(algorithm.to_string());

        Ok(())
    }

    async fn get_security_info(&self) -> Result<SecurityInfo, SecurityError> {
        // If security is enabled, we need to initialize our DTLS connection
        // to get our fingerprint information
        if self.config.security_mode.is_enabled() && self.connection.lock().await.is_none() {
            self.init_connection().await?;
        }

        // Calculate crypto suites based on our SRTP profiles
        let crypto_suites = self
            .config
            .srtp_profiles
            .iter()
            .map(|p| match p {
                SrtpProfile::AesCm128HmacSha1_80 => "AES_CM_128_HMAC_SHA1_80",
                SrtpProfile::AesCm128HmacSha1_32 => "AES_CM_128_HMAC_SHA1_32",
                SrtpProfile::AesGcm128 => "AEAD_AES_128_GCM",
                SrtpProfile::AesGcm256 => "AEAD_AES_256_GCM",
            })
            .map(|s| s.to_string())
            .collect::<Vec<_>>();

        // Get the fingerprint from our connection
        let fingerprint = self.get_fingerprint().await.unwrap_or_else(|_| {
            "00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF".to_string()
        });

        Ok(SecurityInfo {
            mode: self.config.security_mode,
            fingerprint: Some(fingerprint),
            fingerprint_algorithm: self.remote_fingerprint_algorithm.lock().await.clone(),
            crypto_suites,
            key_params: None,
            srtp_profile: Some("AES_CM_128_HMAC_SHA1_80".to_string()),
        })
    }

    async fn close(&self) -> Result<(), SecurityError> {
        // Reset handshake state
        let mut handshake_complete = self.handshake_completed.lock().await;
        *handshake_complete = false;

        // Close DTLS connection
        let mut conn_guard = self.connection.lock().await;
        if let Some(conn) = conn_guard.as_mut() {
            match conn.close().await {
                Ok(_) => {}
                Err(e) => {
                    return Err(SecurityError::Internal(format!(
                        "Failed to close DTLS connection: {}",
                        e
                    )))
                }
            }
        }
        *conn_guard = None;

        // Clear SRTP context
        let mut srtp_guard = self.srtp_context.lock().await;
        *srtp_guard = None;

        Ok(())
    }

    fn is_secure(&self) -> bool {
        self.config.security_mode.is_enabled()
    }

    fn get_security_info_sync(&self) -> SecurityInfo {
        SecurityInfo {
            mode: self.config.security_mode,
            fingerprint: None, // Will be filled by async get_security_info method
            fingerprint_algorithm: None, // Can't await in a sync function
            crypto_suites: vec!["AES_CM_128_HMAC_SHA1_80".to_string()],
            key_params: None,
            srtp_profile: Some("AES_CM_128_HMAC_SHA1_80".to_string()),
        }
    }

    async fn get_fingerprint(&self) -> Result<String, SecurityError> {
        verify::generate_fingerprint(&self.connection).await
    }

    async fn get_fingerprint_algorithm(&self) -> Result<String, SecurityError> {
        // Return the default algorithm used
        Ok(verify::get_fingerprint_algorithm())
    }

    async fn has_transport(&self) -> Result<bool, SecurityError> {
        let conn_guard = self.connection.lock().await;
        if let Some(conn) = conn_guard.as_ref() {
            Ok(conn.has_transport())
        } else {
            Ok(false)
        }
    }

    async fn wait_for_handshake(&self) -> Result<(), SecurityError> {
        handshake::wait_for_handshake(
            &self.connection,
            &self.handshake_completed,
            &self.srtp_context,
        )
        .await
    }

    async fn complete_handshake(
        &self,
        remote_addr: SocketAddr,
        remote_fingerprint: &str,
    ) -> Result<(), SecurityError> {
        debug!("Starting complete handshake process with {}", remote_addr);

        // Set remote address and fingerprint
        self.set_remote_address(remote_addr).await?;
        self.set_remote_fingerprint(remote_fingerprint, "sha-256")
            .await?;

        // Start handshake
        self.start_handshake().await?;

        // Wait for handshake with a reasonable timeout
        let start_time = std::time::Instant::now();
        let timeout = Duration::from_secs(5);

        while !self.is_handshake_complete().await? {
            if start_time.elapsed() > timeout {
                return Err(SecurityError::Handshake(
                    "Handshake timed out after 5 seconds".to_string(),
                ));
            }

            tokio::time::sleep(Duration::from_millis(100)).await;
            debug!(
                "Waiting for handshake completion... ({:?} elapsed)",
                start_time.elapsed()
            );
        }

        debug!("Handshake completed successfully");
        Ok(())
    }

    async fn process_packet(&self, data: &[u8]) -> Result<(), SecurityError> {
        processor::process_packet(
            data,
            &self.connection,
            &self.remote_addr,
            &self.handshake_completed,
            &self.srtp_context,
        )
        .await
    }

    async fn start_packet_handler(&self) -> Result<(), SecurityError> {
        // Get the client socket
        let socket_guard = self.socket.lock().await;
        let socket = socket_guard.clone().ok_or_else(|| {
            SecurityError::Configuration("No socket set for client security context".to_string())
        })?;
        drop(socket_guard);

        // Get remote address
        let remote_addr_guard = self.remote_addr.lock().await;
        let remote_addr = remote_addr_guard.ok_or_else(|| {
            SecurityError::Configuration(
                "Remote address not set for client security context".to_string(),
            )
        })?;
        drop(remote_addr_guard);

        // Create a context reference for the packet handler
        let context = Arc::new(self.clone()) as Arc<dyn ClientSecurityContext>;

        // Delegate to the transport module's packet handler implementation
        transport::start_packet_handler(&socket, remote_addr, context).await
    }

    async fn is_ready(&self) -> Result<bool, SecurityError> {
        // Check if socket is set
        let socket_set = self.socket.lock().await.is_some();

        // Check if remote address is set
        let remote_addr_set = self.remote_addr.lock().await.is_some();

        // Check if remote fingerprint is set (needed for verification)
        let remote_fingerprint_set = self.remote_fingerprint.lock().await.is_some();

        // Check if DTLS connection is initialized
        let connection_guard = self.connection.lock().await;
        let connection_initialized = connection_guard.is_some();

        // Check if the connection has a transport
        let has_transport = if let Some(conn) = connection_guard.as_ref() {
            conn.has_transport()
        } else {
            false
        };

        // All prerequisites must be met for the context to be ready
        let is_ready = socket_set && remote_addr_set && connection_initialized && has_transport;

        debug!("Client security context ready: {}", is_ready);
        debug!("  - Socket set: {}", socket_set);
        debug!("  - Remote address set: {}", remote_addr_set);
        debug!("  - Remote fingerprint set: {}", remote_fingerprint_set);
        debug!("  - Connection initialized: {}", connection_initialized);
        debug!("  - Has transport: {}", has_transport);

        Ok(is_ready)
    }

    async fn process_dtls_packet(&self, data: &[u8]) -> Result<(), SecurityError> {
        processor::process_dtls_packet(
            data,
            &self.connection,
            &self.remote_addr,
            &self.handshake_completed,
            &self.srtp_context,
        )
        .await
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    /// Get the security configuration
    fn get_config(&self) -> &ClientSecurityConfig {
        &self.config
    }
}