server.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{collections::HashMap, fs::File, io::BufReader, path::PathBuf, sync::Arc};
  19. use darkfi::{
  20. event_graph::Event,
  21. system::{StoppableTask, StoppableTaskPtr, Subscription},
  22. util::path::expand_path,
  23. Error, Result,
  24. };
  25. use futures_rustls::{
  26. rustls::{self, pki_types::PrivateKeyDer},
  27. TlsAcceptor,
  28. };
  29. use log::{debug, error, info};
  30. use smol::{
  31. fs,
  32. lock::{Mutex, RwLock},
  33. net::{SocketAddr, TcpListener},
  34. prelude::{AsyncRead, AsyncWrite},
  35. Executor,
  36. };
  37. use url::Url;
  38. use super::{client::Client, IrcChannel, IrcContact, Privmsg};
  39. use crate::{
  40. crypto::saltbox,
  41. settings::{parse_autojoin_channels, parse_configured_channels, parse_configured_contacts},
  42. DarkIrc,
  43. };
  44. /// Max channel/nick length
  45. pub const MAX_NICK_LEN: usize = 24;
  46. /// IRC server instance
  47. pub struct IrcServer {
  48. /// DarkIrc instance
  49. pub darkirc: Arc<DarkIrc>,
  50. /// Path to the darkirc config file
  51. config_path: PathBuf,
  52. /// TCP listener
  53. listener: TcpListener,
  54. /// TLS acceptor
  55. acceptor: Option<TlsAcceptor>,
  56. /// Configured autojoin channels
  57. pub autojoin: RwLock<Vec<String>>,
  58. /// Configured IRC channels
  59. pub channels: RwLock<HashMap<String, IrcChannel>>,
  60. /// Configured IRC contacts
  61. pub contacts: RwLock<HashMap<String, IrcContact>>,
  62. /// Active client connections
  63. clients: Mutex<HashMap<u16, StoppableTaskPtr>>,
  64. }
  65. impl IrcServer {
  66. /// Instantiate a new IRC server. This function will try to bind a TCP socket,
  67. /// and optionally load a TLS certificate and key. To start the listening loop,
  68. /// call `IrcServer::listen()`.
  69. pub async fn new(
  70. darkirc: Arc<DarkIrc>,
  71. listen: Url,
  72. tls_cert: Option<String>,
  73. tls_secret: Option<String>,
  74. config_path: PathBuf,
  75. ) -> Result<Arc<Self>> {
  76. let scheme = listen.scheme();
  77. if scheme != "tcp" && scheme != "tcp+tls" {
  78. error!("IRC server supports listening only on tcp:// or tcp+tls://");
  79. return Err(Error::BindFailed(listen.to_string()))
  80. }
  81. if scheme == "tcp+tls" && (tls_cert.is_none() || tls_secret.is_none()) {
  82. error!("You must provide a TLS certificate and key if you want a TLS server");
  83. return Err(Error::BindFailed(listen.to_string()))
  84. }
  85. // Bind listener
  86. let listen_addr = listen.socket_addrs(|| None)?[0];
  87. let listener = TcpListener::bind(listen_addr).await?;
  88. let acceptor = match scheme {
  89. "tcp+tls" => {
  90. // openssl genpkey -algorithm ED25519 > example.com.key
  91. // openssl req -new -out example.com.csr -key example.com.key
  92. // openssl x509 -req -in example.com.csr -signkey example.com.key -out example.com.crt
  93. let f = File::open(expand_path(tls_secret.as_ref().unwrap())?)?;
  94. let mut reader = BufReader::new(f);
  95. let secret = PrivateKeyDer::Pkcs8(
  96. rustls_pemfile::pkcs8_private_keys(&mut reader).next().unwrap().unwrap(),
  97. );
  98. let f = File::open(expand_path(tls_cert.as_ref().unwrap())?)?;
  99. let mut reader = BufReader::new(f);
  100. let cert = rustls_pemfile::certs(&mut reader).next().unwrap().unwrap();
  101. let config = rustls::ServerConfig::builder()
  102. .with_no_client_auth()
  103. .with_single_cert(vec![cert], secret)
  104. .unwrap();
  105. let acceptor = TlsAcceptor::from(Arc::new(config));
  106. Some(acceptor)
  107. }
  108. _ => None,
  109. };
  110. let self_ = Arc::new(Self {
  111. darkirc,
  112. config_path,
  113. listener,
  114. acceptor,
  115. autojoin: RwLock::new(Vec::new()),
  116. channels: RwLock::new(HashMap::new()),
  117. contacts: RwLock::new(HashMap::new()),
  118. clients: Mutex::new(HashMap::new()),
  119. });
  120. // Load any channel/contact configuration.
  121. self_.rehash().await?;
  122. Ok(self_)
  123. }
  124. /// Reload the darkirc configuration file and reconfigure channels and contacts.
  125. pub async fn rehash(&self) -> Result<()> {
  126. let contents = fs::read_to_string(&self.config_path).await?;
  127. let contents = match toml::from_str(&contents) {
  128. Ok(v) => v,
  129. Err(e) => {
  130. error!("Failed parsing TOML config: {}", e);
  131. return Err(Error::ParseFailed("Failed parsing TOML config"))
  132. }
  133. };
  134. // Parse autojoin channels
  135. let autojoin = parse_autojoin_channels(&contents)?;
  136. // Parse configured channels
  137. let channels = parse_configured_channels(&contents)?;
  138. // Parse configured contacts
  139. let contacts = parse_configured_contacts(&contents)?;
  140. // FIXME: This will remove clients' joined channels. They need to stay.
  141. // Only if everything is fine, replace.
  142. *self.autojoin.write().await = autojoin;
  143. *self.channels.write().await = channels;
  144. *self.contacts.write().await = contacts;
  145. Ok(())
  146. }
  147. /// Start accepting new IRC connections.
  148. pub async fn listen(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  149. loop {
  150. let (stream, peer_addr) = match self.listener.accept().await {
  151. Ok((s, a)) => (s, a),
  152. // As per usual accept(2) recommendations
  153. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  154. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  155. _ => {
  156. error!("[IRC SERVER] Failed accepting connection: {}", e);
  157. return Err(e.into())
  158. }
  159. },
  160. Err(e) => {
  161. error!("[IRC SERVER] Failed accepting new connection: {}", e);
  162. continue
  163. }
  164. };
  165. match &self.acceptor {
  166. // Expecting encrypted TLS connection
  167. Some(acceptor) => {
  168. let stream = match acceptor.accept(stream).await {
  169. Ok(s) => s,
  170. Err(e) => {
  171. error!("[IRC SERVER] Failed accepting new TLS connection: {}", e);
  172. continue
  173. }
  174. };
  175. // Subscribe to incoming events and set up the connection.
  176. let incoming = self.darkirc.event_graph.event_sub.clone().subscribe().await;
  177. if let Err(e) = self
  178. .clone()
  179. .process_connection(stream, peer_addr, incoming, ex.clone())
  180. .await
  181. {
  182. error!("[IRC SERVER] Failed processing new connection: {}", e);
  183. continue
  184. };
  185. }
  186. // Expecting plain TCP connection
  187. None => {
  188. // Subscribe to incoming events and set up the connection.
  189. let incoming = self.darkirc.event_graph.event_sub.clone().subscribe().await;
  190. if let Err(e) = self
  191. .clone()
  192. .process_connection(stream, peer_addr, incoming, ex.clone())
  193. .await
  194. {
  195. error!("[IRC SERVER] Failed processing new connection: {}", e);
  196. continue
  197. };
  198. }
  199. }
  200. info!("[IRC SERVER] Accepted new client connection at: {}", peer_addr);
  201. }
  202. }
  203. /// IRC client connection process.
  204. /// Sets up multiplexing between the server and client.
  205. /// Detaches the connection as a `StoppableTask`.
  206. async fn process_connection<C: AsyncRead + AsyncWrite + Send + Unpin + 'static>(
  207. self: Arc<Self>,
  208. stream: C,
  209. peer_addr: SocketAddr,
  210. incoming: Subscription<Event>,
  211. ex: Arc<Executor<'_>>,
  212. ) -> Result<()> {
  213. let port = peer_addr.port();
  214. let client = Client::new(self.clone(), incoming, peer_addr).await?;
  215. let conn_task = StoppableTask::new();
  216. self.clients.lock().await.insert(port, conn_task.clone());
  217. conn_task.clone().start(
  218. async move { client.multiplex_connection(stream).await },
  219. move |res| async move {
  220. match res {
  221. Ok(()) => info!("[IRC SERVER] Disconnected client from {}", peer_addr),
  222. Err(e) => error!("[IRC SERVER] Disconnected client from {}: {}", peer_addr, e),
  223. }
  224. self.clone().clients.lock().await.remove(&port);
  225. },
  226. Error::ChannelStopped,
  227. ex,
  228. );
  229. Ok(())
  230. }
  231. fn pad(string: &str) -> Vec<u8> {
  232. let mut bytes = string.as_bytes().to_vec();
  233. bytes.resize(MAX_NICK_LEN, 0x00);
  234. bytes
  235. }
  236. fn unpad(vec: &mut Vec<u8>) {
  237. if let Some(i) = vec.iter().rposition(|x| *x != 0) {
  238. let new_len = i + 1;
  239. vec.truncate(new_len);
  240. }
  241. }
  242. /// Try encrypting a given `Privmsg` if there is such a channel/contact.
  243. pub async fn try_encrypt(&self, privmsg: &mut Privmsg) {
  244. if let Some((name, channel)) = self.channels.read().await.get_key_value(&privmsg.channel) {
  245. if let Some(saltbox) = &channel.saltbox {
  246. // We will pad the name and nick to MAX_NICK_LEN so they all look the same.
  247. privmsg.channel = saltbox::encrypt(saltbox, &Self::pad(&privmsg.channel));
  248. privmsg.nick = saltbox::encrypt(saltbox, &Self::pad(&privmsg.nick));
  249. privmsg.msg = saltbox::encrypt(saltbox, privmsg.msg.as_bytes());
  250. debug!("Successfully encrypted message for {}", name);
  251. return
  252. }
  253. };
  254. if let Some((name, contact)) = self.contacts.read().await.get_key_value(&privmsg.channel) {
  255. if let Some(saltbox) = &contact.saltbox {
  256. // We will pad the nicks to MAX_NICK_LEN so they all look the same.
  257. privmsg.channel = saltbox::encrypt(saltbox, &Self::pad(&privmsg.channel));
  258. privmsg.nick = saltbox::encrypt(saltbox, &Self::pad(&privmsg.nick));
  259. privmsg.msg = saltbox::encrypt(saltbox, privmsg.msg.as_bytes());
  260. debug!("Successfully encrypted message for {}", name);
  261. }
  262. };
  263. }
  264. /// Try decrypting a given potentially encrypted `Privmsg` object.
  265. pub async fn try_decrypt(&self, privmsg: &mut Privmsg) {
  266. // If all fields have base58, then we can consider decrypting.
  267. let channel_ciphertext = match bs58::decode(&privmsg.channel).into_vec() {
  268. Ok(v) => v,
  269. Err(_) => return,
  270. };
  271. let nick_ciphertext = match bs58::decode(&privmsg.nick).into_vec() {
  272. Ok(v) => v,
  273. Err(_) => return,
  274. };
  275. let msg_ciphertext = match bs58::decode(&privmsg.msg).into_vec() {
  276. Ok(v) => v,
  277. Err(_) => return,
  278. };
  279. // Now go through all 3 ciphertexts. We'll use intermediate buffers
  280. // for decryption, iff all passes, we will return a modified
  281. // (i.e. decrypted) privmsg, otherwise we return the original.
  282. for (name, channel) in self.channels.read().await.iter() {
  283. if let Some(saltbox) = &channel.saltbox {
  284. let Some(mut channel_dec) = saltbox::try_decrypt(saltbox, &channel_ciphertext)
  285. else {
  286. continue
  287. };
  288. let Some(mut nick_dec) = saltbox::try_decrypt(saltbox, &nick_ciphertext) else {
  289. continue
  290. };
  291. let Some(msg_dec) = saltbox::try_decrypt(saltbox, &msg_ciphertext) else {
  292. continue
  293. };
  294. Self::unpad(&mut channel_dec);
  295. Self::unpad(&mut nick_dec);
  296. privmsg.channel = String::from_utf8_lossy(&channel_dec).into();
  297. privmsg.nick = String::from_utf8_lossy(&nick_dec).into();
  298. privmsg.msg = String::from_utf8_lossy(&msg_dec).into();
  299. debug!("Successfully decrypted message for {}", name);
  300. return
  301. }
  302. }
  303. for (name, contact) in self.contacts.read().await.iter() {
  304. if let Some(saltbox) = &contact.saltbox {
  305. let Some(mut channel_dec) = saltbox::try_decrypt(saltbox, &channel_ciphertext)
  306. else {
  307. continue
  308. };
  309. let Some(mut nick_dec) = saltbox::try_decrypt(saltbox, &nick_ciphertext) else {
  310. continue
  311. };
  312. let Some(msg_dec) = saltbox::try_decrypt(saltbox, &msg_ciphertext) else {
  313. continue
  314. };
  315. Self::unpad(&mut channel_dec);
  316. Self::unpad(&mut nick_dec);
  317. privmsg.channel = String::from_utf8_lossy(&channel_dec).into();
  318. //privmsg.nick = String::from_utf8_lossy(&nick_dec).into();
  319. privmsg.nick = name.to_string();
  320. privmsg.msg = String::from_utf8_lossy(&msg_dec).into();
  321. debug!("Successfully decrypted message from {}", name);
  322. return
  323. }
  324. }
  325. }
  326. }