mod.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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::{collections::HashMap, 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 smol::Executor;
  27. use darkfi::{
  28. net::P2pPtr,
  29. system::SubscriberPtr,
  30. util::path::{expand_path, get_config_path},
  31. Error, Result,
  32. };
  33. use crate::{
  34. buffers::SeenIds,
  35. settings::{
  36. parse_configured_channels, parse_configured_contacts, Args, ChannelInfo, ContactInfo,
  37. CONFIG_FILE,
  38. },
  39. Privmsg,
  40. };
  41. mod client;
  42. pub use client::IrcClient;
  43. #[derive(Clone)]
  44. pub struct IrcConfig {
  45. // init bool
  46. pub is_nick_init: bool,
  47. pub is_user_init: bool,
  48. pub is_registered: bool,
  49. pub is_cap_end: bool,
  50. pub is_pass_init: bool,
  51. // user config
  52. pub nickname: String,
  53. pub password: String,
  54. pub capabilities: HashMap<String, bool>,
  55. // channels and contacts
  56. pub auto_channels: Vec<String>,
  57. pub configured_chans: HashMap<String, ChannelInfo>,
  58. pub configured_contacts: HashMap<String, ContactInfo>,
  59. }
  60. impl IrcConfig {
  61. pub fn new(settings: &Args) -> Result<Self> {
  62. let password = settings.password.as_ref().unwrap_or(&String::new()).clone();
  63. let auto_channels = settings.autojoin.clone();
  64. // Pick up channel settings from the TOML configuration
  65. let cfg_path = get_config_path(settings.config.clone(), CONFIG_FILE)?;
  66. let toml_contents = std::fs::read_to_string(cfg_path)?;
  67. let configured_chans = parse_configured_channels(&toml_contents)?;
  68. let configured_contacts = parse_configured_contacts(&toml_contents)?;
  69. let mut capabilities = HashMap::new();
  70. capabilities.insert("no-history".to_string(), false);
  71. Ok(Self {
  72. is_nick_init: false,
  73. is_user_init: false,
  74. is_registered: false,
  75. is_cap_end: true,
  76. is_pass_init: false,
  77. nickname: "anon".to_string(),
  78. password,
  79. auto_channels,
  80. configured_chans,
  81. configured_contacts,
  82. capabilities,
  83. })
  84. }
  85. }
  86. pub struct IrcServer {
  87. settings: Args,
  88. irc_config: IrcConfig,
  89. seen: Arc<Mutex<SeenIds>>,
  90. p2p: P2pPtr,
  91. notify_clients: SubscriberPtr<Privmsg>,
  92. }
  93. impl IrcServer {
  94. pub async fn new(
  95. settings: Args,
  96. seen: Arc<Mutex<SeenIds>>,
  97. p2p: P2pPtr,
  98. notify_clients: SubscriberPtr<Privmsg>,
  99. ) -> Result<Self> {
  100. let irc_config = IrcConfig::new(&settings)?;
  101. Ok(Self { settings, irc_config, seen, p2p, notify_clients })
  102. }
  103. /// Start listening to new irc clients connecting to the irc server address
  104. /// then spawn new connections
  105. pub async fn start(&self, executor: Arc<Executor<'_>>) -> Result<()> {
  106. let (listener, acceptor) = self.setup_listener().await?;
  107. info!("[IRC SERVER] listening on {}", self.settings.irc_listen);
  108. loop {
  109. let (stream, peer_addr) = match listener.accept().await {
  110. Ok((s, a)) => (s, a),
  111. Err(e) => {
  112. error!("[IRC SERVER] Failed accepting new connections: {}", e);
  113. continue
  114. }
  115. };
  116. let result = if let Some(acceptor) = acceptor.clone() {
  117. let stream = match acceptor.accept(stream).await {
  118. Ok(s) => s,
  119. Err(e) => {
  120. error!("[IRC SERVER] Failed accepting TLS connection: {}", e);
  121. continue
  122. }
  123. };
  124. self.process_connection(executor.clone(), stream, peer_addr).await
  125. } else {
  126. self.process_connection(executor.clone(), stream, peer_addr).await
  127. };
  128. if let Err(e) = result {
  129. error!("[IRC SERVER] Failed processing connection {}: {}", peer_addr, e);
  130. continue
  131. };
  132. info!("[IRC SERVER] Accept new connection: {}", peer_addr);
  133. }
  134. }
  135. /// On every new connection create new IrcClient which will process the messages
  136. async fn process_connection<C: AsyncRead + AsyncWrite + Send + Unpin + 'static>(
  137. &self,
  138. executor: Arc<Executor<'_>>,
  139. stream: C,
  140. peer_addr: SocketAddr,
  141. ) -> Result<()> {
  142. let (reader, writer) = stream.split();
  143. let reader = BufReader::new(reader);
  144. // New subscription
  145. let client_subscription = self.notify_clients.clone().subscribe().await;
  146. // New irc connection
  147. let mut client = IrcClient::new(
  148. writer,
  149. peer_addr,
  150. self.seen.clone(),
  151. self.irc_config.clone(),
  152. self.p2p.clone(),
  153. self.notify_clients.clone(),
  154. client_subscription,
  155. );
  156. executor
  157. .spawn(async move {
  158. client.listen(reader).await;
  159. })
  160. .detach();
  161. Ok(())
  162. }
  163. /// Setup a listener for irc server
  164. async fn setup_listener(&self) -> Result<(TcpListener, Option<TlsAcceptor>)> {
  165. let listenaddr = self.settings.irc_listen.socket_addrs(|| None)?[0];
  166. let listener = TcpListener::bind(listenaddr).await?;
  167. let acceptor = match self.settings.irc_listen.scheme() {
  168. "tls" => {
  169. // openssl genpkey -algorithm ED25519 > example.com.key
  170. // openssl req -new -out example.com.csr -key example.com.key
  171. // openssl x509 -req -days 700 -in example.com.csr -signkey example.com.key -out example.com.crt
  172. if self.settings.irc_tls_secret.is_none() || self.settings.irc_tls_cert.is_none() {
  173. error!("[IRC SERVER] To listen using TLS, please set irc_tls_secret and irc_tls_cert in your config file.");
  174. return Err(Error::KeypairPathNotFound)
  175. }
  176. let file =
  177. File::open(expand_path(self.settings.irc_tls_secret.as_ref().unwrap())?)?;
  178. let mut reader = std::io::BufReader::new(file);
  179. let secret = &rustls_pemfile::pkcs8_private_keys(&mut reader)?[0];
  180. let secret = rustls::PrivateKey(secret.clone());
  181. let file = File::open(expand_path(self.settings.irc_tls_cert.as_ref().unwrap())?)?;
  182. let mut reader = std::io::BufReader::new(file);
  183. let certificate = &rustls_pemfile::certs(&mut reader)?[0];
  184. let certificate = rustls::Certificate(certificate.clone());
  185. let config = rustls::ServerConfig::builder()
  186. .with_safe_defaults()
  187. .with_no_client_auth()
  188. .with_single_cert(vec![certificate], secret)?;
  189. let acceptor = TlsAcceptor::from(Arc::new(config));
  190. Some(acceptor)
  191. }
  192. _ => None,
  193. };
  194. Ok((listener, acceptor))
  195. }
  196. }