channel.rs 19 KB

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