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 pathTunnelControllerIPCService.swift
295 lines (253 loc) · 9.46 KB
/
TunnelControllerIPCService.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
//
// TunnelControllerIPCService.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 Combine
import Foundation
import NetworkProtection
import NetworkProtectionIPC
import NetworkProtectionUI
import PixelKit
import UDSHelper
/// Takes care of handling incoming IPC requests from clients that need to be relayed to the tunnel, and handling state
/// changes that need to be relayed back to IPC clients.
///
/// This also includes the tunnel settings which are controller through shared `UserDefaults` as a form of IPC.
/// Clients can edit those defaults and this class will observe the changes and relay them to the runnel.
///
final class TunnelControllerIPCService {
private let tunnelController: NetworkProtectionTunnelController
private let networkExtensionController: NetworkExtensionController
private let uninstaller: VPNUninstalling
private let server: NetworkProtectionIPC.VPNControllerXPCServer
private let statusReporter: NetworkProtectionStatusReporter
private var cancellables = Set<AnyCancellable>()
private let defaults: UserDefaults
private let pixelKit: PixelKit?
private let udsServer: UDSServer
enum IPCError: SilentErrorConvertible {
case versionMismatched
var asSilentError: KnownFailure.SilentError? {
switch self {
case .versionMismatched: return .loginItemVersionMismatched
}
}
}
enum UDSError: PixelKitEventV2 {
case udsServerStartFailure(_ error: Error)
var name: String {
switch self {
case .udsServerStartFailure:
return "vpn_agent_uds_server_start_failure"
}
}
var error: Error? {
switch self {
case .udsServerStartFailure(let error):
return error
}
}
var parameters: [String: String]? {
return nil
}
}
init(tunnelController: NetworkProtectionTunnelController,
uninstaller: VPNUninstalling,
networkExtensionController: NetworkExtensionController,
statusReporter: NetworkProtectionStatusReporter,
fileManager: FileManager = .default,
defaults: UserDefaults = .netP,
pixelKit: PixelKit? = .shared) {
self.tunnelController = tunnelController
self.uninstaller = uninstaller
self.networkExtensionController = networkExtensionController
server = .init(machServiceName: Bundle.main.bundleIdentifier!)
self.statusReporter = statusReporter
self.defaults = defaults
self.pixelKit = pixelKit
udsServer = UDSServer(socketFileURL: VPNIPCResources.socketFileURL)
subscribeToErrorChanges()
subscribeToStatusUpdates()
subscribeToServerChanges()
subscribeToKnownFailureUpdates()
subscribeToDataVolumeUpdates()
server.serverDelegate = self
}
public func activate() {
server.activate()
do {
try udsServer.start { [weak self] message in
guard let self else { return nil }
let command = try JSONDecoder().decode(VPNIPCClientCommand.self, from: message)
switch command {
case .uninstall(let component):
try await uninstall(component)
return nil
case .quit:
quitAgent()
return nil
}
}
} catch {
pixelKit?.fire(UDSError.udsServerStartFailure(error))
assertionFailure(error.localizedDescription)
}
}
private func subscribeToErrorChanges() {
statusReporter.connectionErrorObserver.publisher
.subscribe(on: DispatchQueue.main)
.sink { [weak self] error in
self?.server.errorChanged(error)
}
.store(in: &cancellables)
}
private func subscribeToServerChanges() {
statusReporter.serverInfoObserver.publisher
.subscribe(on: DispatchQueue.main)
.sink { [weak self] serverInfo in
self?.server.serverInfoChanged(serverInfo)
}
.store(in: &cancellables)
}
private func subscribeToStatusUpdates() {
statusReporter.statusObserver.publisher
.subscribe(on: DispatchQueue.main)
.sink { [weak self] status in
self?.server.statusChanged(status)
}
.store(in: &cancellables)
}
private func subscribeToKnownFailureUpdates() {
statusReporter.knownFailureObserver.publisher
.subscribe(on: DispatchQueue.main)
.sink { [weak self] failure in
self?.server.knownFailureUpdated(failure)
}
.store(in: &cancellables)
}
private func subscribeToDataVolumeUpdates() {
statusReporter.dataVolumeObserver.publisher
.subscribe(on: DispatchQueue.main)
.sink { [weak self] dataVolume in
self?.server.dataVolumeUpdated(dataVolume)
}
.store(in: &cancellables)
}
}
// MARK: - Requests from the client
extension TunnelControllerIPCService: XPCServerInterface {
func register(completion: @escaping (Error?) -> Void) {
register(version: version, bundlePath: bundlePath, completion: completion)
}
func register(version: String, bundlePath: String, completion: @escaping (Error?) -> Void) {
server.serverInfoChanged(statusReporter.serverInfoObserver.recentValue)
server.statusChanged(statusReporter.statusObserver.recentValue)
if self.version != version {
let error = TunnelControllerIPCService.IPCError.versionMismatched
NetworkProtectionKnownFailureStore().lastKnownFailure = KnownFailure(error)
completion(error)
} else {
completion(nil)
}
}
func start(completion: @escaping (Error?) -> Void) {
Task {
await tunnelController.start()
}
// For IPC requests, completion means the IPC request was processed, and NOT
// that the requested operation was executed fully. Failure to complete the
// operation will be handled entirely within the tunnel controller.
completion(nil)
}
func stop(completion: @escaping (Error?) -> Void) {
Task {
await tunnelController.stop()
}
// For IPC requests, completion means the IPC request was processed, and NOT
// that the requested operation was executed fully. Failure to complete the
// operation will be handled entirely within the tunnel controller.
completion(nil)
}
func fetchLastError(completion: @escaping (Error?) -> Void) {
Task {
guard #available(macOS 13.0, *),
let connection = await tunnelController.connection else {
completion(nil)
return
}
connection.fetchLastDisconnectError(completionHandler: completion)
}
}
func resetAll(uninstallSystemExtension: Bool) async {
try? await networkExtensionController.deactivateSystemExtension()
}
func command(_ command: VPNCommand) async throws {
try await tunnelController.relay(command)
switch command {
case .removeSystemExtension:
try await uninstall(.systemExtension)
case .expireRegistrationKey:
// Intentional no-op: handled by the extension
break
case .sendTestNotification:
// Intentional no-op: handled by the extension
break
case .removeVPNConfiguration:
try await uninstall(.configuration)
case .restartAdapter:
// Intentional no-op: handled by the extension
break
case .uninstallVPN:
try await uninstall(.all)
case .disableConnectOnDemandAndShutDown:
// Not implemented on macOS yet
break
case .quitAgent:
quitAgent()
}
}
private func uninstall(_ component: VPNUninstallComponent) async throws {
switch component {
case .all:
try await uninstaller.uninstall(includingSystemExtension: true)
case .configuration:
try await uninstaller.removeVPNConfiguration()
case .systemExtension:
try await uninstaller.removeSystemExtension()
}
}
private func quitAgent() {
exit(EXIT_SUCCESS)
}
}
// MARK: - Error Handling
extension TunnelControllerIPCService.IPCError: LocalizedError, CustomNSError {
var errorDescription: String? {
switch self {
case .versionMismatched: return "Login item version mismatched"
}
}
var errorCode: Int {
switch self {
case .versionMismatched: return 0
}
}
var errorUserInfo: [String: Any] {
switch self {
case .versionMismatched: return [:]
}
}
}