summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/TunnelManager/TunnelManager.swift
blob: fde0ec5216268c9a7a407ff0ab318335aadffd61 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
//
//  TunnelManager.swift
//  MullvadVPN
//
//  Created by pronebird on 25/09/2019.
//  Copyright © 2025 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(1)

/// 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, @unchecked Sendable {
    private enum OperationCategory: String, Sendable {
        case manageTunnel
        case deviceStateUpdate
        case settingsUpdate
        case tunnelStateUpdate

        var category: String {
            "TunnelManager.\(rawValue)"
        }
    }

    // MARK: - Internal variables

    let backgroundTaskProvider: BackgroundTaskProviding
    fileprivate let tunnelStore: any TunnelStoreProtocol
    private let relayCacheTracker: RelayCacheTrackerProtocol
    private let accountsProxy: RESTAccountHandling
    private let devicesProxy: DeviceHandling
    private let apiProxy: APIQuerying

    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 let relaySelector: RelaySelectorProtocol

    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?

    private var observer: TunnelObserver?

    // MARK: - Initialization

    init(
        backgroundTaskProvider: BackgroundTaskProviding,
        tunnelStore: any TunnelStoreProtocol,
        relayCacheTracker: RelayCacheTrackerProtocol,
        accountsProxy: RESTAccountHandling,
        devicesProxy: DeviceHandling,
        apiProxy: APIQuerying,
        relaySelector: RelaySelectorProtocol
    ) {
        self.backgroundTaskProvider = backgroundTaskProvider
        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.relaySelector = relaySelector

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidBecomeActive),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
    }

    // 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 @Sendable () -> 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(
                backgroundTaskProvider: backgroundTaskProvider,
                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 }
                if let error = result.error {
                    self.logger.error(
                        error: error,
                        message: "Failed to start the tunnel."
                    )

                    let tunnelError = StartTunnelError(underlyingError: error)

                    self.observerList.notify { observer in
                        observer.tunnelManager(self, didFailWithError: tunnelError)
                    }
                }

                completionHandler?(result.error)
            }
        )

        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                name: "Start tunnel",
                cancelUponExpiration: true
            ))
        operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))

        operationQueue.addOperation(operation)
    }

    func stopTunnel(isOnDemandEnabled: Bool = false, completionHandler: ((Error?) -> Void)? = nil) {
        let operation = StopTunnelOperation(
            dispatchQueue: internalQueue,
            interactor: TunnelInteractorProxy(self)
        ) { [weak self] result in
            guard let self else { return }

            if let error = result.error {
                self.logger.error(
                    error: error,
                    message: "Failed to stop the tunnel."
                )

                let tunnelError = StopTunnelError(underlyingError: error)

                self.observerList.notify { observer in
                    observer.tunnelManager(self, didFailWithError: tunnelError)
                }
            }

            completionHandler?(result.error)
        }
        operation.isOnDemandEnabled = isOnDemandEnabled
        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                name: "Stop tunnel",
                cancelUponExpiration: true
            ))
        operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))

        operationQueue.addOperation(operation)
    }

    func reconnectTunnel(selectNewRelay: Bool, completionHandler: (@Sendable (Error?) -> Void)? = nil) {
        // Start polling the tunnel immediately when the user reconnects
        startPollingTunnelStatus(interval: establishingTunnelStatusPollInterval)
        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
                    if case let .success(observedState) = result {
                        guard let connectionState = observedState.connectionState else { return }

                        // This makes the app feel very responsive when the user wants to reconnect
                        // If the tunnel is already connected, at worst the next tunnel status poll will correct the state
                        self._tunnelStatus.state = .reconnecting(
                            connectionState.selectedRelays,
                            isPostQuantum: connectionState.isPostQuantum,
                            isDaita: connectionState.isDaitaEnabled
                        )
                        self._tunnelStatus.observedState = observedState
                    }

                    finish(result.error)
                }
            } catch {
                finish(error)

                return AnyCancellable()
            }
        }

        operation.completionBlock = {
            DispatchQueue.main.async {
                self.didReconnectTunnel(error: operation.error)

                completionHandler?(operation.error)
            }
        }

        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                name: "Reconnect tunnel",
                cancelUponExpiration: true
            )
        )
        operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))

        operationQueue.addOperation(operation)
    }

    func reapplyTunnelConfiguration() {
        guard let tunnel else { return }
        if self.tunnelStatus.state.isSecured {
            let observer = TunnelBlockObserver(
                didUpdateTunnelStatus: { _, status in
                    if case .disconnected = status.state {
                        if let observer = self.observer {
                            self.removeObserver(observer)
                            self.observer = nil
                        }
                        self.startTunnel()
                    }
                }
            )
            addObserver(observer)
            self.observer = observer

            let configuration = TunnelConfiguration(
                includeAllNetworks: settings.includeAllNetworks,
                excludeLocalNetworks: settings.localNetworkSharing
            )

            tunnel.setConfiguration(configuration)
            tunnel.saveToPreferences { _ in
                self.stopTunnel(isOnDemandEnabled: true)
            }
        }
    }

    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 @Sendable (Result<StoredAccountData?, Error>) -> Void
    ) {
        let operation = SetAccountOperation(
            dispatchQueue: internalQueue,
            interactor: TunnelInteractorProxy(self),
            accountsProxy: accountsProxy,
            devicesProxy: devicesProxy,
            action: action
        )

        operation.completionQueue = .main
        operation.completionHandler = { [weak self] result in
            guard let self else { return }
            startOrStopPeriodicPrivateKeyRotation()

            completionHandler(result)
        }

        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                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: (@Sendable (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(
                backgroundTaskProvider: backgroundTaskProvider,
                name: "Update account data",
                cancelUponExpiration: true
            )
        )

        operation.addCondition(
            MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
        )

        operationQueue.addOperation(operation)
    }

    func redeemVoucher(
        _ voucherCode: String,
        completion: (@Sendable (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(
                backgroundTaskProvider: backgroundTaskProvider,
                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: (@Sendable (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(
                backgroundTaskProvider: backgroundTaskProvider,
                name: "Update device data",
                cancelUponExpiration: true
            )
        )

        operation.addCondition(
            MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
        )

        operationQueue.addOperation(operation)
    }

    func rotatePrivateKey(completionHandler: @MainActor @escaping @Sendable (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 }
            MainActor.assumeIsolated {
                self.updatePrivateKeyRotationTimer()

                let error = result.error
                if let error {
                    self.handleRestError(error)
                }

                completionHandler(error)
            }
        }

        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                name: "Rotate private key",
                cancelUponExpiration: true
            )
        )

        operation.addCondition(
            MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
        )

        operationQueue.addOperation(operation)

        return operation
    }

    func updateSettings(_ updates: [TunnelSettingsUpdate], completionHandler: (@Sendable () -> 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()
    }

    func selectRelays(tunnelSettings: LatestTunnelSettings) throws -> SelectedRelays {
        let retryAttempts = tunnelStatus.observedState.connectionState?.connectionAttemptCount ?? 0

        return try relaySelector.selectRelays(
            tunnelSettings: tunnelSettings,
            connectionAttemptCount: retryAttempts
        )
    }

    // 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.notify { 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: @Sendable (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 = _tunnelStatus.observedState.connectionState?.lastKeyRotation
        if lastPacketTunnelKeyRotation != newPacketTunnelKeyRotation {
            lastPacketTunnelKeyRotation = newPacketTunnelKeyRotation
            refreshDeviceState()
        }
        switch _tunnelStatus.state {
        case .connecting, .reconnecting, .negotiatingEphemeralPeer:
            // Start polling tunnel status to keep the relay information up to date
            // while the tunnel process is trying to connect.
            startPollingTunnelStatus(interval: establishingTunnelStatusPollInterval)

        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.notify { observer in
                observer.tunnelManager(self, didUpdateTunnelStatus: self._tunnelStatus)
            }
        }

        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.notify { 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.notify { observer in
                    observer.tunnelManager(
                        self,
                        didUpdateDeviceState: deviceState,
                        previousDeviceState: previousDeviceState
                    )
                }
            }
        }
    }

    // MARK: - Private methods

    @objc private func applicationDidBecomeActive() {
        #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 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,reasserting or error 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, .error:
            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?.pathUpdateHandler = nil
        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(
                backgroundTaskProvider: backgroundTaskProvider,
                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 @Sendable (inout LatestTunnelSettings) -> Void,
        completionHandler: (@Sendable () -> Void)?
    ) {
        let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {
            let currentSettings = self._tunnelSettings
            var updatedSettings = self._tunnelSettings
            let settingsStrategy = TunnelSettingsStrategy()

            modificationBlock(&updatedSettings)

            self.setSettings(updatedSettings, persist: true)
            let reconnectionStrategy = settingsStrategy.getReconnectionStrategy(
                oldSettings: currentSettings,
                newSettings: updatedSettings
            )
            switch reconnectionStrategy {
            case .currentRelayReconnect:
                self.reconnectTunnel(selectNewRelay: false)
            case .newRelayReconnect:
                self.reconnectTunnel(selectNewRelay: true)
            case .hardReconnect:
                self.reapplyTunnelConfiguration()
            }
        }

        operation.completionBlock = {
            DispatchQueue.main.async {
                completionHandler?()
            }
        }

        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                name: taskName,
                cancelUponExpiration: false
            ))
        operation.addCondition(
            MutuallyExclusive(category: OperationCategory.settingsUpdate.category)
        )

        operationQueue.addOperation(operation)
    }

    private func scheduleDeviceStateUpdate(
        taskName: String,
        reconnectTunnel: Bool = true,
        modificationBlock: @escaping @Sendable (inout DeviceState) -> Void,
        completionHandler: (@Sendable () -> 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 = {
            DispatchQueue.main.async {
                completionHandler?()
            }
        }

        operation.addObserver(
            BackgroundObserver(
                backgroundTaskProvider: backgroundTaskProvider,
                name: taskName,
                cancelUponExpiration: false
            ))
        operation.addCondition(
            MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)
        )

        operationQueue.addOperation(operation)
    }

    // MARK: - Tunnel status polling

    private func startPollingTunnelStatus(interval: Duration) {
        /*
         Ignore idempotency, otherwise the timer will not be using the correct time interval
         when switching between states, until the tunnel disconnects.
         */
        isPolling = true
        tunnelStatusPollTimer?.cancel()

        logger.debug("Start polling tunnel status every \(interval.logFormat()).")

        let timer = DispatchSource.makeTimerSource(queue: .main)
        timer.setEventHandler { [weak self] in
            self?.refreshTunnelStatus()
        }
        timer.schedule(wallDeadline: .now() + interval, repeating: interval.timeInterval)
        timer.activate()

        tunnelStatusPollTimer = timer
    }

    private func cancelPollingTunnelStatus() {
        guard isPolling else { return }

        logger.debug("Cancel tunnel status polling.")

        tunnelStatusPollTimer?.cancel()
        tunnelStatusPollTimer = nil
        isPolling = false
    }

    fileprivate func removeLastUsedAccount() {
        do {
            try SettingsManager.setLastUsedAccount(nil)
        } catch {
            logger.error(
                error: error,
                message: "Failed to delete account data."
            )
        }
    }

    func handleRestError(_ error: Error) {
        guard let restError = error as? REST.Error else { return }

        if restError.compareErrorCode(.deviceNotFound) {
            handleBlockedState(reason: .deviceRevoked)
        } else if restError.compareErrorCode(.invalidAccount) {
            handleBlockedState(reason: .invalidAccount)
        }
    }

    private func handleBlockedState(reason: BlockedStateReason) {
        switch reason {
        case .deviceRevoked:
            setDeviceState(.revoked, persist: true)
        case .invalidAccount:
            unsetTunnelConfiguration {
                self.setDeviceState(.revoked, persist: true)
                self.operationQueue.cancelAllOperations()
                self.removeLastUsedAccount()
            }
        default:
            break
        }
    }

    private func unsetTunnelConfiguration(completion: @escaping @Sendable () -> Void) {
        // Tell the caller to unsubscribe from VPN status notifications.
        prepareForVPNConfigurationDeletion()

        // Reset tunnel.
        _ = setTunnelStatus { tunnelStatus in
            tunnelStatus = TunnelStatus()
            tunnelStatus.state = .disconnected
        }

        // Finish immediately if tunnel provider is not set.
        guard let tunnel else {
            completion()
            return
        }

        // Remove VPN configuration.
        tunnel.removeFromPreferences { [self] error in
            internalQueue.async { [self] in
                // Ignore error but log it.
                if let error {
                    logger.error(
                        error: error,
                        message: "Failed to remove VPN configuration."
                    )
                }

                setTunnel(nil, shouldRefreshTunnelState: false)

                completion()
            }
        }
    }
}

