summaryrefslogtreecommitdiffhomepage
path: root/mullvad-daemon/src/settings.rs
blob: 0b25a1415759b897f4a941898de3c245ff08bde7 (plain)
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
use log::{debug, error, info};
use mullvad_types::{
    relay_constraints::{BridgeSettings, BridgeState, RelaySettingsUpdate},
    settings::Settings,
};
use std::{
    fs::{self, File},
    io,
    ops::Deref,
    path::{Path, PathBuf},
};
use talpid_types::ErrorExt;

#[cfg(windows)]
use talpid_core::logging::windows::log_sink;


static SETTINGS_FILE: &str = "settings.json";


#[derive(err_derive::Error, Debug)]
pub enum Error {
    #[error(display = "Unable to remove settings file {}", _0)]
    #[cfg(not(target_os = "android"))]
    DeleteError(String, #[error(source)] io::Error),

    #[error(display = "Unable to serialize settings to JSON")]
    SerializeError(#[error(source)] serde_json::Error),

    #[error(display = "Unable to write settings to {}", _0)]
    WriteError(String, #[error(source)] io::Error),
}

#[derive(err_derive::Error, Debug)]
enum LoadSettingsError {
    #[error(display = "Cannot find settings file")]
    FileNotFound,

    #[error(display = "Unable to read settings file")]
    Other(#[error(source)] io::Error),

    #[error(display = "Unable to parse settings file")]
    ParseError(#[error(source)] mullvad_types::settings::Error),

    #[cfg(windows)]
    #[error(display = "Failed to restore Windows Update backup: {}", _0)]
    WinMigrationError(ffi::WinUtilMigrationStatus),
}


#[derive(Debug)]
pub struct SettingsPersister {
    settings: Settings,
    path: PathBuf,
}

impl SettingsPersister {
    /// Loads user settings from file. If no file is present it returns the defaults.
    pub fn load(settings_dir: &Path) -> Self {
        let path = settings_dir.join(SETTINGS_FILE);
        let (mut settings, mut should_save) = Self::load_settings(&path);

        // Force IPv6 to be enabled on Android
        if cfg!(target_os = "android") {
            should_save |=
                Self::update_field(&mut settings.tunnel_options.generic.enable_ipv6, true);
        }

        let mut persister = SettingsPersister { settings, path };

        if should_save {
            if let Err(error) = persister.save() {
                error!(
                    "{}",
                    error.display_chain_with_msg("Failed to save updated settings")
                );
            }
        }

        persister
    }

    fn load_settings(path: &Path) -> (Settings, bool) {
        Self::load_settings_from_file(path)
            .or_else(|error| match error {
                #[cfg(windows)]
                LoadSettingsError::FileNotFound => {
                    Self::try_load_settings_after_windows_update(path)
                }
                _ => Err(error),
            })
            .unwrap_or_else(|error| {
                info!(
                    "{}",
                    error.display_chain_with_msg("Failed to load settings. Using defaults.")
                );
                (Settings::default(), true)
            })
    }

    fn load_settings_from_file(path: &Path) -> Result<(Settings, bool), LoadSettingsError> {
        info!("Loading settings from {}", path.display());

        let settings_bytes = fs::read(path).map_err(|error| {
            if error.kind() == io::ErrorKind::NotFound {
                LoadSettingsError::FileNotFound
            } else {
                LoadSettingsError::Other(error)
            }
        })?;

        Settings::load_from_bytes(&settings_bytes)
            .map(|settings| (settings, false))
            .or_else(|_| {
                Settings::migrate_from_bytes(&settings_bytes).map(|settings| (settings, true))
            })
            .map_err(LoadSettingsError::ParseError)
    }

    #[cfg(windows)]
    fn try_load_settings_after_windows_update(
        path: &Path,
    ) -> Result<(Settings, bool), LoadSettingsError> {
        info!("No settings file found. Attempting migration from Windows Update backup location");

        Self::migrate_after_windows_update()?;
        Self::load_settings_from_file(path)
    }

    #[cfg(windows)]
    fn migrate_after_windows_update() -> Result<(), LoadSettingsError> {
        unsafe {
            ffi::WinUtil_MigrateAfterWindowsUpdate(Some(log_sink), b"Settings migrator\0".as_ptr())
                .into()
        }
    }

    /// Serializes the settings and saves them to the file it was loaded from.
    fn save(&mut self) -> Result<(), Error> {
        debug!("Writing settings to {}", self.path.display());
        let mut file = File::create(&self.path)
            .map_err(|e| Error::WriteError(self.path.display().to_string(), e))?;

        serde_json::to_writer_pretty(&mut file, &self.settings).map_err(Error::SerializeError)?;
        file.sync_all()
            .map_err(|e| Error::WriteError(self.path.display().to_string(), e))
    }

    /// Resets default settings
    #[cfg(not(target_os = "android"))]
    pub fn reset(&mut self) -> Result<(), Error> {
        self.settings = Settings::default();
        self.save().or_else(|e| {
            log::error!(
                "{}",
                e.display_chain_with_msg("Unable to save default settings")
            );
            log::info!("Will attempt to remove settings file");
            fs::remove_file(&self.path)
                .map_err(|e| Error::DeleteError(self.path.display().to_string(), e))
        })
    }

    pub fn to_settings(&self) -> Settings {
        self.settings.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, account_token: Option<String>) -> Result<bool, Error> {
        let should_save = self.settings.set_account_token(account_token);
        self.update(should_save)
    }

    pub fn update_relay_settings(&mut self, update: RelaySettingsUpdate) -> Result<bool, Error> {
        let should_save = self.settings.update_relay_settings(update);
        self.update(should_save)
    }

    pub fn set_allow_lan(&mut self, allow_lan: bool) -> Result<bool, Error> {
        let should_save = Self::update_field(&mut self.settings.allow_lan, allow_lan);
        self.update(should_save)
    }

    pub fn set_block_when_disconnected(
        &mut self,
        block_when_disconnected: bool,
    ) -> Result<bool, Error> {
        let should_save = Self::update_field(
            &mut self.settings.block_when_disconnected,
            block_when_disconnected,
        );
        self.update(should_save)
    }

    pub fn set_auto_connect(&mut self, auto_connect: bool) -> Result<bool, Error> {
        let should_save = Self::update_field(&mut self.settings.auto_connect, auto_connect);
        self.update(should_save)
    }

    pub fn set_openvpn_mssfix(&mut self, openvpn_mssfix: Option<u16>) -> Result<bool, Error> {
        let should_save = Self::update_field(
            &mut self.settings.tunnel_options.openvpn.mssfix,
            openvpn_mssfix,
        );
        self.update(should_save)
    }

    pub fn set_enable_ipv6(&mut self, enable_ipv6: bool) -> Result<bool, Error> {
        let should_save = Self::update_field(
            &mut self.settings.tunnel_options.generic.enable_ipv6,
            enable_ipv6,
        );
        self.update(should_save)
    }

    pub fn set_wireguard_mtu(&mut self, mtu: Option<u16>) -> Result<bool, Error> {
        let should_save = Self::update_field(&mut self.settings.tunnel_options.wireguard.mtu, mtu);
        self.update(should_save)
    }

    pub fn set_wireguard_rotation_interval(
        &mut self,
        automatic_rotation: Option<u32>,
    ) -> Result<bool, Error> {
        let should_save = Self::update_field(
            &mut self.settings.tunnel_options.wireguard.automatic_rotation,
            automatic_rotation,
        );
        self.update(should_save)
    }

    pub fn set_show_beta_releases(&mut self, show_beta_releases: bool) -> Result<bool, Error> {
        let should_save =
            Self::update_field(&mut self.settings.show_beta_releases, show_beta_releases);
        self.update(should_save)
    }

    pub fn set_bridge_settings(&mut self, bridge_settings: BridgeSettings) -> Result<bool, Error> {
        let should_save = Self::update_field(&mut self.settings.bridge_settings, bridge_settings);
        self.update(should_save)
    }

    pub fn set_bridge_state(&mut self, bridge_state: BridgeState) -> Result<bool, Error> {
        let should_save = self.settings.set_bridge_state(bridge_state);
        self.update(should_save)
    }

    fn update_field<T: Eq>(field: &mut T, new_value: T) -> bool {
        if *field != new_value {
            *field = new_value;
            true
        } else {
            false
        }
    }

    fn update(&mut self, should_save: bool) -> Result<bool, Error> {
        if should_save {
            self.save().map(|_| true)
        } else {
            Ok(false)
        }
    }
}

impl Deref for SettingsPersister {
    type Target = Settings;

    fn deref(&self) -> &Self::Target {
        &self.settings
    }
}


#[cfg(windows)]
mod ffi {
    use std::fmt;
    use talpid_core::logging::windows::LogSink;

    #[derive(Debug)]
    #[allow(dead_code)]
    #[repr(u32)]
    pub enum WinUtilMigrationStatus {
        Success = 0,
        Aborted = 1,
        NothingToMigrate = 2,
        Failed = 3,
    }

    impl fmt::Display for WinUtilMigrationStatus {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            use WinUtilMigrationStatus::*;
            write!(
                f,
                "{}",
                match self {
                    Success => "Migration completed successfully",
                    Aborted => "Migration was aborted to avoid overwriting current settings",
                    NothingToMigrate => "Could not migrate settings - no backup present",
                    Failed => "Migration failed",
                }
            )
        }
    }

    impl Into<Result<(), super::LoadSettingsError>> for WinUtilMigrationStatus {
        fn into(self) -> Result<(), super::LoadSettingsError> {
            match self {
                WinUtilMigrationStatus::Success => Ok(()),
                val => Err(super::LoadSettingsError::WinMigrationError(val)),
            }
        }
    }

    #[allow(non_snake_case)]
    extern "system" {
        #[link_name = "WinUtil_MigrateAfterWindowsUpdate"]
        pub fn WinUtil_MigrateAfterWindowsUpdate(
            sink: Option<LogSink>,
            sink_context: *const u8,
        ) -> WinUtilMigrationStatus;
    }
}