-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathdefguard-client.rs
More file actions
525 lines (485 loc) · 20.4 KB
/
defguard-client.rs
File metadata and controls
525 lines (485 loc) · 20.4 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! defguard desktop client
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[cfg(target_os = "macos")]
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::{env, str::FromStr, sync::LazyLock};
#[cfg(unix)]
use defguard_client::set_perms;
#[cfg(windows)]
use defguard_client::utils::sync_connections;
use defguard_client::{
active_connections::close_all_connections,
app_config::AppConfig,
appstate::AppState,
commands::*,
database::{
handle_db_migrations,
models::{location_stats::LocationStats, tunnel::TunnelStats},
DB_POOL,
},
enterprise::provisioning::handle_client_initialization,
events::handle_deep_link,
periodic::run_periodic_tasks,
service,
tray::{configure_tray_icon, setup_tray},
utils::load_log_targets,
window_manager::*,
LOG_FILENAME, VERSION,
};
use log::{Level, LevelFilter};
use tauri::{async_runtime, AppHandle, Builder, Manager, RunEvent, WindowEvent};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_log::{Target, TargetKind};
#[macro_use]
extern crate log;
// For tauri logging plugin:
// if found in metadata target name it will ignore the log if it was below info level.
const LOGGING_TARGET_IGNORE_LIST: [&str; 5] = ["tauri", "sqlx", "hyper", "h2", "tower"];
static LOG_INCLUDES: LazyLock<Vec<String>> = LazyLock::new(load_log_targets);
async fn startup(app_handle: &AppHandle) {
debug!("Purging old stats from the database.");
if let Err(err) = LocationStats::purge(&*DB_POOL).await {
error!("Failed to purge location stats: {err}");
} else {
debug!("Old location stats have been purged successfully.");
}
if let Err(err) = TunnelStats::purge(&*DB_POOL).await {
error!("Failed to purge tunnel stats: {err}");
} else {
debug!("Old tunnel stats have been purged successfully.");
}
// Sync already active connections on windows.
// When windows is restarted, the app doesn't close the active connections
// and they are still running after the restart. We sync them here to
// reflect the real system's state.
// TODO: Find a way to intercept the shutdown event and close all connections
#[cfg(windows)]
{
match sync_connections(app_handle).await {
Ok(()) => {
info!(
"Synchronized application's active connections with the connections \
already open on the system, if there were any."
);
}
Err(err) => {
warn!(
"Failed to synchronize application's active connections with the connections \
already open on the system. \
The connections' state in the application may not reflect system's state. \
Reconnect manually to reset them. Error: {err}"
);
}
};
}
#[cfg(target_os = "macos")]
{
use defguard_client::{
apple::get_managers_for_tunnels_and_locations, utils::get_all_tunnels_locations,
};
let semaphore = Arc::new(AtomicBool::new(false));
let semaphore_clone = Arc::clone(&semaphore);
// Retrieve MTU from `AppConfig`.
let app_state = app_handle.state::<AppState>();
let mtu = app_state
.app_config
.lock()
.expect("failed to lock app state")
.mtu();
let handle = async_runtime::spawn(async move {
if let Err(err) = defguard_client::apple::sync_locations_and_tunnels(mtu).await {
error!("Failed to sync locations and tunnels: {err}");
}
semaphore_clone.store(true, Ordering::Release);
});
defguard_client::apple::spawn_runloop_and_wait_for(&semaphore);
let _ = handle.await;
let (tunnels, locations) = get_all_tunnels_locations().await;
let handle = app_handle.clone();
// Observer thread is blocking, so its better not to mess with the tauri runtime,
// hence std::thread::spawn.
std::thread::spawn(move || {
defguard_client::apple::observer_thread(get_managers_for_tunnels_and_locations(
&tunnels, &locations,
));
error!("VPN observer thread has exited unexpectedly, quitting the app.");
handle.exit(0);
});
let handle = app_handle.clone();
async_runtime::spawn(async move {
defguard_client::apple::connection_state_update_thread(&handle).await;
error!("Connection state update thread has exited unexpectedly, quitting the app.");
handle.exit(0);
});
}
// Run periodic tasks.
let periodic_tasks_handle = app_handle.clone();
async_runtime::spawn(async move {
run_periodic_tasks(&periodic_tasks_handle).await;
// One of the tasks exited, so something went wrong, quit the app
error!("One of the periodic tasks has stopped unexpectedly. Exiting the application.");
periodic_tasks_handle.exit(0);
});
debug!("Periodic tasks have been started.");
// Load tray menu after database initialization, so all instance and locations can be shown.
debug!(
"Re-generating tray menu to show all available instances and locations as we have \
connected to the database."
);
if let Err(err) = setup_tray(app_handle).await {
error!("Failed to setup system tray: {err}");
}
match configure_tray_icon(app_handle).await {
Ok(()) => info!("System tray configured."),
Err(err) => error!("Failed to configure system tray: {err}"),
}
debug!("Tray menu has been re-generated successfully.");
}
/// Open the appropriate window, either the old or the new UI, depending if there are locations.
#[cfg(not(target_os = "linux"))]
fn open_appropriate_window(app_handle: &AppHandle) {
let has_locations = async_runtime::block_on(has_non_service_locations());
if has_locations {
let _ = WindowManager::open_tray(app_handle);
} else {
let _ = WindowManager::open_full_view(app_handle);
}
}
fn main() {
let app = Builder::default()
.invoke_handler(tauri::generate_handler![
all_locations,
has_any_visible_locations,
save_device_config,
all_instances,
connect,
disconnect,
update_instance,
location_stats,
location_interface_details,
all_connections,
last_connection,
active_connection,
update_location_routing,
delete_instance,
parse_tunnel_config,
save_tunnel,
all_tunnels,
open_link,
tunnel_details,
update_tunnel,
delete_tunnel,
get_latest_app_version,
start_global_logwatcher,
stop_global_logwatcher,
command_get_app_config,
command_set_app_config,
get_provisioning_config,
get_platform_header,
get_posture_data,
set_location_mfa_method,
open_new_ui_window,
open_old_ui_window,
swap_to_new_ui,
swap_to_old_ui,
close_tray_window,
all_active_connections,
disconnect_locations,
])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let label = window.label();
if label == NEW_UI_WINDOW_ID || label == OLD_UI_WINDOW_ID {
#[cfg(not(target_os = "macos"))]
let _ = window.hide();
#[cfg(target_os = "macos")]
let _ = tauri::AppHandle::hide(window.app_handle());
api.prevent_close();
}
}
})
// Initialize plugins here, except for `tauri_plugin_log` which is handled in `setup()`.
// Single instance plugin should always be the first to register.
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
let is_deep_link = argv.iter().any(|a| a.starts_with("defguard://"));
// User tried to spawn second instance, mirror tray left click path.
if !is_deep_link {
#[cfg(target_os = "linux")]
let _ = WindowManager::open_full_view(app);
#[cfg(not(target_os = "linux"))]
{
open_appropriate_window(app);
}
}
}))
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_process::init())
.setup(|app| {
// Create Help menu on macOS.
// https://github.com/tauri-apps/tauri/issues/9371
#[cfg(target_os = "macos")]
{
use tauri_plugin_opener::OpenerExt;
const DOC_ITEM_ID: &str = "doc";
const REPORT_ITEM_ID: &str = "issue";
const DOC_URL: &str = "https://docs.defguard.net/using-defguard-for-end-users/desktop-client";
const REPORT_URL: &str = "https://github.com/DefGuard/client/issues/new?labels=bug&template=bug_report.md";
if let Some(menu) = app.menu() {
if let Some(help_submenu) = menu.get(tauri::menu::HELP_SUBMENU_ID) {
let report_item = tauri::menu::MenuItem::with_id(
app,
REPORT_ITEM_ID,
"Report an issue",
true,
None::<&str>,
)?;
let _ = help_submenu.as_submenu_unchecked().append(&report_item);
let doc_item = tauri::menu::MenuItem::with_id(
app,
DOC_ITEM_ID,
"Defguard Desktop Client Help",
true,
None::<&str>,
)?;
let _ = help_submenu.as_submenu_unchecked().append(&doc_item);
}
}
app.on_menu_event(move |app, event| {
let id = event.id();
if id == DOC_ITEM_ID {
let _ = app.opener().open_url(DOC_URL, None::<&str>);
} else if id == REPORT_ITEM_ID {
let _ = app.opener().open_url(REPORT_URL, None::<&str>);
}
});
app.set_dock_visibility(false);
}
// Register for Linux and debug Windows builds.
#[cfg(any(target_os = "linux", windows))]
{
use tauri_plugin_deep_link::DeepLinkExt;
app.deep_link().register_all()?;
}
let app_handle = app.app_handle();
// Single Rust-side entry point for all deep link events (runtime).
{
let handle = app_handle.clone();
app.deep_link().on_open_url(move |event| {
handle_deep_link(&handle, &event.urls());
});
}
// Prepare `AppConfig`.
let config = AppConfig::new(app_handle);
// Setup logging.
// If deriving from env value fails, use config default (env overrides config file).
let config_log_level = config.log_level;
let log_level = match &env::var("DEFGUARD_CLIENT_LOG_LEVEL") {
Ok(env_value) => LevelFilter::from_str(env_value).unwrap_or(config_log_level),
Err(_) => config_log_level,
};
app_handle.plugin(
tauri_plugin_log::Builder::new()
.format(move |out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
tauri_plugin_log::TimezoneStrategy::UseUtc
.get_now()
// Sets the time format. Service's logs have a subsecond part, so we
// also need to include it here, otherwise the logs couldn't be sorted
// correctly when displayed together in the UI.
.format(&time::macros::format_description!(
"[[[year]-[month]-[day]][[[hour]:[minute]:[second].[subsecond]]"
))
.unwrap(),
record.level(),
record.target(),
message
));
})
.targets([
Target::new(TargetKind::Stdout),
Target::new(TargetKind::LogDir { file_name: Some(LOG_FILENAME.to_string()) }),
])
.level(log_level)
.filter(|metadata| {
if metadata.level() == Level::Error {
return true;
}
if !LOG_INCLUDES.is_empty() {
for target in &*LOG_INCLUDES {
if metadata.target().contains(target) {
return true;
}
}
return false;
}
true
})
.filter(|metadata| {
// Log all errors, warnings and infos.
let level = metadata.level();
if level == LevelFilter::Error
|| level == LevelFilter::Warn
|| level == LevelFilter::Info
{
return true;
}
// Otherwise do not log these targets.
for target in &LOGGING_TARGET_IGNORE_LIST {
if metadata.target().contains(target) {
return false;
}
}
true
})
.build(),
)?;
// run DB migrations
async_runtime::block_on(handle_db_migrations());
// Check if client needs to be initialized
// and try to load provisioning config if necessary
let provisioning_config =
async_runtime::block_on(handle_client_initialization(app_handle));
let state = AppState::new(config, provisioning_config);
app.manage(state);
// Pre-build both windows hidden so they can be shown/hidden without recreation.
if let Err(e) = WindowManager::build_tray_window(app_handle) {
warn!("Failed to pre-build tray window: {e}");
}
if let Err(e) = WindowManager::build_full_window(app_handle) {
warn!("Failed to pre-build full window: {e}");
}
// Decide which window to show based on platform and available locations.
#[cfg(target_os = "linux")]
{
let _ = WindowManager::open_full_view(app_handle);
}
#[cfg(not(target_os = "linux"))]
{
// If the app was cold-launched by a deep-link, the full view must open, not the
// tray.
let launched_by_deep_link = app_handle
.deep_link()
.get_current()
.ok()
.flatten()
.is_some();
if launched_by_deep_link {
info!("App launched via deep link, opening full view directly.");
let _ = WindowManager::open_full_view(app_handle);
} else {
open_appropriate_window(app_handle);
}
}
info!("App setup completed, log level: {log_level}");
Ok(())
})
.build(tauri::generate_context!())
.expect("Failed to build Tauri application");
info!("Starting Defguard client version {VERSION}");
// Run application.
debug!("Starting the main application event loop.");
app.run(|app_handle, event| match event {
// Startup tasks
RunEvent::Ready => {
let data_dir = app_handle
.path()
.app_data_dir()
.unwrap_or_else(|_| "UNDEFINED DATA DIRECTORY".into());
let log_dir = app_handle
.path()
.app_log_dir()
.unwrap_or_else(|_| "UNDEFINED LOG DIRECTORY".into());
// Ensure directories have appropriate permissions (dg25-28).
#[cfg(unix)]
{
set_perms(&data_dir);
set_perms(&log_dir);
}
info!(
"Application data (database file) will be stored in: {} and application logs in: \
{}. Logs of the background Defguard service responsible for managing VPN \
connections at the network level will be stored in: {}.",
data_dir.display(),
log_dir.display(),
service::config::DEFAULT_LOG_DIR
);
async_runtime::block_on(startup(app_handle));
// Handle a deep link that launched the app (startup case).
if let Ok(Some(urls)) = app_handle.deep_link().get_current() {
handle_deep_link(app_handle, &urls);
}
// Handle Ctrl-C.
debug!("Setting up Ctrl-C handler.");
let app_handle_clone = app_handle.clone();
async_runtime::spawn(async move {
tokio::signal::ctrl_c()
.await
.expect("Signal handler failure");
debug!("Ctrl-C handler: quitting the app");
app_handle_clone.exit(0);
});
debug!("Ctrl-C handler has been set up successfully");
}
RunEvent::ExitRequested { code, api, .. } => {
debug!("Received exit request");
// `code` is `None` when the exit is requested by user interaction.
if code.is_none() {
// Prevent shutdown on window close.
api.prevent_exit();
}
}
// Handle shutdown.
RunEvent::Exit => {
debug!("Exiting the application's main event loop.");
#[cfg(target_os = "macos")]
{
let semaphore = Arc::new(AtomicBool::new(false));
let semaphore_clone = Arc::clone(&semaphore);
let handle = async_runtime::spawn(async move {
let _ = close_all_connections().await;
// This will clean the database file, pruning write-ahead log.
DB_POOL.close().await;
semaphore_clone.store(true, Ordering::Release);
});
// Obj-C API needs a runtime, but at this point Tauri has closed its runtime, so
// create a temporary one.
defguard_client::apple::spawn_runloop_and_wait_for(&semaphore);
async_runtime::block_on(async move {
let _ = handle.await;
});
}
#[cfg(not(target_os = "macos"))]
{
async_runtime::block_on(async move {
let _ = close_all_connections().await;
// This will clean the database file, pruning write-ahead log.
DB_POOL.close().await;
});
}
}
#[cfg(target_os = "macos")]
RunEvent::Reopen {
has_visible_windows,
..
} => {
if !has_visible_windows {
open_appropriate_window(app_handle);
}
}
_ => {
trace!("Received event: {event:?}");
}
});
}