rport 0.2.28

A p2p port forwarding client using WebRTC datachannels
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
use anyhow::{anyhow, Result};
use reqwest::Client;
use rustrtc::{
    transports::sctp::{DataChannel, DataChannelConfig, DataChannelEvent},
    PeerConnection, PeerConnectionEvent, SdpType, SessionDescription,
};
use serde_json::Value;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tracing::{error, info};

use crate::webrtc_config::WebRTCConfig;
use crate::{config::IceServerConfig, OfferMessage};

const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);

pub async fn forward_stream_to_webrtc<R, W>(
    peer_connection: Arc<PeerConnection>,
    data_channel: Arc<DataChannel>,
    connect_timeout: Option<u32>,
    mut input: R,
    mut output: W,
) -> Result<()>
where
    R: tokio::io::AsyncRead + Unpin + Send + 'static,
    W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
    // Wait for data channel open
    let (open_tx, open_rx) = tokio::sync::oneshot::channel();
    let (msg_tx, mut msg_rx) = tokio::sync::mpsc::unbounded_channel();
    let dc_closed = tokio_util::sync::CancellationToken::new();

    let dc_clone = data_channel.clone();
    let pc_disc = peer_connection.clone();
    let dc_closed_tx = dc_closed.clone();
    tokio::spawn(async move {
        let mut open_tx = Some(open_tx);
        while let Some(event) = dc_clone.recv().await {
            match event {
                DataChannelEvent::Open => {
                    if let Some(tx) = open_tx.take() {
                        let _ = tx.send(());
                    }
                }
                DataChannelEvent::Message(data) => {
                    let _ = msg_tx.send(data);
                }
                DataChannelEvent::Close => {
                    if let Some(reason) = pc_disc.disconnect_reason() {
                        tracing::warn!("Data channel closed (reason: {})", reason);
                    }
                    dc_closed_tx.cancel();
                    break;
                }
            }
        }
    });

    let connect_timeout = connect_timeout.unwrap_or(30);
    if let Err(_) = tokio::time::timeout(Duration::from_secs(connect_timeout.into()), open_rx).await
    {
        return Err(anyhow!("Data channel open timeout"));
    }

    let pc_monitor = peer_connection.clone();
    let webrtc_dead = tokio_util::sync::CancellationToken::new();
    let webrtc_dead_tx = webrtc_dead.clone();
    tokio::spawn(async move {
        let mut state_rx = pc_monitor.subscribe_peer_state();
        while let Ok(()) = state_rx.changed().await {
            let state = *state_rx.borrow();
            match state {
                rustrtc::PeerConnectionState::Disconnected
                | rustrtc::PeerConnectionState::Failed
                | rustrtc::PeerConnectionState::Closed => {
                    if let Some(reason) = pc_monitor.disconnect_reason() {
                        tracing::warn!("WebRTC connection lost: {} (state: {:?})", reason, state);
                    } else {
                        tracing::warn!("WebRTC connection lost: state {:?}", state);
                    }
                    webrtc_dead_tx.cancel();
                    break;
                }
                _ => {}
            }
        }
    });

    // Set up input -> WebRTC forwarding
    let pc_clone = peer_connection.clone();
    let dc_id = data_channel.id;

    let input_task = async move {
        let mut buffer = [0u8; 1200];

        loop {
            match input.read(&mut buffer).await {
                Ok(0) => {
                    tracing::debug!("forward_stream_to_webrtc: input EOF");
                    break;
                }
                Ok(n) => {
                    let data = &buffer[..n];
                    if let Err(e) = pc_clone.send_data(dc_id, data).await {
                        tracing::error!("Failed to send data through WebRTC: {}", e);
                        break;
                    }
                }
                Err(e) => {
                    tracing::debug!("forward_stream_to_webrtc: input read failed: {}", e);
                    break;
                }
            }
        }
    };

    // Set up WebRTC -> output forwarding
    let mut output_task = tokio::spawn(async move {
        while let Some(data) = msg_rx.recv().await {
            if output.write_all(&data).await.is_err() {
                break;
            }
            if output.flush().await.is_err() {
                break;
            }
        }
    });

    // Main select: wait for any side to finish
    tokio::select! {
        _ = webrtc_dead.cancelled() => {
            // WebRTC connection died — exit immediately
            tracing::debug!("forward_stream_to_webrtc: exiting due to WebRTC disconnect");
        }
        _ = dc_closed.cancelled() => {
            // Data channel closed from remote side
            tracing::debug!("forward_stream_to_webrtc: data channel closed by remote");
        }
        _ = input_task => {
            // Local input (stdin/TCP) closed.
            // Don't exit immediately — wait for output side to drain or WebRTC to close,
            // so SCTP has time to flush any pending data.
            tracing::debug!("forward_stream_to_webrtc: input closed, waiting for drain");
            tokio::select! {
                _ = tokio::time::sleep(DRAIN_TIMEOUT) => {
                    tracing::debug!("forward_stream_to_webrtc: drain timeout, closing");
                }
                _ = dc_closed.cancelled() => {
                    tracing::debug!("forward_stream_to_webrtc: data channel closed during drain");
                }
                _ = &mut output_task => {
                    tracing::debug!("forward_stream_to_webrtc: output finished during drain");
                }
            }
        }
        _ = &mut output_task => {
            tracing::debug!("forward_stream_to_webrtc: output closed");
        }
    }
    Ok(())
}