#if DEBUG

    // MARK: - Simulations

    extension TunnelManager {
        enum AccountExpirySimulationOption {
            case closeToExpiry(days: Int)
            case expired
            case active

            fileprivate var date: Date? {
                let calendar = Calendar.current
                let now = Date()

                switch self {
                case .active:
                    return calendar.date(byAdding: .year, value: 1, to: now)

                case let .closeToExpiry(days):
                    return calendar.date(
                        byAdding: DateComponents(day: days, second: 5),
                        to: now
                    )

                case .expired:
                    return calendar.date(byAdding: .minute, value: -1, to: now)
                }
            }
        }

        /**
        
         This function simulates account state transitions. The change is not permanent and any call to
         `updateAccountData()` will overwrite it, but it's usually enough for quick testing.
        
         It can be invoked somewhere in `initTunnelManagerOperation` (`AppDelegate`) after tunnel manager is fully
         initialized. The following code snippet can be used to cycle through various states:
        
         ```
         func delay(seconds: UInt) async throws {
         try await Task.sleep(nanoseconds: UInt64(seconds) * 1_000_000_000)
         }
        
         Task {
         print("Wait 5 seconds")
         try await delay(seconds: 5)
        
         print("Simulate active account")
         self.tunnelManager.simulateAccountExpiration(option: .active)
         try await delay(seconds: 5)
        
         print("Simulate close to expiry")
         self.tunnelManager.simulateAccountExpiration(option: .closeToExpiry)
         try await delay(seconds: 10)
        
         print("Simulate expired account")
         self.tunnelManager.simulateAccountExpiration(option: .expired)
         try await delay(seconds: 5)
        
         print("Simulate active account")
         self.tunnelManager.simulateAccountExpiration(option: .active)
         }
         ```
        
         Another way to invoke this code is to pause debugger and run it directly:
        
         ```
         command alias swift expression -l Swift -O --
        
         swift import MullvadVPN
         swift (UIApplication.shared.delegate as? AppDelegate)?.tunnelManager.simulateAccountExpiration(option: .closeToExpiry)
         ```
        
         */
        func simulateAccountExpiration(option: AccountExpirySimulationOption) {
            scheduleDeviceStateUpdate(taskName: "Simulating account expiry", reconnectTunnel: false) { deviceState in
                guard case .loggedIn(var accountData, let deviceData) = deviceState, let date = option.date else {
                    return
                }

                accountData.expiry = date

                deviceState = .loggedIn(accountData, deviceData)
            }
        }
    }

