-
Notifications
You must be signed in to change notification settings - Fork 137
/
magicsock.rs
3366 lines (2998 loc) · 118 KB
/
magicsock.rs
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
//! Implements a socket that can change its communication path while in use, actively searching for the best way to communicate.
//!
//! Based on tailscale/wgengine/magicsock
//!
//! ### `DEV_DERP_ONLY` env var:
//! When present at *compile time*, this env var will force all packets
//! to be sent over the DERP relay connection, regardless of whether or
//! not we have a direct UDP address for the given peer.
//!
//! The intended use is for testing the DERP protocol inside the MagicSock
//! to ensure that we can rely on the relay to send packets when two peers
//! are unable to find direct UDP connections to each other.
//!
//! This also prevent this node from attempting to hole punch and prevents it
//! from responding to any hole punching attemtps. This node will still,
//! however, read any packets that come off the UDP sockets.
// #[cfg(test)]
// pub(crate) use conn::tests as conn_tests;
use std::{
collections::HashMap,
fmt::Display,
io,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
sync::{
atomic::{AtomicBool, AtomicU16, AtomicU64, Ordering},
Arc,
},
task::{Context, Poll, Waker},
time::{Duration, Instant},
};
use anyhow::{bail, Context as _, Result};
use bytes::Bytes;
use futures::{future::BoxFuture, FutureExt};
use iroh_metrics::{inc, inc_by};
use quinn::AsyncUdpSocket;
use rand::{seq::SliceRandom, Rng, SeedableRng};
use tokio::{
sync::{self, mpsc, Mutex},
time,
};
use tracing::{debug, error, info, info_span, instrument, trace, warn, Instrument};
use crate::{
config::{self, DERP_MAGIC_IP},
derp::{DerpMap, DerpRegion},
disco,
dns::DNS_RESOLVER,
key::{PublicKey, SecretKey, SharedSecret},
magic_endpoint::NodeAddr,
net::{ip::LocalAddresses, netmon},
netcheck, portmapper, stun,
util::AbortingJoinHandle,
};
use self::{
derp_actor::{DerpActor, DerpActorMessage, DerpReadResult},
endpoint::{Options as EndpointOptions, PeerMap},
metrics::Metrics as MagicsockMetrics,
rebinding_conn::RebindingUdpConn,
udp_actor::{IpPacket, NetworkReadResult, NetworkSource, UdpActor, UdpActorMessage},
};
mod derp_actor;
mod endpoint;
mod metrics;
mod rebinding_conn;
mod timer;
mod udp_actor;
pub use self::endpoint::ConnectionType;
pub use self::endpoint::EndpointInfo;
pub use self::metrics::Metrics;
pub use self::timer::Timer;
/// How long we consider a STUN-derived endpoint valid for. UDP NAT mappings typically
/// expire at 30 seconds, so this is a few seconds shy of that.
const ENDPOINTS_FRESH_ENOUGH_DURATION: Duration = Duration::from_secs(27);
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum CurrentPortFate {
Keep,
Drop,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Network {
Ipv4,
Ipv6,
}
impl From<IpAddr> for Network {
fn from(value: IpAddr) -> Self {
match value {
IpAddr::V4(_) => Self::Ipv4,
IpAddr::V6(_) => Self::Ipv6,
}
}
}
impl Network {
fn default_addr(&self) -> IpAddr {
match self {
Self::Ipv4 => Ipv4Addr::UNSPECIFIED.into(),
Self::Ipv6 => Ipv6Addr::UNSPECIFIED.into(),
}
}
#[cfg(test)]
fn local_addr(&self) -> IpAddr {
match self {
Self::Ipv4 => Ipv4Addr::LOCALHOST.into(),
Self::Ipv6 => Ipv6Addr::LOCALHOST.into(),
}
}
}
impl From<Network> for socket2::Domain {
fn from(value: Network) -> Self {
match value {
Network::Ipv4 => socket2::Domain::IPV4,
Network::Ipv6 => socket2::Domain::IPV6,
}
}
}
/// Contains options for `MagicSock::listen`.
#[derive(derive_more::Debug)]
pub struct Options {
/// The port to listen on.
/// Zero means to pick one automatically.
pub port: u16,
/// Secret key for this node.
pub secret_key: SecretKey,
/// The [`DerpMap`] to use, leave empty to not use a DERP server.
pub derp_map: DerpMap,
/// Callbacks to emit on various socket events
pub callbacks: Callbacks,
}
/// Contains options for `MagicSock::listen`.
#[derive(derive_more::Debug, Default)]
pub struct Callbacks {
/// Optionally provides a func to be called when endpoints change.
#[allow(clippy::type_complexity)]
#[debug("on_endpoints: Option<Box<..>>")]
pub on_endpoints: Option<Box<dyn Fn(&[config::Endpoint]) + Send + Sync + 'static>>,
/// Optionally provides a func to be called when a connection is made to a DERP server.
#[debug("on_derp_active: Option<Box<..>>")]
pub on_derp_active: Option<Box<dyn Fn() + Send + Sync + 'static>>,
/// A callback that provides a `config::NetInfo` when discovered network conditions change.
#[debug("on_net_info: Option<Box<..>>")]
pub on_net_info: Option<Box<dyn Fn(config::NetInfo) + Send + Sync + 'static>>,
}
impl Default for Options {
fn default() -> Self {
Options {
port: 0,
secret_key: SecretKey::generate(),
derp_map: Default::default(),
callbacks: Default::default(),
}
}
}
/// Iroh connectivity layer.
///
/// This is responsible for routing packets to peers based on peer IDs, it will initially
/// route packets via a derper relay and transparently try and establish a peer-to-peer
/// connection and upgrade to it. It will also keep looking for better connections as the
/// network details of both endpoints change.
///
/// It is usually only necessary to use a single [`MagicSock`] instance in an application, it
/// means any QUIC endpoints on top will be sharing as much information about peers as
/// possible.
#[derive(Clone, Debug)]
pub struct MagicSock {
inner: Arc<Inner>,
// Empty when closed
actor_tasks: Arc<Mutex<Vec<AbortingJoinHandle<()>>>>,
}
/// The actual implementation of `MagicSock`.
#[derive(derive_more::Debug)]
struct Inner {
actor_sender: mpsc::Sender<ActorMessage>,
/// Sends network messages.
network_sender: mpsc::Sender<Vec<quinn_udp::Transmit>>,
name: String,
#[allow(clippy::type_complexity)]
#[debug("on_endpoints: Option<Box<..>>")]
on_endpoints: Option<Box<dyn Fn(&[config::Endpoint]) + Send + Sync + 'static>>,
#[debug("on_derp_active: Option<Box<..>>")]
on_derp_active: Option<Box<dyn Fn() + Send + Sync + 'static>>,
/// A callback that provides a `config::NetInfo` when discovered network conditions change.
#[debug("on_net_info: Option<Box<..>>")]
on_net_info: Option<Box<dyn Fn(config::NetInfo) + Send + Sync + 'static>>,
/// Used for receiving DERP messages.
network_recv_ch: flume::Receiver<NetworkReadResult>,
/// Stores wakers, to be called when derp_recv_ch receives new data.
network_recv_wakers: std::sync::Mutex<Option<Waker>>,
network_send_wakers: std::sync::Mutex<Option<Waker>>,
/// Key for this node.
secret_key: SecretKey,
/// Cached version of the Ipv4 and Ipv6 addrs of the current connection.
local_addrs: std::sync::RwLock<(SocketAddr, Option<SocketAddr>)>,
/// Preferred port from `Options::port`; 0 means auto.
port: AtomicU16,
/// Close is in progress (or done)
closing: AtomicBool,
/// Close was called.
closed: AtomicBool,
/// If the last netcheck report, reports IPv6 to be available.
ipv6_reported: Arc<AtomicBool>,
/// None (or zero regions/nodes) means DERP is disabled.
derp_map: DerpMap,
/// Nearest DERP region ID; 0 means none/unknown.
my_derp: AtomicU16,
}
impl Inner {
/// Returns the derp region we are connected to, that has the best latency.
///
/// If `0`, then we are not connected to any derp region.
fn my_derp(&self) -> u16 {
self.my_derp.load(Ordering::Relaxed)
}
/// Sets the derp region with the best latency.
///
/// If we are not connected to any derp regions, set this to `0`.
fn set_my_derp(&self, my_derp: u16) {
self.my_derp.store(my_derp, Ordering::Relaxed);
}
/// Returns `true` if we have DERP configuration for the given DERP `region`.
async fn has_derp_region(&self, region: u16) -> bool {
self.derp_map.contains_region(region)
}
async fn get_derp_region(&self, region: u16) -> Option<DerpRegion> {
self.derp_map.get_region(region).cloned()
}
fn is_closing(&self) -> bool {
self.closing.load(Ordering::Relaxed)
}
fn is_closed(&self) -> bool {
self.closed.load(Ordering::SeqCst)
}
fn public_key(&self) -> PublicKey {
self.secret_key.public()
}
}
#[derive(Debug)]
struct EndpointUpdateState {
/// If running, set to the task handle of the update.
running: sync::watch::Sender<Option<&'static str>>,
want_update: Option<&'static str>,
}
impl EndpointUpdateState {
fn new() -> Self {
let (running, _) = sync::watch::channel(None);
EndpointUpdateState {
running,
want_update: None,
}
}
/// Returns `true` if an update is currently in progress.
fn is_running(&self) -> bool {
self.running.borrow().is_some()
}
}
impl MagicSock {
/// Creates a magic `MagicSock` listening on `opts.port`.
///
/// As the set of possible endpoints for a MagicSock changes, the [`Callbacks::on_endpoints`]
/// callback of [`Options::callbacks`] is called.
///
/// [`Callbacks::on_endpoint`]: crate::magicsock::conn::Callbacks::on_endpoints
pub async fn new(opts: Options) -> Result<Self> {
let name = format!(
"magic-{}",
hex::encode(&opts.secret_key.public().as_bytes()[..8])
);
if crate::util::derp_only_mode() {
warn!("creating a MagicSock that will only send packets over a DERP relay connection.");
}
Self::with_name(name.clone(), opts)
.instrument(info_span!("magicsock", %name))
.await
}
/// Returns `true` if we have DERP configuration for the given DERP `region`.
pub async fn has_derp_region(&self, region: u16) -> bool {
self.inner.has_derp_region(region).await
}
async fn with_name(name: String, opts: Options) -> Result<Self> {
let port_mapper = portmapper::Client::default().await;
let Options {
port,
secret_key,
derp_map,
callbacks:
Callbacks {
on_endpoints,
on_derp_active,
on_net_info,
},
} = opts;
let (network_recv_ch_sender, network_recv_ch_receiver) = flume::bounded(128);
let (pconn4, pconn6) = bind(port).await?;
let port = pconn4.port();
// NOTE: we can end up with a zero port if `std::net::UdpSocket::socket_addr` fails
match port.try_into() {
Ok(non_zero_port) => {
port_mapper.update_local_port(non_zero_port);
}
Err(_zero_port) => debug!("Skipping port mapping with zero local port"),
}
let ipv4_addr = pconn4.local_addr()?;
let ipv6_addr = pconn6.as_ref().and_then(|c| c.local_addr().ok());
let net_checker = netcheck::Client::new(Some(port_mapper.clone())).await?;
let (actor_sender, actor_receiver) = mpsc::channel(128);
let (network_sender, network_receiver) = mpsc::channel(128);
let inner = Arc::new(Inner {
name,
on_endpoints,
on_derp_active,
on_net_info,
port: AtomicU16::new(port),
secret_key,
local_addrs: std::sync::RwLock::new((ipv4_addr, ipv6_addr)),
closing: AtomicBool::new(false),
closed: AtomicBool::new(false),
network_recv_ch: network_recv_ch_receiver,
network_recv_wakers: std::sync::Mutex::new(None),
network_send_wakers: std::sync::Mutex::new(None),
actor_sender: actor_sender.clone(),
network_sender,
ipv6_reported: Arc::new(AtomicBool::new(false)),
derp_map,
my_derp: AtomicU16::new(0),
});
let udp_state = quinn_udp::UdpState::default();
let (ip_sender, ip_receiver) = mpsc::channel(128);
let (udp_actor_sender, udp_actor_receiver) = mpsc::channel(128);
let udp_actor_task = {
let udp_actor =
UdpActor::new(&udp_state, inner.clone(), pconn4.clone(), pconn6.clone());
let net_checker = net_checker.clone();
tokio::task::spawn(
async move {
udp_actor
.run(udp_actor_receiver, net_checker, ip_sender)
.await;
}
.instrument(info_span!("udp.actor")),
)
};
let (derp_actor_sender, derp_actor_receiver) = mpsc::channel(256);
let derp_actor = DerpActor::new(inner.clone(), actor_sender.clone());
let derp_actor_task = tokio::task::spawn(
async move {
derp_actor.run(derp_actor_receiver).await;
}
.instrument(info_span!("derp.actor")),
);
let inner2 = inner.clone();
let main_actor_task = tokio::task::spawn(
async move {
let actor = Actor {
msg_receiver: actor_receiver,
msg_sender: actor_sender,
derp_actor_sender,
udp_actor_sender,
network_receiver,
ip_receiver,
inner: inner2,
derp_recv_sender: network_recv_ch_sender,
endpoints_update_state: EndpointUpdateState::new(),
last_endpoints: Vec::new(),
last_endpoints_time: None,
on_endpoint_refreshed: HashMap::new(),
periodic_re_stun_timer: new_re_stun_timer(false),
net_info_last: None,
disco_info: HashMap::new(),
peer_map: Default::default(),
port_mapper,
pconn4,
pconn6,
udp_state,
no_v4_send: false,
net_checker,
};
if let Err(err) = actor.run().await {
warn!("derp handler errored: {:?}", err);
}
}
.instrument(info_span!("actor")),
);
let c = MagicSock {
inner,
actor_tasks: Arc::new(Mutex::new(vec![
main_actor_task.into(),
derp_actor_task.into(),
udp_actor_task.into(),
])),
};
Ok(c)
}
/// Retrieve connection information about nodes in the network.
pub async fn tracked_endpoints(&self) -> Result<Vec<EndpointInfo>> {
let (s, r) = sync::oneshot::channel();
self.inner
.actor_sender
.send(ActorMessage::TrackedEndpoints(s))
.await?;
let res = r.await?;
Ok(res)
}
/// Retrieve connection information about a node in the network.
pub async fn tracked_endpoint(&self, node_key: PublicKey) -> Result<Option<EndpointInfo>> {
let (s, r) = sync::oneshot::channel();
self.inner
.actor_sender
.send(ActorMessage::TrackedEndpoint(node_key, s))
.await?;
let res = r.await?;
Ok(res)
}
/// Query for the local endpoints discovered during the last endpoint discovery.
pub async fn local_endpoints(&self) -> Result<Vec<config::Endpoint>> {
let (s, r) = sync::oneshot::channel();
self.inner
.actor_sender
.send(ActorMessage::LocalEndpoints(s))
.await?;
let res = r.await?;
Ok(res)
}
/// Get the cached version of the Ipv4 and Ipv6 addrs of the current connection.
pub fn local_addr(&self) -> Result<(SocketAddr, Option<SocketAddr>)> {
Ok(*self.inner.local_addrs.read().unwrap())
}
/// Triggers an address discovery. The provided why string is for debug logging only.
#[instrument(skip_all, fields(self.name = %self.inner.name))]
pub async fn re_stun(&self, why: &'static str) {
self.inner
.actor_sender
.send(ActorMessage::ReStun(why))
.await
.unwrap();
}
/// Returns the [`SocketAddr`] which can be used by the QUIC layer to dial this peer.
///
/// Note this is a user-facing API and does not wrap the [`SocketAddr`] in a
/// `QuicMappedAddr` as we do internally.
pub async fn get_mapping_addr(&self, node_key: &PublicKey) -> Option<SocketAddr> {
let (s, r) = tokio::sync::oneshot::channel();
if self
.inner
.actor_sender
.send(ActorMessage::GetMappingAddr(*node_key, s))
.await
.is_ok()
{
return r.await.ok().flatten().map(|m| m.0);
}
None
}
// TODO
// /// Handles a "ping" CLI query.
// #[instrument(skip_all, fields(self.name = %self.name))]
// pub async fn ping<F>(&self, peer: config::Node, mut res: config::PingResult, cb: F)
// where
// F: Fn(config::PingResult) -> BoxFuture<'static, ()> + Send + Sync + 'static,
// {
// res.node_ip = peer.addresses.get(0).copied();
// res.node_name = match peer.name.as_ref().and_then(|n| n.split('.').next()) {
// Some(name) => {
// // prefer DNS name
// Some(name.to_string())
// }
// None => {
// // else hostname
// Some(peer.hostinfo.hostname.clone())
// }
// };
// let ep = self
// .peer_map
// .read()
// .await
// .endpoint_for_node_key(&peer.key)
// .cloned();
// match ep {
// Some(ep) => {
// ep.cli_ping(res, cb).await;
// }
// None => {
// res.err = Some("unknown peer".to_string());
// cb(res);
// }
// }
// }
/// Sets the connection's preferred local port.
#[instrument(skip_all, fields(self.name = %self.inner.name))]
pub async fn set_preferred_port(&self, port: u16) {
let (s, r) = sync::oneshot::channel();
self.inner
.actor_sender
.send(ActorMessage::SetPreferredPort(port, s))
.await
.unwrap();
r.await.unwrap();
}
/// Returns the DERP region with the best latency.
///
/// If `None`, then we currently have no verified connection to a DERP node in any region.
pub async fn my_derp(&self) -> Option<u16> {
let my_derp = self.inner.my_derp();
if my_derp == 0 {
None
} else {
Some(my_derp)
}
}
#[instrument(skip_all, fields(self.name = %self.inner.name))]
/// Add addresses for a node to the magic socket's addresbook.
pub async fn add_known_addr(&self, addr: NodeAddr) -> Result<()> {
let (s, r) = sync::oneshot::channel();
self.inner
.actor_sender
.send(ActorMessage::AddKnownAddr(addr, s))
.await?;
r.await?;
Ok(())
}
/// Closes the connection.
///
/// Only the first close does anything. Any later closes return nil.
#[instrument(skip_all, fields(name = %self.inner.name))]
pub async fn close(&self) -> Result<()> {
if self.inner.is_closed() {
return Ok(());
}
self.inner.actor_sender.send(ActorMessage::Shutdown).await?;
self.inner.closing.store(true, Ordering::Relaxed);
self.inner.closed.store(true, Ordering::SeqCst);
let mut tasks = self.actor_tasks.lock().await;
let task_count = tasks.len();
let mut i = 0;
while let Some(task) = tasks.pop() {
debug!("waiting for task {i}/{task_count}");
task.await?;
i += 1;
}
Ok(())
}
/// Closes and re-binds the UDP sockets and resets the DERP connection.
/// It should be followed by a call to ReSTUN.
#[instrument(skip_all, fields(name = %self.inner.name))]
pub async fn rebind_all(&self) {
let (s, r) = sync::oneshot::channel();
self.inner
.actor_sender
.send(ActorMessage::RebindAll(s))
.await
.unwrap();
r.await.unwrap();
}
}
/// The info and state for the DiscoKey in the MagicSock.discoInfo map key.
///
/// Note that a DiscoKey does not necessarily map to exactly one
/// node. In the case of shared nodes and users switching accounts, two
/// nodes in the NetMap may legitimately have the same DiscoKey. As
/// such, no fields in here should be considered node-specific.
struct DiscoInfo {
node_key: PublicKey,
/// The precomputed key for communication with the peer that has the `node_key` used to
/// look up this `DiscoInfo` in MagicSock.discoInfo.
/// Not modified once initialized.
shared_key: SharedSecret,
/// The src of a ping for `node_key`.
last_ping_from: Option<SendAddr>,
/// The last time of a ping for `node_key`.
last_ping_time: Option<Instant>,
}
/// Reports whether x and y represent the same set of endpoints. The order doesn't matter.
fn endpoint_sets_equal(xs: &[config::Endpoint], ys: &[config::Endpoint]) -> bool {
if xs.is_empty() && ys.is_empty() {
return true;
}
if xs.len() == ys.len() {
let mut order_matches = true;
for (i, x) in xs.iter().enumerate() {
if x != &ys[i] {
order_matches = false;
break;
}
}
if order_matches {
return true;
}
}
let mut m: HashMap<&config::Endpoint, usize> = HashMap::new();
for x in xs {
*m.entry(x).or_default() |= 1;
}
for y in ys {
*m.entry(y).or_default() |= 2;
}
m.values().all(|v| *v == 3)
}
impl AsyncUdpSocket for MagicSock {
#[instrument(skip_all, fields(name = %self.inner.name))]
fn poll_send(
&self,
_udp_state: &quinn_udp::UdpState,
cx: &mut Context,
transmits: &[quinn_udp::Transmit],
) -> Poll<io::Result<usize>> {
let bytes_total: usize = transmits.iter().map(|t| t.contents.len()).sum();
inc_by!(MagicsockMetrics, send_data, bytes_total as _);
if self.inner.is_closed() {
inc_by!(MagicsockMetrics, send_data_network_down, bytes_total as _);
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::NotConnected,
"connection closed",
)));
}
let mut n = 0;
if transmits.is_empty() {
return Poll::Ready(Ok(n));
}
// Split up transmits by destination, as the rest of the code assumes single dest.
let groups = TransmitIter::new(transmits);
for group in groups {
match self.inner.network_sender.try_reserve() {
Err(mpsc::error::TrySendError::Full(_)) => {
// TODO: add counter?
self.inner
.network_send_wakers
.lock()
.unwrap()
.replace(cx.waker().clone());
break;
}
Err(mpsc::error::TrySendError::Closed(_)) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::NotConnected,
"connection closed",
)));
}
Ok(permit) => {
n += group.len();
permit.send(group);
}
}
}
if n > 0 {
return Poll::Ready(Ok(n));
}
Poll::Pending
}
#[instrument(skip_all, fields(name = %self.inner.name))]
fn poll_recv(
&self,
cx: &mut Context,
bufs: &mut [io::IoSliceMut<'_>],
metas: &mut [quinn_udp::RecvMeta],
) -> Poll<io::Result<usize>> {
// FIXME: currently ipv4 load results in ipv6 traffic being ignored
debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
if self.inner.is_closed() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::NotConnected,
"connection closed",
)));
}
let mut num_msgs = 0;
for (buf_out, meta_out) in bufs.iter_mut().zip(metas.iter_mut()) {
match self.inner.network_recv_ch.try_recv() {
Err(flume::TryRecvError::Empty) => {
self.inner
.network_recv_wakers
.lock()
.unwrap()
.replace(cx.waker().clone());
break;
}
Err(flume::TryRecvError::Disconnected) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::NotConnected,
"connection closed",
)));
}
Ok(dm) => {
if self.inner.is_closed() {
break;
}
match dm {
NetworkReadResult::Error(err) => {
return Poll::Ready(Err(err));
}
NetworkReadResult::Ok {
bytes,
meta,
source,
} => {
buf_out[..bytes.len()].copy_from_slice(&bytes);
*meta_out = meta;
match source {
NetworkSource::Derp => {
inc_by!(MagicsockMetrics, recv_data_derp, bytes.len() as _);
}
NetworkSource::Ipv4 => {
inc_by!(MagicsockMetrics, recv_data_ipv4, bytes.len() as _);
}
NetworkSource::Ipv6 => {
inc_by!(MagicsockMetrics, recv_data_ipv6, bytes.len() as _);
}
}
trace!(
"[QUINN] <- {} ({}b) ({}) ({:?}, {:?})",
meta_out.addr,
meta_out.len,
self.inner.name,
meta_out.dst_ip,
source
);
}
}
num_msgs += 1;
}
}
}
// If we have any msgs to report, they are in the first `num_msgs_total` slots
if num_msgs > 0 {
inc_by!(MagicsockMetrics, recv_datagrams, num_msgs as _);
trace!("received {} datagrams", num_msgs);
return Poll::Ready(Ok(num_msgs));
}
Poll::Pending
}
fn local_addr(&self) -> io::Result<SocketAddr> {
match &*self.inner.local_addrs.read().unwrap() {
(ipv4, None) => {
// Pretend to be IPv6, because our QuinnMappedAddrs
// need to be IPv6.
let ip: IpAddr = match ipv4.ip() {
IpAddr::V4(ip) => ip.to_ipv6_mapped().into(),
IpAddr::V6(ip) => ip.into(),
};
Ok(SocketAddr::new(ip, ipv4.port()))
}
(_, Some(ipv6)) => Ok(*ipv6),
}
}
}
/// Simple DropGuard for decrementing a Waitgroup.
struct WgGuard(wg::AsyncWaitGroup);
impl Drop for WgGuard {
fn drop(&mut self) {
self.0.done();
}
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
enum ActorMessage {
TrackedEndpoints(sync::oneshot::Sender<Vec<EndpointInfo>>),
TrackedEndpoint(PublicKey, sync::oneshot::Sender<Option<EndpointInfo>>),
LocalEndpoints(sync::oneshot::Sender<Vec<config::Endpoint>>),
GetMappingAddr(PublicKey, sync::oneshot::Sender<Option<QuicMappedAddr>>),
SetPreferredPort(u16, sync::oneshot::Sender<()>),
RebindAll(sync::oneshot::Sender<()>),
Shutdown,
CloseOrReconnect(u16, &'static str),
ReStun(&'static str),
EnqueueCallMeMaybe {
derp_region: u16,
endpoint_id: usize,
},
SendPing {
dst: SendAddr,
dst_key: PublicKey,
tx_id: stun::TransactionId,
},
SendCallMeMaybe {
dst: SendAddr,
dst_key: PublicKey,
msg: disco::CallMeMaybe,
},
AddKnownAddr(NodeAddr, sync::oneshot::Sender<()>),
ReceiveDerp(DerpReadResult),
EndpointPingExpired(usize, stun::TransactionId),
}
struct Actor {
inner: Arc<Inner>,
msg_receiver: mpsc::Receiver<ActorMessage>,
msg_sender: mpsc::Sender<ActorMessage>,
derp_actor_sender: mpsc::Sender<DerpActorMessage>,
udp_actor_sender: mpsc::Sender<UdpActorMessage>,
network_receiver: mpsc::Receiver<Vec<quinn_udp::Transmit>>,
ip_receiver: mpsc::Receiver<IpPacket>,
/// Channel to send received derp messages on, for processing.
derp_recv_sender: flume::Sender<NetworkReadResult>,
/// Indicates the update endpoint state.
endpoints_update_state: EndpointUpdateState,
/// Records the endpoints found during the previous
/// endpoint discovery. It's used to avoid duplicate endpoint change notifications.
last_endpoints: Vec<config::Endpoint>,
/// The last time the endpoints were updated, even if there was no change.
last_endpoints_time: Option<Instant>,
/// Functions to run (in their own tasks) when endpoints are refreshed.
on_endpoint_refreshed:
HashMap<usize, Box<dyn Fn() -> BoxFuture<'static, ()> + Send + Sync + 'static>>,
/// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun.
periodic_re_stun_timer: time::Interval,
/// The `NetInfo` provided in the last call to `net_info_func`. It's used to deduplicate calls to netInfoFunc.
net_info_last: Option<config::NetInfo>,
/// The state for an active DiscoKey.
disco_info: HashMap<PublicKey, DiscoInfo>,
/// Tracks the networkmap node entity for each peer discovery key.
peer_map: PeerMap,
// The underlying UDP sockets used to send/rcv packets.
pconn4: RebindingUdpConn,
pconn6: Option<RebindingUdpConn>,
udp_state: quinn_udp::UdpState,
/// The NAT-PMP/PCP/UPnP prober/client, for requesting port mappings from NAT devices.
port_mapper: portmapper::Client,
/// Whether IPv4 UDP is known to be unable to transmit
/// at all. This could happen if the socket is in an invalid state
/// (as can happen on darwin after a network link status change).
no_v4_send: bool,
/// The prober that discovers local network conditions, including the closest DERP relay and NAT mappings.
net_checker: netcheck::Client,
}
impl Actor {
async fn run(mut self) -> Result<()> {
// Setup network monitoring
let monitor = netmon::Monitor::new().await?;
let sender = self.msg_sender.clone();
let _token = monitor
.subscribe(move |is_major| {
let sender = sender.clone();
async move {
info!("link change detected: major? {}", is_major);
// Clear DNS cache
DNS_RESOLVER.clear_cache();
if is_major {
let (s, r) = sync::oneshot::channel();
sender.send(ActorMessage::RebindAll(s)).await.ok();
sender
.send(ActorMessage::ReStun("link-change-major"))
.await
.ok();
r.await.ok();
} else {
sender
.send(ActorMessage::ReStun("link-change-minor"))
.await
.ok();
}
}
.boxed()
})
.await?;
// Let the the hearbeat only start a couple seconds later
let mut endpoint_heartbeat_timer = time::interval_at(
time::Instant::now() + Duration::from_secs(5),
HEARTBEAT_INTERVAL,
);
let mut endpoints_update_receiver = self.endpoints_update_state.running.subscribe();
let mut portmap_watcher = self.port_mapper.watch_external_address();
loop {
tokio::select! {
Some(transmits) = self.network_receiver.recv() => {
trace!("tick: network send");
self.send_network(transmits).await;
}
Some(msg) = self.msg_receiver.recv() => {
trace!(?msg, "tick: msg");
if self.handle_actor_message(msg).await {
return Ok(());
}
}
Some(msg) = self.ip_receiver.recv() => {
trace!("tick: ip_receiver");
match msg {
IpPacket::Disco { sender, sealed_box, src } => {
self.handle_disco_message(sender, &sealed_box, src, None).await;
}
IpPacket::Forward(mut forward) => {
if let NetworkReadResult::Ok { meta, bytes, .. } = &mut forward {
if !self.receive_ip(bytes, meta) {
continue;
}
}
let _ = self.derp_recv_sender.send_async(forward).await;
let mut wakers = self.inner.network_recv_wakers.lock().unwrap();
while let Some(waker) = wakers.take() {
waker.wake();
}
}
}
}
tick = self.periodic_re_stun_timer.tick() => {
trace!("tick: re_stun {:?}", tick);
self.re_stun("periodic").await;
}
Ok(()) = portmap_watcher.changed() => {
trace!("tick: portmap changed");
let new_external_address = *portmap_watcher.borrow();
debug!("external address updated: {new_external_address:?}");