channel.rs 16 KB

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