#endif

private struct TunnelInteractorProxy: TunnelInteractor {
    private let tunnelManager: TunnelManager

    init(_ tunnelManager: TunnelManager) {
        self.tunnelManager = tunnelManager
    }

    var tunnel: (any TunnelProtocol)? {
        tunnelManager.tunnel
    }

    var backgroundTaskProvider: BackgroundTaskProviding {
        tunnelManager.backgroundTaskProvider
    }

    func getPersistentTunnels() -> [any TunnelProtocol] {
        tunnelManager.tunnelStore.getPersistentTunnels()
    }

    func createNewTunnel() -> any TunnelProtocol {
        tunnelManager.tunnelStore.createNewTunnel()
    }

    func setTunnel(_ tunnel: (any TunnelProtocol)?, shouldRefreshTunnelState: Bool) {
        tunnelManager.setTunnel(tunnel, shouldRefreshTunnelState: shouldRefreshTunnelState)
    }

    var tunnelStatus: TunnelStatus {
        tunnelManager.tunnelStatus
    }

    func updateTunnelStatus(_ block: @Sendable (inout TunnelStatus) -> Void) -> TunnelStatus {
        tunnelManager.setTunnelStatus(block)
    }

    var isConfigurationLoaded: Bool {
        tunnelManager.isConfigurationLoaded
    }

    var settings: LatestTunnelSettings {
        tunnelManager.settings
    }

    var deviceState: DeviceState {
        tunnelManager.deviceState
    }

    func setConfigurationLoaded() {
        tunnelManager.setConfigurationLoaded()
    }

    func setSettings(_ settings: LatestTunnelSettings, persist: Bool) {
        tunnelManager.setSettings(settings, persist: persist)
    }

    func setDeviceState(_ deviceState: DeviceState, persist: Bool) {
        tunnelManager.setDeviceState(deviceState, persist: persist)
    }

    func removeLastUsedAccount() {
        tunnelManager.removeLastUsedAccount()
    }

    func startTunnel() {
        tunnelManager.startTunnel()
    }

    func prepareForVPNConfigurationDeletion() {
        tunnelManager.prepareForVPNConfigurationDeletion()
    }

    func selectRelays() throws -> SelectedRelays {
        try tunnelManager.selectRelays(tunnelSettings: tunnelManager.settings)
    }

    func handleRestError(_ error: Error) {
        tunnelManager.handleRestError(error)
    }
}