command.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. use futures::{AsyncRead, AsyncWrite};
  2. use log::{debug, info, warn};
  3. use darkfi::{Error, Result};
  4. use crate::{
  5. crypto::encrypt_privmsg,
  6. privmsg::{Privmsg, MAXIMUM_LENGTH_OF_NICKNAME},
  7. ChannelInfo,
  8. };
  9. use super::IrcServerConnection;
  10. const RPL_NOTOPIC: u32 = 331;
  11. const RPL_TOPIC: u32 = 332;
  12. const RPL_NAMEREPLY: u32 = 353;
  13. const RPL_ENDOFNAMES: u32 = 366;
  14. impl<C: AsyncRead + AsyncWrite + Send + Unpin + 'static> IrcServerConnection<C> {
  15. pub(super) fn on_quit(&self) -> Result<()> {
  16. // Close the connection
  17. Err(Error::NetworkServiceStopped)
  18. }
  19. pub(super) async fn on_receive_user(&mut self) -> Result<()> {
  20. // We can stuff any extra things like public keys in here.
  21. // Ignore it for now.
  22. if self.is_pass_init {
  23. self.is_user_init = true;
  24. } else {
  25. // Close the connection
  26. warn!("Password is required");
  27. return self.on_quit()
  28. }
  29. Ok(())
  30. }
  31. pub(super) async fn on_receive_pass(&mut self, password: &str) -> Result<()> {
  32. if self.password == password {
  33. self.is_pass_init = true
  34. } else {
  35. // Close the connection
  36. warn!("Password is not correct!");
  37. return self.on_quit()
  38. }
  39. Ok(())
  40. }
  41. pub(super) async fn on_receive_nick(&mut self, nickname: &str) -> Result<()> {
  42. if nickname.len() > MAXIMUM_LENGTH_OF_NICKNAME {
  43. return Ok(())
  44. }
  45. self.is_nick_init = true;
  46. let old_nick = std::mem::replace(&mut self.nickname, nickname.to_string());
  47. let nick_reply = format!(":{}!anon@dark.fi NICK {}\r\n", old_nick, self.nickname);
  48. self.reply(&nick_reply).await
  49. }
  50. pub(super) async fn on_receive_part(&mut self, channels: Vec<String>) -> Result<()> {
  51. for chan in channels.iter() {
  52. let part_reply = format!(":{}!anon@dark.fi PART {}\r\n", self.nickname, chan);
  53. self.reply(&part_reply).await?;
  54. if self.configured_chans.contains_key(chan) {
  55. let chan_info = self.configured_chans.get_mut(chan).unwrap();
  56. chan_info.joined = false;
  57. }
  58. }
  59. Ok(())
  60. }
  61. pub(super) async fn on_receive_topic(&mut self, line: &str, channel: &str) -> Result<()> {
  62. if let Some(substr_idx) = line.find(':') {
  63. // Client is setting the topic
  64. if substr_idx >= line.len() {
  65. return Err(Error::MalformedPacket)
  66. }
  67. let topic = &line[substr_idx + 1..];
  68. let chan_info = self.configured_chans.get_mut(channel).unwrap();
  69. chan_info.topic = Some(topic.to_string());
  70. let topic_reply =
  71. format!(":{}!anon@dark.fi TOPIC {} :{}\r\n", self.nickname, channel, topic);
  72. self.reply(&topic_reply).await?;
  73. } else {
  74. // Client is asking or the topic
  75. let chan_info = self.configured_chans.get(channel).unwrap();
  76. let topic_reply = if let Some(topic) = &chan_info.topic {
  77. format!("{} {} {} :{}\r\n", RPL_TOPIC, self.nickname, channel, topic)
  78. } else {
  79. const TOPIC: &str = "No topic is set";
  80. format!("{} {} {} :{}\r\n", RPL_NOTOPIC, self.nickname, channel, TOPIC)
  81. };
  82. self.reply(&topic_reply).await?;
  83. }
  84. Ok(())
  85. }
  86. pub(super) async fn on_ping(&mut self, value: &str) -> Result<()> {
  87. let pong = format!("PONG {}\r\n", value);
  88. self.reply(&pong).await
  89. }
  90. pub(super) async fn on_receive_cap(&mut self, line: &str, subcommand: &str) -> Result<()> {
  91. self.is_cap_end = false;
  92. let capabilities_keys: Vec<String> = self.capabilities.keys().cloned().collect();
  93. if subcommand == "LS" {
  94. let cap_ls_reply = format!(
  95. ":{}!anon@dark.fi CAP * LS :{}\r\n",
  96. self.nickname,
  97. capabilities_keys.join(" ")
  98. );
  99. self.reply(&cap_ls_reply).await?;
  100. }
  101. if subcommand == "REQ" {
  102. let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
  103. if substr_idx >= line.len() {
  104. return Err(Error::MalformedPacket)
  105. }
  106. let cap: Vec<&str> = line[substr_idx + 1..].split(' ').collect();
  107. let mut ack_list = vec![];
  108. let mut nak_list = vec![];
  109. for c in cap {
  110. if self.capabilities.contains_key(c) {
  111. self.capabilities.insert(c.to_string(), true);
  112. ack_list.push(c);
  113. } else {
  114. nak_list.push(c);
  115. }
  116. }
  117. let cap_ack_reply =
  118. format!(":{}!anon@dark.fi CAP * ACK :{}\r\n", self.nickname, ack_list.join(" "));
  119. let cap_nak_reply =
  120. format!(":{}!anon@dark.fi CAP * NAK :{}\r\n", self.nickname, nak_list.join(" "));
  121. self.reply(&cap_ack_reply).await?;
  122. self.reply(&cap_nak_reply).await?;
  123. }
  124. if subcommand == "LIST" {
  125. let enabled_capabilities: Vec<String> =
  126. self.capabilities.clone().into_iter().filter(|(_, v)| *v).map(|(k, _)| k).collect();
  127. let cap_list_reply = format!(
  128. ":{}!anon@dark.fi CAP * LIST :{}\r\n",
  129. self.nickname,
  130. enabled_capabilities.join(" ")
  131. );
  132. self.reply(&cap_list_reply).await?;
  133. }
  134. if subcommand == "END" {
  135. self.is_cap_end = true;
  136. }
  137. Ok(())
  138. }
  139. pub(super) async fn on_receive_names(&mut self, channels: Vec<String>) -> Result<()> {
  140. for chan in channels.iter() {
  141. if !chan.starts_with('#') {
  142. continue
  143. }
  144. if self.configured_chans.contains_key(chan) {
  145. let chan_info = self.configured_chans.get(chan).unwrap();
  146. if chan_info.names.is_empty() {
  147. return Ok(())
  148. }
  149. let names_reply = format!(
  150. ":{}!anon@dark.fi {} = {} : {}\r\n",
  151. self.nickname,
  152. RPL_NAMEREPLY,
  153. chan,
  154. chan_info.names.join(" ")
  155. );
  156. self.reply(&names_reply).await?;
  157. let end_of_names = format!(
  158. ":DarkFi {:03} {} {} :End of NAMES list\r\n",
  159. RPL_ENDOFNAMES, self.nickname, chan
  160. );
  161. self.reply(&end_of_names).await?;
  162. }
  163. }
  164. Ok(())
  165. }
  166. pub(super) async fn on_receive_privmsg(&mut self, line: &str, target: &str) -> Result<()> {
  167. let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
  168. if substr_idx >= line.len() {
  169. return Err(Error::MalformedPacket)
  170. }
  171. let message = line[substr_idx + 1..].to_string();
  172. info!("(Plain) PRIVMSG {} :{}", target, message);
  173. let privmsgs_buffer = self.privmsgs_buffer.lock().await;
  174. let last_term = privmsgs_buffer.last_term() + 1;
  175. drop(privmsgs_buffer);
  176. let mut privmsg = Privmsg::new(&self.nickname, target, &message, last_term);
  177. if target.starts_with('#') {
  178. if !self.configured_chans.contains_key(target) {
  179. return Ok(())
  180. }
  181. let channel_info = self.configured_chans.get(target).unwrap();
  182. if !channel_info.joined {
  183. return Ok(())
  184. }
  185. if let Some(salt_box) = &channel_info.salt_box {
  186. encrypt_privmsg(salt_box, &mut privmsg);
  187. info!("(Encrypted) PRIVMSG: {:?}", privmsg);
  188. }
  189. } else {
  190. // If we have a configured secret for this nick, we encrypt the message.
  191. if let Some(salt_box) = self.configured_contacts.get(target) {
  192. encrypt_privmsg(salt_box, &mut privmsg);
  193. info!("(Encrypted) PRIVMSG: {:?}", privmsg);
  194. }
  195. }
  196. {
  197. (*self.seen_msg_ids.lock().await).push(privmsg.id);
  198. (*self.privmsgs_buffer.lock().await).push(&privmsg)
  199. }
  200. self.senders.notify_with_exclude(privmsg.clone(), &[self.subscriber_id]).await;
  201. debug!(target: "ircd", "PRIVMSG to be sent: {:?}", privmsg);
  202. self.p2p.broadcast(privmsg).await?;
  203. Ok(())
  204. }
  205. pub(super) async fn on_receive_join(&mut self, channels: Vec<String>) -> Result<()> {
  206. for chan in channels.iter() {
  207. if !chan.starts_with('#') {
  208. continue
  209. }
  210. if !self.configured_chans.contains_key(chan) {
  211. let mut chan_info = ChannelInfo::new()?;
  212. chan_info.topic = Some("n/a".to_string());
  213. self.configured_chans.insert(chan.to_string(), chan_info);
  214. }
  215. let chan_info = self.configured_chans.get_mut(chan).unwrap();
  216. if chan_info.joined {
  217. return Ok(())
  218. }
  219. chan_info.joined = true;
  220. let topic =
  221. if let Some(topic) = chan_info.topic.clone() { topic } else { "n/a".to_string() };
  222. chan_info.topic = Some(topic.to_string());
  223. {
  224. let j = format!(":{}!anon@dark.fi JOIN {}\r\n", self.nickname, chan);
  225. let t = format!(":DarkFi TOPIC {} :{}\r\n", chan, topic);
  226. self.reply(&j).await?;
  227. self.reply(&t).await?;
  228. }
  229. // Send messages in buffer
  230. if !self.capabilities.get("no-history").unwrap() {
  231. for msg in self.privmsgs_buffer.lock().await.iter() {
  232. if msg.target == *chan {
  233. self.senders.notify_by_id(msg.clone(), self.subscriber_id).await;
  234. }
  235. }
  236. }
  237. }
  238. self.on_receive_names(channels).await?;
  239. Ok(())
  240. }
  241. }