settings.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 async_std::sync::Arc;
  19. use crypto_box::ChaChaBox;
  20. use log::{info, warn};
  21. use serde::{self, Deserialize};
  22. use std::collections::{HashMap, HashSet};
  23. use structopt::StructOpt;
  24. use structopt_toml::StructOptToml;
  25. use toml::Value;
  26. use url::Url;
  27. use darkfi::{net::settings::SettingsOpt, Result};
  28. // Location for config file
  29. pub const CONFIG_FILE: &str = "darkirc_config.toml";
  30. pub const CONFIG_FILE_CONTENTS: &str = include_str!("../darkirc_config.toml");
  31. // Msg config
  32. pub const MAXIMUM_LENGTH_OF_MESSAGE: usize = 1024;
  33. pub const MAXIMUM_LENGTH_OF_NICK_CHAN_CNT: usize = 32;
  34. // IRC Client
  35. pub enum RPL {
  36. NoTopic = 331,
  37. Topic = 332,
  38. NameReply = 353,
  39. EndOfNames = 366,
  40. }
  41. /// ircd cli
  42. #[derive(Clone, Deserialize, StructOpt, StructOptToml)]
  43. #[serde(default)]
  44. #[structopt(name = "darkirc")]
  45. pub struct Args {
  46. /// Sets a custom config file
  47. #[structopt(long)]
  48. pub config: Option<String>,
  49. /// JSON-RPC listen URL
  50. #[structopt(long = "rpc", default_value = "tcp://127.0.0.1:26660")]
  51. pub rpc_listen: Url,
  52. /// IRC listen URL
  53. #[structopt(long = "irc", default_value = "tcp://127.0.0.1:6667")]
  54. pub irc_listen: Url,
  55. /// Optional TLS certificate file path if `irc_listen` uses TLS
  56. pub irc_tls_cert: Option<String>,
  57. /// Optional TLS certificate key file path if `irc_listen` uses TLS
  58. pub irc_tls_secret: Option<String>,
  59. /// Generate a new NaCl keypair and exit
  60. #[structopt(long)]
  61. pub gen_keypair: bool,
  62. /// Generate a new NaCl secret for an encrypted channel and exit
  63. #[structopt(long)]
  64. pub gen_secret: bool,
  65. /// Path to save keypair in
  66. #[structopt(short)]
  67. pub output: Option<String>,
  68. /// Autojoin channels
  69. #[structopt(long)]
  70. pub autojoin: Vec<String>,
  71. /// Password
  72. #[structopt(long)]
  73. pub password: Option<String>,
  74. /// Network settings
  75. #[structopt(flatten)]
  76. pub net: SettingsOpt,
  77. #[structopt(short, long)]
  78. /// Set log file to ouput into
  79. pub log: Option<String>,
  80. /// Increase verbosity
  81. #[structopt(short, parse(from_occurrences))]
  82. pub verbose: u8,
  83. }
  84. /// This struct holds information about preconfigured contacts.
  85. /// In the TOML configuration file, we can configure contacts as such:
  86. ///
  87. /// ```toml
  88. /// [contact."nick"]
  89. /// pubkey = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  90. /// ```
  91. #[derive(Clone)]
  92. pub struct ContactInfo {
  93. /// Optional NaCl box for the channel, used for {en,de}cryption.
  94. pub salt_box: Option<Arc<ChaChaBox>>,
  95. }
  96. impl ContactInfo {
  97. pub fn new() -> Result<Self> {
  98. Ok(Self { salt_box: None })
  99. }
  100. }
  101. /// Defined user modes
  102. #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
  103. pub enum UserMode {
  104. None,
  105. Op,
  106. Voice,
  107. HalfOp,
  108. Admin,
  109. Owner,
  110. }
  111. impl std::fmt::Display for UserMode {
  112. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  113. match self {
  114. Self::None => write!(f, ""),
  115. Self::Op => write!(f, "@"),
  116. Self::Voice => write!(f, "+"),
  117. Self::HalfOp => write!(f, "%"),
  118. Self::Admin => write!(f, "&"),
  119. Self::Owner => write!(f, "~"),
  120. }
  121. }
  122. }
  123. /// This struct holds info about a specific nickname within a channel.
  124. /// We usually use it to implement modes.
  125. #[derive(Debug, Clone, Eq)]
  126. pub struct Nick {
  127. name: String,
  128. mode: UserMode,
  129. }
  130. impl Nick {
  131. pub fn new(name: String) -> Self {
  132. Self { name, mode: UserMode::None }
  133. }
  134. pub fn set_mode(&mut self, mode: UserMode) -> Option<String> {
  135. if self.mode == mode {
  136. return None
  137. }
  138. self.mode = mode;
  139. Some(format!("+{}", mode))
  140. }
  141. pub fn unset_mode(&mut self, mode: UserMode) -> Option<String> {
  142. if self.mode != mode {
  143. return None
  144. }
  145. self.mode = mode;
  146. Some(format!("-{}", mode))
  147. }
  148. }
  149. impl PartialEq for Nick {
  150. fn eq(&self, other: &Self) -> bool {
  151. self.name == other.name
  152. }
  153. }
  154. impl From<String> for Nick {
  155. fn from(name: String) -> Self {
  156. Self { name, mode: UserMode::None }
  157. }
  158. }
  159. impl std::hash::Hash for Nick {
  160. fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
  161. state.write(&self.name.clone().into_bytes());
  162. }
  163. }
  164. impl std::fmt::Display for Nick {
  165. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  166. write!(f, "{}{}", self.mode, self.name)
  167. }
  168. }
  169. /// This struct holds information about preconfigured channels.
  170. /// In the TOML configuration file, we can configure channels as such:
  171. /// ```toml
  172. /// [channel."#dev"]
  173. /// secret = "GvH4kno3kUu6dqPrZ8zjMhqxTUDZ2ev16EdprZiZJgj1"
  174. /// topic = "DarkFi Development Channel"
  175. /// ```
  176. /// Having a secret will enable a NaCl box that is able to encrypt and
  177. /// decrypt messages in this channel using this set shared secret.
  178. /// The secret should be shared OOB, via a secure channel.
  179. /// Having a topic set is useful if one wants to have a topic in the
  180. /// configured channel. It is not shared with others, but it is useful
  181. /// for personal reference.
  182. #[derive(Default, Clone)]
  183. pub struct ChannelInfo {
  184. /// Optional topic for the channel
  185. pub topic: Option<String>,
  186. /// Optional NaCl box for the channel, used for {en,de}cryption.
  187. pub salt_box: Option<Arc<ChaChaBox>>,
  188. /// All nicknames which are visible on the channel
  189. pub names: HashSet<Nick>,
  190. }
  191. impl ChannelInfo {
  192. pub fn new() -> Result<Self> {
  193. Ok(Self { topic: None, salt_box: None, names: HashSet::new() })
  194. }
  195. pub fn names(&self) -> String {
  196. self.names.iter().map(|n| n.to_string()).collect::<Vec<String>>().join(" ")
  197. }
  198. }
  199. /// Parse a TOML string for any configured channels and return
  200. /// a map containing said configurations.
  201. ///
  202. /// ```toml
  203. /// [channel."#memes"]
  204. /// secret = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  205. /// topic = "Dank Memes"
  206. /// ```
  207. pub fn parse_configured_channels(data: &str) -> Result<HashMap<String, ChannelInfo>> {
  208. let mut ret = HashMap::new();
  209. let map = match toml::from_str(data)? {
  210. Value::Table(m) => m,
  211. _ => return Ok(ret),
  212. };
  213. if !map.contains_key("channel") {
  214. return Ok(ret)
  215. }
  216. if !map["channel"].is_table() {
  217. return Ok(ret)
  218. }
  219. for chan in map["channel"].as_table().unwrap() {
  220. if chan.0.len() > MAXIMUM_LENGTH_OF_NICK_CHAN_CNT {
  221. warn!("Channel name is too long, skipping...");
  222. continue
  223. }
  224. info!("Found configuration for channel {}", chan.0);
  225. let mut channel_info = ChannelInfo::new()?;
  226. if chan.1.as_table().unwrap().contains_key("topic") {
  227. let topic = chan.1["topic"].as_str().unwrap().to_string();
  228. info!("Found topic for channel {}: {}", chan.0, topic);
  229. channel_info.topic = Some(topic);
  230. }
  231. if chan.1.as_table().unwrap().contains_key("secret") {
  232. // Build the NaCl box
  233. if let Some(s) = chan.1["secret"].as_str() {
  234. let salt_box = salt_box_from_shared_secret(s)?;
  235. channel_info.salt_box = Some(Arc::new(salt_box));
  236. info!("Instantiated NaCl box for channel {}", chan.0);
  237. }
  238. }
  239. ret.insert(chan.0.to_string(), channel_info);
  240. }
  241. Ok(ret)
  242. }
  243. /// Parse a TOML string for any configured contact list and return
  244. /// a map containing said configurations.
  245. ///
  246. /// ```toml
  247. /// [contact."nick"]
  248. /// public_key = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  249. /// ```
  250. pub fn parse_configured_contacts(data: &str) -> Result<HashMap<String, ContactInfo>> {
  251. let mut ret = HashMap::new();
  252. let map = match toml::from_str(data) {
  253. Ok(Value::Table(m)) => m,
  254. _ => {
  255. warn!("Invalid TOML string passed as argument to parse_configured_contacts()");
  256. return Ok(ret)
  257. }
  258. };
  259. if !map.contains_key("contact") {
  260. return Ok(ret)
  261. }
  262. if !map["contact"].is_table() {
  263. warn!("TOML configuration contains a \"contact\" field, but it is not a table.");
  264. return Ok(ret)
  265. }
  266. let contacts = map["contact"].as_table().unwrap();
  267. // Our secret key for NaCl boxes.
  268. let found_secret = match parse_secret_key(data) {
  269. Ok(v) => v,
  270. Err(_) => {
  271. info!("Did not find secret key in config, skipping contact configuration.");
  272. return Ok(ret)
  273. }
  274. };
  275. let bytes: [u8; 32] = match bs58::decode(found_secret).into_vec() {
  276. Ok(v) => {
  277. if v.len() != 32 {
  278. warn!("Decoded base58 secret key string is not 32 bytes");
  279. warn!("Skipping private contact configuration");
  280. return Ok(ret)
  281. }
  282. v.try_into().unwrap()
  283. }
  284. Err(e) => {
  285. warn!("Failed to decode base58 secret key from string: {}", e);
  286. warn!("Skipping private contact configuration");
  287. return Ok(ret)
  288. }
  289. };
  290. let secret = crypto_box::SecretKey::from(bytes);
  291. for cnt in contacts {
  292. if cnt.0.len() > MAXIMUM_LENGTH_OF_NICK_CHAN_CNT {
  293. warn!("Contact name is too long, skipping...");
  294. continue
  295. }
  296. info!("Found configuration for contact {}", cnt.0);
  297. let mut contact_info = ContactInfo::new()?;
  298. if !cnt.1.is_table() {
  299. warn!("Config for contact {} isn't a TOML table", cnt.0);
  300. continue
  301. }
  302. let table = cnt.1.as_table().unwrap();
  303. if table.is_empty() {
  304. warn!("Configuration for contact {} is empty.", cnt.0);
  305. continue
  306. }
  307. // Build the NaCl box
  308. if !table.contains_key("public_key") || !table["public_key"].is_str() {
  309. warn!("Contact {} doesn't have `public_key` set or is not a valid string.", cnt.0);
  310. continue
  311. }
  312. let pub_str = table["public_key"].as_str().unwrap();
  313. let bytes: [u8; 32] = match bs58::decode(pub_str).into_vec() {
  314. Ok(v) => {
  315. if v.len() != 32 {
  316. warn!("Decoded base58 string is not 32 bytes");
  317. continue
  318. }
  319. v.try_into().unwrap()
  320. }
  321. Err(e) => {
  322. warn!("Failed to decode base58 pubkey from string: {}", e);
  323. continue
  324. }
  325. };
  326. let public = crypto_box::PublicKey::from(bytes);
  327. contact_info.salt_box = Some(Arc::new(ChaChaBox::new(&public, &secret)));
  328. ret.insert(cnt.0.to_string(), contact_info);
  329. info!("Instantiated NaCl box for contact \"{}\"", cnt.0);
  330. }
  331. Ok(ret)
  332. }
  333. fn salt_box_from_shared_secret(s: &str) -> Result<ChaChaBox> {
  334. let bytes: [u8; 32] = bs58::decode(s).into_vec()?.try_into().unwrap();
  335. let secret = crypto_box::SecretKey::from(bytes);
  336. let public = secret.public_key();
  337. Ok(ChaChaBox::new(&public, &secret))
  338. }
  339. fn parse_secret_key(data: &str) -> Result<String> {
  340. let mut sk = String::new();
  341. let map = match toml::from_str(data)? {
  342. Value::Table(m) => m,
  343. _ => return Ok(sk),
  344. };
  345. if !map.contains_key("secret_key") {
  346. return Ok(sk)
  347. }
  348. if !map["secret_key"].is_table() {
  349. return Ok(sk)
  350. }
  351. let secret_keys = map["secret_key"].as_table().unwrap();
  352. for key in secret_keys {
  353. sk = key.0.into();
  354. }
  355. info!("Found secret key in config, noted it down.");
  356. Ok(sk)
  357. }