client.rs 15 KB

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