settings.rs 12 KB

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