-
Notifications
You must be signed in to change notification settings - Fork 381
/
Copy pathlib.rs
3210 lines (2930 loc) · 121 KB
/
lib.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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit = "512"]
#![allow(rustdoc::private_intra_doc_links)]
mod access_method;
pub mod account_history;
mod android_dns;
mod api;
mod api_address_updater;
#[cfg(not(target_os = "android"))]
mod cleanup;
mod custom_list;
pub mod device;
mod dns;
pub mod exception_logging;
mod geoip;
mod leak_checker;
pub mod logging;
#[cfg(target_os = "macos")]
mod macos;
pub mod management_interface;
mod migrations;
mod relay_list;
#[cfg(not(target_os = "android"))]
pub mod rpc_uniqueness_check;
pub mod runtime;
pub mod settings;
pub mod shutdown;
mod target_state;
mod tunnel;
pub mod version;
mod version_check;
use crate::target_state::PersistentTargetState;
use api::AllowedClientsSelector;
use device::{AccountEvent, PrivateAccountAndDevice, PrivateDeviceEvent};
use futures::{
channel::{mpsc, oneshot},
future::{abortable, AbortHandle, Future},
StreamExt,
};
use geoip::GeoIpHandler;
use leak_checker::{LeakChecker, LeakInfo};
use management_interface::ManagementInterfaceServer;
use mullvad_api::ApiEndpoint;
use mullvad_api::{api::AccessMethodEvent, proxy::AllowedClientsProvider};
use mullvad_relay_selector::{RelaySelector, SelectorConfig};
#[cfg(target_os = "android")]
use mullvad_types::account::{PlayPurchase, PlayPurchasePaymentToken};
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
use mullvad_types::settings::SplitApp;
#[cfg(daita)]
use mullvad_types::wireguard::DaitaSettings;
use mullvad_types::{
access_method::{AccessMethod, AccessMethodSetting},
account::{AccountData, AccountNumber, VoucherSubmission},
auth_failed::AuthFailed,
custom_list::CustomList,
device::{Device, DeviceEvent, DeviceEventCause, DeviceId, DeviceState, RemoveDeviceEvent},
features::{compute_feature_indicators, FeatureIndicator, FeatureIndicators},
location::{GeoIpLocation, LocationEventData},
relay_constraints::{
BridgeSettings, BridgeState, BridgeType, ObfuscationSettings, RelayOverride, RelaySettings,
},
relay_list::RelayList,
settings::{DnsOptions, Settings},
states::{Secured, TargetState, TargetStateStrict, TunnelState},
version::{AppVersion, AppVersionInfo},
wireguard::{PublicKey, QuantumResistantState, RotationInterval},
};
use relay_list::{RelayListUpdater, RelayListUpdaterHandle, RELAYS_FILENAME};
use settings::SettingsPersister;
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
use std::collections::HashSet;
#[cfg(target_os = "android")]
use std::os::unix::io::RawFd;
use std::{
marker::PhantomData,
path::PathBuf,
pin::Pin,
sync::{Arc, Weak},
time::Duration,
};
use talpid_core::{
mpsc::Sender,
split_tunnel,
tunnel_state_machine::{self, TunnelCommand, TunnelStateMachineHandle},
};
use talpid_routing::RouteManagerHandle;
#[cfg(target_os = "android")]
use talpid_types::android::AndroidContext;
#[cfg(target_os = "windows")]
use talpid_types::split_tunnel::ExcludedProcess;
use talpid_types::{
net::{IpVersion, TunnelType},
tunnel::{ErrorStateCause, TunnelStateTransition},
ErrorExt,
};
use tokio::io;
#[cfg(target_os = "android")]
use talpid_core::connectivity_listener::ConnectivityListener;
/// Delay between generating a new WireGuard key and reconnecting
const WG_RECONNECT_DELAY: Duration = Duration::from_secs(4 * 60);
pub type ResponseTx<T, E> = oneshot::Sender<Result<T, E>>;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Failed to send command to daemon because it is not running")]
DaemonUnavailable,
#[error("Unable to initialize network event loop")]
InitIoEventLoop(#[source] io::Error),
#[error("Unable to create RPC client")]
InitRpcFactory(#[source] mullvad_api::Error),
#[error("REST request failed")]
RestError(#[source] mullvad_api::rest::Error),
#[error("Management interface error")]
ManagementInterfaceError(#[source] management_interface::Error),
#[error("API availability check failed")]
ApiCheckError(#[source] mullvad_api::availability::Error),
#[error("Version check failed")]
VersionCheckError(#[source] version_check::Error),
#[error("Unable to load account history")]
LoadAccountHistory(#[source] account_history::Error),
#[error("Failed to start account manager")]
LoadAccountManager(#[source] device::Error),
#[error("Failed to log in to account")]
LoginError(#[source] device::Error),
#[error("Failed to log out of account")]
LogoutError(#[source] device::Error),
#[error("Failed to rotate WireGuard key")]
KeyRotationError(#[source] device::Error),
#[error("Failed to list devices")]
ListDevicesError(#[source] device::Error),
#[error("Failed to remove device")]
RemoveDeviceError(#[source] device::Error),
#[error("Failed to update device")]
UpdateDeviceError(#[source] device::Error),
#[error("Failed to submit voucher")]
VoucherSubmission(#[source] device::Error),
#[cfg(target_os = "linux")]
#[error("Unable to initialize split tunneling")]
InitSplitTunneling(#[source] split_tunnel::Error),
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
#[error("Split tunneling error")]
SplitTunnelError(#[source] split_tunnel::Error),
#[error("An account is already set")]
AlreadyLoggedIn,
#[error("No account number is set")]
NoAccountNumber,
#[error("No account history available for the token")]
NoAccountNumberHistory,
#[error("Settings error")]
SettingsError(#[source] settings::Error),
#[error("Account history error")]
AccountHistory(#[source] account_history::Error),
#[cfg(not(target_os = "android"))]
#[error("Factory reset partially failed: {0}")]
FactoryResetError(&'static str),
#[error("Tunnel state machine error")]
TunnelError(#[source] tunnel_state_machine::Error),
/// Errors from [talpid_routing::RouteManagerHandle].
#[error("Route manager error")]
RouteManager(#[source] talpid_routing::Error),
/// Custom list already exists
#[error("Custom list error: {0}")]
CustomListError(#[source] mullvad_types::custom_list::Error),
#[error("Access method error")]
AccessMethodError(#[source] access_method::Error),
#[error("API connection mode error")]
ApiConnectionModeError(#[source] mullvad_api::api::Error),
#[error("No custom bridge has been specified")]
NoCustomProxySaved,
#[cfg(target_os = "macos")]
#[error("Failed to set exclusion group")]
GroupIdError(#[source] io::Error),
#[cfg(target_os = "android")]
#[error("Failed to initialize play purchase")]
InitPlayPurchase(#[source] device::Error),
#[cfg(target_os = "android")]
#[error("Failed to verify play purchase")]
VerifyPlayPurchase(#[source] device::Error),
}
/// Enum representing commands that can be sent to the daemon.
pub enum DaemonCommand {
/// Set target state. Does nothing if the daemon already has the state that is being set.
SetTargetState(oneshot::Sender<bool>, TargetState),
/// Reconnect the tunnel, if one is connecting/connected.
Reconnect(oneshot::Sender<bool>),
/// Request the current state.
GetState(oneshot::Sender<TunnelState>),
CreateNewAccount(ResponseTx<String, Error>),
/// Request the metadata for an account.
GetAccountData(
ResponseTx<AccountData, mullvad_api::rest::Error>,
AccountNumber,
),
/// Request www auth token for an account
GetWwwAuthToken(ResponseTx<String, Error>),
/// Submit voucher to add time to the current account. Returns time added in seconds
SubmitVoucher(ResponseTx<VoucherSubmission, Error>, String),
/// Request account history
GetAccountHistory(oneshot::Sender<Option<AccountNumber>>),
/// Remove the last used account, if there is one
ClearAccountHistory(ResponseTx<(), Error>),
/// Get the list of countries and cities where there are relays.
GetRelayLocations(oneshot::Sender<RelayList>),
/// Trigger an asynchronous relay list update. This returns before the relay list is actually
/// updated.
UpdateRelayLocations,
/// Log in with a given account and create a new device.
LoginAccount(ResponseTx<(), Error>, AccountNumber),
/// Log out of the current account and remove the device, if they exist.
LogoutAccount(ResponseTx<(), Error>),
/// Return the current device configuration.
GetDevice(ResponseTx<DeviceState, Error>),
/// Update/check the current device, if there is one.
UpdateDevice(ResponseTx<(), Error>),
/// Return all the devices for a given account number.
ListDevices(ResponseTx<Vec<Device>, Error>, AccountNumber),
/// Remove device from a given account.
RemoveDevice(ResponseTx<(), Error>, AccountNumber, DeviceId),
/// Place constraints on the type of tunnel and relay
SetRelaySettings(ResponseTx<(), settings::Error>, RelaySettings),
/// Set the allow LAN setting.
SetAllowLan(ResponseTx<(), settings::Error>, bool),
/// Set the beta program setting.
SetShowBetaReleases(ResponseTx<(), settings::Error>, bool),
/// Set the block_when_disconnected setting.
#[cfg(not(target_os = "android"))]
SetBlockWhenDisconnected(ResponseTx<(), settings::Error>, bool),
/// Set the auto-connect setting.
SetAutoConnect(ResponseTx<(), settings::Error>, bool),
/// Set the mssfix argument for OpenVPN
SetOpenVpnMssfix(ResponseTx<(), settings::Error>, Option<u16>),
/// Set proxy details for OpenVPN
SetBridgeSettings(ResponseTx<(), Error>, BridgeSettings),
/// Set proxy state
SetBridgeState(ResponseTx<(), settings::Error>, BridgeState),
/// Set if IPv6 should be enabled in the tunnel
SetEnableIpv6(ResponseTx<(), settings::Error>, bool),
/// Set whether to enable PQ PSK exchange in the tunnel
SetQuantumResistantTunnel(ResponseTx<(), settings::Error>, QuantumResistantState),
/// Set DAITA settings for the tunnel
#[cfg(daita)]
SetEnableDaita(ResponseTx<(), settings::Error>, bool),
#[cfg(daita)]
SetDaitaUseMultihopIfNecessary(ResponseTx<(), settings::Error>, bool),
#[cfg(daita)]
SetDaitaSettings(ResponseTx<(), settings::Error>, DaitaSettings),
/// Set DNS options or servers to use
SetDnsOptions(ResponseTx<(), settings::Error>, DnsOptions),
/// Set override options to use for a given relay
SetRelayOverride(ResponseTx<(), settings::Error>, RelayOverride),
/// Remove all relay override options
ClearAllRelayOverrides(ResponseTx<(), settings::Error>),
/// Toggle macOS network check leak
/// Set MTU for wireguard tunnels
SetWireguardMtu(ResponseTx<(), settings::Error>, Option<u16>),
/// Set automatic key rotation interval for wireguard tunnels
SetWireguardRotationInterval(ResponseTx<(), settings::Error>, Option<RotationInterval>),
/// Get the daemon settings
GetSettings(oneshot::Sender<Settings>),
/// Reset all daemon settings to the defaults
ResetSettings(ResponseTx<(), settings::Error>),
/// Generate new wireguard key
RotateWireguardKey(ResponseTx<(), Error>),
/// Return a public key of the currently set wireguard private key, if there is one
GetWireguardKey(ResponseTx<Option<PublicKey>, Error>),
/// Create custom list
CreateCustomList(ResponseTx<mullvad_types::custom_list::Id, Error>, String),
/// Delete custom list
DeleteCustomList(ResponseTx<(), Error>, mullvad_types::custom_list::Id),
/// Update a custom list with a given id
UpdateCustomList(ResponseTx<(), Error>, CustomList),
/// Remove all custom lists
ClearCustomLists(ResponseTx<(), Error>),
/// Add API access methods
AddApiAccessMethod(
ResponseTx<mullvad_types::access_method::Id, Error>,
String,
bool,
AccessMethod,
),
/// Remove an API access method
RemoveApiAccessMethod(ResponseTx<(), Error>, mullvad_types::access_method::Id),
/// Set the API access method to use
SetApiAccessMethod(ResponseTx<(), Error>, mullvad_types::access_method::Id),
/// Edit an API access method
UpdateApiAccessMethod(ResponseTx<(), Error>, AccessMethodSetting),
/// Remove all custom API access methods
ClearCustomApiAccessMethods(ResponseTx<(), Error>),
/// Get the currently used API access method
GetCurrentAccessMethod(ResponseTx<AccessMethodSetting, Error>),
/// Test an API access method
TestApiAccessMethodById(ResponseTx<bool, Error>, mullvad_types::access_method::Id),
/// Test a custom API access method
TestCustomApiAccessMethod(
ResponseTx<bool, Error>,
talpid_types::net::proxy::CustomProxy,
),
/// Get information about the currently running and latest app versions
GetVersionInfo(oneshot::Sender<Result<AppVersionInfo, Error>>),
/// Return whether the daemon is performing post-upgrade tasks
IsPerformingPostUpgrade(oneshot::Sender<bool>),
/// Get current version of the app
GetCurrentVersion(oneshot::Sender<AppVersion>),
/// Remove settings and clear the cache
#[cfg(not(target_os = "android"))]
FactoryReset(ResponseTx<(), Error>),
/// Request list of processes excluded from the tunnel
#[cfg(target_os = "linux")]
GetSplitTunnelProcesses(ResponseTx<Vec<i32>, split_tunnel::Error>),
/// Exclude traffic of a process (PID) from the tunnel
#[cfg(target_os = "linux")]
AddSplitTunnelProcess(ResponseTx<(), split_tunnel::Error>, i32),
/// Remove process (PID) from list of processes excluded from the tunnel
#[cfg(target_os = "linux")]
RemoveSplitTunnelProcess(ResponseTx<(), split_tunnel::Error>, i32),
/// Clear list of processes excluded from the tunnel
#[cfg(target_os = "linux")]
ClearSplitTunnelProcesses(ResponseTx<(), split_tunnel::Error>),
/// Exclude traffic of an application from the tunnel
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
AddSplitTunnelApp(ResponseTx<(), Error>, SplitApp),
/// Remove application from list of apps to exclude from the tunnel
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
RemoveSplitTunnelApp(ResponseTx<(), Error>, SplitApp),
/// Clear list of apps to exclude from the tunnel
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
ClearSplitTunnelApps(ResponseTx<(), Error>),
/// Enable or disable split tunneling
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
SetSplitTunnelState(ResponseTx<(), Error>, bool),
/// Returns all processes currently being excluded from the tunnel
#[cfg(windows)]
GetSplitTunnelProcesses(ResponseTx<Vec<ExcludedProcess>, split_tunnel::Error>),
/// Notify the split tunnel monitor that a volume was mounted or dismounted
#[cfg(target_os = "windows")]
CheckVolumes(ResponseTx<(), Error>),
/// Register settings for WireGuard obfuscator
SetObfuscationSettings(ResponseTx<(), settings::Error>, ObfuscationSettings),
/// Saves the target tunnel state and enters a blocking state. The state is restored
/// upon restart.
PrepareRestart(bool),
/// Causes a socket to bypass the tunnel. This has no effect when connected. It is only used
/// to bypass the tunnel in blocking states.
#[cfg(target_os = "android")]
BypassSocket(RawFd, oneshot::Sender<()>),
/// Initialize a google play purchase through the API.
#[cfg(target_os = "android")]
InitPlayPurchase(ResponseTx<PlayPurchasePaymentToken, Error>),
/// Verify that a google play payment was successful through the API.
#[cfg(target_os = "android")]
VerifyPlayPurchase(ResponseTx<(), Error>, PlayPurchase),
/// Patch the settings using a JSON patch
ApplyJsonSettings(ResponseTx<(), settings::patch::Error>, String),
/// Return a JSON blob containing all overridable settings, if there are any
ExportJsonSettings(ResponseTx<String, settings::patch::Error>),
/// Request the current feature indicators.
GetFeatureIndicators(oneshot::Sender<FeatureIndicators>),
}
/// All events that can happen in the daemon. Sent from various threads and exposed interfaces.
pub(crate) enum InternalDaemonEvent {
/// Tunnel has changed state.
TunnelStateTransition(TunnelStateTransition),
/// A command sent to the daemon.
Command(DaemonCommand),
/// Daemon shutdown triggered by a signal, ctrl-c or similar.
/// The boolean should indicate whether the shutdown was user-initiated.
TriggerShutdown(bool),
/// The background job fetching new `AppVersionInfo`s got a new info object.
NewAppVersionInfo(AppVersionInfo),
/// Sent when a device is updated in any way (key rotation, login, logout, etc.).
DeviceEvent(AccountEvent),
/// Sent when access methods are changed in any way (new active access method).
AccessMethodEvent {
event: AccessMethodEvent,
endpoint_active_tx: oneshot::Sender<()>,
},
/// Handles updates from versions without devices.
DeviceMigrationEvent(Result<PrivateAccountAndDevice, device::Error>),
/// A geographical location has has been received from am.i.mullvad.net
LocationEvent(LocationEventData),
/// A generic event for when any settings change.
SettingsChanged,
/// The split tunnel paths or state were updated.
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
ExcludedPathsEvent(ExcludedPathsUpdate, oneshot::Sender<Result<(), Error>>),
/// A network leak was detected.
LeakDetected(LeakInfo),
}
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
pub(crate) enum ExcludedPathsUpdate {
SetState(bool),
SetPaths(HashSet<SplitApp>),
}
impl From<TunnelStateTransition> for InternalDaemonEvent {
fn from(tunnel_state_transition: TunnelStateTransition) -> Self {
InternalDaemonEvent::TunnelStateTransition(tunnel_state_transition)
}
}
impl From<DaemonCommand> for InternalDaemonEvent {
fn from(command: DaemonCommand) -> Self {
InternalDaemonEvent::Command(command)
}
}
impl From<AppVersionInfo> for InternalDaemonEvent {
fn from(command: AppVersionInfo) -> Self {
InternalDaemonEvent::NewAppVersionInfo(command)
}
}
impl From<AccountEvent> for InternalDaemonEvent {
fn from(event: AccountEvent) -> Self {
InternalDaemonEvent::DeviceEvent(event)
}
}
impl From<(AccessMethodEvent, oneshot::Sender<()>)> for InternalDaemonEvent {
fn from(event: (AccessMethodEvent, oneshot::Sender<()>)) -> Self {
InternalDaemonEvent::AccessMethodEvent {
event: event.0,
endpoint_active_tx: event.1,
}
}
}
pub struct DaemonCommandChannel {
sender: DaemonCommandSender,
receiver: mpsc::UnboundedReceiver<InternalDaemonEvent>,
}
impl Default for DaemonCommandChannel {
fn default() -> Self {
Self::new()
}
}
impl DaemonCommandChannel {
pub fn new() -> Self {
let (untracked_sender, receiver) = mpsc::unbounded();
let sender = DaemonCommandSender(Arc::new(untracked_sender));
Self { sender, receiver }
}
pub fn sender(&self) -> DaemonCommandSender {
self.sender.clone()
}
fn destructure(
self,
) -> (
DaemonEventSender,
mpsc::UnboundedReceiver<InternalDaemonEvent>,
) {
let event_sender = DaemonEventSender::new(Arc::downgrade(&self.sender.0));
(event_sender, self.receiver)
}
}
#[derive(Debug, Clone)]
pub struct DaemonCommandSender(Arc<mpsc::UnboundedSender<InternalDaemonEvent>>);
impl DaemonCommandSender {
pub fn send(&self, command: DaemonCommand) -> Result<(), Error> {
self.0
.unbounded_send(InternalDaemonEvent::Command(command))
.map_err(|_| Error::DaemonUnavailable)
}
/// Shuts down the daemon. This triggers the shutdown as though the user would shut it down
/// because blocking traffic on Android relies on the daemon process being alive and keeping a
/// tunnel device open.
#[cfg(target_os = "android")]
pub fn shutdown(&self) -> Result<(), Error> {
self.0
.unbounded_send(InternalDaemonEvent::TriggerShutdown(true))
.map_err(|_| Error::DaemonUnavailable)
}
}
pub(crate) struct DaemonEventSender<E = InternalDaemonEvent> {
sender: Weak<mpsc::UnboundedSender<InternalDaemonEvent>>,
_event: PhantomData<E>,
}
impl<E> Clone for DaemonEventSender<E>
where
InternalDaemonEvent: From<E>,
{
fn clone(&self) -> Self {
DaemonEventSender {
sender: self.sender.clone(),
_event: PhantomData,
}
}
}
impl DaemonEventSender {
pub fn new(sender: Weak<mpsc::UnboundedSender<InternalDaemonEvent>>) -> Self {
DaemonEventSender {
sender,
_event: PhantomData,
}
}
pub fn to_specialized_sender<E>(&self) -> DaemonEventSender<E>
where
InternalDaemonEvent: From<E>,
{
DaemonEventSender {
sender: self.sender.clone(),
_event: PhantomData,
}
}
}
impl<E> Sender<E> for DaemonEventSender<E>
where
InternalDaemonEvent: From<E>,
{
fn send(&self, event: E) -> Result<(), talpid_core::mpsc::Error> {
match self.sender.upgrade() {
Some(sender) => sender
.unbounded_send(InternalDaemonEvent::from(event))
.map_err(|_| talpid_core::mpsc::Error::ChannelClosed),
_ => Err(talpid_core::mpsc::Error::ChannelClosed),
}
}
}
impl<E> DaemonEventSender<E>
where
InternalDaemonEvent: From<E>,
{
pub fn to_unbounded_sender<T>(&self) -> mpsc::UnboundedSender<T>
where
InternalDaemonEvent: From<E>,
T: Send + 'static,
E: From<T>,
{
let (tx, mut rx) = mpsc::unbounded::<T>();
let sender = self.sender.clone();
tokio::runtime::Handle::current().spawn(async move {
while let Some(msg) = rx.next().await {
if let Some(tx) = sender.upgrade() {
let e: E = E::from(msg);
if tx.send(e.into()).is_err() {
return;
}
} else {
return;
};
}
});
tx
}
}
pub struct Daemon {
tunnel_state: TunnelState,
target_state: PersistentTargetState,
#[cfg(target_os = "linux")]
exclude_pids: split_tunnel::PidManager,
rx: mpsc::UnboundedReceiver<InternalDaemonEvent>,
tx: DaemonEventSender,
reconnection_job: Option<AbortHandle>,
management_interface: ManagementInterfaceServer,
migration_complete: migrations::MigrationComplete,
settings: SettingsPersister,
account_history: account_history::AccountHistory,
device_checker: device::TunnelStateChangeHandler,
account_manager: device::AccountManagerHandle,
access_mode_handler: mullvad_api::api::AccessModeSelectorHandle,
api_runtime: mullvad_api::Runtime,
api_handle: mullvad_api::rest::MullvadRestHandle,
version_updater_handle: version_check::VersionUpdaterHandle,
relay_selector: RelaySelector,
relay_list_updater: RelayListUpdaterHandle,
parameters_generator: tunnel::ParametersGenerator,
shutdown_tasks: Vec<Pin<Box<dyn Future<Output = ()> + Send + Sync>>>,
tunnel_state_machine_handle: TunnelStateMachineHandle,
#[cfg(target_os = "windows")]
volume_update_tx: mpsc::UnboundedSender<()>,
location_handler: GeoIpHandler,
leak_checker: LeakChecker,
}
pub struct DaemonConfig {
pub log_dir: Option<PathBuf>,
pub resource_dir: PathBuf,
pub settings_dir: PathBuf,
pub cache_dir: PathBuf,
pub rpc_socket_path: PathBuf,
pub endpoint: ApiEndpoint,
#[cfg(target_os = "android")]
pub android_context: AndroidContext,
}
impl Daemon {
pub async fn start(
config: DaemonConfig,
daemon_command_channel: DaemonCommandChannel,
) -> Result<Self, Error> {
#[cfg(target_os = "macos")]
macos::bump_filehandle_limit();
let command_sender = daemon_command_channel.sender();
let management_interface =
ManagementInterfaceServer::start(command_sender, config.rpc_socket_path)
.map_err(Error::ManagementInterfaceError)?;
let (internal_event_tx, internal_event_rx) = daemon_command_channel.destructure();
#[cfg(target_os = "android")]
let connectivity_listener = ConnectivityListener::new(config.android_context.clone())
.inspect_err(|error| {
log::error!(
"{}",
error.display_chain_with_msg("Failed to start connectivity listener")
);
})
.map_err(|_| Error::DaemonUnavailable)?;
mullvad_api::proxy::ApiConnectionMode::try_delete_cache(&config.cache_dir).await;
let api_runtime = mullvad_api::Runtime::with_cache(
&config.endpoint,
&config.cache_dir,
true,
#[cfg(target_os = "android")]
api::create_bypass_tx(&internal_event_tx),
)
.await
.map_err(Error::InitRpcFactory)?;
let api_availability = api_runtime.availability_handle();
api_availability.suspend();
let migration_data = migrations::migrate_all(&config.cache_dir, &config.settings_dir)
.await
.unwrap_or_else(|error| {
log::error!(
"{}",
error.display_chain_with_msg("Failed to migrate settings or cache")
);
None
});
let settings_event_listener = management_interface.notifier().clone();
let mut settings = SettingsPersister::load(&config.settings_dir).await;
settings.register_change_listener(move |settings| {
// Notify management interface server of changes to the settings
settings_event_listener.notify_settings(settings.to_owned());
});
let initial_selector_config = SelectorConfig::from_settings(&settings);
let relay_selector = RelaySelector::new(
initial_selector_config,
config.resource_dir.join(RELAYS_FILENAME),
config.cache_dir.join(RELAYS_FILENAME),
);
let settings_relay_selector = relay_selector.clone();
settings.register_change_listener(move |settings| {
// Notify relay selector of changes to the settings/selector config
settings_relay_selector
.clone()
.set_config(SelectorConfig::from_settings(settings));
});
let allowed_clients_selector = AllowedClientsSelector {};
let selector_box: Box<dyn AllowedClientsProvider> = Box::new(allowed_clients_selector);
let (access_mode_handler, access_mode_provider) =
mullvad_api::api::AccessModeSelector::spawn(
config.cache_dir.clone(),
relay_selector.clone(),
settings.api_access_methods.clone(),
#[cfg(feature = "api-override")]
config.endpoint.clone(),
internal_event_tx.to_unbounded_sender(),
api_runtime.address_cache().clone(),
selector_box,
)
.await
.map_err(Error::ApiConnectionModeError)?;
let api_handle = api_runtime.mullvad_rest_handle(access_mode_provider);
// Continually update the API IP
tokio::spawn(api_address_updater::run_api_address_fetcher(
api_runtime.address_cache().clone(),
api_handle.clone(),
#[cfg(feature = "api-override")]
config.endpoint.clone(),
));
let access_method_handle = access_mode_handler.clone();
settings.register_change_listener(move |settings| {
let handle = access_method_handle.clone();
let new_access_methods = settings.api_access_methods.clone();
tokio::spawn(async move {
let _ = handle.update_access_methods(new_access_methods).await;
});
});
let migration_complete = if let Some(migration_data) = migration_data {
migrations::migrate_device(
migration_data,
api_handle.clone(),
internal_event_tx.clone(),
)
} else {
migrations::MigrationComplete::new(true)
};
let (account_manager, data) = device::AccountManager::spawn(
api_handle.clone(),
&config.settings_dir,
settings
.tunnel_options
.wireguard
.rotation_interval
.unwrap_or_default(),
internal_event_tx.to_specialized_sender(),
)
.await
.map_err(Error::LoadAccountManager)?;
let account_history = account_history::AccountHistory::new(
&config.settings_dir,
data.device().map(|device| device.account_number.clone()),
)
.await
.map_err(Error::LoadAccountHistory)?;
let target_state = if settings.auto_connect {
log::info!("Automatically connecting since auto-connect is turned on");
PersistentTargetState::new_secured(&config.cache_dir).await
} else {
PersistentTargetState::new(&config.cache_dir).await
};
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
let exclude_paths = if settings.split_tunnel.enable_exclusions {
settings
.split_tunnel
.apps
.iter()
.cloned()
.map(SplitApp::to_tunnel_command_repr)
.collect()
} else {
vec![]
};
let parameters_generator = tunnel::ParametersGenerator::new(
account_manager.clone(),
relay_selector.clone(),
settings.tunnel_options.clone(),
);
let param_gen = parameters_generator.clone();
let (param_gen_tx, mut param_gen_rx) = mpsc::unbounded();
tokio::spawn(async move {
while let Some(tunnel_options) = param_gen_rx.next().await {
param_gen.set_tunnel_options(&tunnel_options).await;
}
});
settings.register_change_listener(move |settings| {
let _ = param_gen_tx.unbounded_send(settings.tunnel_options.to_owned());
});
// Register a listener for generic settings changes.
// This is useful for example for updating feature indicators when the settings change.
let settings_changed_event_sender = internal_event_tx.clone();
settings.register_change_listener(move |_settings| {
let _ = settings_changed_event_sender.send(InternalDaemonEvent::SettingsChanged);
});
let route_manager = RouteManagerHandle::spawn(
#[cfg(target_os = "linux")]
mullvad_types::TUNNEL_FWMARK,
#[cfg(target_os = "linux")]
mullvad_types::TUNNEL_TABLE_ID,
#[cfg(target_os = "android")]
config.android_context.clone(),
)
.await
.map_err(Error::RouteManager)?;
let (offline_state_tx, offline_state_rx) = mpsc::unbounded();
#[cfg(target_os = "windows")]
let (volume_update_tx, volume_update_rx) = mpsc::unbounded();
let tunnel_state_machine_handle = tunnel_state_machine::spawn(
tunnel_state_machine::InitialTunnelState {
allow_lan: settings.allow_lan,
#[cfg(not(target_os = "android"))]
block_when_disconnected: settings.block_when_disconnected,
dns_config: dns::addresses_from_options(&settings.tunnel_options.dns_options),
allowed_endpoint: access_mode_handler
.get_current()
.await
.map_err(Error::ApiConnectionModeError)?
.endpoint,
reset_firewall: *target_state != TargetState::Secured,
#[cfg(any(windows, target_os = "android", target_os = "macos"))]
exclude_paths,
},
parameters_generator.clone(),
config.log_dir,
config.resource_dir.clone(),
internal_event_tx.to_specialized_sender(),
offline_state_tx,
route_manager.clone(),
#[cfg(target_os = "windows")]
volume_update_rx,
#[cfg(target_os = "android")]
config.android_context,
#[cfg(target_os = "android")]
connectivity_listener.clone(),
#[cfg(target_os = "linux")]
tunnel_state_machine::LinuxNetworkingIdentifiers {
fwmark: mullvad_types::TUNNEL_FWMARK,
table_id: mullvad_types::TUNNEL_TABLE_ID,
},
)
.await
.map_err(Error::TunnelError)?;
api::forward_offline_state(api_availability.clone(), offline_state_rx);
let relay_list_listener = management_interface.notifier().clone();
let on_relay_list_update = move |relay_list: &RelayList| {
relay_list_listener.notify_relay_list(relay_list.clone());
};
let mut relay_list_updater = RelayListUpdater::spawn(
relay_selector.clone(),
api_handle.clone(),
&config.cache_dir,
on_relay_list_update,
);
let version_updater_handle = version_check::VersionUpdater::spawn(
api_handle.clone(),
api_availability.clone(),
config.cache_dir.clone(),
internal_event_tx.to_specialized_sender(),
settings.show_beta_releases,
)
.await;
// Attempt to download a fresh relay list
relay_list_updater.update().await;
let location_handler = GeoIpHandler::new(
api_runtime.rest_handle(
#[cfg(not(target_os = "android"))]
mullvad_api::DefaultDnsResolver,
#[cfg(target_os = "android")]
android_dns::AndroidDnsResolver::new(connectivity_listener),
),
internal_event_tx.clone().to_specialized_sender(),
);
let leak_checker = {
let mut leak_checker = LeakChecker::new(route_manager);
let internal_event_tx = internal_event_tx.clone();
leak_checker.add_leak_callback(move |info| {
internal_event_tx
.send(InternalDaemonEvent::LeakDetected(info))
.is_ok()
});
leak_checker
};
let daemon = Daemon {
tunnel_state: TunnelState::Disconnected {
location: None,
#[cfg(not(target_os = "android"))]
locked_down: settings.block_when_disconnected,
},
target_state,
#[cfg(target_os = "linux")]
exclude_pids: split_tunnel::PidManager::new().map_err(Error::InitSplitTunneling)?,
rx: internal_event_rx,
tx: internal_event_tx,
reconnection_job: None,
management_interface,
migration_complete,
settings,
account_history,
device_checker: device::TunnelStateChangeHandler::new(account_manager.clone()),
account_manager,
access_mode_handler,
api_runtime,
api_handle,
version_updater_handle,
relay_selector,
relay_list_updater,
parameters_generator,
shutdown_tasks: vec![],
tunnel_state_machine_handle,
#[cfg(target_os = "windows")]
volume_update_tx,
location_handler,
leak_checker,
};
api_availability.unsuspend();
Ok(daemon)
}
/// Consume the `Daemon` and run the main event loop. Blocks until an error happens or a
/// shutdown event is received.
pub async fn run(mut self) -> Result<(), Error> {
self.handle_initial_target_state();
self.handle_events().await;
self.disconnect_tunnel_and_wait().await;
self.finalize().await;
Ok(())
}
fn handle_initial_target_state(&mut self) {
match self.target_state.to_strict() {
either::Either::Right(state) => {
self.send_tunnel_command(Self::secured_state_to_tunnel_command(state));
}
either::Either::Left(_) => {
// Fetching GeoIpLocation is automatically done when connecting.
// If TargetState is Unsecured we will not connect on lauch and
// so we have to explicitly fetch this information.
self.fetch_am_i_mullvad()
}
}
}
/// Map the secured target state to a tunnel command
const fn secured_state_to_tunnel_command(_: TargetStateStrict<Secured>) -> TunnelCommand {
TunnelCommand::Connect
}
/// Begin disconnecting and wait for the tunnel state machine to be disconnected
async fn disconnect_tunnel_and_wait(&mut self) {
if self.tunnel_state.is_disconnected() {
return;
}
self.disconnect_tunnel();
while let Some(event) = self.rx.next().await {
match event {
InternalDaemonEvent::TunnelStateTransition(transition) => {
self.handle_tunnel_state_transition(transition).await;
}
_ => {
log::trace!("Ignoring event because the daemon is shutting down");
}
}