Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mitigate known pixel noise #851

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ let package = Package(
.target(
name: "NetworkProtection",
dependencies: [
"PixelKit",
.target(name: "WireGuardC"),
.product(name: "WireGuard", package: "wireguard-apple"),
"Common",
Expand Down
32 changes: 32 additions & 0 deletions Sources/Common/Extensions/ProcessInfo+SystemBootDate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//
// ProcessInfo.swift
//
// Copyright © 2024 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

extension ProcessInfo {

public static func systemBootDate() -> Date {
var tv = timeval()
var tvSize = MemoryLayout<timeval>.size
let err = sysctlbyname("kern.boottime", &tv, &tvSize, nil, 0)
guard err == 0, tvSize == MemoryLayout<timeval>.size else {
return Date(timeIntervalSince1970: 0)
}
return Date(timeIntervalSince1970: Double(tv.tv_sec) + Double(tv.tv_usec) / 1_000_000.0)
}
}
20 changes: 14 additions & 6 deletions Sources/NetworkProtection/PacketTunnelProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -566,20 +566,27 @@ open class PacketTunnelProvider: NEPacketTunnelProvider {

open override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
Task { @MainActor in
providerEvents.fire(.tunnelStartAttempt(.begin))
let options = options ?? [:]
let startupMethod = StartupOptions.StartupMethod(options: options)
let startedByOnDemand = startupMethod == .automaticOnDemand
let pixelHandler = VPNTunnelStartPixelHandler(eventHandler: providerEvents, userDefaults: defaults)

//providerEvents.fire(.tunnelStartAttempt(.begin))
pixelHandler.handle(.begin, onDemand: startedByOnDemand)
prepareToConnect(using: tunnelProviderProtocol)

connectionStatus = .connecting

let startupOptions = StartupOptions(options: options ?? [:])
let startupOptions = StartupOptions(options: options)
os_log("Starting tunnel with options: %{public}s", log: .networkProtection, startupOptions.description)

resetIssueStateOnTunnelStart(startupOptions)

let internalCompletionHandler = { [weak self, providerEvents] (error: Error?) in
let internalCompletionHandler = { [weak self] (error: Error?) in
guard let error else {
completionHandler(nil)
providerEvents.fire(.tunnelStartAttempt(.success))
//providerEvents.fire(.tunnelStartAttempt(.success))
pixelHandler.handle(.success, onDemand: startedByOnDemand)
return
}

Expand All @@ -591,11 +598,12 @@ open class PacketTunnelProvider: NEPacketTunnelProvider {
self?.connectionStatus = .disconnected
self?.knownFailureStore.lastKnownFailure = KnownFailure(error)

providerEvents.fire(.tunnelStartAttempt(.failure(error)))
//providerEvents.fire(.tunnelStartAttempt(.failure(error)))
pixelHandler.handle(.failure(error), onDemand: startedByOnDemand)
completionHandler(error)
}

if startupOptions.startupMethod == .automaticOnDemand {
if startedByOnDemand {
Task {
// We add a 10 seconds delay when the VPN is started by
// on-demand and there's an error, to avoid frenetic ON/OFF
Expand Down
100 changes: 100 additions & 0 deletions Sources/NetworkProtection/Pixels/VPNTunnelStartPixelHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//
// VPNTunnelStartPixelHandler.swift
//
// Copyright © 2024 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 Common
import Foundation
import PixelKit

/// This class handles firing the tunnel start attempts.
///
/// The reason this logic is contained here, is that we were getting flooded by attempt pixels when an unattended system kept failing with
/// on-demand enabled. This class aims to confine these pixels to "sessions" of attempts, so to speak.
///
final class VPNTunnelStartPixelHandler {

typealias Event = PacketTunnelProvider.Event
typealias Step = PacketTunnelProvider.TunnelStartAttemptStep

private static let canFireKey = "VPNTunnelStartPixelHandler.canFire"
private static let lastFireDateKey = "VPNTunnelStartPixelHandler.lastFireDate"

private let userDefaults: UserDefaults
private let systemBootDate: Date
private let eventHandler: EventMapping<Event>

init(eventHandler: EventMapping<Event>,
systemBootDate: Date = ProcessInfo.systemBootDate(),
userDefaults: UserDefaults) {

self.userDefaults = userDefaults
self.systemBootDate = systemBootDate
self.eventHandler = eventHandler
}

func handle(_ step: Step, onDemand: Bool) {
if shouldResumeFiring(onDemand: onDemand) {
canFire = true
}

if canFire {
let event = Event.tunnelStartAttempt(step)
eventHandler.fire(event)
}

switch step {
case .failure where onDemand == true:
// After firing an on-demand start failure, we always silence pixels
canFire = false
case .success:
// A success always restores firing
canFire = true
default:
break
}
}

private func shouldResumeFiring(onDemand: Bool) -> Bool {
guard onDemand else {
return true
}

return lastFireDate < systemBootDate
}

// MARK: - User Defaults stored values

var canFire: Bool {
get {
userDefaults.value(forKey: Self.canFireKey) as? Bool ?? true
}

set {
userDefaults.setValue(newValue, forKey: Self.canFireKey)
}
}

private var lastFireDate: Date {
let interval = userDefaults.value(forKey: Self.lastFireDateKey) as? TimeInterval ?? 0
return Date(timeIntervalSinceReferenceDate: interval)
}

private func updateLastFireDate() {
let interval = Date().timeIntervalSinceReferenceDate
userDefaults.setValue(interval, forKey: Self.lastFireDateKey)
}
}
22 changes: 11 additions & 11 deletions Sources/NetworkProtection/StartupOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ struct StartupOptions {
return "manually by the system"
}
}

init(options: [String: Any]) {
if options[NetworkProtectionOptionKey.isOnDemand] as? Bool == true {
self = .automaticOnDemand
} else if options[NetworkProtectionOptionKey.activationAttemptId] != nil {
self = .manualByMainApp
} else {
self = .manualByTheSystem
}
}
}

/// Stored options are the options that the our network extension stores / remembers.
Expand Down Expand Up @@ -113,17 +123,7 @@ struct StartupOptions {
let enableTester: StoredOption<Bool>

init(options: [String: Any]) {
let startupMethod: StartupMethod = {
if options[NetworkProtectionOptionKey.isOnDemand] as? Bool == true {
return .automaticOnDemand
} else if options[NetworkProtectionOptionKey.activationAttemptId] != nil {
return .manualByMainApp
} else {
return .manualByTheSystem
}
}()

self.startupMethod = startupMethod
self.startupMethod = StartupMethod(options: options)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just moved this to an init so we can use it from the packet tunnel provider.


simulateError = options[NetworkProtectionOptionKey.tunnelFailureSimulation] as? Bool ?? false
simulateCrash = options[NetworkProtectionOptionKey.tunnelFatalErrorCrashSimulation] as? Bool ?? false
Expand Down
Loading
Loading