protocol_address.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. use std::sync::Arc;
  19. use async_trait::async_trait;
  20. use log::debug;
  21. use smol::Executor;
  22. use super::{
  23. super::{
  24. channel::ChannelPtr,
  25. hosts::HostsPtr,
  26. message::{AddrsMessage, GetAddrsMessage},
  27. message_subscriber::MessageSubscription,
  28. p2p::P2pPtr,
  29. session::SESSION_OUTBOUND,
  30. settings::SettingsPtr,
  31. },
  32. protocol_base::{ProtocolBase, ProtocolBasePtr},
  33. protocol_jobs_manager::{ProtocolJobsManager, ProtocolJobsManagerPtr},
  34. };
  35. use crate::{system::sleep, Result};
  36. /// Defines address and get-address messages
  37. pub struct ProtocolAddress {
  38. channel: ChannelPtr,
  39. addrs_sub: MessageSubscription<AddrsMessage>,
  40. get_addrs_sub: MessageSubscription<GetAddrsMessage>,
  41. hosts: HostsPtr,
  42. settings: SettingsPtr,
  43. jobsman: ProtocolJobsManagerPtr,
  44. }
  45. const PROTO_NAME: &str = "ProtocolAddress";
  46. impl ProtocolAddress {
  47. /// Creates a new address protocol. Makes an address, an external address
  48. /// and a get-address subscription and adds them to the address protocol
  49. /// instance.
  50. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  51. let settings = p2p.settings();
  52. let hosts = p2p.hosts();
  53. // Creates a subscription to address message
  54. let addrs_sub =
  55. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addrs dispatcher!");
  56. // Creates a subscription to get-address message
  57. let get_addrs_sub =
  58. channel.subscribe_msg::<GetAddrsMessage>().await.expect("Missing getaddrs dispatcher!");
  59. Arc::new(Self {
  60. channel: channel.clone(),
  61. addrs_sub,
  62. get_addrs_sub,
  63. hosts,
  64. jobsman: ProtocolJobsManager::new(PROTO_NAME, channel),
  65. settings,
  66. })
  67. }
  68. /// Handles receiving the address message. Loops to continually receive
  69. /// address messages on the address subscription. Validates and adds the
  70. /// received addresses to the hosts set.
  71. async fn handle_receive_addrs(self: Arc<Self>) -> Result<()> {
  72. debug!(
  73. target: "net::protocol_address::handle_receive_addrs()",
  74. "[START] address={}", self.channel.address(),
  75. );
  76. loop {
  77. let addrs_msg = self.addrs_sub.receive().await?;
  78. debug!(
  79. target: "net::protocol_address::handle_receive_addrs()",
  80. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.address(),
  81. );
  82. // TODO: We might want to close the channel here if we're getting
  83. // corrupted addresses.
  84. self.hosts.store(&addrs_msg.addrs).await;
  85. }
  86. }
  87. /// Handles receiving the get-address message. Continually receives get-address
  88. /// messages on the get-address subscription. Then replies with an address message.
  89. async fn handle_receive_get_addrs(self: Arc<Self>) -> Result<()> {
  90. debug!(
  91. target: "net::protocol_address::handle_receive_get_addrs()",
  92. "[START] address={}", self.channel.address(),
  93. );
  94. loop {
  95. let get_addrs_msg = self.get_addrs_sub.receive().await?;
  96. debug!(
  97. target: "net::protocol_address::handle_receive_get_addrs()",
  98. "Received GetAddrs({}) message from {}", get_addrs_msg.max, self.channel.address(),
  99. );
  100. // Validate transports length
  101. // TODO: Verify this limit. It should be the max number of all our allowed transports,
  102. // plus their mixing.
  103. if get_addrs_msg.transports.len() > 20 {
  104. // TODO: Should this error out, effectively ending the connection?
  105. let addrs_msg = AddrsMessage { addrs: vec![] };
  106. self.channel.send(&addrs_msg).await?;
  107. continue
  108. }
  109. // First we grab address with the requested transports
  110. let mut addrs = self
  111. .hosts
  112. .fetch_n_random_with_schemes(&get_addrs_msg.transports, get_addrs_msg.max)
  113. .await;
  114. // Then we grab addresses without the requested transports
  115. // to fill a 2 * max length vector.
  116. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  117. addrs.append(
  118. &mut self
  119. .hosts
  120. .fetch_n_random_excluding_schemes(&get_addrs_msg.transports, remain)
  121. .await,
  122. );
  123. debug!(
  124. target: "net::protocol_address::handle_receive_get_addrs()",
  125. "Sending {} addresses to {}", addrs.len(), self.channel.address(),
  126. );
  127. let addrs_msg = AddrsMessage { addrs };
  128. self.channel.send(&addrs_msg).await?;
  129. }
  130. }
  131. /// Periodically send our external addresses through the channel.
  132. async fn send_my_addrs(self: Arc<Self>) -> Result<()> {
  133. debug!(
  134. target: "net::protocol_address::send_my_addrs()",
  135. "[START] address={}", self.channel.address(),
  136. );
  137. // FIXME: Revisit this. Why do we keep sending it?
  138. loop {
  139. let ext_addr_msg = AddrsMessage { addrs: self.settings.external_addrs.clone() };
  140. self.channel.send(&ext_addr_msg).await?;
  141. sleep(900).await;
  142. }
  143. }
  144. }
  145. #[async_trait]
  146. impl ProtocolBase for ProtocolAddress {
  147. /// Starts the address protocol. Runs receive address and get address
  148. /// protocols on the protocol task manager. Then sends get-address msg.
  149. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  150. debug!(target: "net::protocol_address::start()", "START => address={}", self.channel.address());
  151. let type_id = self.channel.session_type_id();
  152. self.jobsman.clone().start(ex.clone());
  153. // If it's an outbound session + has an extern_addr, send our address.
  154. if type_id == SESSION_OUTBOUND && !self.settings.external_addrs.is_empty() {
  155. self.jobsman.clone().spawn(self.clone().send_my_addrs(), ex.clone()).await;
  156. }
  157. self.jobsman.clone().spawn(self.clone().handle_receive_addrs(), ex.clone()).await;
  158. self.jobsman.spawn(self.clone().handle_receive_get_addrs(), ex).await;
  159. // Send get_address message.
  160. let get_addrs = GetAddrsMessage {
  161. max: self.settings.outbound_connections as u32,
  162. transports: self.settings.allowed_transports.clone(),
  163. };
  164. self.channel.send(&get_addrs).await?;
  165. debug!(target: "net::protocol_address::start()", "END => address={}", self.channel.address());
  166. Ok(())
  167. }
  168. fn name(&self) -> &'static str {
  169. PROTO_NAME
  170. }
  171. }