wconnect 0.11.0

Wispers Connect connectivity test and sidecar utility
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
//! Serving mode - handles hub connection and incoming P2P connections.

use anyhow::{Context, Result};
use std::collections::HashSet;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};
use wispers_connect::P2pError;
use wispers_connect::{
    IncomingConnections, NodeState, QuicConnection, ServingHandle, ServingSession, UdpConnection,
};

use crate::ipc;

/// Port forwarding allowlist configuration.
#[derive(Clone, Debug)]
pub enum AllowedPorts {
    /// Allow FORWARD to any port
    All,
    /// Allow FORWARD only to specific ports
    Whitelist(HashSet<u16>),
}

impl AllowedPorts {
    /// Parse the CLI argument value.
    /// Empty string means allow all ports.
    /// Comma-separated list means allow only those ports.
    pub fn parse(value: &str) -> Result<Self> {
        if value.is_empty() {
            return Ok(AllowedPorts::All);
        }

        let mut ports = HashSet::new();
        for part in value.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            let port: u16 = part
                .parse()
                .with_context(|| format!("invalid port number: {}", part))?;
            ports.insert(port);
        }

        if ports.is_empty() {
            Ok(AllowedPorts::All)
        } else {
            Ok(AllowedPorts::Whitelist(ports))
        }
    }

    /// Check if a port is allowed.
    pub fn is_allowed(&self, port: u16) -> bool {
        match self {
            AllowedPorts::All => true,
            AllowedPorts::Whitelist(ports) => ports.contains(&port),
        }
    }
}

pub async fn serve(
    hub_override: Option<&str>,
    profile: &str,
    allowed_ports: Option<AllowedPorts>,
    allow_egress: bool,
) -> Result<()> {
    let storage = super::get_storage(hub_override, profile)?;
    let node = super::load_node(&storage).await?;

    if node.state() == NodeState::Pending {
        anyhow::bail!("Not registered. Use 'wconnect register <token>' first.");
    }

    let cg_id = node.connectivity_group_id().unwrap().to_string();
    let node_number = node.node_number().unwrap();

    // Start IPC server first (so it's available while connecting to hub)
    let ipc_server = ipc::Server::bind(&cg_id, node_number)
        .await
        .context("failed to start IPC server")?;

    // Share allowed_ports with spawned tasks
    let allowed_ports = Arc::new(allowed_ports);

    println!(
        "Serving node {} in group {} (socket: {:?})",
        node_number,
        cg_id,
        ipc_server.path()
    );
    if let Some(ref ports) = *allowed_ports {
        match ports {
            AllowedPorts::All => println!("  Port forwarding: all ports allowed"),
            AllowedPorts::Whitelist(set) => {
                let mut ports: Vec<_> = set.iter().collect();
                ports.sort();
                println!("  Port forwarding: allowed ports {:?}", ports);
            }
        }
    } else {
        println!("  Port forwarding: disabled");
    }
    if allow_egress {
        println!("  Internet egress: enabled");
    } else {
        println!("  Internet egress: disabled");
    }

    // Shared state for the serving handle (None until hub connects)
    let handle_state: Arc<RwLock<Option<ServingHandle>>> = Arc::new(RwLock::new(None));

    // Spawn hub connection in background
    let connect_handle_state = handle_state.clone();
    let mut connect_task = tokio::spawn(async move {
        let result: Result<(ServingHandle, ServingSession, IncomingConnections), anyhow::Error> =
            node.start_serving()
                .await
                .context("failed to start serving");

        if let Ok((handle, _session, _)) = &result {
            *connect_handle_state.write().await = Some(handle.clone());
        }
        result
    });

    // Session task (None until hub connects)
    let mut session_task: Option<
        tokio::task::JoinHandle<Result<(), wispers_connect::ServingError>>,
    > = None;

    // Incoming P2P connections receivers
    let mut incoming_udp_rx: Option<tokio::sync::mpsc::Receiver<Result<UdpConnection, P2pError>>> =
        None;
    let mut incoming_quic_rx: Option<
        tokio::sync::mpsc::Receiver<Result<QuicConnection, P2pError>>,
    > = None;

    // Accept IPC client connections, handle hub connection completing
    loop {
        tokio::select! {
            // Hub connection completed
            result = &mut connect_task, if session_task.is_none() => {
                match result {
                    Ok(Ok((handle, session, incoming))) => {
                        info!("Connected to hub");
                        *handle_state.write().await = Some(handle);
                        session_task = Some(tokio::spawn(async move { session.run().await }));
                        incoming_udp_rx = Some(incoming.udp);
                        incoming_quic_rx = Some(incoming.quic);
                    }
                    Ok(Err(e)) => {
                        return Err(e);
                    }
                    Err(e) => {
                        return Err(anyhow::anyhow!("Connect task panicked: {}", e));
                    }
                }
            }

            // Session completed (hub disconnected, error, or shutdown via handle)
            result = async { session_task.as_mut().unwrap().await }, if session_task.is_some() => {
                match result {
                    Ok(Ok(())) => {
                        info!("Session ended normally");
                        break;
                    }
                    Ok(Err(e)) => {
                        return Err(anyhow::anyhow!("Session error: {}", e));
                    }
                    Err(e) => {
                        return Err(anyhow::anyhow!("Session task panicked: {}", e));
                    }
                }
            }

            // Incoming UDP P2P connection
            Some(result) = async {
                match incoming_udp_rx.as_mut() {
                    Some(rx) => rx.recv().await,
                    None => std::future::pending().await,
                }
            } => {
                match result {
                    Ok(conn) => {
                        debug!(peer_node = conn.peer_node_number, "Incoming UDP P2P connection");
                        tokio::spawn(handle_udp_connection(conn));
                    }
                    Err(e) => {
                        warn!(error = %e, "UDP connection failed");
                    }
                }
            }

            // Incoming QUIC P2P connection
            Some(result) = async {
                match incoming_quic_rx.as_mut() {
                    Some(rx) => rx.recv().await,
                    None => std::future::pending().await,
                }
            } => {
                match result {
                    Ok(conn) => {
                        debug!(peer_node = conn.peer_node_number, "Incoming QUIC P2P connection");
                        let allowed_ports = Arc::clone(&allowed_ports);
                        tokio::spawn(handle_quic_connection(conn, allowed_ports, allow_egress));
                    }
                    Err(e) => {
                        warn!(error = %e, "QUIC connection handshake failed");
                    }
                }
            }

            // New IPC client connection
            result = ipc_server.accept() => {
                match result {
                    Ok(stream) => {
                        let client_handle_state = handle_state.clone();
                        tokio::spawn(async move {
                            ipc::handle_client_with_optional_handle(stream, client_handle_state).await;
                        });
                    }
                    Err(e) => {
                        error!(error = %e, "Failed to accept IPC connection");
                    }
                }
            }
        }
    }

    Ok(())
}

