client.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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::net::SocketAddr;
  19. use futures::{
  20. io::{BufReader, ReadHalf, WriteHalf},
  21. AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, FutureExt,
  22. };
  23. use log::{debug, error, info, warn};
  24. use darkfi::{system::Subscription, Error, Result};
  25. use crate::{
  26. crypto::{decrypt_privmsg, decrypt_target, encrypt_privmsg},
  27. privmsg::PrivMsgEvent,
  28. settings,
  29. settings::RPL,
  30. ChannelInfo,
  31. };
  32. use super::{ClientSubMsg, IrcConfig, NotifierMsg};
  33. pub struct IrcClient<C: AsyncRead + AsyncWrite + Send + Unpin + 'static> {
  34. // network stream
  35. write_stream: WriteHalf<C>,
  36. read_stream: BufReader<ReadHalf<C>>,
  37. pub address: SocketAddr,
  38. // irc config
  39. irc_config: IrcConfig,
  40. server_notifier: smol::channel::Sender<(NotifierMsg, u64)>,
  41. subscription: Subscription<ClientSubMsg>,
  42. }
  43. impl<C: AsyncRead + AsyncWrite + Send + Unpin + 'static> IrcClient<C> {
  44. pub fn new(
  45. write_stream: WriteHalf<C>,
  46. read_stream: BufReader<ReadHalf<C>>,
  47. address: SocketAddr,
  48. irc_config: IrcConfig,
  49. server_notifier: smol::channel::Sender<(NotifierMsg, u64)>,
  50. subscription: Subscription<ClientSubMsg>,
  51. ) -> Self {
  52. Self { write_stream, read_stream, address, irc_config, subscription, server_notifier }
  53. }
  54. /// Start listening for messages came from View or irc client
  55. pub async fn listen(&mut self) {
  56. loop {
  57. let mut line = String::new();
  58. futures::select! {
  59. // Process msg from View
  60. msg = self.subscription.receive().fuse() => {
  61. match msg {
  62. ClientSubMsg::Privmsg(mut m) => {
  63. if let Err(e) = self.process_msg(&mut m).await {
  64. error!("[CLIENT {}] Process msg: {}", self.address, e);
  65. break
  66. }
  67. }
  68. ClientSubMsg::Config(c) => self.update_config(c).await,
  69. }
  70. }
  71. // Process msg from IRC client
  72. err = self.read_stream.read_line(&mut line).fuse() => {
  73. if let Err(e) = err {
  74. error!("[CLIENT {}] Read line error: {}", self.address, e);
  75. break
  76. }
  77. if let Err(e) = self.process_line(line).await {
  78. error!("[CLIENT {}] Process line failed: {}", self.address, e);
  79. break
  80. }
  81. }
  82. }
  83. }
  84. warn!("[CLIENT {}] Close connection", self.address);
  85. self.subscription.unsubscribe().await;
  86. }
  87. pub async fn update_config(&mut self, new_config: IrcConfig) {
  88. self.irc_config.channels.extend(new_config.channels);
  89. self.irc_config.contacts.extend(new_config.contacts);
  90. self.irc_config.nickname = new_config.nickname;
  91. self.irc_config.private_key = new_config.private_key;
  92. self.irc_config.password = new_config.password;
  93. if self.on_receive_join(self.irc_config.channels.keys().cloned().collect()).await.is_err() {
  94. warn!("Error to join updated channels");
  95. }
  96. }
  97. pub async fn process_msg(&mut self, msg: &mut PrivMsgEvent) -> Result<()> {
  98. info!("[CLIENT {}] msg from View: {:?}", self.address, msg.to_string());
  99. decrypt_target(
  100. msg,
  101. &self.irc_config.channels,
  102. &self.irc_config.contacts,
  103. &self.irc_config.private_key,
  104. );
  105. if msg.target.starts_with('#') {
  106. // Try to potentially decrypt the incoming message.
  107. if !self.irc_config.channels.contains_key(&msg.target) {
  108. return Ok(())
  109. }
  110. let chan_info = self.irc_config.channels.get_mut(&msg.target).unwrap();
  111. if !chan_info.joined {
  112. return Ok(())
  113. }
  114. if let Some(salt_box) = &chan_info.salt_box(&msg.target) {
  115. decrypt_privmsg(salt_box, msg);
  116. info!(
  117. "[CLIENT {}] Decrypted received message: {:?}",
  118. self.address,
  119. msg.to_string()
  120. );
  121. }
  122. // add the nickname to the channel's names
  123. if !chan_info.names.contains(&msg.nick) {
  124. chan_info.names.push(msg.nick.clone());
  125. }
  126. self.reply(&msg.to_string()).await?;
  127. } else if self.irc_config.private_key.is_some() {
  128. if let Some(contact_info) = self.irc_config.contacts.get(&msg.target) {
  129. let salt_box = &contact_info
  130. .salt_box(self.irc_config.private_key.as_ref().unwrap(), &msg.target);
  131. if salt_box.is_none() {
  132. return Ok(())
  133. }
  134. decrypt_privmsg(salt_box.as_ref().unwrap(), msg);
  135. info!(
  136. "[CLIENT {}] Decrypted received message: {:?}",
  137. self.address,
  138. msg.to_string()
  139. );
  140. self.reply(&msg.to_string()).await?;
  141. }
  142. }
  143. Ok(())
  144. }
  145. pub async fn process_line(&mut self, line: String) -> Result<()> {
  146. let irc_msg = match clean_input_line(line) {
  147. Ok(msg) => msg,
  148. Err(e) => {
  149. warn!("[CLIENT {}] Connection error: {}", self.address, e);
  150. return Err(Error::ChannelStopped)
  151. }
  152. };
  153. info!("[CLIENT {}] Process msg: {}", self.address, irc_msg);
  154. if let Err(e) = self.update(irc_msg).await {
  155. warn!("[CLIENT {}] Connection error: {}", self.address, e);
  156. return Err(Error::ChannelStopped)
  157. }
  158. Ok(())
  159. }
  160. async fn update(&mut self, line: String) -> Result<()> {
  161. if line.len() > settings::MAXIMUM_LENGTH_OF_MESSAGE {
  162. return Err(Error::MalformedPacket)
  163. }
  164. let (command, value) = parse_line(&line)?;
  165. let (command, value) = (command.as_str(), value.as_str());
  166. match command {
  167. "PASS" => self.on_receive_pass(value).await?,
  168. "USER" => self.on_receive_user().await?,
  169. "NAMES" => self.on_receive_names(value.split(',').map(String::from).collect()).await?,
  170. "NICK" => self.on_receive_nick(value).await?,
  171. "JOIN" => self.on_receive_join(value.split(',').map(String::from).collect()).await?,
  172. "PART" => self.on_receive_part(value.split(',').map(String::from).collect()).await?,
  173. "TOPIC" => self.on_receive_topic(&line, value).await?,
  174. "PING" => self.on_ping(value).await?,
  175. "PRIVMSG" => self.on_receive_privmsg(&line, value).await?,
  176. "CAP" => self.on_receive_cap(&line, &value.to_uppercase()).await?,
  177. "QUIT" => self.on_quit()?,
  178. _ => warn!("[CLIENT {}] Unimplemented `{}` command", self.address, command),
  179. }
  180. self.registre().await?;
  181. Ok(())
  182. }
  183. async fn registre(&mut self) -> Result<()> {
  184. if !self.irc_config.is_pass_init && self.irc_config.password.is_empty() {
  185. self.irc_config.is_pass_init = true
  186. }
  187. if !self.irc_config.is_registered &&
  188. self.irc_config.is_cap_end &&
  189. self.irc_config.is_nick_init &&
  190. self.irc_config.is_user_init
  191. {
  192. debug!("Initializing peer connection");
  193. let register_reply =
  194. format!(":darkfi 001 {} :Let there be dark\r\n", self.irc_config.nickname);
  195. self.reply(&register_reply).await?;
  196. self.irc_config.is_registered = true;
  197. // join all channels
  198. self.on_receive_join(self.irc_config.channels.keys().cloned().collect()).await?;
  199. if *self.irc_config.capabilities.get("no-history").unwrap() {
  200. return Ok(())
  201. }
  202. }
  203. Ok(())
  204. }
  205. async fn reply(&mut self, message: &str) -> Result<()> {
  206. self.write_stream.write_all(message.as_bytes()).await?;
  207. debug!("Sent {}", message.trim_end());
  208. Ok(())
  209. }
  210. fn on_quit(&self) -> Result<()> {
  211. // Close the connection
  212. Err(Error::NetworkServiceStopped)
  213. }
  214. async fn on_receive_user(&mut self) -> Result<()> {
  215. // We can stuff any extra things like public keys in here.
  216. // Ignore it for now.
  217. if self.irc_config.is_pass_init {
  218. self.irc_config.is_user_init = true;
  219. } else {
  220. // Close the connection
  221. warn!("[CLIENT {}] Password is required", self.address);
  222. return self.on_quit()
  223. }
  224. Ok(())
  225. }
  226. async fn on_receive_pass(&mut self, password: &str) -> Result<()> {
  227. if self.irc_config.password == password {
  228. self.irc_config.is_pass_init = true
  229. } else {
  230. // Close the connection
  231. warn!("[CLIENT {}] Password is not correct!", self.address);
  232. return self.on_quit()
  233. }
  234. Ok(())
  235. }
  236. async fn on_receive_nick(&mut self, nickname: &str) -> Result<()> {
  237. if nickname.len() > settings::MAXIMUM_LENGTH_OF_NICKNAME {
  238. return Ok(())
  239. }
  240. self.irc_config.is_nick_init = true;
  241. let old_nick = std::mem::replace(&mut self.irc_config.nickname, nickname.to_string());
  242. let nick_reply =
  243. format!(":{}!anon@dark.fi NICK {}\r\n", old_nick, self.irc_config.nickname);
  244. self.reply(&nick_reply).await
  245. }
  246. async fn on_receive_part(&mut self, channels: Vec<String>) -> Result<()> {
  247. for chan in channels.iter() {
  248. let part_reply =
  249. format!(":{}!anon@dark.fi PART {}\r\n", self.irc_config.nickname, chan);
  250. self.reply(&part_reply).await?;
  251. if self.irc_config.channels.contains_key(chan) {
  252. let chan_info = self.irc_config.channels.get_mut(chan).unwrap();
  253. chan_info.joined = false;
  254. }
  255. }
  256. Ok(())
  257. }
  258. async fn on_receive_topic(&mut self, line: &str, channel: &str) -> Result<()> {
  259. if let Some(substr_idx) = line.find(':') {
  260. // Client is setting the topic
  261. if substr_idx >= line.len() {
  262. return Err(Error::MalformedPacket)
  263. }
  264. let topic = &line[substr_idx + 1..];
  265. let chan_info = self.irc_config.channels.get_mut(channel).unwrap();
  266. chan_info.topic = Some(topic.to_string());
  267. let topic_reply = format!(
  268. ":{}!anon@dark.fi TOPIC {} :{}\r\n",
  269. self.irc_config.nickname, channel, topic
  270. );
  271. self.reply(&topic_reply).await?;
  272. } else {
  273. // Client is asking or the topic
  274. let chan_info = self.irc_config.channels.get(channel).unwrap();
  275. let topic_reply = if let Some(topic) = &chan_info.topic {
  276. format!(
  277. "{} {} {} :{}\r\n",
  278. RPL::Topic as u32,
  279. self.irc_config.nickname,
  280. channel,
  281. topic
  282. )
  283. } else {
  284. const TOPIC: &str = "No topic is set";
  285. format!(
  286. "{} {} {} :{}\r\n",
  287. RPL::NoTopic as u32,
  288. self.irc_config.nickname,
  289. channel,
  290. TOPIC
  291. )
  292. };
  293. self.reply(&topic_reply).await?;
  294. }
  295. Ok(())
  296. }
  297. async fn on_ping(&mut self, value: &str) -> Result<()> {
  298. let pong = format!("PONG {}\r\n", value);
  299. self.reply(&pong).await
  300. }
  301. async fn on_receive_cap(&mut self, line: &str, subcommand: &str) -> Result<()> {
  302. self.irc_config.is_cap_end = false;
  303. let capabilities_keys: Vec<String> = self.irc_config.capabilities.keys().cloned().collect();
  304. match subcommand {
  305. "LS" => {
  306. let cap_ls_reply = format!(
  307. ":{}!anon@dark.fi CAP * LS :{}\r\n",
  308. self.irc_config.nickname,
  309. capabilities_keys.join(" ")
  310. );
  311. self.reply(&cap_ls_reply).await?;
  312. }
  313. "REQ" => {
  314. let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
  315. if substr_idx >= line.len() {
  316. return Err(Error::MalformedPacket)
  317. }
  318. let cap: Vec<&str> = line[substr_idx + 1..].split(' ').collect();
  319. let mut ack_list = vec![];
  320. let mut nak_list = vec![];
  321. for c in cap {
  322. if self.irc_config.capabilities.contains_key(c) {
  323. self.irc_config.capabilities.insert(c.to_string(), true);
  324. ack_list.push(c);
  325. } else {
  326. nak_list.push(c);
  327. }
  328. }
  329. let cap_ack_reply = format!(
  330. ":{}!anon@dark.fi CAP * ACK :{}\r\n",
  331. self.irc_config.nickname,
  332. ack_list.join(" ")
  333. );
  334. let cap_nak_reply = format!(
  335. ":{}!anon@dark.fi CAP * NAK :{}\r\n",
  336. self.irc_config.nickname,
  337. nak_list.join(" ")
  338. );
  339. self.reply(&cap_ack_reply).await?;
  340. self.reply(&cap_nak_reply).await?;
  341. }
  342. "LIST" => {
  343. let enabled_capabilities: Vec<String> = self
  344. .irc_config
  345. .capabilities
  346. .clone()
  347. .into_iter()
  348. .filter(|(_, v)| *v)
  349. .map(|(k, _)| k)
  350. .collect();
  351. let cap_list_reply = format!(
  352. ":{}!anon@dark.fi CAP * LIST :{}\r\n",
  353. self.irc_config.nickname,
  354. enabled_capabilities.join(" ")
  355. );
  356. self.reply(&cap_list_reply).await?;
  357. }
  358. "END" => {
  359. self.irc_config.is_cap_end = true;
  360. }
  361. _ => {}
  362. }
  363. Ok(())
  364. }
  365. async fn on_receive_names(&mut self, channels: Vec<String>) -> Result<()> {
  366. for chan in channels.iter() {
  367. if !chan.starts_with('#') {
  368. continue
  369. }
  370. if self.irc_config.channels.contains_key(chan) {
  371. let chan_info = self.irc_config.channels.get(chan).unwrap();
  372. if chan_info.names.is_empty() {
  373. return Ok(())
  374. }
  375. let names_reply = format!(
  376. ":{}!anon@dark.fi {} = {} : {}\r\n",
  377. self.irc_config.nickname,
  378. RPL::NameReply as u32,
  379. chan,
  380. chan_info.names.join(" ")
  381. );
  382. self.reply(&names_reply).await?;
  383. let end_of_names = format!(
  384. ":DarkFi {:03} {} {} :End of NAMES list\r\n",
  385. RPL::EndOfNames as u32,
  386. self.irc_config.nickname,
  387. chan
  388. );
  389. self.reply(&end_of_names).await?;
  390. }
  391. }
  392. Ok(())
  393. }
  394. async fn on_receive_privmsg(&mut self, line: &str, target: &str) -> Result<()> {
  395. let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
  396. if substr_idx >= line.len() {
  397. return Err(Error::MalformedPacket)
  398. }
  399. let message = line[substr_idx + 1..].to_string();
  400. info!("[CLIENT {}] (Plain) PRIVMSG {} :{}", self.address, target, message,);
  401. let mut privmsg = PrivMsgEvent {
  402. nick: self.irc_config.nickname.clone(),
  403. target: target.to_string(),
  404. msg: message,
  405. };
  406. if target.starts_with('#') {
  407. if !self.irc_config.channels.contains_key(target) {
  408. return Ok(())
  409. }
  410. let channel_info = self.irc_config.channels.get(target).unwrap();
  411. if !channel_info.joined {
  412. return Ok(())
  413. }
  414. if let Some(salt_box) = &channel_info.salt_box(target) {
  415. encrypt_privmsg(salt_box, &mut privmsg);
  416. info!("[CLIENT {}] (Encrypted) PRIVMSG: {:?}", self.address, privmsg.to_string());
  417. }
  418. } else if self.irc_config.private_key.is_some() {
  419. if let Some(contact_info) = self.irc_config.contacts.get(target) {
  420. if let Some(salt_box) =
  421. &contact_info.salt_box(self.irc_config.private_key.as_ref().unwrap(), target)
  422. {
  423. encrypt_privmsg(salt_box, &mut privmsg);
  424. info!(
  425. "[CLIENT {}] (Encrypted) PRIVMSG: {:?}",
  426. self.address,
  427. privmsg.to_string()
  428. );
  429. }
  430. }
  431. }
  432. self.server_notifier
  433. .send((NotifierMsg::Privmsg(privmsg), self.subscription.get_id()))
  434. .await?;
  435. Ok(())
  436. }
  437. async fn on_receive_join(&mut self, channels: Vec<String>) -> Result<()> {
  438. for chan in channels.iter() {
  439. if !chan.starts_with('#') {
  440. continue
  441. }
  442. if !self.irc_config.channels.contains_key(chan) {
  443. let mut chan_info = ChannelInfo::new();
  444. chan_info.topic = Some("n/a".to_string());
  445. self.irc_config.channels.insert(chan.to_string(), chan_info);
  446. }
  447. let chan_info = self.irc_config.channels.get_mut(chan).unwrap();
  448. if chan_info.joined {
  449. return Ok(())
  450. }
  451. chan_info.joined = true;
  452. let topic =
  453. if let Some(topic) = chan_info.topic.clone() { topic } else { "n/a".to_string() };
  454. chan_info.topic = Some(topic.to_string());
  455. {
  456. let j = format!(":{}!anon@dark.fi JOIN {}\r\n", self.irc_config.nickname, chan);
  457. let t = format!(":DarkFi TOPIC {} :{}\r\n", chan, topic);
  458. self.reply(&j).await?;
  459. self.reply(&t).await?;
  460. }
  461. }
  462. Ok(())
  463. }
  464. }
  465. //
  466. // Helper functions
  467. //
  468. fn clean_input_line(mut line: String) -> Result<String> {
  469. if line.is_empty() {
  470. return Err(Error::ChannelStopped)
  471. }
  472. if line == "\n" || line == "\r\n" {
  473. return Err(Error::ChannelStopped)
  474. }
  475. if &line[(line.len() - 2)..] == "\r\n" {
  476. // Remove CRLF
  477. line.pop();
  478. line.pop();
  479. } else if &line[(line.len() - 1)..] == "\n" {
  480. line.pop();
  481. } else {
  482. return Err(Error::ChannelStopped)
  483. }
  484. Ok(line.clone())
  485. }
  486. fn parse_line(line: &str) -> Result<(String, String)> {
  487. let mut tokens = line.split_ascii_whitespace();
  488. // Commands can begin with :garbage but we will reject clients doing
  489. // that for now to keep the protocol simple and focused.
  490. let command = tokens.next().ok_or(Error::MalformedPacket)?.to_uppercase();
  491. let value = tokens.next().ok_or(Error::MalformedPacket)?;
  492. Ok((command, value.to_owned()))
  493. }