settings.rs 12 KB

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