summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/AppDelegate.swift
blob: 4c99cfd8576557fe710f7eb9f35c9e2242226e8d (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
//
//  AppDelegate.swift
//  MullvadVPN
//
//  Created by pronebird on 19/03/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import BackgroundTasks
import MullvadLogging
import MullvadREST
import MullvadTransport
import MullvadTypes
import Operations
import RelayCache
import StoreKit
import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, StorePaymentManagerDelegate {
    private var logger: Logger!

    #if targetEnvironment(simulator)
    private var simulatorTunnelProviderHost: SimulatorTunnelProviderHost?
    #endif

    private let operationQueue = AsyncOperationQueue.makeSerial()

    private(set) var tunnelStore: TunnelStore!
    private(set) var tunnelManager: TunnelManager!
    private(set) var addressCache: REST.AddressCache!

    private var proxyFactory: REST.ProxyFactory!
    private(set) var apiProxy: REST.APIProxy!
    private(set) var accountsProxy: REST.AccountsProxy!
    private(set) var devicesProxy: REST.DevicesProxy!

    private(set) var addressCacheTracker: AddressCacheTracker!
    private(set) var relayCacheTracker: RelayCacheTracker!
    private(set) var storePaymentManager: StorePaymentManager!
    private var transportMonitor: TransportMonitor!
    private var relayConstraintsObserver: TunnelBlockObserver!
    private let migrationManager = MigrationManager()

    // MARK: - Application lifecycle

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        configureLogging()

        logger = Logger(label: "AppDelegate")

        let containerURL = ApplicationConfiguration.containerURL

        addressCache = REST.AddressCache(canWriteToCache: true, cacheDirectory: containerURL)
        addressCache.loadFromFile()

        proxyFactory = REST.ProxyFactory.makeProxyFactory(
            transportProvider: REST.AnyTransportProvider { [weak self] in
                return self?.transportMonitor.makeTransport()
            },
            addressCache: addressCache
        )

        apiProxy = proxyFactory.createAPIProxy()
        accountsProxy = proxyFactory.createAccountsProxy()
        devicesProxy = proxyFactory.createDevicesProxy()

        let relayCache = RelayCache(cacheDirectory: containerURL)
        relayCacheTracker = RelayCacheTracker(relayCache: relayCache, application: application, apiProxy: apiProxy)

        addressCacheTracker = AddressCacheTracker(
            application: application,
            apiProxy: apiProxy,
            store: addressCache
        )

        tunnelStore = TunnelStore(application: application)

        tunnelManager = TunnelManager(
            application: application,
            tunnelStore: tunnelStore,
            relayCacheTracker: relayCacheTracker,
            accountsProxy: accountsProxy,
            devicesProxy: devicesProxy,
            apiProxy: apiProxy
        )

        let constraintsUpdater = RelayConstraintsUpdater()
        relayConstraintsObserver = TunnelBlockObserver(didUpdateTunnelSettings: { _, settings in
            constraintsUpdater.onNewConstraints?(settings.relayConstraints)
        })

        storePaymentManager = StorePaymentManager(
            application: application,
            queue: .default(),
            apiProxy: apiProxy,
            accountsProxy: accountsProxy
        )

        let urlSessionTransport = URLSessionTransport(urlSession: REST.makeURLSession())
        let shadowsocksCache = ShadowsocksConfigurationCache(cacheDirectory: containerURL)
        let transportProvider = TransportProvider(
            urlSessionTransport: urlSessionTransport,
            relayCache: relayCache,
            addressCache: addressCache,
            shadowsocksCache: shadowsocksCache,
            constraintsUpdater: constraintsUpdater
        )

        tunnelManager.addObserver(relayConstraintsObserver)

        transportMonitor = TransportMonitor(
            tunnelManager: tunnelManager,
            tunnelStore: tunnelStore,
            transportProvider: transportProvider
        )

        #if targetEnvironment(simulator)
        // Configure mock tunnel provider on simulator
        simulatorTunnelProviderHost = SimulatorTunnelProviderHost(
            relayCacheTracker: relayCacheTracker,
            transportProvider: transportProvider
        )
        SimulatorTunnelProvider.shared.delegate = simulatorTunnelProviderHost
        #endif

        registerBackgroundTasks()
        setupPaymentHandler()
        setupNotifications()
        addApplicationNotifications(application: application)

        startInitialization(application: application)

        return true
    }

    // MARK: - UISceneSession lifecycle

    func application(
        _ application: UIApplication,
        configurationForConnecting connectingSceneSession: UISceneSession,
        options: UIScene.ConnectionOptions
    ) -> UISceneConfiguration {
        let sceneConfiguration = UISceneConfiguration(
            name: "Default Configuration",
            sessionRole: connectingSceneSession.role
        )
        sceneConfiguration.delegateClass = SceneDelegate.self

        return sceneConfiguration
    }

    func application(
        _ application: UIApplication,
        didDiscardSceneSessions sceneSessions: Set<UISceneSession>
    ) {}

    // MARK: - Notifications

    @objc private func didBecomeActive(_ notification: Notification) {
        tunnelManager.startPeriodicPrivateKeyRotation()
        relayCacheTracker.startPeriodicUpdates()
        addressCacheTracker.startPeriodicUpdates()
    }

    @objc private func willResignActive(_ notification: Notification) {
        tunnelManager.stopPeriodicPrivateKeyRotation()
        relayCacheTracker.stopPeriodicUpdates()
        addressCacheTracker.stopPeriodicUpdates()
    }

    @objc private func didEnterBackground(_ notification: Notification) {
        scheduleBackgroundTasks()
    }

    // MARK: - Background tasks

    private func registerBackgroundTasks() {
        registerAppRefreshTask()
        registerAddressCacheUpdateTask()
        registerKeyRotationTask()
    }

    private func registerAppRefreshTask() {
        let isRegistered = BGTaskScheduler.shared.register(
            forTaskWithIdentifier: BackgroundTask.appRefresh.identifier,
            using: nil
        ) { [self] task in
            let handle = relayCacheTracker.updateRelays { result in
                task.setTaskCompleted(success: result.isSuccess)
            }

            task.expirationHandler = {
                handle.cancel()
            }

            scheduleAppRefreshTask()
        }

        if isRegistered {
            logger.debug("Registered app refresh task.")
        } else {
            logger.error("Failed to register app refresh task.")
        }
    }

    private func registerKeyRotationTask() {
        let isRegistered = BGTaskScheduler.shared.register(
            forTaskWithIdentifier: BackgroundTask.privateKeyRotation.identifier,
            using: nil
        ) { [self] task in
            let handle = tunnelManager.rotatePrivateKey { [self] error in
                scheduleKeyRotationTask()

                task.setTaskCompleted(success: error == nil)
            }

            task.expirationHandler = {
                handle.cancel()
            }
        }

        if isRegistered {
            logger.debug("Registered private key rotation task.")
        } else {
            logger.error("Failed to register private key rotation task.")
        }
    }

    private func registerAddressCacheUpdateTask() {
        let isRegistered = BGTaskScheduler.shared.register(
            forTaskWithIdentifier: BackgroundTask.addressCacheUpdate.identifier,
            using: nil
        ) { [self] task in
            let handle = addressCacheTracker.updateEndpoints { [self] result in
                scheduleAddressCacheUpdateTask()

                task.setTaskCompleted(success: result.isSuccess)
            }

            task.expirationHandler = {
                handle.cancel()
            }
        }

        if isRegistered {
            logger.debug("Registered address cache update task.")
        } else {
            logger.error("Failed to register address cache update task.")
        }
    }

    private func scheduleBackgroundTasks() {
        scheduleAppRefreshTask()
        scheduleKeyRotationTask()
        scheduleAddressCacheUpdateTask()
    }

    private func scheduleAppRefreshTask() {
        do {
            let date = relayCacheTracker.getNextUpdateDate()

            let request = BGAppRefreshTaskRequest(identifier: BackgroundTask.appRefresh.identifier)
            request.earliestBeginDate = date

            logger.debug("Schedule app refresh task at \(date.logFormatDate()).")

            try BGTaskScheduler.shared.submit(request)
        } catch {
            logger.error(error: error, message: "Could not schedule app refresh task.")
        }
    }

    private func scheduleKeyRotationTask() {
        do {
            guard let date = tunnelManager.getNextKeyRotationDate() else {
                return
            }

            let request = BGProcessingTaskRequest(identifier: BackgroundTask.privateKeyRotation.identifier)
            request.requiresNetworkConnectivity = true
            request.earliestBeginDate = date

            logger.debug("Schedule key rotation task at \(date.logFormatDate()).")

            try BGTaskScheduler.shared.submit(request)
        } catch {
            logger.error(error: error, message: "Could not schedule private key rotation task.")
        }
    }

    private func scheduleAddressCacheUpdateTask() {
        do {
            let date = addressCacheTracker.nextScheduleDate()

            let request = BGProcessingTaskRequest(identifier: BackgroundTask.addressCacheUpdate.identifier)
            request.requiresNetworkConnectivity = true
            request.earliestBeginDate = date

            logger.debug("Schedule address cache update task at \(date.logFormatDate()).")

            try BGTaskScheduler.shared.submit(request)
        } catch {
            logger.error(error: error, message: "Could not schedule address cache update task.")
        }
    }

    // MARK: - Private

    private func configureLogging() {
        var loggerBuilder = LoggerBuilder()
        loggerBuilder.addFileOutput(fileURL: ApplicationConfiguration.logFileURL(for: .mainApp))
        #if DEBUG
        loggerBuilder.addOSLogOutput(subsystem: ApplicationTarget.mainApp.bundleIdentifier)
        #endif
        loggerBuilder.install()
    }

    private func addApplicationNotifications(application: UIApplication) {
        let notificationCenter = NotificationCenter.default

        notificationCenter.addObserver(
            self,
            selector: #selector(didBecomeActive(_:)),
            name: UIApplication.didBecomeActiveNotification,
            object: application
        )
        notificationCenter.addObserver(
            self,
            selector: #selector(willResignActive(_:)),
            name: UIApplication.willResignActiveNotification,
            object: application
        )
        notificationCenter.addObserver(
            self,
            selector: #selector(didEnterBackground(_:)),
            name: UIApplication.didEnterBackgroundNotification,
            object: application
        )
    }

    private func setupPaymentHandler() {
        storePaymentManager.delegate = self
        storePaymentManager.addPaymentObserver(tunnelManager)
    }

    private func setupNotifications() {
        NotificationManager.shared.notificationProviders = [
            TunnelStatusNotificationProvider(tunnelManager: tunnelManager),
            AccountExpirySystemNotificationProvider(tunnelManager: tunnelManager),
            AccountExpiryInAppNotificationProvider(tunnelManager: tunnelManager),
            RegisteredDeviceInAppNotificationProvider(tunnelManager: tunnelManager),
        ]
        UNUserNotificationCenter.current().delegate = self
    }

    private func startInitialization(application: UIApplication) {
        let wipeSettingsOperation = getWipeSettingsOperation()

        let loadTunnelStoreOperation = AsyncBlockOperation(dispatchQueue: .main) { [self] finish in
            tunnelStore.loadPersistentTunnels { [self] error in
                if let error {
                    logger.error(
                        error: error,
                        message: "Failed to load persistent tunnels."
                    )
                }
                finish(nil)
            }
        }

        let migrateSettingsOperation = AsyncBlockOperation(dispatchQueue: .main) { [self] finish in
            migrationManager
                .migrateSettings(store: SettingsManager.store, proxyFactory: proxyFactory) { [self] migrationResult in
                    switch migrationResult {
                    case .success:
                        // Tell the tunnel to re-read tunnel configuration after migration.
                        logger.debug("Reconnect the tunnel after settings migration.")
                        tunnelManager.reconnectTunnel(selectNewRelay: true)
                        fallthrough

                    case .nothing:
                        finish(nil)

                    case let .failure(error):
                        let migrationUIHandler = application.connectedScenes.first { $0 is SettingsMigrationUIHandler }
                            as? SettingsMigrationUIHandler

                        if let migrationUIHandler {
                            migrationUIHandler.showMigrationError(error) {
                                finish(error)
                            }
                        } else {
                            finish(error)
                        }
                    }
                }
        }

        migrateSettingsOperation.addDependencies([wipeSettingsOperation, loadTunnelStoreOperation])

        let initTunnelManagerOperation = AsyncBlockOperation(dispatchQueue: .main) { finish in
            self.tunnelManager.loadConfiguration { error in
                // TODO: avoid throwing fatal error and show the problem report UI instead.
                if let error {
                    fatalError(error.localizedDescription)
                }

                self.logger.debug("Finished initialization.")

                NotificationManager.shared.updateNotifications()
                self.storePaymentManager.startPaymentQueueMonitoring()

                finish(nil)
            }
        }
        initTunnelManagerOperation.addDependency(migrateSettingsOperation)

        operationQueue.addOperations(
            [
                wipeSettingsOperation,
                loadTunnelStoreOperation,
                migrateSettingsOperation,
                initTunnelManagerOperation,
            ],
            waitUntilFinished: false
        )
    }

    /// Returns an operation that acts on two conditions:
    /// 1. Has the app been launched at least once after install? (`FirstTimeLaunch.hasFinished`)
    /// 2. Has the app - at some point in time - been updated from a version compatible with wiping settings?
    /// (`SettingsManager.getShouldWipeSettings()`)
    /// If (1) is `false` and (2) is `true`, we know that the app has been freshly installed/reinstalled and is
    /// compatible, thus triggering a settings wipe.
    private func getWipeSettingsOperation() -> AsyncBlockOperation {
        AsyncBlockOperation {
            if !FirstTimeLaunch.hasFinished, SettingsManager.getShouldWipeSettings() {
                if let deviceState = try? SettingsManager.readDeviceState(),
                   let accountData = deviceState.accountData,
                   let deviceData = deviceState.deviceData {
                    _ = self.devicesProxy.deleteDevice(
                        accountNumber: accountData.number,
                        identifier: deviceData.identifier,
                        retryStrategy: .noRetry
                    ) { _ in
                        // Do nothing.
                    }
                }

                SettingsManager.resetStore(completely: true)
            }

            FirstTimeLaunch.setHasFinished()
            SettingsManager.setShouldWipeSettings()
        }
    }

    // MARK: - StorePaymentManagerDelegate

    func storePaymentManager(_ manager: StorePaymentManager, didRequestAccountTokenFor payment: SKPayment) -> String? {
        // Since we do not persist the relation between payment and account number between the
        // app launches, we assume that all successful purchases belong to the active account
        // number.
        tunnelManager.deviceState.accountData?.number
    }

    // MARK: - UNUserNotificationCenterDelegate

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let blockOperation = AsyncBlockOperation(dispatchQueue: .main) {
            NotificationManager.shared.handleSystemNotificationResponse(response)

            completionHandler()
        }

        operationQueue.addOperation(blockOperation)
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.list, .banner, .sound])
    }
}