channel.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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};
  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::{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. 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. 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. Calls `send_message` that creates
  167. /// a new payload and sends it over the network transport as a packet.
  168. /// Returns an error if something goes wrong.
  169. pub async fn send<M: message::Message>(&self, message: &M) -> Result<()> {
  170. debug!(
  171. target: "net::channel::send()", "[START] command={} {:?}",
  172. M::NAME, self,
  173. );
  174. if self.is_stopped() {
  175. return Err(Error::ChannelStopped)
  176. }
  177. // Catch failure and stop channel, return a net error
  178. if let Err(e) = self.send_message(message).await {
  179. if self.session.upgrade().unwrap().type_id() & (SESSION_ALL & !SESSION_REFINE) != 0 {
  180. error!(
  181. target: "net::channel::send()", "[P2P] Channel send error for [{:?}]: {}",
  182. self, e
  183. );
  184. }
  185. self.stop().await;
  186. return Err(Error::ChannelStopped)
  187. }
  188. debug!(
  189. target: "net::channel::send()", "[END] command={} {:?}",
  190. M::NAME, self
  191. );
  192. Ok(())
  193. }
  194. /// Sends an outbound Message by writing data to the given async stream.
  195. async fn send_message<M: message::Message>(&self, payload: &M) -> Result<()> {
  196. let command = M::NAME.to_string();
  197. assert!(!command.is_empty());
  198. assert!(std::mem::size_of::<usize>() <= std::mem::size_of::<u64>());
  199. let stream = &mut *self.writer.lock().await;
  200. let mut buffer = Vec::<u8>::new();
  201. let mut written: usize = 0;
  202. dnetev!(self, SendMessage, {
  203. chan: self.info.clone(),
  204. cmd: command,
  205. time: NanoTimestamp::current_time(),
  206. });
  207. trace!(target: "net::channel::send_message()", "Sending magic...");
  208. written += MAGIC_BYTES.encode_async(stream).await?;
  209. trace!(target: "net::channel::send_message()", "Sent magic");
  210. trace!(target: "net::channel::send_message()", "Sending command...");
  211. written += M::NAME.to_string().encode_async(stream).await?;
  212. trace!(target: "net::channel::send_message()", "Sent command: {}", M::NAME.to_string());
  213. trace!(target: "net::channel::send_message()", "Sending payload...");
  214. // First encode the payload to an intermediate buffer.
  215. payload.encode_async(&mut buffer).await?;
  216. // Then extract the length of the intermediate buffer as a VarInt
  217. // and write to the stream. This is the length of the payload.
  218. // Then encode the payload itself to the stream.
  219. written += VarInt(buffer.len() as u64).encode_async(stream).await?;
  220. written += payload.encode_async(stream).await?;
  221. trace!(target: "net::channel::send_message()", "Sent payload {} bytes, total bytes {}",
  222. buffer.len(), written);
  223. stream.flush().await?;
  224. Ok(())
  225. }
  226. /// Returns a decoded Message command.
  227. /// We start by extracting the length from the stream, then allocate
  228. /// the precise buffer for this length using stream.take(). This provides
  229. /// a basic DDOS protection.
  230. pub async fn read_command<R: AsyncRead + Unpin + Send + Sized>(
  231. &self,
  232. stream: &mut R,
  233. ) -> Result<String> {
  234. // Messages should have a 4 byte header of magic digits.
  235. // This is used for network debugging.
  236. let mut magic = [0u8; 4];
  237. trace!(target: "net::channel::read_command()", "Reading magic...");
  238. stream.read_exact(&mut magic).await?;
  239. trace!(target: "net::channel::read_command()", "Read magic {:?}", magic);
  240. if magic != MAGIC_BYTES {
  241. error!(target: "net::channel::read_command", "Error: Magic bytes mismatch");
  242. return Err(Error::MalformedPacket)
  243. }
  244. let cmd_len = VarInt::decode_async(stream).await?.0;
  245. let mut take = stream.take(cmd_len);
  246. let mut bytes = Vec::new();
  247. for _ in 0..cmd_len {
  248. bytes.push(AsyncDecodable::decode_async(&mut take).await?);
  249. }
  250. let command = String::from_utf8(bytes)?;
  251. Ok(command)
  252. }
  253. /// Subscribe to a message on the message subsystem.
  254. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  255. debug!(
  256. target: "net::channel::subscribe_msg()", "[START] command={} {:?}",
  257. M::NAME, self
  258. );
  259. let sub = self.message_subsystem.subscribe::<M>().await;
  260. debug!(
  261. target: "net::channel::subscribe_msg()", "[END] command={} {:?}",
  262. M::NAME, self
  263. );
  264. sub
  265. }
  266. /// Handle network errors. Panic if error passes silently, otherwise
  267. /// broadcast the error.
  268. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  269. debug!(target: "net::channel::handle_stop()", "[START] {:?}", self);
  270. self.stopped.store(true, SeqCst);
  271. match result {
  272. Ok(()) => panic!("Channel task should never complete without error status"),
  273. // Send this error to all channel subscribers
  274. Err(e) => {
  275. self.stop_publisher.notify(Error::ChannelStopped).await;
  276. self.message_subsystem.trigger_error(e).await;
  277. }
  278. }
  279. debug!(target: "net::channel::handle_stop()", "[END] {:?}", self);
  280. }
  281. /// Run the receive loop. Start receiving messages or handle network failure.
  282. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  283. debug!(target: "net::channel::main_receive_loop()", "[START] {:?}", self);
  284. // Acquire reader lock
  285. let reader = &mut *self.reader.lock().await;
  286. // Run loop
  287. loop {
  288. let command = match self.read_command(reader).await {
  289. Ok(command) => command,
  290. Err(err) => {
  291. if Self::is_eof_error(&err) {
  292. info!(
  293. target: "net::channel::main_receive_loop()",
  294. "[P2P] Channel inbound connection {} disconnected",
  295. self.address(),
  296. );
  297. } else if self.session.upgrade().unwrap().type_id() &
  298. (SESSION_ALL & !SESSION_REFINE) !=
  299. 0
  300. {
  301. error!(
  302. target: "net::channel::main_receive_loop()",
  303. "[P2P] Read error on channel {}: {}",
  304. self.address(), err,
  305. );
  306. }
  307. debug!(
  308. target: "net::channel::main_receive_loop()",
  309. "Stopping channel {:?}", self
  310. );
  311. self.stop().await;
  312. return Err(Error::ChannelStopped)
  313. }
  314. };
  315. dnetev!(self, RecvMessage, {
  316. chan: self.info.clone(),
  317. cmd: command.clone(),
  318. time: NanoTimestamp::current_time(),
  319. });
  320. // Send result to our publishers
  321. match self.message_subsystem.notify(&command, reader).await {
  322. Ok(()) => {}
  323. // If we're getting messages without dispatchers, it's spam.
  324. Err(Error::MissingDispatcher) => {
  325. debug!(target: "net::channel::main_receive_loop()", "Stopping channel {:?}", self);
  326. if let BanPolicy::Strict = self.p2p().settings().read().await.ban_policy {
  327. self.ban(self.address()).await;
  328. }
  329. self.stop().await;
  330. return Err(Error::ChannelStopped)
  331. }
  332. Err(_) => unreachable!("You added a new error in notify()"),
  333. }
  334. }
  335. }
  336. /// Ban a malicious peer and stop the channel.
  337. pub async fn ban(&self, peer: &Url) {
  338. debug!(target: "net::channel::ban()", "START {:?}", self);
  339. debug!(target: "net::channel::ban()", "Peer: {:?}", peer);
  340. // Just store the hostname if this is an inbound session.
  341. // This will block all ports from this peer by setting
  342. // `hosts.block_all_ports()` to true.
  343. let peer = {
  344. if self.session_type_id() & SESSION_INBOUND != 0 {
  345. if peer.host_str().is_none() {
  346. error!("[P2P] ban() caught Url without host: {:?}", peer);
  347. return
  348. }
  349. // An inbound Tor connection can't really be banned :)
  350. #[cfg(feature = "p2p-tor")]
  351. if (peer.scheme() == "tor" || peer.scheme() == "tor+tls") &&
  352. self.p2p().hosts().is_local_host(peer)
  353. {
  354. return
  355. }
  356. #[cfg(feature = "p2p-unix")]
  357. if peer.scheme() == "unix" {
  358. return
  359. }
  360. let mut addr = peer.clone();
  361. addr.set_port(None).unwrap();
  362. addr
  363. } else {
  364. peer.clone()
  365. }
  366. };
  367. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  368. self.p2p().hosts().move_host(&peer, last_seen, HostColor::Black).unwrap();
  369. self.stop().await;
  370. debug!(target: "net::channel::ban()", "STOP {:?}", self);
  371. }
  372. /// Returns the relevant socket address for this connection. If this is
  373. /// an outbound connection, the transport-processed resolve_addr will
  374. /// be returned. Otherwise for inbound connections it will default
  375. /// to connect_addr.
  376. pub fn address(&self) -> &Url {
  377. if self.info.resolve_addr.is_some() {
  378. self.info.resolve_addr.as_ref().unwrap()
  379. } else {
  380. &self.info.connect_addr
  381. }
  382. }
  383. /// Returns the socket address that has undergone transport
  384. /// processing, if it exists. Returns None otherwise.
  385. pub fn resolve_addr(&self) -> Option<Url> {
  386. self.info.resolve_addr.clone()
  387. }
  388. /// Return the socket address without transport processing.
  389. pub fn connect_addr(&self) -> &Url {
  390. &self.info.connect_addr
  391. }
  392. /// Set the VersionMessage of the node this channel is connected
  393. /// to. Called on receiving a version message in `ProtocolVersion`.
  394. pub(crate) async fn set_version(&self, version: Arc<VersionMessage>) {
  395. *self.version.lock().await = Some(version);
  396. }
  397. /// Returns the inner [`MessageSubsystem`] reference
  398. pub fn message_subsystem(&self) -> &MessageSubsystem {
  399. &self.message_subsystem
  400. }
  401. fn session(&self) -> Arc<dyn Session> {
  402. self.session.upgrade().unwrap()
  403. }
  404. pub fn session_type_id(&self) -> SessionBitFlag {
  405. let session = self.session();
  406. session.type_id()
  407. }
  408. fn p2p(&self) -> P2pPtr {
  409. self.session().p2p()
  410. }
  411. fn is_eof_error(err: &Error) -> bool {
  412. match err {
  413. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  414. _ => false,
  415. }
  416. }
  417. }
  418. impl fmt::Debug for Channel {
  419. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  420. write!(f, "<Channel addr='{}' id={}>", self.address(), self.info.id)
  421. }
  422. }