settings.rs 9.3 KB

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