-
Notifications
You must be signed in to change notification settings - Fork 328
/
mod.rs
346 lines (301 loc) · 11.6 KB
/
mod.rs
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use crate::relay_constraints::{
BridgeConstraints, BridgeSettings, BridgeState, Constraint, LocationConstraint,
OpenVpnConstraints, RelayConstraints, RelayConstraintsUpdate, RelaySettings,
RelaySettingsUpdate, TunnelProtocol,
};
use log::{debug, info};
use serde::{Deserialize, Serialize};
use serde_json;
use std::{
fs::{self, File},
io::{self, Read},
path::PathBuf,
};
use talpid_types::{
net::{openvpn, wireguard, GenericTunnelOptions},
ErrorExt,
};
mod migrations;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(err_derive::Error, Debug)]
pub enum Error {
#[error(display = "Unable to create settings directory")]
DirectoryError(#[error(cause)] mullvad_paths::Error),
#[error(display = "Unable to read settings from {}", _0)]
ReadError(String, #[error(cause)] io::Error),
#[error(display = "Unable to remove settings file {}", _0)]
DeleteError(String, #[error(cause)] io::Error),
#[error(display = "Malformed settings")]
ParseError(#[error(cause)] serde_json::Error),
#[error(display = "Unable to serialize settings to JSON")]
SerializeError(#[error(cause)] serde_json::Error),
#[error(display = "Unable to write settings to {}", _0)]
WriteError(String, #[error(cause)] io::Error),
#[error(display = "Invalid OpenVPN proxy configuration: {}", _0)]
InvalidProxyData(String),
#[error(display = "Unable to read any version of the settings")]
NoMatchingVersion,
}
static SETTINGS_FILE: &str = "settings.json";
/// Mullvad daemon settings.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(default)]
pub struct Settings {
account_token: Option<String>,
relay_settings: RelaySettings,
bridge_settings: BridgeSettings,
bridge_state: BridgeState,
/// If the daemon should allow communication with private (LAN) networks.
allow_lan: bool,
/// Extra level of kill switch. When this setting is on, the disconnected state will block
/// the firewall to not allow any traffic in or out.
block_when_disconnected: bool,
/// If the daemon should connect the VPN tunnel directly on start or not.
auto_connect: bool,
/// Options that should be applied to tunnels of a specific type regardless of where the relays
/// might be located.
tunnel_options: TunnelOptions,
/// Specifies settings schema version
settings_version: migrations::SettingsVersion,
}
impl Default for Settings {
fn default() -> Self {
Settings {
account_token: None,
relay_settings: RelaySettings::Normal(RelayConstraints {
location: Constraint::Only(LocationConstraint::Country("se".to_owned())),
..Default::default()
}),
bridge_settings: BridgeSettings::Normal(BridgeConstraints {
location: Constraint::Any,
}),
bridge_state: BridgeState::Auto,
allow_lan: false,
block_when_disconnected: false,
auto_connect: false,
tunnel_options: TunnelOptions::default(),
settings_version: migrations::SettingsVersion::V2,
}
}
}
impl Settings {
/// Loads user settings from file. If no file is present it returns the defaults.
pub fn load() -> Result<Settings> {
let path = Self::get_settings_path()?;
match File::open(&path) {
Ok(file) => {
info!("Loading settings from {}", path.display());
let mut settings_bytes = vec![];
io::BufReader::new(file)
.read_to_end(&mut settings_bytes)
.map_err(|e| Error::ReadError("Failed to read settings file".to_owned(), e))?;
Self::parse_settings(&mut settings_bytes).or_else(|e| {
log::error!(
"{}",
e.display_chain_with_msg("Failed to parse settings file")
);
let settings = migrations::try_migrate_settings(&settings_bytes)?;
if let Err(e) = settings.save() {
log::error!("Failed to save settings after migration: {}", e);
}
Ok(settings)
})
}
Err(e) => Err(Error::ReadError(path.display().to_string(), e)),
}
}
/// Serializes the settings and saves them to the file it was loaded from.
fn save(&self) -> Result<()> {
let path = Self::get_settings_path()?;
debug!("Writing settings to {}", path.display());
let mut file =
File::create(&path).map_err(|e| Error::WriteError(path.display().to_string(), e))?;
serde_json::to_writer_pretty(&mut file, self).map_err(Error::SerializeError)?;
file.sync_all()
.map_err(|e| Error::WriteError(path.display().to_string(), e))
}
/// Resets default settings
pub fn reset(&mut self) -> Result<()> {
*self = Default::default();
self.save().or_else(|e| {
log::error!(
"{}",
e.display_chain_with_msg("Unable to save default settings")
);
log::error!("Will attempt to remove settings file");
Self::get_settings_path().and_then(|path| {
fs::remove_file(&path)
.map_err(|e| Error::DeleteError(path.display().to_string(), e))
})
})
}
fn get_settings_path() -> Result<PathBuf> {
let dir = ::mullvad_paths::settings_dir().map_err(Error::DirectoryError)?;
Ok(dir.join(SETTINGS_FILE))
}
fn parse_settings(bytes: &[u8]) -> Result<Settings> {
serde_json::from_slice(bytes).map_err(Error::ParseError)
}
pub fn get_account_token(&self) -> Option<String> {
self.account_token.clone()
}
/// Changes account number to the one given. Also saves the new settings to disk.
/// The boolean in the Result indicates if the account token changed or not
pub fn set_account_token(&mut self, mut account_token: Option<String>) -> Result<bool> {
if account_token.as_ref().map(String::len) == Some(0) {
debug!("Setting empty account token is treated as unsetting it");
account_token = None;
}
if account_token != self.account_token {
if account_token.is_none() {
info!("Unsetting account token");
} else if self.account_token.is_none() {
info!("Setting account token");
} else {
info!("Changing account token")
}
self.account_token = account_token;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn get_relay_settings(&self) -> RelaySettings {
self.relay_settings.clone()
}
pub fn update_relay_settings(&mut self, update: RelaySettingsUpdate) -> Result<bool> {
let update_supports_bridge = update.supports_bridge();
let new_settings = self.relay_settings.merge(update);
if self.relay_settings != new_settings {
if !update_supports_bridge && BridgeState::On == self.bridge_state {
self.bridge_state = BridgeState::Auto;
}
debug!(
"changing relay settings from {} to {}",
self.relay_settings, new_settings
);
self.relay_settings = new_settings;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn get_allow_lan(&self) -> bool {
self.allow_lan
}
pub fn set_allow_lan(&mut self, allow_lan: bool) -> Result<bool> {
if allow_lan != self.allow_lan {
self.allow_lan = allow_lan;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn get_block_when_disconnected(&self) -> bool {
self.block_when_disconnected
}
pub fn set_block_when_disconnected(&mut self, block_when_disconnected: bool) -> Result<bool> {
if block_when_disconnected != self.block_when_disconnected {
self.block_when_disconnected = block_when_disconnected;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn get_auto_connect(&self) -> bool {
self.auto_connect
}
pub fn set_auto_connect(&mut self, auto_connect: bool) -> Result<bool> {
if auto_connect != self.auto_connect {
self.auto_connect = auto_connect;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn set_openvpn_mssfix(&mut self, openvpn_mssfix: Option<u16>) -> Result<bool> {
if self.tunnel_options.openvpn.mssfix != openvpn_mssfix {
self.tunnel_options.openvpn.mssfix = openvpn_mssfix;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn set_enable_ipv6(&mut self, enable_ipv6: bool) -> Result<bool> {
if self.tunnel_options.generic.enable_ipv6 != enable_ipv6 {
self.tunnel_options.generic.enable_ipv6 = enable_ipv6;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn set_wireguard_mtu(&mut self, mtu: Option<u16>) -> Result<bool> {
if self.tunnel_options.wireguard.mtu != mtu {
self.tunnel_options.wireguard.mtu = mtu;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn get_tunnel_options(&self) -> &TunnelOptions {
&self.tunnel_options
}
pub fn get_bridge_settings(&self) -> &BridgeSettings {
&self.bridge_settings
}
pub fn set_bridge_settings(&mut self, bridge_settings: BridgeSettings) -> Result<bool> {
if self.bridge_settings != bridge_settings {
self.bridge_settings = bridge_settings;
self.save().map(|_| true)
} else {
Ok(false)
}
}
pub fn get_bridge_state(&self) -> &BridgeState {
&self.bridge_state
}
pub fn set_bridge_state(&mut self, bridge_state: BridgeState) -> Result<bool> {
if self.bridge_state != bridge_state {
self.bridge_state = bridge_state;
if self.bridge_state == BridgeState::On {
self.apply_proxy_constraints();
}
self.save().map(|_| true)
} else {
Ok(false)
}
}
// Set the OpenVPN tunnel to use TCP.
fn apply_proxy_constraints(&mut self) {
let constraints_update = RelayConstraintsUpdate {
tunnel_protocol: Some(Constraint::Only(TunnelProtocol::OpenVpn)),
openvpn_constraints: Some(OpenVpnConstraints {
protocol: Constraint::Any,
port: Constraint::Any,
}),
..Default::default()
};
let settings_update = RelaySettingsUpdate::Normal(constraints_update);
self.relay_settings.merge(settings_update);
}
}
/// TunnelOptions holds configuration data that applies to all kinds of tunnels.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct TunnelOptions {
/// openvpn holds OpenVPN specific tunnel options.
pub openvpn: openvpn::TunnelOptions,
/// Contains wireguard tunnel options.
pub wireguard: wireguard::TunnelOptions,
/// Contains generic tunnel options that may apply to more than a single tunnel type.
pub generic: GenericTunnelOptions,
}
impl Default for TunnelOptions {
fn default() -> Self {
TunnelOptions {
openvpn: openvpn::TunnelOptions::default(),
wireguard: wireguard::TunnelOptions { mtu: None },
generic: GenericTunnelOptions { enable_ipv6: false },
}
}
}