client.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. collections::{HashMap, HashSet, VecDeque},
  20. sync::{
  21. atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
  22. Arc,
  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 sled_overlay::sled;
  34. use smol::{
  35. io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader},
  36. lock::{OnceCell, RwLock},
  37. net::SocketAddr,
  38. prelude::{AsyncRead, AsyncWrite},
  39. };
  40. use super::{
  41. server::{IrcServer, MAX_MSG_LEN, MAX_NICK_LEN},
  42. NickServ, Privmsg, SERVER_NAME,
  43. };
  44. const PENALTY_LIMIT: usize = 5;
  45. /// Reply types, we can either send server replies, or client replies.
  46. pub enum ReplyType {
  47. /// Server reply, we have to use numerics
  48. Server((u16, String)),
  49. /// Client reply, message from someone to some{one,where}
  50. Client((String, String)),
  51. /// Pong reply, we just use server origin
  52. Pong(String),
  53. /// CAP reply
  54. Cap(String),
  55. /// NOTICE reply (from, to, what)
  56. Notice((String, String, String)),
  57. }
  58. /// Stateful IRC client handler, used for each client connection
  59. pub struct Client {
  60. /// Pointer to parent `IrcServer`
  61. pub server: Arc<IrcServer>,
  62. /// Subscription for incoming events
  63. pub incoming: Subscription<Event>,
  64. /// Client socket addr
  65. pub addr: SocketAddr,
  66. /// ID of the last sent event
  67. pub last_sent: RwLock<blake3::Hash>,
  68. /// Active (joined) channels for this client
  69. pub channels: RwLock<HashSet<String>>,
  70. /// Penalty counter, when limit is reached, disconnect client
  71. pub penalty: AtomicUsize,
  72. /// Registration marker
  73. pub registered: AtomicBool,
  74. /// Registration pause marker
  75. pub reg_paused: AtomicBool,
  76. /// CAP END marker
  77. pub is_cap_end: AtomicBool,
  78. /// Password setup marker
  79. pub is_pass_set: AtomicBool,
  80. /// Client username
  81. pub username: Arc<RwLock<String>>,
  82. /// Client nickname
  83. pub nickname: Arc<RwLock<String>>,
  84. /// Client realname
  85. pub realname: RwLock<String>,
  86. /// Client caps
  87. pub caps: RwLock<HashMap<String, bool>>,
  88. /// Set of seen messages for the user
  89. /// TODO: It grows indefinitely, needs to be pruned.
  90. pub seen: OnceCell<sled::Tree>,
  91. /// NickServ instance
  92. pub nickserv: Arc<NickServ>,
  93. }
  94. impl Client {
  95. /// Instantiate a new Client.
  96. pub async fn new(
  97. server: Arc<IrcServer>,
  98. incoming: Subscription<Event>,
  99. addr: SocketAddr,
  100. ) -> Result<Self> {
  101. let caps =
  102. HashMap::from([("no-history".to_string(), false), ("no-autojoin".to_string(), false)]);
  103. let username = Arc::new(RwLock::new(String::from("*")));
  104. let nickname = Arc::new(RwLock::new(String::from("*")));
  105. Ok(Self {
  106. server: server.clone(),
  107. incoming,
  108. addr,
  109. last_sent: RwLock::new(NULL_ID),
  110. channels: RwLock::new(HashSet::new()),
  111. penalty: AtomicUsize::new(0),
  112. registered: AtomicBool::new(false),
  113. reg_paused: AtomicBool::new(false),
  114. is_cap_end: AtomicBool::new(false),
  115. is_pass_set: AtomicBool::new(false),
  116. username: username.clone(),
  117. nickname: nickname.clone(),
  118. realname: RwLock::new(String::from("*")),
  119. caps: RwLock::new(caps),
  120. seen: OnceCell::new(),
  121. nickserv: Arc::new(
  122. NickServ::new(username.clone(), nickname.clone(), server.clone()).await?,
  123. ),
  124. })
  125. }
  126. /// This function handles a single IRC client. We listen to messages from the
  127. /// IRC client and relay them to the network, and we also get notified of
  128. /// incoming messages and relay them to the IRC client. The notifications come
  129. /// from events being inserted into the Event Graph.
  130. pub async fn multiplex_connection<S>(&self, stream: S) -> Result<()>
  131. where
  132. S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
  133. {
  134. let (reader, mut writer) = io::split(stream);
  135. let mut reader = BufReader::new(reader);
  136. // Our buffer for the client line
  137. let mut line = String::new();
  138. let mut args_queue: VecDeque<_> = VecDeque::new();
  139. loop {
  140. futures::select! {
  141. // Process message from the IRC client
  142. r = reader.read_line(&mut line).fuse() => {
  143. // If something failed during reading, we disconnect.
  144. if let Err(e) = r {
  145. error!("[IRC CLIENT] Read failed for {}: {}", self.addr, e);
  146. self.incoming.unsubscribe().await;
  147. return Err(Error::ChannelStopped)
  148. }
  149. // If the penalty limit is reached, disconnect the client.
  150. if self.penalty.load(SeqCst) == PENALTY_LIMIT {
  151. self.incoming.unsubscribe().await;
  152. return Err(Error::ChannelStopped)
  153. }
  154. // We'll be strict here and disconnect the client
  155. // in case line processing failed in any way.
  156. match self.process_client_line(&line, &mut writer, &mut args_queue).await {
  157. // If we got an event back, we should broadcast it.
  158. // This means we add it to our DAG, and the DAG will
  159. // handle the rest of the propagation.
  160. Ok(Some(events)) => {
  161. for event in events {
  162. // Update the last sent event.
  163. let event_id = event.id();
  164. *self.last_sent.write().await = event_id;
  165. // If it fails for some reason, for now, we just note it
  166. // and pass.
  167. if let Err(e) = self.server.darkirc.event_graph.dag_insert(&[event.clone()]).await {
  168. error!("[IRC CLIENT] Failed inserting new event to DAG: {}", e);
  169. } else {
  170. // We sent this, so it should be considered seen.
  171. if let Err(e) = self.mark_seen(&event_id).await {
  172. error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({}) failed: {}", event_id, e);
  173. return Err(e)
  174. }
  175. // Otherwise, broadcast it
  176. self.server.darkirc.p2p.broadcast(&EventPut(event)).await;
  177. }
  178. }
  179. }
  180. // If we got nothing, we just pass.
  181. Ok(None) => {}
  182. // If we got an error, we disconnect the client.
  183. Err(e) => {
  184. self.incoming.unsubscribe().await;
  185. return Err(e)
  186. }
  187. }
  188. // Clear the line buffer
  189. line = String::new();
  190. }
  191. // Process message from the network. These should only be PRIVMSG.
  192. r = self.incoming.receive().fuse() => {
  193. // We will skip this if it's our own message.
  194. let event_id = r.id();
  195. if *self.last_sent.read().await == event_id {
  196. continue
  197. }
  198. // If this event was seen, skip it
  199. match self.is_seen(&event_id).await {
  200. Ok(true) => continue,
  201. Ok(false) => {},
  202. Err(e) => {
  203. error!("[IRC CLIENT] (multiplex_connection) self.is_seen({}) failed: {}", event_id, e);
  204. return Err(e)
  205. }
  206. }
  207. // Try to deserialize the `Event`'s content into a `Privmsg`
  208. let mut privmsg: Privmsg = match deserialize_async_partial(r.content()).await {
  209. Ok((v, _)) => v,
  210. Err(e) => {
  211. error!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  212. continue
  213. }
  214. };
  215. // We should skip any attempts to contact services from the network.
  216. if ["nickserv", "chanserv"].contains(&privmsg.nick.to_lowercase().as_str()) {
  217. continue
  218. }
  219. // If successful, potentially decrypt it:
  220. self.server.try_decrypt(&mut privmsg).await;
  221. // If we have this channel, or it's a DM, forward it to the client.
  222. // As a DM, we consider something that is <= MAX_NICK_LEN, and does not
  223. // start with the '#' character. With ChaCha, the ciphertext should be
  224. // longer than our MAX_NICK_LEN, so in case it is garbled, it should be
  225. // skipped by this code.
  226. let have_channel = self.channels.read().await.contains(&privmsg.channel);
  227. let msg_for_self = !privmsg.channel.starts_with('#') && privmsg.channel.as_bytes().len() <= MAX_NICK_LEN;
  228. if have_channel || msg_for_self {
  229. // Add the nickname to the list of nicks on the channel, if it's a channel.
  230. let mut chans_lock = self.server.channels.write().await;
  231. if let Some(chan) = chans_lock.get_mut(&privmsg.channel) {
  232. chan.nicks.insert(privmsg.nick.clone());
  233. }
  234. drop(chans_lock);
  235. // Format the message
  236. let msg = format!("PRIVMSG {} :{}", privmsg.channel, privmsg.msg);
  237. // Send it to the client
  238. let reply = ReplyType::Client((privmsg.nick, msg));
  239. if let Err(e) = self.reply(&mut writer, &reply).await {
  240. error!("[IRC CLIENT] Failed writing PRIVMSG to client: {}", e);
  241. continue
  242. }
  243. // Mark the message as seen for this USER
  244. if let Err(e) = self.mark_seen(&event_id).await {
  245. error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({}) failed: {}", event_id, e);
  246. return Err(e)
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }
  253. /// Send a reply to the IRC client. Matches on the reply type.
  254. async fn reply<W>(&self, writer: &mut W, reply: &ReplyType) -> Result<()>
  255. where
  256. W: AsyncWrite + Unpin,
  257. {
  258. let r = match reply {
  259. ReplyType::Server((rpl, msg)) => format!(":{} {:03} {}", SERVER_NAME, rpl, msg),
  260. ReplyType::Client((nick, msg)) => format!(":{}!~anon@darkirc {}", nick, msg),
  261. ReplyType::Pong(origin) => format!(":{} PONG :{}", SERVER_NAME, origin),
  262. ReplyType::Cap(msg) => format!(":{} {}", SERVER_NAME, msg),
  263. ReplyType::Notice((src, dst, msg)) => {
  264. format!(":{}!~anon@darkirc NOTICE {} :{}", src, dst, msg)
  265. }
  266. };
  267. debug!("[{}] <-- {}", self.addr, r);
  268. writer.write(r.as_bytes()).await?;
  269. writer.write(b"\r\n").await?;
  270. writer.flush().await?;
  271. Ok(())
  272. }
  273. /// Handle the incoming line given sent by the IRC client
  274. async fn process_client_line<W>(
  275. &self,
  276. line: &str,
  277. writer: &mut W,
  278. args_queue: &mut VecDeque<String>,
  279. ) -> Result<Option<Vec<Event>>>
  280. where
  281. W: AsyncWrite + Unpin,
  282. {
  283. if line.trim().is_empty() {
  284. // Silently ignore empty commands
  285. return Ok(None)
  286. }
  287. let mut line = line.to_string();
  288. // Remove CRLF
  289. if &line[(line.len() - 2)..] == "\r\n" {
  290. line.pop();
  291. line.pop();
  292. } else if &line[(line.len() - 1)..] == "\n" {
  293. line.pop();
  294. } else {
  295. return Err(Error::ParseFailed("Line doesn't end with CR/LF"))
  296. }
  297. // Prefix the message part of PRIVMSG with ':' if is not already.
  298. // Or realname part of USER command.
  299. let mut words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();
  300. if words[0].to_uppercase() == "PRIVMSG" {
  301. if words.len() > 1 && !words[2].starts_with(':') {
  302. words[2] = format!(":{}", words[2]);
  303. }
  304. line = words.join(" ");
  305. } else if words[0].to_uppercase() == "USER" {
  306. if words.len() > 1 && !words[4].starts_with(':') {
  307. words[4] = format!(":{}", words[4]);
  308. }
  309. line = words.join(" ");
  310. }
  311. // Parse the line
  312. let mut tokens = line.split_ascii_whitespace();
  313. // Commands can begin with :garbage, but we will reject clients
  314. // doing that for now to keep the protocol simple and focused.
  315. let cmd = tokens.next().ok_or(Error::ParseFailed("Invalid command line"))?;
  316. let args = line.replacen(cmd, "", 1);
  317. let cmd = cmd.to_uppercase();
  318. debug!("[{}] --> {}{}", self.addr, cmd, args);
  319. // Handle the command. These implementations are in `command.rs`.
  320. let replies: Vec<ReplyType> = match cmd.as_str() {
  321. "ADMIN" => self.handle_cmd_admin(&args).await?,
  322. "CAP" => self.handle_cmd_cap(&args).await?,
  323. "INFO" => self.handle_cmd_info(&args).await?,
  324. "JOIN" => self.handle_cmd_join(&args, true).await?,
  325. "LIST" => self.handle_cmd_list(&args).await?,
  326. "MODE" => self.handle_cmd_mode(&args).await?,
  327. "MOTD" => self.handle_cmd_motd(&args).await?,
  328. "NAMES" => self.handle_cmd_names(&args).await?,
  329. "NICK" => self.handle_cmd_nick(&args).await?,
  330. "PART" => self.handle_cmd_part(&args).await?,
  331. "PASS" => self.handle_cmd_pass(&args).await?,
  332. "PING" => self.handle_cmd_ping(&args).await?,
  333. "PRIVMSG" => self.handle_cmd_privmsg(&args).await?,
  334. "REHASH" => self.handle_cmd_rehash(&args).await?,
  335. "TOPIC" => self.handle_cmd_topic(&args).await?,
  336. "USER" => self.handle_cmd_user(&args).await?,
  337. "VERSION" => self.handle_cmd_version(&args).await?,
  338. "QUIT" => return Err(Error::ChannelStopped),
  339. _ => {
  340. warn!("[IRC CLIENT] Unimplemented \"{}\" command", cmd);
  341. vec![]
  342. }
  343. };
  344. // Depending on the reply type, we send according messages.
  345. for reply in replies.iter() {
  346. self.reply(writer, reply).await?;
  347. }
  348. // If the command was a PRIVMSG the client sent, we need to encrypt it and
  349. // create an Event to broadcast and return it from this function. So let's try.
  350. // We also do not allow sending unencrypted DMs. In that case, we send a notice
  351. // to the client to inform them that the feature is not enabled.
  352. // NOTE: This is not the most performant way to do this, probably not even
  353. // TODO: the best place to do it. Patches welcome. It's also a bit fragile
  354. // since we assume that `handle_cmd_privmsg()` won't return any replies.
  355. if cmd.as_str() == "PRIVMSG" && replies.is_empty() {
  356. // If the DAG is not synced yet, queue client lines
  357. // Once synced, send queued lines and continue as normal
  358. if !*self.server.darkirc.event_graph.synced.read().await {
  359. debug!("DAG is still syncing, queuing and skipping...");
  360. args_queue.push_back(args);
  361. return Ok(None)
  362. }
  363. // Check if we have queued PRIVMSGs, if we do send all of them first.
  364. let mut pending_events = vec![];
  365. if !args_queue.is_empty() {
  366. for _ in 0..args_queue.len() {
  367. let args = args_queue.pop_front().unwrap();
  368. pending_events.push(self.privmsg_to_event(args).await);
  369. }
  370. return Ok(Some(pending_events))
  371. }
  372. // If queue is empty, create an event and return it
  373. let event = self.privmsg_to_event(args).await;
  374. return Ok(Some(vec![event]))
  375. }
  376. Ok(None)
  377. }
  378. // Internal helper function that creates an Event from PRIVMSG arguments
  379. async fn privmsg_to_event(&self, args: String) -> Event {
  380. let channel = args.split_ascii_whitespace().next().unwrap().to_string();
  381. let msg_offset = args.find(':').unwrap() + 1;
  382. let (_, msg) = args.split_at(msg_offset);
  383. // Truncate messages longer than MAX_MSG_LEN
  384. let msg = if msg.len() > MAX_MSG_LEN { msg.split_at(MAX_MSG_LEN).0 } else { msg };
  385. let mut privmsg =
  386. Privmsg { channel, nick: self.nickname.read().await.to_string(), msg: msg.to_string() };
  387. // Encrypt the Privmsg if an encryption method is available.
  388. self.server.try_encrypt(&mut privmsg).await;
  389. // Build a DAG event and return it.
  390. Event::new(serialize_async(&privmsg).await, &self.server.darkirc.event_graph).await
  391. }
  392. /// Atomically mark a message as seen for this client.
  393. pub async fn mark_seen(&self, event_id: &blake3::Hash) -> Result<()> {
  394. let db = self
  395. .seen
  396. .get_or_init(|| async {
  397. let u = self.username.read().await.to_string();
  398. self.server.darkirc.sled.open_tree(format!("darkirc_user_{}", u)).unwrap()
  399. })
  400. .await;
  401. debug!("Marking event {} as seen", event_id);
  402. let mut batch = sled::Batch::default();
  403. batch.insert(event_id.as_bytes(), &[]);
  404. Ok(db.apply_batch(batch)?)
  405. }
  406. /// Check if a message was already marked seen for this client.
  407. pub async fn is_seen(&self, event_id: &blake3::Hash) -> Result<bool> {
  408. let db = self
  409. .seen
  410. .get_or_init(|| async {
  411. let u = self.username.read().await.to_string();
  412. self.server.darkirc.sled.open_tree(format!("darkirc_user_{}", u)).unwrap()
  413. })
  414. .await;
  415. Ok(db.contains_key(event_id.as_bytes())?)
  416. }
  417. }