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
use async_trait::async_trait;
use futures::{future, FutureExt};
use network_interface::{NetworkInterface, NetworkInterfaceConfig};
use std::{
any::Any,
cmp::Ordering,
collections::HashSet,
fmt,
hash::{Hash, Hasher},
io::{Error, ErrorKind, Result},
net::{IpAddr, SocketAddr},
time::Duration,
};
use tokio::{
net::{lookup_host, TcpListener, TcpSocket},
sync::{mpsc, watch},
time::sleep,
};
use super::{AcceptedIoBox, AcceptingTransport, ConnectingTransport, IoBox, LinkTag, LinkTagBox};
use aggligator::{control::Direction, Link};
static NAME: &str = "tcp";
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IpVersion {
IPv4,
IPv6,
#[default]
Both,
}
impl IpVersion {
pub fn from_only(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, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TcpLinkTag {
pub interface: Vec<u8>,
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} {}", String::from_utf8_lossy(&self.interface), self.remote)
}
}
impl TcpLinkTag {
pub fn new(interface: &[u8], remote: SocketAddr, direction: Direction) -> Self {
Self { interface: interface.to_vec(), remote, direction }
}
}
impl LinkTag for TcpLinkTag {
fn transport_name(&self) -> &str {
NAME
}
fn direction(&self) -> Direction {
self.direction
}
fn user_data(&self) -> Vec<u8> {
self.interface.clone()
}
fn as_any(&self) -> &dyn Any {
self
}
fn box_clone(&self) -> LinkTagBox {
Box::new(self.clone())
}
fn dyn_cmp(&self, other: &dyn LinkTag) -> Ordering {
let other = other.as_any().downcast_ref::<Self>().unwrap();
Ord::cmp(self, other)
}
fn dyn_hash(&self, mut state: &mut dyn Hasher) {
Hash::hash(self, &mut state)
}
}
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())
}
#[derive(Debug, Clone)]
pub struct TcpConnector {
hosts: Vec<String>,
ip_version: IpVersion,
resolve_interval: Duration,
}
impl fmt::Display for TcpConnector {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.hosts.len() > 1 {
write!(f, "[{}]", self.hosts.join(", "))
} else {
write!(f, "{}", &self.hosts[0])
}
}
}
impl TcpConnector {
pub async fn new(hosts: impl IntoIterator<Item = String>, default_port: u16) -> Result<Self> {
let mut hosts: Vec<_> = hosts.into_iter().collect();
if hosts.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "at least one host is required"));
}
for host in &mut hosts {
if !host.contains(':') {
host.push_str(&format!(":{default_port}"));
}
}
let this = Self { hosts, ip_version: IpVersion::Both, resolve_interval: Duration::from_secs(10) };
let addrs = this.resolve().await?;
if addrs.is_empty() {
return Err(Error::new(ErrorKind::NotFound, "cannot resolve IP address of host"));
}
tracing::info!("{} resolves to: {:?}", &this, addrs);
Ok(this)
}
pub fn set_ip_version(&mut self, ip_version: IpVersion) {
self.ip_version = ip_version;
}
pub fn set_resolve_interval(&mut self, resolve_interval: Duration) {
self.resolve_interval = resolve_interval;
}
async fn resolve(&self) -> Result<Vec<SocketAddr>> {
let mut all_addrs = HashSet::new();
for host in &self.hosts {
all_addrs.extend(lookup_host(host).await?.filter(|addr| {
!((addr.is_ipv4() && self.ip_version.is_only_ipv6())
|| (addr.is_ipv6() && self.ip_version.is_only_ipv4()))
}));
}
let mut all_addrs: Vec<_> = all_addrs.into_iter().collect();
all_addrs.sort();
Ok(all_addrs)
}
fn interface_names_for_target(interfaces: &[NetworkInterface], target: SocketAddr) -> HashSet<Vec<u8>> {
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.as_bytes().to_vec()),
Some(addr) if addr.ip().is_ipv6() && target.is_ipv6() => Some(iface.name.as_bytes().to_vec()),
_ => None,
})
.collect()
}
fn bind_socket_to_interface(socket: &TcpSocket, interface: &[u8], remote: IpAddr) -> Result<()> {
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
{
let _ = remote;
socket.bind_device(Some(interface))
}
#[cfg(not(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))]
{
for ifn in local_interfaces()? {
if ifn.name.as_bytes() == interface {
let Some(addr) = ifn.addr else { continue };
match (addr.ip(), remote) {
(IpAddr::V4(_), IpAddr::V4(_)) => (),
(IpAddr::V6(_), IpAddr::V6(_)) => (),
_ => continue,
}
if addr.ip().is_loopback() != remote.is_loopback() {
continue;
}
tracing::debug!("binding to {addr:?} on interface {}", &ifn.name);
socket.bind(SocketAddr::new(addr.ip(), 0))?;
return Ok(());
}
}
Err(Error::new(ErrorKind::NotFound, "no IP address for interface"))
}
}
}
#[async_trait]
impl ConnectingTransport for TcpConnector {
fn name(&self) -> &str {
NAME
}
async fn link_tags(&self, tx: watch::Sender<HashSet<LinkTagBox>>) -> Result<()> {
loop {
let interfaces = local_interfaces()?;
let mut tags: HashSet<LinkTagBox> = HashSet::new();
for addr in self.resolve().await? {
for iface in Self::interface_names_for_target(&interfaces, addr) {
let tag = TcpLinkTag::new(&iface, addr, Direction::Outgoing);
tags.insert(Box::new(tag.clone()));
}
}
tx.send_if_modified(|v| {
if *v != tags {
*v = tags;
true
} else {
false
}
});
sleep(self.resolve_interval).await;
}
}
async fn connect(&self, tag: &dyn LinkTag) -> Result<IoBox> {
let tag: &TcpLinkTag = tag.as_any().downcast_ref().unwrap();
let socket = match tag.remote.ip() {
IpAddr::V4(_) => TcpSocket::new_v4(),
IpAddr::V6(_) => TcpSocket::new_v6(),
}?;
Self::bind_socket_to_interface(&socket, &tag.interface, tag.remote.ip())?;
let stream = socket.connect(tag.remote).await?;
let _ = stream.set_nodelay(true);
let (rh, wh) = stream.into_split();
Ok(IoBox::new(rh, wh))
}
async fn link_filter(&self, new: &Link<LinkTagBox>, existing: &[Link<LinkTagBox>]) -> bool {
let Some(new_tag) = new.tag().as_any().downcast_ref::<TcpLinkTag>() else { return true };
let intro = format!(
"Judging {} TCP link {} {} ({}) on {}",
new.direction(),
match new.direction() {
Direction::Incoming => "from",
Direction::Outgoing => "to",
},
new_tag.remote,
String::from_utf8_lossy(new.remote_user_data()),
String::from_utf8_lossy(&new_tag.interface)
);
match existing.iter().find(|link| {
let Some(tag) = link.tag().as_any().downcast_ref::<TcpLinkTag>() else { return false };
tag.interface == new_tag.interface && link.remote_user_data() == new.remote_user_data()
}) {
Some(other) => {
let other_tag = other.tag().as_any().downcast_ref::<TcpLinkTag>().unwrap();
tracing::debug!("{intro} => link {} is redundant, rejecting.", other_tag.remote);
false
}
None => {
tracing::debug!("{intro} => accepted.");
true
}
}
}
}
#[derive(Debug)]
pub struct TcpAcceptor {
listeners: Vec<TcpListener>,
}
impl fmt::Display for TcpAcceptor {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let addrs: Vec<_> = self
.listeners
.iter()
.filter_map(|listener| listener.local_addr().ok().map(|addr| addr.to_string()))
.collect();
if addrs.len() > 1 {
write!(f, "[{}]", addrs.join(", "))
} else {
write!(f, "{}", addrs[0])
}
}
}
impl TcpAcceptor {
pub async fn new(addrs: impl IntoIterator<Item = SocketAddr>) -> Result<Self> {
let mut listeners = Vec::new();
for addr in addrs {
listeners.push(TcpListener::bind(addr).await?);
}
if listeners.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "at least one listening address is required"));
}
Ok(Self { listeners })
}
}
#[async_trait]
impl AcceptingTransport for TcpAcceptor {
fn name(&self) -> &str {
NAME
}
async fn listen(&self, tx: mpsc::Sender<AcceptedIoBox>) -> Result<()> {
loop {
let (res, _, _) =
future::select_all(self.listeners.iter().map(|listener| listener.accept().boxed())).await;
let (socket, mut remote) = res?;
let mut local = socket.local_addr()?;
if let IpAddr::V6(addr) = remote.ip() {
if let Some(addr) = addr.to_ipv4_mapped() {
remote.set_ip(addr.into());
}
}
if let IpAddr::V6(addr) = local.ip() {
if let Some(addr) = addr.to_ipv4_mapped() {
local.set_ip(addr.into());
}
}
let interfaces = local_interfaces()?;
let Some(interface) = interfaces
.into_iter()
.find_map(|interface| {
interface
.addr
.map(|addr| addr.ip() == local.ip())
.unwrap_or_default()
.then_some(interface.name.into_bytes())
})
else {
tracing::warn!("Interface for incoming connection from {remote} to {local} not found, rejecting.");
continue;
};
tracing::debug!("Accepted TCP connection from {remote} on {}", String::from_utf8_lossy(&interface));
let tag = TcpLinkTag { interface, remote, direction: Direction::Incoming };
let _ = socket.set_nodelay(true);
let (rh, wh) = socket.into_split();
let _ = tx.send(AcceptedIoBox::new(rh, wh, tag)).await;
}
}
}