protocol_address.rs 5.3 KB

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