-
Notifications
You must be signed in to change notification settings - Fork 384
/
Copy pathformat.rs
331 lines (310 loc) · 12.2 KB
/
format.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
use std::collections::HashMap;
use itertools::Itertools;
use mullvad_types::{
auth_failed::AuthFailed, features::FeatureIndicators, location::GeoIpLocation,
states::TunnelState,
};
use talpid_types::{
net::{Endpoint, TunnelEndpoint},
tunnel::{ActionAfterDisconnect, ErrorState},
};
#[macro_export]
macro_rules! print_option {
($value:expr_2021 $(,)?) => {{
println!("{:<4}{:<24}{}", "", "", $value,)
}};
($option:literal, $value:expr_2021 $(,)?) => {{
println!("{:<4}{:<24}{}", "", concat!($option, ":"), $value,)
}};
($option:expr_2021, $value:expr_2021 $(,)?) => {{
println!("{:<4}{:<24}{}", "", format!("{}:", $option), $value,)
}};
}
pub fn print_state(state: &TunnelState, previous_state: Option<&TunnelState>, verbose: bool) {
use TunnelState::*;
// When we enter the connected or disconnected state, am.i.mullvad.net will
// be polled to get exit location. When it arrives, we will get another
// tunnel state of the same enum type, but with the location filled in. This
// match statement checks if the new state is an updated version of the old
// one and if so skips the print to avoid spamming the user. Note that for
// graphical frontends updating the drawn state with an identical one is
// invisible, so this is only an issue for the CLI.
match state {
Disconnected {
location,
locked_down,
} => {
let old_location = match previous_state {
Some(Disconnected {
location,
locked_down: was_locked_down,
}) => {
if *locked_down && !was_locked_down {
print_option!("Internet access is blocked due to lockdown mode");
} else if !*locked_down && *was_locked_down {
print_option!("Internet access is no longer blocked due to lockdown mode");
}
location
}
_ => {
println!("Disconnected");
if *locked_down {
print_option!("Internet access is blocked due to lockdown mode");
}
&None
}
};
let location_fmt = location.as_ref().map(format_location).unwrap_or_default();
let old_location_fmt = old_location
.as_ref()
.map(format_location)
.unwrap_or_default();
if location_fmt != old_location_fmt {
print_option!("Visible location", location_fmt);
}
}
Connecting {
endpoint,
location,
feature_indicators,
} => {
let (old_endpoint, old_location, old_feature_indicators) = match previous_state {
Some(Connecting {
endpoint,
location,
feature_indicators,
}) => {
if verbose {
println!("Connecting")
}
(Some(endpoint), location, Some(feature_indicators))
}
_ => {
println!("Connecting");
(None, &None, None)
}
};
print_connection_info(
endpoint,
old_endpoint,
location.as_ref(),
old_location.as_ref(),
feature_indicators,
old_feature_indicators,
verbose,
);
}
Connected {
endpoint,
location,
feature_indicators,
} => {
let (old_endpoint, old_location, old_feature_indicators) = match previous_state {
Some(Connected {
endpoint,
location,
feature_indicators,
}) => {
if verbose {
println!("Connected")
}
(Some(endpoint), location, Some(feature_indicators))
}
Some(Connecting {
endpoint,
location,
feature_indicators,
}) => {
println!("Connected");
(Some(endpoint), location, Some(feature_indicators))
}
_ => {
println!("Connected");
(None, &None, None)
}
};
print_connection_info(
endpoint,
old_endpoint,
location.as_ref(),
old_location.as_ref(),
feature_indicators,
old_feature_indicators,
verbose,
);
}
Disconnecting(ActionAfterDisconnect::Reconnect) => {}
Disconnecting(_) => println!("Disconnecting"),
Error(e) => print_error_state(e),
}
}
fn connection_information(
endpoint: Option<&TunnelEndpoint>,
location: Option<&GeoIpLocation>,
feature_indicators: Option<&FeatureIndicators>,
verbose: bool,
) -> HashMap<&'static str, Option<String>> {
let mut info: HashMap<&'static str, Option<String>> = HashMap::new();
let endpoint_fmt =
endpoint.map(|endpoint| format_relay_connection(endpoint, location, verbose));
info.insert("Relay", endpoint_fmt);
let tunnel_interface_fmt = endpoint
.filter(|_| verbose)
.and_then(|endpoint| endpoint.tunnel_interface.clone());
info.insert("Tunnel interface", tunnel_interface_fmt);
let bridge_type_fmt = endpoint
.filter(|_| verbose)
.and_then(|endpoint| endpoint.proxy)
.map(|bridge| bridge.proxy_type.to_string());
info.insert("Bridge type", bridge_type_fmt);
let tunnel_type_fmt = endpoint
.filter(|_| verbose)
.map(|endpoint| endpoint.tunnel_type.to_string());
info.insert("Tunnel type", tunnel_type_fmt);
info.insert("Visible location", location.map(format_location));
let features_fmt = feature_indicators
.filter(|f| !f.is_empty())
.map(ToString::to_string);
info.insert("Features", features_fmt);
info
}
fn print_connection_info(
endpoint: &TunnelEndpoint,
old_endpoint: Option<&TunnelEndpoint>,
location: Option<&GeoIpLocation>,
old_location: Option<&GeoIpLocation>,
feature_indicators: &FeatureIndicators,
old_feature_indicators: Option<&FeatureIndicators>,
verbose: bool,
) {
let current_info =
connection_information(Some(endpoint), location, Some(feature_indicators), verbose);
let previous_info =
connection_information(old_endpoint, old_location, old_feature_indicators, verbose);
for (name, value) in current_info
.into_iter()
// Hack that puts important items first, e.g. "Relay"
.sorted_by_key(|(name, _)| ( name.len(), name.to_owned() ))
{
let previous_value = previous_info.get(name).and_then(|i| i.clone());
match (value, previous_value) {
(Some(value), None) => print_option!(name, value),
(Some(value), Some(previous_value)) if (value != previous_value) => {
print_option!(format!("{name} (new)"), value)
}
(Some(value), Some(_)) if verbose => print_option!(name, value),
(None, None) if verbose => print_option!(name, "None"),
(None, Some(_)) => print_option!(format!("{name} (new)"), "None"),
_ => {}
}
}
}
pub fn format_location(location: &GeoIpLocation) -> String {
let mut formatted_location = location.country.to_string();
if let Some(city) = &location.city {
formatted_location.push_str(&format!(", {}", city));
}
if let Some(ipv4) = location.ipv4 {
formatted_location.push_str(&format!(". IPv4: {}", ipv4));
}
if let Some(ipv6) = location.ipv6 {
formatted_location.push_str(&format!(", IPv6: {}", ipv6));
}
formatted_location
}
fn format_relay_connection(
endpoint: &TunnelEndpoint,
location: Option<&GeoIpLocation>,
verbose: bool,
) -> String {
let first_hop = endpoint.entry_endpoint.as_ref().map(|entry| {
let endpoint = format_endpoint(
location.and_then(|l| l.entry_hostname.as_deref()),
// Check if we *actually* want to print an obfuscator endpoint ..
match endpoint.obfuscation {
Some(ref obfuscation) => &obfuscation.endpoint,
_ => entry,
},
verbose,
);
format!(" via {endpoint}")
});
let bridge = endpoint.proxy.as_ref().map(|proxy| {
let proxy_endpoint = format_endpoint(
location.and_then(|l| l.bridge_hostname.as_deref()),
&proxy.endpoint,
verbose,
);
format!(" via {proxy_endpoint}")
});
let exit_endpoint = format_endpoint(
location.and_then(|l| l.hostname.as_deref()),
// Check if we *actually* want to print an obfuscator endpoint ..
// The obfuscator information should be printed for the exit relay if multihop is disabled
match (endpoint.obfuscation, &first_hop) {
(Some(ref obfuscation), None) => &obfuscation.endpoint,
_ => &endpoint.endpoint,
},
verbose,
);
format!(
"{exit_endpoint}{first_hop}{bridge}",
first_hop = first_hop.unwrap_or_default(),
bridge = bridge.unwrap_or_default(),
)
}
fn format_endpoint(hostname: Option<&str>, endpoint: &Endpoint, verbose: bool) -> String {
match (hostname, verbose) {
(Some(hostname), true) => format!("{hostname} ({endpoint})"),
(None, true) => endpoint.to_string(),
(Some(hostname), false) => hostname.to_string(),
(None, false) => endpoint.address.to_string(),
}
}
fn print_error_state(error_state: &ErrorState) {
if error_state.block_failure().is_some() {
eprintln!("Mullvad daemon failed to setup firewall rules!");
eprintln!("Daemon cannot block traffic from flowing, non-local traffic will leak");
}
match error_state.cause() {
#[cfg(target_os = "linux")]
cause @ talpid_types::tunnel::ErrorStateCause::SetFirewallPolicyError(_) => {
println!("Blocked: {cause}");
println!("Your kernel might be terribly out of date or missing nftables");
}
#[cfg(target_os = "macos")]
cause @ talpid_types::tunnel::ErrorStateCause::NeedFullDiskPermissions => {
println!("Blocked: {cause}");
println!();
println!(
r#"Enable "Full Disk Access" for "Mullvad VPN" in the macOS system settings:"#
);
println!(
r#"open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles""#
);
println!();
println!("Restart the Mullvad daemon for the change to take effect:");
println!("launchctl unload -w /Library/LaunchDaemons/net.mullvad.daemon.plist");
println!("launchctl load -w /Library/LaunchDaemons/net.mullvad.daemon.plist");
}
talpid_types::tunnel::ErrorStateCause::AuthFailed(Some(auth_failed)) => {
println!(
"Blocked: Authentication with remote server failed: {}",
get_auth_failed_message(AuthFailed::from(auth_failed.as_str()))
);
}
cause => println!("Blocked: {cause}"),
}
}
const fn get_auth_failed_message(auth_failed: AuthFailed) -> &'static str {
const INVALID_ACCOUNT_MSG: &str = "You've logged in with an account number that is not valid. Please log out and try another one.";
const EXPIRED_ACCOUNT_MSG: &str = "You have no more VPN time left on this account. Please log in on our website to buy more credit.";
const TOO_MANY_CONNECTIONS_MSG: &str = "This account has too many simultaneous connections. Disconnect another device or try connecting again shortly.";
const UNKNOWN_MSG: &str = "Unknown error.";
match auth_failed {
AuthFailed::InvalidAccount => INVALID_ACCOUNT_MSG,
AuthFailed::ExpiredAccount => EXPIRED_ACCOUNT_MSG,
AuthFailed::TooManyConnections => TOO_MANY_CONNECTIONS_MSG,
AuthFailed::Unknown => UNKNOWN_MSG,
}
}