summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Notifications/Notification Providers/TunnelStatusNotificationProvider.swift
blob: 12d626762e794b4cc718f3a0cd1f8307136e61b2 (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
//
//  TunnelStatusNotificationProvider.swift
//  TunnelStatusNotificationProvider
//
//  Created by pronebird on 20/08/2021.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import PacketTunnelCore
import UIKit

final class TunnelStatusNotificationProvider: NotificationProvider, InAppNotificationProvider, @unchecked Sendable {
    enum ActionIdentifier: String {
        case showVPNSettings
    }

    private var isWaitingForConnectivity = false
    private var noNetwork = false
    private var packetTunnelError: BlockedStateReason?
    private var tunnelManagerError: Error?
    private var tunnelObserver: TunnelBlockObserver?

    override var identifier: NotificationProviderIdentifier {
        .tunnelStatusNotificationProvider
    }

    override var priority: NotificationPriority {
        .critical
    }

    var notificationDescriptor: InAppNotificationDescriptor? {
        if let packetTunnelError {
            return notificationDescription(for: packetTunnelError)
        } else if let tunnelManagerError {
            return notificationDescription(for: tunnelManagerError)
        } else if isWaitingForConnectivity {
            return connectivityNotificationDescription()
        } else if noNetwork {
            return noNetworkNotificationDescription()
        } else {
            return nil
        }
    }

    init(tunnelManager: TunnelManager) {
        super.init()

        let tunnelObserver = TunnelBlockObserver(
            didLoadConfiguration: { [weak self] tunnelManager in
                self?.handleTunnelStatus(tunnelManager.tunnelStatus)
            },
            didUpdateTunnelStatus: { [weak self] _, tunnelStatus in
                self?.handleTunnelStatus(tunnelStatus)
            },
            didFailWithError: { [weak self] _, error in
                self?.tunnelManagerError = error
            }
        )
        self.tunnelObserver = tunnelObserver

        tunnelManager.addObserver(tunnelObserver)
    }

    // MARK: - Private

    private func handleTunnelStatus(_ tunnelStatus: TunnelStatus) {
        let invalidateForTunnelError = updateLastTunnelError(tunnelStatus.state)
        let invalidateForManagerError = updateTunnelManagerError(tunnelStatus.state)
        let invalidateForConnectivity = updateConnectivity(tunnelStatus.state)
        let invalidateForNetwork = updateNetwork(tunnelStatus.state)

        if invalidateForTunnelError || invalidateForManagerError || invalidateForConnectivity || invalidateForNetwork {
            invalidate()
        }
    }

    private func updateLastTunnelError(_ tunnelState: TunnelState) -> Bool {
        let lastTunnelError = tunnelError(from: tunnelState)

        if packetTunnelError != lastTunnelError {
            packetTunnelError = lastTunnelError

            return true
        }

        return false
    }

    private func updateConnectivity(_ tunnelState: TunnelState) -> Bool {
        let isWaitingState = tunnelState == .waitingForConnectivity(.noConnection)

        if isWaitingForConnectivity != isWaitingState {
            isWaitingForConnectivity = isWaitingState
            return true
        }

        return false
    }

    private func updateNetwork(_ tunnelState: TunnelState) -> Bool {
        let isWaitingState = tunnelState == .waitingForConnectivity(.noNetwork)

        if noNetwork != isWaitingState {
            noNetwork = isWaitingState
            return true
        }

        return false
    }

    private func updateTunnelManagerError(_ tunnelState: TunnelState) -> Bool {
        switch tunnelState {
        case .connecting, .connected, .reconnecting:
            // As of now, tunnel manager error can be received only when starting or stopping
            // the tunnel. Make sure to reset it on each connection attempt.
            if tunnelManagerError != nil {
                tunnelManagerError = nil
                return true
            }

        default:
            break
        }

        return false
    }

    // Extracts the blocked state reason from tunnel state with a few exceptions.
    // We already have dedicated screens for .accountExpired and .deviceRevoked,
    // so no need to show banners as well.
    private func tunnelError(from tunnelState: TunnelState) -> BlockedStateReason? {
        let errorsToIgnore: [BlockedStateReason] = [.accountExpired, .deviceRevoked]

        if case let .error(blockedStateReason) = tunnelState, !errorsToIgnore.contains(blockedStateReason) {
            return blockedStateReason
        }

        return nil
    }

    private func notificationDescription(for packetTunnelError: BlockedStateReason) -> InAppNotificationDescriptor {
        let tapAction: InAppNotificationAction? =
            switch packetTunnelError {
            case .noRelaysSatisfyingPortConstraints:
                InAppNotificationAction {
                    NotificationManager.shared
                        .notificationProvider(
                            self,
                            didReceiveAction: "\(ActionIdentifier.showVPNSettings)"
                        )
                }
            default:
                nil
            }
        return InAppNotificationDescriptor(
            identifier: identifier,
            style: .error,
            title: NSLocalizedString("BLOCKING INTERNET", comment: ""),
            body: createNotificationBody(localizedReasonForBlockedStateError(packetTunnelError)),
            tapAction: tapAction
        )
    }

    private func createNotificationBody(_ string: String) -> NSAttributedString {
        NSAttributedString(
            markdownString: string,
            options: MarkdownStylingOptions(font: UIFont.preferredFont(forTextStyle: .body)),
            applyEffect: { markdownType, _ in
                guard case .bold = markdownType else { return [:] }
                return [.foregroundColor: UIColor.InAppNotificationBanner.titleColor]
            }
        )
    }

    private func notificationDescription(for error: Error) -> InAppNotificationDescriptor {
        let body: String

        if let startError = error as? StartTunnelError {
            body = String(
                format: NSLocalizedString("Failed to start the tunnel: %@.", comment: ""),
                startError.underlyingError?.localizedDescription ?? ""
            )
        } else if let stopError = error as? StopTunnelError {
            body = String(
                format: NSLocalizedString("Failed to stop the tunnel: %@.", comment: ""),
                stopError.underlyingError?.localizedDescription ?? ""
            )
        } else {
            body = error.localizedDescription
        }

        return InAppNotificationDescriptor(
            identifier: identifier,
            style: .error,
            title: NSLocalizedString("TUNNEL ERROR", comment: ""),
            body: .init(string: body)
        )
    }

    private func connectivityNotificationDescription() -> InAppNotificationDescriptor {
        InAppNotificationDescriptor(
            identifier: identifier,
            style: .warning,
            title: NSLocalizedString("NETWORK ISSUES", comment: ""),
            body: .init(
                string: NSLocalizedString(
                    """
                    Your device is offline. The tunnel will automatically connect once your device is back online.
                    """,
                    comment: ""
                )
            )
        )
    }

    private func noNetworkNotificationDescription() -> InAppNotificationDescriptor {
        InAppNotificationDescriptor(
            identifier: identifier,
            style: .warning,
            title: NSLocalizedString("NETWORK ISSUES", comment: ""),
            body: .init(
                string: NSLocalizedString(
                    """
                    Your device is offline. Try connecting again when the device \
                    has access to Internet.
                    """,
                    comment: ""
                )
            )
        )
    }

    private func localizedReasonForBlockedStateError(_ error: BlockedStateReason) -> String {
        switch error {
        case .outdatedSchema:
            NSLocalizedString(
                "Unable to start tunnel connection after update. Please disconnect and reconnect.",
                comment: ""
            )
        case .noRelaysSatisfyingFilterConstraints:
            NSLocalizedString("No servers match your location filter. Try changing filter settings.", comment: "")
        case .multihopEntryEqualsExit:
            NSLocalizedString(
                "The entry and exit servers cannot be the same. Try changing one to a new server or location.",
                comment: ""
            )
        case .noRelaysSatisfyingDaitaConstraints:
            NSLocalizedString(
                "No DAITA compatible servers match your location settings. Try changing location.",
                comment: ""
            )
        case .noRelaysSatisfyingObfuscationSettings:
            NSLocalizedString(
                "No servers match your obfuscation settings. Try changing location or obfuscation method.",
                comment: ""
            )
        case .noRelaysSatisfyingConstraints:
            NSLocalizedString("No servers match your settings, try changing server or other settings.", comment: "")
        case .noRelaysSatisfyingPortConstraints:
            NSLocalizedString(
                "The selected WireGuard port is not supported, please change it under **VPN settings**.",
                comment: ""
            )
        case .invalidAccount:
            NSLocalizedString(
                "You are logged in with an invalid account number. Please log out and try another one.",
                comment: ""
            )
        case .deviceLoggedOut:
            NSLocalizedString("Unable to authenticate account. Please log out and log back in.", comment: "")
        default:
            NSLocalizedString("Unable to start tunnel connection. Please send a problem report.", comment: "")
        }
    }
}