channel.rs 16 KB

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