settings.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. /// Flag indicates whether the user has joined the channel or not
  189. pub joined: bool,
  190. /// All nicknames which are visible on the channel
  191. pub names: HashSet<Nick>,
  192. }
  193. impl ChannelInfo {
  194. pub fn new() -> Result<Self> {
  195. Ok(Self { topic: None, salt_box: None, joined: false, names: HashSet::new() })
  196. }
  197. pub fn names(&self) -> String {
  198. self.names.iter().map(|n| n.to_string()).collect::<Vec<String>>().join(" ")
  199. }
  200. }
  201. /// Parse a TOML string for any configured channels and return
  202. /// a map containing said configurations.
  203. ///
  204. /// ```toml
  205. /// [channel."#memes"]
  206. /// secret = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  207. /// topic = "Dank Memes"
  208. /// ```
  209. pub fn parse_configured_channels(data: &str) -> Result<HashMap<String, ChannelInfo>> {
  210. let mut ret = HashMap::new();
  211. let map = match toml::from_str(data)? {
  212. Value::Table(m) => m,
  213. _ => return Ok(ret),
  214. };
  215. if !map.contains_key("channel") {
  216. return Ok(ret)
  217. }
  218. if !map["channel"].is_table() {
  219. return Ok(ret)
  220. }
  221. for chan in map["channel"].as_table().unwrap() {
  222. if chan.0.len() > MAXIMUM_LENGTH_OF_NICK_CHAN_CNT {
  223. warn!("Channel name is too long, skipping...");
  224. continue
  225. }
  226. info!("Found configuration for channel {}", chan.0);
  227. let mut channel_info = ChannelInfo::new()?;
  228. if chan.1.as_table().unwrap().contains_key("topic") {
  229. let topic = chan.1["topic"].as_str().unwrap().to_string();
  230. info!("Found topic for channel {}: {}", chan.0, topic);
  231. channel_info.topic = Some(topic);
  232. }
  233. if chan.1.as_table().unwrap().contains_key("secret") {
  234. // Build the NaCl box
  235. if let Some(s) = chan.1["secret"].as_str() {
  236. let salt_box = salt_box_from_shared_secret(s)?;
  237. channel_info.salt_box = Some(Arc::new(salt_box));
  238. info!("Instantiated NaCl box for channel {}", chan.0);
  239. }
  240. }
  241. ret.insert(chan.0.to_string(), channel_info);
  242. }
  243. Ok(ret)
  244. }
  245. /// Parse a TOML string for any configured contact list and return
  246. /// a map containing said configurations.
  247. ///
  248. /// ```toml
  249. /// [contact."nick"]
  250. /// public_key = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  251. /// ```
  252. pub fn parse_configured_contacts(data: &str) -> Result<HashMap<String, ContactInfo>> {
  253. let mut ret = HashMap::new();
  254. let map = match toml::from_str(data) {
  255. Ok(Value::Table(m)) => m,
  256. _ => {
  257. warn!("Invalid TOML string passed as argument to parse_configured_contacts()");
  258. return Ok(ret)
  259. }
  260. };
  261. if !map.contains_key("contact") {
  262. return Ok(ret)
  263. }
  264. if !map["contact"].is_table() {
  265. warn!("TOML configuration contains a \"contact\" field, but it is not a table.");
  266. return Ok(ret)
  267. }
  268. let contacts = map["contact"].as_table().unwrap();
  269. // Our secret key for NaCl boxes.
  270. let found_secret = match parse_secret_key(data) {
  271. Ok(v) => v,
  272. Err(_) => {
  273. info!("Did not find secret key in config, skipping contact configuration.");
  274. return Ok(ret)
  275. }
  276. };
  277. let bytes: [u8; 32] = match bs58::decode(found_secret).into_vec() {
  278. Ok(v) => {
  279. if v.len() != 32 {
  280. warn!("Decoded base58 secret key string is not 32 bytes");
  281. warn!("Skipping private contact configuration");
  282. return Ok(ret)
  283. }
  284. v.try_into().unwrap()
  285. }
  286. Err(e) => {
  287. warn!("Failed to decode base58 secret key from string: {}", e);
  288. warn!("Skipping private contact configuration");
  289. return Ok(ret)
  290. }
  291. };
  292. let secret = crypto_box::SecretKey::from(bytes);
  293. for cnt in contacts {
  294. if cnt.0.len() > MAXIMUM_LENGTH_OF_NICK_CHAN_CNT {
  295. warn!("Contact name is too long, skipping...");
  296. continue
  297. }
  298. info!("Found configuration for contact {}", cnt.0);
  299. let mut contact_info = ContactInfo::new()?;
  300. if !cnt.1.is_table() {
  301. warn!("Config for contact {} isn't a TOML table", cnt.0);
  302. continue
  303. }
  304. let table = cnt.1.as_table().unwrap();
  305. if table.is_empty() {
  306. warn!("Configuration for contact {} is empty.", cnt.0);
  307. continue
  308. }
  309. // Build the NaCl box
  310. if !table.contains_key("public_key") || !table["public_key"].is_str() {
  311. warn!("Contact {} doesn't have `public_key` set or is not a valid string.", cnt.0);
  312. continue
  313. }
  314. let pub_str = table["public_key"].as_str().unwrap();
  315. let bytes: [u8; 32] = match bs58::decode(pub_str).into_vec() {
  316. Ok(v) => {
  317. if v.len() != 32 {
  318. warn!("Decoded base58 string is not 32 bytes");
  319. continue
  320. }
  321. v.try_into().unwrap()
  322. }
  323. Err(e) => {
  324. warn!("Failed to decode base58 pubkey from string: {}", e);
  325. continue
  326. }
  327. };
  328. let public = crypto_box::PublicKey::from(bytes);
  329. contact_info.salt_box = Some(Arc::new(ChaChaBox::new(&public, &secret)));
  330. ret.insert(cnt.0.to_string(), contact_info);
  331. info!("Instantiated NaCl box for contact \"{}\"", cnt.0);
  332. }
  333. Ok(ret)
  334. }
  335. fn salt_box_from_shared_secret(s: &str) -> Result<ChaChaBox> {
  336. let bytes: [u8; 32] = bs58::decode(s).into_vec()?.try_into().unwrap();
  337. let secret = crypto_box::SecretKey::from(bytes);
  338. let public = secret.public_key();
  339. Ok(ChaChaBox::new(&public, &secret))
  340. }
  341. fn parse_secret_key(data: &str) -> Result<String> {
  342. let mut sk = String::new();
  343. let map = match toml::from_str(data)? {
  344. Value::Table(m) => m,
  345. _ => return Ok(sk),
  346. };
  347. if !map.contains_key("secret_key") {
  348. return Ok(sk)
  349. }
  350. if !map["secret_key"].is_table() {
  351. return Ok(sk)
  352. }
  353. let secret_keys = map["secret_key"].as_table().unwrap();
  354. for key in secret_keys {
  355. sk = key.0.into();
  356. }
  357. info!("Found secret key in config, noted it down.");
  358. Ok(sk)
  359. }