/// Handle an incoming UDP P2P connection (respond to pings).
async fn handle_udp_connection(conn: UdpConnection) {
    let peer = conn.peer_node_number;
    debug!(peer, "UDP connected (connection already established)");

    loop {
        match conn.recv().await {
            Ok(data) => {
                if data == b"ping" {
                    info!(peer, "Received ping, sending pong");
                    if let Err(e) = conn.send(b"pong") {
                        warn!(peer, error = %e, "Failed to send pong");
                        break;
                    }
                } else {
                    debug!(peer, bytes = data.len(), "Received data");
                }
            }
            Err(e) => {
                debug!(peer, error = %e, "UDP connection closed");
                break;
            }
        }
    }
}

/// Handle an incoming QUIC P2P connection.
async fn handle_quic_connection(
    conn: QuicConnection,
    allowed_ports: Arc<Option<AllowedPorts>>,
    allow_egress: bool,
) {
    let peer = conn.peer_node_number;
    debug!(peer, "QUIC connected (connection already established)");

    loop {
        match conn.accept_stream().await {
            Ok(stream) => {
                let stream_id = stream.id();
                debug!(peer, stream_id, "Accepted stream");
                let allowed_ports = Arc::clone(&allowed_ports);
                tokio::spawn(handle_quic_stream(
                    stream,
                    peer,
                    stream_id,
                    allowed_ports,
                    allow_egress,
                ));
            }
            Err(e) => {
                debug!(peer, error = %e, "QUIC connection closed");
                break;
            }
        }
    }
}