pub struct CliClient {
    server_url: String,
    token: String,
    client: Client,
    webrtc_config: WebRTCConfig,
}

impl CliClient {
    pub fn new(
        server_url: String,
        token: String,
        ice_servers: Option<Vec<IceServerConfig>>,
        enable_upnp: bool,
    ) -> Self {
        let webrtc_config = WebRTCConfig::new(
            server_url.clone(),
            token.clone(),
            ice_servers.unwrap_or_default(),
            enable_upnp,
        );
        Self {
            server_url,
            token,
            client: Client::new(),
            webrtc_config,
        }
    }

    pub async fn connect_proxy_command(
        &self,
        connect_timeout: Option<u32>,
        agent_id: String,
    ) -> Result<()> {
        // ProxyCommand mode - NO LOGGING to avoid SSH interference
        let (peer_connection, data_channel) =
            self.create_webrtc_connection_silent(&agent_id).await?;
        if let Err(e) = forward_stream_to_webrtc(
            peer_connection,
            data_channel,
            connect_timeout,
            tokio::io::stdin(),
            tokio::io::stdout(),
        )
        .await
        {
            tracing::error!("forward_stream_to_webrtc failed: {}", e);
            return Err(e);
        }
        Ok(())
    }

    pub async fn connect_port_forward(&self, agent_id: String, local_port: u16) -> Result<()> {
        info!(
            "Starting port forward from localhost:{} to agent {}",
            local_port, agent_id
        );

        let listener = TcpListener::bind(format!("127.0.0.1:{}", local_port)).await?;
        info!("Listening on localhost:{}", local_port);

        loop {
            match listener.accept().await {
                Ok((tcp_stream, addr)) => {
                    info!("New connection from {}", addr);

                    let agent_id = agent_id.clone();
                    let client = self.clone();

                    tokio::spawn(async move {
                        if let Err(e) = client.handle_tcp_connection(tcp_stream, agent_id).await {
                            error!("Failed to handle TCP connection: {}", e);
                        }
                    });
                }
                Err(e) => {
                    error!("Failed to accept connection: {}", e);
                }
            }
        }
    }

