outbound_session.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //! Outbound connections session. Manages the creation of outbound sessions.
  19. //! Used to create an outbound session and to stop and start the session.
  20. //!
  21. //! Class consists of a weak pointer to the p2p interface and a vector of
  22. //! outbound connection slots. Using a weak pointer to p2p allows us to
  23. //! avoid circular dependencies. The vector of slots is wrapped in a mutex
  24. //! lock. This is switched on every time we instantiate a connection slot
  25. //! and insures that no other part of the program uses the slots at the
  26. //! same time.
  27. use std::{
  28. collections::HashSet,
  29. sync::{Arc, Weak},
  30. };
  31. use async_trait::async_trait;
  32. use log::{debug, error, info, warn};
  33. use smol::{lock::Mutex, Executor};
  34. use url::Url;
  35. use super::{
  36. super::{
  37. channel::ChannelPtr,
  38. connector::Connector,
  39. dnet::{self, dnetev, DnetEvent},
  40. message::GetAddrsMessage,
  41. p2p::{P2p, P2pPtr},
  42. },
  43. Session, SessionBitFlag, SESSION_OUTBOUND,
  44. };
  45. use crate::{
  46. system::{sleep, StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr},
  47. Error, Result,
  48. };
  49. pub type OutboundSessionPtr = Arc<OutboundSession>;
  50. /// Connection state
  51. #[derive(Eq, PartialEq, Copy, Clone, Debug)]
  52. pub enum OutboundState {
  53. Open,
  54. Pending,
  55. Connected,
  56. }
  57. impl std::fmt::Display for OutboundState {
  58. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  59. write!(
  60. f,
  61. "{}",
  62. match self {
  63. Self::Open => "open",
  64. Self::Pending => "pending",
  65. Self::Connected => "connected",
  66. }
  67. )
  68. }
  69. }
  70. /// Defines outbound connections session.
  71. pub struct OutboundSession {
  72. /// Weak pointer to parent p2p object
  73. p2p: Weak<P2p>,
  74. /// Outbound connection slots
  75. connect_slots: Mutex<Vec<StoppableTaskPtr>>,
  76. /// Subscriber used to signal channels processing
  77. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  78. /// Flag to toggle channel_subscriber notifications
  79. notify: Mutex<bool>,
  80. }
  81. impl OutboundSession {
  82. /// Create a new outbound session.
  83. pub fn new(p2p: Weak<P2p>) -> OutboundSessionPtr {
  84. Arc::new(Self {
  85. p2p,
  86. connect_slots: Mutex::new(vec![]),
  87. channel_subscriber: Subscriber::new(),
  88. notify: Mutex::new(false),
  89. })
  90. }
  91. /// Start the outbound session. Runs the channel connect loop.
  92. pub async fn start(self: Arc<Self>) -> Result<()> {
  93. let ex = self.p2p().executor();
  94. let n_slots = self.p2p().settings().outbound_connections;
  95. info!(target: "net::outbound_session", "[P2P] Starting {} outbound connection slots.", n_slots);
  96. // Activate mutex lock on connection slots.
  97. let mut connect_slots = self.connect_slots.lock().await;
  98. for i in 0..n_slots as u32 {
  99. let task = StoppableTask::new();
  100. task.clone().start(
  101. self.clone().channel_connect_loop(i),
  102. // Ignore stop handler
  103. |_| async {},
  104. Error::NetworkServiceStopped,
  105. ex.clone(),
  106. );
  107. connect_slots.push(task);
  108. }
  109. Ok(())
  110. }
  111. /// Stops the outbound session.
  112. pub async fn stop(&self) {
  113. let connect_slots = &*self.connect_slots.lock().await;
  114. for slot in connect_slots {
  115. slot.stop().await;
  116. }
  117. }
  118. /// Creates a connector object and tries to connect using it.
  119. pub async fn channel_connect_loop(self: Arc<Self>, slot: u32) -> Result<()> {
  120. let ex = self.p2p().executor();
  121. let parent = Arc::downgrade(&self);
  122. let connector = Connector::new(self.p2p().settings(), Arc::new(parent));
  123. // Retrieve whitelisted outbound transports
  124. let transports = &self.p2p().settings().allowed_transports;
  125. // This is the main outbound connection loop where we try to establish
  126. // a connection in the slot. The `try_connect` function will block in
  127. // case the connection was sucessfully established. If it fails, then
  128. // we will wait for a defined number of seconds and try to fill the
  129. // slot again. This function should never exit during the lifetime of
  130. // the P2P network, as it is supposed to represent an outbound slot we
  131. // want to fill.
  132. // The actual connection logic and peer selection is in `try_connect`.
  133. // If the connection is successful, `try_connect` will wait for a stop
  134. // signal and then exit. Once it exits, we'll run `try_connect` again
  135. // and attempt to fill the slot with another peer.
  136. loop {
  137. match self.try_connect(slot, &connector, transports, ex.clone()).await {
  138. Ok(()) => {
  139. info!(
  140. target: "net::outbound_session",
  141. "[P2P] Outbound slot #{} disconnected",
  142. slot
  143. );
  144. }
  145. Err(e) => {
  146. error!(
  147. target: "net::outbound_session",
  148. "[P2P] Outbound slot #{} connection failed: {}",
  149. slot, e,
  150. );
  151. dnetev!(self, OutboundDisconnected, {
  152. slot,
  153. err: e.to_string()
  154. });
  155. }
  156. }
  157. }
  158. }
  159. /// Start making an outbound connection, using provided [`Connector`].
  160. /// Tries to find a valid address to connect to, otherwise does peer
  161. /// discovery. The peer discovery loops until some peer we can connect
  162. /// to is found. Once connected, registers the channel, removes it from
  163. /// the list of pending channels, and starts sending messages across the
  164. /// channel. In case of any failures, a network error is returned and the
  165. /// main connect loop (parent of this function) will iterate again.
  166. async fn try_connect(
  167. &self,
  168. slot: u32,
  169. connector: &Connector,
  170. transports: &[String],
  171. ex: Arc<Executor<'_>>,
  172. ) -> Result<()> {
  173. debug!(
  174. target: "net::outbound_session::try_connect()",
  175. "[P2P] Finding a host to connect to for outbound slot #{}",
  176. slot,
  177. );
  178. // Find an address to connect to. We also do peer discovery here if needed.
  179. let addr = self.load_address(slot, transports).await?;
  180. info!(
  181. target: "net::outbound_session::try_connect()",
  182. "[P2P] Connecting outbound slot #{} [{}]",
  183. slot, addr,
  184. );
  185. dnetev!(self, OutboundConnecting, {
  186. slot,
  187. addr: addr.clone(),
  188. });
  189. match connector.connect(&addr).await {
  190. Ok((url, channel)) => {
  191. info!(
  192. target: "net::outbound_session::try_connect()",
  193. "[P2P] Outbound slot #{} connected [{}]",
  194. slot, url
  195. );
  196. dnetev!(self, OutboundConnected, {
  197. slot,
  198. addr: addr.clone(),
  199. channel_id: channel.info.id
  200. });
  201. let stop_sub =
  202. channel.subscribe_stop().await.expect("Channel should not be stopped");
  203. // Register the new channel
  204. self.register_channel(channel.clone(), ex.clone()).await?;
  205. // Channel is now connected but not yet setup
  206. // Remove pending lock since register_channel will add the channel to p2p
  207. self.p2p().remove_pending(&addr).await;
  208. // Notify that channel processing has been finished
  209. if *self.notify.lock().await {
  210. self.channel_subscriber.notify(Ok(channel)).await;
  211. }
  212. // Wait for channel to close
  213. stop_sub.receive().await;
  214. return Ok(())
  215. }
  216. Err(e) => {
  217. error!(
  218. target: "net::outbound_session::try_connect()",
  219. "[P2P] Unable to connect outbound slot #{} [{}]: {}",
  220. slot, addr, e
  221. );
  222. }
  223. }
  224. // At this point we failed to connect. We'll quarantine this peer now.
  225. self.p2p().hosts().quarantine(&addr).await;
  226. // Notify that channel processing failed
  227. if *self.notify.lock().await {
  228. self.channel_subscriber.notify(Err(Error::ConnectFailed)).await;
  229. }
  230. Err(Error::ConnectFailed)
  231. }
  232. /// Loops through host addresses to find an outbound address that we can
  233. /// connect to. Check whether the address is valid by making sure it isn't
  234. /// our own inbound address, then checks whether it is already connected
  235. /// (exists) or connecting (pending). If no address was found, we'll attempt
  236. /// to do peer discovery and try to fill the slot again.
  237. async fn load_address(&self, slot: u32, transports: &[String]) -> Result<Url> {
  238. loop {
  239. let p2p = self.p2p();
  240. let retry_sleep = p2p.settings().outbound_connect_timeout;
  241. if *p2p.peer_discovery_running.lock().await {
  242. debug!(
  243. target: "net::outbound_session::load_address()",
  244. "[P2P] #{} Peer discovery active, waiting {} seconds...",
  245. slot, retry_sleep,
  246. );
  247. sleep(retry_sleep).await;
  248. }
  249. // Collect hosts
  250. let mut hosts = HashSet::new();
  251. // If transport mixing is enabled, then for example we're allowed to
  252. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  253. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  254. let transport_mixing = self.p2p().settings().transport_mixing;
  255. macro_rules! mix_transport {
  256. ($a:expr, $b:expr) => {
  257. if transports.contains(&$a.to_string()) && transport_mixing {
  258. let mut a_to_b = p2p.hosts().load_with_schemes(&[$b.to_string()]).await;
  259. for addr in a_to_b.iter_mut() {
  260. addr.set_scheme($a).unwrap();
  261. hosts.insert(addr.clone());
  262. }
  263. }
  264. };
  265. }
  266. mix_transport!("tor", "tcp");
  267. mix_transport!("tor+tls", "tcp+tls");
  268. mix_transport!("nym", "tcp");
  269. mix_transport!("nym+tls", "tcp+tls");
  270. // And now the actual requested transports
  271. for addr in p2p.hosts().load_with_schemes(transports).await {
  272. hosts.insert(addr);
  273. }
  274. // Try to find an unused host in the set.
  275. for host in &hosts {
  276. // Check if we already have this connection established
  277. if p2p.exists(host).await {
  278. continue
  279. }
  280. // Check if we already have this configured as a manual peer
  281. if p2p.settings().peers.contains(host) {
  282. continue
  283. }
  284. // Obtain a lock on this address to prevent duplicate connection
  285. if !p2p.add_pending(host).await {
  286. continue
  287. }
  288. return Ok(host.clone())
  289. }
  290. // We didn't find a host to connect to, let's try to find more peers.
  291. info!(
  292. target: "net::outbound_session::load_address()",
  293. "[P2P] Outbound #{}: No peers found. Starting peer discovery...",
  294. slot,
  295. );
  296. // NOTE: A design decision here is to do a sleep inside peer_discovery()
  297. // so that there's a certain period (outbound_connect_timeout) of time
  298. // to send the GetAddr, receive Addrs, and sort things out. By sleeping
  299. // inside peer_discovery, it will block here in the slot sessions, while
  300. // other slots can keep trying to find hosts. This is also why we sleep
  301. // in the beginning of this loop if peer discovery is currently active.
  302. self.peer_discovery(slot).await;
  303. }
  304. }
  305. /// Activate peer discovery if not active already. This will loop through all
  306. /// connected P2P channels and send out a `GetAddrs` message to request more
  307. /// peers. Other parts of the P2P stack will then handle the incoming addresses
  308. /// and place them in the hosts list.
  309. /// This function will also sleep `Settings::outbound_connect_timeout` seconds
  310. /// after broadcasting in order to let the P2P stack receive and work through
  311. /// the addresses it is expecting.
  312. async fn peer_discovery(&self, slot: u32) {
  313. let p2p = self.p2p();
  314. if *p2p.peer_discovery_running.lock().await {
  315. info!(
  316. target: "net::outbound_session::peer_discovery()",
  317. "[P2P] Outbound #{}: Peer discovery already active",
  318. slot,
  319. );
  320. return
  321. }
  322. info!(
  323. target: "net::outbound_session::peer_discovery()",
  324. "[P2P] Outbound #{}: Started peer discovery",
  325. slot,
  326. );
  327. *p2p.peer_discovery_running.lock().await = true;
  328. // Broadcast the GetAddrs message to all active channels.
  329. // If we have no active channels, we will perform a SeedSyncSession instead.
  330. if p2p.random_channel().await.is_some() {
  331. let get_addrs = GetAddrsMessage { max: p2p.settings().outbound_connections as u32 };
  332. info!(
  333. target: "net::outbound_session::peer_discovery()",
  334. "[P2P] Outbound #{}: Broadcasting GetAddrs across active channels",
  335. slot,
  336. );
  337. p2p.broadcast(&get_addrs).await;
  338. } else {
  339. warn!(
  340. target: "net::outbound_session::peer_discovery()",
  341. "[P2P] No connected channels found for peer discovery. Reseeding.",
  342. );
  343. if let Err(e) = p2p.clone().reseed().await {
  344. error!(
  345. target: "net::outbound_session::peer_discovery()",
  346. "[P2P] Network reseed failed: {}", e,
  347. );
  348. }
  349. }
  350. // Now sleep to let the GetAddrs propagate, and hopefully
  351. // in the meantime we'll get some peers.
  352. debug!(
  353. target: "net::outbound_session::peer_discovery()",
  354. "[P2P] Outbound #{}: Sleeping {} seconds",
  355. slot, p2p.settings().outbound_connect_timeout,
  356. );
  357. sleep(p2p.settings().outbound_connect_timeout).await;
  358. *p2p.peer_discovery_running.lock().await = false;
  359. }
  360. /// Enable channel_subscriber notifications.
  361. pub async fn enable_notify(self: Arc<Self>) {
  362. *self.notify.lock().await = true;
  363. }
  364. /// Disable channel_subscriber notifications.
  365. pub async fn disable_notify(self: Arc<Self>) {
  366. *self.notify.lock().await = false;
  367. }
  368. }
  369. #[async_trait]
  370. impl Session for OutboundSession {
  371. fn p2p(&self) -> P2pPtr {
  372. self.p2p.upgrade().unwrap()
  373. }
  374. fn type_id(&self) -> SessionBitFlag {
  375. SESSION_OUTBOUND
  376. }
  377. }