This repository was archived by the owner on Feb 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathVPNMetadataCollector.swift
341 lines (287 loc) · 12.3 KB
/
VPNMetadataCollector.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
//
// VPNMetadataCollector.swift
//
// Copyright © 2023 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import AppKit
import Common
import LoginItems
import NetworkProtection
import NetworkExtension
import NetworkProtectionIPC
import NetworkProtectionUI
import Subscription
struct VPNMetadata: Encodable {
struct AppInfo: Encodable {
let appVersion: String
let lastAgentVersionRun: String
let lastExtensionVersionRun: String
let isInternalUser: Bool
let isInApplicationsDirectory: Bool
}
struct DeviceInfo: Encodable {
let osVersion: String
let buildFlavor: String
let lowPowerModeEnabled: Bool
let cpuArchitecture: String
}
struct NetworkInfo: Encodable {
let currentPath: String
}
struct VPNState: Encodable {
let onboardingState: String
let connectionState: String
let lastStartErrorDescription: String
let lastTunnelErrorDescription: String
let lastKnownFailureDescription: String
let connectedServer: String
let connectedServerIP: String
}
struct VPNSettingsState: Encodable {
let connectOnLoginEnabled: Bool
let includeAllNetworksEnabled: Bool
let enforceRoutesEnabled: Bool
let excludeLocalNetworksEnabled: Bool
let notifyStatusChangesEnabled: Bool
let showInMenuBarEnabled: Bool
let selectedServer: String
let selectedEnvironment: String
let customDNS: Bool
}
struct LoginItemState: Encodable {
let vpnMenuState: String
let vpnMenuIsRunning: Bool
let notificationsAgentState: String
let notificationsAgentIsRunning: Bool
}
struct PrivacyProInfo: Encodable {
let hasPrivacyProAccount: Bool
let hasVPNEntitlement: Bool
}
let appInfo: AppInfo
let deviceInfo: DeviceInfo
let networkInfo: NetworkInfo
let vpnState: VPNState
let vpnSettingsState: VPNSettingsState
let loginItemState: LoginItemState
let privacyProInfo: PrivacyProInfo
func toPrettyPrintedJSON() -> String? {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let encodedMetadata = try? encoder.encode(self) else {
assertionFailure("Failed to encode metadata")
return nil
}
return String(data: encodedMetadata, encoding: .utf8)
}
func toBase64() -> String {
let encoder = JSONEncoder()
do {
let encodedMetadata = try encoder.encode(self)
return encodedMetadata.base64EncodedString()
} catch {
return "Failed to encode metadata to JSON, error message: \(error.localizedDescription)"
}
}
}
protocol VPNMetadataCollector {
func collectVPNMetadata() async -> VPNMetadata
}
final class DefaultVPNMetadataCollector: VPNMetadataCollector {
private let statusReporter: NetworkProtectionStatusReporter
private let ipcClient: VPNControllerXPCClient
private let defaults: UserDefaults
private let accountManager: AccountManager
private let settings: VPNSettings
init(defaults: UserDefaults = .netP,
accountManager: AccountManager) {
let ipcClient = VPNControllerXPCClient.shared
ipcClient.register { _ in }
self.accountManager = accountManager
self.ipcClient = ipcClient
self.defaults = defaults
self.statusReporter = DefaultNetworkProtectionStatusReporter(
statusObserver: ipcClient.connectionStatusObserver,
serverInfoObserver: ipcClient.serverInfoObserver,
connectionErrorObserver: ipcClient.connectionErrorObserver,
connectivityIssuesObserver: ConnectivityIssueObserverThroughDistributedNotifications(),
controllerErrorMessageObserver: ControllerErrorMesssageObserverThroughDistributedNotifications(),
dataVolumeObserver: ipcClient.dataVolumeObserver,
knownFailureObserver: KnownFailureObserverThroughDistributedNotifications()
)
// Force refresh just in case. A refresh is requested when the IPC client is created, but distributed notifications don't guarantee delivery
// so we'll play it safe and add one more attempt.
self.statusReporter.forceRefresh()
self.settings = VPNSettings(defaults: defaults)
updateSettings()
}
func updateSettings() {
let subscriptionAppGroup = Bundle.main.appGroup(bundle: .subs)
let subscriptionUserDefaults = UserDefaults(suiteName: subscriptionAppGroup)!
let subscriptionEnvironment = DefaultSubscriptionManager.getSavedOrDefaultEnvironment(userDefaults: subscriptionUserDefaults)
settings.alignTo(subscriptionEnvironment: subscriptionEnvironment)
}
@MainActor
func collectVPNMetadata() async -> VPNMetadata {
let appInfoMetadata = collectAppInfoMetadata()
let deviceInfoMetadata = collectDeviceInfoMetadata()
let networkInfoMetadata = await collectNetworkInformation()
let vpnState = await collectVPNState()
let vpnSettingsState = collectVPNSettingsState()
let loginItemState = collectLoginItemState()
let privacyProInfo = await collectPrivacyProInfo()
return VPNMetadata(
appInfo: appInfoMetadata,
deviceInfo: deviceInfoMetadata,
networkInfo: networkInfoMetadata,
vpnState: vpnState,
vpnSettingsState: vpnSettingsState,
loginItemState: loginItemState,
privacyProInfo: privacyProInfo
)
}
// MARK: - Metadata Collection
private func collectAppInfoMetadata() -> VPNMetadata.AppInfo {
let appVersion = AppVersion.shared.versionAndBuildNumber
let versionStore = NetworkProtectionLastVersionRunStore(userDefaults: defaults)
let isInternalUser = NSApp.delegateTyped.internalUserDecider.isInternalUser
let isInApplicationsDirectory = Bundle.main.isInApplicationsDirectory
return .init(
appVersion: appVersion,
lastAgentVersionRun: versionStore.lastAgentVersionRun ?? "none",
lastExtensionVersionRun: versionStore.lastExtensionVersionRun ?? "none",
isInternalUser: isInternalUser,
isInApplicationsDirectory: isInApplicationsDirectory
)
}
private func collectDeviceInfoMetadata() -> VPNMetadata.DeviceInfo {
let buildFlavor = AppVersion.shared.buildType
let osVersion = AppVersion.shared.osVersion
let lowPowerModeEnabled: Bool
if #available(macOS 12.0, *) {
lowPowerModeEnabled = ProcessInfo.processInfo.isLowPowerModeEnabled
} else {
lowPowerModeEnabled = false
}
let architecture = getMachineArchitecture()
return .init(osVersion: osVersion, buildFlavor: buildFlavor, lowPowerModeEnabled: lowPowerModeEnabled, cpuArchitecture: architecture)
}
private func getMachineArchitecture() -> String {
#if arch(arm)
return "arm"
#elseif arch(arm64)
return "arm64"
#elseif arch(i386)
return "i386"
#elseif arch(x86_64)
return "x86_64"
#else
return "unknown"
#endif
}
func collectNetworkInformation() async -> VPNMetadata.NetworkInfo {
let monitor = NWPathMonitor()
monitor.start(queue: DispatchQueue(label: "VPNMetadataCollector.NWPathMonitor.paths"))
let startTime = CFAbsoluteTimeGetCurrent()
while true {
if !monitor.currentPath.availableInterfaces.isEmpty {
let path = monitor.currentPath
monitor.cancel()
return .init(currentPath: path.anonymousDescription)
}
// Wait up to 3 seconds to fetch the path.
let currentExecutionTime = CFAbsoluteTimeGetCurrent() - startTime
if currentExecutionTime >= 3.0 {
return .init(currentPath: "Timed out fetching path")
}
}
}
@MainActor
func collectVPNState() async -> VPNMetadata.VPNState {
let onboardingState: String
switch defaults.networkProtectionOnboardingStatus {
case .completed:
onboardingState = "complete"
case .isOnboarding(let step):
switch step {
case .userNeedsToAllowExtension:
onboardingState = "pending-extension-approval"
case .userNeedsToAllowVPNConfiguration:
onboardingState = "pending-vpn-approval"
}
}
let errorHistory = VPNOperationErrorHistory(ipcClient: ipcClient, defaults: defaults)
let connectionState = String(describing: statusReporter.statusObserver.recentValue)
let lastTunnelErrorDescription = await errorHistory.lastTunnelErrorDescription
let lastKnownFailureDescription = NetworkProtectionKnownFailureStore().lastKnownFailure?.description ?? "none"
let connectedServer = statusReporter.serverInfoObserver.recentValue.serverLocation?.serverLocation ?? "none"
let connectedServerIP = statusReporter.serverInfoObserver.recentValue.serverAddress ?? "none"
return .init(onboardingState: onboardingState,
connectionState: connectionState,
lastStartErrorDescription: errorHistory.lastStartErrorDescription,
lastTunnelErrorDescription: lastTunnelErrorDescription,
lastKnownFailureDescription: lastKnownFailureDescription,
connectedServer: connectedServer,
connectedServerIP: connectedServerIP)
}
func collectLoginItemState() -> VPNMetadata.LoginItemState {
let vpnMenuState = String(describing: LoginItem.vpnMenu.status)
let vpnMenuIsRunning = !NSRunningApplication.runningApplications(withBundleIdentifier: LoginItem.vpnMenu.agentBundleID).isEmpty
#if NETP_SYSTEM_EXTENSION
let notificationsAgentState = String(describing: LoginItem.notificationsAgent.status)
let notificationsAgentIsRunning = !NSRunningApplication.runningApplications(withBundleIdentifier: LoginItem.notificationsAgent.agentBundleID).isEmpty
return .init(
vpnMenuState: vpnMenuState,
vpnMenuIsRunning: vpnMenuIsRunning,
notificationsAgentState: notificationsAgentState,
notificationsAgentIsRunning: notificationsAgentIsRunning)
#else
return .init(
vpnMenuState: vpnMenuState,
vpnMenuIsRunning: vpnMenuIsRunning,
notificationsAgentState: "not-required",
notificationsAgentIsRunning: false
)
#endif
}
func collectVPNSettingsState() -> VPNMetadata.VPNSettingsState {
return .init(
connectOnLoginEnabled: settings.connectOnLogin,
includeAllNetworksEnabled: settings.includeAllNetworks,
enforceRoutesEnabled: settings.enforceRoutes,
excludeLocalNetworksEnabled: settings.excludeLocalNetworks,
notifyStatusChangesEnabled: settings.notifyStatusChanges,
showInMenuBarEnabled: settings.showInMenuBar,
selectedServer: settings.selectedServer.stringValue ?? "automatic",
selectedEnvironment: settings.selectedEnvironment.rawValue,
customDNS: settings.dnsSettings.usesCustomDNS
)
}
func collectPrivacyProInfo() async -> VPNMetadata.PrivacyProInfo {
let hasVPNEntitlement = (try? await accountManager.hasEntitlement(forProductName: .networkProtection).get()) ?? false
return .init(
hasPrivacyProAccount: accountManager.isUserAuthenticated,
hasVPNEntitlement: hasVPNEntitlement
)
}
}
// MARK: - Unified feedback form support
extension VPNMetadata: UnifiedFeedbackMetadata {}
extension DefaultVPNMetadataCollector: UnifiedMetadataCollector {
func collectMetadata() async -> VPNMetadata {
await collectVPNMetadata()
}
}