settings.rs 12 KB

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