/// Handle a single QUIC stream - read command and dispatch.
async fn handle_quic_stream(
    stream: wispers_connect::QuicStream,
    _peer: i32,
    stream_id: u64,
    allowed_ports: Arc<Option<AllowedPorts>>,
    allow_egress: bool,
) {
    let mut buf = [0u8; 1024];
    let n = match stream.read(&mut buf).await {
        Ok(0) => {
            debug!(stream_id, "Stream closed by peer before command");
            return;
        }
        Ok(n) => n,
        Err(e) => {
            warn!(stream_id, error = %e, "Stream read error");
            return;
        }
    };

    let data = &buf[..n];

    // Parse command (first line)
    let line = match data.iter().position(|&b| b == b'\n') {
        Some(pos) => &data[..pos],
        None => data,
    };

    match line {
        b"PING" => {
            info!(stream_id, "Received PING, sending PONG");
            if let Err(e) = stream.write_all(b"PONG\n").await {
                warn!(stream_id, error = %e, "Failed to send PONG");
            }
            let _ = stream.finish().await;
        }
        cmd if cmd.starts_with(b"FORWARD ") => {
            let port_str = String::from_utf8_lossy(&cmd[8..]);
            match port_str.trim().parse::<u16>() {
                Ok(port) => {
                    info!(stream_id, port, "Received FORWARD");
                    handle_forward_stream(stream, port, &allowed_ports).await;
                }
                Err(_) => {
                    let _ = stream.write_all(b"ERROR invalid port\n").await;
                    let _ = stream.finish().await;
                }
            }
        }
        cmd if cmd.starts_with(b"CONNECT ") => {
            let target = String::from_utf8_lossy(&cmd[8..]).trim().to_string();
            info!(stream_id, target = %target, "Received CONNECT");
            handle_connect_stream(stream, &target, allow_egress).await;
        }
        _ => {
            warn!(
                stream_id,
                cmd = %String::from_utf8_lossy(line),
                "Unknown command",
            );
            let _ = stream.write_all(b"ERROR unknown command\n").await;
            let _ = stream.finish().await;
        }
    }
}

/// Handle a FORWARD command - connect to local port and relay.
async fn handle_forward_stream(
    stream: wispers_connect::QuicStream,
    port: u16,
    allowed_ports: &Option<AllowedPorts>,
) {
    // Check if port forwarding is allowed
    let allowed = match allowed_ports {
        None => false,
        Some(ports) => ports.is_allowed(port),
    };

    if !allowed {
        warn!(port, "FORWARD denied: port not in allowlist");
        let _ = stream.write_all(b"ERROR port not allowed\n").await;
        let _ = stream.finish().await;
        return;
    }

    let stream = Arc::new(stream);

    // Connect to localhost:port
    let tcp = match TcpStream::connect(format!("127.0.0.1:{}", port)).await {
        Ok(tcp) => {
            if let Err(e) = stream.write_all(b"OK\n").await {
                warn!(error = %e, "Failed to send OK");
                return;
            }
            tcp
        }
        Err(e) => {
            let msg = format!("ERROR {}\n", e);
            let _ = stream.write_all(msg.as_bytes()).await;
            let _ = stream.finish().await;
            return;
        }
    };

    let (mut tcp_read, mut tcp_write) = tcp.into_split();

    let stream_read = Arc::clone(&stream);
    let stream_write = Arc::clone(&stream);

    // QUIC -> TCP
    let quic_to_tcp = async move {
        let mut buf = [0u8; 8192];
        loop {
            match stream_read.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    if let Err(e) = tcp_write.write_all(&buf[..n]).await {
                        debug!(error = %e, "TCP write error");
                        break;
                    }
                }
                Err(e) => {
                    debug!(error = %e, "QUIC read error");
                    break;
                }
            }
        }
        let _ = tcp_write.shutdown().await;
    };

    // TCP -> QUIC
    let tcp_to_quic = async move {
        let mut buf = [0u8; 8192];
        loop {
            match tcp_read.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    if let Err(e) = stream_write.write_all(&buf[..n]).await {
                        debug!(error = %e, "QUIC write error");
                        break;
                    }
                }
                Err(e) => {
                    debug!(error = %e, "TCP read error");
                    break;
                }
            }
        }
        let _ = stream_write.finish().await;
    };

    tokio::join!(quic_to_tcp, tcp_to_quic);
}

