-
Notifications
You must be signed in to change notification settings - Fork 389
/
Copy pathTunnelMonitor.swift
376 lines (293 loc) · 10.3 KB
/
TunnelMonitor.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
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
//
// TunnelMonitor.swift
// PacketTunnelCore
//
// Created by pronebird on 09/02/2022.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import MullvadTypes
import Network
import NetworkExtension
/// Tunnel monitor.
public final class TunnelMonitor: TunnelMonitorProtocol {
private let tunnelDeviceInfo: TunnelDeviceInfoProtocol
private let nslock = NSLock()
private let timerQueue = DispatchQueue(label: "TunnelMonitor-timerQueue")
private let eventQueue: DispatchQueue
private let timings: TunnelMonitorTimings
private var pinger: PingerProtocol
private var isObservingDefaultPath = false
private var timer: DispatchSourceTimer?
private var state: TunnelMonitorState
private var probeAddress: IPv4Address?
private let logger = Logger(label: "TunnelMonitor")
private var _onEvent: ((TunnelMonitorEvent) -> Void)?
public var onEvent: ((TunnelMonitorEvent) -> Void)? {
get {
nslock.withLock {
return _onEvent
}
}
set {
nslock.withLock {
_onEvent = newValue
}
}
}
public init(
eventQueue: DispatchQueue,
pinger: PingerProtocol,
tunnelDeviceInfo: TunnelDeviceInfoProtocol,
timings: TunnelMonitorTimings
) {
self.eventQueue = eventQueue
self.tunnelDeviceInfo = tunnelDeviceInfo
self.timings = timings
state = TunnelMonitorState(timings: timings)
self.pinger = pinger
self.pinger.onReply = { [weak self] reply in
guard let self else { return }
switch reply {
case let .success(sender, sequenceNumber):
didReceivePing(from: sender, sequenceNumber: sequenceNumber)
case let .parseError(error):
logger.error(error: error, message: "Failed to parse ICMP response.")
}
}
}
deinit {
stop()
}
public func start(probeAddress: IPv4Address) {
nslock.lock()
defer { nslock.unlock() }
if case .stopped = state.connectionState {
logger.debug("Start with address: \(probeAddress).")
} else {
_stop(forRestart: true)
logger.debug("Restart with address: \(probeAddress).")
}
self.probeAddress = probeAddress
state.connectionState = .pendingStart
startMonitoring()
}
public func stop() {
nslock.lock()
defer { nslock.unlock() }
_stop()
}
public func onWake() {
nslock.lock()
defer { nslock.unlock() }
logger.trace("Wake up.")
switch state.connectionState {
case .connecting, .connected:
startConnectivityCheckTimer()
case .waitingConnectivity, .pendingStart, .stopped, .recovering:
break
}
}
public func onSleep() {
nslock.lock()
defer { nslock.unlock() }
logger.trace("Prepare to sleep.")
stopConnectivityCheckTimer()
}
public func handleNetworkPathUpdate(_ networkPath: Network.NWPath.Status) {
nslock.withLock {
let isReachable = networkPath == .satisfied || networkPath == .requiresConnection
switch state.connectionState {
case .pendingStart:
if isReachable {
logger.debug("Start monitoring connection.")
startMonitoring()
} else {
logger.debug("Wait for network to become reachable before starting monitoring.")
state.connectionState = .waitingConnectivity
}
case .waitingConnectivity:
guard isReachable else { return }
logger.debug("Network is reachable. Resume monitoring.")
startMonitoring()
case .connecting, .connected:
guard !isReachable else { return }
logger.debug("Network is unreachable. Pause monitoring.")
state.connectionState = .waitingConnectivity
stopMonitoring(resetRetryAttempt: true)
case .stopped, .recovering:
break
}
}
}
// MARK: - Private
private func _stop(forRestart: Bool = false) {
if case .stopped = state.connectionState {
return
}
if !forRestart {
logger.debug("Stop tunnel monitor.")
}
probeAddress = nil
stopMonitoring(resetRetryAttempt: !forRestart)
state.connectionState = .stopped
}
private func checkConnectivity() {
nslock.lock()
defer { nslock.unlock() }
guard let newStats = getStats(),
state.connectionState == .connecting || state.connectionState == .connected
else { return }
// Check if counters were reset.
let isStatsReset = newStats.bytesReceived < state.netStats.bytesReceived ||
newStats.bytesSent < state.netStats.bytesSent
guard !isStatsReset else {
logger.trace("Stats was being reset.")
state.netStats = newStats
return
}
#if DEBUG
logCounters(currentStats: state.netStats, newStats: newStats)
#endif
let now = Date()
state.updateNetStats(newStats: newStats, now: now)
let timeout = state.getPingTimeout()
let evaluation = state.evaluateConnection(now: now, pingTimeout: timeout)
if evaluation != .ok {
logger.trace("Evaluation: \(evaluation)")
}
switch evaluation {
case .ok:
break
case .pingTimeout:
startConnectionRecovery()
case .suspendHeartbeat:
state.isHeartbeatSuspended = true
case .sendHeartbeatPing, .retryHeartbeatPing, .sendNextPing, .sendInitialPing,
.inboundTrafficTimeout, .trafficTimeout:
if state.isHeartbeatSuspended {
state.isHeartbeatSuspended = false
state.timeoutReference = now
}
sendPing(now: now)
}
}
#if DEBUG
private func logCounters(currentStats: WgStats, newStats: WgStats) {
let rxDelta = newStats.bytesReceived.saturatingSubtraction(currentStats.bytesReceived)
let txDelta = newStats.bytesSent.saturatingSubtraction(currentStats.bytesSent)
guard rxDelta > 0 || txDelta > 0 else { return }
logger.trace(
"""
rx: \(newStats.bytesReceived) (+\(rxDelta)) \
tx: \(newStats.bytesSent) (+\(txDelta))
"""
)
}
#endif
private func startConnectionRecovery() {
stopMonitoring(resetRetryAttempt: false)
state.retryAttempt = state.retryAttempt.saturatingAddition(1)
state.connectionState = .recovering
probeAddress = nil
sendConnectionLostEvent()
}
private func sendPing(now: Date) {
do {
let sendResult = try pinger.send()
state.updatePingStats(sendResult: sendResult, now: now)
logger.trace("Send ping icmp_seq=\(sendResult.sequenceNumber).")
} catch {
logger.error(error: error, message: "Failed to send ping.")
}
}
private func didReceivePing(from sender: IPAddress, sequenceNumber: UInt16) {
nslock.lock()
defer { nslock.unlock() }
guard let probeAddress else { return }
if sender.rawValue != probeAddress.rawValue {
logger.trace("Got reply from unknown sender: \(sender), expected: \(probeAddress).")
}
let now = Date()
guard let pingTimestamp = state.setPingReplyReceived(sequenceNumber, now: now) else {
logger.trace("Got unknown ping sequence: \(sequenceNumber).")
return
}
logger.trace({
let time = now.timeIntervalSince(pingTimestamp) * 1000
let message = String(
format: "Received reply icmp_seq=%d, time=%.2f ms.",
sequenceNumber,
time
)
return Logger.Message(stringLiteral: message)
}())
if case .connecting = state.connectionState {
state.connectionState = .connected
state.retryAttempt = 0
sendConnectionEstablishedEvent()
}
}
private func startMonitoring() {
do {
guard let probeAddress else {
logger.debug("Failed to obtain probe address.")
return
}
try pinger.startPinging(destAddress: probeAddress)
state.connectionState = .connecting
startConnectivityCheckTimer()
} catch {
logger.error(error: error, message: "Failed to open socket.")
}
}
private func stopMonitoring(resetRetryAttempt: Bool) {
stopConnectivityCheckTimer()
pinger.stopPinging()
state.netStats = WgStats()
state.lastSeenRx = nil
state.lastSeenTx = nil
state.pingStats = PingStats()
if resetRetryAttempt {
state.retryAttempt = 0
}
state.isHeartbeatSuspended = false
}
private func startConnectivityCheckTimer() {
let timer = DispatchSource.makeTimerSource(queue: timerQueue)
timer.setEventHandler { [weak self] in
self?.checkConnectivity()
}
timer.schedule(wallDeadline: .now(), repeating: timings.connectivityCheckInterval.timeInterval)
timer.activate()
self.timer?.cancel()
self.timer = timer
state.timeoutReference = Date()
logger.trace("Start connectivity check timer.")
}
private func stopConnectivityCheckTimer() {
guard let timer else { return }
logger.trace("Stop connectivity check timer.")
timer.cancel()
self.timer = nil
}
private func sendConnectionEstablishedEvent() {
eventQueue.async {
self.onEvent?(.connectionEstablished)
}
}
private func sendConnectionLostEvent() {
eventQueue.async {
self.onEvent?(.connectionLost)
}
}
private func getStats() -> WgStats? {
do {
return try tunnelDeviceInfo.getStats()
} catch {
logger.error(error: error, message: "Failed to obtain adapter stats.")
return nil
}
}
}