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
#[cfg(feature = "tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
mod tls;
#[cfg(feature = "tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
pub use tls::*;
use aggligator::{
alc::Stream,
cfg::Cfg,
connect::{connect, Outgoing},
control::{Direction, Link},
dump::dump_to_json_line_file,
};
use futures::Future;
use network_interface::{NetworkInterface, NetworkInterfaceConfig};
use std::{
collections::HashSet,
fmt,
future::IntoFuture,
io::{Error, ErrorKind, Result},
net::{IpAddr, SocketAddr},
path::{Path, PathBuf},
pin::Pin,
time::Duration,
};
use tokio::{
io::{AsyncRead, AsyncWrite},
net::{lookup_host, TcpListener, TcpSocket, TcpStream},
sync::{mpsc, watch},
time::{sleep, timeout},
};
use aggligator::{
connect::{Listener, Server},
control::Control,
io::{IoRx, IoRxBox, IoTx, IoTxBox},
};
use crate::TagError;
pub const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
pub const LINK_RETRY_INTERVAL: Duration = Duration::from_secs(10);
pub const DUMP_BUFFER: usize = 8192;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IpVersion {
IPv4,
IPv6,
#[default]
Both,
}
impl IpVersion {
pub fn from_args(only_ipv4: bool, only_ipv6: bool) -> Result<Self> {
match (only_ipv4, only_ipv6) {
(false, false) => Ok(Self::Both),
(true, false) => Ok(Self::IPv4),
(false, true) => Ok(Self::IPv6),
(true, true) => {
Err(Error::new(ErrorKind::InvalidInput, "IPv4 and IPv6 options are mutally exclusive"))
}
}
}
pub fn is_only_ipv4(&self) -> bool {
matches!(self, Self::IPv4)
}
pub fn is_only_ipv6(&self) -> bool {
matches!(self, Self::IPv6)
}
}
#[derive(Debug, Clone)]
pub struct TargetSet {
targets: Vec<String>,
version: IpVersion,
}
impl fmt::Display for TargetSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.targets.len() > 1 {
write!(f, "[{}]", self.targets.join(", "))
} else {
write!(f, "{}", &self.targets[0])
}
}
}
impl TargetSet {
pub async fn new(mut targets: Vec<String>, default_port: u16, version: IpVersion) -> Result<Self> {
if targets.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "at least one target is required"));
}
for target in &mut targets {
if !target.contains(':') {
target.push_str(&format!(":{}", default_port));
}
}
let this = Self { targets, version };
let addrs = this.resolve().await?;
tracing::info!("{} resolves to: {:?}", &this, addrs);
Ok(this)
}
pub async fn resolve(&self) -> Result<Vec<SocketAddr>> {
let mut all_addrs = HashSet::new();
for target in &self.targets {
all_addrs.extend(lookup_host(target).await?.filter(|addr| {
!((addr.is_ipv4() && self.version.is_only_ipv6())
|| (addr.is_ipv6() && self.version.is_only_ipv4()))
}));
}
let mut all_addrs: Vec<_> = all_addrs.into_iter().collect();
all_addrs.sort();
if all_addrs.is_empty() {
return Err(Error::new(ErrorKind::NotFound, "cannot resolve IP address of target"));
}
Ok(all_addrs)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TcpLinkTag {
pub interface: String,
pub remote: SocketAddr,
pub direction: Direction,
}
impl fmt::Display for TcpLinkTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let dir = match self.direction {
Direction::Incoming => "<-",
Direction::Outgoing => "->",
};
write!(f, "{:16} {dir} {}", &self.interface, self.remote)
}
}
impl TcpLinkTag {
pub fn new(interface: &str, remote: SocketAddr, direction: Direction) -> Self {
Self { interface: interface.to_string(), remote, direction }
}
}
pub fn local_interfaces() -> Result<Vec<NetworkInterface>> {
Ok(NetworkInterface::show()
.map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?
.into_iter()
.filter(|iface| !iface.name.starts_with("ifb"))
.collect())
}
pub fn interface_names_for_target(interfaces: &[NetworkInterface], target: SocketAddr) -> HashSet<String> {
interfaces
.iter()
.cloned()
.filter_map(|iface| match &iface.addr {
Some(addr) if addr.ip().is_unspecified() => None,
Some(addr) if addr.ip().is_loopback() != target.ip().is_loopback() => None,
Some(addr) if addr.ip().is_ipv4() && target.is_ipv4() => Some(iface.name),
Some(addr) if addr.ip().is_ipv6() && target.is_ipv6() => Some(iface.name),
_ => None,
})
.collect()
}
pub async fn monitor_potential_link_tags(
target: TargetSet, tags_tx: watch::Sender<Vec<TcpLinkTag>>,
) -> Result<()> {
loop {
let interfaces = local_interfaces()?;
let mut tags = Vec::new();
for target in target.resolve().await? {
for iface in interface_names_for_target(&interfaces, target) {
let tag = TcpLinkTag::new(&iface, target, Direction::Outgoing);
tags.push(tag.clone());
}
}
tags.sort();
if tags_tx.send(tags).is_err() {
break;
}
sleep(LINK_RETRY_INTERVAL).await;
}
Ok(())
}
pub async fn tcp_connect_links(control: Control<IoTxBox, IoRxBox, TcpLinkTag>, target: TargetSet) -> Result<()> {
tcp_connect_links_and_monitor(
control,
target,
watch::channel(Default::default()).0,
mpsc::channel(1).0,
watch::channel(Default::default()).1,
)
.await
}
pub async fn tcp_connect_links_wrapped<R, W, F, Fut>(
control: Control<IoTx<W>, IoRx<R>, TcpLinkTag>, target: TargetSet, wrap_fn: F,
) -> Result<()>
where
F: FnOnce(TcpStream) -> Fut + Send + Sync + Clone + 'static,
Fut: Future<Output = Result<(R, W)>> + Send,
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
tcp_connect_links_and_monitor_wrapped(
control,
target,
wrap_fn,
watch::channel(Default::default()).0,
mpsc::channel(1).0,
watch::channel(Default::default()).1,
)
.await
}
async fn box_tcp_stream(
stream: TcpStream,
) -> Result<(Pin<Box<dyn AsyncRead + Send + Sync + 'static>>, Pin<Box<dyn AsyncWrite + Send + Sync + 'static>>)> {
let (r, w) = stream.into_split();
Ok((Box::pin(r), Box::pin(w)))
}
pub async fn tcp_connect_links_and_monitor(
control: Control<IoTxBox, IoRxBox, TcpLinkTag>, target: TargetSet, tags_tx: watch::Sender<Vec<TcpLinkTag>>,
tag_err_tx: mpsc::Sender<TagError<TcpLinkTag>>, disabled_tags_rx: watch::Receiver<HashSet<TcpLinkTag>>,
) -> Result<()> {
tcp_connect_links_and_monitor_wrapped(control, target, box_tcp_stream, tags_tx, tag_err_tx, disabled_tags_rx)
.await
}
pub async fn tcp_connect_links_and_monitor_wrapped<R, W, F, Fut>(
control: Control<IoTx<W>, IoRx<R>, TcpLinkTag>, target: TargetSet, wrap_fn: F,
tags_tx: watch::Sender<Vec<TcpLinkTag>>, tag_err_tx: mpsc::Sender<TagError<TcpLinkTag>>,
mut disabled_tags_rx: watch::Receiver<HashSet<TcpLinkTag>>,
) -> Result<()>
where
F: FnOnce(TcpStream) -> Fut + Send + Sync + Clone + 'static,
Fut: Future<Output = Result<(R, W)>> + Send,
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
async fn do_connect(iface: &[u8], ifaces: &[NetworkInterface], target: SocketAddr) -> Result<TcpStream> {
let socket = match target.ip() {
IpAddr::V4(_) => TcpSocket::new_v4(),
IpAddr::V6(_) => TcpSocket::new_v6(),
}?;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
socket.bind_device(Some(iface))?;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
let _ = ifaces;
#[cfg(not(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))]
{
let mut bound = false;
for ifn in ifaces {
if ifn.name.as_bytes() == iface {
let Some(addr) = ifn.addr else { continue };
match (addr.ip(), target.ip()) {
(IpAddr::V4(_), IpAddr::V4(_)) => (),
(IpAddr::V6(_), IpAddr::V6(_)) => (),
_ => continue,
}
if addr.ip().is_loopback() != target.ip().is_loopback() {
continue;
}
tracing::debug!("binding to {addr:?} on interface {}", &ifn.name);
socket.bind(SocketAddr::new(addr.ip(), 0))?;
bound = true;
break;
}
}
if !bound {
return Err(Error::new(ErrorKind::NotFound, "no IP address for interface"));
}
}
socket.connect(target).await
}
let mut running = HashSet::new();
let (disconnected_tx, mut disconnected_rx) = mpsc::channel(16);
while !control.is_terminated() {
tracing::debug!("Trying to establish new links...");
let interfaces = local_interfaces()?;
let disabled = disabled_tags_rx.borrow_and_update().clone();
let mut tags = Vec::new();
while let Ok(tag) = disconnected_rx.try_recv() {
running.remove(&tag);
}
match target.resolve().await {
Ok(targets) => {
for target in targets {
for iface in interface_names_for_target(&interfaces, target) {
let tag = TcpLinkTag::new(&iface, target, Direction::Outgoing);
tags.push(tag.clone());
if running.contains(&tag) || disabled.contains(&tag) {
continue;
}
running.insert(tag.clone());
let control = control.clone();
let interfaces = interfaces.clone();
let disconnected_tx = disconnected_tx.clone();
let tag_err_tx = tag_err_tx.clone();
let wrap_fn = wrap_fn.clone();
tokio::spawn(async move {
tracing::debug!("Trying TCP connection for {tag}");
match timeout(TCP_CONNECT_TIMEOUT, do_connect(iface.as_bytes(), &interfaces, target))
.await
{
Ok(Ok(strm)) => {
tracing::debug!("TCP connection established for {tag}");
match timeout(TCP_CONNECT_TIMEOUT, wrap_fn(strm)).await {
Ok(Ok((read, write))) => {
match control.add_io(read, write, tag.clone(), iface.as_bytes()).await
{
Ok(link) => {
tracing::info!("Link established for {tag}");
let reason = link.disconnected().await;
tracing::warn!("Link for {tag} disconnected: {reason}");
let _ = tag_err_tx
.send(TagError::new(control.id(), link.tag(), reason))
.await;
}
Err(err) => {
tracing::warn!("Establishing link for {tag} failed: {err}");
let _ = tag_err_tx
.send(TagError::new(control.id(), &tag, err))
.await;
}
}
}
Ok(Err(err)) => {
tracing::warn!("Wrapping connection to {tag} failed: {err}");
let _ = tag_err_tx.send(TagError::new(control.id(), &tag, err)).await;
}
Err(_) => {
tracing::warn!("Wrapping connection to {tag} timed out");
let _ = tag_err_tx
.send(TagError::new(control.id(), &tag, "wrapping timeout"))
.await;
}
}
}
Ok(Err(err)) => {
tracing::warn!("TCP connection for {tag} failed: {}", &err);
let _ = tag_err_tx.send(TagError::new(control.id(), &tag, err)).await;
}
Err(_) => {
tracing::warn!("TCP connection for {tag} timed out");
let _ = tag_err_tx
.send(TagError::new(control.id(), &tag, "TCP connect timeout"))
.await;
}
}
let _ = disconnected_tx.send(tag.clone()).await;
});
}
}
}
Err(err) => tracing::warn!("cannot lookup target: {err}"),
}
tags.sort();
tags_tx.send_replace(tags);
sleep(LINK_RETRY_INTERVAL).await;
}
Ok(())
}
#[allow(clippy::type_complexity)]
pub async fn alc_listen<R, W, F>(
listener: Listener<IoTx<W>, IoRx<R>, TcpLinkTag>, work_fn: impl Fn(Stream) -> F,
) -> Result<()>
where
F: Future<Output = ()> + Send + 'static,
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
alc_listen_and_monitor(listener, work_fn, mpsc::channel(1).0, None).await
}
#[allow(clippy::type_complexity)]
pub async fn alc_listen_and_monitor<R, W, F>(
mut listener: Listener<IoTx<W>, IoRx<R>, TcpLinkTag>, work_fn: impl Fn(Stream) -> F,
control_tx: mpsc::Sender<(Control<IoTx<W>, IoRx<R>, TcpLinkTag>, String)>, dump: Option<PathBuf>,
) -> Result<()>
where
F: Future<Output = ()> + Send + 'static,
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
loop {
let mut inc = listener.next().await.map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?;
let id = inc.id();
tracing::info!("Accepting incoming connection {id} consisting of links {:?}", inc.link_tags());
let (mut task, ch, mut control) = inc.accept().await;
#[cfg(feature = "dump")]
if let Some(dump) = &dump {
let (tx, rx) = mpsc::channel(DUMP_BUFFER);
task.dump(tx);
tokio::spawn(aggligator::dump::dump_to_json_line_file(dump.clone(), rx));
}
#[cfg(not(feature = "dump"))]
let _ = dump;
task.set_link_filter(tcp_link_filter);
tokio::spawn(task.into_future());
if control_tx.is_closed() {
tokio::spawn(async move {
while !control.is_terminated() {
tracing::info!("Connection {id} now consists of links {:?}", control.links());
control.links_changed().await;
}
tracing::info!("Connection {id} terminated");
});
} else {
let _ = control_tx.send((control, String::new())).await;
}
let f = work_fn(ch.into_stream());
tokio::spawn(async move {
f.await;
tracing::info!("Incoming connection {id} done");
});
}
}
pub async fn alc_connect<R, W>(cfg: Cfg) -> (Outgoing, Control<IoTx<W>, IoRx<R>, TcpLinkTag>)
where
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
alc_connect_and_dump(cfg, None::<PathBuf>).await
}
pub async fn alc_connect_and_dump<R, W>(
cfg: Cfg, dump: Option<impl AsRef<Path>>,
) -> (Outgoing, Control<IoTx<W>, IoRx<R>, TcpLinkTag>)
where
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
let (mut task, outgoing, control) = connect(cfg);
if let Some(dump) = &dump {
let (tx, rx) = mpsc::channel(DUMP_BUFFER);
task.dump(tx);
let dump = dump.as_ref().to_path_buf();
tokio::spawn(dump_to_json_line_file(dump, rx));
}
tokio::spawn(task.into_future());
(outgoing, control)
}
pub async fn tcp_link_filter(new: Link<TcpLinkTag>, existing: Vec<Link<TcpLinkTag>>) -> bool {
let intro = format!(
"Judging {} link {} {} ({}) on {}",
new.direction(),
match new.direction() {
Direction::Incoming => "from",
Direction::Outgoing => "to",
},
new.tag().remote,
String::from_utf8_lossy(new.remote_user_data()),
&new.tag().interface
);
match existing.into_iter().find(|link| {
link.tag().interface == new.tag().interface && link.remote_user_data() == new.remote_user_data()
}) {
Some(other) => {
tracing::debug!("{intro} => link {} is redundant, rejecting.", other.tag().remote);
false
}
None => {
tracing::debug!("{intro} => accepted.");
true
}
}
}
pub async fn tcp_listen(server: Server<IoTxBox, IoRxBox, TcpLinkTag>, addr: SocketAddr) -> Result<()> {
tcp_listen_wrapped(server, addr, box_tcp_stream).await
}
pub async fn tcp_listen_wrapped<R, W, F, Fut>(
server: Server<IoTx<W>, IoRx<R>, TcpLinkTag>, addr: SocketAddr, wrap_fn: F,
) -> Result<()>
where
F: FnOnce(TcpStream) -> Fut + Send + Sync + Clone + 'static,
Fut: Future<Output = Result<(R, W)>> + Send,
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
let tcp_listener = TcpListener::bind(addr).await?;
tracing::info!("Listening on {}", addr);
loop {
let (socket, mut src) = tcp_listener.accept().await?;
let mut local_addr = socket.local_addr()?;
if let IpAddr::V6(addr) = src.ip() {
if let Some(addr) = addr.to_ipv4_mapped() {
src.set_ip(addr.into());
}
}
if let IpAddr::V6(addr) = local_addr.ip() {
if let Some(addr) = addr.to_ipv4_mapped() {
local_addr.set_ip(addr.into());
}
}
let interfaces = local_interfaces()?;
let Some(interface) = interfaces
.into_iter()
.find_map(|interface| {
interface
.addr
.map(|addr| addr.ip() == local_addr.ip())
.unwrap_or_default()
.then_some(interface.name)
})
else {
tracing::warn!("Interface for incoming connection from {src} to {local_addr} not found, rejecting.");
continue;
};
tracing::debug!("Accepted TCP connection from {src} on {interface}");
let tag = TcpLinkTag { interface: interface.clone(), remote: src, direction: Direction::Incoming };
let server = server.clone();
let wrap_fn = wrap_fn.clone();
tokio::spawn(async move {
let (read, write) = match wrap_fn(socket).await {
Ok(s) => s,
Err(err) => {
tracing::warn!("Wrapping connection from {src} failed: {err}");
return;
}
};
match server.add_incoming_io(read, write, tag, interface.as_bytes()).await {
Ok(link) => {
tracing::info!("Added incoming link: {link:?}");
tokio::spawn(async move {
let reason = link.disconnected().await;
tracing::warn!("Incoming link {src} disconnected: {reason:?}");
});
}
Err(err) => {
tracing::warn!("Adding incoming link failed: {err}");
}
}
});
}
}