forked from n0-computer/dumbpipe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
866 lines (795 loc) · 29.9 KB
/
main.rs
File metadata and controls
866 lines (795 loc) · 29.9 KB
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! Command line arguments.
use clap::{Parser, Subcommand};
use dumbpipe::EndpointTicket;
use iroh::{endpoint::Connecting, Endpoint, EndpointAddr, SecretKey};
use n0_snafu::{Result, ResultExt};
use std::{
io,
net::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs},
str::FromStr,
};
use tokio::{
io::{AsyncRead, AsyncWrite, AsyncWriteExt},
select,
};
use tokio_util::sync::CancellationToken;
#[cfg(unix)]
use {
std::path::PathBuf,
tokio::net::{UnixListener, UnixStream},
};
/// Create a dumb pipe between two machines, using an iroh endpoint.
///
/// One side listens, the other side connects. Both sides are identified by a
/// 32 byte endpoint id.
///
/// Connecting to a endpoint id is independent of its IP address. Dumbpipe will try
/// to establish a direct connection even through NATs and firewalls. If that
/// fails, it will fall back to using a relay server.
///
/// For all subcommands, you can specify a secret key using the IROH_SECRET
/// environment variable. If you don't, a random one will be generated.
///
/// You can also specify a port for the endpoint. If you don't, a random one
/// will be chosen.
#[derive(Parser, Debug)]
pub struct Args {
#[clap(subcommand)]
pub command: Commands,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Generate a short endpoint ticket. This ticket can be used to later connect to a
/// listener that is using the same secret key again.
///
/// This command only really makes sense when you are providing dumbpipe with a
/// secret key.
GenerateTicket,
/// Listen on an endpoint and forward stdin/stdout to the first incoming
/// bidi stream.
///
/// Will print a endpoint ticket on stderr that can be used to connect.
Listen(ListenArgs),
/// Listen on an endpoint and forward incoming connections to the specified
/// host and port. Every incoming bidi stream is forwarded to a new connection.
///
/// Will print a endpoint ticket on stderr that can be used to connect.
///
/// As far as the endpoint is concerned, this is listening. But it is
/// connecting to a TCP socket for which you have to specify the host and port.
ListenTcp(ListenTcpArgs),
/// Connect to an endpoint, open a bidi stream, and forward stdin/stdout.
///
/// A endpoint ticket is required to connect.
Connect(ConnectArgs),
/// Connect to an endpoint, open a bidi stream, and forward stdin/stdout
/// to it.
///
/// A endpoint ticket is required to connect.
///
/// As far as the endpoint is concerned, this is connecting. But it is
/// listening on a TCP socket for which you have to specify the interface and port.
ConnectTcp(ConnectTcpArgs),
#[cfg(unix)]
/// Listen on an endpoint and forward incoming connections to the specified
/// Unix socket path. Every incoming bidi stream is forwarded to a new connection.
///
/// Will print a endpoint ticket on stderr that can be used to connect.
///
/// As far as the endpoint is concerned, this is listening. But it is
/// connecting to a Unix socket for which you have to specify the path.
ListenUnix(ListenUnixArgs),
#[cfg(unix)]
/// Connect to an endpoint, open a bidi stream, and forward connections
/// from the specified Unix socket path.
///
/// A endpoint ticket is required to connect.
///
/// As far as the endpoint is concerned, this is connecting. But it is
/// listening on a Unix socket for which you have to specify the path.
ConnectUnix(ConnectUnixArgs),
}
#[derive(Parser, Debug)]
pub struct CommonArgs {
/// The IPv4 address that the endpoint will listen on.
///
/// If None, defaults to a random free port, but it can be useful to specify a fixed
/// port, e.g. to configure a firewall rule.
#[clap(long, default_value = None)]
pub ipv4_addr: Option<SocketAddrV4>,
/// The IPv6 address that the endpoint will listen on.
///
/// If None, defaults to a random free port, but it can be useful to specify a fixed
/// port, e.g. to configure a firewall rule.
#[clap(long, default_value = None)]
pub ipv6_addr: Option<SocketAddrV6>,
/// A custom ALPN to use for the endpoint.
///
/// This is an expert feature that allows dumbpipe to be used to interact
/// with existing iroh protocols.
///
/// When using this option, the connect side must also specify the same ALPN.
/// The listen side will not expect a handshake, and the connect side will
/// not send one.
///
/// Alpns are byte strings. To specify an utf8 string, prefix it with `utf8:`.
/// Otherwise, it will be parsed as a hex string.
#[clap(long)]
pub custom_alpn: Option<String>,
/// The verbosity level. Repeat to increase verbosity.
#[clap(short = 'v', long, action = clap::ArgAction::Count)]
pub verbose: u8,
}
impl CommonArgs {
fn alpn(&self) -> Result<Vec<u8>> {
Ok(match &self.custom_alpn {
Some(alpn) => parse_alpn(alpn)?,
None => dumbpipe::ALPN.to_vec(),
})
}
fn is_custom_alpn(&self) -> bool {
self.custom_alpn.is_some()
}
}
fn parse_alpn(alpn: &str) -> Result<Vec<u8>> {
Ok(if let Some(text) = alpn.strip_prefix("utf8:") {
text.as_bytes().to_vec()
} else {
hex::decode(alpn).e()?
})
}
#[derive(Parser, Debug)]
pub struct ListenArgs {
/// Immediately close our sending side, indicating that we will not transmit any data
#[clap(long)]
pub recv_only: bool,
#[clap(flatten)]
pub common: CommonArgs,
}
#[derive(Parser, Debug)]
pub struct ListenTcpArgs {
#[clap(long)]
pub host: String,
#[clap(flatten)]
pub common: CommonArgs,
}
#[derive(Parser, Debug)]
pub struct ConnectTcpArgs {
/// The addresses to listen on for incoming tcp connections.
///
/// To listen on all network interfaces, use 0.0.0.0:12345
#[clap(long)]
pub addr: String,
/// The endpoint to connect to
pub ticket: EndpointTicket,
#[clap(flatten)]
pub common: CommonArgs,
}
#[derive(Parser, Debug)]
pub struct ConnectArgs {
/// The endpoint to connect to
pub ticket: EndpointTicket,
/// Immediately close our sending side, indicating that we will not transmit any data
#[clap(long)]
pub recv_only: bool,
#[clap(flatten)]
pub common: CommonArgs,
}
#[cfg(unix)]
#[derive(Parser, Debug)]
pub struct ListenUnixArgs {
/// Path to the Unix socket to connect to
#[clap(long)]
pub socket_path: PathBuf,
#[clap(flatten)]
pub common: CommonArgs,
}
#[cfg(unix)]
#[derive(Parser, Debug)]
pub struct ConnectUnixArgs {
/// Path to the Unix socket to listen on
#[clap(long)]
pub socket_path: PathBuf,
/// The endpoint to connect to
pub ticket: EndpointTicket,
#[clap(flatten)]
pub common: CommonArgs,
}
/// Copy from a reader to a quinn stream.
///
/// Will send a reset to the other side if the operation is cancelled, and fail
/// with an error.
///
/// Returns the number of bytes copied in case of success.
async fn copy_to_quinn(
mut from: impl AsyncRead + Unpin,
mut send: quinn::SendStream,
token: CancellationToken,
) -> io::Result<u64> {
tracing::trace!("copying to quinn");
tokio::select! {
res = tokio::io::copy(&mut from, &mut send) => {
let size = res?;
send.finish()?;
Ok(size)
}
_ = token.cancelled() => {
// send a reset to the other side immediately
send.reset(0u8.into()).ok();
Err(io::Error::other("cancelled"))
}
}
}
/// Copy from a quinn stream to a writer.
///
/// Will send stop to the other side if the operation is cancelled, and fail
/// with an error.
///
/// Returns the number of bytes copied in case of success.
async fn copy_from_quinn(
mut recv: quinn::RecvStream,
mut to: impl AsyncWrite + Unpin,
token: CancellationToken,
) -> io::Result<u64> {
tokio::select! {
res = tokio::io::copy(&mut recv, &mut to) => {
Ok(res?)
},
_ = token.cancelled() => {
recv.stop(0u8.into()).ok();
Err(io::Error::other("cancelled"))
}
}
}
/// Get the secret key or generate a new one.
///
/// Print the secret key to stderr if it was generated, so the user can save it.
fn get_or_create_secret() -> Result<SecretKey> {
match std::env::var("IROH_SECRET") {
Ok(secret) => SecretKey::from_str(&secret).context("invalid secret"),
Err(_) => {
let key = SecretKey::generate(&mut rand::rng());
eprintln!(
"using secret key {}",
data_encoding::HEXLOWER.encode(&key.to_bytes())
);
Ok(key)
}
}
}
/// Create a new iroh endpoint.
async fn create_endpoint(
secret_key: SecretKey,
common: &CommonArgs,
alpns: Vec<Vec<u8>>,
) -> Result<Endpoint> {
let mut builder = Endpoint::builder().secret_key(secret_key).alpns(alpns);
if let Some(addr) = common.ipv4_addr {
builder = builder.bind_addr_v4(addr);
}
if let Some(addr) = common.ipv6_addr {
builder = builder.bind_addr_v6(addr);
}
let endpoint = builder.bind().await?;
Ok(endpoint)
}
fn cancel_token<T>(token: CancellationToken) -> impl Fn(T) -> T {
move |x| {
token.cancel();
x
}
}
/// Bidirectionally forward data from a quinn stream and an arbitrary tokio
/// reader/writer pair, aborting both sides when either one forwarder is done,
/// or when control-c is pressed.
async fn forward_bidi(
from1: impl AsyncRead + Send + Sync + Unpin + 'static,
to1: impl AsyncWrite + Send + Sync + Unpin + 'static,
from2: quinn::RecvStream,
to2: quinn::SendStream,
) -> Result<()> {
let token1 = CancellationToken::new();
let token2 = token1.clone();
let token3 = token1.clone();
let forward_from_stdin = tokio::spawn(async move {
copy_to_quinn(from1, to2, token1.clone())
.await
.map_err(cancel_token(token1))
});
let forward_to_stdout = tokio::spawn(async move {
copy_from_quinn(from2, to1, token2.clone())
.await
.map_err(cancel_token(token2))
});
let _control_c = tokio::spawn(async move {
tokio::signal::ctrl_c().await?;
token3.cancel();
io::Result::Ok(())
});
forward_to_stdout.await.e()?.e()?;
forward_from_stdin.await.e()?.e()?;
Ok(())
}
async fn listen_stdio(args: ListenArgs) -> Result<()> {
let secret_key = get_or_create_secret()?;
let endpoint = create_endpoint(secret_key, &args.common, vec![args.common.alpn()?]).await?;
// wait for the endpoint to figure out its home relay and addresses before making a ticket
endpoint.online().await;
let addr = endpoint.addr();
let short = create_short_ticket(&addr);
let ticket = EndpointTicket::new(addr);
// print the ticket on stderr so it doesn't interfere with the data itself
//
// note that the tests rely on the ticket being the last thing printed
eprintln!("Listening. To connect, use:\ndumbpipe connect {ticket}");
if args.common.verbose > 0 {
eprintln!("or:\ndumbpipe connect {short}");
}
loop {
let Some(connecting) = endpoint.accept().await else {
break;
};
let connection = match connecting.await {
Ok(connection) => connection,
Err(cause) => {
tracing::warn!("error accepting connection: {}", cause);
// if accept fails, we want to continue accepting connections
continue;
}
};
let remote_endpoint_id = &connection.remote_id()?;
tracing::info!("got connection from {}", remote_endpoint_id);
let (s, mut r) = match connection.accept_bi().await {
Ok(x) => x,
Err(cause) => {
tracing::warn!("error accepting stream: {}", cause);
// if accept_bi fails, we want to continue accepting connections
continue;
}
};
tracing::info!("accepted bidi stream from {}", remote_endpoint_id);
if !args.common.is_custom_alpn() {
// read the handshake and verify it
let mut buf = [0u8; dumbpipe::HANDSHAKE.len()];
r.read_exact(&mut buf).await.e()?;
snafu::ensure_whatever!(buf == dumbpipe::HANDSHAKE, "invalid handshake");
}
if args.recv_only {
tracing::info!(
"forwarding stdout to {} (ignoring stdin)",
remote_endpoint_id
);
forward_bidi(tokio::io::empty(), tokio::io::stdout(), r, s).await?;
} else {
tracing::info!("forwarding stdin/stdout to {}", remote_endpoint_id);
forward_bidi(tokio::io::stdin(), tokio::io::stdout(), r, s).await?;
}
// stop accepting connections after the first successful one
break;
}
Ok(())
}
async fn connect_stdio(args: ConnectArgs) -> Result<()> {
let secret_key = get_or_create_secret()?;
let endpoint = create_endpoint(secret_key, &args.common, vec![]).await?;
let addr = args.ticket.endpoint_addr();
let remote_endpoint_id = addr.id;
// connect to the remote, try only once
let connection = endpoint.connect(addr.clone(), &args.common.alpn()?).await?;
tracing::info!("connected to {}", remote_endpoint_id);
// open a bidi stream, try only once
let (mut s, r) = connection.open_bi().await.e()?;
tracing::info!("opened bidi stream to {}", remote_endpoint_id);
// send the handshake unless we are using a custom alpn
// when using a custom alpn, evertyhing is up to the user
if !args.common.is_custom_alpn() {
// the connecting side must write first. we don't know if there will be something
// on stdin, so just write a handshake.
s.write_all(&dumbpipe::HANDSHAKE).await.e()?;
}
if args.recv_only {
tracing::info!(
"forwarding stdout to {} (ignoring stdin)",
remote_endpoint_id
);
forward_bidi(tokio::io::empty(), tokio::io::stdout(), r, s).await?;
} else {
tracing::info!("forwarding stdin/stdout to {}", remote_endpoint_id);
forward_bidi(tokio::io::stdin(), tokio::io::stdout(), r, s).await?;
}
tokio::io::stdout().flush().await.e()?;
Ok(())
}
/// Listen on a tcp port and forward incoming connections to an endpoint.
async fn connect_tcp(args: ConnectTcpArgs) -> Result<()> {
let addrs = args
.addr
.to_socket_addrs()
.context(format!("invalid host string {}", args.addr))?;
let secret_key = get_or_create_secret()?;
let endpoint = create_endpoint(secret_key, &args.common, vec![])
.await
.context("unable to bind endpoint")?;
tracing::info!("tcp listening on {:?}", addrs);
// Wait for our own endpoint to be ready before trying to connect.
endpoint.online().await;
let tcp_listener = match tokio::net::TcpListener::bind(addrs.as_slice()).await {
Ok(tcp_listener) => tcp_listener,
Err(cause) => {
tracing::error!("error binding tcp socket to {:?}: {}", addrs, cause);
return Ok(());
}
};
async fn handle_tcp_accept(
next: io::Result<(tokio::net::TcpStream, SocketAddr)>,
addr: EndpointAddr,
endpoint: Endpoint,
handshake: bool,
alpn: &[u8],
) -> Result<()> {
let (tcp_stream, tcp_addr) = next.context("error accepting tcp connection")?;
let (tcp_recv, tcp_send) = tcp_stream.into_split();
tracing::info!("got tcp connection from {}", tcp_addr);
let remote_endpoint_id = addr.id;
let connection = endpoint
.connect(addr, alpn)
.await
.context(format!("error connecting to {remote_endpoint_id}"))?;
let (mut endpoint_send, endpoint_recv) = connection
.open_bi()
.await
.context(format!("error opening bidi stream to {remote_endpoint_id}"))?;
// send the handshake unless we are using a custom alpn
// when using a custom alpn, evertyhing is up to the user
if handshake {
// the connecting side must write first. we don't know if there will be something
// on stdin, so just write a handshake.
endpoint_send.write_all(&dumbpipe::HANDSHAKE).await.e()?;
}
forward_bidi(tcp_recv, tcp_send, endpoint_recv, endpoint_send).await?;
Ok::<_, n0_snafu::Error>(())
}
let addr = args.ticket.endpoint_addr();
loop {
// also wait for ctrl-c here so we can use it before accepting a connection
let next = tokio::select! {
stream = tcp_listener.accept() => stream,
_ = tokio::signal::ctrl_c() => {
eprintln!("got ctrl-c, exiting");
break;
}
};
let endpoint = endpoint.clone();
let addr = addr.clone();
let handshake = !args.common.is_custom_alpn();
let alpn = args.common.alpn()?;
tokio::spawn(async move {
if let Err(cause) = handle_tcp_accept(next, addr, endpoint, handshake, &alpn).await {
// log error at warn level
//
// we should know about it, but it's not fatal
tracing::warn!("error handling connection: {}", cause);
}
});
}
Ok(())
}
/// Listen on an endpoint and forward incoming connections to a tcp socket.
async fn listen_tcp(args: ListenTcpArgs) -> Result<()> {
let addrs = match args.host.to_socket_addrs() {
Ok(addrs) => addrs.collect::<Vec<_>>(),
Err(e) => snafu::whatever!("invalid host string {}: {}", args.host, e),
};
let secret_key = get_or_create_secret()?;
let endpoint = create_endpoint(secret_key, &args.common, vec![args.common.alpn()?]).await?;
// wait for the endpoint to figure out its address before making a ticket
endpoint.online().await;
let addr = endpoint.addr();
let short = create_short_ticket(&addr);
let ticket = EndpointTicket::new(addr);
// print the ticket on stderr so it doesn't interfere with the data itself
//
// note that the tests rely on the ticket being the last thing printed
eprintln!("Forwarding incoming requests to '{}'.", args.host);
eprintln!("To connect, use e.g.:");
eprintln!("dumbpipe connect-tcp {ticket}");
if args.common.verbose > 0 {
eprintln!("or:\ndumbpipe connect-tcp {short}");
}
tracing::info!("endpoint id is {}", ticket.endpoint_addr().id);
tracing::info!(
"relay url is {:?}",
ticket
.endpoint_addr()
.relay_urls()
.next()
.map_or("None".to_string(), |url| url.to_string())
);
// handle a new incoming connection on the endpoint
async fn handle_endpoint_accept(
connecting: Connecting,
addrs: Vec<std::net::SocketAddr>,
handshake: bool,
) -> Result<()> {
let connection = connecting.await.context("error accepting connection")?;
let remote_endpoint_id = &connection.remote_id()?;
tracing::info!("got connection from {}", remote_endpoint_id);
let (s, mut r) = connection
.accept_bi()
.await
.context("error accepting stream")?;
tracing::info!("accepted bidi stream from {}", remote_endpoint_id);
if handshake {
// read the handshake and verify it
let mut buf = [0u8; dumbpipe::HANDSHAKE.len()];
r.read_exact(&mut buf).await.e()?;
snafu::ensure_whatever!(buf == dumbpipe::HANDSHAKE, "invalid handshake");
}
let connection = tokio::net::TcpStream::connect(addrs.as_slice())
.await
.context(format!("error connecting to {addrs:?}"))?;
let (read, write) = connection.into_split();
forward_bidi(read, write, r, s).await?;
Ok(())
}
loop {
let incoming = select! {
incoming = endpoint.accept() => incoming,
_ = tokio::signal::ctrl_c() => {
eprintln!("got ctrl-c, exiting");
break;
}
};
let Some(incoming) = incoming else {
break;
};
let Ok(connecting) = incoming.accept() else {
break;
};
let addrs = addrs.clone();
let handshake = !args.common.is_custom_alpn();
tokio::spawn(async move {
if let Err(cause) = handle_endpoint_accept(connecting, addrs, handshake).await {
// log error at warn level
//
// we should know about it, but it's not fatal
tracing::warn!("error handling connection: {}", cause);
}
});
}
Ok(())
}
/// Creates a ticket that only includes the id and any relay urls
fn create_short_ticket(addr: &EndpointAddr) -> EndpointTicket {
let mut short = EndpointAddr::new(addr.id);
for relay_url in addr.relay_urls() {
short = short.with_relay_url(relay_url.clone());
}
short.into()
}
#[cfg(unix)]
/// Listen on an endpoint and forward incoming connections to a Unix socket.
async fn listen_unix(args: ListenUnixArgs) -> Result<()> {
let socket_path = args.socket_path.clone();
let secret_key = get_or_create_secret()?;
let endpoint = create_endpoint(secret_key, &args.common, vec![args.common.alpn()?]).await?;
// wait for the endpoint to figure out its address before making a ticket
endpoint.online().await;
let addr = endpoint.addr();
let short = create_short_ticket(&addr);
let ticket = EndpointTicket::new(addr);
// print the ticket on stderr so it doesn't interfere with the data itself
//
// note that the tests rely on the ticket being the last thing printed
eprintln!(
"Forwarding incoming requests to '{}'.",
socket_path.display()
);
eprintln!("To connect, use e.g.:");
eprintln!("dumbpipe connect-unix --socket-path /path/to/client.sock {ticket}");
eprintln!("dumbpipe connect-tcp --addr 127.0.0.1:8080 {ticket}");
if args.common.verbose > 0 {
eprintln!("or:\ndumbpipe connect-unix --socket-path /path/to/client.sock {short}");
eprintln!("dumbpipe connect-tcp --addr 127.0.0.1:8080 {short}");
}
tracing::info!("endpoint id is {}", ticket.endpoint_addr().id);
tracing::info!(
"relay url is {:?}",
ticket
.endpoint_addr()
.relay_urls()
.next()
.map_or("None".to_string(), |url| url.to_string())
);
// handle a new incoming connection on the endpoint
async fn handle_endpoint_accept(
connecting: Connecting,
socket_path: PathBuf,
handshake: bool,
) -> Result<()> {
tracing::trace!("accepting connection");
let connection = connecting.await.context("error accepting connection")?;
let remote_endpoint_id = &connection.remote_id()?;
tracing::info!("got connection from {}", remote_endpoint_id);
let (s, mut r) = connection
.accept_bi()
.await
.context("error accepting stream")?;
tracing::info!("accepted bidi stream from {}", remote_endpoint_id);
if handshake {
// read the handshake and verify it
tracing::trace!("reading handshake");
let mut buf = [0u8; dumbpipe::HANDSHAKE.len()];
r.read_exact(&mut buf).await.e()?;
snafu::ensure_whatever!(buf == dumbpipe::HANDSHAKE, "invalid handshake");
tracing::trace!("handshake verified");
}
tracing::trace!("connecting to backend socket {:?}", socket_path);
let connection = UnixStream::connect(&socket_path)
.await
.context(format!("error connecting to {socket_path:?}"))?;
tracing::trace!("connected to backend socket");
let (read, write) = connection.into_split();
tracing::trace!("starting forward_bidi");
forward_bidi(read, write, r, s).await?;
tracing::trace!("forward_bidi finished");
Ok(())
}
loop {
let incoming = select! {
incoming = endpoint.accept() => incoming,
_ = tokio::signal::ctrl_c() => {
eprintln!("got ctrl-c, exiting");
break;
}
};
let Some(incoming) = incoming else {
break;
};
let Ok(connecting) = incoming.accept() else {
break;
};
let socket_path = socket_path.clone();
let handshake = !args.common.is_custom_alpn();
tokio::spawn(async move {
if let Err(cause) = handle_endpoint_accept(connecting, socket_path, handshake).await {
// log error at warn level
//
// we should know about it, but it's not fatal
tracing::warn!("error handling connection: {}", cause);
}
});
}
Ok(())
}
#[cfg(unix)]
/// A RAII guard to clean up a Unix socket file.
struct UnixSocketGuard {
path: PathBuf,
}
#[cfg(unix)]
impl Drop for UnixSocketGuard {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_file(&self.path) {
if e.kind() != std::io::ErrorKind::NotFound {
tracing::error!("failed to remove socket file {:?}: {}", self.path, e);
}
}
}
}
#[cfg(unix)]
/// Listen on a Unix socket and forward connections to an endpoint.
async fn connect_unix(args: ConnectUnixArgs) -> Result<()> {
let socket_path = args.socket_path.clone();
let secret_key = get_or_create_secret()?;
let endpoint = create_endpoint(secret_key, &args.common, vec![])
.await
.context("unable to bind endpoint")?;
tracing::info!("unix listening on {:?}", socket_path);
// Wait for our own endpoint to be ready before trying to connect.
endpoint.online().await;
// Remove existing socket file if it exists
if let Err(e) = tokio::fs::remove_file(&socket_path).await {
if e.kind() != io::ErrorKind::NotFound {
snafu::whatever!("failed to remove existing socket file: {}", e);
}
}
let addr = args.ticket.endpoint_addr();
tracing::info!("connecting to remote endpoint: {:?}", addr);
let connection = endpoint
.connect(addr.clone(), &args.common.alpn()?)
.await
.context("failed to connect to remote endpoint")?;
tracing::info!("connected to remote endpoint successfully");
let unix_listener = UnixListener::bind(&socket_path)
.with_context(|| format!("failed to bind Unix socket at {socket_path:?}"))?;
tracing::info!("bound local unix socket: {:?}", socket_path);
let _guard = UnixSocketGuard {
path: socket_path.clone(),
};
async fn handle_unix_accept(
next: io::Result<(UnixStream, tokio::net::unix::SocketAddr)>,
connection: iroh::endpoint::Connection,
handshake: bool,
) -> Result<()> {
tracing::trace!("handling new local connection");
let (unix_stream, unix_addr) = next.context("error accepting unix connection")?;
let (unix_recv, unix_send) = unix_stream.into_split();
tracing::trace!("got unix connection from {:?}", unix_addr);
tracing::trace!("opening bidi stream");
let (mut endpoint_send, endpoint_recv) = connection
.open_bi()
.await
.context("error opening bidi stream")?;
tracing::trace!("bidi stream opened");
// send the handshake unless we are using a custom alpn
// when using a custom alpn, everything is up to the user
if handshake {
tracing::trace!("sending handshake");
// the connecting side must write first. we don't know if there will be something
// on stdin, so just write a handshake.
endpoint_send.write_all(&dumbpipe::HANDSHAKE).await.e()?;
tracing::trace!("handshake sent");
}
tracing::trace!("starting forward_bidi");
forward_bidi(unix_recv, unix_send, endpoint_recv, endpoint_send).await?;
tracing::trace!("forward_bidi finished");
Ok(())
}
tracing::info!("entering accept loop");
loop {
// also wait for ctrl-c here so we can use it before accepting a connection
let next = tokio::select! {
stream = unix_listener.accept() => stream,
_ = tokio::signal::ctrl_c() => {
eprintln!("got ctrl-c, exiting");
break;
}
};
tracing::trace!("accepted a local connection");
let connection = connection.clone();
let handshake = !args.common.is_custom_alpn();
tokio::spawn(async move {
tracing::trace!("spawning handler task");
if let Err(cause) = handle_unix_accept(next, connection, handshake).await {
// log error at warn level
//
// we should know about it, but it's not fatal
tracing::warn!("error handling connection: {}", cause);
}
tracing::trace!("handler task finished");
});
}
Ok(())
}
async fn generate_ticket() -> Result<()> {
let secret_key = get_or_create_secret()?;
let public_key = secret_key.public();
let addr = EndpointAddr::new(public_key);
let ticket = EndpointTicket::new(addr);
println!("{}", ticket);
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse();
let res = match args.command {
Commands::GenerateTicket => generate_ticket().await,
Commands::Listen(args) => listen_stdio(args).await,
Commands::ListenTcp(args) => listen_tcp(args).await,
Commands::Connect(args) => connect_stdio(args).await,
Commands::ConnectTcp(args) => connect_tcp(args).await,
#[cfg(unix)]
Commands::ListenUnix(args) => listen_unix(args).await,
#[cfg(unix)]
Commands::ConnectUnix(args) => connect_unix(args).await,
};
match res {
Ok(()) => std::process::exit(0),
Err(e) => {
eprintln!("error: {e}");
std::process::exit(1)
}
}
}