settings.rs 10 KB

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