server.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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::{fs::File, net::SocketAddr};
  19. use async_std::{
  20. net::TcpListener,
  21. sync::{Arc, Mutex},
  22. };
  23. use futures::{io::BufReader, AsyncRead, AsyncReadExt, AsyncWrite};
  24. use futures_rustls::{rustls, TlsAcceptor};
  25. use log::{error, info};
  26. use darkfi::{
  27. event_graph::{
  28. get_current_time,
  29. model::{Event, EventId, ModelPtr},
  30. protocol_event::{Seen, SeenPtr, UnreadEventsPtr},
  31. view::ViewPtr,
  32. },
  33. net::P2pPtr,
  34. system::SubscriberPtr,
  35. util::path::expand_path,
  36. Error, Result,
  37. };
  38. use super::{ClientSubMsg, IrcClient, IrcConfig, NotifierMsg};
  39. use crate::{settings::Args, PrivMsgEvent};
  40. mod nickserv;
  41. use nickserv::NickServ;
  42. const NICK_NICKSERV: &str = "nickserv";
  43. pub struct IrcServer {
  44. settings: Args,
  45. p2p: P2pPtr,
  46. model: ModelPtr<PrivMsgEvent>,
  47. view: ViewPtr<PrivMsgEvent>,
  48. unread_events: UnreadEventsPtr<PrivMsgEvent>,
  49. clients_subscriptions: SubscriberPtr<ClientSubMsg>,
  50. seen: SeenPtr<EventId>,
  51. missed_events: Arc<Mutex<Vec<Event<PrivMsgEvent>>>>,
  52. /// nickserv service
  53. pub nickserv: NickServ,
  54. }
  55. impl IrcServer {
  56. pub async fn new(
  57. settings: Args,
  58. p2p: P2pPtr,
  59. model: ModelPtr<PrivMsgEvent>,
  60. view: ViewPtr<PrivMsgEvent>,
  61. unread_events: UnreadEventsPtr<PrivMsgEvent>,
  62. clients_subscriptions: SubscriberPtr<ClientSubMsg>,
  63. ) -> Result<Self> {
  64. let seen = Seen::new();
  65. let missed_events = Arc::new(Mutex::new(vec![]));
  66. Ok(Self {
  67. settings,
  68. p2p,
  69. model,
  70. view,
  71. unread_events,
  72. clients_subscriptions,
  73. seen,
  74. missed_events,
  75. nickserv: NickServ::default(),
  76. })
  77. }
  78. pub async fn start(&self, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  79. let (msg_notifier, msg_recv) = smol::channel::unbounded();
  80. // Listen to msgs from clients
  81. executor
  82. .clone()
  83. .spawn(Self::listen_to_msgs(
  84. self.p2p.clone(),
  85. self.model.clone(),
  86. self.seen.clone(),
  87. self.unread_events.clone(),
  88. msg_recv,
  89. self.clients_subscriptions.clone(),
  90. ))
  91. .detach();
  92. executor
  93. .clone()
  94. .spawn(Self::listen_to_view(
  95. self.view.clone(),
  96. self.seen.clone(),
  97. self.missed_events.clone(),
  98. self.clients_subscriptions.clone(),
  99. ))
  100. .detach();
  101. // Start listening for new connections
  102. self.listen(msg_notifier, executor.clone()).await?;
  103. Ok(())
  104. }
  105. async fn listen_to_view(
  106. view: ViewPtr<PrivMsgEvent>,
  107. seen: SeenPtr<EventId>,
  108. missed_events: Arc<Mutex<Vec<Event<PrivMsgEvent>>>>,
  109. clients_subscriptions: SubscriberPtr<ClientSubMsg>,
  110. ) -> Result<()> {
  111. loop {
  112. let event = view.lock().await.process().await?;
  113. if !seen.push(&event.hash()).await {
  114. continue
  115. }
  116. missed_events.lock().await.push(event.clone());
  117. let msg = event.action.clone();
  118. clients_subscriptions.notify(ClientSubMsg::Privmsg(msg)).await;
  119. }
  120. }
  121. /// Start listening to msgs from irc clients
  122. pub async fn listen_to_msgs(
  123. p2p: P2pPtr,
  124. model: ModelPtr<PrivMsgEvent>,
  125. seen: SeenPtr<EventId>,
  126. unread_events: UnreadEventsPtr<PrivMsgEvent>,
  127. recv: smol::channel::Receiver<(NotifierMsg, u64)>,
  128. clients_subscriptions: SubscriberPtr<ClientSubMsg>,
  129. ) -> Result<()> {
  130. loop {
  131. let (msg, subscription_id) = recv.recv().await?;
  132. match msg {
  133. NotifierMsg::Privmsg(msg) => {
  134. // First check if we're communicating with any services.
  135. // If not, then we proceed with behaving like it's a normal
  136. // message.
  137. // TODO: This needs to be protected from adversaries doing
  138. // remote execution.
  139. match msg.target.to_lowercase().as_str() {
  140. NICK_NICKSERV => {
  141. //self.nickserv.act(msg);
  142. continue
  143. }
  144. _ => {} // pass
  145. }
  146. let event = Event {
  147. previous_event_hash: model.lock().await.get_head_hash(),
  148. action: msg.clone(),
  149. timestamp: get_current_time(),
  150. read_confirms: 0,
  151. };
  152. // Since this will be added to the View directly, other clients connected to irc
  153. // server must get informed about this new msg
  154. clients_subscriptions
  155. .notify_with_exclude(ClientSubMsg::Privmsg(msg), &[subscription_id])
  156. .await;
  157. if !seen.push(&event.hash()).await {
  158. continue
  159. }
  160. unread_events.lock().await.insert(&event);
  161. p2p.broadcast(event).await?;
  162. }
  163. NotifierMsg::UpdateConfig => {
  164. //
  165. // load and parse the new settings from configuration file and pass it to all
  166. // irc clients
  167. //
  168. // let new_config = IrcConfig::new()?;
  169. // clients_subscriptions.notify(ClientSubMsg::Config(new_config)).await;
  170. }
  171. }
  172. }
  173. }
  174. /// Start listening to new connections from irc clients
  175. pub async fn listen(
  176. &self,
  177. notifier: smol::channel::Sender<(NotifierMsg, u64)>,
  178. executor: Arc<smol::Executor<'_>>,
  179. ) -> Result<()> {
  180. let (listener, acceptor) = self.setup_listener().await?;
  181. info!("[IRC SERVER] listening on {}", self.settings.irc_listen);
  182. loop {
  183. let (stream, peer_addr) = match listener.accept().await {
  184. Ok((s, a)) => (s, a),
  185. Err(e) => {
  186. error!("[IRC SERVER] Failed accepting new connections: {}", e);
  187. continue
  188. }
  189. };
  190. let result = if let Some(acceptor) = acceptor.clone() {
  191. // TLS connection
  192. let stream = match acceptor.accept(stream).await {
  193. Ok(s) => s,
  194. Err(e) => {
  195. error!("[IRC SERVER] Failed accepting TLS connection: {}", e);
  196. continue
  197. }
  198. };
  199. self.process_connection(stream, peer_addr, notifier.clone(), executor.clone()).await
  200. } else {
  201. // TCP connection
  202. self.process_connection(stream, peer_addr, notifier.clone(), executor.clone()).await
  203. };
  204. if let Err(e) = result {
  205. error!("[IRC SERVER] Failed processing connection {}: {}", peer_addr, e);
  206. continue
  207. };
  208. info!("[IRC SERVER] Accept new connection: {}", peer_addr);
  209. }
  210. }
  211. /// On every new connection create new IrcClient
  212. async fn process_connection<C: AsyncRead + AsyncWrite + Send + Unpin + 'static>(
  213. &self,
  214. stream: C,
  215. peer_addr: SocketAddr,
  216. notifier: smol::channel::Sender<(NotifierMsg, u64)>,
  217. executor: Arc<smol::Executor<'_>>,
  218. ) -> Result<()> {
  219. let (reader, writer) = stream.split();
  220. let reader = BufReader::new(reader);
  221. // Subscription for the new client
  222. let client_subscription = self.clients_subscriptions.clone().subscribe().await;
  223. // new irc configuration
  224. let irc_config = IrcConfig::new(&self.settings)?;
  225. // New irc client
  226. let mut client = IrcClient::new(
  227. writer,
  228. reader,
  229. peer_addr,
  230. irc_config,
  231. notifier,
  232. client_subscription,
  233. self.missed_events.clone(),
  234. );
  235. // Start listening and detach
  236. executor
  237. .spawn(async move {
  238. client.listen().await;
  239. })
  240. .detach();
  241. Ok(())
  242. }
  243. /// Setup a listener for irc server
  244. async fn setup_listener(&self) -> Result<(TcpListener, Option<TlsAcceptor>)> {
  245. let listenaddr = self.settings.irc_listen.socket_addrs(|| None)?[0];
  246. let listener = TcpListener::bind(listenaddr).await?;
  247. let acceptor = match self.settings.irc_listen.scheme() {
  248. "tls" => {
  249. // openssl genpkey -algorithm ED25519 > example.com.key
  250. // openssl req -new -out example.com.csr -key example.com.key
  251. // openssl x509 -req -days 700 -in example.com.csr -signkey example.com.key -out example.com.crt
  252. if self.settings.irc_tls_secret.is_none() || self.settings.irc_tls_cert.is_none() {
  253. error!("[IRC SERVER] To listen using TLS, please set irc_tls_secret and irc_tls_cert in your config file.");
  254. return Err(Error::KeypairPathNotFound)
  255. }
  256. let file =
  257. File::open(expand_path(self.settings.irc_tls_secret.as_ref().unwrap())?)?;
  258. let mut reader = std::io::BufReader::new(file);
  259. let secret = &rustls_pemfile::pkcs8_private_keys(&mut reader)?[0];
  260. let secret = rustls::PrivateKey(secret.clone());
  261. let file = File::open(expand_path(self.settings.irc_tls_cert.as_ref().unwrap())?)?;
  262. let mut reader = std::io::BufReader::new(file);
  263. let certificate = &rustls_pemfile::certs(&mut reader)?[0];
  264. let certificate = rustls::Certificate(certificate.clone());
  265. let config = rustls::ServerConfig::builder()
  266. .with_safe_defaults()
  267. .with_no_client_auth()
  268. .with_single_cert(vec![certificate], secret)?;
  269. let acceptor = TlsAcceptor::from(Arc::new(config));
  270. Some(acceptor)
  271. }
  272. _ => None,
  273. };
  274. Ok((listener, acceptor))
  275. }
  276. }