Skip to content

Commit

Permalink
Fix on demand so that it's not enabled too soon (#2499)
Browse files Browse the repository at this point in the history
Task/Issue URL: https://app.asana.com/0/1203137811378537/1206543593200557/f

## Description:

Enables on-demand only after the VPN has connected.
  • Loading branch information
diegoreymendez authored Feb 23, 2024
1 parent 77cace8 commit 2700cb9
Showing 1 changed file with 36 additions and 6 deletions.
42 changes: 36 additions & 6 deletions DuckDuckGo/NetworkProtectionTunnelController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ final class NetworkProtectionTunnelController: TunnelController {
private let debugFeatures = NetworkProtectionDebugFeatures()
private let tokenStore = NetworkProtectionKeychainTokenStore()
private let errorStore = NetworkProtectionTunnelErrorStore()
private let notificationCenter: NotificationCenter = .default
private var previousStatus: NEVPNStatus = .invalid
private var cancellables = Set<AnyCancellable>()

// MARK: - Starting & Stopping the VPN

Expand All @@ -39,6 +42,10 @@ final class NetworkProtectionTunnelController: TunnelController {
case simulateControllerFailureError
}

init() {
subscribeToStatusChanges()
}

/// Starts the VPN connection used for Network Protection
///
func start() async {
Expand Down Expand Up @@ -142,12 +149,6 @@ final class NetworkProtectionTunnelController: TunnelController {
Pixel.fire(pixel: .networkProtectionActivationRequestFailed, error: error)
throw error
}

if !debugFeatures.alwaysOnDisabled {
Task {
try await enableOnDemand(tunnelManager: tunnelManager)
}
}
}

/// The actual storage for our tunnel manager.
Expand Down Expand Up @@ -231,6 +232,35 @@ final class NetworkProtectionTunnelController: TunnelController {
tunnelManager.onDemandRules = [NEOnDemandRuleConnect()]
}

// MARK: - Observing Status Changes

private func subscribeToStatusChanges() {
notificationCenter.publisher(for: .NEVPNStatusDidChange)
.sink(receiveValue: handleStatusChange(_:))
.store(in: &cancellables)
}

private func handleStatusChange(_ notification: Notification) {
guard !debugFeatures.alwaysOnDisabled,
let session = (notification.object as? NETunnelProviderSession),
session.status != previousStatus,
let manager = session.manager as? NETunnelProviderManager else {
return
}

Task { @MainActor in
previousStatus = session.status

switch session.status {
case .connected:
try await enableOnDemand(tunnelManager: manager)
default:
break
}

}
}

// MARK: - On Demand

@MainActor
Expand Down

0 comments on commit 2700cb9

Please sign in to comment.