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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
mod provider;
#[cfg(feature = "async-io")]
pub use provider::async_io;
#[cfg(feature = "tokio")]
pub use provider::tokio;
use futures::{
future::{self, Ready},
prelude::*,
stream::SelectAll,
};
use futures_timer::Delay;
use if_watch::IfEvent;
use libp2p_core::{
address_translation,
multiaddr::{Multiaddr, Protocol},
transport::{ListenerId, TransportError, TransportEvent},
};
use provider::{Incoming, Provider};
use socket2::{Domain, Socket, Type};
use std::{
collections::{HashSet, VecDeque},
io,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener},
pin::Pin,
sync::{Arc, RwLock},
task::{Context, Poll, Waker},
time::Duration,
};
#[derive(Clone, Debug)]
pub struct Config {
ttl: Option<u32>,
nodelay: Option<bool>,
backlog: u32,
enable_port_reuse: bool,
}
type Port = u16;
#[derive(Debug, Clone)]
enum PortReuse {
Disabled,
Enabled {
listen_addrs: Arc<RwLock<HashSet<(IpAddr, Port)>>>,
},
}
impl PortReuse {
fn register(&mut self, ip: IpAddr, port: Port) {
if let PortReuse::Enabled { listen_addrs } = self {
log::trace!("Registering for port reuse: {}:{}", ip, port);
listen_addrs
.write()
.expect("`register()` and `unregister()` never panic while holding the lock")
.insert((ip, port));
}
}
fn unregister(&mut self, ip: IpAddr, port: Port) {
if let PortReuse::Enabled { listen_addrs } = self {
log::trace!("Unregistering for port reuse: {}:{}", ip, port);
listen_addrs
.write()
.expect("`register()` and `unregister()` never panic while holding the lock")
.remove(&(ip, port));
}
}
fn local_dial_addr(&self, remote_ip: &IpAddr) -> Option<SocketAddr> {
if let PortReuse::Enabled { listen_addrs } = self {
for (ip, port) in listen_addrs
.read()
.expect("`local_dial_addr` never panic while holding the lock")
.iter()
{
if ip.is_ipv4() == remote_ip.is_ipv4()
&& ip.is_loopback() == remote_ip.is_loopback()
{
if remote_ip.is_ipv4() {
return Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), *port));
} else {
return Some(SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), *port));
}
}
}
}
None
}
}
impl Config {
pub fn new() -> Self {
Self {
ttl: None,
nodelay: None,
backlog: 1024,
enable_port_reuse: false,
}
}
pub fn ttl(mut self, value: u32) -> Self {
self.ttl = Some(value);
self
}
pub fn nodelay(mut self, value: bool) -> Self {
self.nodelay = Some(value);
self
}
pub fn listen_backlog(mut self, backlog: u32) -> Self {
self.backlog = backlog;
self
}
pub fn port_reuse(mut self, port_reuse: bool) -> Self {
self.enable_port_reuse = port_reuse;
self
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
pub struct Transport<T>
where
T: Provider + Send,
{
config: Config,
port_reuse: PortReuse,
listeners: SelectAll<ListenStream<T>>,
pending_events:
VecDeque<TransportEvent<<Self as libp2p_core::Transport>::ListenerUpgrade, io::Error>>,
}
impl<T> Transport<T>
where
T: Provider + Send,
{
pub fn new(config: Config) -> Self {
let port_reuse = if config.enable_port_reuse {
PortReuse::Enabled {
listen_addrs: Arc::new(RwLock::new(HashSet::new())),
}
} else {
PortReuse::Disabled
};
Transport {
config,
port_reuse,
..Default::default()
}
}
fn create_socket(&self, socket_addr: &SocketAddr) -> io::Result<Socket> {
let domain = if socket_addr.is_ipv4() {
Domain::IPV4
} else {
Domain::IPV6
};
let socket = Socket::new(domain, Type::STREAM, Some(socket2::Protocol::TCP))?;
if socket_addr.is_ipv6() {
socket.set_only_v6(true)?;
}
if let Some(ttl) = self.config.ttl {
socket.set_ttl(ttl)?;
}
if let Some(nodelay) = self.config.nodelay {
socket.set_nodelay(nodelay)?;
}
socket.set_reuse_address(true)?;
#[cfg(unix)]
if let PortReuse::Enabled { .. } = &self.port_reuse {
socket.set_reuse_port(true)?;
}
Ok(socket)
}
fn do_listen(
&mut self,
id: ListenerId,
socket_addr: SocketAddr,
) -> io::Result<ListenStream<T>> {
let socket = self.create_socket(&socket_addr)?;
socket.bind(&socket_addr.into())?;
socket.listen(self.config.backlog as _)?;
socket.set_nonblocking(true)?;
let listener: TcpListener = socket.into();
let local_addr = listener.local_addr()?;
if local_addr.ip().is_unspecified() {
return ListenStream::<T>::new(
id,
listener,
Some(T::new_if_watcher()?),
self.port_reuse.clone(),
);
}
self.port_reuse.register(local_addr.ip(), local_addr.port());
let listen_addr = ip_to_multiaddr(local_addr.ip(), local_addr.port());
self.pending_events.push_back(TransportEvent::NewAddress {
listener_id: id,
listen_addr,
});
ListenStream::<T>::new(id, listener, None, self.port_reuse.clone())
}
}
impl<T> Default for Transport<T>
where
T: Provider + Send,
{
fn default() -> Self {
let config = Config::default();
let port_reuse = if config.enable_port_reuse {
PortReuse::Enabled {
listen_addrs: Arc::new(RwLock::new(HashSet::new())),
}
} else {
PortReuse::Disabled
};
Transport {
port_reuse,
config,
listeners: SelectAll::new(),
pending_events: VecDeque::new(),
}
}
}
impl<T> libp2p_core::Transport for Transport<T>
where
T: Provider + Send + 'static,
T::Listener: Unpin,
T::Stream: Unpin,
{
type Output = T::Stream;
type Error = io::Error;
type Dial = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
type ListenerUpgrade = Ready<Result<Self::Output, Self::Error>>;
fn listen_on(&mut self, addr: Multiaddr) -> Result<ListenerId, TransportError<Self::Error>> {
let socket_addr = if let Ok(sa) = multiaddr_to_socketaddr(addr.clone()) {
sa
} else {
return Err(TransportError::MultiaddrNotSupported(addr));
};
let id = ListenerId::new();
log::debug!("listening on {}", socket_addr);
let listener = self
.do_listen(id, socket_addr)
.map_err(TransportError::Other)?;
self.listeners.push(listener);
Ok(id)
}
fn remove_listener(&mut self, id: ListenerId) -> bool {
if let Some(listener) = self.listeners.iter_mut().find(|l| l.listener_id == id) {
listener.close(Ok(()));
true
} else {
false
}
}
fn dial(&mut self, addr: Multiaddr) -> Result<Self::Dial, TransportError<Self::Error>> {
let socket_addr = if let Ok(socket_addr) = multiaddr_to_socketaddr(addr.clone()) {
if socket_addr.port() == 0 || socket_addr.ip().is_unspecified() {
return Err(TransportError::MultiaddrNotSupported(addr));
}
socket_addr
} else {
return Err(TransportError::MultiaddrNotSupported(addr));
};
log::debug!("dialing {}", socket_addr);
let socket = self
.create_socket(&socket_addr)
.map_err(TransportError::Other)?;
if let Some(addr) = self.port_reuse.local_dial_addr(&socket_addr.ip()) {
log::trace!("Binding dial socket to listen socket {}", addr);
socket.bind(&addr.into()).map_err(TransportError::Other)?;
}
socket
.set_nonblocking(true)
.map_err(TransportError::Other)?;
Ok(async move {
match socket.connect(&socket_addr.into()) {
Ok(()) => {}
Err(err) if err.raw_os_error() == Some(libc::EINPROGRESS) => {}
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
Err(err) => return Err(err),
};
let stream = T::new_stream(socket.into()).await?;
Ok(stream)
}
.boxed())
}
fn dial_as_listener(
&mut self,
addr: Multiaddr,
) -> Result<Self::Dial, TransportError<Self::Error>> {
self.dial(addr)
}
fn address_translation(&self, listen: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr> {
if !is_tcp_addr(listen) || !is_tcp_addr(observed) {
return None;
}
match &self.port_reuse {
PortReuse::Disabled => address_translation(listen, observed),
PortReuse::Enabled { .. } => Some(observed.clone()),
}
}
fn poll(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> {
if let Some(event) = self.pending_events.pop_front() {
return Poll::Ready(event);
}
match self.listeners.poll_next_unpin(cx) {
Poll::Ready(Some(transport_event)) => Poll::Ready(transport_event),
_ => Poll::Pending,
}
}
}
struct ListenStream<T>
where
T: Provider,
{
listener_id: ListenerId,
listen_addr: SocketAddr,
listener: T::Listener,
if_watcher: Option<T::IfWatcher>,
port_reuse: PortReuse,
sleep_on_error: Duration,
pause: Option<Delay>,
pending_event: Option<<Self as Stream>::Item>,
is_closed: bool,
close_listener_waker: Option<Waker>,
}
impl<T> ListenStream<T>
where
T: Provider,
{
fn new(
listener_id: ListenerId,
listener: TcpListener,
if_watcher: Option<T::IfWatcher>,
port_reuse: PortReuse,
) -> io::Result<Self> {
let listen_addr = listener.local_addr()?;
let listener = T::new_listener(listener)?;
Ok(ListenStream {
port_reuse,
listener,
listener_id,
listen_addr,
if_watcher,
pause: None,
sleep_on_error: Duration::from_millis(100),
pending_event: None,
is_closed: false,
close_listener_waker: None,
})
}
fn disable_port_reuse(&mut self) {
match &self.if_watcher {
Some(if_watcher) => {
for ip_net in T::addrs(if_watcher) {
self.port_reuse
.unregister(ip_net.addr(), self.listen_addr.port());
}
}
None => self
.port_reuse
.unregister(self.listen_addr.ip(), self.listen_addr.port()),
}
}
fn close(&mut self, reason: Result<(), io::Error>) {
if self.is_closed {
return;
}
self.pending_event = Some(TransportEvent::ListenerClosed {
listener_id: self.listener_id,
reason,
});
self.is_closed = true;
if let Some(waker) = self.close_listener_waker.take() {
waker.wake();
}
}
fn poll_if_addr(&mut self, cx: &mut Context<'_>) -> Poll<<Self as Stream>::Item> {
let if_watcher = match self.if_watcher.as_mut() {
Some(if_watcher) => if_watcher,
None => return Poll::Pending,
};
let my_listen_addr_port = self.listen_addr.port();
while let Poll::Ready(Some(event)) = if_watcher.poll_next_unpin(cx) {
match event {
Ok(IfEvent::Up(inet)) => {
let ip = inet.addr();
if self.listen_addr.is_ipv4() == ip.is_ipv4() {
let ma = ip_to_multiaddr(ip, my_listen_addr_port);
log::debug!("New listen address: {}", ma);
self.port_reuse.register(ip, my_listen_addr_port);
return Poll::Ready(TransportEvent::NewAddress {
listener_id: self.listener_id,
listen_addr: ma,
});
}
}
Ok(IfEvent::Down(inet)) => {
let ip = inet.addr();
if self.listen_addr.is_ipv4() == ip.is_ipv4() {
let ma = ip_to_multiaddr(ip, my_listen_addr_port);
log::debug!("Expired listen address: {}", ma);
self.port_reuse.unregister(ip, my_listen_addr_port);
return Poll::Ready(TransportEvent::AddressExpired {
listener_id: self.listener_id,
listen_addr: ma,
});
}
}
Err(error) => {
self.pause = Some(Delay::new(self.sleep_on_error));
return Poll::Ready(TransportEvent::ListenerError {
listener_id: self.listener_id,
error,
});
}
}
}
Poll::Pending
}
}
impl<T> Drop for ListenStream<T>
where
T: Provider,
{
fn drop(&mut self) {
self.disable_port_reuse();
}
}
impl<T> Stream for ListenStream<T>
where
T: Provider,
T::Listener: Unpin,
T::Stream: Unpin,
{
type Item = TransportEvent<Ready<Result<T::Stream, io::Error>>, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
if let Some(mut pause) = self.pause.take() {
match pause.poll_unpin(cx) {
Poll::Ready(_) => {}
Poll::Pending => {
self.pause = Some(pause);
return Poll::Pending;
}
}
}
if let Some(event) = self.pending_event.take() {
return Poll::Ready(Some(event));
}
if self.is_closed {
return Poll::Ready(None);
}
if let Poll::Ready(event) = self.poll_if_addr(cx) {
return Poll::Ready(Some(event));
}
match T::poll_accept(&mut self.listener, cx) {
Poll::Ready(Ok(Incoming {
local_addr,
remote_addr,
stream,
})) => {
let local_addr = ip_to_multiaddr(local_addr.ip(), local_addr.port());
let remote_addr = ip_to_multiaddr(remote_addr.ip(), remote_addr.port());
log::debug!("Incoming connection from {} at {}", remote_addr, local_addr);
return Poll::Ready(Some(TransportEvent::Incoming {
listener_id: self.listener_id,
upgrade: future::ok(stream),
local_addr,
send_back_addr: remote_addr,
}));
}
Poll::Ready(Err(error)) => {
self.pause = Some(Delay::new(self.sleep_on_error));
return Poll::Ready(Some(TransportEvent::ListenerError {
listener_id: self.listener_id,
error,
}));
}
Poll::Pending => {}
}
self.close_listener_waker = Some(cx.waker().clone());
Poll::Pending
}
}
fn multiaddr_to_socketaddr(mut addr: Multiaddr) -> Result<SocketAddr, ()> {
let mut port = None;
while let Some(proto) = addr.pop() {
match proto {
Protocol::Ip4(ipv4) => match port {
Some(port) => return Ok(SocketAddr::new(ipv4.into(), port)),
None => return Err(()),
},
Protocol::Ip6(ipv6) => match port {
Some(port) => return Ok(SocketAddr::new(ipv6.into(), port)),
None => return Err(()),
},
Protocol::Tcp(portnum) => match port {
Some(_) => return Err(()),
None => port = Some(portnum),
},
Protocol::P2p(_) => {}
_ => return Err(()),
}
}
Err(())
}
fn ip_to_multiaddr(ip: IpAddr, port: u16) -> Multiaddr {
Multiaddr::empty().with(ip.into()).with(Protocol::Tcp(port))
}
fn is_tcp_addr(addr: &Multiaddr) -> bool {
use Protocol::*;
let mut iter = addr.iter();
let first = match iter.next() {
None => return false,
Some(p) => p,
};
let second = match iter.next() {
None => return false,
Some(p) => p,
};
matches!(first, Ip4(_) | Ip6(_) | Dns(_) | Dns4(_) | Dns6(_)) && matches!(second, Tcp(_))
}
#[deprecated(since = "0.37.0", note = "Use `Config` instead.")]
pub type GenTcpConfig = Config;
#[cfg(feature = "async-io")]
#[deprecated(since = "0.37.0", note = "Use `async_io::Transport` instead.")]
pub type TcpTransport = Transport<async_io::Tcp>;
#[cfg(feature = "tokio")]
#[deprecated(since = "0.37.0", note = "Use `tokio::Transport` instead.")]
pub type TokioTcpTransport = Transport<tokio::Tcp>;
#[cfg(test)]
mod tests {
use super::*;
use futures::{
channel::{mpsc, oneshot},
future::poll_fn,
};
use libp2p_core::PeerId;
use libp2p_core::Transport as _;
#[test]
fn multiaddr_to_tcp_conversion() {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
assert!(
multiaddr_to_socketaddr("/ip4/127.0.0.1/udp/1234".parse::<Multiaddr>().unwrap())
.is_err()
);
assert_eq!(
multiaddr_to_socketaddr("/ip4/127.0.0.1/tcp/12345".parse::<Multiaddr>().unwrap()),
Ok(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
12345,
))
);
assert_eq!(
multiaddr_to_socketaddr(
"/ip4/255.255.255.255/tcp/8080"
.parse::<Multiaddr>()
.unwrap()
),
Ok(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)),
8080,
))
);
assert_eq!(
multiaddr_to_socketaddr("/ip6/::1/tcp/12345".parse::<Multiaddr>().unwrap()),
Ok(SocketAddr::new(
IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
12345,
))
);
assert_eq!(
multiaddr_to_socketaddr(
"/ip6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/tcp/8080"
.parse::<Multiaddr>()
.unwrap()
),
Ok(SocketAddr::new(
IpAddr::V6(Ipv6Addr::new(
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
)),
8080,
))
);
}
#[test]
fn communicating_between_dialer_and_listener() {
env_logger::try_init().ok();
async fn listener<T: Provider>(addr: Multiaddr, mut ready_tx: mpsc::Sender<Multiaddr>) {
let mut tcp = Transport::<T>::default().boxed();
tcp.listen_on(addr).unwrap();
loop {
match tcp.select_next_some().await {
TransportEvent::NewAddress { listen_addr, .. } => {
ready_tx.send(listen_addr).await.unwrap();
}
TransportEvent::Incoming { upgrade, .. } => {
let mut upgrade = upgrade.await.unwrap();
let mut buf = [0u8; 3];
upgrade.read_exact(&mut buf).await.unwrap();
assert_eq!(buf, [1, 2, 3]);
upgrade.write_all(&[4, 5, 6]).await.unwrap();
return;
}
e => panic!("Unexpected transport event: {e:?}"),
}
}
}
async fn dialer<T: Provider>(mut ready_rx: mpsc::Receiver<Multiaddr>) {
let addr = ready_rx.next().await.unwrap();
let mut tcp = Transport::<T>::default();
let mut socket = tcp.dial(addr.clone()).unwrap().await.unwrap();
socket.write_all(&[0x1, 0x2, 0x3]).await.unwrap();
let mut buf = [0u8; 3];
socket.read_exact(&mut buf).await.unwrap();
assert_eq!(buf, [4, 5, 6]);
}
fn test(addr: Multiaddr) {
#[cfg(feature = "async-io")]
{
let (ready_tx, ready_rx) = mpsc::channel(1);
let listener = listener::<async_io::Tcp>(addr.clone(), ready_tx);
let dialer = dialer::<async_io::Tcp>(ready_rx);
let listener = async_std::task::spawn(listener);
async_std::task::block_on(dialer);
async_std::task::block_on(listener);
}
#[cfg(feature = "tokio")]
{
let (ready_tx, ready_rx) = mpsc::channel(1);
let listener = listener::<tokio::Tcp>(addr, ready_tx);
let dialer = dialer::<tokio::Tcp>(ready_rx);
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
let tasks = ::tokio::task::LocalSet::new();
let listener = tasks.spawn_local(listener);
tasks.block_on(&rt, dialer);
tasks.block_on(&rt, listener).unwrap();
}
}
test("/ip4/127.0.0.1/tcp/0".parse().unwrap());
test("/ip6/::1/tcp/0".parse().unwrap());
}
#[test]
fn wildcard_expansion() {
env_logger::try_init().ok();
async fn listener<T: Provider>(addr: Multiaddr, mut ready_tx: mpsc::Sender<Multiaddr>) {
let mut tcp = Transport::<T>::default().boxed();
tcp.listen_on(addr).unwrap();
loop {
match tcp.select_next_some().await {
TransportEvent::NewAddress { listen_addr, .. } => {
let mut iter = listen_addr.iter();
match iter.next().expect("ip address") {
Protocol::Ip4(ip) => assert!(!ip.is_unspecified()),
Protocol::Ip6(ip) => assert!(!ip.is_unspecified()),
other => panic!("Unexpected protocol: {other}"),
}
if let Protocol::Tcp(port) = iter.next().expect("port") {
assert_ne!(0, port)
} else {
panic!("No TCP port in address: {listen_addr}")
}
ready_tx.send(listen_addr).await.ok();
}
TransportEvent::Incoming { .. } => {
return;
}
_ => {}
}
}
}
async fn dialer<T: Provider>(mut ready_rx: mpsc::Receiver<Multiaddr>) {
let dest_addr = ready_rx.next().await.unwrap();
let mut tcp = Transport::<T>::default();
tcp.dial(dest_addr).unwrap().await.unwrap();
}
fn test(addr: Multiaddr) {
#[cfg(feature = "async-io")]
{
let (ready_tx, ready_rx) = mpsc::channel(1);
let listener = listener::<async_io::Tcp>(addr.clone(), ready_tx);
let dialer = dialer::<async_io::Tcp>(ready_rx);
let listener = async_std::task::spawn(listener);
async_std::task::block_on(dialer);
async_std::task::block_on(listener);
}
#[cfg(feature = "tokio")]
{
let (ready_tx, ready_rx) = mpsc::channel(1);
let listener = listener::<tokio::Tcp>(addr, ready_tx);
let dialer = dialer::<tokio::Tcp>(ready_rx);
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
let tasks = ::tokio::task::LocalSet::new();
let listener = tasks.spawn_local(listener);
tasks.block_on(&rt, dialer);
tasks.block_on(&rt, listener).unwrap();
}
}
test("/ip4/0.0.0.0/tcp/0".parse().unwrap());
test("/ip6/::1/tcp/0".parse().unwrap());
}
#[test]
fn port_reuse_dialing() {
env_logger::try_init().ok();
async fn listener<T: Provider>(
addr: Multiaddr,
mut ready_tx: mpsc::Sender<Multiaddr>,
port_reuse_rx: oneshot::Receiver<Protocol<'_>>,
) {
let mut tcp = Transport::<T>::new(Config::new()).boxed();
tcp.listen_on(addr).unwrap();
loop {
match tcp.select_next_some().await {
TransportEvent::NewAddress { listen_addr, .. } => {
ready_tx.send(listen_addr).await.ok();
}
TransportEvent::Incoming {
upgrade,
mut send_back_addr,
..
} => {
let remote_port_reuse = port_reuse_rx.await.unwrap();
assert_eq!(send_back_addr.pop().unwrap(), remote_port_reuse);
let mut upgrade = upgrade.await.unwrap();
let mut buf = [0u8; 3];
upgrade.read_exact(&mut buf).await.unwrap();
assert_eq!(buf, [1, 2, 3]);
upgrade.write_all(&[4, 5, 6]).await.unwrap();
return;
}
e => panic!("Unexpected event: {e:?}"),
}
}
}
async fn dialer<T: Provider>(
addr: Multiaddr,
mut ready_rx: mpsc::Receiver<Multiaddr>,
port_reuse_tx: oneshot::Sender<Protocol<'_>>,
) {
let dest_addr = ready_rx.next().await.unwrap();
let mut tcp = Transport::<T>::new(Config::new().port_reuse(true));
tcp.listen_on(addr).unwrap();
match poll_fn(|cx| Pin::new(&mut tcp).poll(cx)).await {
TransportEvent::NewAddress { .. } => {
let listener = tcp.listeners.iter().next().unwrap();
let port_reuse_tcp = tcp.port_reuse.local_dial_addr(&listener.listen_addr.ip());
let port_reuse_listener = listener
.port_reuse
.local_dial_addr(&listener.listen_addr.ip());
assert!(port_reuse_tcp.is_some());
assert_eq!(port_reuse_tcp, port_reuse_listener);
port_reuse_tx
.send(Protocol::Tcp(port_reuse_tcp.unwrap().port()))
.ok();
let mut socket = tcp.dial(dest_addr).unwrap().await.unwrap();
socket.write_all(&[0x1, 0x2, 0x3]).await.unwrap();
let mut buf = [0u8; 3];
socket.read_exact(&mut buf).await.unwrap();
assert_eq!(buf, [4, 5, 6]);
}
e => panic!("Unexpected transport event: {e:?}"),
}
}
fn test(addr: Multiaddr) {
#[cfg(feature = "async-io")]
{
let (ready_tx, ready_rx) = mpsc::channel(1);
let (port_reuse_tx, port_reuse_rx) = oneshot::channel();
let listener = listener::<async_io::Tcp>(addr.clone(), ready_tx, port_reuse_rx);
let dialer = dialer::<async_io::Tcp>(addr.clone(), ready_rx, port_reuse_tx);
let listener = async_std::task::spawn(listener);
async_std::task::block_on(dialer);
async_std::task::block_on(listener);
}
#[cfg(feature = "tokio")]
{
let (ready_tx, ready_rx) = mpsc::channel(1);
let (port_reuse_tx, port_reuse_rx) = oneshot::channel();
let listener = listener::<tokio::Tcp>(addr.clone(), ready_tx, port_reuse_rx);
let dialer = dialer::<tokio::Tcp>(addr, ready_rx, port_reuse_tx);
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
let tasks = ::tokio::task::LocalSet::new();
let listener = tasks.spawn_local(listener);
tasks.block_on(&rt, dialer);
tasks.block_on(&rt, listener).unwrap();
}
}
test("/ip4/127.0.0.1/tcp/0".parse().unwrap());
test("/ip6/::1/tcp/0".parse().unwrap());
}
#[test]
fn port_reuse_listening() {
env_logger::try_init().ok();
async fn listen_twice<T: Provider>(addr: Multiaddr) {
let mut tcp = Transport::<T>::new(Config::new().port_reuse(true));
tcp.listen_on(addr).unwrap();
match poll_fn(|cx| Pin::new(&mut tcp).poll(cx)).await {
TransportEvent::NewAddress {
listen_addr: addr1, ..
} => {
let listener1 = tcp.listeners.iter().next().unwrap();
let port_reuse_tcp =
tcp.port_reuse.local_dial_addr(&listener1.listen_addr.ip());
let port_reuse_listener1 = listener1
.port_reuse
.local_dial_addr(&listener1.listen_addr.ip());
assert!(port_reuse_tcp.is_some());
assert_eq!(port_reuse_tcp, port_reuse_listener1);
tcp.listen_on(addr1.clone()).unwrap();
match poll_fn(|cx| Pin::new(&mut tcp).poll(cx)).await {
TransportEvent::NewAddress {
listen_addr: addr2, ..
} => assert_eq!(addr1, addr2),
e => panic!("Unexpected transport event: {e:?}"),
}
}
e => panic!("Unexpected transport event: {e:?}"),
}
}
fn test(addr: Multiaddr) {
#[cfg(feature = "async-io")]
{
let listener = listen_twice::<async_io::Tcp>(addr.clone());
async_std::task::block_on(listener);
}
#[cfg(feature = "tokio")]
{
let listener = listen_twice::<tokio::Tcp>(addr);
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
rt.block_on(listener);
}
}
test("/ip4/127.0.0.1/tcp/0".parse().unwrap());
}
#[test]
fn listen_port_0() {
env_logger::try_init().ok();
async fn listen<T: Provider>(addr: Multiaddr) -> Multiaddr {
let mut tcp = Transport::<T>::default().boxed();
tcp.listen_on(addr).unwrap();
tcp.select_next_some()
.await
.into_new_address()
.expect("listen address")
}
fn test(addr: Multiaddr) {
#[cfg(feature = "async-io")]
{
let new_addr = async_std::task::block_on(listen::<async_io::Tcp>(addr.clone()));
assert!(!new_addr.to_string().contains("tcp/0"));
}
#[cfg(feature = "tokio")]
{
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
let new_addr = rt.block_on(listen::<tokio::Tcp>(addr));
assert!(!new_addr.to_string().contains("tcp/0"));
}
}
test("/ip6/::1/tcp/0".parse().unwrap());
test("/ip4/127.0.0.1/tcp/0".parse().unwrap());
}
#[test]
fn listen_invalid_addr() {
env_logger::try_init().ok();
fn test(addr: Multiaddr) {
#[cfg(feature = "async-io")]
{
let mut tcp = async_io::Transport::default();
assert!(tcp.listen_on(addr.clone()).is_err());
}
#[cfg(feature = "tokio")]
{
let mut tcp = tokio::Transport::default();
assert!(tcp.listen_on(addr).is_err());
}
}
test("/ip4/127.0.0.1/tcp/12345/tcp/12345".parse().unwrap());
}
#[cfg(feature = "async-io")]
#[test]
fn test_address_translation_async_io() {
test_address_translation::<async_io::Transport>()
}
#[cfg(feature = "tokio")]
#[test]
fn test_address_translation_tokio() {
test_address_translation::<tokio::Transport>()
}
fn test_address_translation<T>()
where
T: Default + libp2p_core::Transport,
{
let transport = T::default();
let port = 42;
let tcp_listen_addr = Multiaddr::empty()
.with(Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
.with(Protocol::Tcp(port));
let observed_ip = Ipv4Addr::new(123, 45, 67, 8);
let tcp_observed_addr = Multiaddr::empty()
.with(Protocol::Ip4(observed_ip))
.with(Protocol::Tcp(1))
.with(Protocol::P2p(PeerId::random().into()));
let translated = transport
.address_translation(&tcp_listen_addr, &tcp_observed_addr)
.unwrap();
let mut iter = translated.iter();
assert_eq!(iter.next(), Some(Protocol::Ip4(observed_ip)));
assert_eq!(iter.next(), Some(Protocol::Tcp(port)));
assert_eq!(iter.next(), None);
let quic_addr = Multiaddr::empty()
.with(Protocol::Ip4(Ipv4Addr::new(87, 65, 43, 21)))
.with(Protocol::Udp(1))
.with(Protocol::QuicV1);
assert!(transport
.address_translation(&tcp_listen_addr, &quic_addr)
.is_none());
assert!(transport
.address_translation(&quic_addr, &tcp_observed_addr)
.is_none());
}
#[test]
fn test_remove_listener() {
env_logger::try_init().ok();
async fn cycle_listeners<T: Provider>() -> bool {
let mut tcp = Transport::<T>::default().boxed();
let listener_id = tcp
.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
.unwrap();
tcp.remove_listener(listener_id)
}
#[cfg(feature = "async-io")]
{
assert!(async_std::task::block_on(cycle_listeners::<async_io::Tcp>()));
}
#[cfg(feature = "tokio")]
{
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
assert!(rt.block_on(cycle_listeners::<tokio::Tcp>()));
}
}
}