server.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. use async_std::net::TcpStream;
  2. use std::net::SocketAddr;
  3. use futures::{io::WriteHalf, AsyncWriteExt};
  4. use fxhash::FxHashMap;
  5. use log::{debug, info, warn};
  6. use rand::{rngs::OsRng, RngCore};
  7. use ringbuffer::RingBufferWrite;
  8. use darkfi::{net::P2pPtr, system::SubscriberPtr, Error, Result};
  9. use crate::{
  10. crypto::{encrypt_message, try_decrypt_message},
  11. privmsg::{Privmsg, PrivmsgsBuffer, SeenMsgIds},
  12. ChannelInfo,
  13. };
  14. const RPL_NOTOPIC: u32 = 331;
  15. const RPL_TOPIC: u32 = 332;
  16. const RPL_NAMEREPLY: u32 = 353;
  17. pub struct IrcServerConnection {
  18. // server stream
  19. write_stream: WriteHalf<TcpStream>,
  20. peer_address: SocketAddr,
  21. // msg ids
  22. seen_msg_ids: SeenMsgIds,
  23. privmsgs_buffer: PrivmsgsBuffer,
  24. // user & channels
  25. is_nick_init: bool,
  26. is_user_init: bool,
  27. is_registered: bool,
  28. nickname: String,
  29. auto_channels: Vec<String>,
  30. pub configured_chans: FxHashMap<String, ChannelInfo>,
  31. // p2p
  32. p2p: P2pPtr,
  33. senders: SubscriberPtr<Privmsg>,
  34. subscriber_id: u64,
  35. }
  36. impl IrcServerConnection {
  37. pub fn new(
  38. write_stream: WriteHalf<TcpStream>,
  39. peer_address: SocketAddr,
  40. seen_msg_ids: SeenMsgIds,
  41. privmsgs_buffer: PrivmsgsBuffer,
  42. auto_channels: Vec<String>,
  43. configured_chans: FxHashMap<String, ChannelInfo>,
  44. p2p: P2pPtr,
  45. senders: SubscriberPtr<Privmsg>,
  46. subscriber_id: u64,
  47. ) -> Self {
  48. Self {
  49. write_stream,
  50. peer_address,
  51. seen_msg_ids,
  52. privmsgs_buffer,
  53. is_nick_init: false,
  54. is_user_init: false,
  55. is_registered: false,
  56. nickname: "anon".to_string(),
  57. auto_channels,
  58. configured_chans,
  59. p2p,
  60. senders,
  61. subscriber_id,
  62. }
  63. }
  64. pub async fn update(&mut self, line: String) -> Result<()> {
  65. let mut tokens = line.split_ascii_whitespace();
  66. // Commands can begin with :garbage but we will reject clients doing
  67. // that for now to keep the protocol simple and focused.
  68. let command = tokens.next().ok_or(Error::MalformedPacket)?;
  69. info!("IRC server received command: {}", command.to_uppercase());
  70. match command.to_uppercase().as_str() {
  71. "USER" => {
  72. // We can stuff any extra things like public keys in here.
  73. // Ignore it for now.
  74. self.is_user_init = true;
  75. }
  76. "NAMES" => {
  77. let channels = tokens.next().ok_or(Error::MalformedPacket)?;
  78. for chan in channels.split(',') {
  79. if !chan.starts_with('#') {
  80. warn!("{} is not a valid name for channel", chan);
  81. continue
  82. }
  83. if self.configured_chans.contains_key(chan) {
  84. let chan_info = self.configured_chans.get(chan).unwrap();
  85. if chan_info.names.is_empty() {
  86. continue
  87. }
  88. let names_reply = format!(
  89. ":{}!anon@dark.fi {} = {} : {}\r\n",
  90. self.nickname,
  91. RPL_NAMEREPLY,
  92. chan,
  93. chan_info.names.join(" ")
  94. );
  95. self.reply(&names_reply).await?;
  96. }
  97. }
  98. }
  99. "NICK" => {
  100. let nickname = tokens.next().ok_or(Error::MalformedPacket)?;
  101. self.is_nick_init = true;
  102. let old_nick = std::mem::replace(&mut self.nickname, nickname.to_string());
  103. let nick_reply = format!(":{}!anon@dark.fi NICK {}\r\n", old_nick, self.nickname);
  104. self.reply(&nick_reply).await?;
  105. }
  106. "JOIN" => {
  107. let channels = tokens.next().ok_or(Error::MalformedPacket)?;
  108. for chan in channels.split(',') {
  109. if !chan.starts_with('#') {
  110. warn!("{} is not a valid name for channel", chan);
  111. continue
  112. }
  113. let join_reply = format!(":{}!anon@dark.fi JOIN {}\r\n", self.nickname, chan);
  114. self.reply(&join_reply).await?;
  115. if !self.configured_chans.contains_key(chan) {
  116. self.configured_chans.insert(chan.to_string(), ChannelInfo::new()?);
  117. } else {
  118. let chan_info = self.configured_chans.get_mut(chan).unwrap();
  119. chan_info.joined = true;
  120. }
  121. }
  122. }
  123. "PART" => {
  124. let channels = tokens.next().ok_or(Error::MalformedPacket)?;
  125. for chan in channels.split(',') {
  126. let part_reply = format!(":{}!anon@dark.fi PART {}\r\n", self.nickname, chan);
  127. self.reply(&part_reply).await?;
  128. if self.configured_chans.contains_key(chan) {
  129. let chan_info = self.configured_chans.get_mut(chan).unwrap();
  130. chan_info.joined = false;
  131. }
  132. }
  133. }
  134. "TOPIC" => {
  135. let channel = tokens.next().ok_or(Error::MalformedPacket)?;
  136. if let Some(substr_idx) = line.find(':') {
  137. // Client is setting the topic
  138. if substr_idx >= line.len() {
  139. return Err(Error::MalformedPacket)
  140. }
  141. let topic = &line[substr_idx + 1..];
  142. let chan_info = self.configured_chans.get_mut(channel).unwrap();
  143. chan_info.topic = Some(topic.to_string());
  144. let topic_reply =
  145. format!(":{}!anon@dark.fi TOPIC {} :{}\r\n", self.nickname, channel, topic);
  146. self.reply(&topic_reply).await?;
  147. } else {
  148. // Client is asking or the topic
  149. let chan_info = self.configured_chans.get(channel).unwrap();
  150. let topic_reply = if let Some(topic) = &chan_info.topic {
  151. format!("{} {} {} :{}\r\n", RPL_TOPIC, self.nickname, channel, topic)
  152. } else {
  153. const TOPIC: &str = "No topic is set";
  154. format!("{} {} {} :{}\r\n", RPL_NOTOPIC, self.nickname, channel, TOPIC)
  155. };
  156. self.reply(&topic_reply).await?;
  157. }
  158. }
  159. "PING" => {
  160. let pong = tokens.next().ok_or(Error::MalformedPacket)?;
  161. let pong = format!("PONG {}\r\n", pong);
  162. self.reply(&pong).await?;
  163. }
  164. "PRIVMSG" => {
  165. let channel = tokens.next().ok_or(Error::MalformedPacket)?;
  166. let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
  167. if substr_idx >= line.len() {
  168. return Err(Error::MalformedPacket)
  169. }
  170. let message = &line[substr_idx + 1..];
  171. info!("(Plain) PRIVMSG {} :{}", channel, message);
  172. if self.configured_chans.contains_key(channel) {
  173. let channel_info = self.configured_chans.get(channel).unwrap();
  174. if channel_info.joined {
  175. let message = if let Some(salt_box) = &channel_info.salt_box {
  176. let encrypted = encrypt_message(salt_box, message);
  177. info!("(Encrypted) PRIVMSG {} :{}", channel, encrypted);
  178. encrypted
  179. } else {
  180. message.to_string()
  181. };
  182. let random_id = OsRng.next_u64();
  183. let protocol_msg = Privmsg {
  184. id: random_id,
  185. nickname: self.nickname.clone(),
  186. channel: channel.to_string(),
  187. message,
  188. };
  189. {
  190. (*self.seen_msg_ids.lock().await).push(random_id);
  191. (*self.privmsgs_buffer.lock().await).push(protocol_msg.clone())
  192. }
  193. self.senders
  194. .notify_with_exclude(protocol_msg.clone(), &[self.subscriber_id])
  195. .await;
  196. debug!(target: "ircd", "PRIVMSG to be sent: {:?}", protocol_msg);
  197. self.p2p.broadcast(protocol_msg).await?;
  198. }
  199. }
  200. }
  201. "QUIT" => {
  202. // Close the connection
  203. return Err(Error::NetworkServiceStopped)
  204. }
  205. _ => {
  206. warn!("Unimplemented `{}` command", command);
  207. }
  208. }
  209. if !self.is_registered && self.is_nick_init && self.is_user_init {
  210. debug!("Initializing peer connection");
  211. let register_reply = format!(":darkfi 001 {} :Let there be dark\r\n", self.nickname);
  212. self.reply(&register_reply).await?;
  213. self.is_registered = true;
  214. // Auto-joins
  215. macro_rules! autojoin {
  216. ($channel:expr,$topic:expr) => {
  217. let j = format!(":{}!anon@dark.fi JOIN {}\r\n", self.nickname, $channel);
  218. let t = format!(":DarkFi TOPIC {} :{}\r\n", $channel, $topic);
  219. self.reply(&j).await?;
  220. self.reply(&t).await?;
  221. };
  222. }
  223. for chan in self.auto_channels.clone() {
  224. if self.configured_chans.contains_key(&chan) {
  225. let chan_info = self.configured_chans.get_mut(&chan).unwrap();
  226. let topic = if let Some(topic) = chan_info.topic.clone() {
  227. topic
  228. } else {
  229. "n/a".to_string()
  230. };
  231. chan_info.topic = Some(topic.to_string());
  232. autojoin!(chan, topic);
  233. } else {
  234. let mut chan_info = ChannelInfo::new()?;
  235. chan_info.topic = Some("n/a".to_string());
  236. self.configured_chans.insert(chan.clone(), chan_info);
  237. autojoin!(chan, "n/a");
  238. }
  239. }
  240. }
  241. Ok(())
  242. }
  243. pub async fn reply(&mut self, message: &str) -> Result<()> {
  244. self.write_stream.write_all(message.as_bytes()).await?;
  245. debug!("Sent {}", message);
  246. Ok(())
  247. }
  248. pub async fn process_msg_from_p2p(&mut self, msg: &Privmsg) -> Result<()> {
  249. let mut msg = msg.clone();
  250. // Try to potentially decrypt the incoming message.
  251. if self.configured_chans.contains_key(&msg.channel) {
  252. let chan_info = self.configured_chans.get_mut(&msg.channel).unwrap();
  253. if !chan_info.joined {
  254. return Ok(())
  255. }
  256. let salt_box = chan_info.salt_box.clone();
  257. if salt_box.is_some() {
  258. let decrypted_msg = try_decrypt_message(&salt_box.unwrap(), &msg.message);
  259. if decrypted_msg.is_none() {
  260. return Ok(())
  261. }
  262. msg.message = decrypted_msg.unwrap();
  263. info!("Decrypted received message: {:?}", msg);
  264. }
  265. // add the nickname to the channel's names
  266. if !chan_info.names.contains(&msg.nickname) {
  267. chan_info.names.push(msg.nickname.clone());
  268. }
  269. }
  270. self.reply(&msg.to_irc_msg()).await?;
  271. Ok(())
  272. }
  273. pub async fn process_line_from_client(
  274. &mut self,
  275. err: std::result::Result<usize, std::io::Error>,
  276. line: String,
  277. ) -> Result<()> {
  278. if let Err(e) = err {
  279. warn!("Read line error {}: {}", self.peer_address, e);
  280. return Err(Error::ChannelStopped)
  281. }
  282. info!("Received msg from IRC client: {:?}", line);
  283. let irc_msg = self.clean_input_line(line)?;
  284. info!("Send msg to IRC client '{}' from {}", irc_msg, self.peer_address);
  285. if let Err(e) = self.update(irc_msg).await {
  286. warn!("Connection error: {} for {}", e, self.peer_address);
  287. return Err(Error::ChannelStopped)
  288. }
  289. Ok(())
  290. }
  291. fn clean_input_line(&self, mut line: String) -> Result<String> {
  292. if line.is_empty() {
  293. warn!("Received empty line from {}. ", self.peer_address);
  294. warn!("Closing connection.");
  295. return Err(Error::ChannelStopped)
  296. }
  297. if &line[(line.len() - 2)..] == "\r\n" {
  298. // Remove CRLF
  299. line.pop();
  300. line.pop();
  301. } else if &line[(line.len() - 1)..] == "\n" {
  302. line.pop();
  303. } else {
  304. warn!("Closing connection.");
  305. return Err(Error::ChannelStopped)
  306. }
  307. Ok(line.clone())
  308. }
  309. }