settings.rs 8.4 KB

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