    async fn handle_tcp_connection(
        &self,
        mut tcp_stream: TcpStream,
        agent_id: String,
    ) -> Result<()> {
        let (close_tx, close_rx) = tokio::sync::oneshot::channel();
        let max_read_timeout = Duration::from_secs(1800); // 30 minutes
        let setup_result = async {
            // Create WebRTC connection for this TCP connection
            let (peer_connection, data_channel) = self.create_webrtc_connection(&agent_id).await?;

            let pc_clone = peer_connection.clone();
            tokio::spawn(async move {
                while let Some(event) = pc_clone.recv().await {
                    match event {
                        PeerConnectionEvent::DataChannel(dc) => {
                            tracing::debug!(
                                "CliClient PC Event: DataChannel: id={}, label={}",
                                dc.id,
                                dc.label
                            );
                        }
                        _ => {}
                    }
                }
            });

            // Monitor peer connection state for disconnect reasons
            let pc_monitor = peer_connection.clone();
            tokio::spawn(async move {
                let mut state_rx = pc_monitor.subscribe_peer_state();
                while let Ok(()) = state_rx.changed().await {
                    let state = *state_rx.borrow();
                    match state {
                        rustrtc::PeerConnectionState::Disconnected
                        | rustrtc::PeerConnectionState::Failed
                        | rustrtc::PeerConnectionState::Closed => {
                            if let Some(reason) = pc_monitor.disconnect_reason() {
                                tracing::warn!(
                                    "WebRTC connection ended: {} (state: {:?})",
                                    reason,
                                    state
                                );
                            } else {
                                tracing::warn!("WebRTC connection ended: state {:?}", state);
                            }
                            break;
                        }
                        _ => {
                            tracing::debug!("Peer connection state: {:?}", state);
                        }
                    }
                }
            });

            // Wait for connection to be established
            if let Err(_) = tokio::time::timeout(
                Duration::from_secs(30),
                peer_connection.wait_for_connected(),
            )
            .await
            {
                return Err(anyhow!("WebRTC connection timeout"));
            }
            peer_connection.wait_for_connected().await?;

            // Wait for data channel open and handle messages
            let (open_tx, open_rx) = tokio::sync::oneshot::channel();
            let (msg_tx, msg_rx) = tokio::sync::mpsc::unbounded_channel();

            let dc_clone = data_channel.clone();
            tokio::spawn(async move {
                let mut open_tx = Some(open_tx);
                while let Some(event) = dc_clone.recv().await {
                    match event {
                        DataChannelEvent::Open => {
                            if let Some(tx) = open_tx.take() {
                                let _ = tx.send(());
                            }
                        }
                        DataChannelEvent::Message(data) => {
                            let _ = msg_tx.send(data);
                        }
                        DataChannelEvent::Close => {
                            let _ = close_tx.send(());
                            break;
                        }
                    }
                }
            });

            if let Err(_) = tokio::time::timeout(Duration::from_secs(10), open_rx).await {
                return Err(anyhow!("Data channel open timeout"));
            }

            Ok((peer_connection, data_channel, msg_rx))
        }
        .await;

        let (peer_connection, data_channel, mut msg_rx) = match setup_result {
            Ok(res) => res,
            Err(e) => {
                let msg = format!("RPORT_SETUP_ERROR: {}\n", e);
                error!("{}", msg);
                let _ = tcp_stream.write_all(msg.as_bytes()).await;
                let _ = tcp_stream.flush().await;
                tokio::time::sleep(Duration::from_millis(500)).await;
                return Err(e);
            }
        };

        // Split the TCP stream
        let (mut tcp_read, mut tcp_write) = tcp_stream.into_split();

        let pc_clone = peer_connection.clone();
        let dc_id = data_channel.id;

        let tcp_to_webrtc = async move {
            let mut buffer = [0u8; 1024];
            loop {
                let r = tokio::time::timeout(max_read_timeout, tcp_read.read(&mut buffer)).await?;
                match r {
                    Ok(0) => {
                        info!("TCP connection closed by client");
                        break;
                    }
                    Ok(n) => {
                        let data = &buffer[..n];
                        if let Err(e) = pc_clone.send_data(dc_id, data).await {
                            error!("Failed to send data through WebRTC: {}", e);
                            break;
                        }
                    }
                    Err(e) => {
                        error!("Failed to read from TCP: {}", e);
                        break;
                    }
                }
            }
            Ok::<(), anyhow::Error>(())
        };

        // Set up WebRTC -> TCP forwarding
        let webrtc_to_tcp = async move {
            while let Some(data) = msg_rx.recv().await {
                if let Err(e) = tcp_write.write_all(&data).await {
                    error!("Failed to write to TCP: {}", e);
                    break;
                }
                if let Err(e) = tcp_write.flush().await {
                    error!("Failed to flush TCP: {}", e);
                    break;
                }
            }
        };

        // Wait for either direction to close
        tokio::select! {
            _ = close_rx => {
                let reason_str = peer_connection
                    .disconnect_reason()
                    .map(|r| format!("{}", r))
                    .unwrap_or_else(|| "normal close".to_string());
                info!("Data channel closed (reason: {})", reason_str);
            }
            _ = tcp_to_webrtc => {
                info!("TCP to WebRTC forwarding ended");
            }
            _ = webrtc_to_tcp => {
                info!("WebRTC to TCP forwarding ended");
            }
        }

        peer_connection.close();
        Ok(())
    }

