client.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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, HashSet},
  20. sync::{
  21. atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
  22. Arc,
  23. },
  24. };
  25. use darkfi::{
  26. event_graph2::{proto::EventPut, Event, NULL_ID},
  27. system::Subscription,
  28. Error, Result,
  29. };
  30. use darkfi_serial::{deserialize_async_partial, serialize_async};
  31. use futures::FutureExt;
  32. use log::{debug, error, warn};
  33. use smol::{
  34. io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader},
  35. lock::Mutex,
  36. net::SocketAddr,
  37. prelude::{AsyncRead, AsyncWrite},
  38. };
  39. use super::{server::IrcServer, Privmsg, SERVER_NAME};
  40. const PENALTY_LIMIT: usize = 5;
  41. /// Reply types, we can either send server replies, or client replies.
  42. pub enum ReplyType {
  43. /// Server reply, we have to use numerics
  44. Server((u16, String)),
  45. /// Client reply, message from someone to some{one,where}
  46. Client((String, String)),
  47. /// Pong reply, we just use server origin
  48. Pong(String),
  49. /// CAP reply
  50. Cap(String),
  51. }
  52. /// Stateful IRC client, used for each client connection
  53. pub struct Client {
  54. /// Pointer to parent `IrcServer`
  55. pub server: Arc<IrcServer>,
  56. /// Subscription for incoming events
  57. pub incoming: Subscription<Event>,
  58. /// Client socket addr
  59. pub addr: SocketAddr,
  60. /// ID of the last sent event
  61. pub last_sent: Mutex<blake3::Hash>,
  62. /// Active (joined) channels for this client
  63. pub channels: Mutex<HashSet<String>>,
  64. /// Penalty counter, when limit is reached, disconnect client
  65. pub penalty: AtomicUsize,
  66. /// Registration marker
  67. pub registered: AtomicBool,
  68. /// Registration pause marker
  69. pub reg_paused: AtomicBool,
  70. /// Client username
  71. pub username: Mutex<String>,
  72. /// Client nickname
  73. pub nickname: Mutex<String>,
  74. /// Client realname
  75. pub realname: Mutex<String>,
  76. /// Client caps
  77. pub caps: Mutex<HashMap<String, bool>>,
  78. }
  79. impl Client {
  80. /// Instantiate a new Client.
  81. pub async fn new(
  82. server: Arc<IrcServer>,
  83. incoming: Subscription<Event>,
  84. addr: SocketAddr,
  85. ) -> Result<Self> {
  86. let caps = HashMap::from([("no-history".to_string(), false)]);
  87. Ok(Self {
  88. server,
  89. incoming,
  90. addr,
  91. last_sent: Mutex::new(NULL_ID),
  92. channels: Mutex::new(HashSet::new()),
  93. penalty: AtomicUsize::new(0),
  94. registered: AtomicBool::new(false),
  95. reg_paused: AtomicBool::new(false),
  96. username: Mutex::new(String::from("*")),
  97. nickname: Mutex::new(String::from("*")),
  98. realname: Mutex::new(String::from("*")),
  99. caps: Mutex::new(caps),
  100. })
  101. }
  102. /// This function handles a single IRC client. We listen to messages from the
  103. /// IRC client and relay them to the network, and we also get notified of
  104. /// incoming messages and relay them to the IRC client. The notifications come
  105. /// from events being inserted into the Event Graph.
  106. pub async fn multiplex_connection<S>(&self, stream: S) -> Result<()>
  107. where
  108. S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
  109. {
  110. let (reader, mut writer) = io::split(stream);
  111. let mut reader = BufReader::new(reader);
  112. // Our buffer for the client line
  113. let mut line = String::new();
  114. loop {
  115. futures::select! {
  116. // Process message from the IRC client
  117. r = reader.read_line(&mut line).fuse() => {
  118. // If something failed during reading, we disconnect.
  119. if let Err(e) = r {
  120. error!("[IRC CLIENT] Read failed for {}: {}", self.addr, e);
  121. self.incoming.unsubscribe().await;
  122. return Err(Error::ChannelStopped)
  123. }
  124. // If the penalty limit is reached, disconnect the client.
  125. if self.penalty.load(SeqCst) == PENALTY_LIMIT {
  126. self.incoming.unsubscribe().await;
  127. return Err(Error::ChannelStopped)
  128. }
  129. // We'll be strict here and disconnect the client
  130. // in case line processing failed in any way.
  131. match self.process_client_line(&line, &mut writer).await {
  132. // If we got an event back, we should broadcast it.
  133. // This means we add it to our DAG, and the DAG will
  134. // handle the rest of the propagation.
  135. Ok(Some(event)) => {
  136. // Update the last sent event.
  137. *self.last_sent.lock().await = event.id();
  138. // If it fails for some reason, for now, we just note it
  139. // and pass.
  140. if let Err(e) = self.server.darkirc.event_graph.dag_insert(event.clone()).await {
  141. error!("[IRC CLIENT] Failed inserting new event to DAG: {}", e);
  142. } else {
  143. // Otherwise, broadcast it
  144. self.server.darkirc.p2p.broadcast(&EventPut(event)).await;
  145. }
  146. }
  147. // If we got nothing, we just pass.
  148. Ok(None) => {}
  149. // If we got an error, we disconnect the client.
  150. Err(e) => {
  151. self.incoming.unsubscribe().await;
  152. return Err(e)
  153. }
  154. }
  155. // Clear the line buffer
  156. line = String::new();
  157. continue
  158. }
  159. // Process message from the network. These should only be PRIVMSG.
  160. r = self.incoming.receive().fuse() => {
  161. // We will skip this if it's our own message.
  162. if *self.last_sent.lock().await == r.id() {
  163. continue
  164. }
  165. // Try to deserialize the `Event`'s content into a `Privmsg`
  166. let mut privmsg: Privmsg = match deserialize_async_partial(r.content()).await {
  167. Ok((v, _)) => v,
  168. Err(e) => {
  169. error!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  170. continue
  171. }
  172. };
  173. // If successful, potentially decrypt it:
  174. self.server.try_decrypt(&mut privmsg).await;
  175. // If we have this channel, or it's a DM to our nickname, forward
  176. // it to the client.
  177. let have_channel = self.channels.lock().await.contains(&privmsg.channel);
  178. let msg_for_self = *self.nickname.lock().await == privmsg.channel;
  179. if have_channel || msg_for_self {
  180. // Add the nickname to the list of nicks on the channel
  181. (*self.server.channels.lock().await).get_mut(&privmsg.channel)
  182. .unwrap().nicks.insert(privmsg.nick.clone());
  183. // Format the message
  184. let msg = format!("PRIVMSG {} :{}", privmsg.channel, privmsg.msg);
  185. // Send it to the client
  186. let reply = ReplyType::Client((privmsg.nick, msg));
  187. if let Err(e) = self.reply(&mut writer, &reply).await {
  188. error!("[IRC CLIENT] Failed writing PRIVMSG to client: {}", e);
  189. continue
  190. }
  191. }
  192. }
  193. }
  194. }
  195. }
  196. /// Send a reply to the IRC client. Matches on the reply type.
  197. async fn reply<W>(&self, writer: &mut W, reply: &ReplyType) -> Result<()>
  198. where
  199. W: AsyncWrite + Unpin,
  200. {
  201. let r = match reply {
  202. ReplyType::Server((rpl, msg)) => format!(":{} {:03} {}", SERVER_NAME, rpl, msg),
  203. ReplyType::Client((nick, msg)) => format!(":{}!~anon@darkirc {}", nick, msg),
  204. ReplyType::Pong(origin) => format!(":{} PONG :{}", SERVER_NAME, origin),
  205. ReplyType::Cap(msg) => format!(":{} {}", SERVER_NAME, msg),
  206. };
  207. debug!("[{}] <-- {}", self.addr, r);
  208. writer.write(r.as_bytes()).await?;
  209. writer.write(b"\r\n").await?;
  210. writer.flush().await?;
  211. Ok(())
  212. }
  213. /// Handle the incoming line given sent by the IRC client
  214. async fn process_client_line<W>(&self, line: &str, writer: &mut W) -> Result<Option<Event>>
  215. where
  216. W: AsyncWrite + Unpin,
  217. {
  218. if line.is_empty() || line == "\n" || line == "\r\n" {
  219. return Err(Error::ParseFailed("Line is empty"))
  220. }
  221. let mut line = line.to_string();
  222. // Remove CRLF
  223. if &line[(line.len() - 2)..] == "\r\n" {
  224. line.pop();
  225. line.pop();
  226. } else if &line[(line.len() - 1)..] == "\n" {
  227. line.pop();
  228. } else {
  229. return Err(Error::ParseFailed("Line doesn't end with CR/LF"))
  230. }
  231. // Parse the line
  232. let mut tokens = line.split_ascii_whitespace();
  233. // Commands can begin with :garbage, but we will reject clients
  234. // doing that for now to keep the protocol simple and focused.
  235. let cmd = tokens.next().ok_or(Error::ParseFailed("Invalid command line"))?;
  236. let args = line.replacen(cmd, "", 1);
  237. let cmd = cmd.to_uppercase();
  238. debug!("[{}] --> {}{}", self.addr, cmd, args);
  239. // Handle the command. These implementations are in `command.rs`.
  240. let replies: Vec<ReplyType> = match cmd.as_str() {
  241. "ADMIN" => self.handle_cmd_admin(&args).await?,
  242. "CAP" => self.handle_cmd_cap(&args).await?,
  243. "INFO" => self.handle_cmd_info(&args).await?,
  244. "JOIN" => self.handle_cmd_join(&args).await?,
  245. "LIST" => self.handle_cmd_list(&args).await?,
  246. "MODE" => self.handle_cmd_mode(&args).await?,
  247. "MOTD" => self.handle_cmd_motd(&args).await?,
  248. "NAMES" => self.handle_cmd_names(&args).await?,
  249. "NICK" => self.handle_cmd_nick(&args).await?,
  250. "PART" => self.handle_cmd_part(&args).await?,
  251. "PING" => self.handle_cmd_ping(&args).await?,
  252. "PRIVMSG" => self.handle_cmd_privmsg(&args).await?,
  253. "REHASH" => self.handle_cmd_rehash(&args).await?,
  254. "TOPIC" => self.handle_cmd_topic(&args).await?,
  255. "USER" => self.handle_cmd_user(&args).await?,
  256. "VERSION" => self.handle_cmd_version(&args).await?,
  257. "QUIT" => return Err(Error::ChannelStopped),
  258. _ => {
  259. warn!("[IRC CLIENT] Unimplemented \"{}\" command", cmd);
  260. vec![]
  261. }
  262. };
  263. // Depending on the reply type, we send according messages.
  264. for reply in replies.iter() {
  265. self.reply(writer, reply).await?;
  266. }
  267. // If the command was a PRIVMSG the client sent, we need to encrypt it and
  268. // create an Event to broadcast and return it from this function. So let's try.
  269. // We also do not allow sending unencrypted DMs. In that case, we send a notice
  270. // to the client to inform them that the feature is not enabled.
  271. // NOTE: This is not the most performant way to do this, probably not even
  272. // TODO: the best place to do it. Patches welcome. It's also a bit fragile
  273. // since we assume that `handle_cmd_privmsg()` won't return any replies.
  274. if cmd.as_str() == "PRIVMSG" && replies.is_empty() {
  275. let channel = args.split_ascii_whitespace().next().unwrap().to_string();
  276. let msg_offset = args.find(':').unwrap() + 1;
  277. let (_, msg) = args.split_at(msg_offset);
  278. let mut privmsg = Privmsg {
  279. channel,
  280. nick: self.nickname.lock().await.to_string(),
  281. msg: msg.to_string(),
  282. };
  283. // Encrypt the Privmsg if an encryption method is available.
  284. self.server.try_encrypt(&mut privmsg).await;
  285. // Build a DAG event and return it.
  286. let event = Event::new(
  287. serialize_async(&privmsg).await,
  288. self.server.darkirc.event_graph.clone(),
  289. )
  290. .await;
  291. return Ok(Some(event))
  292. }
  293. Ok(None)
  294. }
  295. }