1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use crate::dirs::Dirs;
use crate::error::QuicP2pError;
use crate::utils;
use crate::R;
use bytes::Bytes;
use log::{trace, warn};
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet, fmt, fs, io, net::IpAddr, net::SocketAddr, path::PathBuf, str::FromStr,
};
use structopt::StructOpt;
use unwrap::unwrap;
#[derive(Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq, StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct Config {
#[structopt(
short,
long,
default_value = "[]",
parse(try_from_str = "serde_json::from_str")
)]
pub hard_coded_contacts: HashSet<SocketAddr>,
#[structopt(short, long)]
pub port: Option<u16>,
#[structopt(long)]
pub ip: Option<IpAddr>,
#[structopt(long)]
pub max_msg_size_allowed: Option<u32>,
#[structopt(long)]
pub idle_timeout_msec: Option<u64>,
#[structopt(long)]
pub keep_alive_interval_msec: Option<u32>,
#[structopt(long)]
pub bootstrap_cache_dir: Option<String>,
#[structopt(long)]
pub upnp_lease_duration: Option<u32>,
#[structopt(short = "t", long, default_value = "node")]
pub our_type: OurType,
}
impl Config {
pub fn read_or_construct_default(user_override: Option<&Dirs>) -> R<Config> {
let config_path = config_path(user_override)?;
if config_path.exists() {
trace!("Reading config from {:?}", config_path);
Ok(utils::read_from_disk(&config_path)?)
} else {
let config_dir = config_path
.parent()
.ok_or_else(|| io::ErrorKind::NotFound.into())
.map_err(QuicP2pError::Io)?;
fs::create_dir_all(&config_dir)?;
let cfg = Config::default();
utils::write_to_disk(&config_path, &cfg)?;
Ok(cfg)
}
}
}
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
pub(crate) struct SerialisableCertificate {
pub cert_der: Bytes,
pub key_der: Bytes,
}
impl SerialisableCertificate {
pub fn obtain_priv_key_and_cert(&self) -> R<(quinn::PrivateKey, quinn::Certificate)> {
Ok((
quinn::PrivateKey::from_der(&self.key_der)
.map_err(|_| QuicP2pError::CertificateParseError)?,
quinn::Certificate::from_der(&self.cert_der)
.map_err(|_| QuicP2pError::CertificateParseError)?,
))
}
}
impl Default for SerialisableCertificate {
fn default() -> Self {
let cert = unwrap!(rcgen::generate_simple_self_signed(vec![
"MaidSAFE.net".to_string()
]));
Self {
cert_der: unwrap!(cert.serialize_der()).into(),
key_der: cert.serialize_private_key_der().into(),
}
}
}
impl FromStr for SerialisableCertificate {
type Err = QuicP2pError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cert = base64::decode(s)?;
let (cert_der, key_der) = bincode::deserialize(&cert)?;
Ok(Self { cert_der, key_der })
}
}
impl ToString for SerialisableCertificate {
fn to_string(&self) -> String {
let cert = unwrap!(bincode::serialize(&(&self.cert_der, &self.key_der)));
base64::encode(&cert)
}
}
impl fmt::Debug for SerialisableCertificate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"SerialisableCertificate {{ cert_der: {}, key_der: <HIDDEN> }}",
utils::bin_data_format(&self.cert_der)
)
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Eq, PartialEq)]
pub enum OurType {
Client,
Node,
}
impl FromStr for OurType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"client" => Ok(OurType::Client),
"node" => Ok(OurType::Node),
x => {
let err = format!("Unknown client type: {}", x);
warn!("{}", err);
Err(err)
}
}
}
}
impl Default for OurType {
fn default() -> Self {
OurType::Node
}
}
fn config_path(user_override: Option<&Dirs>) -> R<PathBuf> {
let path = |dir: &Dirs| {
let path = dir.config_dir();
path.join("config")
};
let cfg_path = user_override.map_or_else(
|| Ok::<_, QuicP2pError>(path(&utils::project_dir()?)),
|d| Ok(path(d)),
)?;
Ok(cfg_path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::test_dirs;
use crate::utils;
#[test]
fn config_create_read_and_write() {
let dir = test_dirs();
let config_path = unwrap!(config_path(Some(&dir)));
assert!(utils::read_from_disk::<Config>(&config_path).is_err());
let cfg = unwrap!(Config::read_or_construct_default(Some(&dir)));
let read_cfg = unwrap!(utils::read_from_disk(&config_path));
assert_eq!(cfg, read_cfg);
}
}