    async fn create_webrtc_connection(
        &self,
        agent_id: &str,
    ) -> Result<(Arc<PeerConnection>, Arc<DataChannel>)> {
        info!("Creating WebRTC peer connection for agent: {}", agent_id);

        // Create WebRTC peer connection
        let peer_connection = self.create_peer_connection().await?;

        // Create a data channel before creating the offer
        let data_channel_config = DataChannelConfig {
            ordered: true,
            ..Default::default()
        };
        let data_channel =
            peer_connection.create_data_channel("port-forward", Some(data_channel_config))?;

        // Create offer
        let offer = peer_connection.create_offer().await?;
        peer_connection.set_local_description(offer.clone())?;

        // Wait for ICE gathering
        if let Err(_) = tokio::time::timeout(
            Duration::from_secs(3),
            peer_connection.wait_for_gathering_complete(),
        )
        .await
        {
            info!("ICE gathering timed out, proceeding with gathered candidates");
        }

        let offer = peer_connection
            .local_description()
            .ok_or_else(|| anyhow!("Failed to get local description after ICE gathering"))?;
        let sdp = offer.to_sdp_string();
        // Filter out IPv6 candidates for compatibility
        let offer_sdp = sdp
            .lines()
            .filter(|l| !l.contains("IP6") && !l.contains("::"))
            .collect::<Vec<_>>()
            .join("\r\n");

        // Send offer to server
        let offer_msg = OfferMessage {
            id: agent_id.to_string(),
            offer: offer_sdp,
        };

        info!("Sending offer to signaling server...");
        let url = format!("{}/rport/offer?token={}", self.server_url, self.token);
        let response = self.client.post(&url).json(&offer_msg).send().await?;

        if !response.status().is_success() {
            return Err(anyhow!("Failed to send offer: {}", response.status()));
        }

        let response_body: Value = response.json().await?;
        let answer_sdp = response_body["answer"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing answer in response"))?;

        // Set remote description from answer
        let answer = SessionDescription::parse(SdpType::Answer, &answer_sdp)?;
        peer_connection.set_remote_description(answer).await?;

        info!("WebRTC handshake completed successfully");

        Ok((peer_connection, data_channel))
    }

    async fn create_webrtc_connection_silent(
        &self,
        agent_id: &str,
    ) -> Result<(Arc<PeerConnection>, Arc<DataChannel>)> {
        let peer_connection = self.create_peer_connection().await?;

        let pc_clone = peer_connection.clone();
        tokio::spawn(async move {
            while let Some(event) = pc_clone.recv().await {
                match event {
                    PeerConnectionEvent::DataChannel(_) => {}
                    _ => {}
                }
            }
        });

        let data_channel_config = DataChannelConfig {
            ordered: true,
            ..Default::default()
        };
        let data_channel =
            peer_connection.create_data_channel("port-forward", Some(data_channel_config))?;
        let offer = peer_connection.create_offer().await?;
        peer_connection.set_local_description(offer.clone())?;

        if let Err(_) = tokio::time::timeout(
            Duration::from_secs(3),
            peer_connection.wait_for_gathering_complete(),
        )
        .await
        {
            info!("ICE gathering timed out, proceeding with gathered candidates");
        }

        let offer = peer_connection
            .local_description()
            .ok_or_else(|| anyhow!("Failed to get local description after ICE gathering"))?;

        // Strip IPv6 candidates from offer
        let offer_sdp = offer.to_sdp_string();
        let url = format!("{}/rport/offer?token={}", self.server_url, self.token);
        tracing::debug!(
            "create_webrtc_connection_silent: sending offer to {} \n {}",
            url,
            offer_sdp
        );

        let offer_msg = OfferMessage {
            id: agent_id.to_string(),
            offer: offer_sdp,
        };
        let response = self
            .client
            .post(&url)
            .timeout(Duration::from_secs(10))
            .json(&offer_msg)
            .send()
            .await?;

        if !response.status().is_success() {
            tracing::error!("Failed to send offer: {}", response.status());
            return Err(anyhow!("Failed to send offer: {}", response.status()));
        }

        let response_body: Value = response.json().await?;
        let answer_sdp = response_body["answer"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing answer in response"))?;

        // Set remote description from answer
        let answer = SessionDescription::parse(SdpType::Answer, &answer_sdp)?;
        peer_connection.set_remote_description(answer).await?;
        Ok((peer_connection, data_channel))
    }

    async fn create_peer_connection(&self) -> Result<Arc<PeerConnection>> {
        self.webrtc_config.create_peer_connection().await
    }
}

impl Clone for CliClient {
    fn clone(&self) -> Self {
        Self {
            server_url: self.server_url.clone(),
            token: self.token.clone(),
            client: Client::new(),
            webrtc_config: self.webrtc_config.clone(),
        }
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use crate::OfferMessage;
    use rustrtc::{PeerConnection, RtcConfiguration};
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    #[tokio::test]
    async fn test_connect_port_forward_integration() -> Result<()> {
        let _ = tracing_subscriber::fmt()
            .with_env_filter("debug")
            .try_init();

        // Setup "Agent" side WebRTC
        let config = RtcConfiguration::default();
        let agent_pc = Arc::new(PeerConnection::new(config));
        agent_pc.add_transceiver(
            rustrtc::MediaKind::Application,
            rustrtc::TransceiverDirection::SendRecv,
        );

        // Setup Mock Signaling Server
        let listener = TcpListener::bind("127.0.0.1:0").await?;
        let local_addr = listener.local_addr()?;
        let server_url = format!("http://{}", local_addr);

        let agent_pc_clone = agent_pc.clone();

        // Spawn the mock server
        tokio::spawn(async move {
            loop {
                let (mut socket, _) = match listener.accept().await {
                    Ok(conn) => conn,
                    Err(_) => break,
                };

                let agent_pc = agent_pc_clone.clone();
                tokio::spawn(async move {
                    let mut buf = [0u8; 8192];
                    let n = match socket.read(&mut buf).await {
                        Ok(n) if n > 0 => n,
                        _ => return,
                    };

                    let req = String::from_utf8_lossy(&buf[..n]);

                    if req.contains("GET /rport/iceservers") {
                        let response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n[]";
                        socket.write_all(response.as_bytes()).await.unwrap();
                        return;
                    }

                    if req.contains("POST /rport/offer") {
                        // Find body
                        if let Some(idx) = req.find("\r\n\r\n") {
                            let body = &req[idx + 4..];

                            if let Ok(offer_msg) = serde_json::from_str::<OfferMessage>(body) {
                                // Handle WebRTC negotiation
                                let offer =
                                    SessionDescription::parse(SdpType::Offer, &offer_msg.offer)
                                        .unwrap();
                                agent_pc.set_remote_description(offer).await.unwrap();

                                let answer = agent_pc.create_answer().await.unwrap();
                                agent_pc.set_local_description(answer.clone()).unwrap();
                                agent_pc.wait_for_gathering_complete().await;
                                let answer = agent_pc.local_description().unwrap();
                                let answer_sdp = answer.to_sdp_string();

                                let response_json = serde_json::json!({
                                    "uuid": uuid::Uuid::new_v4(),
                                    "offer": offer_msg.offer,
                                    "answer": answer_sdp
                                });

                                let response_body = response_json.to_string();
                                let response = format!(
                                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
                                    response_body.len(),
                                    response_body
                                );
                                socket.write_all(response.as_bytes()).await.unwrap();
                            }
                        }
                    }
                });
            }
        });

        // Setup Client
        let client = CliClient::new(server_url, "test-token".to_string(), None, false);

        // Run connect_port_forward in background
        let client_clone = client.clone();
        tokio::spawn(async move {
            if let Err(e) = client_clone
                .connect_port_forward("gpu03".to_string(), 4023)
                .await
            {
                eprintln!("connect_port_forward failed: {}", e);
            }
        });

        // Wait for listener to be ready
        tokio::time::sleep(Duration::from_secs(1)).await;

        // Connect to the forwarded port
        info!("Connecting to 127.0.0.1:4023");
        let _stream = TcpStream::connect("127.0.0.1:4023").await?;

        // Verify connection on Agent side
        // Wait for DataChannel from Client (DCEP)
        let (dc_tx, dc_rx) = tokio::sync::oneshot::channel();

        let agent_pc_clone = agent_pc.clone();
        tokio::spawn(async move {
            let mut dc_tx = Some(dc_tx);
            while let Some(event) = agent_pc_clone.recv().await {
                if let PeerConnectionEvent::DataChannel(dc) = event {
                    if let Some(tx) = dc_tx.take() {
                        let _ = tx.send(dc);
                    }
                }
            }
        });

        info!("Waiting for Agent PC connection...");
        agent_pc.wait_for_connected().await.unwrap();
        info!("Agent PC connected!");

        let dc = tokio::time::timeout(Duration::from_secs(5), dc_rx).await??;

        // Wait for DC open
        let (open_tx, open_rx) = tokio::sync::oneshot::channel();
        let dc_clone = dc.clone();
        tokio::spawn(async move {
            let mut open_tx = Some(open_tx);
            while let Some(event) = dc_clone.recv().await {
                if let DataChannelEvent::Open = event {
                    if let Some(tx) = open_tx.take() {
                        let _ = tx.send(());
                    }
                }
            }
        });

        tokio::time::timeout(Duration::from_secs(5), open_rx).await??;
        info!("DataChannel Open!");
        Ok(())
    }
}