/// Handle a CONNECT command - connect to arbitrary host:port and relay.
async fn handle_connect_stream(
    stream: wispers_connect::QuicStream,
    target: &str,
    allow_egress: bool,
) {
    // Check if egress is allowed
    if !allow_egress {
        warn!(target, "CONNECT denied: egress not enabled");
        let _ = stream.write_all(b"ERROR egress not allowed\n").await;
        let _ = stream.finish().await;
        return;
    }

    // Parse host:port
    let (host, port) = match parse_host_port(target) {
        Some(hp) => hp,
        None => {
            warn!(target, "CONNECT invalid target");
            let _ = stream.write_all(b"ERROR invalid target format\n").await;
            let _ = stream.finish().await;
            return;
        }
    };

    let stream = Arc::new(stream);

    // Connect to remote host:port
    let tcp = match TcpStream::connect((host.as_str(), port)).await {
        Ok(tcp) => {
            if let Err(e) = stream.write_all(b"OK\n").await {
                warn!(error = %e, "Failed to send OK");
                return;
            }
            tcp
        }
        Err(e) => {
            let msg = format!("ERROR {}\n", e);
            let _ = stream.write_all(msg.as_bytes()).await;
            let _ = stream.finish().await;
            return;
        }
    };

    let (mut tcp_read, mut tcp_write) = tcp.into_split();

    let stream_read = Arc::clone(&stream);
    let stream_write = Arc::clone(&stream);

    // QUIC -> TCP
    let quic_to_tcp = async move {
        let mut buf = [0u8; 8192];
        loop {
            match stream_read.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    if let Err(e) = tcp_write.write_all(&buf[..n]).await {
                        debug!(error = %e, "TCP write error");
                        break;
                    }
                }
                Err(e) => {
                    debug!(error = %e, "QUIC read error");
                    break;
                }
            }
        }
        let _ = tcp_write.shutdown().await;
    };

    // TCP -> QUIC
    let tcp_to_quic = async move {
        let mut buf = [0u8; 8192];
        loop {
            match tcp_read.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    if let Err(e) = stream_write.write_all(&buf[..n]).await {
                        debug!(error = %e, "QUIC write error");
                        break;
                    }
                }
                Err(e) => {
                    debug!(error = %e, "TCP read error");
                    break;
                }
            }
        }
        let _ = stream_write.finish().await;
    };

    tokio::join!(quic_to_tcp, tcp_to_quic);
}

/// Parse a "host:port" string into (host, port).
fn parse_host_port(target: &str) -> Option<(String, u16)> {
    // Find the last colon (to handle IPv6 addresses like [::1]:8080)
    let colon_pos = target.rfind(':')?;

    let host = &target[..colon_pos];
    let port_str = &target[colon_pos + 1..];

    // Host must not be empty
    if host.is_empty() {
        return None;
    }

    // Parse port
    let port: u16 = port_str.parse().ok()?;

    Some((host.to_string(), port))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_allowed_ports_parse_empty() {
        let ports = AllowedPorts::parse("").unwrap();
        assert!(matches!(ports, AllowedPorts::All));
        assert!(ports.is_allowed(80));
        assert!(ports.is_allowed(443));
        assert!(ports.is_allowed(8080));
    }

    #[test]
    fn test_allowed_ports_parse_single() {
        let ports = AllowedPorts::parse("80").unwrap();
        assert!(ports.is_allowed(80));
        assert!(!ports.is_allowed(443));
    }

    #[test]
    fn test_allowed_ports_parse_multiple() {
        let ports = AllowedPorts::parse("80,443,8080").unwrap();
        assert!(ports.is_allowed(80));
        assert!(ports.is_allowed(443));
        assert!(ports.is_allowed(8080));
        assert!(!ports.is_allowed(22));
    }

    #[test]
    fn test_allowed_ports_parse_with_spaces() {
        let ports = AllowedPorts::parse("80, 443, 8080").unwrap();
        assert!(ports.is_allowed(80));
        assert!(ports.is_allowed(443));
        assert!(ports.is_allowed(8080));
    }

    #[test]
    fn test_allowed_ports_parse_invalid() {
        assert!(AllowedPorts::parse("abc").is_err());
        assert!(AllowedPorts::parse("80,abc").is_err());
        assert!(AllowedPorts::parse("99999").is_err()); // > u16::MAX
    }

    #[test]
    fn test_parse_host_port_basic() {
        let (host, port) = parse_host_port("example.com:443").unwrap();
        assert_eq!(host, "example.com");
        assert_eq!(port, 443);
    }

    #[test]
    fn test_parse_host_port_localhost() {
        let (host, port) = parse_host_port("localhost:8080").unwrap();
        assert_eq!(host, "localhost");
        assert_eq!(port, 8080);
    }

    #[test]
    fn test_parse_host_port_ipv4() {
        let (host, port) = parse_host_port("192.168.1.1:80").unwrap();
        assert_eq!(host, "192.168.1.1");
        assert_eq!(port, 80);
    }

    #[test]
    fn test_parse_host_port_ipv6() {
        let (host, port) = parse_host_port("[::1]:8080").unwrap();
        assert_eq!(host, "[::1]");
        assert_eq!(port, 8080);
    }

    #[test]
    fn test_parse_host_port_invalid() {
        assert!(parse_host_port("example.com").is_none()); // no port
        assert!(parse_host_port(":8080").is_none()); // no host
        assert!(parse_host_port("example.com:abc").is_none()); // invalid port
        assert!(parse_host_port("example.com:99999").is_none()); // port too large
    }
}