-
Notifications
You must be signed in to change notification settings - Fork 389
/
Copy pathmain.rs
199 lines (168 loc) · 6.34 KB
/
main.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
use clap::Parser;
use mullvad_api::{self, proxy::ApiConnectionMode, DEVICE_NOT_FOUND};
use mullvad_management_interface::MullvadProxyClient;
use mullvad_types::version::ParsedAppVersion;
use once_cell::sync::Lazy;
use std::{path::PathBuf, process, str::FromStr, time::Duration};
use talpid_core::{
firewall::{self, Firewall},
future_retry::{retry_future, ConstantInterval},
};
use talpid_types::ErrorExt;
static APP_VERSION: Lazy<ParsedAppVersion> =
Lazy::new(|| ParsedAppVersion::from_str(mullvad_version::VERSION).unwrap());
const DEVICE_REMOVAL_STRATEGY: ConstantInterval = ConstantInterval::new(Duration::ZERO, Some(5));
#[repr(i32)]
enum ExitStatus {
Ok = 0,
Error = 1,
VersionNotOlder = 2,
DaemonNotRunning = 3,
}
impl From<Error> for ExitStatus {
fn from(error: Error) -> ExitStatus {
match error {
Error::RpcConnectionError(_) => ExitStatus::DaemonNotRunning,
_ => ExitStatus::Error,
}
}
}
#[derive(err_derive::Error, Debug)]
#[error(no_from)]
pub enum Error {
#[error(display = "Failed to connect to RPC client")]
RpcConnectionError(#[error(source)] mullvad_management_interface::Error),
#[error(display = "RPC call failed")]
DaemonRpcError(#[error(source)] mullvad_management_interface::Error),
#[error(display = "This command cannot be run if the daemon is active")]
DaemonIsRunning,
#[error(display = "Firewall error")]
FirewallError(#[error(source)] firewall::Error),
#[error(display = "Failed to initialize mullvad RPC runtime")]
RpcInitializationError(#[error(source)] mullvad_api::Error),
#[error(display = "Failed to remove device from account")]
RemoveDeviceError(#[error(source)] mullvad_api::rest::Error),
#[error(display = "Failed to obtain settings directory path")]
SettingsPathError(#[error(source)] mullvad_paths::Error),
#[error(display = "Failed to obtain cache directory path")]
CachePathError(#[error(source)] mullvad_paths::Error),
#[error(display = "Failed to read the device cache")]
ReadDeviceCacheError(#[error(source)] mullvad_daemon::device::Error),
#[error(display = "Failed to write the device cache")]
WriteDeviceCacheError(#[error(source)] mullvad_daemon::device::Error),
#[error(display = "Cannot parse the version string")]
ParseVersionStringError,
}
#[derive(Debug, Parser)]
#[command(author, version = mullvad_version::VERSION, about, long_about = None)]
#[command(propagate_version = true)]
#[command(
arg_required_else_help = true,
disable_help_subcommand = true,
disable_version_flag = true
)]
enum Cli {
/// Move a running daemon into a blocking state and save its target state
PrepareRestart,
/// Remove any firewall rules introduced by the daemon
ResetFirewall,
/// Remove the current device from the active account
RemoveDevice,
/// Checks whether the given version is older than the current version
IsOlderVersion {
/// Version string to compare the current version
#[arg(required = true)]
old_version: String,
},
}
#[tokio::main]
async fn main() {
env_logger::init();
let result = match Cli::parse() {
Cli::PrepareRestart => prepare_restart().await,
Cli::ResetFirewall => reset_firewall().await,
Cli::RemoveDevice => remove_device().await,
Cli::IsOlderVersion { old_version } => {
match is_older_version(&old_version) {
// Returning exit status
Ok(status) => process::exit(status as i32),
Err(error) => Err(error),
}
}
};
if let Err(e) = result {
eprintln!("{}", e.display_chain());
process::exit(ExitStatus::from(e) as i32);
}
}
fn is_older_version(old_version: &str) -> Result<ExitStatus, Error> {
let parsed_version =
ParsedAppVersion::from_str(old_version).map_err(|_| Error::ParseVersionStringError)?;
Ok(if parsed_version < *APP_VERSION {
ExitStatus::Ok
} else {
ExitStatus::VersionNotOlder
})
}
async fn prepare_restart() -> Result<(), Error> {
let mut rpc = MullvadProxyClient::new()
.await
.map_err(Error::RpcConnectionError)?;
rpc.prepare_restart().await.map_err(Error::DaemonRpcError)?;
Ok(())
}
async fn reset_firewall() -> Result<(), Error> {
// Ensure that the daemon isn't running
if MullvadProxyClient::new().await.is_ok() {
return Err(Error::DaemonIsRunning);
}
Firewall::new(
#[cfg(target_os = "linux")]
mullvad_types::TUNNEL_FWMARK,
)
.map_err(Error::FirewallError)?
.reset_policy()
.map_err(Error::FirewallError)
}
async fn remove_device() -> Result<(), Error> {
let (cache_path, settings_path) = get_paths()?;
let (cacher, state) = mullvad_daemon::device::DeviceCacher::new(&settings_path)
.await
.map_err(Error::ReadDeviceCacheError)?;
if let Some(device) = state.into_device() {
let api_runtime = mullvad_api::Runtime::with_cache(&cache_path, false)
.await
.map_err(Error::RpcInitializationError)?;
let connection_mode = ApiConnectionMode::try_from_cache(&cache_path).await;
let proxy = mullvad_api::DevicesProxy::new(
api_runtime.mullvad_rest_handle(connection_mode.clone(), connection_mode.into_repeat()),
);
let device_removal = retry_future(
move || proxy.remove(device.account_token.clone(), device.device.id.clone()),
move |result| match result {
Err(error) => error.is_network_error(),
_ => false,
},
DEVICE_REMOVAL_STRATEGY,
)
.await;
// `DEVICE_NOT_FOUND` is not considered to be an error in this context.
match device_removal {
Ok(_) => Ok(()),
Err(mullvad_api::rest::Error::ApiError(_status, code)) if code == DEVICE_NOT_FOUND => {
Ok(())
}
Err(e) => Err(Error::RemoveDeviceError(e)),
}?;
cacher
.remove()
.await
.map_err(Error::WriteDeviceCacheError)?;
}
Ok(())
}
fn get_paths() -> Result<(PathBuf, PathBuf), Error> {
let cache_path = mullvad_paths::cache_dir().map_err(Error::CachePathError)?;
let settings_path = mullvad_paths::settings_dir().map_err(Error::SettingsPathError)?;
Ok((cache_path, settings_path))
}