settings.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 crypto_box::SalsaBox;
  19. use log::{info, warn};
  20. use serde::{self, Deserialize};
  21. use std::collections::HashMap;
  22. use structopt::StructOpt;
  23. use structopt_toml::StructOptToml;
  24. use toml::Value;
  25. use url::Url;
  26. use darkfi::{net::settings::SettingsOpt, Result};
  27. // Location for config file
  28. pub const CONFIG_FILE: &str = "darkirc_config.toml";
  29. pub const CONFIG_FILE_CONTENTS: &str = include_str!("../darkirc_config.toml");
  30. // Msg config
  31. pub const MAXIMUM_LENGTH_OF_MESSAGE: usize = 1024;
  32. pub const MAXIMUM_LENGTH_OF_NICKNAME: usize = 32;
  33. // IRC Client
  34. pub enum RPL {
  35. NoTopic = 331,
  36. Topic = 332,
  37. NameReply = 353,
  38. EndOfNames = 366,
  39. }
  40. /// ircd cli
  41. #[derive(Clone, Deserialize, StructOpt, StructOptToml)]
  42. #[serde(default)]
  43. #[structopt(name = "darkirc")]
  44. pub struct Args {
  45. /// Sets a custom config file
  46. #[structopt(long)]
  47. pub config: Option<String>,
  48. /// JSON-RPC listen URL
  49. #[structopt(long = "rpc", default_value = "tcp://127.0.0.1:26660")]
  50. pub rpc_listen: Url,
  51. /// IRC listen URL
  52. #[structopt(long = "irc", default_value = "tcp://127.0.0.1:6667")]
  53. pub irc_listen: Url,
  54. /// Optional TLS certificate file path if `irc_listen` uses TLS
  55. pub irc_tls_cert: Option<String>,
  56. /// Optional TLS certificate key file path if `irc_listen` uses TLS
  57. pub irc_tls_secret: Option<String>,
  58. /// Generate a new NaCl keypair and exit
  59. #[structopt(long)]
  60. pub gen_keypair: bool,
  61. /// Path to save keypair in
  62. #[structopt(short)]
  63. pub output: Option<String>,
  64. /// Autojoin channels
  65. #[structopt(long)]
  66. pub autojoin: Vec<String>,
  67. /// Password
  68. #[structopt(long)]
  69. pub password: Option<String>,
  70. // /// Private key
  71. // #[structopt(skip)]
  72. // pub private_key: Option<String>,
  73. /// Network settings
  74. #[structopt(flatten)]
  75. pub net: SettingsOpt,
  76. /// Increase verbosity
  77. #[structopt(short, parse(from_occurrences))]
  78. pub verbose: u8,
  79. }
  80. /// This struct holds information about preconfigured contacts.
  81. /// In the TOML configuration file, we can configure contacts as such:
  82. ///
  83. /// ```toml
  84. /// [contact."nick"]
  85. /// pubkey = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  86. /// ```
  87. #[derive(Clone)]
  88. pub struct ContactInfo {
  89. /// Optional NaCl box for the channel, used for {en,de}cryption.
  90. pub salt_box: Option<SalsaBox>,
  91. }
  92. impl ContactInfo {
  93. pub fn new() -> Result<Self> {
  94. Ok(Self { salt_box: None })
  95. }
  96. }
  97. /// This struct holds information about preconfigured channels.
  98. /// In the TOML configuration file, we can configure channels as such:
  99. /// ```toml
  100. /// [channel."#dev"]
  101. /// secret = "GvH4kno3kUu6dqPrZ8zjMhqxTUDZ2ev16EdprZiZJgj1"
  102. /// topic = "DarkFi Development Channel"
  103. /// ```
  104. /// Having a secret will enable a NaCl box that is able to encrypt and
  105. /// decrypt messages in this channel using this set shared secret.
  106. /// The secret should be shared OOB, via a secure channel.
  107. /// Having a topic set is useful if one wants to have a topic in the
  108. /// configured channel. It is not shared with others, but it is useful
  109. /// for personal reference.
  110. #[derive(Default, Clone)]
  111. pub struct ChannelInfo {
  112. /// Optional topic for the channel
  113. pub topic: Option<String>,
  114. /// Optional NaCl box for the channel, used for {en,de}cryption.
  115. pub salt_box: Option<SalsaBox>,
  116. /// Flag indicates whether the user has joined the channel or not
  117. pub joined: bool,
  118. /// All nicknames which are visible on the channel
  119. pub names: Vec<String>,
  120. }
  121. impl ChannelInfo {
  122. pub fn new() -> Result<Self> {
  123. Ok(Self { topic: None, salt_box: None, joined: false, names: vec![] })
  124. }
  125. }
  126. /// Parse a TOML string for any configured channels and return
  127. /// a map containing said configurations.
  128. ///
  129. /// ```toml
  130. /// [channel."#memes"]
  131. /// secret = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  132. /// topic = "Dank Memes"
  133. /// ```
  134. pub fn parse_configured_channels(data: &str) -> Result<HashMap<String, ChannelInfo>> {
  135. let mut ret = HashMap::new();
  136. let map = match toml::from_str(data)? {
  137. Value::Table(m) => m,
  138. _ => return Ok(ret),
  139. };
  140. if !map.contains_key("channel") {
  141. return Ok(ret)
  142. }
  143. if !map["channel"].is_table() {
  144. return Ok(ret)
  145. }
  146. for chan in map["channel"].as_table().unwrap() {
  147. info!("Found configuration for channel {}", chan.0);
  148. let mut channel_info = ChannelInfo::new()?;
  149. if chan.1.as_table().unwrap().contains_key("topic") {
  150. let topic = chan.1["topic"].as_str().unwrap().to_string();
  151. info!("Found topic for channel {}: {}", chan.0, topic);
  152. channel_info.topic = Some(topic);
  153. }
  154. if chan.1.as_table().unwrap().contains_key("secret") {
  155. // Build the NaCl box
  156. if let Some(s) = chan.1["secret"].as_str() {
  157. let salt_box = salt_box_from_shared_secret(s)?;
  158. channel_info.salt_box = Some(salt_box);
  159. info!("Instantiated NaCl box for channel {}", chan.0);
  160. }
  161. }
  162. ret.insert(chan.0.to_string(), channel_info);
  163. }
  164. Ok(ret)
  165. }
  166. /// Parse a TOML string for any configured contact list and return
  167. /// a map containing said configurations.
  168. ///
  169. /// ```toml
  170. /// [contact."nick"]
  171. /// contact_pubkey = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  172. /// ```
  173. pub fn parse_configured_contacts(data: &str) -> Result<HashMap<String, ContactInfo>> {
  174. let mut ret = HashMap::new();
  175. let map = match toml::from_str(data) {
  176. Ok(Value::Table(m)) => m,
  177. _ => {
  178. warn!("Invalid TOML string passed as argument to parse_configured_contacts()");
  179. return Ok(ret)
  180. }
  181. };
  182. if !map.contains_key("contact") {
  183. return Ok(ret)
  184. }
  185. if !map["contact"].is_table() {
  186. warn!("TOML configuration contains a \"contact\" field, but it is not a table.");
  187. return Ok(ret)
  188. }
  189. let contacts = map["contact"].as_table().unwrap();
  190. // Our secret key for NaCl boxes.
  191. let found_priv = match parse_priv_key(data) {
  192. Ok(v) => v,
  193. Err(_) => {
  194. info!("Did not find private key in config, skipping contact configuration.");
  195. return Ok(ret)
  196. }
  197. };
  198. let bytes: [u8; 32] = match bs58::decode(found_priv).into_vec() {
  199. Ok(v) => {
  200. if v.len() != 32 {
  201. warn!("Decoded base58 secret key string is not 32 bytes");
  202. warn!("Skipping private contact configuration");
  203. return Ok(ret)
  204. }
  205. v.try_into().unwrap()
  206. }
  207. Err(e) => {
  208. warn!("Failed to decode base58 secret key from string: {}", e);
  209. warn!("Skipping private contact configuration");
  210. return Ok(ret)
  211. }
  212. };
  213. let secret = crypto_box::SecretKey::from(bytes);
  214. for cnt in contacts {
  215. info!("Found configuration for contact {}", cnt.0);
  216. let mut contact_info = ContactInfo::new()?;
  217. if !cnt.1.is_table() {
  218. warn!("Config for contact {} isn't a TOML table", cnt.0);
  219. continue
  220. }
  221. let table = cnt.1.as_table().unwrap();
  222. if table.is_empty() {
  223. warn!("Configuration for contact {} is empty.", cnt.0);
  224. continue
  225. }
  226. // Build the NaCl box
  227. if !table.contains_key("contact_pubkey") || !table["contact_pubkey"].is_str() {
  228. warn!("Contact {} doesn't have `contact_pubkey` set or is not a string.", cnt.0);
  229. continue
  230. }
  231. let pub_str = table["contact_pubkey"].as_str().unwrap();
  232. let bytes: [u8; 32] = match bs58::decode(pub_str).into_vec() {
  233. Ok(v) => {
  234. if v.len() != 32 {
  235. warn!("Decoded base58 string is not 32 bytes");
  236. continue
  237. }
  238. v.try_into().unwrap()
  239. }
  240. Err(e) => {
  241. warn!("Failed to decode base58 pubkey from string: {}", e);
  242. continue
  243. }
  244. };
  245. let public = crypto_box::PublicKey::from(bytes);
  246. contact_info.salt_box = Some(SalsaBox::new(&public, &secret));
  247. ret.insert(cnt.0.to_string(), contact_info);
  248. info!("Instantiated NaCl box for contact {}", cnt.0);
  249. }
  250. Ok(ret)
  251. }
  252. fn salt_box_from_shared_secret(s: &str) -> Result<SalsaBox> {
  253. let bytes: [u8; 32] = bs58::decode(s).into_vec()?.try_into().unwrap();
  254. let secret = crypto_box::SecretKey::from(bytes);
  255. let public = secret.public_key();
  256. Ok(SalsaBox::new(&public, &secret))
  257. }
  258. fn parse_priv_key(data: &str) -> Result<String> {
  259. let mut pk = String::new();
  260. let map = match toml::from_str(data)? {
  261. Value::Table(m) => m,
  262. _ => return Ok(pk),
  263. };
  264. if !map.contains_key("private_key") {
  265. return Ok(pk)
  266. }
  267. if !map["private_key"].is_table() {
  268. return Ok(pk)
  269. }
  270. let private_keys = map["private_key"].as_table().unwrap();
  271. for prv_key in private_keys {
  272. pk = prv_key.0.into();
  273. }
  274. info!("Found secret key in config, noted it down.");
  275. Ok(pk)
  276. }
  277. // fn parse_priv(key: &str) -> Result<crypto_box::SecretKey> {
  278. // let bytes: [u8; 32] = bs58::decode(key).into_vec()?.try_into().unwrap();
  279. // Ok(crypto_box::SecretKey::from(bytes))
  280. // }
  281. // fn parse_pub(key: &str) -> Result<crypto_box::PublicKey> {
  282. // let bytes: [u8; 32] = bs58::decode(key).into_vec()?.try_into().unwrap();
  283. // Ok(crypto_box::PublicKey::from(bytes))
  284. // }