client.rs 20 KB

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