settings.rs 9.9 KB

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