settings.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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::collections::HashMap;
  19. use crypto_box::SalsaBox;
  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. /// Recover public key from secret key
  75. #[structopt(long = "recover_pubkey")]
  76. pub secret: Option<String>,
  77. /// Path to save keypair in
  78. #[structopt(short)]
  79. pub output: Option<String>,
  80. /// Autojoin channels
  81. #[structopt(long)]
  82. pub autojoin: Vec<String>,
  83. /// Password
  84. #[structopt(long)]
  85. pub password: Option<String>,
  86. #[structopt(flatten)]
  87. pub net: SettingsOpt,
  88. /// Increase verbosity
  89. #[structopt(short, parse(from_occurrences))]
  90. pub verbose: u8,
  91. }
  92. #[derive(Clone)]
  93. pub struct ContactInfo {
  94. /// Optional NaCl box for the channel, used for {en,de}cryption.
  95. pub salt_box: Option<SalsaBox>,
  96. }
  97. impl ContactInfo {
  98. pub fn new() -> Result<Self> {
  99. Ok(Self { salt_box: None })
  100. }
  101. }
  102. /// This struct holds information about preconfigured channels.
  103. /// In the TOML configuration file, we can configure channels as such:
  104. /// ```toml
  105. /// [channel."#dev"]
  106. /// secret = "GvH4kno3kUu6dqPrZ8zjMhqxTUDZ2ev16EdprZiZJgj1"
  107. /// topic = "DarkFi Development Channel"
  108. /// ```
  109. /// Having a secret will enable a NaCl box that is able to encrypt and
  110. /// decrypt messages in this channel using this set shared secret.
  111. /// The secret should be shared OOB, via a secure channel.
  112. /// Having a topic set is useful if one wants to have a topic in the
  113. /// configured channel. It is not shared with others, but it is useful
  114. /// for personal reference.
  115. #[derive(Clone)]
  116. pub struct ChannelInfo {
  117. /// Optional topic for the channel
  118. pub topic: Option<String>,
  119. /// Optional NaCl box for the channel, used for {en,de}cryption.
  120. pub salt_box: Option<SalsaBox>,
  121. /// Flag indicates whether the user has joined the channel or not
  122. pub joined: bool,
  123. /// All nicknames which are visible on the channel
  124. pub names: Vec<String>,
  125. }
  126. impl ChannelInfo {
  127. pub fn new() -> Result<Self> {
  128. Ok(Self { topic: None, salt_box: None, joined: false, names: vec![] })
  129. }
  130. }
  131. fn salt_box_from_shared_secret(s: &str) -> Result<SalsaBox> {
  132. let bytes: [u8; 32] = bs58::decode(s).into_vec()?.try_into().unwrap();
  133. let secret = crypto_box::SecretKey::from(bytes);
  134. let public = secret.public_key();
  135. Ok(SalsaBox::new(&public, &secret))
  136. }
  137. fn parse_priv_key(data: &str) -> Result<String> {
  138. let mut pk = String::new();
  139. let map = match toml::from_str(data)? {
  140. Value::Table(m) => m,
  141. _ => return Ok(pk),
  142. };
  143. if !map.contains_key("private_key") {
  144. return Ok(pk)
  145. }
  146. if !map["private_key"].is_table() {
  147. return Ok(pk)
  148. }
  149. let private_keys = map["private_key"].as_table().unwrap();
  150. for prv_key in private_keys {
  151. pk = prv_key.0.into();
  152. }
  153. info!("Found secret key in config, noted it down.");
  154. Ok(pk)
  155. }
  156. /// Parse a TOML string for any configured contact list and return
  157. /// a map containing said configurations.
  158. ///
  159. /// ```toml
  160. /// [contact."nick"]
  161. /// contact_pubkey = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  162. /// ```
  163. pub fn parse_configured_contacts(data: &str) -> Result<HashMap<String, ContactInfo>> {
  164. let mut ret = HashMap::new();
  165. let map = match toml::from_str(data) {
  166. Ok(Value::Table(m)) => m,
  167. _ => {
  168. warn!("Invalid TOML string passed as argument to parse_configured_contacts()");
  169. return Ok(ret)
  170. }
  171. };
  172. if !map.contains_key("contact") {
  173. return Ok(ret)
  174. }
  175. if !map["contact"].is_table() {
  176. warn!("TOML configuration contains a \"contact\" field, but it is not a table.");
  177. return Ok(ret)
  178. }
  179. let contacts = map["contact"].as_table().unwrap();
  180. // Our secret key for NaCl boxes.
  181. let found_priv = match parse_priv_key(data) {
  182. Ok(v) => v,
  183. Err(_) => {
  184. info!("Did not found private key in config, skipping contact configuration.");
  185. return Ok(ret)
  186. }
  187. };
  188. let bytes: [u8; 32] = match bs58::decode(found_priv).into_vec() {
  189. Ok(v) => {
  190. if v.len() != 32 {
  191. warn!("Decoded base58 secret key string is not 32 bytes");
  192. warn!("Skipping private contact configuration");
  193. return Ok(ret)
  194. }
  195. v.try_into().unwrap()
  196. }
  197. Err(e) => {
  198. warn!("Failed to decode base58 secret key from string: {}", e);
  199. warn!("Skipping private contact configuration");
  200. return Ok(ret)
  201. }
  202. };
  203. let secret = crypto_box::SecretKey::from(bytes);
  204. for cnt in contacts {
  205. info!("Found configuration for contact {}", cnt.0);
  206. let mut contact_info = ContactInfo::new()?;
  207. if !cnt.1.is_table() {
  208. warn!("Config for contact {} isn't a TOML table", cnt.0);
  209. continue
  210. }
  211. let table = cnt.1.as_table().unwrap();
  212. if table.is_empty() {
  213. warn!("Configuration for contact {} is empty.", cnt.0);
  214. continue
  215. }
  216. // Build the NaCl box
  217. if !table.contains_key("contact_pubkey") || !table["contact_pubkey"].is_str() {
  218. warn!("Contact {} doesn't have `contact_pubkey` set or is not a string.", cnt.0);
  219. continue
  220. }
  221. let pub_str = table["contact_pubkey"].as_str().unwrap();
  222. let bytes: [u8; 32] = match bs58::decode(pub_str).into_vec() {
  223. Ok(v) => {
  224. if v.len() != 32 {
  225. warn!("Decoded base58 string is not 32 bytes");
  226. continue
  227. }
  228. v.try_into().unwrap()
  229. }
  230. Err(e) => {
  231. warn!("Failed to decode base58 pubkey from string: {}", e);
  232. continue
  233. }
  234. };
  235. let public = crypto_box::PublicKey::from(bytes);
  236. contact_info.salt_box = Some(SalsaBox::new(&public, &secret));
  237. ret.insert(cnt.0.to_string(), contact_info);
  238. info!("Instantiated NaCl box for contact {}", cnt.0);
  239. }
  240. Ok(ret)
  241. }
  242. /// Parse a TOML string for any configured channels and return
  243. /// a map containing said configurations.
  244. ///
  245. /// ```toml
  246. /// [channel."#memes"]
  247. /// secret = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  248. /// topic = "Dank Memes"
  249. /// ```
  250. pub fn parse_configured_channels(data: &str) -> Result<HashMap<String, ChannelInfo>> {
  251. let mut ret = HashMap::new();
  252. let map = match toml::from_str(data)? {
  253. Value::Table(m) => m,
  254. _ => return Ok(ret),
  255. };
  256. if !map.contains_key("channel") {
  257. return Ok(ret)
  258. }
  259. if !map["channel"].is_table() {
  260. return Ok(ret)
  261. }
  262. for chan in map["channel"].as_table().unwrap() {
  263. info!("Found configuration for channel {}", chan.0);
  264. let mut channel_info = ChannelInfo::new()?;
  265. if chan.1.as_table().unwrap().contains_key("topic") {
  266. let topic = chan.1["topic"].as_str().unwrap().to_string();
  267. info!("Found topic for channel {}: {}", chan.0, topic);
  268. channel_info.topic = Some(topic);
  269. }
  270. if chan.1.as_table().unwrap().contains_key("secret") {
  271. // Build the NaCl box
  272. if let Some(s) = chan.1["secret"].as_str() {
  273. let salt_box = salt_box_from_shared_secret(s)?;
  274. channel_info.salt_box = Some(salt_box);
  275. info!("Instantiated NaCl box for channel {}", chan.0);
  276. }
  277. }
  278. ret.insert(chan.0.to_string(), channel_info);
  279. }
  280. Ok(ret)
  281. }
  282. pub fn get_current_time() -> u64 {
  283. let start = std::time::SystemTime::now();
  284. start
  285. .duration_since(std::time::UNIX_EPOCH)
  286. .expect("Time went backwards")
  287. .as_millis()
  288. .try_into()
  289. .unwrap()
  290. }