protocol_address.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. use std::sync::Arc;
  2. use async_trait::async_trait;
  3. use log::debug;
  4. use smol::Executor;
  5. use url::Url;
  6. use crate::{util::async_util, Result};
  7. use super::{
  8. super::{
  9. message, message_subscriber::MessageSubscription, ChannelPtr, HostsPtr, P2pPtr,
  10. SettingsPtr, SESSION_OUTBOUND,
  11. },
  12. ProtocolBase, ProtocolBasePtr, ProtocolJobsManager, ProtocolJobsManagerPtr,
  13. };
  14. const SEND_ADDR_SLEEP_SECONDS: u64 = 900;
  15. /// Defines address and get-address messages.
  16. pub struct ProtocolAddress {
  17. channel: ChannelPtr,
  18. addrs_sub: MessageSubscription<message::AddrsMessage>,
  19. get_addrs_sub: MessageSubscription<message::GetAddrsMessage>,
  20. hosts: HostsPtr,
  21. jobsman: ProtocolJobsManagerPtr,
  22. settings: SettingsPtr,
  23. }
  24. impl ProtocolAddress {
  25. /// Create a new address protocol. Makes an address and get-address
  26. /// subscription and adds them to the address protocol instance.
  27. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  28. let settings = p2p.settings();
  29. let hosts = p2p.hosts();
  30. // Creates a subscription to address message.
  31. let addrs_sub = channel
  32. .clone()
  33. .subscribe_msg::<message::AddrsMessage>()
  34. .await
  35. .expect("Missing addrs dispatcher!");
  36. // Creates a subscription to get-address message.
  37. let get_addrs_sub = channel
  38. .clone()
  39. .subscribe_msg::<message::GetAddrsMessage>()
  40. .await
  41. .expect("Missing getaddrs dispatcher!");
  42. Arc::new(Self {
  43. channel: channel.clone(),
  44. addrs_sub,
  45. get_addrs_sub,
  46. hosts,
  47. jobsman: ProtocolJobsManager::new("ProtocolAddress", channel),
  48. settings,
  49. })
  50. }
  51. /// Handles receiving the address message. Loops to continually recieve
  52. /// address messages on the address subsciption. Adds the recieved
  53. /// addresses to the list of hosts.
  54. async fn handle_receive_addrs(self: Arc<Self>) -> Result<()> {
  55. debug!(target: "net", "ProtocolAddress::handle_receive_addrs() [START]");
  56. loop {
  57. let addrs_msg = self.addrs_sub.receive().await?;
  58. debug!(
  59. target: "net",
  60. "ProtocolAddress::handle_receive_addrs() received {} addrs",
  61. addrs_msg.addrs.len()
  62. );
  63. for (i, addr) in addrs_msg.addrs.iter().enumerate() {
  64. debug!(target: "net", " addr[{}]: {}", i, addr);
  65. }
  66. self.hosts.store(addrs_msg.addrs.clone()).await;
  67. }
  68. }
  69. /// Handles receiving the get-address message. Continually recieves
  70. /// get-address messages on the get-address subsciption. Then replies
  71. /// with an address message.
  72. async fn handle_receive_get_addrs(self: Arc<Self>) -> Result<()> {
  73. debug!(target: "net", "ProtocolAddress::handle_receive_get_addrs() [START]");
  74. loop {
  75. let _get_addrs = self.get_addrs_sub.receive().await?;
  76. debug!(target: "net", "ProtocolAddress::handle_receive_get_addrs() received GetAddrs message");
  77. // Loads the list of hosts.
  78. let addrs = self.hosts.load_all().await;
  79. debug!(
  80. target: "net",
  81. "ProtocolAddress::handle_receive_get_addrs() sending {} addrs",
  82. addrs.len()
  83. );
  84. // Creates an address messages containing host address.
  85. let addrs_msg = message::AddrsMessage { addrs };
  86. // Sends the address message across the channel.
  87. self.channel.clone().send(addrs_msg).await?;
  88. }
  89. }
  90. async fn send_addrs(self: Arc<Self>, addrs: Vec<Url>) -> Result<()> {
  91. debug!(target: "net", "ProtocolAddress::send_addrs() [START]");
  92. loop {
  93. let addrs = addrs.clone();
  94. let addr_msg = message::AddrsMessage { addrs };
  95. self.channel.clone().send(addr_msg).await?;
  96. async_util::sleep(SEND_ADDR_SLEEP_SECONDS).await;
  97. }
  98. }
  99. }
  100. #[async_trait]
  101. impl ProtocolBase for ProtocolAddress {
  102. /// Starts the address protocol. Runs receive address and get address
  103. /// protocols on the protocol task manager. Then sends get-address
  104. /// message.
  105. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  106. let type_id = self.channel.session_type_id();
  107. // if it's an outbound session + has an external address
  108. // send our address
  109. if type_id == SESSION_OUTBOUND && self.settings.external_addr.is_some() {
  110. self.jobsman.clone().start(executor.clone());
  111. self.jobsman
  112. .clone()
  113. .spawn(
  114. self.clone().send_addrs(vec![self.settings.external_addr.clone().unwrap()]),
  115. executor.clone(),
  116. )
  117. .await;
  118. }
  119. debug!(target: "net", "ProtocolAddress::start() [START]");
  120. self.jobsman.clone().start(executor.clone());
  121. self.jobsman.clone().spawn(self.clone().handle_receive_addrs(), executor.clone()).await;
  122. self.jobsman.clone().spawn(self.clone().handle_receive_get_addrs(), executor).await;
  123. // Send get_address message.
  124. let get_addrs = message::GetAddrsMessage {};
  125. let _ = self.channel.clone().send(get_addrs).await;
  126. debug!(target: "net", "ProtocolAddress::start() [END]");
  127. Ok(())
  128. }
  129. fn name(&self) -> &'static str {
  130. "ProtocolAddress"
  131. }
  132. }