channel.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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::{
  19. collections::HashMap,
  20. fmt,
  21. sync::{
  22. atomic::{AtomicBool, Ordering::SeqCst},
  23. Arc,
  24. },
  25. time::UNIX_EPOCH,
  26. };
  27. use darkfi_serial::{
  28. async_trait, AsyncDecodable, AsyncEncodable, SerialDecodable, SerialEncodable, VarInt,
  29. };
  30. use log::{debug, error, info, trace, warn};
  31. use rand::{rngs::OsRng, Rng};
  32. use smol::{
  33. io::{self, AsyncRead, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
  34. lock::{Mutex as AsyncMutex, OnceCell},
  35. Executor,
  36. };
  37. use url::Url;
  38. use super::{
  39. dnet::{self, dnetev, DnetEvent},
  40. hosts::{HostColor, HostsPtr},
  41. message,
  42. message::{SerializedMessage, VersionMessage, MAX_COMMAND_LENGTH},
  43. message_publisher::{MessageSubscription, MessageSubsystem},
  44. metering::{MeteringConfiguration, MeteringQueue},
  45. p2p::P2pPtr,
  46. session::{
  47. Session, SessionBitFlag, SessionWeakPtr, SESSION_ALL, SESSION_INBOUND, SESSION_REFINE,
  48. },
  49. transport::PtStream,
  50. };
  51. use crate::{
  52. net::BanPolicy,
  53. system::{msleep, Publisher, PublisherPtr, StoppableTask, StoppableTaskPtr, Subscription},
  54. util::time::NanoTimestamp,
  55. Error, Result,
  56. };
  57. /// Atomic pointer to async channel
  58. pub type ChannelPtr = Arc<Channel>;
  59. /// Channel debug info
  60. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  61. pub struct ChannelInfo {
  62. pub resolve_addr: Option<Url>,
  63. pub connect_addr: Url,
  64. pub start_time: u64,
  65. pub id: u32,
  66. }
  67. impl ChannelInfo {
  68. fn new(resolve_addr: Option<Url>, connect_addr: Url, start_time: u64) -> Self {
  69. Self { resolve_addr, connect_addr, start_time, id: OsRng.gen() }
  70. }
  71. }
  72. /// Async channel for communication between nodes.
  73. pub struct Channel {
  74. /// The reading half of the transport stream
  75. reader: AsyncMutex<ReadHalf<Box<dyn PtStream>>>,
  76. /// The writing half of the transport stream
  77. writer: AsyncMutex<WriteHalf<Box<dyn PtStream>>>,
  78. /// The message subsystem instance for this channel
  79. message_subsystem: MessageSubsystem,
  80. /// Publisher listening for stop signal for closing this channel
  81. stop_publisher: PublisherPtr<Error>,
  82. /// Task that is listening for the stop signal
  83. receive_task: StoppableTaskPtr,
  84. /// A boolean marking if this channel is stopped
  85. stopped: AtomicBool,
  86. /// Weak pointer to respective session
  87. pub(in crate::net) session: SessionWeakPtr,
  88. /// The version message of the node we are connected to.
  89. /// Some if the version exchange has already occurred, None
  90. /// otherwise.
  91. pub version: OnceCell<Arc<VersionMessage>>,
  92. /// Channel debug info
  93. pub info: ChannelInfo,
  94. /// Map holding a `MeteringQueue` for each [`Message`] to perform
  95. /// rate limiting of propagation towards the stream.
  96. metering_map: AsyncMutex<HashMap<String, MeteringQueue>>,
  97. }
  98. impl Channel {
  99. /// Sets up a new channel. Creates a reader and writer [`PtStream`] and
  100. /// the message publisher subsystem. Performs a network handshake on the
  101. /// subsystem dispatchers.
  102. pub async fn new(
  103. stream: Box<dyn PtStream>,
  104. resolve_addr: Option<Url>,
  105. connect_addr: Url,
  106. session: SessionWeakPtr,
  107. ) -> Arc<Self> {
  108. let (reader, writer) = io::split(stream);
  109. let reader = AsyncMutex::new(reader);
  110. let writer = AsyncMutex::new(writer);
  111. let message_subsystem = MessageSubsystem::new();
  112. Self::setup_dispatchers(&message_subsystem).await;
  113. let start_time = UNIX_EPOCH.elapsed().unwrap().as_secs();
  114. let info = ChannelInfo::new(resolve_addr, connect_addr.clone(), start_time);
  115. let metering_map = AsyncMutex::new(HashMap::new());
  116. Arc::new(Self {
  117. reader,
  118. writer,
  119. message_subsystem,
  120. stop_publisher: Publisher::new(),
  121. receive_task: StoppableTask::new(),
  122. stopped: AtomicBool::new(false),
  123. session,
  124. version: OnceCell::new(),
  125. info,
  126. metering_map,
  127. })
  128. }
  129. /// Perform network handshake for message subsystem dispatchers.
  130. async fn setup_dispatchers(subsystem: &MessageSubsystem) {
  131. subsystem.add_dispatch::<message::VersionMessage>().await;
  132. subsystem.add_dispatch::<message::VerackMessage>().await;
  133. subsystem.add_dispatch::<message::PingMessage>().await;
  134. subsystem.add_dispatch::<message::PongMessage>().await;
  135. subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  136. subsystem.add_dispatch::<message::AddrsMessage>().await;
  137. }
  138. /// Starts the channel. Runs a receive loop to start receiving messages
  139. /// or handles a network failure.
  140. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  141. debug!(target: "net::channel::start()", "START {self:?}");
  142. let self_ = self.clone();
  143. self.receive_task.clone().start(
  144. self.clone().main_receive_loop(),
  145. |result| self_.handle_stop(result),
  146. Error::ChannelStopped,
  147. executor,
  148. );
  149. debug!(target: "net::channel::start()", "END {self:?}");
  150. }
  151. /// Stops the channel.
  152. /// Notifies all publishers that the channel has been closed in `handle_stop()`.
  153. pub async fn stop(&self) {
  154. debug!(target: "net::channel::stop()", "START {self:?}");
  155. self.receive_task.stop().await;
  156. debug!(target: "net::channel::stop()", "END {self:?}");
  157. }
  158. /// Creates a subscription to a stopped signal.
  159. /// If the channel is stopped then this will return a ChannelStopped error.
  160. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  161. debug!(target: "net::channel::subscribe_stop()", "START {self:?}");
  162. if self.is_stopped() {
  163. return Err(Error::ChannelStopped)
  164. }
  165. let sub = self.stop_publisher.clone().subscribe().await;
  166. debug!(target: "net::channel::subscribe_stop()", "END {self:?}");
  167. Ok(sub)
  168. }
  169. pub fn is_stopped(&self) -> bool {
  170. self.stopped.load(SeqCst)
  171. }
  172. /// Sends a message across a channel. First it converts the message
  173. /// into a `SerializedMessage` and then calls `send_serialized` to send it.
  174. /// Returns an error if something goes wrong.
  175. pub async fn send<M: message::Message>(&self, message: &M) -> Result<()> {
  176. self.send_serialized(
  177. &SerializedMessage::new(message).await,
  178. &M::METERING_SCORE,
  179. &M::METERING_CONFIGURATION,
  180. )
  181. .await
  182. }
  183. /// Sends the encoded payload of provided `SerializedMessage` across the channel.
  184. ///
  185. /// We first check if we should apply some throttling, based on the provided
  186. /// `Message` configuration. We always sleep 2x times more than the expected one,
  187. /// so we don't flood the peer.
  188. /// Then, calls `send_message` that creates a new payload and sends it over the
  189. /// network transport as a packet.
  190. /// Returns an error if something goes wrong.
  191. pub async fn send_serialized(
  192. &self,
  193. message: &SerializedMessage,
  194. metering_score: &u64,
  195. metering_config: &MeteringConfiguration,
  196. ) -> Result<()> {
  197. debug!(
  198. target: "net::channel::send()", "[START] command={} {self:?}",
  199. message.command,
  200. );
  201. // Check if we need to initialize a `MeteringQueue`
  202. // for this specific `Message`.
  203. let mut lock = self.metering_map.lock().await;
  204. if !lock.contains_key(&message.command) {
  205. lock.insert(message.command.clone(), MeteringQueue::new(metering_config.clone()));
  206. }
  207. // Insert metering information and grab potential sleep time.
  208. // It's safe to unwrap here since we initialized the value
  209. // previously.
  210. let queue = lock.get_mut(&message.command).unwrap();
  211. queue.push(metering_score);
  212. let sleep_time = queue.sleep_time();
  213. drop(lock);
  214. // Check if we need to sleep
  215. if let Some(sleep_time) = sleep_time {
  216. let sleep_time = 2 * sleep_time;
  217. debug!(
  218. target: "net::channel::send()",
  219. "[P2P] Channel rate limit is active, sleeping before sending for: {sleep_time} (ms)"
  220. );
  221. msleep(sleep_time).await;
  222. }
  223. // Check if the channel is stopped, so we can abort
  224. if self.is_stopped() {
  225. return Err(Error::ChannelStopped)
  226. }
  227. // Catch failure and stop channel, return a net error
  228. if let Err(e) = self.send_message(message).await {
  229. if self.session.upgrade().unwrap().type_id() & (SESSION_ALL & !SESSION_REFINE) != 0 {
  230. error!(
  231. target: "net::channel::send()", "[P2P] Channel send error for [{self:?}]: {e}"
  232. );
  233. }
  234. self.stop().await;
  235. return Err(Error::ChannelStopped)
  236. }
  237. debug!(
  238. target: "net::channel::send()", "[END] command={} {self:?}",
  239. message.command
  240. );
  241. Ok(())
  242. }
  243. /// Sends the encoded payload of provided `SerializedMessage` by writing
  244. /// the data to the channel async stream.
  245. async fn send_message(&self, message: &SerializedMessage) -> Result<()> {
  246. assert!(!message.command.is_empty());
  247. let stream = &mut *self.writer.lock().await;
  248. let mut written: usize = 0;
  249. dnetev!(self, SendMessage, {
  250. chan: self.info.clone(),
  251. cmd: message.command.clone(),
  252. time: NanoTimestamp::current_time(),
  253. });
  254. trace!(target: "net::channel::send_message()", "Sending magic...");
  255. let magic_bytes = self.p2p().settings().read().await.magic_bytes.0;
  256. written += magic_bytes.encode_async(stream).await?;
  257. trace!(target: "net::channel::send_message()", "Sent magic");
  258. trace!(target: "net::channel::send_message()", "Sending command...");
  259. written += message.command.encode_async(stream).await?;
  260. trace!(target: "net::channel::send_message()", "Sent command: {}", message.command);
  261. trace!(target: "net::channel::send_message()", "Sending payload...");
  262. // First extract the length of the payload as a VarInt and write it to the stream.
  263. written += VarInt(message.payload.len() as u64).encode_async(stream).await?;
  264. // Then write the encoded payload itself to the stream.
  265. stream.write_all(&message.payload).await?;
  266. written += message.payload.len();
  267. trace!(target: "net::channel::send_message()", "Sent payload {} bytes, total bytes {written}",
  268. message.payload.len());
  269. stream.flush().await?;
  270. Ok(())
  271. }
  272. /// Returns a decoded Message command. We start by extracting the length
  273. /// from the stream, then allocate the precise buffer for this length
  274. /// using stream.take(). This manual deserialization provides a basic
  275. /// DDOS protection, since it prevents nodes from sending an arbitarily
  276. /// large payload.
  277. pub async fn read_command<R: AsyncRead + Unpin + Send + Sized>(
  278. &self,
  279. stream: &mut R,
  280. ) -> Result<String> {
  281. // Messages should have a 4 byte header of magic digits.
  282. // This is used for network debugging.
  283. let mut magic = [0u8; 4];
  284. trace!(target: "net::channel::read_command()", "Reading magic...");
  285. stream.read_exact(&mut magic).await?;
  286. trace!(target: "net::channel::read_command()", "Read magic {magic:?}");
  287. let magic_bytes = self.p2p().settings().read().await.magic_bytes.0;
  288. if magic != magic_bytes {
  289. error!(target: "net::channel::read_command", "Error: Magic bytes mismatch");
  290. return Err(Error::MalformedPacket)
  291. }
  292. // First extract the length from the stream
  293. let cmd_len = VarInt::decode_async(stream).await?.0;
  294. if cmd_len > (MAX_COMMAND_LENGTH as u64) {
  295. error!(target: "net::channel::read_command",
  296. "Error: Command length ({cmd_len}) exceeds configured limit ({MAX_COMMAND_LENGTH}). Dropping...");
  297. return Err(Error::MessageInvalid);
  298. }
  299. // Then extract precisely `cmd_len` items from the stream.
  300. let mut take = stream.take(cmd_len);
  301. // Deserialize into a vector of `cmd_len` size.
  302. let mut bytes = vec![0; cmd_len.try_into().unwrap()];
  303. take.read_exact(&mut bytes).await?;
  304. let command = String::from_utf8(bytes)?;
  305. Ok(command)
  306. }
  307. /// Subscribe to a message on the message subsystem.
  308. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  309. debug!(
  310. target: "net::channel::subscribe_msg()", "[START] command={} {self:?}",
  311. M::NAME
  312. );
  313. let sub = self.message_subsystem.subscribe::<M>().await;
  314. debug!(
  315. target: "net::channel::subscribe_msg()", "[END] command={} {self:?}",
  316. M::NAME
  317. );
  318. sub
  319. }
  320. /// Handle network errors. Panic if error passes silently, otherwise
  321. /// broadcast the error.
  322. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  323. debug!(target: "net::channel::handle_stop()", "[START] {self:?}");
  324. self.stopped.store(true, SeqCst);
  325. match result {
  326. Ok(()) => panic!("Channel task should never complete without error status"),
  327. // Send this error to all channel subscribers
  328. Err(e) => {
  329. self.stop_publisher.notify(Error::ChannelStopped).await;
  330. self.message_subsystem.trigger_error(e).await;
  331. }
  332. }
  333. debug!(target: "net::channel::handle_stop()", "[END] {self:?}");
  334. }
  335. /// Run the receive loop. Start receiving messages or handle network failure.
  336. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  337. debug!(target: "net::channel::main_receive_loop()", "[START] {self:?}");
  338. // Acquire reader lock
  339. let reader = &mut *self.reader.lock().await;
  340. // Run loop
  341. loop {
  342. let command = match self.read_command(reader).await {
  343. Ok(command) => command,
  344. Err(err) => {
  345. if Self::is_eof_error(&err) {
  346. info!(
  347. target: "net::channel::main_receive_loop()",
  348. "[P2P] Channel {} disconnected",
  349. self.address()
  350. );
  351. } else if let Error::MessageInvalid = err {
  352. // The command name length has exceeded the limit, this is possibly a malicious attack so ban it
  353. if let BanPolicy::Strict = self.p2p().settings().read().await.ban_policy {
  354. self.ban().await;
  355. }
  356. } else if self.session.upgrade().unwrap().type_id() &
  357. (SESSION_ALL & !SESSION_REFINE) !=
  358. 0
  359. {
  360. error!(
  361. target: "net::channel::main_receive_loop()",
  362. "[P2P] Read error on channel {}: {err}",
  363. self.address()
  364. );
  365. }
  366. debug!(
  367. target: "net::channel::main_receive_loop()",
  368. "Stopping channel {self:?}"
  369. );
  370. return Err(Error::ChannelStopped)
  371. }
  372. };
  373. dnetev!(self, RecvMessage, {
  374. chan: self.info.clone(),
  375. cmd: command.clone(),
  376. time: NanoTimestamp::current_time(),
  377. });
  378. // Send result to our publishers
  379. match self.message_subsystem.notify(&command, reader).await {
  380. Ok(()) => {}
  381. Err(Error::MissingDispatcher) |
  382. Err(Error::MessageInvalid) |
  383. Err(Error::MeteringLimitExceeded) => {
  384. // If we're getting messages without dispatchers or its invalid,
  385. // it's spam. We therefore ban this channel if:
  386. //
  387. // 1) This channel is NOT part of a refine session.
  388. //
  389. // It's possible that nodes can send messages without
  390. // dispatchers during the refinery process. If that happens
  391. // we simply ignore it. Otherwise, it's spam.
  392. //
  393. // 2) BanPolicy is set to Strict.
  394. //
  395. // We only ban if the BanPolicy is set to Strict, which is
  396. // the default setting for most nodes. The exception to
  397. // this is a seed node like Lilith which has BanPolicy::Relaxed
  398. // since it regularly forms connections with nodes sending
  399. // messages it does not have dispatchers for.
  400. if self.session.upgrade().unwrap().type_id() != SESSION_REFINE {
  401. warn!(
  402. target: "net::channel::main_receive_loop()",
  403. "MissingDispatcher|MessageInvalid|MeteringLimitExceeded for command={command}, channel={self:?}"
  404. );
  405. if let BanPolicy::Strict = self.p2p().settings().read().await.ban_policy {
  406. self.ban().await;
  407. }
  408. return Err(Error::ChannelStopped)
  409. }
  410. }
  411. Err(_) => unreachable!("You added a new error in notify()"),
  412. }
  413. }
  414. }
  415. /// Ban a malicious peer and stop the channel.
  416. pub async fn ban(&self) {
  417. debug!(target: "net::channel::ban()", "START {self:?}");
  418. debug!(target: "net::channel::ban()", "Peer: {:?}", self.address());
  419. // Just store the hostname if this is an inbound session.
  420. // This will block all ports from this peer by setting
  421. // `hosts.block_all_ports()` to true.
  422. let peer = {
  423. if self.session_type_id() & SESSION_INBOUND != 0 {
  424. if self.address().host().is_none() {
  425. error!("[P2P] ban() caught Url without host: {:?}", self.address());
  426. return
  427. }
  428. // An inbound Tor connection can't really be banned :)
  429. #[cfg(feature = "p2p-tor")]
  430. if (self.address().scheme() == "tor" || self.address().scheme() == "tor+tls") &&
  431. self.p2p().hosts().is_local_host(self.address())
  432. {
  433. return
  434. }
  435. if self.address().scheme() == "unix" {
  436. return
  437. }
  438. let mut addr = self.address().clone();
  439. addr.set_port(None).unwrap();
  440. addr
  441. } else {
  442. self.address().clone()
  443. }
  444. };
  445. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  446. info!(target: "net::channel::ban()", "Blacklisting peer={peer}");
  447. match self.p2p().hosts().move_host(&peer, last_seen, HostColor::Black) {
  448. Ok(()) => {
  449. info!(target: "net::channel::ban()", "Peer={peer} blacklisted successfully");
  450. }
  451. Err(e) => {
  452. warn!(target: "net::channel::ban()", "Could not blacklisted peer={peer}, err={e}");
  453. }
  454. }
  455. self.stop().await;
  456. debug!(target: "net::channel::ban()", "STOP {self:?}");
  457. }
  458. /// Returns the relevant socket address for this connection. If this is
  459. /// an outbound connection, the transport-processed resolve_addr will
  460. /// be returned. Otherwise for inbound connections it will default
  461. /// to connect_addr.
  462. pub fn address(&self) -> &Url {
  463. if self.info.resolve_addr.is_some() {
  464. self.info.resolve_addr.as_ref().unwrap()
  465. } else {
  466. &self.info.connect_addr
  467. }
  468. }
  469. /// Returns the socket address that has undergone transport
  470. /// processing, if it exists. Returns None otherwise.
  471. pub fn resolve_addr(&self) -> Option<Url> {
  472. self.info.resolve_addr.clone()
  473. }
  474. /// Return the socket address without transport processing.
  475. pub fn connect_addr(&self) -> &Url {
  476. &self.info.connect_addr
  477. }
  478. /// Set the VersionMessage of the node this channel is connected
  479. /// to. Called on receiving a version message in `ProtocolVersion`.
  480. pub(crate) async fn set_version(&self, version: Arc<VersionMessage>) {
  481. self.version.set(version).await.unwrap();
  482. }
  483. /// Should only be called after the version exchange has been completed.
  484. pub fn get_version(&self) -> Arc<VersionMessage> {
  485. self.version.get().unwrap().clone()
  486. }
  487. /// Returns the inner [`MessageSubsystem`] reference
  488. pub fn message_subsystem(&self) -> &MessageSubsystem {
  489. &self.message_subsystem
  490. }
  491. fn session(&self) -> Arc<dyn Session> {
  492. self.session.upgrade().unwrap()
  493. }
  494. pub fn session_type_id(&self) -> SessionBitFlag {
  495. let session = self.session();
  496. session.type_id()
  497. }
  498. #[inline]
  499. pub fn p2p(&self) -> P2pPtr {
  500. self.session().p2p()
  501. }
  502. #[inline]
  503. pub fn hosts(&self) -> HostsPtr {
  504. self.p2p().hosts()
  505. }
  506. fn is_eof_error(err: &Error) -> bool {
  507. match err {
  508. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  509. _ => false,
  510. }
  511. }
  512. }
  513. impl fmt::Debug for Channel {
  514. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  515. write!(f, "<Channel addr='{}' id={}>", self.address(), self.info.id)
  516. }
  517. }