Skip to main content

ouisync/network/
mod.rs

1mod addr_filter;
2mod choke;
3mod client;
4mod connection;
5mod connection_monitor;
6mod constants;
7mod crypto;
8mod debug_payload;
9mod dht;
10mod event;
11mod gateway;
12mod ip;
13mod local_discovery;
14mod message;
15mod message_broker;
16mod message_dispatcher;
17mod peer_addr;
18mod peer_exchange;
19mod peer_info;
20mod peer_source;
21mod peer_state;
22mod protocol;
23mod request_tracker;
24mod runtime_id;
25mod seen_peers;
26mod server;
27mod stats;
28mod stun;
29mod stun_server_list;
30#[cfg(test)]
31mod tests;
32mod upnp;
33
34pub use self::{
35    addr_filter::AddrFilter,
36    connection::PeerInfoCollector,
37    dht::{DEFAULT_DHT_ROUTERS, DhtContactsStoreTrait, DhtLookupStream, DhtPin},
38    event::{NetworkEvent, NetworkEventReceiver, NetworkEventStream},
39    peer_addr::PeerAddr,
40    peer_info::PeerInfo,
41    peer_source::PeerSource,
42    peer_state::PeerState,
43    runtime_id::{PublicRuntimeId, SecretRuntimeId},
44    stats::Stats,
45};
46use dht::DhtEvent;
47pub use net::{
48    bus::{BusRecvStream as RecvStream, BusSendStream as SendStream, TopicId},
49    stun::NatBehavior,
50};
51
52use self::{
53    choke::Choker,
54    connection::{ConnectionPermit, ConnectionSet, ReserveResult},
55    connection_monitor::ConnectionMonitor,
56    constants::REQUEST_TIMEOUT,
57    dht::DhtDiscovery,
58    event::ProtocolVersions,
59    gateway::{Connectivity, Gateway, StackAddresses},
60    local_discovery::LocalDiscovery,
61    message_broker::MessageBroker,
62    peer_addr::PeerPort,
63    peer_exchange::{PexDiscovery, PexRepository},
64    peer_source::ConnectionDirection,
65    protocol::{MAGIC, VERSION, Version},
66    request_tracker::RequestTracker,
67    seen_peers::{SeenPeer, SeenPeers},
68    stats::{ByteCounters, StatsTracker},
69    stun::StunClients,
70};
71use crate::{
72    protocol::RepositoryId,
73    repository::{RepositoryHandle, Vault},
74};
75use backoff::{ExponentialBackoffBuilder, backoff::Backoff};
76use btdht::{self, INFO_HASH_LEN, InfoHash};
77use deadlock::BlockingMutex;
78use futures_util::future;
79use net::{
80    quic,
81    unified::{Connection, ConnectionError},
82};
83use portable_atomic::{AtomicBool, Ordering};
84use scoped_task::ScopedAbortHandle;
85use slab::Slab;
86use state_monitor::StateMonitor;
87use std::{
88    collections::HashSet,
89    io, mem,
90    net::{SocketAddr, SocketAddrV4, SocketAddrV6},
91    sync::{Arc, Weak},
92};
93use thiserror::Error;
94use tokio::{
95    io::{AsyncReadExt, AsyncWriteExt},
96    sync::{mpsc, watch},
97    task::{AbortHandle, JoinSet},
98    time::Duration,
99};
100use tracing::{Instrument, Span};
101
102#[derive(Default)]
103pub struct NetworkBuilder {
104    dht_contacts: Option<Arc<dyn DhtContactsStoreTrait>>,
105    monitor: Option<StateMonitor>,
106    runtime_id: Option<SecretRuntimeId>,
107    addr_filter: AddrFilter,
108}
109
110impl NetworkBuilder {
111    pub fn dht_contacts(self, contacts: Arc<dyn DhtContactsStoreTrait>) -> Self {
112        Self {
113            dht_contacts: Some(contacts),
114            ..self
115        }
116    }
117
118    pub fn monitor(self, monitor: StateMonitor) -> Self {
119        Self {
120            monitor: Some(monitor),
121            ..self
122        }
123    }
124
125    pub fn runtime_id(self, runtime_id: SecretRuntimeId) -> Self {
126        Self {
127            runtime_id: Some(runtime_id),
128            ..self
129        }
130    }
131
132    pub fn addr_filter(self, addr_filter: AddrFilter) -> Self {
133        Self {
134            addr_filter,
135            ..self
136        }
137    }
138
139    pub fn build(self) -> Network {
140        let (incoming_tx, incoming_rx) = mpsc::channel(1);
141        let gateway = Gateway::new(incoming_tx);
142        let monitor = self.monitor.unwrap_or_else(StateMonitor::make_root);
143
144        // Note that we're now only using quic for the transport discovered over the dht.
145        // This is because the dht doesn't let us specify whether the remote peer SocketAddr is
146        // TCP, UDP or anything else.
147        // TODO: There are ways to address this: e.g. we could try both, or we could include
148        // the protocol information in the info-hash generation. There are pros and cons to
149        // these approaches.
150        let dht_discovery =
151            DhtDiscovery::new(None, None, self.dht_contacts, monitor.make_child("DHT"));
152        // TODO: do we need unbounded channel here?
153        let (dht_discovery_tx, dht_discovery_rx) = mpsc::unbounded_channel();
154
155        let port_forwarder = upnp::PortForwarder::new(monitor.make_child("UPnP"));
156
157        let (pex_discovery_tx, pex_discovery_rx) = mpsc::channel(1);
158        let pex_discovery = PexDiscovery::new(pex_discovery_tx);
159
160        let user_provided_peers = SeenPeers::new();
161
162        let this_runtime_id = self.runtime_id.unwrap_or_else(SecretRuntimeId::random);
163        let this_runtime_id_public = this_runtime_id.public();
164
165        let connections_monitor = monitor.make_child("Connections");
166        let peers_monitor = monitor.make_child("Peers");
167
168        let tasks = Arc::new(BlockingMutex::new(JoinSet::new()));
169
170        let inner = Arc::new(Inner {
171            main_monitor: monitor,
172            connections_monitor,
173            peers_monitor,
174            span: Span::current(),
175            gateway,
176            this_runtime_id,
177            registry: BlockingMutex::new(Registry {
178                peers: Some(Slab::new()),
179                repos: Slab::new(),
180            }),
181            port_forwarder,
182            port_forwarder_state: BlockingMutex::new(ComponentState::disabled(
183                DisableReason::Explicit,
184            )),
185            local_discovery_state: BlockingMutex::new(ComponentState::disabled(
186                DisableReason::Explicit,
187            )),
188            dht_discovery,
189            dht_discovery_tx,
190            local_dht_enabled: AtomicBool::new(false),
191            pex_discovery,
192            stun_clients: StunClients::new(),
193            connections: ConnectionSet::new(),
194            user_provided_peers,
195            tasks: Arc::downgrade(&tasks),
196            protocol_versions: watch::Sender::new(ProtocolVersions::new()),
197            our_addresses: BlockingMutex::new(HashSet::default()),
198            stats_tracker: StatsTracker::default(),
199            addr_filter: self.addr_filter,
200        });
201
202        inner.spawn(inner.clone().handle_incoming_connections(incoming_rx));
203        inner.spawn(inner.clone().run_dht(dht_discovery_rx));
204        inner.spawn(inner.clone().run_peer_exchange(pex_discovery_rx));
205
206        tracing::debug!(this_runtime_id = ?this_runtime_id_public.as_public_key(), "Network created");
207
208        Network {
209            inner,
210            _tasks: tasks,
211        }
212    }
213}
214
215pub struct Network {
216    inner: Arc<Inner>,
217    // We keep tasks here instead of in Inner because we want them to be
218    // destroyed when Network is Dropped.
219    _tasks: Arc<BlockingMutex<JoinSet<()>>>,
220}
221
222impl Network {
223    /// Returns builder to create `Network` with custom options.
224    pub fn builder() -> NetworkBuilder {
225        NetworkBuilder::default()
226    }
227
228    /// Create network with default options. Equal to `Self::builder().build()`.
229    pub fn new() -> Self {
230        Self::builder().build()
231    }
232
233    /// Binds the network to the specified addresses.
234    /// Rebinds if already bound. Unbinds and disables the network if `addrs` is empty.
235    ///
236    /// NOTE: currently at most one address per protocol (QUIC/TCP) and family (IPv4/IPv6) is used
237    /// and the rest are ignored, but this might change in the future.
238    pub async fn bind(&self, addrs: &[PeerAddr]) {
239        self.inner.bind(addrs).await
240    }
241
242    pub fn listener_local_addrs(&self) -> Vec<PeerAddr> {
243        self.inner.gateway.listener_local_addrs()
244    }
245
246    pub fn set_port_forwarding_enabled(&self, enabled: bool) {
247        let mut state = self.inner.port_forwarder_state.lock().unwrap();
248
249        if enabled {
250            if state.is_enabled() {
251                return;
252            }
253
254            state.enable(PortMappings::new(
255                &self.inner.port_forwarder,
256                &self.inner.gateway,
257            ));
258        } else {
259            state.disable(DisableReason::Explicit);
260        }
261    }
262
263    pub fn is_port_forwarding_enabled(&self) -> bool {
264        self.inner.port_forwarder_state.lock().unwrap().is_enabled()
265    }
266
267    pub fn set_local_discovery_enabled(&self, enabled: bool) {
268        let mut state = self.inner.local_discovery_state.lock().unwrap();
269
270        if enabled {
271            if state.is_enabled() {
272                return;
273            }
274
275            if let Some(handle) = self.inner.spawn_local_discovery() {
276                state.enable(handle.into());
277            } else {
278                state.disable(DisableReason::Implicit);
279            }
280        } else {
281            state.disable(DisableReason::Explicit);
282        }
283    }
284
285    pub fn is_local_discovery_enabled(&self) -> bool {
286        self.inner
287            .local_discovery_state
288            .lock()
289            .unwrap()
290            .is_enabled()
291    }
292
293    /// Sets whether sending contacts to other peer over peer exchange is enabled.
294    ///
295    /// Note: PEX sending for a given repo is enabled only if it's enabled globally using this
296    /// function and also for the repo using [Registration::set_pex_enabled].
297    pub fn set_pex_send_enabled(&self, enabled: bool) {
298        self.inner.pex_discovery.set_send_enabled(enabled)
299    }
300
301    pub fn is_pex_send_enabled(&self) -> bool {
302        self.inner.pex_discovery.is_send_enabled()
303    }
304
305    /// Sets whether receiving contacts over peer exchange is enabled.
306    ///
307    /// Note: PEX receiving for a given repo is enabled only if it's enabled globally using this
308    /// function and also for the repo using [Registration::set_pex_enabled].
309    pub fn set_pex_recv_enabled(&self, enabled: bool) {
310        self.inner.pex_discovery.set_recv_enabled(enabled)
311    }
312
313    pub fn is_pex_recv_enabled(&self) -> bool {
314        self.inner.pex_discovery.is_recv_enabled()
315    }
316    /// Find out external address using the STUN protocol.
317    /// Currently QUIC only.
318    pub async fn external_addr_v4(&self) -> Option<SocketAddrV4> {
319        self.inner.stun_clients.external_addr_v4().await
320    }
321
322    /// Find out external address using the STUN protocol.
323    /// Currently QUIC only.
324    pub async fn external_addr_v6(&self) -> Option<SocketAddrV6> {
325        self.inner.stun_clients.external_addr_v6().await
326    }
327
328    /// Determine the behaviour of the NAT we are behind. Returns `None` on unknown.
329    /// Currently IPv4 only.
330    pub async fn nat_behavior(&self) -> Option<NatBehavior> {
331        self.inner.stun_clients.nat_behavior().await
332    }
333
334    /// Get the network traffic stats.
335    pub fn stats(&self) -> Stats {
336        self.inner.stats_tracker.read()
337    }
338
339    pub fn add_user_provided_peer(&self, peer: &PeerAddr) {
340        self.inner.clone().establish_user_provided_connection(peer);
341    }
342
343    pub fn remove_user_provided_peer(&self, peer: &PeerAddr) {
344        self.inner.user_provided_peers.remove(peer)
345    }
346
347    pub fn this_runtime_id(&self) -> PublicRuntimeId {
348        self.inner.this_runtime_id.public()
349    }
350
351    pub fn peer_info_collector(&self) -> PeerInfoCollector {
352        self.inner.connections.peer_info_collector()
353    }
354
355    pub fn peer_info(&self, addr: PeerAddr) -> Option<PeerInfo> {
356        self.inner.connections.get_peer_info(addr)
357    }
358
359    pub fn current_protocol_version(&self) -> u64 {
360        self.inner.protocol_versions.borrow().our.into()
361    }
362
363    pub fn highest_seen_protocol_version(&self) -> u64 {
364        self.inner.protocol_versions.borrow().highest_seen.into()
365    }
366
367    /// Subscribe to network events.
368    pub fn subscribe(&self) -> NetworkEventReceiver {
369        NetworkEventReceiver::new(
370            self.inner.protocol_versions.subscribe(),
371            self.inner.connections.subscribe(),
372        )
373    }
374
375    /// Register a local repository into the network. This links the repository with all matching
376    /// repositories of currently connected remote replicas as well as any replicas connected in
377    /// the future. The repository is automatically deregistered when the returned `Registration`
378    /// is dropped.
379    ///
380    /// Note: A repository should have at most one registration - creating more than one has
381    /// undesired effects. This is currently not enforced and so it's a responsibility of the
382    /// caller.
383    pub fn register(&self, handle: RepositoryHandle) -> Registration {
384        *handle.vault.monitor.info_hash.get() =
385            Some(repository_info_hash(handle.vault.repository_id()));
386
387        let pex = self.inner.pex_discovery.new_repository();
388
389        let request_tracker = RequestTracker::new(handle.vault.monitor.traffic.clone());
390        request_tracker.set_timeout(REQUEST_TIMEOUT);
391
392        // TODO: Should this be global instead of per repo?
393        let choker = Choker::new();
394
395        let stats_tracker = StatsTracker::default();
396
397        let mut registry = self.inner.registry.lock().unwrap();
398
399        registry.create_link(
400            handle.vault.clone(),
401            &pex,
402            &request_tracker,
403            &choker,
404            stats_tracker.bytes.clone(),
405        );
406
407        let key = registry.repos.insert(RegistrationHolder {
408            vault: handle.vault,
409            dht: None,
410            pex,
411            request_tracker,
412            choker,
413            stats_tracker,
414        });
415
416        Registration {
417            inner: self.inner.clone(),
418            key,
419        }
420    }
421
422    /// Gracefully disconnect from peers. Failing to call this function on app termination will
423    /// cause the peers to not learn that we disconnected just now. They will still find out later
424    /// once the keep-alive mechanism kicks in, but in the mean time we will not be able to
425    /// reconnect (by starting the app again) because the remote peer will keep dropping new
426    /// connections from us.
427    pub async fn shutdown(&self) {
428        // TODO: Would be a nice-to-have to also wait for all the spawned tasks here (e.g. dicovery
429        // mechanisms).
430        let Some(peers) = self.inner.registry.lock().unwrap().peers.take() else {
431            tracing::warn!("Network already shut down");
432            return;
433        };
434
435        shutdown_peers(peers).await;
436    }
437
438    /// Change the sync protocol request timeout. Useful mostly for testing and benchmarking as the
439    /// default value should be sufficient for most use cases.
440    pub fn set_request_timeout(&self, timeout: Duration) {
441        for (_, holder) in &self.inner.registry.lock().unwrap().repos {
442            holder.request_tracker.set_timeout(timeout);
443        }
444    }
445
446    /// Opens a side channel for the underlying IPv4 UDP socket, or `None` if IPv4 QUIC stack isn't
447    /// configured.
448    ///
449    /// The side channel is used to send/receive raw UDP datagrams on the same socket that the sync
450    /// protocol uses.
451    pub fn open_udp_side_channel_v4(&self) -> Option<quic::SideChannel> {
452        self.inner
453            .gateway
454            .udp_side_channel_maker_v4()
455            .as_ref()
456            .map(|m| m.make())
457    }
458
459    /// Opens a side channel for the underlying IPv6 UDP socket, or `None` if IPv6 QUIC stack isn't
460    /// configured.
461    ///
462    /// The side channel is used to send/receive raw UDP datagrams on the same socket that the sync
463    /// protocol uses.
464    pub fn open_udp_side_channel_v6(&self) -> Option<quic::SideChannel> {
465        self.inner
466            .gateway
467            .udp_side_channel_maker_v4()
468            .as_ref()
469            .map(|m| m.make())
470    }
471
472    /// Opens raw byte stream to the given peer, bound to the given topic. This can be used to
473    /// send/recv arbitrary data to the peer, outside of the ouisync protocol.
474    ///
475    /// Returns `None` if no active connection to the peer exists.
476    pub fn open_stream(
477        &self,
478        addr: PeerAddr,
479        topic_id: TopicId,
480    ) -> Option<(SendStream, RecvStream)> {
481        let key = self.inner.connections.get_peer_key(addr)?;
482        Some(
483            self.inner
484                .registry
485                .lock()
486                .unwrap()
487                .peers
488                .as_ref()?
489                .get(key)?
490                .open_stream(topic_id),
491        )
492    }
493
494    /// Changes the DHT routers (boostrap nodes), rebootstraps the DHTs and restarts any ongoing
495    /// lookups.
496    pub fn set_dht_routers(&self, routers: HashSet<String>) {
497        self.inner.dht_discovery.set_routers(routers);
498    }
499
500    /// Returns the current DHT routers (bootstrap nodes).
501    pub fn dht_routers(&self) -> HashSet<String> {
502        self.inner.dht_discovery.routers()
503    }
504
505    /// Performs explicit DHT lookup or announce for the given infohash and returns a stream of the
506    /// discovered peer addresses. It will not automatically connect to them.
507    pub fn dht_lookup(&self, info_hash: InfoHash, announce: bool) -> DhtLookupStream {
508        DhtLookupStream::start(
509            &self.inner.dht_discovery,
510            info_hash,
511            announce,
512            self.is_local_dht_enabled(),
513        )
514    }
515
516    /// Set whether DHT on the local network (or localhost) is enabled. By default this is `false`
517    /// because DHT is a global discovery mechanism and finding a local peer on it is unexpected
518    /// (and could indicate malice). However, is some situations it's still useful to enable it
519    /// (typically for testing).
520    ///
521    /// Note: this option is currently experimental and unstable (semver extempt). It's possible it
522    /// will be removed in the future.
523    pub fn set_local_dht_enabled(&self, enabled: bool) {
524        let prev = self
525            .inner
526            .local_dht_enabled
527            .swap(enabled, Ordering::Release);
528
529        if prev != enabled {
530            self.inner.rebind_dht(self.inner.gateway.connectivity());
531        }
532    }
533
534    pub fn is_local_dht_enabled(&self) -> bool {
535        self.inner.local_dht_enabled.load(Ordering::Acquire)
536    }
537
538    /// Creates a "pin" which starts the DHT instances and keeps them running. This prevents the
539    /// DHTs to shut down even when there are no more ongoing lookups. This is useful if one wants
540    /// to avoid having to rebootstrap the DHT when doing another lookup in the future.
541    ///
542    /// Note that DHT is automatically started and kept running when there is at least one
543    /// repository with DHT enabled. Thus, pinning the DHT while having DHT-enabled repos is
544    /// unnecessary (but harmless).
545    pub async fn pin_dht(&self) -> DhtPin {
546        self.inner.dht_discovery.pin().await
547    }
548}
549
550impl Default for Network {
551    fn default() -> Self {
552        Self::new()
553    }
554}
555
556pub struct Registration {
557    inner: Arc<Inner>,
558    key: usize,
559}
560
561impl Registration {
562    pub fn set_dht_enabled(&self, enabled: bool) {
563        let mut registry = self.inner.registry.lock().unwrap();
564        let holder = &mut registry.repos[self.key];
565
566        if enabled {
567            holder.dht = Some(
568                self.inner
569                    .start_dht_lookup(repository_info_hash(holder.vault.repository_id())),
570            );
571        } else {
572            holder.dht = None;
573        }
574    }
575
576    /// This function provides the information to the user whether DHT is enabled for this
577    /// repository, not necessarily whether the DHT tasks are currently running. The subtle
578    /// difference is in that this function should return true even in case e.g. the whole network
579    /// is disabled.
580    pub fn is_dht_enabled(&self) -> bool {
581        self.inner.registry.lock().unwrap().repos[self.key]
582            .dht
583            .is_some()
584    }
585
586    /// Enables/disables peer exchange for this repo.
587    ///
588    /// Note: sending/receiving over PEX for this repo is enabled only if it's enabled using this
589    /// function and also globally using [Network::set_pex_send_enabled] and/or
590    /// [Network::set_pex_recv_enabled].
591    pub fn set_pex_enabled(&self, enabled: bool) {
592        let registry = self.inner.registry.lock().unwrap();
593        registry.repos[self.key].pex.set_enabled(enabled);
594    }
595
596    pub fn is_pex_enabled(&self) -> bool {
597        self.inner.registry.lock().unwrap().repos[self.key]
598            .pex
599            .is_enabled()
600    }
601
602    /// Fetch per-repository network statistics.
603    pub fn stats(&self) -> Stats {
604        self.inner.registry.lock().unwrap().repos[self.key]
605            .stats_tracker
606            .read()
607    }
608}
609
610impl Drop for Registration {
611    fn drop(&mut self) {
612        let mut registry = self
613            .inner
614            .registry
615            .lock()
616            .unwrap_or_else(|error| error.into_inner());
617
618        if let Some(holder) = registry.repos.try_remove(self.key) {
619            for (_, peer) in registry.peers.as_mut().into_iter().flatten() {
620                peer.destroy_link(holder.vault.repository_id());
621            }
622        }
623    }
624}
625
626struct RegistrationHolder {
627    vault: Vault,
628    dht: Option<dht::LookupRequest>,
629    pex: PexRepository,
630    request_tracker: RequestTracker,
631    choker: Choker,
632    stats_tracker: StatsTracker,
633}
634
635struct Inner {
636    main_monitor: StateMonitor,
637    connections_monitor: StateMonitor,
638    peers_monitor: StateMonitor,
639    span: Span,
640    gateway: Gateway,
641    this_runtime_id: SecretRuntimeId,
642    registry: BlockingMutex<Registry>,
643    port_forwarder: upnp::PortForwarder,
644    port_forwarder_state: BlockingMutex<ComponentState<PortMappings>>,
645    local_discovery_state: BlockingMutex<ComponentState<ScopedAbortHandle>>,
646    dht_discovery: DhtDiscovery,
647    dht_discovery_tx: mpsc::UnboundedSender<DhtEvent>,
648    local_dht_enabled: AtomicBool,
649    pex_discovery: PexDiscovery,
650    stun_clients: StunClients,
651    connections: ConnectionSet,
652    protocol_versions: watch::Sender<ProtocolVersions>,
653    user_provided_peers: SeenPeers,
654    // Note that unwrapping the upgraded weak pointer should be fine because if the underlying Arc
655    // was Dropped, we would not be asking for the upgrade in the first place.
656    tasks: Weak<BlockingMutex<JoinSet<()>>>,
657    // Used to prevent repeatedly connecting to self.
658    our_addresses: BlockingMutex<HashSet<PeerAddr>>,
659    stats_tracker: StatsTracker,
660    addr_filter: AddrFilter,
661}
662
663struct Registry {
664    // This is None once the network calls shutdown.
665    peers: Option<Slab<MessageBroker>>,
666    repos: Slab<RegistrationHolder>,
667}
668
669impl Registry {
670    fn create_link(
671        &mut self,
672        repo: Vault,
673        pex: &PexRepository,
674        request_tracker: &RequestTracker,
675        choker: &Choker,
676        byte_counters: Arc<ByteCounters>,
677    ) {
678        if let Some(peers) = &mut self.peers {
679            for (_, peer) in peers {
680                peer.create_link(
681                    repo.clone(),
682                    pex,
683                    request_tracker.clone(),
684                    choker.clone(),
685                    byte_counters.clone(),
686                )
687            }
688        }
689    }
690}
691
692impl Inner {
693    fn is_shutdown(&self) -> bool {
694        self.registry.lock().unwrap().peers.is_none()
695    }
696
697    async fn bind(self: &Arc<Self>, bind: &[PeerAddr]) {
698        let bind = StackAddresses::from(bind);
699
700        // TODO: Would be preferable to only rebind those stacks that actually need rebinding.
701        if !self.gateway.addresses().any_stack_needs_rebind(&bind) {
702            return;
703        }
704
705        // Gateway
706        self.span.in_scope(|| self.gateway.bind(&bind));
707
708        let conn = self.gateway.connectivity();
709
710        // STUN
711        match conn {
712            Connectivity::Full => self.stun_clients.rebind(
713                self.gateway.udp_side_channel_maker_v4().map(|m| m.make()),
714                self.gateway.udp_side_channel_maker_v6().map(|m| m.make()),
715            ),
716            Connectivity::LocalOnly | Connectivity::Disabled => (),
717        }
718
719        // DHT
720        self.rebind_dht(conn);
721
722        // Port forwarding
723        match conn {
724            Connectivity::Full => {
725                let mut state = self.port_forwarder_state.lock().unwrap();
726                if !state.is_disabled(DisableReason::Explicit) {
727                    state.enable(PortMappings::new(&self.port_forwarder, &self.gateway));
728                }
729            }
730            Connectivity::LocalOnly | Connectivity::Disabled => {
731                self.port_forwarder_state
732                    .lock()
733                    .unwrap()
734                    .disable_if_enabled(DisableReason::Implicit);
735            }
736        }
737
738        // Local discovery
739        //
740        // Note: no need to check the Connectivity because local discovery depends only on whether
741        // Gateway is bound.
742        {
743            let mut state = self.local_discovery_state.lock().unwrap();
744            if !state.is_disabled(DisableReason::Explicit) {
745                if let Some(handle) = self.spawn_local_discovery() {
746                    state.enable(handle.into());
747                } else {
748                    state.disable(DisableReason::Implicit);
749                }
750            }
751        }
752
753        // - If we are disabling connectivity, disconnect from all existing peers.
754        // - If we are going from `Full` -> `LocalOnly`, also disconnect from all with the
755        //   assumption that the local ones will be subsequently re-established. Ideally we would
756        //   disconnect only the non-local ones to avoid the reconnect overhead, but the
757        //   implementation is simpler this way and the trade-off doesn't seem to be too bad.
758        // - If we are going to `Full`, keep all existing connections.
759        if matches!(conn, Connectivity::LocalOnly | Connectivity::Disabled) {
760            self.disconnect_all().await;
761        }
762    }
763
764    // Disconnect from all currently connected peers, regardless of their source.
765    async fn disconnect_all(&self) {
766        let Some(peers) = self.registry.lock().unwrap().peers.replace(Slab::default()) else {
767            return;
768        };
769
770        shutdown_peers(peers).await;
771    }
772
773    fn spawn_local_discovery(self: &Arc<Self>) -> Option<AbortHandle> {
774        let ports: Vec<_> = self
775            .gateway
776            .listener_local_addrs()
777            .into_iter()
778            .filter_map(|addr| match addr {
779                PeerAddr::Tcp(SocketAddr::V4(addr)) => Some(PeerPort::Tcp(addr.port())),
780                PeerAddr::Quic(SocketAddr::V4(addr)) => Some(PeerPort::Quic(addr.port())),
781                _ => None,
782            })
783            .collect();
784
785        if !ports.is_empty() {
786            Some(
787                self.spawn(
788                    self.clone()
789                        .run_local_discovery(ports)
790                        .instrument(self.span.clone()),
791                ),
792            )
793        } else {
794            tracing::error!("Not enabling local discovery because there is no IPv4 listener");
795            None
796        }
797    }
798
799    async fn run_local_discovery(self: Arc<Self>, listener_ports: Vec<PeerPort>) {
800        let mut discovery = LocalDiscovery::new(
801            listener_ports,
802            self.main_monitor.make_child("LocalDiscovery"),
803        );
804
805        loop {
806            let peer = discovery.recv().await;
807
808            if self.is_shutdown() {
809                break;
810            }
811
812            self.spawn(
813                self.clone()
814                    .handle_peer_found(peer, PeerSource::LocalDiscovery),
815            );
816        }
817    }
818
819    fn start_dht_lookup(&self, info_hash: InfoHash) -> dht::LookupRequest {
820        self.dht_discovery
821            .start_lookup(info_hash, true, self.dht_discovery_tx.clone())
822    }
823
824    fn rebind_dht(&self, conn: Connectivity) {
825        match (conn, self.local_dht_enabled.load(Ordering::Acquire)) {
826            (Connectivity::Full, _) | (Connectivity::LocalOnly, true) => self.dht_discovery.rebind(
827                self.gateway.udp_side_channel_maker_v4(),
828                self.gateway.udp_side_channel_maker_v6(),
829            ),
830            (Connectivity::LocalOnly, false) | (Connectivity::Disabled, _) => {
831                self.dht_discovery.rebind(None, None)
832            }
833        }
834    }
835
836    async fn run_dht(self: Arc<Self>, mut discovery_rx: mpsc::UnboundedReceiver<DhtEvent>) {
837        while let Some(event) = discovery_rx.recv().await {
838            if self.is_shutdown() {
839                break;
840            }
841
842            let peer = match event {
843                DhtEvent::PeerFound(peer) => peer,
844                DhtEvent::RoundEnded => continue,
845            };
846
847            if !self.local_dht_enabled.load(Ordering::Acquire) && peer.initial_addr().is_local() {
848                continue;
849            }
850
851            self.spawn(self.clone().handle_peer_found(peer, PeerSource::Dht));
852        }
853    }
854
855    async fn run_peer_exchange(self: Arc<Self>, mut discovery_rx: mpsc::Receiver<SeenPeer>) {
856        while let Some(peer) = discovery_rx.recv().await {
857            if self.is_shutdown() {
858                break;
859            }
860
861            self.spawn(
862                self.clone()
863                    .handle_peer_found(peer, PeerSource::PeerExchange),
864            );
865        }
866    }
867
868    fn establish_user_provided_connection(self: Arc<Self>, peer: &PeerAddr) {
869        let peer = match self.user_provided_peers.insert(*peer) {
870            Some(peer) => peer,
871            // Already in `user_provided_peers`.
872            None => return,
873        };
874
875        self.spawn(
876            self.clone()
877                .handle_peer_found(peer, PeerSource::UserProvided),
878        );
879    }
880
881    async fn handle_incoming_connections(
882        self: Arc<Self>,
883        mut rx: mpsc::Receiver<(Connection, PeerAddr)>,
884    ) {
885        while let Some((connection, addr)) = rx.recv().await {
886            match self.connections.reserve(addr, PeerSource::Listener) {
887                ReserveResult::Permit(permit) => {
888                    if self.is_shutdown() {
889                        break;
890                    }
891
892                    let this = self.clone();
893
894                    let monitor = self.span.in_scope(|| {
895                        ConnectionMonitor::new(
896                            &self.connections_monitor,
897                            &permit.addr(),
898                            permit.source(),
899                        )
900                    });
901                    monitor.mark_as_connecting(permit.id());
902
903                    self.spawn(async move {
904                        this.handle_connection(connection, permit, &monitor).await;
905                    });
906                }
907                ReserveResult::Occupied(_, _their_source, permit_id) => {
908                    tracing::debug!(?addr, ?permit_id, "dropping accepted duplicate connection");
909                }
910            }
911        }
912    }
913
914    async fn handle_peer_found(self: Arc<Self>, peer: SeenPeer, source: PeerSource) {
915        let create_backoff = || {
916            ExponentialBackoffBuilder::new()
917                .with_initial_interval(Duration::from_millis(100))
918                .with_max_interval(Duration::from_secs(8))
919                .with_max_elapsed_time(None)
920                .build()
921        };
922
923        let mut backoff = create_backoff();
924
925        let mut next_sleep = None;
926
927        loop {
928            let monitor = self.span.in_scope(|| {
929                ConnectionMonitor::new(&self.connections_monitor, peer.initial_addr(), source)
930            });
931
932            // TODO: We should also check whether the user still wants to accept connections from
933            // the given `source` (the preference may have changed in the mean time).
934
935            if self.is_shutdown() {
936                return;
937            }
938
939            let addr = match peer.addr_if_seen() {
940                Some(addr) => *addr,
941                None => return,
942            };
943
944            if self.our_addresses.lock().unwrap().contains(&addr) {
945                // Don't connect to self.
946                return;
947            }
948
949            let permit = match self.connections.reserve(addr, source) {
950                ReserveResult::Permit(permit) => permit,
951                ReserveResult::Occupied(on_release, their_source, connection_id) => {
952                    if source == their_source {
953                        // This is a duplicate from the same source, ignore it.
954                        return;
955                    }
956
957                    // This is a duplicate from a different source, if the other source releases
958                    // it, then we may want to try to keep hold of it.
959                    monitor.mark_as_awaiting_permit();
960                    tracing::debug!(
961                        parent: monitor.span(),
962                        %connection_id,
963                        "Duplicate from different source - awaiting permit"
964                    );
965
966                    on_release.await;
967
968                    next_sleep = None;
969                    backoff = create_backoff();
970
971                    continue;
972                }
973            };
974
975            if let Some(sleep) = next_sleep {
976                tracing::debug!(parent: monitor.span(), "Next connection attempt in {:?}", sleep);
977                tokio::time::sleep(sleep).await;
978            }
979
980            next_sleep = backoff.next_backoff();
981
982            permit.mark_as_connecting();
983            monitor.mark_as_connecting(permit.id());
984            tracing::trace!(parent: monitor.span(), "Connecting");
985
986            let Some(addr) = peer.addr_if_seen() else {
987                break;
988            };
989
990            if !self.addr_filter.apply(addr.socket_addr()) {
991                tracing::debug!("Invalid peer address - discarding");
992                break;
993            }
994
995            let socket = match self
996                .gateway
997                .connect_with_retries(&peer)
998                .instrument(monitor.span().clone())
999                .await
1000            {
1001                Some(socket) => socket,
1002                None => break,
1003            };
1004
1005            if !self.handle_connection(socket, permit, &monitor).await {
1006                break;
1007            }
1008        }
1009    }
1010
1011    /// Return true iff the peer is suitable for reconnection.
1012    async fn handle_connection(
1013        &self,
1014        connection: Connection,
1015        permit: ConnectionPermit,
1016        monitor: &ConnectionMonitor,
1017    ) -> bool {
1018        tracing::trace!(parent: monitor.span(), "Handshaking");
1019
1020        permit.mark_as_handshaking();
1021        monitor.mark_as_handshaking();
1022
1023        let handshake_result = perform_handshake(
1024            &connection,
1025            VERSION,
1026            &self.this_runtime_id,
1027            permit.source().direction(),
1028        )
1029        .await;
1030
1031        if let Err(error) = &handshake_result {
1032            tracing::debug!(parent: monitor.span(), ?error, "Handshake failed");
1033        }
1034
1035        let that_runtime_id = match handshake_result {
1036            Ok(writer_id) => writer_id,
1037            Err(HandshakeError::ProtocolVersionMismatch(their_version)) => {
1038                self.on_protocol_mismatch(their_version);
1039                return false;
1040            }
1041            Err(
1042                HandshakeError::Timeout
1043                | HandshakeError::BadMagic
1044                | HandshakeError::Io(_)
1045                | HandshakeError::Connection(_),
1046            ) => return false,
1047        };
1048
1049        // prevent self-connections.
1050        if that_runtime_id == self.this_runtime_id.public() {
1051            tracing::debug!(parent: monitor.span(), "Connection from self, discarding");
1052            self.our_addresses.lock().unwrap().insert(permit.addr());
1053            return false;
1054        }
1055
1056        let closed = connection.closed();
1057
1058        let key = {
1059            let mut registry = self.registry.lock().unwrap();
1060            let registry = &mut *registry;
1061
1062            let Some(peers) = &mut registry.peers else {
1063                // Network has been shut down.
1064                return false;
1065            };
1066
1067            let pex_peer = self.pex_discovery.new_peer();
1068            pex_peer.handle_connection(permit.addr(), permit.source(), permit.released());
1069
1070            let mut peer = monitor.span().in_scope(|| {
1071                MessageBroker::new(
1072                    self.this_runtime_id.public(),
1073                    that_runtime_id,
1074                    connection,
1075                    pex_peer,
1076                    self.peers_monitor.make_child(format!(
1077                        "{} {}",
1078                        permit.source().direction().glyph(),
1079                        permit.addr()
1080                    )),
1081                    self.stats_tracker.bytes.clone(),
1082                    permit.byte_counters(),
1083                )
1084            });
1085
1086            // TODO: for DHT connection we should only link the repository for which we did the
1087            // lookup but make sure we correctly handle edge cases, for example, when we have
1088            // more than one repository shared with the peer.
1089            for (_, holder) in &registry.repos {
1090                peer.create_link(
1091                    holder.vault.clone(),
1092                    &holder.pex,
1093                    holder.request_tracker.clone(),
1094                    holder.choker.clone(),
1095                    holder.stats_tracker.bytes.clone(),
1096                );
1097            }
1098
1099            peers.insert(peer)
1100        };
1101
1102        permit.mark_as_active(that_runtime_id, key);
1103        monitor.mark_as_active(that_runtime_id);
1104
1105        // Wait until the connection gets closed, then remove the `MessageBroker` instance. Using a
1106        // RAII to also remove it in case this function gets cancelled.
1107        let _guard = PeerGuard {
1108            registry: &self.registry,
1109            key,
1110        };
1111
1112        closed.await;
1113
1114        true
1115    }
1116
1117    fn on_protocol_mismatch(&self, their_version: Version) {
1118        self.protocol_versions.send_if_modified(|versions| {
1119            if versions.highest_seen < their_version {
1120                versions.highest_seen = their_version;
1121                true
1122            } else {
1123                false
1124            }
1125        });
1126    }
1127
1128    fn spawn<Fut>(&self, f: Fut) -> AbortHandle
1129    where
1130        Fut: Future<Output = ()> + Send + 'static,
1131    {
1132        // TODO: this `unwrap` is sketchy. Maybe we should simply not spawn if `tasks` can't be
1133        // upgraded?
1134        let tasks = self.tasks.upgrade().unwrap();
1135        let mut tasks = tasks.lock().unwrap();
1136
1137        // IMPORTANT: Drain completed tasks. This is necessary because `JoinSet` doesn't
1138        // automatically remove completed tasks (presumably to not lose their results), and so not
1139        // doing it would cause memory leak.
1140        while tasks.try_join_next().is_some() {}
1141
1142        tasks.spawn(f.instrument(Span::current()))
1143    }
1144}
1145
1146//------------------------------------------------------------------------------
1147
1148// Exchange runtime ids with the peer. Returns their (verified) runtime id.
1149async fn perform_handshake(
1150    connection: &Connection,
1151    this_version: Version,
1152    this_runtime_id: &SecretRuntimeId,
1153    dir: ConnectionDirection,
1154) -> Result<PublicRuntimeId, HandshakeError> {
1155    let result = tokio::time::timeout(std::time::Duration::from_secs(5), async move {
1156        let (mut writer, mut reader) = match dir {
1157            ConnectionDirection::Incoming => connection.incoming().await?,
1158            ConnectionDirection::Outgoing => connection.outgoing().await?,
1159        };
1160
1161        writer.write_all(MAGIC).await?;
1162
1163        // Backward fix for Ouisync *App* versions v0.8.3 (and possibly prior)
1164        {
1165            // Those versions of Ouisync App had a race condition where if some peer with a higher
1166            // protocol version managed to connect and handshake before the app subscribed to
1167            // "higher protocol version" notifications then they would never get the notification.
1168            // On Pixel 9a, and when connecting to a PC, the handshake happened ~100ms prior to
1169            // subscribe. Using 700ms to account for slower devices.
1170            tokio::time::sleep(std::time::Duration::from_millis(700)).await;
1171        }
1172
1173        this_version.write_into(&mut writer).await?;
1174
1175        let mut that_magic = [0; MAGIC.len()];
1176        reader.read_exact(&mut that_magic).await?;
1177
1178        if MAGIC != &that_magic {
1179            return Err(HandshakeError::BadMagic);
1180        }
1181
1182        let that_version = Version::read_from(&mut reader).await?;
1183        if that_version > this_version {
1184            return Err(HandshakeError::ProtocolVersionMismatch(that_version));
1185        }
1186
1187        let that_runtime_id =
1188            runtime_id::exchange(this_runtime_id, &mut writer, &mut reader).await?;
1189
1190        writer.shutdown().await?;
1191
1192        Ok(that_runtime_id)
1193    })
1194    .await;
1195
1196    match result {
1197        Ok(subresult) => subresult,
1198        Err(_) => Err(HandshakeError::Timeout),
1199    }
1200}
1201
1202#[derive(Debug, Error)]
1203enum HandshakeError {
1204    #[error("protocol version mismatch")]
1205    ProtocolVersionMismatch(Version),
1206    #[error("bad magic")]
1207    BadMagic,
1208    #[error("timeout")]
1209    Timeout,
1210    #[error("IO error")]
1211    Io(#[from] io::Error),
1212    #[error("connection error")]
1213    Connection(#[from] ConnectionError),
1214}
1215
1216// RAII guard which when dropped removes the peer from the registry.
1217struct PeerGuard<'a> {
1218    registry: &'a BlockingMutex<Registry>,
1219    key: usize,
1220}
1221
1222impl Drop for PeerGuard<'_> {
1223    fn drop(&mut self) {
1224        if let Some(peers) = &mut self
1225            .registry
1226            .lock()
1227            .unwrap_or_else(|error| error.into_inner())
1228            .peers
1229        {
1230            peers.try_remove(self.key);
1231        }
1232    }
1233}
1234
1235struct PortMappings {
1236    _mappings: Vec<upnp::Mapping>,
1237}
1238
1239impl PortMappings {
1240    fn new(forwarder: &upnp::PortForwarder, gateway: &Gateway) -> Self {
1241        let mappings = gateway
1242            .listener_local_addrs()
1243            .into_iter()
1244            .filter_map(|addr| {
1245                match addr {
1246                    PeerAddr::Quic(SocketAddr::V4(addr)) => {
1247                        Some(forwarder.add_mapping(
1248                            addr.port(), // internal
1249                            addr.port(), // external
1250                            ip::Protocol::Udp,
1251                        ))
1252                    }
1253                    PeerAddr::Tcp(SocketAddr::V4(addr)) => {
1254                        Some(forwarder.add_mapping(
1255                            addr.port(), // internal
1256                            addr.port(), // external
1257                            ip::Protocol::Tcp,
1258                        ))
1259                    }
1260                    PeerAddr::Quic(SocketAddr::V6(_)) | PeerAddr::Tcp(SocketAddr::V6(_)) => {
1261                        // TODO: the ipv6 port typically doesn't need to be port-mapped but it might
1262                        // need to be opened in the firewall ("pinholed"). Consider using UPnP for that
1263                        // as well.
1264                        None
1265                    }
1266                }
1267            })
1268            .collect();
1269
1270        Self {
1271            _mappings: mappings,
1272        }
1273    }
1274}
1275
1276enum ComponentState<T> {
1277    Enabled(T),
1278    Disabled(DisableReason),
1279}
1280
1281impl<T> ComponentState<T> {
1282    fn disabled(reason: DisableReason) -> Self {
1283        Self::Disabled(reason)
1284    }
1285
1286    fn is_enabled(&self) -> bool {
1287        matches!(self, Self::Enabled(_))
1288    }
1289
1290    fn is_disabled(&self, reason: DisableReason) -> bool {
1291        match self {
1292            Self::Disabled(current_reason) if *current_reason == reason => true,
1293            Self::Disabled(_) | Self::Enabled(_) => false,
1294        }
1295    }
1296
1297    fn disable(&mut self, reason: DisableReason) -> Option<T> {
1298        match mem::replace(self, Self::Disabled(reason)) {
1299            Self::Enabled(payload) => Some(payload),
1300            Self::Disabled(_) => None,
1301        }
1302    }
1303
1304    fn disable_if_enabled(&mut self, reason: DisableReason) -> Option<T> {
1305        match self {
1306            Self::Enabled(_) => match mem::replace(self, Self::Disabled(reason)) {
1307                Self::Enabled(payload) => Some(payload),
1308                Self::Disabled(_) => unreachable!(),
1309            },
1310            Self::Disabled(_) => None,
1311        }
1312    }
1313
1314    fn enable(&mut self, payload: T) -> Option<T> {
1315        match mem::replace(self, Self::Enabled(payload)) {
1316            Self::Enabled(payload) => Some(payload),
1317            Self::Disabled(_) => None,
1318        }
1319    }
1320}
1321
1322#[derive(Eq, PartialEq)]
1323enum DisableReason {
1324    // Disabled implicitly because `Network` was disabled
1325    Implicit,
1326    // Disabled explicitly
1327    Explicit,
1328}
1329
1330pub fn repository_info_hash(id: &RepositoryId) -> InfoHash {
1331    // Calculate the info hash by hashing the id with BLAKE3 and taking the first 20 bytes.
1332    // (bittorrent uses SHA-1 but that is less secure).
1333    // `unwrap` is OK because the byte slice has the correct length.
1334    InfoHash::try_from(&id.salted_hash(b"ouisync repository info-hash").as_ref()[..INFO_HASH_LEN])
1335        .unwrap()
1336}
1337
1338async fn shutdown_peers(peers: Slab<MessageBroker>) {
1339    future::join_all(peers.into_iter().map(|(_, peer)| peer.shutdown())).await;
1340}