-
Notifications
You must be signed in to change notification settings - Fork 392
/
Copy pathTunnelManager.swift
1282 lines (1017 loc) · 39.3 KB
/
TunnelManager.swift
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
//
// TunnelManager.swift
// MullvadVPN
//
// Created by pronebird on 25/09/2019.
// Copyright © 2019 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import MullvadREST
import MullvadSettings
import MullvadTypes
import NetworkExtension
import Operations
import PacketTunnelCore
import StoreKit
import UIKit
import WireGuardKitTypes
/// Interval used for periodic polling of tunnel relay status when tunnel is establishing
/// connection.
private let establishingTunnelStatusPollInterval: Duration = .seconds(3)
/// Interval used for periodic polling of tunnel connectivity status once the tunnel connection
/// is established.
private let establishedTunnelStatusPollInterval: Duration = .seconds(5)
/// A class that provides a convenient interface for VPN tunnels configuration, manipulation and
/// monitoring.
final class TunnelManager: StorePaymentObserver {
private enum OperationCategory: String {
case manageTunnel
case deviceStateUpdate
case settingsUpdate
case tunnelStateUpdate
var category: String {
"TunnelManager.\(rawValue)"
}
}
// MARK: - Internal variables
private let application: BackgroundTaskProvider
fileprivate let tunnelStore: any TunnelStoreProtocol
private let relayCacheTracker: RelayCacheTrackerProtocol
private let accountsProxy: RESTAccountHandling
private let devicesProxy: DeviceHandling
private let apiProxy: APIQuerying
private let accessTokenManager: RESTAccessTokenManagement
private let logger = Logger(label: "TunnelManager")
private var nslock = NSRecursiveLock()
private let operationQueue = AsyncOperationQueue()
private let internalQueue = DispatchQueue(label: "TunnelManager.internalQueue")
private var statusObserver: TunnelStatusBlockObserver?
private var lastMapConnectionStatusOperation: Operation?
private let observerList = ObserverList<TunnelObserver>()
private var networkMonitor: NWPathMonitor?
private var privateKeyRotationTimer: DispatchSourceTimer?
public private(set) var isRunningPeriodicPrivateKeyRotation = false
public private(set) var nextKeyRotationDate: Date?
private var tunnelStatusPollTimer: DispatchSourceTimer?
private var isPolling = false
private var _isConfigurationLoaded = false
private var _deviceState: DeviceState = .loggedOut
private var _tunnelSettings = LatestTunnelSettings()
private var _tunnel: (any TunnelProtocol)?
private var _tunnelStatus = TunnelStatus()
/// Last processed device check.
private var lastPacketTunnelKeyRotation: Date?
// MARK: - Initialization
init(
application: BackgroundTaskProvider,
tunnelStore: any TunnelStoreProtocol,
relayCacheTracker: RelayCacheTrackerProtocol,
accountsProxy: RESTAccountHandling,
devicesProxy: DeviceHandling,
apiProxy: APIQuerying,
accessTokenManager: RESTAccessTokenManagement
) {
self.application = application
self.tunnelStore = tunnelStore
self.relayCacheTracker = relayCacheTracker
self.accountsProxy = accountsProxy
self.devicesProxy = devicesProxy
self.apiProxy = apiProxy
self.operationQueue.name = "TunnelManager.operationQueue"
self.operationQueue.underlyingQueue = internalQueue
self.accessTokenManager = accessTokenManager
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationDidBecomeActive(_:)),
name: UIApplication.didBecomeActiveNotification,
object: application
)
}
// MARK: - Periodic private key rotation
func startPeriodicPrivateKeyRotation() {
nslock.lock()
defer { nslock.unlock() }
guard !isRunningPeriodicPrivateKeyRotation, deviceState.isLoggedIn else { return }
logger.debug("Start periodic private key rotation.")
isRunningPeriodicPrivateKeyRotation = true
updatePrivateKeyRotationTimer()
}
func stopPeriodicPrivateKeyRotation() {
nslock.lock()
defer { nslock.unlock() }
guard isRunningPeriodicPrivateKeyRotation else { return }
logger.debug("Stop periodic private key rotation.")
isRunningPeriodicPrivateKeyRotation = false
updatePrivateKeyRotationTimer()
}
func startOrStopPeriodicPrivateKeyRotation() {
if deviceState.isLoggedIn {
startPeriodicPrivateKeyRotation()
} else {
stopPeriodicPrivateKeyRotation()
}
}
func getNextKeyRotationDate() -> Date? {
nslock.lock()
defer { nslock.unlock() }
return deviceState.deviceData.flatMap { WgKeyRotation(data: $0).nextRotationDate }
}
private func updatePrivateKeyRotationTimer() {
nslock.lock()
defer { nslock.unlock() }
privateKeyRotationTimer?.cancel()
privateKeyRotationTimer = nil
nextKeyRotationDate = nil
guard isRunningPeriodicPrivateKeyRotation,
let scheduleDate = getNextKeyRotationDate() else { return }
nextKeyRotationDate = scheduleDate
let timer = DispatchSource.makeTimerSource(queue: .main)
timer.setEventHandler { [weak self] in
_ = self?.rotatePrivateKey { _ in
// no-op
}
}
timer.schedule(wallDeadline: .now() + scheduleDate.timeIntervalSinceNow)
timer.activate()
privateKeyRotationTimer = timer
logger.debug("Schedule next private key rotation at \(scheduleDate.logFormatted).")
}
// MARK: - Public methods
func loadConfiguration(completionHandler: @escaping () -> Void) {
let loadTunnelOperation = LoadTunnelConfigurationOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self)
)
loadTunnelOperation.completionQueue = .main
loadTunnelOperation.completionHandler = { [weak self] completion in
guard let self else { return }
if case let .failure(error) = completion {
self.logger.error(
error: error,
message: "Failed to load configuration."
)
}
self.updatePrivateKeyRotationTimer()
self.startNetworkMonitor()
completionHandler()
}
loadTunnelOperation.addObserver(
BackgroundObserver(
application: application,
name: "Load tunnel configuration",
cancelUponExpiration: false
)
)
loadTunnelOperation.addCondition(
MutuallyExclusive(category: OperationCategory.manageTunnel.category)
)
operationQueue.addOperation(loadTunnelOperation)
}
func startTunnel(completionHandler: ((Error?) -> Void)? = nil) {
let operation = StartTunnelOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self),
completionHandler: { [weak self] result in
guard let self else { return }
DispatchQueue.main.async {
if let error = result.error {
self.logger.error(
error: error,
message: "Failed to start the tunnel."
)
let tunnelError = StartTunnelError(underlyingError: error)
self.observerList.forEach { observer in
observer.tunnelManager(self, didFailWithError: tunnelError)
}
}
completionHandler?(result.error)
}
}
)
operation.addObserver(BackgroundObserver(
application: application,
name: "Start tunnel",
cancelUponExpiration: true
))
operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))
operationQueue.addOperation(operation)
}
func stopTunnel(completionHandler: ((Error?) -> Void)? = nil) {
let operation = StopTunnelOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self)
) { [weak self] result in
guard let self else { return }
DispatchQueue.main.async {
if let error = result.error {
self.logger.error(
error: error,
message: "Failed to stop the tunnel."
)
let tunnelError = StopTunnelError(underlyingError: error)
self.observerList.forEach { observer in
observer.tunnelManager(self, didFailWithError: tunnelError)
}
}
completionHandler?(result.error)
}
}
operation.addObserver(BackgroundObserver(
application: application,
name: "Stop tunnel",
cancelUponExpiration: true
))
operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))
operationQueue.addOperation(operation)
}
func reconnectTunnel(selectNewRelay: Bool, completionHandler: ((Error?) -> Void)? = nil) {
let operation = AsyncBlockOperation(dispatchQueue: internalQueue) { finish -> Cancellable in
do {
guard let tunnel = self.tunnel else {
throw UnsetTunnelError()
}
return tunnel.reconnectTunnel(to: selectNewRelay ? .random : .current) { result in
finish(result.error)
}
} catch {
finish(error)
return AnyCancellable()
}
}
operation.completionBlock = {
DispatchQueue.main.async {
self.didReconnectTunnel(error: operation.error)
completionHandler?(operation.error)
}
}
operation.addObserver(
BackgroundObserver(
application: application,
name: "Reconnect tunnel",
cancelUponExpiration: true
)
)
operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))
operationQueue.addOperation(operation)
}
func setNewAccount() async throws -> StoredAccountData {
try await setAccount(action: .new)!
}
func setExistingAccount(accountNumber: String) async throws -> StoredAccountData {
try await setAccount(action: .existing(accountNumber))!
}
private func setAccount(
action: SetAccountAction,
completionHandler: @escaping (Result<StoredAccountData?, Error>) -> Void
) {
let operation = SetAccountOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self),
accountsProxy: accountsProxy,
devicesProxy: devicesProxy,
accessTokenManager: accessTokenManager,
action: action
)
operation.completionQueue = .main
operation.completionHandler = { [weak self] result in
guard let self else { return }
startOrStopPeriodicPrivateKeyRotation()
completionHandler(result)
}
operation.addObserver(BackgroundObserver(
application: application,
name: action.taskName,
cancelUponExpiration: true
))
operation.addCondition(
MutuallyExclusive(category: OperationCategory.manageTunnel.category)
)
operation.addCondition(
MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
)
operation.addCondition(
MutuallyExclusive(category: OperationCategory.settingsUpdate.category)
)
// Unsetting (ie. logging out) or deleting the account should cancel all other
// currently ongoing activity.
switch action {
case .unset, .delete:
operationQueue.cancelAllOperations()
default:
break
}
operationQueue.addOperation(operation)
}
private func setAccount(action: SetAccountAction) async throws -> StoredAccountData? {
try await withCheckedThrowingContinuation { continuation in
setAccount(action: action) { result in
continuation.resume(with: result)
}
}
}
func unsetAccount() async {
_ = try? await setAccount(action: .unset)
}
func updateAccountData(_ completionHandler: ((Error?) -> Void)? = nil) {
let operation = UpdateAccountDataOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self),
accountsProxy: accountsProxy
)
operation.completionQueue = .main
operation.completionHandler = { completion in
completionHandler?(completion.error)
}
operation.addObserver(
BackgroundObserver(
application: application,
name: "Update account data",
cancelUponExpiration: true
)
)
operation.addCondition(
MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
)
operationQueue.addOperation(operation)
}
func redeemVoucher(
_ voucherCode: String,
completion: ((Result<REST.SubmitVoucherResponse, Error>) -> Void)? = nil
) -> Cancellable {
let operation = RedeemVoucherOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self),
voucherCode: voucherCode,
apiProxy: apiProxy
)
operation.completionQueue = .main
operation.completionHandler = completion
operation.addObserver(
BackgroundObserver(
application: application,
name: "Redeem voucher",
cancelUponExpiration: true
)
)
operation.addCondition(MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category))
operationQueue.addOperation(operation)
return operation
}
func deleteAccount(accountNumber: String) async throws {
_ = try await setAccount(action: .delete(accountNumber))
}
func updateDeviceData(_ completionHandler: ((Error?) -> Void)? = nil) {
let operation = UpdateDeviceDataOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self),
devicesProxy: devicesProxy
)
operation.completionQueue = .main
operation.completionHandler = { completion in
completionHandler?(completion.error)
}
operation.addObserver(
BackgroundObserver(
application: application,
name: "Update device data",
cancelUponExpiration: true
)
)
operation.addCondition(
MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
)
operationQueue.addOperation(operation)
}
func rotatePrivateKey(completionHandler: @escaping (Error?) -> Void) -> Cancellable {
let operation = RotateKeyOperation(
dispatchQueue: internalQueue,
interactor: TunnelInteractorProxy(self),
devicesProxy: devicesProxy
)
operation.completionQueue = .main
operation.completionHandler = { [weak self] result in
guard let self else { return }
updatePrivateKeyRotationTimer()
let error = result.error
if let error {
handleRestError(error)
}
completionHandler(error)
}
operation.addObserver(
BackgroundObserver(
application: application,
name: "Rotate private key",
cancelUponExpiration: true
)
)
operation.addCondition(
MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
)
operationQueue.addOperation(operation)
return operation
}
func updateSettings(_ updates: [TunnelSettingsUpdate], completionHandler: (() -> Void)? = nil) {
let taskName = "Set " + updates.map(\.subjectName).joined(separator: ", ")
scheduleSettingsUpdate(
taskName: taskName,
modificationBlock: { settings in
for update in updates {
update.apply(to: &settings)
}
},
completionHandler: completionHandler
)
}
func refreshRelayCacheTracker() throws {
try relayCacheTracker.refreshCachedRelays()
}
// MARK: - Tunnel observeration
/// Add tunnel observer.
/// In order to cancel the observation, either call `removeObserver(_:)` or simply release
/// the observer.
func addObserver(_ observer: TunnelObserver) {
observerList.append(observer)
}
/// Remove tunnel observer.
func removeObserver(_ observer: TunnelObserver) {
observerList.remove(observer)
}
// MARK: - StorePaymentObserver
func storePaymentManager(
_ manager: StorePaymentManager,
didReceiveEvent event: StorePaymentEvent
) {
guard case let .finished(paymentCompletion) = event else {
return
}
scheduleDeviceStateUpdate(
taskName: "Update account expiry after in-app purchase",
modificationBlock: { deviceState in
switch deviceState {
case .loggedIn(var accountData, let deviceData):
if accountData.number == paymentCompletion.accountNumber {
accountData.expiry = paymentCompletion.serverResponse.newExpiry
deviceState = .loggedIn(accountData, deviceData)
}
case .loggedOut, .revoked:
break
}
},
completionHandler: nil
)
}
// MARK: - TunnelInteractor
var isConfigurationLoaded: Bool {
nslock.lock()
defer { nslock.unlock() }
return _isConfigurationLoaded
}
fileprivate var tunnel: (any TunnelProtocol)? {
nslock.lock()
defer { nslock.unlock() }
return _tunnel
}
var tunnelStatus: TunnelStatus {
nslock.lock()
defer { nslock.unlock() }
return _tunnelStatus
}
var settings: LatestTunnelSettings {
nslock.lock()
defer { nslock.unlock() }
return _tunnelSettings
}
var deviceState: DeviceState {
nslock.lock()
defer { nslock.unlock() }
return _deviceState
}
fileprivate func setConfigurationLoaded() {
nslock.lock()
defer { nslock.unlock() }
guard !_isConfigurationLoaded else {
return
}
_isConfigurationLoaded = true
DispatchQueue.main.async {
self.observerList.forEach { observer in
observer.tunnelManagerDidLoadConfiguration(self)
}
}
}
fileprivate func setTunnel(_ tunnel: (any TunnelProtocol)?, shouldRefreshTunnelState: Bool) {
nslock.lock()
defer { nslock.unlock() }
if let tunnel {
subscribeVPNStatusObserver(tunnel: tunnel)
} else {
unsubscribeVPNStatusObserver()
}
_tunnel = tunnel
// Update the existing state
if shouldRefreshTunnelState {
logger.debug("Refresh tunnel status for new tunnel.")
refreshTunnelStatus()
}
}
fileprivate func setTunnelStatus(_ block: (inout TunnelStatus) -> Void) -> TunnelStatus {
nslock.lock()
defer { nslock.unlock() }
var newTunnelStatus = _tunnelStatus
block(&newTunnelStatus)
guard _tunnelStatus != newTunnelStatus else {
return newTunnelStatus
}
logger.info("Status: \(newTunnelStatus).")
_tunnelStatus = newTunnelStatus
// Packet tunnel may have attempted or rotated the key.
// In that case we have to reload device state from Keychain as it's likely was modified by packet tunnel.
let newPacketTunnelKeyRotation = newTunnelStatus.observedState.connectionState?.lastKeyRotation
if lastPacketTunnelKeyRotation != newPacketTunnelKeyRotation {
lastPacketTunnelKeyRotation = newPacketTunnelKeyRotation
refreshDeviceState()
}
switch newTunnelStatus.state {
case .connecting, .reconnecting:
// Start polling tunnel status to keep the relay information up to date
// while the tunnel process is trying to connect.
startPollingTunnelStatus(interval: establishingTunnelStatusPollInterval)
#if DEBUG
case .negotiatingKey:
startPollingTunnelStatus(interval: establishingTunnelStatusPollInterval)
#endif
case .connected, .waitingForConnectivity(.noConnection):
// Start polling tunnel status to keep connectivity status up to date.
startPollingTunnelStatus(interval: establishedTunnelStatusPollInterval)
case .pendingReconnect, .disconnecting, .disconnected, .waitingForConnectivity(.noNetwork):
// Stop polling tunnel status once connection moved to final state.
cancelPollingTunnelStatus()
case let .error(blockedStateReason):
switch blockedStateReason {
case .deviceRevoked, .invalidAccount:
handleBlockedState(reason: blockedStateReason)
default:
break
}
// Stop polling tunnel status once blocked state has been determined.
cancelPollingTunnelStatus()
}
DispatchQueue.main.async {
self.observerList.forEach { observer in
observer.tunnelManager(self, didUpdateTunnelStatus: newTunnelStatus)
}
}
return newTunnelStatus
}
fileprivate func setSettings(_ settings: LatestTunnelSettings, persist: Bool) {
nslock.lock()
defer { nslock.unlock() }
let shouldCallDelegate = _tunnelSettings != settings && _isConfigurationLoaded
_tunnelSettings = settings
if persist {
do {
try SettingsManager.writeSettings(settings)
} catch {
logger.error(
error: error,
message: "Failed to write settings."
)
}
}
if shouldCallDelegate {
DispatchQueue.main.async {
self.observerList.forEach { observer in
observer.tunnelManager(self, didUpdateTunnelSettings: settings)
}
}
}
}
fileprivate func setDeviceState(_ deviceState: DeviceState, persist: Bool) {
nslock.lock()
defer { nslock.unlock() }
let shouldCallDelegate = _deviceState != deviceState && _isConfigurationLoaded
let previousDeviceState = _deviceState
_deviceState = deviceState
if persist {
do {
try SettingsManager.writeDeviceState(deviceState)
} catch {
logger.error(
error: error,
message: "Failed to write device state."
)
}
}
if shouldCallDelegate {
DispatchQueue.main.async {
self.observerList.forEach { observer in
observer.tunnelManager(
self,
didUpdateDeviceState: deviceState,
previousDeviceState: previousDeviceState
)
}
}
}
}
// MARK: - Private methods
@objc private func applicationDidBecomeActive(_ notification: Notification) {
#if DEBUG
logger.debug("Refresh device state and tunnel status due to application becoming active.")
#endif
refreshTunnelStatus()
refreshDeviceState()
}
private func didUpdateNetworkPath(_ path: Network.NWPath) {
updateTunnelStatus(tunnel?.status ?? .disconnected)
}
fileprivate func selectRelay() throws -> SelectedRelay {
let cachedRelays = try relayCacheTracker.getCachedRelays()
let retryAttempts = tunnelStatus.observedState.connectionState?.connectionAttemptCount ?? 0
let selectorResult = try RelaySelector.evaluate(
relays: cachedRelays.relays,
constraints: settings.relayConstraints,
numberOfFailedAttempts: retryAttempts
)
return SelectedRelay(
endpoint: selectorResult.endpoint,
hostname: selectorResult.relay.hostname,
location: selectorResult.location,
retryAttempts: retryAttempts
)
}
fileprivate func prepareForVPNConfigurationDeletion() {
nslock.lock()
defer { nslock.unlock() }
// Unregister from receiving VPN connection status changes
unsubscribeVPNStatusObserver()
// Cancel last VPN status mapping operation
lastMapConnectionStatusOperation?.cancel()
lastMapConnectionStatusOperation = nil
}
private func didReconnectTunnel(error: Error?) {
nslock.lock()
defer { nslock.unlock() }
if let error, !error.isOperationCancellationError {
logger.error(error: error, message: "Failed to reconnect the tunnel.")
}
// Refresh tunnel status only when connecting or reasserting to pick up the next relay,
// since both states may persist for a long period of time until the tunnel is fully
// connected.
switch tunnelStatus.state {
case .connecting, .reconnecting:
logger.debug("Refresh tunnel status due to reconnect.")
refreshTunnelStatus()
default:
break
}
}
private func subscribeVPNStatusObserver(tunnel: any TunnelProtocol) {
nslock.lock()
defer { nslock.unlock() }
unsubscribeVPNStatusObserver()
statusObserver = tunnel
.addBlockObserver(queue: internalQueue) { [weak self] tunnel, status in
guard let self else { return }
self.logger.debug("VPN connection status changed to \(status).")
if [.disconnected, .invalid].contains(tunnel.status) {
self.startNetworkMonitor()
} else {
self.cancelNetworkMonitor()
}
self.updateTunnelStatus(status)
}
}
private func startNetworkMonitor() {
cancelNetworkMonitor()
networkMonitor = NWPathMonitor()
networkMonitor?.pathUpdateHandler = { [weak self] path in
self?.didUpdateNetworkPath(path)
}
networkMonitor?.start(queue: internalQueue)
}
private func cancelNetworkMonitor() {
networkMonitor?.cancel()
networkMonitor = nil
}
private func unsubscribeVPNStatusObserver() {
nslock.lock()
defer { nslock.unlock() }
statusObserver?.invalidate()
statusObserver = nil
}
private func refreshTunnelStatus() {
nslock.lock()
defer { nslock.unlock() }
if let connectionStatus = _tunnel?.status {
updateTunnelStatus(connectionStatus)
}
}
/// Refresh device state from settings and update the in-memory value.
/// Used to refresh device state when it's modified by packet tunnel during key rotation.
private func refreshDeviceState() {
let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {
do {
let newDeviceState = try SettingsManager.readDeviceState()
self.setDeviceState(newDeviceState, persist: false)
} catch {
if let error = error as? KeychainError, error == .itemNotFound {
return
}
self.logger.error(error: error, message: "Failed to refresh device state")
}
}
operation.addCondition(MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category))
operation.addObserver(BackgroundObserver(
application: application,
name: "Refresh device state",
cancelUponExpiration: true
))
operationQueue.addOperation(operation)
}
/// Update `TunnelStatus` from `NEVPNStatus`.
/// Collects the `PacketTunnelStatus` from the tunnel via IPC if needed before assigning
/// the `tunnelStatus`.
private func updateTunnelStatus(_ connectionStatus: NEVPNStatus) {
nslock.lock()
defer { nslock.unlock() }
let operation = MapConnectionStatusOperation(
queue: internalQueue,
interactor: TunnelInteractorProxy(self),
connectionStatus: connectionStatus,
networkStatus: networkMonitor?.currentPath.status
)
operation.addCondition(
MutuallyExclusive(category: OperationCategory.tunnelStateUpdate.category)
)
// Cancel last VPN status mapping operation
lastMapConnectionStatusOperation?.cancel()
lastMapConnectionStatusOperation = operation
operationQueue.addOperation(operation)
}
private func scheduleSettingsUpdate(
taskName: String,
modificationBlock: @escaping (inout LatestTunnelSettings) -> Void,
completionHandler: (() -> Void)?
) {
let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {
let currentSettings = self._tunnelSettings
var updatedSettings = self._tunnelSettings
modificationBlock(&updatedSettings)
// Select new relay only when relay constraints change.
let currentConstraints = currentSettings.relayConstraints
let updatedConstraints = updatedSettings.relayConstraints
let selectNewRelay = currentConstraints != updatedConstraints
self.setSettings(updatedSettings, persist: true)
self.reconnectTunnel(selectNewRelay: selectNewRelay, completionHandler: nil)
}
operation.completionBlock = {
DispatchQueue.main.async {
completionHandler?()
}
}
operation.addObserver(BackgroundObserver(
application: application,
name: taskName,
cancelUponExpiration: false
))
operation.addCondition(
MutuallyExclusive(category: OperationCategory.settingsUpdate.category)
)
operationQueue.addOperation(operation)
}
private func scheduleDeviceStateUpdate(
taskName: String,
reconnectTunnel: Bool = true,
modificationBlock: @escaping (inout DeviceState) -> Void,
completionHandler: (() -> Void)? = nil
) {
let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {
var deviceState = self.deviceState
modificationBlock(&deviceState)
self.setDeviceState(deviceState, persist: true)
if reconnectTunnel {
self.reconnectTunnel(selectNewRelay: false, completionHandler: nil)
}
}
operation.completionBlock = {