content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
//\n// TunnelControlPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass TunnelControlPage: Page {\n private struct ConnectionAttempt: Hashable {\n let ipAddress: String\n let port: String\n let protocolName: String\n }\n\n var connectionIsSecured: Bool {\n app.staticTexts[AccessibilityIdentifier.connectionStatusConnectedLabel].exists\n }\n\n /// Poll the "in address row" label for its updated values and output an array of ConnectionAttempt objects representing the connection attempts that have been communicated through the UI.\n /// - Parameters:\n /// - attemptsCount: number of connection attempts to look for\n /// - timeout: return the attemps found so far after this many seconds if `attemptsCount` haven't been reached yet\n private func waitForConnectionAttempts(_ attemptsCount: Int, timeout: TimeInterval) -> [ConnectionAttempt] {\n var connectionAttempts: [ConnectionAttempt] = []\n var lastConnectionAttempt: ConnectionAttempt?\n let startTime = Date()\n let pollingInterval = TimeInterval(0.5) // How often to check for changes\n\n let inAddressRow = app.staticTexts[AccessibilityIdentifier.connectionPanelInAddressRow]\n\n while Date().timeIntervalSince(startTime) < timeout {\n let expectation = XCTestExpectation(description: "Wait for connection attempts")\n\n DispatchQueue.global().asyncAfter(deadline: .now() + pollingInterval) {\n expectation.fulfill()\n }\n\n _ = XCTWaiter.wait(for: [expectation], timeout: pollingInterval + 0.5)\n\n let currentText = inAddressRow.label\n\n // Skip initial label value with IP address only - no port or protocol\n guard currentText.contains(" ") == true else {\n continue\n }\n\n let addressPortComponent = currentText.components(separatedBy: " ")[0]\n let ipAddress = addressPortComponent.components(separatedBy: ":")[0]\n let port = addressPortComponent.components(separatedBy: ":")[1]\n let protocolName = currentText.components(separatedBy: " ")[1]\n let connectionAttempt = ConnectionAttempt(\n ipAddress: ipAddress,\n port: port,\n protocolName: protocolName\n )\n\n if connectionAttempt != lastConnectionAttempt {\n connectionAttempts.append(connectionAttempt)\n lastConnectionAttempt = connectionAttempt\n\n if connectionAttempts.count == attemptsCount {\n break\n }\n }\n }\n\n return connectionAttempts\n }\n\n func getInIPv4AddressLabel() -> String {\n app.staticTexts[AccessibilityIdentifier.connectionPanelInAddressRow].label.components(separatedBy: ":")[0]\n }\n\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.connectionView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapSelectLocationButton() -> Self {\n app.buttons[AccessibilityIdentifier.selectLocationButton].tap()\n return self\n }\n\n @discardableResult func tapConnectButton() -> Self {\n app.buttons[AccessibilityIdentifier.connectButton].tap()\n return self\n }\n\n @discardableResult func tapDisconnectButton() -> Self {\n app.buttons[AccessibilityIdentifier.disconnectButton].tap()\n return self\n }\n\n @discardableResult func tapCancelButton() -> Self {\n app.buttons[AccessibilityIdentifier.cancelButton].tap()\n return self\n }\n\n /// Tap either cancel or disconnect button, depending on the current connection state. Use this function sparingly when it's irrelevant whether the app is currently connecting to a relay or already connected.\n @discardableResult func tapCancelOrDisconnectButton() -> Self {\n let cancelButton = app.buttons[.cancelButton]\n let disconnectButton = app.buttons[.disconnectButton]\n\n if disconnectButton.exists && disconnectButton.isHittable {\n disconnectButton.tap()\n } else {\n cancelButton.tap()\n }\n\n return self\n }\n\n @discardableResult func waitForConnectedLabel() -> Self {\n let labelFound = app.staticTexts[.connectionStatusConnectedLabel]\n .waitForExistence(timeout: BaseUITestCase.extremelyLongTimeout)\n XCTAssertTrue(labelFound, "Secure connection label presented")\n\n return self\n }\n\n @discardableResult func tapRelayStatusExpandCollapseButton() -> Self {\n app.buttons[AccessibilityIdentifier.relayStatusCollapseButton].tap()\n return self\n }\n\n /// Verify that the app attempts to connect over UDP before switching to TCP. For testing blocked UDP traffic.\n @discardableResult func verifyConnectingOverTCPAfterUDPAttempts() -> Self {\n let connectionAttempts = waitForConnectionAttempts(4, timeout: 30)\n\n // Should do four connection attempts but due to UI bug sometimes only two are displayed, sometimes all four\n if connectionAttempts.count == 4 { // Expected retries flow\n for (attemptIndex, attempt) in connectionAttempts.enumerated() {\n if attemptIndex < 3 {\n XCTAssertEqual(attempt.protocolName, "UDP")\n } else if attemptIndex == 3 {\n XCTAssertEqual(attempt.protocolName, "TCP")\n } else {\n XCTFail("Unexpected connection attempt")\n }\n }\n } else if connectionAttempts.count == 3 { // Most of the times this incorrect flow is shown\n for (attemptIndex, attempt) in connectionAttempts.enumerated() {\n if attemptIndex == 0 || attemptIndex == 1 {\n XCTAssertEqual(attempt.protocolName, "UDP")\n } else if attemptIndex == 2 {\n XCTAssertEqual(attempt.protocolName, "TCP")\n } else {\n XCTFail("Unexpected connection attempt")\n }\n }\n } else {\n XCTFail("Unexpected number of connection attempts, expected 3~4, got \(connectionAttempts.count)")\n }\n\n return self\n }\n\n /// Verify that connection attempts are made in the correct order\n @discardableResult func verifyConnectionAttemptsOrder() -> Self {\n var connectionAttempts = waitForConnectionAttempts(4, timeout: 80)\n var totalAttemptsOffset = 0\n XCTAssertEqual(connectionAttempts.count, 4)\n\n /// Sometimes, the UI will only show an IP address for the first connection attempt, which gets skipped by\n /// `waitForConnectionAttempts`, and offsets expected attempts count by 1, but still counts towards\n /// total connection attempts. Remove that last attempt which would be the first one of a new series\n /// of connection attempts.\n if connectionAttempts.last?.protocolName == "UDP" {\n connectionAttempts.removeLast()\n totalAttemptsOffset = 1\n }\n for (attemptIndex, attempt) in connectionAttempts.enumerated() {\n if attemptIndex < 3 - totalAttemptsOffset {\n XCTAssertEqual(attempt.protocolName, "UDP")\n } else {\n XCTAssertEqual(attempt.protocolName, "TCP")\n let validPorts = ["80", "5001"]\n XCTAssertTrue(validPorts.contains(attempt.port))\n }\n }\n\n return self\n }\n\n @discardableResult func verifyConnectingToPort(_ port: String) -> Self {\n let connectionAttempts = waitForConnectionAttempts(1, timeout: 10)\n XCTAssertEqual(connectionAttempts.count, 1)\n XCTAssertEqual(connectionAttempts.first!.port, port)\n\n return self\n }\n\n /// Verify that the app attempts to connect over Multihop.\n @discardableResult func verifyConnectingOverMultihop() -> Self {\n XCTAssertTrue(app.staticTexts["Multihop"].exists)\n return self\n }\n\n /// Verify that the app attempts to connect using DAITA.\n @discardableResult func verifyConnectingUsingDAITA() -> Self {\n XCTAssertTrue(app.staticTexts["DAITA"].exists)\n return self\n }\n\n func getInIPAddressFromConnectionStatus() -> String {\n let inAddressRow = app.staticTexts[.connectionPanelInAddressRow]\n return inAddressRow.label.components(separatedBy: ":")[0]\n }\n\n func getCurrentRelayName() -> String {\n let server = app.staticTexts[.connectionPanelServerLabel]\n return server.label\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\TunnelControlPage.swift
TunnelControlPage.swift
Swift
8,730
0.95
0.109091
0.121547
react-lib
162
2025-02-14T18:58:50.777059
GPL-3.0
true
01563a2762190086c2cc4ff12951af5d
//\n// UDPOverTCPObfuscationSettingsPage.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-12-12.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass UDPOverTCPObfuscationSettingsPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n }\n\n private var table: XCUIElement {\n app.collectionViews[AccessibilityIdentifier.wireGuardObfuscationUdpOverTcpTable]\n }\n\n private func portCell(_ index: Int) -> XCUIElement {\n table.cells.element(boundBy: index)\n }\n\n @discardableResult func tapAutomaticPortCell() -> Self {\n portCell(0).tap()\n return self\n }\n\n @discardableResult func tapPort80Cell() -> Self {\n portCell(1).tap()\n return self\n }\n\n @discardableResult func tapPort5001Cell() -> Self {\n portCell(2).tap()\n return self\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround for setting accessibility identifier on navigation bar button being non-trivial\n app.navigationBars.buttons.element(boundBy: 0).tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\UDPOverTCPObfuscationSettingsPage.swift
UDPOverTCPObfuscationSettingsPage.swift
Swift
1,163
0.95
0.044444
0.216216
vue-tools
513
2025-05-31T16:06:07.891668
BSD-3-Clause
true
a77e68874a449ee97fad5c54712dafc3
//\n// VPNSettingsPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-03-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass VPNSettingsPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n }\n\n private func cellSubButton(\n _ cellAccessiblityIdentifier: AccessibilityIdentifier,\n _ subButtonAccessibilityIdentifier: AccessibilityIdentifier\n ) -> XCUIElement {\n let tableView = app.tables[AccessibilityIdentifier.vpnSettingsTableView]\n let matchingCells = tableView.cells[cellAccessiblityIdentifier]\n let expandButton = matchingCells.buttons[subButtonAccessibilityIdentifier]\n let lastCell = tableView.cells.allElementsBoundByIndex.last!\n tableView.scrollDownToElement(element: lastCell)\n return expandButton\n }\n\n private func cellExpandButton(_ cellAccessiblityIdentifier: AccessibilityIdentifier) -> XCUIElement {\n let tableView = app.tables[AccessibilityIdentifier.vpnSettingsTableView]\n let matchingCells = tableView.otherElements[cellAccessiblityIdentifier]\n let expandButton = matchingCells.buttons[.expandButton]\n let lastCell = tableView.cells.allElementsBoundByIndex.last!\n tableView.scrollDownToElement(element: lastCell)\n return expandButton\n }\n\n private func cellPortSelectorButton(_ cellAccessiblityIdentifier: AccessibilityIdentifier) -> XCUIElement {\n return cellSubButton(cellAccessiblityIdentifier, .openPortSelectorMenuButton)\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround for setting accessibility identifier on navigation bar button being non-trivial\n app.buttons.matching(identifier: "Settings").allElementsBoundByIndex.last?.tap()\n return self\n }\n\n @discardableResult func tapDNSSettingsCell() -> Self {\n app.tables\n .cells[AccessibilityIdentifier.dnsSettings]\n .tap()\n\n return self\n }\n\n @discardableResult func tapLocalNetworkSharingSwitch() -> Self {\n app.cells[AccessibilityIdentifier.localNetworkSharing]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n app.buttons[AccessibilityIdentifier.acceptLocalNetworkSharingButton]\n .tap()\n\n return self\n }\n\n @discardableResult func tapWireGuardPortsExpandButton() -> Self {\n cellExpandButton(AccessibilityIdentifier.wireGuardPortsCell).tap()\n return self\n }\n\n @discardableResult func tapWireGuardObfuscationExpandButton() -> Self {\n cellExpandButton(AccessibilityIdentifier.wireGuardObfuscationCell).tap()\n\n return self\n }\n\n @discardableResult func tapUDPOverTCPPortSelectorButton() -> Self {\n cellPortSelectorButton(AccessibilityIdentifier.wireGuardObfuscationUdpOverTcp).tap()\n\n return self\n }\n\n @discardableResult func tapShadowsocksPortSelectorButton() -> Self {\n cellPortSelectorButton(AccessibilityIdentifier.wireGuardObfuscationShadowsocks).tap()\n\n return self\n }\n\n @discardableResult func tapQuantumResistantTunnelExpandButton() -> Self {\n cellExpandButton(AccessibilityIdentifier.quantumResistantTunnelCell).tap()\n\n return self\n }\n\n @discardableResult func tapQuantumResistantTunnelAutomaticCell() -> Self {\n app.cells[AccessibilityIdentifier.quantumResistanceAutomatic]\n .tap()\n return self\n }\n\n @discardableResult func tapQuantumResistantTunnelOnCell() -> Self {\n app.cells[AccessibilityIdentifier.quantumResistanceOn]\n .tap()\n return self\n }\n\n @discardableResult func tapQuantumResistantTunnelOffCell() -> Self {\n app.cells[AccessibilityIdentifier.quantumResistanceOff]\n .tap()\n return self\n }\n\n @discardableResult func tapWireGuardObfuscationAutomaticCell() -> Self {\n app.cells[AccessibilityIdentifier.wireGuardObfuscationAutomatic]\n .tap()\n return self\n }\n\n @discardableResult func tapWireGuardObfuscationUdpOverTcpCell() -> Self {\n app.cells[AccessibilityIdentifier.wireGuardObfuscationUdpOverTcp].tap()\n\n return self\n }\n\n @discardableResult func tapWireGuardObfuscationShadowsocksCell() -> Self {\n app.cells[AccessibilityIdentifier.wireGuardObfuscationShadowsocks].tap()\n\n return self\n }\n\n @discardableResult func tapWireGuardObfuscationOffCell() -> Self {\n app.cells[AccessibilityIdentifier.wireGuardObfuscationOff].tap()\n\n return self\n }\n\n @discardableResult func tapCustomWireGuardPortTextField() -> Self {\n app.textFields[AccessibilityIdentifier.customWireGuardPortTextField]\n .tap()\n return self\n }\n\n @discardableResult func verifyCustomWireGuardPortSelected(portNumber: String) -> Self {\n let cell = app.cells[AccessibilityIdentifier.wireGuardCustomPort]\n XCTAssertTrue(cell.isSelected)\n let textField = app.textFields[AccessibilityIdentifier.customWireGuardPortTextField]\n\n guard let textFieldValue = textField.value as? String else {\n XCTFail("Failed to read custom port text field value")\n return self\n }\n\n XCTAssertEqual(textFieldValue, portNumber)\n return self\n }\n\n @discardableResult func verifyWireGuardObfuscationOnSelected() -> Self {\n let onCell = app.cells[AccessibilityIdentifier.wireGuardObfuscationUdpOverTcp]\n XCTAssertTrue(onCell.isSelected)\n return self\n }\n\n @discardableResult func verifyUDPOverTCPPort80Selected() -> Self {\n let detailLabel = app.staticTexts[AccessibilityIdentifier.wireGuardObfuscationUdpOverTcpPort]\n XCTAssertTrue(detailLabel.label.hasSuffix(" 80"))\n return self\n }\n\n @discardableResult func verifyQuantumResistantTunnelOffSelected() -> Self {\n let cell = app.cells[AccessibilityIdentifier.quantumResistanceOff]\n XCTAssertTrue(cell.isSelected)\n return self\n }\n\n @discardableResult func verifyQuantumResistantTunnelOnSelected() -> Self {\n let cell = app.cells[AccessibilityIdentifier.quantumResistanceOn]\n XCTAssertTrue(cell.isSelected)\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\VPNSettingsPage.swift
VPNSettingsPage.swift
Swift
6,297
0.95
0.011111
0.055944
python-kit
957
2025-01-07T15:17:16.080086
BSD-3-Clause
true
6af4bcca042d5f9b2e28ffb055cc17c3
//\n// WelcomePage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass WelcomePage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.welcomeView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapAddTimeButton() -> Self {\n app.buttons[AccessibilityIdentifier.purchaseButton].tap()\n return self\n }\n\n @discardableResult func tapRedeemButton() -> Self {\n app.buttons[AccessibilityIdentifier.redeemVoucherButton].tap()\n return self\n }\n\n func getAccountNumber() -> String {\n let labelValue = app.staticTexts[AccessibilityIdentifier.welcomeAccountNumberLabel].label\n return labelValue.replacingOccurrences(of: " ", with: "")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\WelcomePage.swift
WelcomePage.swift
Swift
919
0.95
0.029412
0.25
node-utils
190
2025-06-18T16:03:15.972094
BSD-3-Clause
true
e8cc4a17fad3b3bf627e5c94eeb564f3
//\n// SnapshotHelper.swift\n// Example\n//\n// Created by Felix Krause on 10/8/15.\n//\n\n// -----------------------------------------------------\n// IMPORTANT: When modifying this file, make sure to\n// increment the version number at the very\n// bottom of the file to notify users about\n// the new SnapshotHelper.swift\n// -----------------------------------------------------\n\nimport Foundation\nimport XCTest\n\n@MainActor\nfunc setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) {\n Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations)\n}\n\n@MainActor\nfunc snapshot(_ name: String, waitForLoadingIndicator: Bool) {\n if waitForLoadingIndicator {\n Snapshot.snapshot(name)\n } else {\n Snapshot.snapshot(name, timeWaitingForIdle: 0)\n }\n}\n\n/// - Parameters:\n/// - name: The name of the snapshot\n/// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait.\n@MainActor\nfunc snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {\n Snapshot.snapshot(name, timeWaitingForIdle: timeout)\n}\n\nenum SnapshotError: Error, CustomDebugStringConvertible {\n case cannotFindSimulatorHomeDirectory\n case cannotRunOnPhysicalDevice\n\n var debugDescription: String {\n switch self {\n case .cannotFindSimulatorHomeDirectory:\n return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable."\n case .cannotRunOnPhysicalDevice:\n return "Can't use Snapshot on a physical device."\n }\n }\n}\n\n@objcMembers\n@MainActor\nopen class Snapshot: NSObject {\n static var app: XCUIApplication?\n static var waitForAnimations = true\n static var cacheDirectory: URL?\n static var screenshotsDirectory: URL? {\n return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true)\n }\n\n static var deviceLanguage = ""\n static var currentLocale = ""\n\n open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) {\n Snapshot.app = app\n Snapshot.waitForAnimations = waitForAnimations\n\n do {\n let cacheDir = try getCacheDirectory()\n Snapshot.cacheDirectory = cacheDir\n setLanguage(app)\n setLocale(app)\n setLaunchArguments(app)\n } catch let error {\n NSLog(error.localizedDescription)\n }\n }\n\n class func setLanguage(_ app: XCUIApplication) {\n guard let cacheDirectory = self.cacheDirectory else {\n NSLog("CacheDirectory is not set - probably running on a physical device?")\n return\n }\n\n let path = cacheDirectory.appendingPathComponent("language.txt")\n\n do {\n let trimCharacterSet = CharacterSet.whitespacesAndNewlines\n deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)\n app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]\n } catch {\n NSLog("Couldn't detect/set language...")\n }\n }\n\n class func setLocale(_ app: XCUIApplication) {\n guard let cacheDirectory = self.cacheDirectory else {\n NSLog("CacheDirectory is not set - probably running on a physical device?")\n return\n }\n\n let path = cacheDirectory.appendingPathComponent("locale.txt")\n\n do {\n let trimCharacterSet = CharacterSet.whitespacesAndNewlines\n currentLocale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)\n } catch {\n NSLog("Couldn't detect/set locale...")\n }\n\n if currentLocale.isEmpty && !deviceLanguage.isEmpty {\n currentLocale = Locale(identifier: deviceLanguage).identifier\n }\n\n if !currentLocale.isEmpty {\n app.launchArguments += ["-AppleLocale", "\"\(currentLocale)\""]\n }\n }\n\n class func setLaunchArguments(_ app: XCUIApplication) {\n guard let cacheDirectory = self.cacheDirectory else {\n NSLog("CacheDirectory is not set - probably running on a physical device?")\n return\n }\n\n let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt")\n app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]\n\n do {\n let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8)\n let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])\n let matches = regex.matches(\n in: launchArguments,\n options: [],\n range: NSRange(location: 0, length: launchArguments.count)\n )\n let results = matches.map { result -> String in\n (launchArguments as NSString).substring(with: result.range)\n }\n app.launchArguments += results\n } catch {\n NSLog("Couldn't detect/set launch_arguments...")\n }\n }\n\n open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {\n if timeout > 0 {\n waitForLoadingIndicatorToDisappear(within: timeout)\n }\n\n NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work\n\n if Snapshot.waitForAnimations {\n sleep(1) // Waiting for the animation to be finished (kind of)\n }\n\n #if os(OSX)\n guard let app = self.app else {\n NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")\n return\n }\n\n app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])\n #else\n\n guard self.app != nil else {\n NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")\n return\n }\n\n let screenshot = XCUIScreen.main.screenshot()\n #if os(iOS) && !targetEnvironment(macCatalyst)\n let image = XCUIDevice.shared.orientation.isLandscape\n ? fixLandscapeOrientation(image: screenshot.image)\n : screenshot.image\n #else\n let image = screenshot.image\n #endif\n\n guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"],\n let screenshotsDir = screenshotsDirectory else { return }\n\n do {\n // The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices\n let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ")\n let range = NSRange(location: 0, length: simulator.count)\n simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "")\n\n let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png")\n #if swift(<5.0)\n try UIImagePNGRepresentation(image)?.write(to: path, options: .atomic)\n #else\n try image.pngData()?.write(to: path, options: .atomic)\n #endif\n } catch let error {\n NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png")\n NSLog(error.localizedDescription)\n }\n #endif\n }\n\n class func fixLandscapeOrientation(image: UIImage) -> UIImage {\n #if os(watchOS)\n return image\n #else\n if #available(iOS 10.0, *) {\n let format = UIGraphicsImageRendererFormat()\n format.scale = image.scale\n let renderer = UIGraphicsImageRenderer(size: image.size, format: format)\n return renderer.image { _ in\n image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))\n }\n } else {\n return image\n }\n #endif\n }\n\n class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) {\n #if os(tvOS)\n return\n #endif\n\n guard let app = self.app else {\n NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")\n return\n }\n\n let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element\n let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(\n predicate: NSPredicate(format: "exists == false"),\n object: networkLoadingIndicator\n )\n _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout)\n }\n\n class func getCacheDirectory() throws -> URL {\n let cachePath = "Library/Caches/tools.fastlane"\n // on OSX config is stored in /Users/<username>/Library\n // and on iOS/tvOS/WatchOS it's in simulator's home dir\n #if os(OSX)\n let homeDir = URL(fileURLWithPath: NSHomeDirectory())\n return homeDir.appendingPathComponent(cachePath)\n #elseif arch(arm64)\n guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {\n throw SnapshotError.cannotFindSimulatorHomeDirectory\n }\n let homeDir = URL(fileURLWithPath: simulatorHostHome)\n return homeDir.appendingPathComponent(cachePath)\n #else\n throw SnapshotError.cannotRunOnPhysicalDevice\n #endif\n }\n}\n\nprivate extension XCUIElementAttributes {\n var isNetworkLoadingIndicator: Bool {\n if hasAllowListedIdentifier { return false }\n\n let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20)\n let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(\n 2,\n and: 3\n )\n\n return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize\n }\n\n var hasAllowListedIdentifier: Bool {\n let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]\n\n return allowListedIdentifiers.contains(identifier)\n }\n\n func isStatusBar(_ deviceWidth: CGFloat) -> Bool {\n if elementType == .statusBar { return true }\n guard frame.origin == .zero else { return false }\n\n let oldStatusBarSize = CGSize(width: deviceWidth, height: 20)\n let newStatusBarSize = CGSize(width: deviceWidth, height: 44)\n\n return [oldStatusBarSize, newStatusBarSize].contains(frame.size)\n }\n}\n\nprivate extension XCUIElementQuery {\n var networkLoadingIndicators: XCUIElementQuery {\n let isNetworkLoadingIndicator = NSPredicate { evaluatedObject, _ in\n guard let element = evaluatedObject as? XCUIElementAttributes else { return false }\n\n return element.isNetworkLoadingIndicator\n }\n\n return self.containing(isNetworkLoadingIndicator)\n }\n\n @MainActor\n var deviceStatusBars: XCUIElementQuery {\n guard let app = Snapshot.app else {\n fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")\n }\n\n let deviceWidth = app.windows.firstMatch.frame.width\n\n let isStatusBar = NSPredicate { evaluatedObject, _ in\n guard let element = evaluatedObject as? XCUIElementAttributes else { return false }\n\n return element.isStatusBar(deviceWidth)\n }\n\n return self.containing(isStatusBar)\n }\n}\n\nprivate extension CGFloat {\n func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool {\n return numberA ... numberB ~= self\n }\n}\n\n// Please don't remove the lines below\n// They are used to detect outdated configuration files\n// SnapshotHelperVersion [1.30]\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Screenshots\SnapshotHelper.swift
SnapshotHelper.swift
Swift
11,733
0.95
0.122699
0.143911
node-utils
456
2024-02-17T09:08:49.308065
GPL-3.0
true
eb1956b8632c06dc5c7cd095af5270af
//\n// AsyncBlockOperation.swift\n// Operations\n//\n// Created by pronebird on 06/07/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport protocol MullvadTypes.Cancellable\n\n/// Asynchronous block operation\npublic class AsyncBlockOperation: AsyncOperation, @unchecked Sendable {\n private var executor: ((@escaping @Sendable (Error?) -> Void) -> Cancellable?)?\n private var cancellableTask: Cancellable?\n\n public init(\n dispatchQueue: DispatchQueue? = nil,\n block: @escaping @Sendable (@escaping @Sendable (Error?) -> Void) -> Void\n ) {\n super.init(dispatchQueue: dispatchQueue)\n executor = { finish in\n block(finish)\n return nil\n }\n }\n\n public init(dispatchQueue: DispatchQueue? = nil, block: @escaping @Sendable () -> Void) {\n super.init(dispatchQueue: dispatchQueue)\n executor = { finish in\n block()\n finish(nil)\n return nil\n }\n }\n\n public init(\n dispatchQueue: DispatchQueue? = nil,\n cancellableTask: @escaping @Sendable (@escaping @Sendable (Error?) -> Void) -> Cancellable\n ) {\n super.init(dispatchQueue: dispatchQueue)\n executor = { cancellableTask($0) }\n }\n\n override public func main() {\n let executor = executor\n self.executor = nil\n\n assert(executor != nil)\n\n cancellableTask = executor?(self.finish)\n }\n\n override public func operationDidCancel() {\n cancellableTask?.cancel()\n }\n\n override public func operationDidFinish() {\n executor = nil\n cancellableTask = nil\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\AsyncBlockOperation.swift
AsyncBlockOperation.swift
Swift
1,656
0.95
0.016129
0.153846
awesome-app
172
2025-04-24T05:30:02.222190
BSD-3-Clause
false
ac16f9a30bcaf035f2d76c0c4005cf61
//\n// AsyncOperation.swift\n// Operations\n//\n// Created by pronebird on 01/06/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n@objc private enum State: Int, Comparable, CustomStringConvertible {\n case initialized\n case pending\n case evaluatingConditions\n case ready\n case executing\n case finished\n\n static func < (lhs: State, rhs: State) -> Bool {\n lhs.rawValue < rhs.rawValue\n }\n\n var description: String {\n switch self {\n case .initialized:\n return "initialized"\n case .pending:\n return "pending"\n case .evaluatingConditions:\n return "evaluatingConditions"\n case .ready:\n return "ready"\n case .executing:\n return "executing"\n case .finished:\n return "finished"\n }\n }\n}\n\n/// A base implementation of an asynchronous operation\nopen class AsyncOperation: Operation, @unchecked Sendable {\n /// Mutex lock used for guarding critical sections of operation lifecycle.\n private let operationLock = NSRecursiveLock()\n\n /// Mutex lock used to guard `state` and `isCancelled` properties.\n ///\n /// This lock must not encompass KVO hooks such as `willChangeValue` and `didChangeValue` to\n /// prevent deadlocks, since KVO observers may synchronously query the operation state on a\n /// different thread.\n ///\n /// `operationLock` should be used along with `stateLock` to ensure internal state consistency\n /// when multiple access to `state` or `isCancelled` is necessary, such as when testing\n /// the value before modifying it.\n private let stateLock = NSRecursiveLock()\n\n /// Backing variable for `state`.\n /// Access must be guarded with `stateLock`.\n private var _state: State = .initialized\n\n /// Backing variable for `_isCancelled`.\n /// Access must be guarded with `stateLock`.\n private var __isCancelled = false\n\n /// Backing variable for `error`.\n /// Access must be guarded with `stateLock`.\n private var __error: Error?\n\n /// Operation state.\n @objc private var state: State {\n get {\n stateLock.lock()\n defer { stateLock.unlock() }\n return _state\n }\n set(newState) {\n willChangeValue(for: \.state)\n stateLock.lock()\n assert(_state < newState)\n _state = newState\n stateLock.unlock()\n didChangeValue(for: \.state)\n }\n }\n\n private var _isCancelled: Bool {\n get {\n stateLock.lock()\n defer { stateLock.unlock() }\n return __isCancelled\n }\n set {\n willChangeValue(for: \.isCancelled)\n stateLock.lock()\n __isCancelled = newValue\n stateLock.unlock()\n didChangeValue(for: \.isCancelled)\n }\n }\n\n private var _error: Error? {\n get {\n stateLock.lock()\n defer { stateLock.unlock() }\n return __error\n }\n set {\n stateLock.lock()\n defer { stateLock.unlock() }\n __error = newValue\n }\n }\n\n public var error: Error? {\n _error\n }\n\n dynamic override public final var isReady: Bool {\n stateLock.lock()\n defer { stateLock.unlock() }\n\n // super.isReady should turn true when all dependencies are satisfied.\n guard super.isReady else {\n return false\n }\n\n // Mark operation ready when cancelled, so that operation queue could flush it faster.\n guard !__isCancelled else {\n return true\n }\n\n switch _state {\n case .initialized, .pending, .evaluatingConditions:\n return false\n\n case .ready, .executing, .finished:\n return true\n }\n }\n\n override public final var isExecuting: Bool {\n state == .executing\n }\n\n override public final var isFinished: Bool {\n state == .finished\n }\n\n override public final var isCancelled: Bool {\n _isCancelled\n }\n\n override public final var isAsynchronous: Bool {\n true\n }\n\n // MARK: - Observers\n\n private var _observers: [OperationObserver] = []\n\n public final var observers: [OperationObserver] {\n operationLock.lock()\n defer { operationLock.unlock() }\n\n return _observers\n }\n\n public final func addObserver(_ observer: OperationObserver) {\n operationLock.lock()\n assert(state < .executing)\n _observers.append(observer)\n operationLock.unlock()\n observer.didAttach(to: self)\n }\n\n // MARK: - Conditions\n\n private var _conditions: [OperationCondition] = []\n\n public final var conditions: [OperationCondition] {\n operationLock.lock()\n defer { operationLock.unlock() }\n return _conditions\n }\n\n public func addCondition(_ condition: OperationCondition) {\n operationLock.lock()\n defer { operationLock.unlock() }\n\n assert(state < .evaluatingConditions)\n _conditions.append(condition)\n }\n\n private func evaluateConditions() {\n guard !_conditions.isEmpty else {\n state = .ready\n return\n }\n\n state = .evaluatingConditions\n\n nonisolated(unsafe) var results = [Bool](repeating: false, count: _conditions.count)\n let group = DispatchGroup()\n\n for (index, condition) in _conditions.enumerated() {\n group.enter()\n condition.evaluate(for: self) { [weak self] isSatisfied in\n self?.dispatchQueue.async {\n results[index] = isSatisfied\n group.leave()\n }\n }\n }\n\n group.notify(queue: dispatchQueue) { [weak self] in\n self?.didEvaluateConditions(results)\n }\n }\n\n private func didEvaluateConditions(_ results: [Bool]) {\n operationLock.lock()\n defer { operationLock.unlock() }\n\n guard state < .ready else { return }\n\n let conditionsSatisfied = results.allSatisfy { $0 }\n if !conditionsSatisfied {\n cancel()\n }\n\n state = .ready\n }\n\n // MARK: -\n\n public let dispatchQueue: DispatchQueue\n\n private var isReadyObserver: NSKeyValueObservation?\n public init(dispatchQueue: DispatchQueue? = nil) {\n self.dispatchQueue = dispatchQueue ?? DispatchQueue(label: "AsyncOperation.dispatchQueue")\n super.init()\n\n isReadyObserver = observe(\.isReady, options: []) { operation, _ in\n operation.checkReadiness()\n }\n }\n\n deinit {\n // Clear the observer when the operation is deallocated to avoid leaking memory.\n isReadyObserver = nil\n }\n\n // MARK: - KVO\n\n @objc class func keyPathsForValuesAffectingIsReady() -> Set<String> {\n [#keyPath(state)]\n }\n\n @objc class func keyPathsForValuesAffectingIsExecuting() -> Set<String> {\n [#keyPath(state)]\n }\n\n @objc class func keyPathsForValuesAffectingIsFinished() -> Set<String> {\n [#keyPath(state)]\n }\n\n // MARK: - Lifecycle\n\n override public final func start() {\n let currentQueue = OperationQueue.current\n let underlyingQueue = currentQueue?.underlyingQueue\n\n if underlyingQueue == dispatchQueue {\n _start()\n } else {\n dispatchQueue.async {\n self._start()\n }\n }\n }\n\n private func _start() {\n operationLock.lock()\n if _isCancelled {\n notifyCancellation()\n operationLock.unlock()\n finish(error: OperationError.cancelled)\n } else {\n state = .executing\n\n for observer in _observers {\n observer.operationDidStart(self)\n }\n operationLock.unlock()\n\n main()\n }\n }\n\n override open func main() {\n // Override in subclasses\n }\n\n override public final func cancel() {\n operationLock.lock()\n if !_isCancelled {\n _isCancelled = true\n\n // Notify observers only when executing, otherwise `_start()` will take care of doing this as soon\n // as operation is ready to execute.\n if state == .executing {\n dispatchQueue.async {\n self.notifyCancellation()\n }\n }\n }\n operationLock.unlock()\n\n super.cancel()\n }\n\n public func finish() {\n finish(error: nil)\n }\n\n public func finish(error: Error?) {\n guard tryFinish(error: error) else { return }\n\n dispatchQueue.async {\n self.operationDidFinish()\n\n let anError = self.error\n for observer in self.observers {\n observer.operationDidFinish(self, error: anError)\n }\n }\n }\n\n // MARK: - Private\n\n internal func didEnqueue() {\n operationLock.lock()\n defer { operationLock.unlock() }\n\n guard state == .initialized else {\n return\n }\n\n state = .pending\n }\n\n private func checkReadiness() {\n operationLock.lock()\n defer { operationLock.unlock() }\n\n if state == .pending, !_isCancelled, super.isReady {\n evaluateConditions()\n }\n }\n\n private func tryFinish(error: Error?) -> Bool {\n operationLock.lock()\n defer { operationLock.unlock() }\n\n guard state < .finished else { return false }\n\n _error = error\n state = .finished\n\n return true\n }\n\n private func notifyCancellation() {\n operationDidCancel()\n\n for observer in _observers {\n observer.operationDidCancel(self)\n }\n }\n\n // MARK: - Subclass overrides\n\n open func operationDidCancel() {\n // Override in subclasses.\n }\n\n open func operationDidFinish() {\n // Override in subclasses.\n }\n}\n\nextension AsyncOperation: OperationBlockObserverSupport {}\n\nextension Operation {\n public func addDependencies(_ dependencies: [Operation]) {\n for dependency in dependencies {\n addDependency(dependency)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\AsyncOperation.swift
AsyncOperation.swift
Swift
10,241
0.95
0.065
0.125392
react-lib
326
2024-06-24T08:18:36.107302
Apache-2.0
false
e516f89bd8cf0358d7d6ebc52e2568b0
//\n// AsyncOperationQueue.swift\n// Operations\n//\n// Created by pronebird on 30/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class AsyncOperationQueue: OperationQueue, @unchecked Sendable {\n override public func addOperation(_ operation: Operation) {\n if let operation = operation as? AsyncOperation {\n let categories = operation.conditions\n .filter { condition in\n condition.isMutuallyExclusive\n }\n .map { condition in\n condition.name\n }\n\n if !categories.isEmpty {\n ExclusivityManager.shared.addOperation(operation, categories: Set(categories))\n }\n\n super.addOperation(operation)\n\n operation.didEnqueue()\n } else {\n super.addOperation(operation)\n }\n }\n\n override public func addOperations(_ operations: [Operation], waitUntilFinished wait: Bool) {\n for operation in operations {\n addOperation(operation)\n }\n\n if wait {\n for operation in operations {\n operation.waitUntilFinished()\n }\n }\n }\n\n public static func makeSerial() -> AsyncOperationQueue {\n let queue = AsyncOperationQueue()\n queue.maxConcurrentOperationCount = 1\n return queue\n }\n}\n\nprivate final class ExclusivityManager: @unchecked Sendable {\n static let shared = ExclusivityManager()\n\n private var operationsByCategory = [String: [Operation]]()\n private let nslock = NSLock()\n\n private init() {}\n\n func addOperation(_ operation: AsyncOperation, categories: Set<String>) {\n nslock.lock()\n defer { nslock.unlock() }\n\n for category in categories {\n var operations = operationsByCategory[category] ?? []\n\n if let lastOperation = operations.last {\n operation.addDependency(lastOperation)\n }\n\n operations.append(operation)\n\n operationsByCategory[category] = operations\n\n operation.onFinish { [weak self] op, _ in\n self?.removeOperation(op, categories: categories)\n }\n }\n }\n\n private func removeOperation(_ operation: Operation, categories: Set<String>) {\n nslock.lock()\n defer { nslock.unlock() }\n\n for category in categories {\n guard var operations = operationsByCategory[category] else {\n continue\n }\n\n if let index = operations.firstIndex(of: operation) {\n operations.remove(at: index)\n }\n\n if operations.isEmpty {\n operationsByCategory.removeValue(forKey: category)\n } else {\n operationsByCategory[category] = operations\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\AsyncOperationQueue.swift
AsyncOperationQueue.swift
Swift
2,894
0.95
0.117647
0.08642
python-kit
447
2025-05-09T13:20:13.582121
Apache-2.0
false
c5ed63528a272e076341315cfa8df1f6
//\n// BackgroundObserver.swift\n// Operations\n//\n// Created by pronebird on 31/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n#if canImport(UIKit)\n\nimport MullvadTypes\nimport UIKit\n\n@available(iOSApplicationExtension, unavailable)\npublic final class BackgroundObserver: OperationObserver {\n public let name: String\n public let backgroundTaskProvider: BackgroundTaskProviding\n public let cancelUponExpiration: Bool\n\n private var taskIdentifier: UIBackgroundTaskIdentifier?\n\n public init(backgroundTaskProvider: BackgroundTaskProviding, name: String, cancelUponExpiration: Bool) {\n self.backgroundTaskProvider = backgroundTaskProvider\n self.name = name\n self.cancelUponExpiration = cancelUponExpiration\n }\n\n public func didAttach(to operation: Operation) {\n let expirationHandler = cancelUponExpiration\n ? { @MainActor in operation.cancel() } as? @MainActor @Sendable () -> Void\n : nil\n\n taskIdentifier = backgroundTaskProvider.beginBackgroundTask(\n withName: name,\n expirationHandler: expirationHandler\n )\n }\n\n public func operationDidStart(_ operation: Operation) {\n // no-op\n }\n\n public func operationDidCancel(_ operation: Operation) {\n // no-op\n }\n\n public func operationDidFinish(_ operation: Operation, error: Error?) {\n if let taskIdentifier {\n backgroundTaskProvider.endBackgroundTask(taskIdentifier)\n }\n }\n}\n\n#endif\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\BackgroundObserver.swift
BackgroundObserver.swift
Swift
1,518
0.95
0.055556
0.255814
awesome-app
354
2024-04-17T10:24:11.733086
MIT
false
3f9ad277d4d8fe2749fbbc87eadfcc75
//\n// BlockCondition.swift\n// Operations\n//\n// Created by pronebird on 25/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class BlockCondition: OperationCondition {\n public typealias HandlerBlock = (Operation, @escaping (Bool) -> Void) -> Void\n\n public var name: String {\n "BlockCondition"\n }\n\n public var isMutuallyExclusive: Bool {\n false\n }\n\n public let block: HandlerBlock\n public init(block: @escaping HandlerBlock) {\n self.block = block\n }\n\n public func evaluate(for operation: Operation, completion: @escaping (Bool) -> Void) {\n block(operation, completion)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\BlockCondition.swift
BlockCondition.swift
Swift
687
0.95
0.066667
0.291667
node-utils
133
2024-01-06T17:20:50.151321
GPL-3.0
false
97d1d504574a2c16be7c0cecfda6ecda
//\n// GroupOperation.swift\n// Operations\n//\n// Created by pronebird on 31/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class GroupOperation: AsyncOperation, @unchecked Sendable {\n private let operationQueue = AsyncOperationQueue()\n private let children: [Operation]\n\n public init(operations: [Operation]) {\n children = operations\n\n super.init(dispatchQueue: nil)\n }\n\n override public func main() {\n let finishingOperation = BlockOperation()\n finishingOperation.completionBlock = { [weak self] in\n self?.finish()\n }\n finishingOperation.addDependencies(children)\n\n operationQueue.addOperations(children, waitUntilFinished: false)\n operationQueue.addOperation(finishingOperation)\n }\n\n override public func operationDidCancel() {\n operationQueue.cancelAllOperations()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\GroupOperation.swift
GroupOperation.swift
Swift
929
0.95
0.028571
0.25
python-kit
194
2023-07-11T13:17:59.153158
GPL-3.0
false
1928168414243f3865830c7e7f4976d3
//\n// MutuallyExclusive.swift\n// Operations\n//\n// Created by pronebird on 25/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class MutuallyExclusive: OperationCondition {\n public let name: String\n\n public var isMutuallyExclusive: Bool {\n true\n }\n\n public init(category: String) {\n name = "MutuallyExclusive<\(category)>"\n }\n\n public func evaluate(for operation: Operation, completion: @escaping (Bool) -> Void) {\n completion(true)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\MutuallyExclusive.swift
MutuallyExclusive.swift
Swift
537
0.95
0.08
0.35
vue-tools
196
2023-09-02T03:48:22.446430
GPL-3.0
false
739c4204c0aef6edfe9996d4a15be379
//\n// NoCancelledDependenciesCondition.swift\n// Operations\n//\n// Created by pronebird on 25/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class NoCancelledDependenciesCondition: OperationCondition {\n public var name: String {\n "NoCancelledDependenciesCondition"\n }\n\n public var isMutuallyExclusive: Bool {\n false\n }\n\n public init() {}\n\n public func evaluate(for operation: Operation, completion: @escaping (Bool) -> Void) {\n let satisfy = operation.dependencies.allSatisfy { operation in\n !operation.isCancelled\n }\n\n completion(satisfy)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\NoCancelledDependenciesCondition.swift
NoCancelledDependenciesCondition.swift
Swift
670
0.95
0.068966
0.304348
node-utils
186
2025-05-22T18:09:16.998281
GPL-3.0
false
1d376aa56c2b957a3375ba0b59b637d4
//\n// NoFailedDependenciesCondition.swift\n// Operations\n//\n// Created by pronebird on 25/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class NoFailedDependenciesCondition: OperationCondition {\n public var name: String {\n "NoFailedDependenciesCondition"\n }\n\n public var isMutuallyExclusive: Bool {\n false\n }\n\n public let ignoreCancellations: Bool\n public init(ignoreCancellations: Bool) {\n self.ignoreCancellations = ignoreCancellations\n }\n\n public func evaluate(for operation: Operation, completion: @escaping (Bool) -> Void) {\n let satisfy = operation.dependencies.allSatisfy { operation in\n let operationError = (operation as? AsyncOperation)?.error\n let isCancellationError = operationError?.isOperationCancellationError ?? false\n\n if operationError != nil, !isCancellationError {\n return false\n }\n\n // Treat OperationError.cancelled and isCancelled equally.\n if operation.isCancelled || isCancellationError, !self.ignoreCancellations {\n return false\n }\n\n return true\n }\n\n completion(satisfy)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\NoFailedDependenciesCondition.swift
NoFailedDependenciesCondition.swift
Swift
1,249
0.95
0.090909
0.228571
node-utils
61
2025-01-24T07:18:51.121438
BSD-3-Clause
false
756c0d7b838f1c875112da6476dafb1e
//\n// OperationBlockObserverSupport.swift\n// Operations\n//\n// Created by Jon Petersson on 2023-09-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol OperationBlockObserverSupport {}\n\nextension OperationBlockObserverSupport where Self: AsyncOperation {\n /// Add observer responding to cancellation event.\n public func onCancel(_ fn: @escaping (Self) -> Void) {\n addBlockObserver(OperationBlockObserver(didCancel: fn))\n }\n\n /// Add observer responding to finish event.\n public func onFinish(_ fn: @escaping (Self, Error?) -> Void) {\n addBlockObserver(OperationBlockObserver(didFinish: fn))\n }\n\n /// Add observer responding to start event.\n public func onStart(_ fn: @escaping (Self) -> Void) {\n addBlockObserver(OperationBlockObserver(didStart: fn))\n }\n\n /// Add block-based observer.\n public func addBlockObserver(_ observer: OperationBlockObserver<Self>) {\n addObserver(observer)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\OperationBlockObserverSupport.swift
OperationBlockObserverSupport.swift
Swift
1,003
0.95
0
0.407407
react-lib
968
2024-07-26T21:41:46.395616
GPL-3.0
false
2d4973bf651b8f8e5b3f5c782da7a25c
//\n// OperationCondition.swift\n// Operations\n//\n// Created by pronebird on 30/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol OperationCondition {\n var name: String { get }\n var isMutuallyExclusive: Bool { get }\n\n func evaluate(for operation: Operation, completion: @escaping (Bool) -> Void)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\OperationCondition.swift
OperationCondition.swift
Swift
365
0.95
0.0625
0.538462
vue-tools
227
2024-06-26T23:31:53.750037
BSD-3-Clause
false
3f1f8b3d85f6f3dd4c7106fecb6a1632
//\n// OperationError.swift\n// Operations\n//\n// Created by pronebird on 24/01/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum OperationError: LocalizedError, Equatable {\n /// Unsatisfied operation requirement.\n case unsatisfiedRequirement\n\n /// Operation cancelled.\n case cancelled\n\n public var errorDescription: String? {\n switch self {\n case .unsatisfiedRequirement:\n return "Unsatisfied operation requirement."\n case .cancelled:\n return "Operation was cancelled."\n }\n }\n}\n\nextension Error {\n public var isOperationCancellationError: Bool {\n (self as? OperationError) == .cancelled\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\OperationError.swift
OperationError.swift
Swift
724
0.95
0.03125
0.333333
vue-tools
959
2024-05-06T16:56:27.788024
MIT
false
4257acd3e25e8bbe5d617283368288d7
//\n// OperationObserver.swift\n// Operations\n//\n// Created by pronebird on 30/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol OperationObserver {\n func didAttach(to operation: Operation)\n func operationDidStart(_ operation: Operation)\n func operationDidCancel(_ operation: Operation)\n func operationDidFinish(_ operation: Operation, error: Error?)\n}\n\n/// Block based operation observer.\npublic class OperationBlockObserver<OperationType: Operation>: OperationObserver {\n public typealias VoidBlock = (OperationType) -> Void\n public typealias FinishBlock = (OperationType, Error?) -> Void\n\n private let _didAttach: VoidBlock?\n private let _didStart: VoidBlock?\n private let _didCancel: VoidBlock?\n private let _didFinish: FinishBlock?\n\n public init(\n didAttach: VoidBlock? = nil,\n didStart: VoidBlock? = nil,\n didCancel: VoidBlock? = nil,\n didFinish: FinishBlock? = nil\n ) {\n _didAttach = didAttach\n _didStart = didStart\n _didCancel = didCancel\n _didFinish = didFinish\n }\n\n public func didAttach(to operation: Operation) {\n if let operation = operation as? OperationType {\n _didAttach?(operation)\n }\n }\n\n public func operationDidStart(_ operation: Operation) {\n if let operation = operation as? OperationType {\n _didStart?(operation)\n }\n }\n\n public func operationDidCancel(_ operation: Operation) {\n if let operation = operation as? OperationType {\n _didCancel?(operation)\n }\n }\n\n public func operationDidFinish(_ operation: Operation, error: Error?) {\n if let operation = operation as? OperationType {\n _didFinish?(operation, error)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\OperationObserver.swift
OperationObserver.swift
Swift
1,821
0.95
0.079365
0.148148
awesome-app
420
2023-10-27T17:00:26.678890
Apache-2.0
false
866940e883f79cbaf8202cb907375d4b
//\n// OutputOperation.swift\n// Operations\n//\n// Created by pronebird on 31/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol OutputOperation: Operation {\n associatedtype Output: Sendable\n\n var output: Output? { get }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\OutputOperation.swift
OutputOperation.swift
Swift
285
0.95
0
0.583333
awesome-app
91
2025-05-10T22:28:59.739114
Apache-2.0
false
864992f7da50e80ecc67946865735877
//\n// ResultBlockOperation.swift\n// Operations\n//\n// Created by pronebird on 12/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport protocol MullvadTypes.Cancellable\n\npublic final class ResultBlockOperation<Success: Sendable>: ResultOperation<Success>, @unchecked Sendable {\n private var executor: ((@escaping @Sendable (Result<Success, Error>) -> Void) -> Cancellable?)?\n private var cancellableTask: Cancellable?\n\n public init(\n dispatchQueue: DispatchQueue? = nil,\n executionBlock: @escaping @Sendable (_ finish: @escaping (Result<Success, Error>) -> Void) -> Void\n ) {\n super.init(dispatchQueue: dispatchQueue)\n executor = { @Sendable finish in\n executionBlock(finish)\n return nil\n }\n }\n\n public init(dispatchQueue: DispatchQueue? = nil, executionBlock: @escaping @Sendable () throws -> Success) {\n super.init(dispatchQueue: dispatchQueue)\n executor = { @Sendable finish in\n finish(Result { try executionBlock() })\n return nil\n }\n }\n\n public init(\n dispatchQueue: DispatchQueue? = nil,\n cancellableTask: @escaping (_ finish: @escaping @Sendable (Result<Success, Error>) -> Void) -> Cancellable\n ) {\n super.init(dispatchQueue: dispatchQueue)\n executor = { cancellableTask($0) }\n }\n\n override public func main() {\n let executor = executor\n self.executor = nil\n\n assert(executor != nil)\n cancellableTask = executor?(self.finish)\n }\n\n override public func operationDidCancel() {\n cancellableTask?.cancel()\n }\n\n override public func operationDidFinish() {\n executor = nil\n cancellableTask = nil\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\ResultBlockOperation.swift
ResultBlockOperation.swift
Swift
1,772
0.95
0.033898
0.14
awesome-app
53
2025-02-23T08:21:07.918253
GPL-3.0
false
629389e537d68f335ed5ac78321717cf
//\n// ResultOperation.swift\n// Operations\n//\n// Created by pronebird on 23/03/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Base class for operations producing result.\nopen class ResultOperation<Success: Sendable>: AsyncOperation, OutputOperation, @unchecked Sendable {\n public typealias CompletionHandler = (sending Result<Success, Error>) -> Void\n\n private let nslock = NSLock()\n private var _output: Success?\n private var _completionQueue: DispatchQueue?\n private var _completionHandler: CompletionHandler?\n private var pendingFinish = false\n\n public var result: Result<Success, Error>? {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _output.map { .success($0) } ?? error.map { .failure($0) }\n }\n\n public var output: Success? {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _output\n }\n\n public var completionQueue: DispatchQueue? {\n get {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _completionQueue\n }\n set {\n nslock.lock()\n defer { nslock.unlock() }\n\n _completionQueue = newValue\n }\n }\n\n public var completionHandler: CompletionHandler? {\n get {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _completionHandler\n }\n set {\n nslock.lock()\n defer { nslock.unlock() }\n if !pendingFinish {\n _completionHandler = newValue\n }\n }\n }\n\n override public init(dispatchQueue: DispatchQueue?) {\n super.init(dispatchQueue: dispatchQueue)\n }\n\n public init(\n dispatchQueue: DispatchQueue?,\n completionQueue: DispatchQueue?,\n completionHandler: CompletionHandler?\n ) {\n _completionQueue = completionQueue\n _completionHandler = completionHandler\n\n super.init(dispatchQueue: dispatchQueue)\n }\n\n @available(*, unavailable)\n override public func finish() {\n _finish(result: .failure(OperationError.cancelled))\n }\n\n @available(*, unavailable)\n override public func finish(error: Error?) {\n _finish(result: .failure(error ?? OperationError.cancelled))\n }\n\n open func finish(result: Result<Success, Error>) {\n _finish(result: result)\n }\n\n private func _finish(result: Result<Success, Error>) {\n nslock.lock()\n // Bail if operation is already finishing.\n guard !pendingFinish else {\n nslock.unlock()\n return\n }\n\n // Mark that operation is pending finish.\n pendingFinish = true\n\n // Copy completion handler.\n nonisolated(unsafe) let completionHandler = _completionHandler\n\n // Unset completion handler.\n _completionHandler = nil\n\n // Copy completion value.\n if case let .success(output) = result {\n _output = output\n }\n\n // Copy completion queue.\n let completionQueue = _completionQueue\n nslock.unlock()\n\n dispatchAsyncOn(completionQueue) {\n completionHandler?(result)\n\n var error: Error?\n if case let .failure(failure) = result {\n error = failure\n }\n\n // Finish operation.\n super.finish(error: error)\n }\n }\n\n private func dispatchAsyncOn(_ queue: DispatchQueue?, _ block: @escaping @Sendable () -> Void) {\n guard let queue else {\n block()\n return\n }\n queue.async(execute: block)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\Operations\ResultOperation.swift
ResultOperation.swift
Swift
3,636
0.95
0.049645
0.132743
python-kit
989
2024-08-24T08:16:15.025267
Apache-2.0
false
ca680e1a2838a3b2849ec59bf71b459b
//\n// DeviceCheck.swift\n// PacketTunnel\n//\n// Created by pronebird on 13/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// The verdict of an account status check.\nenum AccountVerdict: Equatable {\n /// Account is no longer valid.\n case invalid\n\n /// Account is expired.\n case expired(Account)\n\n /// Account exists and has enough time left.\n case active(Account)\n}\n\n/// The verdict of a device status check.\nenum DeviceVerdict: Equatable {\n /// Device is revoked.\n case revoked\n\n /// Device exists but the public key registered on server does not match any longer.\n case keyMismatch\n\n /// Device is in good standing and should work as normal.\n case active\n}\n\n/// Type describing whether key rotation took place and the outcome of it.\nenum KeyRotationStatus: Equatable {\n /// No rotation took place yet.\n case noAction\n\n /// Rotation attempt took place but without success.\n case attempted(Date)\n\n /// Rotation attempt took place and succeeded.\n case succeeded(Date)\n\n /// Returns `true` if the status is `.succeeded`.\n var isSucceeded: Bool {\n if case .succeeded = self {\n return true\n } else {\n return false\n }\n }\n}\n\n/**\n Struct holding data associated with account and device diagnostics and also device key recovery performed by packet\n tunnel process.\n */\nstruct DeviceCheck: Equatable {\n /// The verdict of account status check.\n var accountVerdict: AccountVerdict\n\n /// The verdict of device status check.\n var deviceVerdict: DeviceVerdict\n\n // The status of the last performed key rotation.\n var keyRotationStatus: KeyRotationStatus\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\DeviceCheck\DeviceCheck.swift
DeviceCheck.swift
Swift
1,732
0.95
0.028571
0.446429
awesome-app
111
2024-03-21T11:00:03.686091
GPL-3.0
false
82cd492e96ec2749b99d10484116cc1f
//\n// DeviceCheckOperation.swift\n// PacketTunnel\n//\n// Created by pronebird on 20/04/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport PacketTunnelCore\nimport WireGuardKitTypes\n\n/**\n An operation that is responsible for performing account and device diagnostics and key rotation from within packet\n tunnel process.\n\n Packet tunnel runs this operation immediately as it starts, with `rotateImmediatelyOnKeyMismatch` flag set to\n `true` which forces key rotation to happpen immediately given that the key stored on server does not match the key\n stored on device. Unless the last rotation attempt took place less than 15 seconds ago in which case the key rotation\n is not performed.\n\n Other times, packet tunnel runs this operation with `rotateImmediatelyOnKeyMismatch` set to `false`, in which\n case it respects the 24 hour interval between key rotation retry attempts.\n */\nfinal class DeviceCheckOperation: ResultOperation<DeviceCheck>, @unchecked Sendable {\n private let logger = Logger(label: "DeviceCheckOperation")\n\n private let remoteService: DeviceCheckRemoteServiceProtocol\n private let deviceStateAccessor: DeviceStateAccessorProtocol\n private let rotateImmediatelyOnKeyMismatch: Bool\n\n private var tasks: [Cancellable] = []\n\n init(\n dispatchQueue: DispatchQueue,\n remoteSevice: DeviceCheckRemoteServiceProtocol,\n deviceStateAccessor: DeviceStateAccessorProtocol,\n rotateImmediatelyOnKeyMismatch: Bool,\n completionHandler: CompletionHandler? = nil\n ) {\n self.remoteService = remoteSevice\n self.deviceStateAccessor = deviceStateAccessor\n self.rotateImmediatelyOnKeyMismatch = rotateImmediatelyOnKeyMismatch\n\n super.init(dispatchQueue: dispatchQueue, completionQueue: dispatchQueue, completionHandler: completionHandler)\n }\n\n override func main() {\n startFlow { result in\n self.finish(result: result)\n }\n }\n\n override func operationDidCancel() {\n tasks.forEach { $0.cancel() }\n }\n\n // MARK: - Flow\n\n /**\n Begins the flow by fetching device state and then fetching account and device data. Calls `didReceiveData()` with\n the received data when done.\n */\n private func startFlow(completion: @escaping (Result<DeviceCheck, Error>) -> Void) {\n do {\n guard case let .loggedIn(accountData, deviceData) = try deviceStateAccessor.read() else {\n throw DeviceCheckError.invalidDeviceState\n }\n\n fetchData(\n accountNumber: accountData.number,\n deviceIdentifier: deviceData.identifier\n ) { [self] accountResult, deviceResult in\n didReceiveData(accountResult: accountResult, deviceResult: deviceResult, completion: completion)\n }\n } catch {\n completion(.failure(error))\n }\n }\n\n /**\n Handles received data results and initiates key rotation when the key stored on server does not match the key\n stored on device.\n */\n private func didReceiveData(\n accountResult: Result<Account, Error>,\n deviceResult: Result<Device, Error>,\n completion: @escaping (Result<DeviceCheck, Error>) -> Void\n ) {\n do {\n let accountVerdict = try accountVerdict(from: accountResult)\n let deviceVerdict = try deviceVerdict(from: deviceResult)\n\n // Do not rotate the key if account is invalid even if the API successfully returns a device.\n if accountVerdict != .invalid, deviceVerdict == .keyMismatch {\n rotateKeyIfNeeded { rotationResult in\n completion(rotationResult.map { rotationStatus in\n DeviceCheck(\n accountVerdict: accountVerdict,\n deviceVerdict: rotationStatus.isSucceeded ? .active : .keyMismatch,\n keyRotationStatus: rotationStatus\n )\n })\n }\n } else {\n completion(.success(DeviceCheck(\n accountVerdict: accountVerdict,\n deviceVerdict: deviceVerdict,\n keyRotationStatus: .noAction\n )))\n }\n } catch {\n completion(.failure(error))\n }\n }\n\n // MARK: - Data fetch\n\n /// Fetch account and device data simultaneously, upon completion calls completion handler passing the results to\n /// it.\n private func fetchData(\n accountNumber: String, deviceIdentifier: String,\n completion: @escaping (Result<Account, Error>, Result<Device, Error>) -> Void\n ) {\n nonisolated(unsafe) var accountResult: Result<Account, Error> = .failure(OperationError.cancelled)\n nonisolated(unsafe) var deviceResult: Result<Device, Error> = .failure(OperationError.cancelled)\n\n let dispatchGroup = DispatchGroup()\n\n dispatchGroup.enter()\n let accountTask = remoteService.getAccountData(accountNumber: accountNumber) { result in\n accountResult = result\n dispatchGroup.leave()\n }\n\n dispatchGroup.enter()\n let deviceTask = remoteService.getDevice(accountNumber: accountNumber, identifier: deviceIdentifier) { result in\n deviceResult = result\n dispatchGroup.leave()\n }\n\n tasks.append(contentsOf: [accountTask, deviceTask])\n\n dispatchGroup.notify(queue: dispatchQueue) {\n completion(accountResult, deviceResult)\n }\n }\n\n // MARK: - Key rotation\n\n /**\n Checks if the key should be rotated by checking when the last rotation took place. If conditions are satisfied,\n then it rotate device key by marking the beginning of key rotation, updating device state and persisting before\n proceeding to rotate the key.\n */\n private func rotateKeyIfNeeded(completion: @escaping (Result<KeyRotationStatus, Error>) -> Void) {\n let deviceState: DeviceState\n do {\n deviceState = try deviceStateAccessor.read()\n } catch {\n logger.error(error: error, message: "Failed to read device state before rotating the key.")\n completion(.failure(error))\n return\n }\n\n guard case let .loggedIn(accountData, deviceData) = deviceState else {\n logger.debug("Will not attempt to rotate the key as device is no longer logged in.")\n completion(.failure(DeviceCheckError.invalidDeviceState))\n return\n }\n\n var keyRotation = WgKeyRotation(data: deviceData)\n guard keyRotation.shouldRotateFromPacketTunnel(rotateImmediately: rotateImmediatelyOnKeyMismatch) else {\n completion(.success(.noAction))\n return\n }\n\n let publicKey = keyRotation.beginAttempt()\n\n do {\n try deviceStateAccessor.write(.loggedIn(accountData, keyRotation.data))\n } catch {\n logger.error(error: error, message: "Failed to persist updated device state before rotating the key.")\n completion(.failure(error))\n return\n }\n\n logger.debug("Rotate private key from packet tunnel.")\n\n let task = remoteService.rotateDeviceKey(\n accountNumber: accountData.number,\n identifier: deviceData.identifier,\n publicKey: publicKey\n ) { result in\n self.dispatchQueue.async {\n let returnResult = result.tryMap { device -> KeyRotationStatus in\n try self.completeKeyRotation(device)\n return .succeeded(Date())\n }\n .flatMapError { error in\n self.logger.error(error: error, message: "Failed to rotate device key.")\n\n if error.isOperationCancellationError {\n return .failure(error)\n } else {\n return .success(.attempted(Date()))\n }\n }\n\n completion(returnResult)\n }\n }\n\n tasks.append(task)\n }\n\n /**\n Updates device state with the new data received from `Device` and marks key rotation as completed by swapping the\n current private key and erasing information about the last key rotation attempt.\n */\n private func completeKeyRotation(_ device: Device) throws {\n logger.debug("Successfully rotated device key. Persisting device state...")\n\n let deviceState = try deviceStateAccessor.read()\n guard case let .loggedIn(accountData, deviceData) = deviceState else {\n logger.debug("Will not persist device state after rotating the key because device is no longer logged in.")\n throw DeviceCheckError.invalidDeviceState\n }\n\n var keyRotation = WgKeyRotation(data: deviceData)\n let isCompleted = keyRotation.setCompleted(with: device)\n\n if isCompleted {\n do {\n try deviceStateAccessor.write(.loggedIn(accountData, keyRotation.data))\n } catch {\n logger.error(error: error, message: "Failed to persist device state after rotating the key.")\n throw error\n }\n } else {\n logger.debug("Cannot complete key rotation due to rotation race.")\n\n throw DeviceCheckError.keyRotationRace\n }\n }\n\n // MARK: - Private helpers\n\n /// Converts account data result type into `AccountVerdict`.\n private func accountVerdict(from accountResult: Result<Account, Error>) throws -> AccountVerdict {\n do {\n let account = try accountResult.get()\n\n return account.expiry > Date() ? .active(account) : .expired(account)\n } catch let error as REST.Error where error.compareErrorCode(.invalidAccount) {\n return .invalid\n }\n }\n\n /// Converts device result type into `DeviceVerdict`.\n private func deviceVerdict(from deviceResult: Result<Device, Error>) throws -> DeviceVerdict {\n do {\n let deviceState = try deviceStateAccessor.read()\n guard let deviceData = deviceState.deviceData else { throw DeviceCheckError.invalidDeviceState }\n\n let device = try deviceResult.get()\n\n return deviceData.wgKeyData.privateKey.publicKey == device.pubkey ? .active : .keyMismatch\n } catch let error as REST.Error where error.compareErrorCode(.deviceNotFound) {\n return .revoked\n }\n }\n}\n\n/// An error used internally by `DeviceCheckOperation`.\npublic enum DeviceCheckError: LocalizedError, Equatable {\n /// Device is no longer logged in.\n case invalidDeviceState\n\n /// Main process has likely performed key rotation at the same time when packet tunnel was doing so.\n case keyRotationRace\n\n public var errorDescription: String? {\n switch self {\n case .invalidDeviceState:\n return "Cannot complete device check because device is no longer logged in."\n case .keyRotationRace:\n return "Detected key rotation race condition."\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\DeviceCheck\DeviceCheckOperation.swift
DeviceCheckOperation.swift
Swift
11,268
0.95
0.091216
0.116466
python-kit
450
2024-06-18T23:50:15.254172
Apache-2.0
false
4080c97571f2610d4495bd072f40eef2
//\n// DeviceCheckRemoteService.swift\n// PacketTunnel\n//\n// Created by pronebird on 30/05/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport WireGuardKitTypes\n\n/// An object that implements remote service used by `DeviceCheckOperation`.\nstruct DeviceCheckRemoteService: DeviceCheckRemoteServiceProtocol {\n private let accountsProxy: RESTAccountHandling\n private let devicesProxy: DeviceHandling\n\n init(accountsProxy: RESTAccountHandling, devicesProxy: DeviceHandling) {\n self.accountsProxy = accountsProxy\n self.devicesProxy = devicesProxy\n }\n\n func getAccountData(\n accountNumber: String,\n completion: @escaping @Sendable (Result<Account, Error>) -> Void\n ) -> Cancellable {\n accountsProxy.getAccountData(\n accountNumber: accountNumber,\n retryStrategy: .noRetry,\n completion: completion\n )\n }\n\n func getDevice(\n accountNumber: String,\n identifier: String,\n completion: @escaping @Sendable (Result<Device, Error>) -> Void\n ) -> Cancellable {\n devicesProxy.getDevice(\n accountNumber: accountNumber,\n identifier: identifier,\n retryStrategy: .noRetry,\n completion: completion\n )\n }\n\n func rotateDeviceKey(\n accountNumber: String,\n identifier: String,\n publicKey: PublicKey,\n completion: @escaping @Sendable (Result<Device, Error>) -> Void\n ) -> Cancellable {\n devicesProxy.rotateDeviceKey(\n accountNumber: accountNumber,\n identifier: identifier,\n publicKey: publicKey,\n retryStrategy: .default,\n completion: completion\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\DeviceCheck\DeviceCheckRemoteService.swift
DeviceCheckRemoteService.swift
Swift
1,798
0.95
0
0.142857
node-utils
963
2024-06-30T00:04:50.041008
GPL-3.0
false
5510f9c76bd4f9dc21b8c9644be50d5a
//\n// DeviceCheckRemoteServiceProtocol.swift\n// PacketTunnel\n//\n// Created by pronebird on 07/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport WireGuardKitTypes\n\n/// A protocol that formalizes remote service dependency used by `DeviceCheckOperation`.\nprotocol DeviceCheckRemoteServiceProtocol {\n func getAccountData(accountNumber: String, completion: @escaping @Sendable (Result<Account, Error>) -> Void)\n -> Cancellable\n func getDevice(\n accountNumber: String,\n identifier: String,\n completion: @escaping @Sendable (Result<Device, Error>) -> Void\n )\n -> Cancellable\n func rotateDeviceKey(\n accountNumber: String,\n identifier: String,\n publicKey: PublicKey,\n completion: @escaping @Sendable (Result<Device, Error>) -> Void\n ) -> Cancellable\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\DeviceCheck\DeviceCheckRemoteServiceProtocol.swift
DeviceCheckRemoteServiceProtocol.swift
Swift
892
0.95
0
0.296296
awesome-app
475
2024-12-16T01:16:31.875201
GPL-3.0
false
852f22a9bdd20328678d40ce334b4649
//\n// DeviceStateAccessor.swift\n// PacketTunnel\n//\n// Created by pronebird on 30/05/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\n/// An object that provides access to `DeviceState` used by `DeviceCheckOperation`.\nstruct DeviceStateAccessor: DeviceStateAccessorProtocol {\n func read() throws -> DeviceState {\n try SettingsManager.readDeviceState()\n }\n\n func write(_ deviceState: DeviceState) throws {\n try SettingsManager.writeDeviceState(deviceState)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\DeviceCheck\DeviceStateAccessor.swift
DeviceStateAccessor.swift
Swift
571
0.95
0.090909
0.421053
vue-tools
732
2024-06-19T15:25:48.140603
BSD-3-Clause
false
7d236f88da785923bdc69d60698f6d03
//\n// DeviceStateAccessorProtocol.swift\n// PacketTunnel\n//\n// Created by pronebird on 07/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\n/// A protocol that formalizes device state accessor dependency used by `DeviceCheckOperation`.\nprotocol DeviceStateAccessorProtocol {\n func read() throws -> DeviceState\n func write(_ deviceState: DeviceState) throws\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\DeviceCheck\DeviceStateAccessorProtocol.swift
DeviceStateAccessorProtocol.swift
Swift
431
0.95
0
0.571429
python-kit
657
2023-08-02T16:17:11.335744
GPL-3.0
false
8015cf7da1fc3dac26940d5d302b37bd
//\n// BlockedStateErrorMapper.swift\n// PacketTunnel\n//\n// Created by pronebird on 14/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\nimport WireGuardKit\n\n/**\n Struct responsible for mapping errors that may occur in the packet tunnel to the `BlockedStateReason`.\n */\npublic struct BlockedStateErrorMapper: BlockedStateErrorMapperProtocol {\n public func mapError(_ error: Error) -> BlockedStateReason {\n switch error {\n case let error as ReadDeviceDataError:\n // Such error is thrown by implementations of `SettingsReaderProtocol`.\n switch error {\n case .loggedOut:\n return .deviceLoggedOut\n case .revoked:\n return .deviceRevoked\n }\n\n case is UnsupportedSettingsVersionError:\n // Can be returned after updating the app. The tunnel is usually restarted right after but the main app\n // needs to be launched to perform settings migration.\n return .outdatedSchema\n\n case let keychainError as KeychainError where keychainError == .interactionNotAllowed:\n // Returned when reading device state from Keychain when it is locked on device boot.\n return .deviceLocked\n\n case let error as ReadSettingsVersionError:\n // Returned when reading tunnel settings from Keychain.\n // interactionNotAllowed is returned when device is locked on boot, otherwise it must be a generic error\n // when reading settings from keychain.\n if case KeychainError.interactionNotAllowed = error.underlyingError as? KeychainError {\n return .deviceLocked\n } else {\n return .readSettings\n }\n\n case let error as NoRelaysSatisfyingConstraintsError:\n // Returned by relay selector when there are no relays satisfying the given constraints.\n return switch error.reason {\n case .filterConstraintNotMatching:\n .noRelaysSatisfyingFilterConstraints\n case .entryEqualsExit:\n .multihopEntryEqualsExit\n case .noDaitaRelaysFound:\n .noRelaysSatisfyingDaitaConstraints\n case .noObfuscatedRelaysFound:\n .noRelaysSatisfyingObfuscationSettings\n default:\n .noRelaysSatisfyingConstraints\n }\n\n case is WireGuardAdapterError:\n // Any errors that originate from wireguard adapter including failure to set tunnel settings using\n // packet tunnel provider.\n return .tunnelAdapter\n\n case is PublicKeyError:\n // Returned when there is an endpoint but its public key is invalid.\n return .invalidRelayPublicKey\n\n default:\n // Everything else in case we introduce new errors and forget to handle them.\n return .unknown\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\BlockedStateErrorMapper.swift
BlockedStateErrorMapper.swift
Swift
3,043
0.95
0.063291
0.3
python-kit
300
2025-04-26T03:34:31.000587
GPL-3.0
false
7ecff6975176b4b5fdbcb3740fdbdce8
//\n// DeviceCheck+BlockedStateReason.swift\n// PacketTunnel\n//\n// Created by pronebird on 14/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport PacketTunnelCore\n\nextension DeviceCheck {\n /// Returns blocked state reason inferred from the device check result.\n var blockedStateReason: BlockedStateReason? {\n if case .invalid = accountVerdict {\n return .invalidAccount\n }\n\n if case .revoked = deviceVerdict {\n return .deviceRevoked\n }\n\n if case .expired = accountVerdict {\n return .accountExpired\n }\n\n return nil\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\DeviceCheck+BlockedStateReason.swift
DeviceCheck+BlockedStateReason.swift
Swift
655
0.95
0.103448
0.333333
awesome-app
987
2025-05-14T21:20:45.508923
MIT
false
27dbd88f9648ed4e68e956f0394cab52
//\n// DeviceChecker.swift\n// PacketTunnel\n//\n// Created by pronebird on 12/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport PacketTunnelCore\n\nfinal class DeviceChecker {\n private let dispatchQueue = DispatchQueue(label: "DeviceCheckerQueue")\n private let operationQueue = AsyncOperationQueue.makeSerial()\n\n private let accountsProxy: RESTAccountHandling\n private let devicesProxy: DeviceHandling\n\n init(accountsProxy: RESTAccountHandling, devicesProxy: DeviceHandling) {\n self.accountsProxy = accountsProxy\n self.devicesProxy = devicesProxy\n }\n\n /**\n Start device diagnostics to determine the reason why the tunnel is not functional.\n\n This involves the following steps:\n\n 1. Fetch account and device data.\n 2. Check account validity and whether it has enough time left.\n 3. Verify that current device is registered with backend and that both device and backend point to the same public\n key.\n 4. Rotate WireGuard key on key mismatch.\n */\n func start(rotateKeyOnMismatch: Bool) async -> Result<DeviceCheck, Error> {\n let checkOperation = DeviceCheckOperation(\n dispatchQueue: dispatchQueue,\n remoteSevice: DeviceCheckRemoteService(accountsProxy: accountsProxy, devicesProxy: devicesProxy),\n deviceStateAccessor: DeviceStateAccessor(),\n rotateImmediatelyOnKeyMismatch: rotateKeyOnMismatch\n )\n\n return await withTaskCancellationHandler {\n return await withCheckedContinuation { continuation in\n checkOperation.completionHandler = { result in\n continuation.resume(with: .success(result))\n }\n operationQueue.addOperation(checkOperation)\n }\n } onCancel: {\n checkOperation.cancel()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\DeviceChecker.swift
DeviceChecker.swift
Swift
1,944
0.95
0.017544
0.183673
react-lib
274
2024-01-06T09:27:41.368729
GPL-3.0
false
12a2fda4fd6696229513b03dd3893892
//\n// NEProviderStopReason+Debug.swift\n// PacketTunnel\n//\n// Created by pronebird on 14/04/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\nextension NEProviderStopReason: CustomStringConvertible {\n public var description: String {\n switch self {\n case .none:\n return "none"\n case .userInitiated:\n return "user initiated"\n case .providerFailed:\n return "provider failed"\n case .noNetworkAvailable:\n return "no network available"\n case .unrecoverableNetworkChange:\n return "unrecoverable network change"\n case .providerDisabled:\n return "provider disabled"\n case .authenticationCanceled:\n return "authentication cancelled"\n case .configurationFailed:\n return "configuration failed"\n case .idleTimeout:\n return "idle timeout"\n case .configurationDisabled:\n return "configuration disabled"\n case .configurationRemoved:\n return "configuration removed"\n case .superceded:\n return "superceded"\n case .userLogout:\n return "user logout"\n case .userSwitch:\n return "user switch"\n case .connectionFailed:\n return "connection failed"\n case .sleep:\n return "sleep"\n case .appUpdate:\n return "app update"\n @unknown default:\n return "unknown value (\(rawValue))"\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\NEProviderStopReason+Debug.swift
NEProviderStopReason+Debug.swift
Swift
1,567
0.95
0.037736
0.137255
awesome-app
46
2024-05-25T07:45:31.083850
MIT
false
7a5c8ca720632be8f3b6485ac03e0472
//\n// PacketTunnelPathObserver.swift\n// PacketTunnel\n//\n// Created by pronebird on 10/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadLogging\nimport MullvadTypes\nimport Network\nimport NetworkExtension\nimport PacketTunnelCore\n\nfinal class PacketTunnelPathObserver: DefaultPathObserverProtocol, Sendable {\n private let eventQueue: DispatchQueue\n private let pathMonitor: NWPathMonitor\n nonisolated(unsafe) let logger = Logger(label: "PacketTunnelPathObserver")\n private let stateLock = NSLock()\n\n nonisolated(unsafe) private var started = false\n\n public var currentPathStatus: Network.NWPath.Status {\n stateLock.withLock {\n pathMonitor.currentPath.status\n }\n }\n\n init(eventQueue: DispatchQueue) {\n self.eventQueue = eventQueue\n\n pathMonitor = NWPathMonitor(prohibitedInterfaceTypes: [.other])\n }\n\n func start(_ body: @escaping @Sendable (Network.NWPath.Status) -> Void) {\n stateLock.withLock {\n guard started == false else { return }\n defer { started = true }\n pathMonitor.pathUpdateHandler = { updatedPath in\n body(updatedPath.status)\n }\n\n pathMonitor.start(queue: eventQueue)\n }\n }\n\n func stop() {\n stateLock.withLock {\n guard started == true else { return }\n defer { started = false }\n pathMonitor.pathUpdateHandler = nil\n pathMonitor.cancel()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\PacketTunnelPathObserver.swift
PacketTunnelPathObserver.swift
Swift
1,529
0.95
0.017857
0.148936
awesome-app
276
2025-05-30T12:46:43.089031
GPL-3.0
false
cd86f9b7d33bdf416abcaab009def6e6
//\n// PacketTunnelProvider.swift\n// PacketTunnel\n//\n// Created by pronebird on 31/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\nimport NetworkExtension\nimport PacketTunnelCore\nimport WireGuardKitTypes\n\nclass PacketTunnelProvider: NEPacketTunnelProvider, @unchecked Sendable {\n private let internalQueue = DispatchQueue(label: "PacketTunnel-internalQueue")\n private let providerLogger: Logger\n\n private var actor: PacketTunnelActor!\n private var appMessageHandler: AppMessageHandler!\n private var stateObserverTask: AnyTask?\n private var deviceChecker: DeviceChecker!\n private var adapter: WgAdapter!\n private var relaySelector: RelaySelectorWrapper!\n private var ephemeralPeerExchangingPipeline: EphemeralPeerExchangingPipeline!\n private let tunnelSettingsUpdater: SettingsUpdater!\n private var encryptedDNSTransport: EncryptedDNSTransport!\n private var migrationManager: MigrationManager!\n let migrationFailureIterator = REST.RetryStrategy.failedMigrationRecovery.makeDelayIterator()\n\n private let tunnelSettingsListener = TunnelSettingsListener()\n private lazy var ephemeralPeerReceiver = {\n EphemeralPeerReceiver(tunnelProvider: adapter, keyReceiver: self)\n }()\n\n // swiftlint:disable:next function_body_length\n override init() {\n Self.configureLogging()\n providerLogger = Logger(label: "PacketTunnelProvider")\n providerLogger.info("Starting new packet tunnel")\n\n let containerURL = ApplicationConfiguration.containerURL\n let addressCache = REST.AddressCache(canWriteToCache: false, cacheDirectory: containerURL)\n addressCache.loadFromFile()\n\n let ipOverrideWrapper = IPOverrideWrapper(\n relayCache: RelayCache(cacheDirectory: containerURL),\n ipOverrideRepository: IPOverrideRepository()\n )\n tunnelSettingsUpdater = SettingsUpdater(listener: tunnelSettingsListener)\n migrationManager = MigrationManager(cacheDirectory: containerURL)\n\n super.init()\n\n performSettingsMigration()\n\n let transportProvider = setUpTransportProvider(\n appContainerURL: containerURL,\n ipOverrideWrapper: ipOverrideWrapper,\n addressCache: addressCache\n )\n\n let apiTransportProvider = APITransportProvider(\n requestFactory: MullvadApiRequestFactory(apiContext: REST.apiContext)\n )\n\n adapter = WgAdapter(packetTunnelProvider: self)\n\n let pinger = TunnelPinger(pingProvider: adapter.icmpPingProvider, replyQueue: internalQueue)\n\n let tunnelMonitor = TunnelMonitor(\n eventQueue: internalQueue,\n pinger: pinger,\n tunnelDeviceInfo: adapter,\n timings: TunnelMonitorTimings()\n )\n\n let proxyFactory = REST.ProxyFactory.makeProxyFactory(\n transportProvider: transportProvider,\n apiTransportProvider: apiTransportProvider,\n addressCache: addressCache\n )\n let accountsProxy = proxyFactory.createAccountsProxy()\n let devicesProxy = proxyFactory.createDevicesProxy()\n\n deviceChecker = DeviceChecker(accountsProxy: accountsProxy, devicesProxy: devicesProxy)\n relaySelector = RelaySelectorWrapper(\n relayCache: ipOverrideWrapper\n )\n\n actor = PacketTunnelActor(\n timings: PacketTunnelActorTimings(),\n tunnelAdapter: adapter,\n tunnelMonitor: tunnelMonitor,\n defaultPathObserver: PacketTunnelPathObserver(eventQueue: internalQueue),\n blockedStateErrorMapper: BlockedStateErrorMapper(),\n relaySelector: relaySelector,\n settingsReader: TunnelSettingsManager(settingsReader: SettingsReader()) { [weak self] settings in\n guard let self = self else { return }\n tunnelSettingsListener.onNewSettings?(settings.tunnelSettings)\n },\n protocolObfuscator: ProtocolObfuscator<TunnelObfuscator>()\n )\n\n let urlRequestProxy = URLRequestProxy(\n dispatchQueue: internalQueue,\n transportProvider: transportProvider\n )\n let apiRequestProxy = APIRequestProxy(\n dispatchQueue: internalQueue,\n transportProvider: apiTransportProvider\n )\n appMessageHandler = AppMessageHandler(\n packetTunnelActor: actor,\n urlRequestProxy: urlRequestProxy,\n apiRequestProxy: apiRequestProxy\n )\n\n ephemeralPeerExchangingPipeline = EphemeralPeerExchangingPipeline(\n EphemeralPeerExchangeActor(\n packetTunnel: ephemeralPeerReceiver,\n onFailure: self.ephemeralPeerExchangeFailed,\n iteratorProvider: { REST.RetryStrategy.postQuantumKeyExchange.makeDelayIterator() }\n ),\n onUpdateConfiguration: { [unowned self] configuration in\n let channel = OneshotChannel()\n actor.changeEphemeralPeerNegotiationState(\n configuration: configuration,\n reconfigurationSemaphore: channel\n )\n await channel.receive()\n }, onFinish: { [unowned self] in\n actor.notifyEphemeralPeerNegotiated()\n }\n )\n }\n\n override func startTunnel(options: [String: NSObject]? = nil) async throws {\n let startOptions = parseStartOptions(options ?? [:])\n\n startObservingActorState()\n\n // Run device check during tunnel startup.\n // This check is allowed to push new key to server if there are some issues with it.\n startDeviceCheck(rotateKeyOnMismatch: true)\n\n actor.start(options: startOptions)\n\n for await state in await actor.observedStates {\n switch state {\n case .connected, .disconnected, .error:\n return\n case let .connecting(connectionState):\n // Give the tunnel a few tries to connect, otherwise return immediately. This will enable VPN in\n // device settings, but the app will still report the true state via ObservedState over IPC.\n // In essence, this prevents the 60s tunnel timeout to trigger.\n if connectionState.connectionAttemptCount > 1 {\n return\n }\n case .negotiatingEphemeralPeer:\n // When negotiating ephemeral peers, allow the connection to go through immediately.\n // Otherwise, the in-tunnel TCP connection will never become ready as the OS doesn't let\n // any traffic through until this function returns, which would prevent negotiating ephemeral peers\n // from an unconnected state.\n return\n default:\n break\n }\n }\n }\n\n override func stopTunnel(with reason: NEProviderStopReason) async {\n providerLogger.debug("stopTunnel: \(reason)")\n\n stopObservingActorState()\n\n actor.stop()\n\n await actor.waitUntilDisconnected()\n }\n\n override func handleAppMessage(_ messageData: Data) async -> Data? {\n return await appMessageHandler.handleAppMessage(messageData)\n }\n\n override func sleep() async {\n actor.onSleep()\n }\n\n override func wake() {\n actor.onWake()\n }\n\n private func performSettingsMigration() {\n nonisolated(unsafe) var hasNotMigrated = true\n repeat {\n migrationManager.migrateSettings(\n store: SettingsManager.store,\n migrationCompleted: { [unowned self] migrationResult in\n switch migrationResult {\n case .success:\n providerLogger.debug("Successful migration from PacketTunnel")\n hasNotMigrated = false\n case .nothing:\n hasNotMigrated = false\n providerLogger.debug("Attempted migration from PacketTunnel, but found nothing to do")\n case let .failure(error):\n providerLogger\n .error(\n "Failed migration from PacketTunnel: \(error)"\n )\n }\n }\n )\n if hasNotMigrated {\n // `next` returns an Optional value, but this iterator is guaranteed to always have a next value\n guard let delay = migrationFailureIterator.next() else { continue }\n\n providerLogger.error("Retrying migration in \(delay.timeInterval) seconds")\n // Block the launch of the Packet Tunnel for as long as the settings migration fail.\n // The process watchdog introduced by iOS 17 will kill this process after 60 seconds.\n Thread.sleep(forTimeInterval: delay.timeInterval)\n }\n } while hasNotMigrated\n }\n\n private func setUpTransportProvider(\n appContainerURL: URL,\n ipOverrideWrapper: IPOverrideWrapper,\n addressCache: REST.AddressCache\n ) -> TransportProvider {\n let urlSession = REST.makeURLSession(addressCache: addressCache)\n let urlSessionTransport = URLSessionTransport(urlSession: urlSession)\n let shadowsocksCache = ShadowsocksConfigurationCache(cacheDirectory: appContainerURL)\n\n let shadowsocksRelaySelector = ShadowsocksRelaySelector(\n relayCache: ipOverrideWrapper\n )\n\n let transportStrategy = TransportStrategy(\n datasource: AccessMethodRepository(),\n shadowsocksLoader: ShadowsocksLoader(\n cache: shadowsocksCache,\n relaySelector: shadowsocksRelaySelector,\n settingsUpdater: tunnelSettingsUpdater\n )\n )\n\n encryptedDNSTransport = EncryptedDNSTransport(urlSession: urlSession)\n return TransportProvider(\n urlSessionTransport: urlSessionTransport,\n addressCache: addressCache,\n transportStrategy: transportStrategy,\n encryptedDNSTransport: encryptedDNSTransport\n )\n }\n}\n\nextension PacketTunnelProvider {\n private static func configureLogging() {\n var loggerBuilder = LoggerBuilder(header: "PacketTunnel version \(Bundle.main.productVersion)")\n let pid = ProcessInfo.processInfo.processIdentifier\n loggerBuilder.metadata["pid"] = .string("\(pid)")\n loggerBuilder.addFileOutput(\n fileURL: ApplicationConfiguration.newLogFileURL(\n for: .packetTunnel,\n in: ApplicationConfiguration.containerURL\n )\n )\n #if DEBUG\n loggerBuilder.addOSLogOutput(subsystem: ApplicationTarget.packetTunnel.bundleIdentifier)\n #endif\n loggerBuilder.install()\n }\n\n private func parseStartOptions(_ options: [String: NSObject]) -> StartOptions {\n let tunnelOptions = PacketTunnelOptions(rawOptions: options)\n var parsedOptions = StartOptions(launchSource: tunnelOptions.isOnDemand() ? .onDemand : .app)\n\n do {\n if let selectedRelays = try tunnelOptions.getSelectedRelays() {\n parsedOptions.launchSource = .app\n parsedOptions.selectedRelays = selectedRelays\n } else if !tunnelOptions.isOnDemand() {\n parsedOptions.launchSource = .system\n }\n } catch {\n providerLogger.error(error: error, message: "Failed to decode relay selector result passed from the app.")\n }\n\n return parsedOptions\n }\n}\n\n// MARK: - State observer\n\nextension PacketTunnelProvider {\n private func startObservingActorState() {\n stopObservingActorState()\n\n stateObserverTask = Task {\n let stateStream = await self.actor.observedStates\n var lastConnectionAttempt: UInt = 0\n\n for await newState in stateStream {\n // Tell packet tunnel when reconnection begins.\n // Packet tunnel moves to `NEVPNStatus.reasserting` state once `reasserting` flag is set to `true`.\n if case .reconnecting = newState, !self.reasserting {\n self.reasserting = true\n }\n\n // Tell packet tunnel when reconnection ends.\n // Packet tunnel moves to `NEVPNStatus.connected` state once `reasserting` flag is set to `false`.\n if case .connected = newState, self.reasserting {\n self.reasserting = false\n }\n\n switch newState {\n case let .reconnecting(observedConnectionState), let .connecting(observedConnectionState):\n let connectionAttempt = observedConnectionState.connectionAttemptCount\n\n // Start device check every second failure attempt to connect.\n if lastConnectionAttempt != connectionAttempt, connectionAttempt > 0,\n connectionAttempt.isMultiple(of: 2) {\n startDeviceCheck()\n }\n\n // Cache last connection attempt to filter out repeating calls.\n lastConnectionAttempt = connectionAttempt\n\n case let .negotiatingEphemeralPeer(observedConnectionState, privateKey):\n await ephemeralPeerExchangingPipeline.startNegotiation(\n observedConnectionState,\n privateKey: privateKey\n )\n case .initial, .connected, .disconnecting, .disconnected, .error:\n break\n }\n }\n }\n }\n\n private func stopObservingActorState() {\n stateObserverTask?.cancel()\n stateObserverTask = nil\n }\n}\n\n// MARK: - Device check\n\nextension PacketTunnelProvider {\n private func startDeviceCheck(rotateKeyOnMismatch: Bool = false) {\n Task {\n await startDeviceCheckInner(rotateKeyOnMismatch: rotateKeyOnMismatch)\n }\n }\n\n private func startDeviceCheckInner(rotateKeyOnMismatch: Bool) async {\n let result = await deviceChecker.start(rotateKeyOnMismatch: rotateKeyOnMismatch)\n\n switch result {\n case let .failure(error):\n switch error {\n case is DeviceCheckError:\n providerLogger.error("\(error.localizedDescription) Forcing a log out")\n actor.setErrorState(reason: .deviceLoggedOut)\n default:\n providerLogger\n .error(\n "Device check encountered a network error: \(error.localizedDescription)"\n )\n }\n\n case let .success(keyRotationResult):\n if let blockedStateReason = keyRotationResult.blockedStateReason {\n providerLogger.error("Entering blocked state after unsuccessful device check: \(blockedStateReason)")\n actor.setErrorState(reason: blockedStateReason)\n return\n }\n\n switch keyRotationResult.keyRotationStatus {\n case let .attempted(date), let .succeeded(date):\n actor.notifyKeyRotation(date: date)\n case .noAction:\n break\n }\n }\n }\n}\n\nextension PacketTunnelProvider: EphemeralPeerReceiving {\n func receivePostQuantumKey(\n _ key: PreSharedKey,\n ephemeralKey: PrivateKey,\n daitaParameters: MullvadTypes.DaitaV2Parameters?\n ) async {\n await ephemeralPeerExchangingPipeline.receivePostQuantumKey(\n key,\n ephemeralKey: ephemeralKey,\n daitaParameters: daitaParameters\n )\n }\n\n public func receiveEphemeralPeerPrivateKey(\n _ ephemeralPeerPrivateKey: PrivateKey,\n daitaParameters: MullvadTypes.DaitaV2Parameters?\n ) async {\n await ephemeralPeerExchangingPipeline.receiveEphemeralPeerPrivateKey(\n ephemeralPeerPrivateKey,\n daitaParameters: daitaParameters\n )\n }\n\n func ephemeralPeerExchangeFailed() {\n // Do not try reconnecting to the `.current` relay, else the actor's `State` equality check will fail\n // and it will not try to reconnect\n actor.reconnect(to: .random, reconnectReason: .connectionLoss)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\PacketTunnelProvider.swift
PacketTunnelProvider.swift
Swift
16,492
0.95
0.06383
0.088154
react-lib
13
2025-02-13T00:33:50.812553
Apache-2.0
false
28590f044b00d5fc89ee33505ae3221b
//\n// SettingsReader.swift\n// PacketTunnel\n//\n// Created by pronebird on 30/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport PacketTunnelCore\n\nstruct SettingsReader: SettingsReaderProtocol {\n func read() throws -> Settings {\n let settings = try SettingsManager.readSettings()\n let deviceState = try SettingsManager.readDeviceState()\n let deviceData = try deviceState.getDeviceData()\n\n return Settings(\n privateKey: deviceData.wgKeyData.privateKey,\n interfaceAddresses: [deviceData.ipv4Address, deviceData.ipv6Address],\n tunnelSettings: settings\n )\n }\n}\n\nprivate extension DeviceState {\n /**\n Returns `StoredDeviceState` if device is logged in, otherwise throws an error.\n\n - Throws: an error of type `ReadDeviceDataError` when device is either revoked or logged out.\n - Returns: a copy of `StoredDeviceData` stored as associated value in `DeviceState.loggedIn` variant.\n */\n func getDeviceData() throws -> StoredDeviceData {\n switch self {\n case .revoked:\n throw ReadDeviceDataError.revoked\n case .loggedOut:\n throw ReadDeviceDataError.loggedOut\n case let .loggedIn(_, deviceData):\n return deviceData\n }\n }\n}\n\n/// Error returned when device state is either revoked or logged out.\npublic enum ReadDeviceDataError: LocalizedError {\n case loggedOut, revoked\n\n public var errorDescription: String? {\n switch self {\n case .loggedOut:\n return "Device is logged out."\n case .revoked:\n return "Device is revoked."\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PacketTunnelProvider\SettingsReader.swift
SettingsReader.swift
Swift
1,714
0.95
0.103448
0.196078
node-utils
696
2023-09-20T08:49:52.288018
MIT
false
f7e9e142a3ab3ed3c1b301897034e10b
//\n// PostQuantumKeyExchangingPipeline.swift\n// PacketTunnel\n//\n// Created by Mojgan on 2024-07-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\nimport WireGuardKitTypes\n\nfinal public class EphemeralPeerExchangingPipeline {\n let keyExchanger: EphemeralPeerExchangeActorProtocol\n let onUpdateConfiguration: (EphemeralPeerNegotiationState) async -> Void\n let onFinish: () -> Void\n\n private var ephemeralPeerExchanger: EphemeralPeerExchangingProtocol!\n\n public init(\n _ keyExchanger: EphemeralPeerExchangeActorProtocol,\n onUpdateConfiguration: @escaping (EphemeralPeerNegotiationState) async -> Void,\n onFinish: @escaping () -> Void\n ) {\n self.keyExchanger = keyExchanger\n self.onUpdateConfiguration = onUpdateConfiguration\n self.onFinish = onFinish\n }\n\n public func startNegotiation(_ connectionState: ObservedConnectionState, privateKey: PrivateKey) async {\n keyExchanger.reset()\n let entryPeer = connectionState.selectedRelays.entry\n let exitPeer = connectionState.selectedRelays.exit\n let enablePostQuantum = connectionState.isPostQuantum\n let enableDaita = connectionState.isDaitaEnabled\n if let entryPeer {\n ephemeralPeerExchanger = MultiHopEphemeralPeerExchanger(\n entry: entryPeer,\n exit: exitPeer,\n devicePrivateKey: privateKey,\n keyExchanger: keyExchanger,\n enablePostQuantum: enablePostQuantum,\n enableDaita: enableDaita,\n onUpdateConfiguration: self.onUpdateConfiguration,\n onFinish: onFinish\n )\n } else {\n ephemeralPeerExchanger = SingleHopEphemeralPeerExchanger(\n exit: exitPeer,\n devicePrivateKey: privateKey,\n keyExchanger: keyExchanger,\n enablePostQuantum: enablePostQuantum,\n enableDaita: enableDaita,\n onUpdateConfiguration: self.onUpdateConfiguration,\n onFinish: onFinish\n )\n }\n await ephemeralPeerExchanger.start()\n }\n\n public func receivePostQuantumKey(\n _ key: PreSharedKey,\n ephemeralKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async {\n await ephemeralPeerExchanger.receivePostQuantumKey(\n key,\n ephemeralKey: ephemeralKey,\n daitaParameters: daitaParameters\n )\n }\n\n public func receiveEphemeralPeerPrivateKey(\n _ ephemeralPeerPrivateKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async {\n await ephemeralPeerExchanger.receiveEphemeralPeerPrivateKey(\n ephemeralPeerPrivateKey,\n daitaParameters: daitaParameters\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PostQuantum\EphemeralPeerExchangingPipeline.swift
EphemeralPeerExchangingPipeline.swift
Swift
2,913
0.95
0.02381
0.090909
awesome-app
580
2023-11-28T20:14:46.526444
Apache-2.0
false
a2498ad5df1b59aec77c6e587e5c0ebd
//\n// MultiHopPostQuantumKeyExchanging.swift\n// PacketTunnel\n//\n// Created by Mojgan on 2024-07-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\nimport WireGuardKitTypes\n\nfinal class MultiHopEphemeralPeerExchanger: EphemeralPeerExchangingProtocol {\n let entry: SelectedRelay\n let exit: SelectedRelay\n let keyExchanger: EphemeralPeerExchangeActorProtocol\n let devicePrivateKey: PrivateKey\n let onFinish: () -> Void\n let onUpdateConfiguration: (EphemeralPeerNegotiationState) async -> Void\n let enablePostQuantum: Bool\n let enableDaita: Bool\n\n private var entryPeerKey: EphemeralPeerKey!\n private var exitPeerKey: EphemeralPeerKey!\n private var daitaParameters: DaitaV2Parameters?\n\n private let defaultGatewayAddressRange = [IPAddressRange(from: "\(LocalNetworkIPs.gatewayAddress.rawValue)/32")!]\n private let allTrafficRange = [\n IPAddressRange(from: "\(LocalNetworkIPs.defaultRouteIpV4.rawValue)/0")!,\n IPAddressRange(from: "\(LocalNetworkIPs.defaultRouteIpV6.rawValue)/0")!,\n ]\n\n private var state: StateMachine = .initial\n\n enum StateMachine {\n case initial\n case negotiatingWithEntry\n case negotiatingBetweenEntryAndExit\n case makeConnection\n }\n\n init(\n entry: SelectedRelay,\n exit: SelectedRelay,\n devicePrivateKey: PrivateKey,\n keyExchanger: EphemeralPeerExchangeActorProtocol,\n enablePostQuantum: Bool,\n enableDaita: Bool,\n onUpdateConfiguration: @escaping (EphemeralPeerNegotiationState) async -> Void,\n onFinish: @escaping () -> Void\n ) {\n self.entry = entry\n self.exit = exit\n self.devicePrivateKey = devicePrivateKey\n self.keyExchanger = keyExchanger\n self.enablePostQuantum = enablePostQuantum\n self.enableDaita = enableDaita\n self.onUpdateConfiguration = onUpdateConfiguration\n self.onFinish = onFinish\n }\n\n func start() async {\n guard state == .initial else { return }\n await negotiateWithEntry()\n }\n\n public func receiveEphemeralPeerPrivateKey(\n _ ephemeralPeerPrivateKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async {\n if state == .negotiatingWithEntry {\n self.daitaParameters = daitaParameters\n entryPeerKey = EphemeralPeerKey(ephemeralKey: ephemeralPeerPrivateKey)\n await negotiateBetweenEntryAndExit()\n } else if state == .negotiatingBetweenEntryAndExit {\n exitPeerKey = EphemeralPeerKey(ephemeralKey: ephemeralPeerPrivateKey)\n await makeConnection()\n }\n }\n\n func receivePostQuantumKey(\n _ preSharedKey: PreSharedKey,\n ephemeralKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async {\n if state == .negotiatingWithEntry {\n self.daitaParameters = daitaParameters\n entryPeerKey = EphemeralPeerKey(preSharedKey: preSharedKey, ephemeralKey: ephemeralKey)\n await negotiateBetweenEntryAndExit()\n } else if state == .negotiatingBetweenEntryAndExit {\n exitPeerKey = EphemeralPeerKey(preSharedKey: preSharedKey, ephemeralKey: ephemeralKey)\n await makeConnection()\n }\n }\n\n private func negotiateWithEntry() async {\n state = .negotiatingWithEntry\n await onUpdateConfiguration(.single(EphemeralPeerRelayConfiguration(\n relay: entry,\n configuration: EphemeralPeerConfiguration(\n privateKey: devicePrivateKey,\n allowedIPs: defaultGatewayAddressRange,\n daitaParameters: daitaParameters\n )\n )))\n keyExchanger.startNegotiation(\n with: devicePrivateKey,\n enablePostQuantum: enablePostQuantum,\n enableDaita: enableDaita\n )\n }\n\n private func negotiateBetweenEntryAndExit() async {\n state = .negotiatingBetweenEntryAndExit\n await onUpdateConfiguration(.multi(\n entry: EphemeralPeerRelayConfiguration(\n relay: entry,\n configuration: EphemeralPeerConfiguration(\n privateKey: entryPeerKey.ephemeralKey,\n preSharedKey: entryPeerKey.preSharedKey,\n allowedIPs: [IPAddressRange(from: "\(exit.endpoint.ipv4Relay.ip)/32")!],\n daitaParameters: self.daitaParameters\n )\n ),\n exit: EphemeralPeerRelayConfiguration(\n relay: exit,\n configuration: EphemeralPeerConfiguration(\n privateKey: devicePrivateKey,\n allowedIPs: defaultGatewayAddressRange,\n daitaParameters: nil\n )\n )\n ))\n // Daita is always disabled when negotiating with the exit peer in the multihop scenarios\n keyExchanger.startNegotiation(\n with: devicePrivateKey,\n enablePostQuantum: enablePostQuantum,\n enableDaita: false\n )\n }\n\n private func makeConnection() async {\n state = .makeConnection\n await onUpdateConfiguration(.multi(\n entry: EphemeralPeerRelayConfiguration(\n relay: entry,\n configuration: EphemeralPeerConfiguration(\n privateKey: entryPeerKey.ephemeralKey,\n preSharedKey: entryPeerKey.preSharedKey,\n allowedIPs: [IPAddressRange(from: "\(exit.endpoint.ipv4Relay.ip)/32")!],\n daitaParameters: self.daitaParameters\n )\n ),\n exit: EphemeralPeerRelayConfiguration(\n relay: exit,\n configuration: EphemeralPeerConfiguration(\n privateKey: exitPeerKey.ephemeralKey,\n preSharedKey: exitPeerKey.preSharedKey,\n allowedIPs: allTrafficRange,\n daitaParameters: nil\n )\n )\n ))\n self.onFinish()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PostQuantum\MultiHopEphemeralPeerExchanger.swift
MultiHopEphemeralPeerExchanger.swift
Swift
6,154
0.95
0.029586
0.051282
python-kit
116
2024-11-16T18:50:15.494417
BSD-3-Clause
false
2f26e2b5f15bbd24110b7bdca2b7cbc0
//\n// PostQuantumKeyExchangeActor.swift\n// PacketTunnel\n//\n// Created by Marco Nikic on 2024-04-12.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntimeProxy\nimport MullvadTypes\nimport NetworkExtension\nimport WireGuardKitTypes\n\npublic protocol PostQuantumKeyExchangeActorProtocol {\n func startNegotiation(with privateKey: PrivateKey)\n func endCurrentNegotiation()\n func reset()\n}\n\npublic class PostQuantumKeyExchangeActor: PostQuantumKeyExchangeActorProtocol {\n struct Negotiation {\n var negotiator: PostQuantumKeyNegotiating\n var inTunnelTCPConnection: NWTCPConnection\n var tcpConnectionObserver: NSKeyValueObservation\n\n func cancel() {\n negotiator.cancelKeyNegotiation()\n tcpConnectionObserver.invalidate()\n inTunnelTCPConnection.cancel()\n }\n }\n\n unowned let packetTunnel: any TunnelProvider\n internal var negotiation: Negotiation?\n private var timer: DispatchSourceTimer?\n private var keyExchangeRetriesIterator: AnyIterator<Duration>!\n private let iteratorProvider: () -> AnyIterator<Duration>\n private let negotiationProvider: PostQuantumKeyNegotiating.Type\n\n // Callback in the event of the negotiation failing on startup\n var onFailure: () -> Void\n\n public init(\n packetTunnel: any TunnelProvider,\n onFailure: @escaping (() -> Void),\n negotiationProvider: PostQuantumKeyNegotiating.Type = PostQuantumKeyNegotiator.self,\n iteratorProvider: @escaping () -> AnyIterator<Duration>\n ) {\n self.packetTunnel = packetTunnel\n self.onFailure = onFailure\n self.negotiationProvider = negotiationProvider\n self.iteratorProvider = iteratorProvider\n self.keyExchangeRetriesIterator = iteratorProvider()\n }\n\n private func createTCPConnection(_ gatewayEndpoint: NWHostEndpoint) -> NWTCPConnection {\n self.packetTunnel.createTCPConnectionThroughTunnel(\n to: gatewayEndpoint,\n enableTLS: false,\n tlsParameters: nil,\n delegate: nil\n )\n }\n\n /// Starts a new key exchange.\n ///\n /// Any ongoing key negotiation is stopped before starting a new one.\n /// An exponential backoff timer is used to stop the exchange if it takes too long,\n /// or if the TCP connection takes too long to become ready.\n /// It is reset after every successful key exchange.\n ///\n /// - Parameter privateKey: The device's current private key\n public func startNegotiation(with privateKey: PrivateKey) {\n endCurrentNegotiation()\n let negotiator = negotiationProvider.init()\n\n let gatewayAddress = "10.64.0.1"\n let IPv4Gateway = IPv4Address(gatewayAddress)!\n let endpoint = NWHostEndpoint(hostname: gatewayAddress, port: "\(CONFIG_SERVICE_PORT)")\n let inTunnelTCPConnection = createTCPConnection(endpoint)\n\n // This will become the new private key of the device\n let ephemeralSharedKey = PrivateKey()\n\n let tcpConnectionTimeout = keyExchangeRetriesIterator.next() ?? .seconds(10)\n // If the connection never becomes viable, force a reconnection after 10 seconds\n scheduleInTunnelConnectionTimeout(startTime: .now() + tcpConnectionTimeout)\n\n let tcpConnectionObserver = inTunnelTCPConnection.observe(\.isViable, options: [\n .initial,\n .new,\n ]) { [weak self] observedConnection, _ in\n guard let self, observedConnection.isViable else { return }\n self.negotiation?.tcpConnectionObserver.invalidate()\n self.timer?.cancel()\n\n if !negotiator.startNegotiation(\n gatewayIP: IPv4Gateway,\n devicePublicKey: privateKey.publicKey,\n presharedKey: ephemeralSharedKey,\n postQuantumKeyReceiver: packetTunnel,\n tcpConnection: inTunnelTCPConnection,\n postQuantumKeyExchangeTimeout: tcpConnectionTimeout\n ) {\n // Cancel the negotiation to shut down any remaining use of the TCP connection on the Rust side\n self.negotiation?.cancel()\n self.negotiation = nil\n self.onFailure()\n }\n }\n negotiation = Negotiation(\n negotiator: negotiator,\n inTunnelTCPConnection: inTunnelTCPConnection,\n tcpConnectionObserver: tcpConnectionObserver\n )\n }\n\n /// Cancels the ongoing key exchange.\n public func endCurrentNegotiation() {\n negotiation?.cancel()\n negotiation = nil\n }\n\n /// Resets the exponential timeout for successful key exchanges, and ends the current key exchange.\n public func reset() {\n keyExchangeRetriesIterator = iteratorProvider()\n endCurrentNegotiation()\n }\n\n private func scheduleInTunnelConnectionTimeout(startTime: DispatchWallTime) {\n let newTimer = DispatchSource.makeTimerSource()\n\n newTimer.setEventHandler { [weak self] in\n self?.onFailure()\n self?.timer?.cancel()\n }\n\n newTimer.schedule(wallDeadline: startTime)\n newTimer.activate()\n\n timer?.cancel()\n timer = newTimer\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PostQuantum\PostQuantumKeyExchangeActor.swift
PostQuantumKeyExchangeActor.swift
Swift
5,261
0.95
0.034483
0.168
vue-tools
505
2025-01-21T17:14:38.077657
Apache-2.0
false
334e5b5f338be3b5ac702ecd4a60e4bb
//\n// SingleHopPostQuantumKeyExchanging.swift\n// PacketTunnel\n//\n// Created by Mojgan on 2024-07-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\nimport WireGuardKitTypes\n\nstruct SingleHopEphemeralPeerExchanger: EphemeralPeerExchangingProtocol {\n let exit: SelectedRelay\n let keyExchanger: EphemeralPeerExchangeActorProtocol\n let devicePrivateKey: PrivateKey\n let onFinish: () -> Void\n let onUpdateConfiguration: (EphemeralPeerNegotiationState) async -> Void\n let enablePostQuantum: Bool\n let enableDaita: Bool\n\n init(\n exit: SelectedRelay,\n devicePrivateKey: PrivateKey,\n keyExchanger: EphemeralPeerExchangeActorProtocol,\n enablePostQuantum: Bool,\n enableDaita: Bool,\n onUpdateConfiguration: @escaping (EphemeralPeerNegotiationState) async -> Void,\n onFinish: @escaping () -> Void\n ) {\n self.devicePrivateKey = devicePrivateKey\n self.exit = exit\n self.keyExchanger = keyExchanger\n self.enablePostQuantum = enablePostQuantum\n self.enableDaita = enableDaita\n self.onUpdateConfiguration = onUpdateConfiguration\n self.onFinish = onFinish\n }\n\n func start() async {\n await onUpdateConfiguration(.single(EphemeralPeerRelayConfiguration(\n relay: exit,\n configuration: EphemeralPeerConfiguration(\n privateKey: devicePrivateKey,\n allowedIPs: [IPAddressRange(from: "\(LocalNetworkIPs.gatewayAddress.rawValue)/32")!],\n daitaParameters: nil\n )\n )))\n keyExchanger.startNegotiation(\n with: devicePrivateKey,\n enablePostQuantum: enablePostQuantum,\n enableDaita: enableDaita\n )\n }\n\n public func receiveEphemeralPeerPrivateKey(_ ephemeralKey: PrivateKey, daitaParameters: DaitaV2Parameters?) async {\n await onUpdateConfiguration(.single(EphemeralPeerRelayConfiguration(\n relay: exit,\n configuration: EphemeralPeerConfiguration(\n privateKey: ephemeralKey,\n preSharedKey: nil,\n allowedIPs: [\n IPAddressRange(from: "\(LocalNetworkIPs.defaultRouteIpV4.rawValue)/0")!,\n IPAddressRange(from: "\(LocalNetworkIPs.defaultRouteIpV6.rawValue)/0")!,\n ],\n daitaParameters: daitaParameters\n )\n )))\n self.onFinish()\n }\n\n func receivePostQuantumKey(\n _ preSharedKey: WireGuardKitTypes.PreSharedKey,\n ephemeralKey: WireGuardKitTypes.PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async {\n await onUpdateConfiguration(.single(EphemeralPeerRelayConfiguration(\n relay: exit,\n configuration: EphemeralPeerConfiguration(\n privateKey: ephemeralKey,\n preSharedKey: preSharedKey,\n allowedIPs: [\n IPAddressRange(from: "\(LocalNetworkIPs.defaultRouteIpV4.rawValue)/0")!,\n IPAddressRange(from: "\(LocalNetworkIPs.defaultRouteIpV6.rawValue)/0")!,\n ],\n daitaParameters: daitaParameters\n )\n )))\n self.onFinish()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\PostQuantum\SingleHopEphemeralPeerExchanger.swift
SingleHopEphemeralPeerExchanger.swift
Swift
3,350
0.95
0
0.079545
vue-tools
547
2024-08-11T06:09:10.823882
Apache-2.0
false
d1cdbda59bd909b93273f11fb63b41c6
//\n// WgAdapter.swift\n// PacketTunnel\n//\n// Created by pronebird on 29/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@preconcurrency import MullvadLogging\nimport MullvadTypes\nimport NetworkExtension\nimport PacketTunnelCore\n@preconcurrency import WireGuardKit\n\nclass WgAdapter: TunnelAdapterProtocol, @unchecked Sendable {\n let logger = Logger(label: "WgAdapter")\n let adapter: WireGuardAdapter\n\n init(packetTunnelProvider: NEPacketTunnelProvider) {\n let wgGoLogger = Logger(label: "WireGuard")\n\n adapter = WireGuardAdapter(\n with: packetTunnelProvider,\n shouldHandleReasserting: false,\n logHandler: { logLevel, string in\n wgGoLogger.log(level: logLevel.loggerLevel, "\(string)")\n }\n )\n }\n\n func start(configuration: TunnelAdapterConfiguration, daita: DaitaConfiguration?) async throws {\n let wgConfig = configuration.asWgConfig\n do {\n try await adapter.stop()\n try await adapter.start(tunnelConfiguration: wgConfig, daita: daita)\n } catch WireGuardAdapterError.invalidState {\n try await adapter.start(tunnelConfiguration: wgConfig, daita: daita)\n }\n\n let tunAddresses = wgConfig.interface.addresses.map { $0.address }\n // TUN addresses can be empty when adapter is configured for blocked state.\n if !tunAddresses.isEmpty {\n logIfDeviceHasSameIP(than: tunAddresses)\n }\n }\n\n func startMultihop(\n entryConfiguration: TunnelAdapterConfiguration? = nil,\n exitConfiguration: TunnelAdapterConfiguration,\n daita: DaitaConfiguration?\n ) async throws {\n let exitConfiguration = exitConfiguration.asWgConfig\n let entryConfiguration = entryConfiguration?.asWgConfig\n\n logger.info("\(exitConfiguration.peers)")\n\n if let entryConfiguration {\n logger.info("\(entryConfiguration.peers)")\n }\n\n do {\n try await adapter.stop()\n try await adapter.startMultihop(\n entryConfiguration: entryConfiguration,\n exitConfiguration: exitConfiguration,\n daita: daita\n )\n } catch WireGuardAdapterError.invalidState {\n try await adapter.startMultihop(\n entryConfiguration: entryConfiguration,\n exitConfiguration: exitConfiguration,\n daita: daita\n )\n }\n\n let exitTunAddresses = exitConfiguration.interface.addresses.map { $0.address }\n let entryTunAddresses = entryConfiguration?.interface.addresses.map { $0.address } ?? []\n let tunAddresses = exitTunAddresses + entryTunAddresses\n\n // TUN addresses can be empty when adapter is configured for blocked state.\n if !tunAddresses.isEmpty {\n logIfDeviceHasSameIP(than: tunAddresses)\n }\n }\n\n func stop() async throws {\n try await adapter.stop()\n }\n\n private func logIfDeviceHasSameIP(than addresses: [IPAddress]) {\n let sameIPv4 = IPv4Address("10.127.255.254")\n let sameIPv6 = IPv6Address("fc00:bbbb:bbbb:bb01:ffff:ffff:ffff:ffff")\n\n let hasIPv4SameAddress = addresses.compactMap { $0 as? IPv4Address }\n .contains { $0 == sameIPv4 }\n let hasIPv6SameAddress = addresses.compactMap { $0 as? IPv6Address }\n .contains { $0 == sameIPv6 }\n\n let isUsingSameIP = (hasIPv4SameAddress || hasIPv6SameAddress) ? "" : "NOT "\n logger.debug("Same IP is \(isUsingSameIP)being used")\n }\n\n public var icmpPingProvider: ICMPPingProvider {\n adapter\n }\n}\n\nextension WgAdapter: TunnelDeviceInfoProtocol {\n var interfaceName: String? {\n return adapter.interfaceName\n }\n\n func getStats() throws -> WgStats {\n var result: String?\n\n let dispatchGroup = DispatchGroup()\n dispatchGroup.enter()\n adapter.getRuntimeConfiguration { string in\n result = string\n dispatchGroup.leave()\n }\n\n guard case .success = dispatchGroup.wait(wallTimeout: .now() + 1) else { throw StatsError.timeout }\n guard let result else { throw StatsError.nilValue }\n guard let newStats = WgStats(from: result) else { throw StatsError.parse }\n\n return newStats\n }\n\n enum StatsError: LocalizedError {\n case timeout, nilValue, parse\n\n var errorDescription: String? {\n switch self {\n case .timeout:\n return "adapter.getRuntimeConfiguration() timeout."\n case .nilValue:\n return "Received nil string for stats."\n case .parse:\n return "Couldn't parse stats."\n }\n }\n }\n}\n\nprivate extension TunnelAdapterConfiguration {\n var asWgConfig: TunnelConfiguration {\n var interfaceConfig = InterfaceConfiguration(privateKey: privateKey)\n interfaceConfig.addresses = interfaceAddresses\n interfaceConfig.dns = dns.map { DNSServer(address: $0) }\n interfaceConfig.listenPort = 0\n\n var peers: [PeerConfiguration] = []\n if let peer {\n var peerConfig = PeerConfiguration(publicKey: peer.publicKey)\n peerConfig.endpoint = peer.endpoint.wgEndpoint\n peerConfig.allowedIPs = allowedIPs\n peerConfig.preSharedKey = peer.preSharedKey\n peers.append(peerConfig)\n }\n\n return TunnelConfiguration(\n name: nil,\n interface: interfaceConfig,\n peers: peers,\n pingableGateway: pingableGateway\n )\n }\n}\n\nprivate extension AnyIPEndpoint {\n var wgEndpoint: Endpoint {\n switch self {\n case let .ipv4(endpoint):\n return Endpoint(host: .ipv4(endpoint.ip), port: .init(integerLiteral: endpoint.port))\n case let .ipv6(endpoint):\n return Endpoint(host: .ipv6(endpoint.ip), port: .init(integerLiteral: endpoint.port))\n }\n }\n}\n\nprivate extension WgStats {\n init?(from string: String) {\n var bytesReceived: UInt64?\n var bytesSent: UInt64?\n\n string.enumerateLines { line, stop in\n if bytesReceived == nil, let value = parseValue("rx_bytes=", in: line) {\n bytesReceived = value\n } else if bytesSent == nil, let value = parseValue("tx_bytes=", in: line) {\n bytesSent = value\n }\n\n if bytesReceived != nil, bytesSent != nil {\n stop = true\n }\n }\n\n guard let bytesReceived, let bytesSent else {\n return nil\n }\n\n self.init(bytesReceived: bytesReceived, bytesSent: bytesSent)\n }\n}\n\n@inline(__always) private func parseValue(_ prefixKey: String, in line: String) -> UInt64? {\n guard line.hasPrefix(prefixKey) else { return nil }\n\n let value = line.dropFirst(prefixKey.count)\n\n return UInt64(value)\n}\n\nextension WgAdapter: TunnelProvider {\n public func tunnelHandle() throws -> Int32 {\n return try self.adapter.tunnelHandle()\n }\n\n public func wgFunctions() -> WgFunctionPointers {\n WgFunctionPointers(\n open: adapter.inTunnelTcpOpen,\n close: adapter.inTunnelTcpClose,\n receive: adapter.inTunnelTcpRecv,\n send: adapter.inTunnelTcpSend\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\WireGuardAdapter\WgAdapter.swift
WgAdapter.swift
Swift
7,375
0.95
0.100437
0.04712
vue-tools
406
2024-07-30T04:05:53.303159
MIT
false
7e79069e3a83cc4ef47bd525a4d1133e
//\n// WireGuardAdapter+Async.swift\n// PacketTunnel\n//\n// Created by pronebird on 30/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport WireGuardKit\n\nextension WireGuardAdapter {\n func start(tunnelConfiguration: TunnelConfiguration, daita: DaitaConfiguration?) async throws {\n return try await withCheckedThrowingContinuation { continuation in\n start(tunnelConfiguration: tunnelConfiguration, daita: daita) { error in\n if let error {\n continuation.resume(throwing: error)\n } else {\n continuation.resume(returning: ())\n }\n }\n }\n }\n\n func startMultihop(\n entryConfiguration: TunnelConfiguration?,\n exitConfiguration: TunnelConfiguration,\n daita: DaitaConfiguration?\n ) async throws {\n return try await withCheckedThrowingContinuation { continuation in\n startMultihop(\n exitConfiguration: exitConfiguration,\n entryConfiguration: entryConfiguration,\n daita: daita\n ) { error in\n if let error {\n continuation.resume(throwing: error)\n } else {\n continuation.resume(returning: ())\n }\n }\n }\n }\n\n func stop() async throws {\n return try await withCheckedThrowingContinuation { continuation in\n stop { error in\n if let error {\n continuation.resume(throwing: error)\n } else {\n continuation.resume(returning: ())\n }\n }\n }\n }\n\n func update(tunnelConfiguration: TunnelConfiguration) async throws {\n return try await withCheckedThrowingContinuation { continuation in\n update(tunnelConfiguration: tunnelConfiguration) { error in\n if let error {\n continuation.resume(throwing: error)\n } else {\n continuation.resume(returning: ())\n }\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\WireGuardAdapter\WireGuardAdapter+Async.swift
WireGuardAdapter+Async.swift
Swift
2,154
0.95
0.117647
0.111111
react-lib
856
2023-09-11T15:58:36.803106
MIT
false
87b0e64d653d05fcfdb0163fa1c10092
//\n// WireGuardAdapterError+Localization.swift\n// PacketTunnel\n//\n// Created by pronebird on 14/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport WireGuardKit\n\nextension WireGuardAdapterError: LocalizedError {\n public var errorDescription: String? {\n switch self {\n case .cannotLocateTunnelFileDescriptor:\n return "Failure to locate tunnel file descriptor."\n\n case .invalidState:\n return "Failure to perform an operation in such state."\n\n case let .dnsResolution(resolutionErrors):\n let detailedErrorDescription = resolutionErrors\n .enumerated()\n .map { index, dnsResolutionError in\n let errorDescription = dnsResolutionError.errorDescription ?? "???"\n\n return "\(index): \(dnsResolutionError.address) \(errorDescription)"\n }\n .joined(separator: "\n")\n\n return "Failure to resolve endpoints:\n\(detailedErrorDescription)"\n\n case .setNetworkSettings:\n return "Failure to set network settings."\n\n case let .startWireGuardBackend(code):\n return "Failure to start WireGuard backend (error code: \(code))."\n case .noInterfaceIp:\n return "Interface has no IP address specified."\n case .noSuchTunnel:\n return "No such WireGuard tunnel"\n case .noTunnelVirtualInterface:\n return "Tunnel has no virtual (IAN) interface"\n case .icmpSocketNotOpen:\n return "ICMP socket not open"\n case let .internalError(code):\n return "Internal error \(code)"\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\WireGuardAdapter\WireGuardAdapterError+Localization.swift
WireGuardAdapterError+Localization.swift
Swift
1,699
0.95
0.02
0.166667
react-lib
392
2023-08-03T19:02:37.015076
Apache-2.0
false
76433ec1eb2602f5ec8ca0f2d7dd080a
//\n// WireGuardLogLevel+Logging.swift\n// PacketTunnel\n//\n// Created by pronebird on 15/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport WireGuardKit\n\nextension WireGuardLogLevel {\n var loggerLevel: Logger.Level {\n switch self {\n case .verbose:\n return .debug\n case .error:\n return .error\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnel\WireGuardAdapter\WireGuardLogLevel+Logging.swift
WireGuardLogLevel+Logging.swift
Swift
425
0.95
0.045455
0.35
vue-tools
592
2024-06-14T10:15:32.049025
GPL-3.0
false
6b781510bc4462faa3264124a25d1b1e
//\n// AnyTask.swift\n// PacketTunnel\n//\n// Created by pronebird on 28/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A type-erased `Task`.\npublic protocol AnyTask: Sendable {\n /// Cancel task.\n func cancel()\n}\n\nextension Task: AnyTask {}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\AnyTask.swift
AnyTask.swift
Swift
294
0.95
0
0.642857
awesome-app
735
2024-08-24T01:27:13.911374
Apache-2.0
false
cf2bc1229cd7e0e511d36b8969fe7621
//\n// AutoCancellingTask.swift\n// PacketTunnel\n//\n// Created by pronebird on 31/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/**\n Type that cancels the task held inside upon `deinit`.\n\n It behaves identical to `Combine.AnyCancellable`.\n */\npublic final class AutoCancellingTask: Sendable {\n private let task: AnyTask\n\n init(_ task: AnyTask) {\n self.task = task\n }\n\n deinit {\n task.cancel()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\AutoCancellingTask.swift
AutoCancellingTask.swift
Swift
473
0.95
0.038462
0.428571
react-lib
430
2025-03-10T00:21:44.102066
BSD-3-Clause
false
ad24983023169c5eca7d797986d61097
//\n// ConfigurationBuilder.swift\n// PacketTunnel\n//\n// Created by pronebird on 30/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\nimport WireGuardKitTypes\n\n/// Error returned when there is an endpoint but its public key is invalid.\npublic struct PublicKeyError: LocalizedError {\n let endpoint: MullvadEndpoint\n\n public var errorDescription: String? {\n "Public key is invalid, endpoint: \(endpoint)"\n }\n}\n\n/// Struct building tunnel adapter configuration.\npublic struct ConfigurationBuilder {\n var privateKey: PrivateKey\n var interfaceAddresses: [IPAddressRange]\n var dns: SelectedDNSServers?\n var endpoint: MullvadEndpoint?\n var allowedIPs: [IPAddressRange]\n var preSharedKey: PreSharedKey?\n var pingableGateway: IPv4Address\n\n public init(\n privateKey: PrivateKey,\n interfaceAddresses: [IPAddressRange],\n dns: SelectedDNSServers? = nil,\n endpoint: MullvadEndpoint? = nil,\n allowedIPs: [IPAddressRange],\n preSharedKey: PreSharedKey? = nil,\n pingableGateway: IPv4Address\n ) {\n self.privateKey = privateKey\n self.interfaceAddresses = interfaceAddresses\n self.dns = dns\n self.endpoint = endpoint\n self.allowedIPs = allowedIPs\n self.preSharedKey = preSharedKey\n self.pingableGateway = pingableGateway\n }\n\n public func makeConfiguration() throws -> TunnelAdapterConfiguration {\n return TunnelAdapterConfiguration(\n privateKey: privateKey,\n interfaceAddresses: interfaceAddresses,\n dns: dnsServers,\n peer: try peer,\n allowedIPs: allowedIPs,\n pingableGateway: pingableGateway\n )\n }\n\n private var peer: TunnelPeer? {\n get throws {\n guard let endpoint else { return nil }\n\n guard let publicKey = PublicKey(rawValue: endpoint.publicKey) else {\n throw PublicKeyError(endpoint: endpoint)\n }\n\n return TunnelPeer(\n endpoint: .ipv4(endpoint.ipv4Relay),\n publicKey: publicKey,\n preSharedKey: preSharedKey\n )\n }\n }\n\n private var dnsServers: [IPAddress] {\n guard let dns else { return [] }\n\n switch dns {\n case let .blocking(dnsAddress):\n return [dnsAddress]\n case let .custom(customDNSAddresses):\n return customDNSAddresses\n case .gateway:\n guard let endpoint else { return [] }\n return [endpoint.ipv4Gateway, endpoint.ipv6Gateway]\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\ConfigurationBuilder.swift
ConfigurationBuilder.swift
Swift
2,659
0.95
0.021978
0.1125
awesome-app
995
2024-05-09T17:23:54.878254
GPL-3.0
false
d2da5c7386406d42fdc3fe7b138439bd
//\n// ConnectionConfigurationBuilder.swift\n// PacketTunnelCore\n//\n// Created by Mojgan on 2024-09-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\nimport WireGuardKitTypes\n\nprotocol Configuration {\n var name: String { get }\n func make() throws -> ConnectionConfiguration\n}\n\nstruct ConnectionConfiguration {\n let entryConfiguration: TunnelAdapterConfiguration?\n let exitConfiguration: TunnelAdapterConfiguration\n}\n\nstruct ConnectionConfigurationBuilder {\n enum ConnectionType {\n case normal\n case ephemeral(EphemeralPeerNegotiationState)\n }\n\n let type: ConnectionType\n let settings: Settings\n let connectionData: State.ConnectionData\n\n func make() throws -> ConnectionConfiguration {\n switch type {\n case .normal:\n try NormalConnectionConfiguration(settings: settings, connectionData: connectionData).make()\n case let .ephemeral(ephemeralPeerNegotiationState):\n try EphemeralConnectionConfiguration(\n settings: settings,\n connectionData: connectionData,\n ephemeralPeerNegotiationState: ephemeralPeerNegotiationState\n ).make()\n }\n }\n}\n\nprivate struct NormalConnectionConfiguration: Configuration {\n let settings: Settings\n let connectionData: State.ConnectionData\n\n var name: String {\n "Normal connection configuration"\n }\n\n private var activeKey: PrivateKey {\n switch connectionData.keyPolicy {\n case .useCurrent:\n settings.privateKey\n case let .usePrior(priorKey, _):\n priorKey\n }\n }\n\n func make() throws -> ConnectionConfiguration {\n let entryConfiguration: TunnelAdapterConfiguration? = if connectionData.selectedRelays.entry != nil {\n try ConfigurationBuilder(\n privateKey: activeKey,\n interfaceAddresses: settings.interfaceAddresses,\n dns: settings.dnsServers,\n endpoint: connectionData.connectedEndpoint,\n allowedIPs: [\n IPAddressRange(from: "\(connectionData.selectedRelays.exit.endpoint.ipv4Relay.ip)/32")!,\n ],\n pingableGateway: IPv4Address(LocalNetworkIPs.gatewayAddress.rawValue)!\n ).makeConfiguration()\n } else {\n nil\n }\n let exitConfiguration = try ConfigurationBuilder(\n privateKey: activeKey,\n interfaceAddresses: settings.interfaceAddresses,\n dns: settings.dnsServers,\n endpoint: (entryConfiguration != nil)\n ? connectionData.selectedRelays.exit.endpoint\n : connectionData.connectedEndpoint,\n allowedIPs: [\n IPAddressRange(from: "0.0.0.0/0")!,\n IPAddressRange(from: "::/0")!,\n ],\n pingableGateway: IPv4Address(LocalNetworkIPs.gatewayAddress.rawValue)!\n ).makeConfiguration()\n\n return ConnectionConfiguration(\n entryConfiguration: entryConfiguration,\n exitConfiguration: exitConfiguration\n )\n }\n}\n\nprivate struct EphemeralConnectionConfiguration: Configuration {\n let settings: Settings\n let connectionData: State.ConnectionData\n let ephemeralPeerNegotiationState: EphemeralPeerNegotiationState\n\n var name: String {\n "Ephemeral connection configuration"\n }\n\n func make() throws -> ConnectionConfiguration {\n switch ephemeralPeerNegotiationState {\n case let .single(hop):\n let exitConfiguration = try ConfigurationBuilder(\n privateKey: hop.configuration.privateKey,\n interfaceAddresses: settings.interfaceAddresses,\n dns: settings.dnsServers,\n endpoint: connectionData.connectedEndpoint,\n allowedIPs: hop.configuration.allowedIPs,\n preSharedKey: hop.configuration.preSharedKey,\n pingableGateway: IPv4Address(LocalNetworkIPs.gatewayAddress.rawValue)!\n ).makeConfiguration()\n\n return ConnectionConfiguration(entryConfiguration: nil, exitConfiguration: exitConfiguration)\n\n case let .multi(firstHop, secondHop):\n let entryConfiguration = try ConfigurationBuilder(\n privateKey: firstHop.configuration.privateKey,\n interfaceAddresses: settings.interfaceAddresses,\n dns: settings.dnsServers,\n endpoint: connectionData.connectedEndpoint,\n allowedIPs: firstHop.configuration.allowedIPs,\n preSharedKey: firstHop.configuration.preSharedKey,\n pingableGateway: IPv4Address(LocalNetworkIPs.gatewayAddress.rawValue)!\n ).makeConfiguration()\n\n let exitConfiguration = try ConfigurationBuilder(\n privateKey: secondHop.configuration.privateKey,\n interfaceAddresses: settings.interfaceAddresses,\n dns: settings.dnsServers,\n endpoint: secondHop.relay.endpoint,\n allowedIPs: secondHop.configuration.allowedIPs,\n preSharedKey: secondHop.configuration.preSharedKey,\n pingableGateway: IPv4Address(LocalNetworkIPs.gatewayAddress.rawValue)!\n ).makeConfiguration()\n\n return ConnectionConfiguration(entryConfiguration: entryConfiguration, exitConfiguration: exitConfiguration)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\ConnectionConfigurationBuilder.swift
ConnectionConfigurationBuilder.swift
Swift
5,502
0.95
0.073826
0.053435
python-kit
806
2024-09-09T06:55:04.758846
Apache-2.0
false
fc244fa808c36d2979345f96d6185d79
//\n// EphemeralPeerKey.swift\n// PacketTunnelCore\n//\n// Created by Mojgan on 2024-07-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport WireGuardKitTypes\n\n/// The preshared / private key used by ephemeral peers\npublic struct EphemeralPeerKey: Equatable {\n public let preSharedKey: PreSharedKey?\n public let ephemeralKey: PrivateKey\n\n public init(preSharedKey: PreSharedKey? = nil, ephemeralKey: PrivateKey) {\n self.preSharedKey = preSharedKey\n self.ephemeralKey = ephemeralKey\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\EphemeralPeerKey.swift
EphemeralPeerKey.swift
Swift
534
0.95
0
0.470588
python-kit
678
2023-08-08T04:51:33.956888
Apache-2.0
false
7c273d27e2e685660e9fdcc519ffd4f0
//\n// EphemeralPeerNegotiationState.swift\n// PacketTunnelCore\n//\n// Created by Mojgan on 2024-07-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadTypes\n@preconcurrency import WireGuardKitTypes\n\npublic enum EphemeralPeerNegotiationState: Equatable, Sendable {\n case single(EphemeralPeerRelayConfiguration)\n case multi(entry: EphemeralPeerRelayConfiguration, exit: EphemeralPeerRelayConfiguration)\n\n public static func == (lhs: EphemeralPeerNegotiationState, rhs: EphemeralPeerNegotiationState) -> Bool {\n return switch (lhs, rhs) {\n case let (.single(hop1), .single(hop2)):\n hop1 == hop2\n case let (.multi(entry: entry1, exit: exit1), .multi(entry: entry2, exit: exit2)):\n entry1 == entry2 && exit1 == exit2\n default:\n false\n }\n }\n}\n\npublic struct EphemeralPeerRelayConfiguration: Equatable, CustomDebugStringConvertible, Sendable {\n public let relay: SelectedRelay\n public let configuration: EphemeralPeerConfiguration\n\n public init(relay: SelectedRelay, configuration: EphemeralPeerConfiguration) {\n self.relay = relay\n self.configuration = configuration\n }\n\n public var debugDescription: String {\n "{ relay : \(relay.debugDescription), post quantum: \(configuration.debugDescription) }"\n }\n}\n\npublic struct EphemeralPeerConfiguration: Equatable, CustomDebugStringConvertible, Sendable {\n public let privateKey: PrivateKey\n public let preSharedKey: PreSharedKey?\n public let allowedIPs: [IPAddressRange]\n public let daitaParameters: DaitaV2Parameters?\n\n public init(\n privateKey: PrivateKey,\n preSharedKey: PreSharedKey? = nil,\n allowedIPs: [IPAddressRange],\n daitaParameters: DaitaV2Parameters?\n ) {\n self.privateKey = privateKey\n self.preSharedKey = preSharedKey\n self.allowedIPs = allowedIPs\n self.daitaParameters = daitaParameters\n }\n\n public var debugDescription: String {\n var string = "{ private key : \(privateKey),"\n string += preSharedKey.flatMap {\n "preShared key: \($0), "\n } ?? ""\n string += ", allowedIPs: \(allowedIPs) }"\n return string\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\EphemeralPeerNegotiationState.swift
EphemeralPeerNegotiationState.swift
Swift
2,260
0.95
0.014493
0.116667
python-kit
68
2023-11-14T09:19:47.884128
Apache-2.0
false
7e123faf5da83415631a680d87925211
//\n// EventChannel.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 27/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n// Formerly known as CommandChannel\n//\n\nimport Foundation\n\n/**\n Sync-to-async ordered coalescing channel with unbound buffering.\n\n Publishers send events over the channel to pass work to consumer. Received events\n are buffered, until requested by consumer and coalesced just before consumption.\n\n - Multiple consumers are possible but the actor is really expected to be the only consumer.\n - Internally, the channel acquires a lock, so you can assume FIFO ordering unless you publish values simultaneously from multiple concurrent queues.\n\n ### Example\n\n ```\n let channel = EventChannel()\n channel.send(.stop)\n ```\n\n Consuming events can be implemented using a for-await loop. Note that using a loop should also serialize the event handling as the next event will not\n be consumed until the body of the loop completes the iteration.\n\n ```\n Task.detached {\n for await event in channel {\n await handleMyEvent(event)\n }\n }\n ```\n\n Normally channel is expected to be infinite, but it's convenient to end the stream earlier, for instance when testing the coalescing algorithm:\n\n ```\n channel.send(.start(..))\n channel.send(.stop)\n channel.sendEnd()\n\n let allReceivedEvents = channel\n .map { "\($0)" }\n .reduce(into: [String]()) { $0.append($1) }\n ```\n */\nextension PacketTunnelActor {\n final class EventChannel: @unchecked Sendable {\n typealias Event = PacketTunnelActor.Event\n private enum State {\n /// Channel is active and running.\n case active\n\n /// Channel is awaiting for the buffer to be exhausted before ending all async iterations.\n /// Publishing new values in this state is impossible.\n case pendingEnd\n\n /// Channel finished its work.\n /// Publishing new values in this state is impossible.\n /// An attempt to iterate over the channel in this state is equivalent to iterating over an empty array.\n case finished\n }\n\n /// A buffer of events received but not consumed yet.\n private var buffer: [Event] = []\n\n /// Async continuations awaiting to receive the new value.\n /// Continuations are stored here when there is no new value available for immediate delivery.\n private var pendingContinuations: [CheckedContinuation<Event?, Never>] = []\n\n private var state: State = .active\n private var stateLock = NSLock()\n\n init() {}\n\n deinit {\n // Resume all continuations\n finish()\n }\n\n /// Send event to consumer.\n ///\n /// - Parameter value: a new event.\n func send(_ value: Event) {\n stateLock.withLock {\n guard case .active = state else { return }\n\n buffer.append(value)\n\n if !pendingContinuations.isEmpty, let nextValue = consumeFirst() {\n let continuation = pendingContinuations.removeFirst()\n continuation.resume(returning: nextValue)\n }\n }\n }\n\n /// Mark the end of channel but let consumers exchaust the buffer before declaring the end of iteration.\n /// If the buffer is empty then it should resume all pending continuations and send them `nil` to mark the end of iteration.\n func sendEnd() {\n stateLock.withLock {\n if case .active = state {\n state = .pendingEnd\n\n if buffer.isEmpty {\n state = .finished\n sendEndToPendingContinuations()\n }\n }\n }\n }\n\n /// Flush buffered events and resume all pending continuations sending them `nil` to mark the end of iteration.\n func finish() {\n stateLock.withLock {\n switch state {\n case .active, .pendingEnd:\n state = .finished\n buffer.removeAll()\n\n sendEndToPendingContinuations()\n\n case .finished:\n break\n }\n }\n }\n\n /// Send `nil` to mark the end of iteration to all pending continuations.\n private func sendEndToPendingContinuations() {\n for continuation in pendingContinuations {\n continuation.resume(returning: nil)\n }\n pendingContinuations.removeAll()\n }\n\n /// Consume first message in the buffer.\n /// Returns `nil` if the buffer is empty, otherwise if attempts to coalesce buffered events before consuming the first comand in the list.\n private func consumeFirst() -> Event? {\n guard !buffer.isEmpty else { return nil }\n\n coalesce()\n return buffer.removeFirst()\n }\n\n /// Coalesce buffered events to prevent future execution when the outcome is considered to be similar.\n /// Mutates internal `buffer`.\n private func coalesce() {\n var i = buffer.count - 1\n while i > 0 {\n defer { i -= 1 }\n\n assert(i < buffer.count)\n let current = buffer[i]\n\n // Remove all preceding events when encountered "stop".\n if case .stop = current {\n buffer.removeFirst(i)\n return\n }\n\n // Coalesce earlier reconnection attempts into the most recent.\n // This will rearrange the event buffer but hopefully should have no side effects.\n if case .reconnect = current {\n // Walk backwards starting with the preceding element.\n for j in (0 ..< i).reversed() {\n let preceding = buffer[j]\n // Remove preceding reconnect and adjust the index of the outer loop.\n if case .reconnect = preceding {\n buffer.remove(at: j)\n i -= 1\n }\n }\n }\n }\n }\n\n private func next() async -> Event? {\n return await withCheckedContinuation { continuation in\n stateLock.withLock {\n switch state {\n case .pendingEnd:\n if buffer.isEmpty {\n state = .finished\n continuation.resume(returning: nil)\n } else {\n // Keep consuming until the buffer is exhausted.\n fallthrough\n }\n\n case .active:\n if let value = consumeFirst() {\n continuation.resume(returning: value)\n } else {\n pendingContinuations.append(continuation)\n }\n\n case .finished:\n continuation.resume(returning: nil)\n }\n }\n }\n }\n }\n}\n\nextension PacketTunnelActor.EventChannel: AsyncSequence {\n typealias Element = Event\n\n struct AsyncIterator: AsyncIteratorProtocol {\n let channel: PacketTunnelActor.EventChannel\n func next() async -> Event? {\n return await channel.next()\n }\n }\n\n func makeAsyncIterator() -> AsyncIterator {\n return AsyncIterator(channel: self)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\EventChannel.swift
EventChannel.swift
Swift
7,640
0.95
0.09417
0.206522
node-utils
37
2023-09-08T12:11:29.960090
GPL-3.0
false
bd5e65ba2043df26600ec7147fb34d24
//\n// NetworkPath+.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 14/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\nextension Network.NWPath.Status {\n /// Converts `NetworkPath.status` into `NetworkReachability`.\n var networkReachability: NetworkReachability {\n switch self {\n case .satisfied:\n .reachable\n case .unsatisfied:\n .unreachable\n case .requiresConnection:\n .reachable\n @unknown default:\n .undetermined\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\NetworkPath+NetworkReachability.swift
NetworkPath+NetworkReachability.swift
Swift
587
0.95
0.038462
0.333333
node-utils
21
2023-10-31T11:21:24.161703
GPL-3.0
false
96074cd5e90a038ea528237a9a4862ae
//\n// ObservedState+Extensions.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 16/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nextension ObservedState {\n public var name: String {\n switch self {\n case .connected:\n "Connected"\n case .connecting:\n "Connecting"\n case .negotiatingEphemeralPeer:\n "Negotiating Post Quantum Secure Key"\n case .reconnecting:\n "Reconnecting"\n case .disconnecting:\n "Disconnecting"\n case .disconnected:\n "Disconnected"\n case .initial:\n "Initial"\n case .error:\n "Error"\n }\n }\n\n public var connectionState: ObservedConnectionState? {\n switch self {\n case\n let .connecting(connectionState),\n let .reconnecting(connectionState),\n let .connected(connectionState),\n let .negotiatingEphemeralPeer(connectionState, _),\n let .disconnecting(connectionState):\n connectionState\n default:\n nil\n }\n }\n\n public var blockedState: ObservedBlockedState? {\n switch self {\n case let .error(blockedState):\n blockedState\n default:\n nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\ObservedState+Extensions.swift
ObservedState+Extensions.swift
Swift
1,355
0.95
0.053571
0.134615
node-utils
767
2025-01-09T08:22:40.474754
GPL-3.0
false
be37cb57bd08c49b46a977b796e49fc9
//\n// ObservedState.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 11/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Network\n@preconcurrency import WireGuardKitTypes\n\n/// A serializable representation of internal state.\npublic enum ObservedState: Equatable, Codable, Sendable {\n case initial\n case connecting(ObservedConnectionState)\n case reconnecting(ObservedConnectionState)\n case negotiatingEphemeralPeer(ObservedConnectionState, PrivateKey)\n case connected(ObservedConnectionState)\n case disconnecting(ObservedConnectionState)\n case disconnected\n case error(ObservedBlockedState)\n}\n\n/// A serializable representation of internal connection state.\npublic struct ObservedConnectionState: Equatable, Codable, Sendable {\n public var selectedRelays: SelectedRelays\n public var relayConstraints: RelayConstraints\n public var networkReachability: NetworkReachability\n public var connectionAttemptCount: UInt\n public var transportLayer: TransportLayer\n public var remotePort: UInt16\n public var lastKeyRotation: Date?\n public let isPostQuantum: Bool\n public let isDaitaEnabled: Bool\n public let obfuscationMethod: WireGuardObfuscationState\n\n public var isNetworkReachable: Bool {\n networkReachability != .unreachable\n }\n\n public init(\n selectedRelays: SelectedRelays,\n relayConstraints: RelayConstraints,\n networkReachability: NetworkReachability,\n connectionAttemptCount: UInt,\n transportLayer: TransportLayer,\n remotePort: UInt16,\n lastKeyRotation: Date? = nil,\n isPostQuantum: Bool,\n isDaitaEnabled: Bool,\n obfuscationMethod: WireGuardObfuscationState = .off\n ) {\n self.selectedRelays = selectedRelays\n self.relayConstraints = relayConstraints\n self.networkReachability = networkReachability\n self.connectionAttemptCount = connectionAttemptCount\n self.transportLayer = transportLayer\n self.remotePort = remotePort\n self.lastKeyRotation = lastKeyRotation\n self.isPostQuantum = isPostQuantum\n self.isDaitaEnabled = isDaitaEnabled\n self.obfuscationMethod = obfuscationMethod\n }\n}\n\n/// A serializable representation of internal blocked state.\npublic struct ObservedBlockedState: Equatable, Codable, Sendable {\n public var reason: BlockedStateReason\n public var relayConstraints: RelayConstraints?\n\n public init(reason: BlockedStateReason, relayConstraints: RelayConstraints? = nil) {\n self.reason = reason\n self.relayConstraints = relayConstraints\n }\n}\n\nextension State {\n /// Map `State` to `ObservedState`.\n var observedState: ObservedState {\n switch self {\n case .initial:\n return .initial\n case let .connecting(connState):\n return .connecting(connState.observedConnectionState)\n case let .connected(connState):\n return .connected(connState.observedConnectionState)\n case let .reconnecting(connState):\n return .reconnecting(connState.observedConnectionState)\n case let .disconnecting(connState):\n return .disconnecting(connState.observedConnectionState)\n case let .negotiatingEphemeralPeer(connState, privateKey):\n return .negotiatingEphemeralPeer(connState.observedConnectionState, privateKey)\n case .disconnected:\n return .disconnected\n case let .error(blockedState):\n return .error(blockedState.observedBlockedState)\n }\n }\n}\n\nextension State.ConnectionData {\n /// Map `State.ConnectionData` to `ObservedConnectionState`.\n var observedConnectionState: ObservedConnectionState {\n ObservedConnectionState(\n selectedRelays: selectedRelays,\n relayConstraints: relayConstraints,\n networkReachability: networkReachability,\n connectionAttemptCount: connectionAttemptCount,\n transportLayer: transportLayer,\n remotePort: remotePort,\n lastKeyRotation: lastKeyRotation,\n isPostQuantum: isPostQuantum,\n isDaitaEnabled: isDaitaEnabled,\n obfuscationMethod: obfuscationMethod\n )\n }\n}\n\nextension State.BlockingData {\n /// Map `State.BlockingData` to `ObservedBlockedState`\n var observedBlockedState: ObservedBlockedState {\n return ObservedBlockedState(reason: reason, relayConstraints: relayConstraints)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\ObservedState.swift
ObservedState.swift
Swift
4,591
0.95
0.007752
0.109244
node-utils
946
2025-02-15T00:13:29.186097
Apache-2.0
false
589d1b3e35d7a8c25837dfd117ffb4b6
//\n// Actor+ConnectionMonitoring.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 26/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension PacketTunnelActor {\n /// Assign a closure receiving tunnel monitor events.\n func setTunnelMonitorEventHandler() {\n tunnelMonitor.onEvent = { [weak self] event in\n /// Dispatch tunnel monitor events via command channel to guarantee the order of execution.\n self?.eventChannel.send(.monitorEvent(event))\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+ConnectionMonitoring.swift
PacketTunnelActor+ConnectionMonitoring.swift
Swift
551
0.95
0
0.529412
awesome-app
935
2024-09-30T15:27:38.393699
GPL-3.0
false
e6b76bc5799637c2677fda10ce24fcc7
//\n// Actor+ErrorState.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 26/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\nimport WireGuardKitTypes\n\nextension PacketTunnelActor {\n /**\n Transition actor to error state.\n\n Evaluates the error and maps it to `BlockedStateReason` before switching actor to `.error` state.\n\n - Important: this method will suspend and must only be invoked as a part of channel consumer to guarantee transactional execution.\n\n - Parameter error: an error that occurred while starting the tunnel.\n */\n func setErrorStateInternal(with error: Error) async {\n let reason = blockedStateErrorMapper.mapError(error)\n\n await setErrorStateInternal(with: reason)\n }\n\n /**\n Transition actor to error state.\n\n Normally actor enters error state on its own, due to unrecoverable errors. However error state can also be induced externally for example in response to\n device check indicating certain issues that actor is not able to detect on its own such as invalid account or device being revoked on backend.\n\n - Important: this method will suspend and must only be invoked as a part of channel consumer to guarantee transactional execution.\n\n - Parameter reason: reason why the actor is entering error state.\n */\n func setErrorStateInternal(with reason: BlockedStateReason) async {\n // Tunnel monitor shouldn't run when in error state.\n tunnelMonitor.stop()\n\n if let blockedState = makeBlockedState(reason: reason) {\n state = .error(blockedState)\n await configureAdapterForErrorState()\n }\n }\n\n /**\n Derive `BlockedState` from current `state` updating it with the given block reason.\n\n - Parameter reason: block reason\n - Returns: New blocked state that should be assigned to error state, otherwise `nil` when actor is past or at `disconnecting` phase or\n when actor is already in the error state and no changes need to be made.\n */\n private func makeBlockedState(reason: BlockedStateReason) -> State.BlockingData? {\n switch state {\n case .initial:\n return State.BlockingData(\n reason: reason,\n relayConstraints: nil,\n currentKey: nil,\n keyPolicy: .useCurrent,\n networkReachability: defaultPathObserver.currentPathStatus.networkReachability,\n recoveryTask: startRecoveryTaskIfNeeded(reason: reason),\n priorState: .initial\n )\n\n case let .connected(connState):\n return mapConnectionState(connState, reason: reason, priorState: .connected)\n\n case let .connecting(connState):\n return mapConnectionState(connState, reason: reason, priorState: .connecting)\n\n case let .reconnecting(connState):\n return mapConnectionState(connState, reason: reason, priorState: .reconnecting)\n\n case var .error(blockedState):\n if blockedState.reason != reason {\n blockedState.reason = reason\n return blockedState\n } else {\n return nil\n }\n\n // Ephemeral peer exchange cannot enter the blocked state\n case .disconnecting, .disconnected, .negotiatingEphemeralPeer:\n return nil\n }\n }\n\n /**\n Map connection state to blocked state.\n */\n private func mapConnectionState(\n _ connState: State.ConnectionData,\n reason: BlockedStateReason,\n priorState: State.BlockingData.PriorState\n ) -> State.BlockingData {\n State.BlockingData(\n reason: reason,\n relayConstraints: connState.relayConstraints,\n currentKey: connState.currentKey,\n keyPolicy: connState.keyPolicy,\n networkReachability: connState.networkReachability,\n recoveryTask: startRecoveryTaskIfNeeded(reason: reason),\n priorState: priorState\n )\n }\n\n /**\n Configure tunnel with empty WireGuard configuration that consumes all traffic on device emulating a firewall blocking all traffic.\n */\n private func configureAdapterForErrorState() async {\n do {\n let configurationBuilder = ConfigurationBuilder(\n privateKey: PrivateKey(),\n interfaceAddresses: [],\n allowedIPs: [],\n pingableGateway: IPv4Address(LocalNetworkIPs.gatewayAddress.rawValue)!\n )\n var config = try configurationBuilder.makeConfiguration()\n config.dns = [IPv4Address.loopback]\n config.interfaceAddresses = [IPAddressRange(from: "\(LocalNetworkIPs.gatewayAddress.rawValue)/8")!]\n config.peer = TunnelPeer(\n endpoint: .ipv4(IPv4Endpoint(string: "127.0.0.1:9090")!),\n publicKey: PrivateKey().publicKey\n )\n try? await tunnelAdapter.stop()\n try await tunnelAdapter.start(configuration: config, daita: nil)\n } catch {\n logger.error(error: error, message: "Unable to configure the tunnel for error state.")\n }\n }\n\n /**\n Start a task that will attempt to reconnect the tunnel periodically, but only if the tunnel can recover from error state automatically.\n\n See `BlockedStateReason.shouldRestartAutomatically` for more info.\n\n - Parameter reason: the reason why actor is entering blocked state.\n - Returns: a task that will attempt to perform periodic recovery when applicable, otherwise `nil`.\n */\n private func startRecoveryTaskIfNeeded(reason: BlockedStateReason) -> AutoCancellingTask? {\n guard reason.shouldRestartAutomatically else { return nil }\n\n // Use detached task to prevent inheriting current context.\n let task = Task.detached { [weak self] in\n while !Task.isCancelled {\n guard let self else { return }\n\n try await Task.sleepUsingContinuousClock(for: timings.bootRecoveryPeriodicity)\n\n // Schedule task to reconnect.\n eventChannel.send(.reconnect(.random))\n }\n }\n\n return AutoCancellingTask(task)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+ErrorState.swift
PacketTunnelActor+ErrorState.swift
Swift
6,286
0.95
0.092593
0.17037
python-kit
280
2025-02-03T03:05:49.448184
GPL-3.0
false
0a5dbef805d9c540c1e8a73c13651e68
//\n// Actor+.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 07/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\n\nextension PacketTunnelActor {\n /// Returns a stream yielding `ObservedState`.\n /// Note that the stream yields current value when created.\n public var observedStates: AsyncStream<ObservedState> {\n AsyncStream { continuation in\n let cancellable = $observedState.sink { newState in\n continuation.yield(newState)\n\n // Finish stream once entered `.disconnected` state.\n if case .disconnected = newState {\n continuation.finish()\n }\n }\n\n continuation.onTermination = { _ in\n cancellable.cancel()\n }\n }\n }\n\n /// Wait until the `observedState` moved to `.disiconnected`.\n public func waitUntilDisconnected() async {\n for await newState in observedStates {\n if case .disconnected = newState {\n return\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+Extensions.swift
PacketTunnelActor+Extensions.swift
Swift
1,108
0.95
0.075
0.314286
python-kit
746
2023-09-28T17:22:48.415916
BSD-3-Clause
false
441adf988677b7431426290f31498a4b
//\n// Actor+KeyPolicy.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 26/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension PacketTunnelActor {\n /**\n Cache WG active key for a period of time, before switching to using the new one stored in settings.\n\n This function replaces the key policy to `.usePrior` caching the currently used key in associated value.\n\n That cached key is used by actor for some time until the new key is propagated across relays. Then it flips the key policy back to `.useCurrent` and\n reconnects the tunnel using new key.\n\n The `lastKeyRotation` passed as an argument is a simple marker value passed back to UI process with actor state. This date can be used to determine when\n the main app has to re-read device state from Keychain, since there is no other mechanism to notify other process when packet tunnel mutates keychain store.\n\n - Parameter lastKeyRotation: date when last key rotation took place.\n */\n func cacheActiveKey(lastKeyRotation: Date?) {\n state.mutateAssociatedData { stateData in\n guard\n stateData.keyPolicy == .useCurrent,\n let currentKey = stateData.currentKey\n else { return }\n // Key policy is preserved between states and key rotation may still happen while in blocked state.\n // Therefore perform the key switch as normal with one exception that it shouldn't reconnect the tunnel\n // automatically.\n stateData.lastKeyRotation = lastKeyRotation\n\n // Move currentKey into keyPolicy.\n stateData.keyPolicy = .usePrior(currentKey, startKeySwitchTask())\n stateData.currentKey = nil\n }\n }\n\n /**\n Switch key policy from `.usePrior` to `.useCurrent` policy and reconnect the tunnel.\n\n Next reconnection attempt will read the new key from settings.\n */\n func switchToCurrentKey() {\n if switchToCurrentKeyInner() {\n eventChannel.send(.reconnect(.random))\n }\n }\n\n /**\n Start a task that will wait for the new key to propagate across relays (see `PacketTunnelActorTimings.wgKeyPropagationDelay`) and then:\n\n 1. Switch `keyPolicy` back to `.useCurrent`.\n 2. Reconnect the tunnel using the new key (currently stored in device state)\n */\n private func startKeySwitchTask() -> AutoCancellingTask {\n // Use detached task to prevent inheriting current context.\n let task = Task.detached { [weak self] in\n guard let self else { return }\n\n // Wait for key to propagate across relays.\n try await Task.sleepUsingContinuousClock(for: timings.wgKeyPropagationDelay)\n\n // Enqueue task to change key policy.\n eventChannel.send(.switchKey)\n }\n\n return AutoCancellingTask(task)\n }\n\n /**\n Switch key policy from `.usePrior` to `.useCurrent` policy.\n\n - Returns: `true` if the tunnel should reconnect, otherwise `false`.\n */\n private func switchToCurrentKeyInner() -> Bool {\n let oldKeyPolicy = state.keyPolicy\n state.mutateKeyPolicy(setCurrentKeyPolicy)\n // Prevent tunnel from reconnecting when in blocked state.\n guard case .error = state else { return state.keyPolicy != oldKeyPolicy }\n return false\n }\n\n /**\n Internal helper that transitions key policy from `.usePrior` to `.useCurrent`.\n\n - Parameter keyPolicy: a reference to key policy held either in connection state or blocked state struct.\n - Returns: `true` when the policy was modified, otherwise `false`.\n */\n private func setCurrentKeyPolicy(_ keyPolicy: inout State.KeyPolicy) {\n if case .usePrior = keyPolicy {\n keyPolicy = .useCurrent\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+KeyPolicy.swift
PacketTunnelActor+KeyPolicy.swift
Swift
3,837
0.95
0.122449
0.3125
python-kit
202
2023-08-07T06:18:24.571398
MIT
false
0362d968c7460b119bd6c05a9c5e909c
//\n// Actor+NetworkReachability.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 26/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\nextension PacketTunnelActor {\n /**\n Start observing changes to default path.\n\n - Parameter notifyObserverWithCurrentPath: immediately notifies path observer with the current path when set to `true`.\n */\n func startDefaultPathObserver() {\n logger.trace("Start default path observer.")\n\n defaultPathObserver.start { [weak self] networkPath in\n self?.eventChannel.send(.networkReachability(networkPath))\n }\n }\n\n /// Stop observing changes to default path.\n func stopDefaultPathObserver() {\n logger.trace("Stop default path observer.")\n\n defaultPathObserver.stop()\n }\n\n /**\n Event handler that receives new network path from tunnel monitor and updates internal state with new network reachability status.\n\n - Parameter networkPath: new default path\n */\n func handleDefaultPathChange(_ networkPath: Network.NWPath.Status) {\n tunnelMonitor.handleNetworkPathUpdate(networkPath)\n\n let newReachability = networkPath.networkReachability\n\n state.mutateAssociatedData { $0.networkReachability = newReachability }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+NetworkReachability.swift
PacketTunnelActor+NetworkReachability.swift
Swift
1,324
0.95
0
0.342857
react-lib
498
2023-12-27T01:51:21.148223
GPL-3.0
false
0c1c09507314a128846ab7edf34bba55
//\n// PacketTunnelActor+PostQuantum.swift\n// PacketTunnelCore\n//\n// Created by Andrew Bulhak on 2024-05-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport WireGuardKitTypes\n\nextension PacketTunnelActor {\n /**\n Attempt to start the process of negotiating a post-quantum secure key, setting up an initial\n connection restricted to the negotiation host and entering the negotiating state.\n */\n internal func tryStartEphemeralPeerNegotiation(\n withSettings settings: Settings,\n nextRelays: NextRelays,\n reason: ActorReconnectReason\n ) async throws {\n if let connectionState = try obfuscateConnection(nextRelays: nextRelays, settings: settings, reason: reason) {\n let activeKey = activeKey(from: connectionState, in: settings)\n state = .negotiatingEphemeralPeer(connectionState, activeKey)\n }\n }\n\n /**\n Called on receipt of the new PQ-negotiated key, to reconnect to the relay, in PQ-secure mode.\n */\n internal func connectWithEphemeralPeer() async {\n guard let connectionData = state.connectionData else {\n logger.error("Could not create connection state in PostQuantumConnect")\n eventChannel.send(.reconnect(.current))\n return\n }\n\n state = .connecting(connectionData)\n\n // Resume tunnel monitoring and use IPv4 gateway as a probe address.\n tunnelMonitor.start(probeAddress: connectionData.selectedRelays.exit.endpoint.ipv4Gateway)\n // Restart default path observer and notify the observer with the current path that might have changed while\n // path observer was paused.\n startDefaultPathObserver()\n }\n\n /**\n Called to reconfigure the tunnel after each ephemeral peer negotiation.\n */\n internal func updateEphemeralPeerNegotiationState(configuration: EphemeralPeerNegotiationState) async throws {\n /**\n The obfuscater needs to be restarted every time a new tunnel configuration is being used,\n because the obfuscation may be tied to a specific UDP session, as is the case for udp2tcp.\n */\n let settings: Settings = try settingsReader.read()\n guard let connectionData = try obfuscateConnection(\n nextRelays: .current,\n settings: settings,\n reason: .userInitiated\n ) else {\n logger.error("Tried to update ephemeral peer negotiation in invalid state: \(state.name)")\n return\n }\n\n var daitaConfiguration: DaitaConfiguration?\n\n switch configuration {\n case let .single(hop):\n let exitConfiguration = try ConnectionConfigurationBuilder(\n type: .ephemeral(.single(hop)),\n settings: settings,\n connectionData: connectionData\n ).make().exitConfiguration\n if settings.daita.daitaState.isEnabled, let daitaSettings = hop.configuration.daitaParameters {\n daitaConfiguration = DaitaConfiguration(daita: daitaSettings)\n }\n try await tunnelAdapter.start(configuration: exitConfiguration, daita: daitaConfiguration)\n\n case let .multi(firstHop, secondHop):\n let connectionConfiguration = try ConnectionConfigurationBuilder(\n type: .ephemeral(.multi(entry: firstHop, exit: secondHop)),\n settings: settings,\n connectionData: connectionData\n ).make()\n\n if settings.daita.daitaState.isEnabled, let daitaSettings = firstHop.configuration.daitaParameters {\n daitaConfiguration = DaitaConfiguration(daita: daitaSettings)\n }\n\n try await tunnelAdapter.startMultihop(\n entryConfiguration: connectionConfiguration.entryConfiguration,\n exitConfiguration: connectionConfiguration.exitConfiguration, daita: daitaConfiguration\n )\n }\n }\n}\n\nextension DaitaConfiguration {\n init(daita: DaitaV2Parameters) {\n self = DaitaConfiguration(\n machines: daita.machines,\n maxEvents: daita.maximumEvents,\n maxActions: daita.maximumActions,\n maxPadding: daita.maximumPadding,\n maxBlocking: daita.maximumBlocking\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+PostQuantum.swift
PacketTunnelActor+PostQuantum.swift
Swift
4,334
0.95
0.119266
0.185567
react-lib
114
2023-12-10T07:40:00.012640
Apache-2.0
false
ed9c4129bc54a80df5ee98331f3a1703
//\n// PacketTunnelActor+Public.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 27/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport WireGuardKitTypes\n\n/**\n Public methods for dispatching commands to Actor.\n\n - All methods in this extension are `nonisolated` because the channel they use to pass commands for execution is `nonisolated` too.\n - FIFO order is guaranteed for all these calls for as long as they are not invoked simultaneously from multiple concurrent queues.\n - There is no way to wait for these tasks to complete, some of them may even be coalesced and never execute. Observe the `state` to follow the progress.\n */\nextension PacketTunnelActor {\n /**\n Tell actor to start the tunnel.\n\n - Parameter options: start options.\n */\n nonisolated public func start(options: StartOptions) {\n eventChannel.send(.start(options))\n }\n\n /**\n Tell actor to stop the tunnel.\n */\n nonisolated public func stop() {\n eventChannel.send(.stop)\n }\n\n /**\n Tell actor to reconnect the tunnel.\n\n - Parameter nextRelays: next relays to connect to.\n */\n public nonisolated func reconnect(to nextRelays: NextRelays, reconnectReason: ActorReconnectReason) {\n eventChannel.send(.reconnect(nextRelays, reason: reconnectReason))\n }\n\n /**\n Tell actor that key rotation took place.\n\n - Parameter date: date when last key rotation took place.\n */\n nonisolated public func notifyKeyRotation(date: Date?) {\n eventChannel.send(.notifyKeyRotated(date))\n }\n\n /**\n Tell actor that the ephemeral peer exchanging took place.\n */\n\n nonisolated public func notifyEphemeralPeerNegotiated() {\n eventChannel.send(.notifyEphemeralPeerNegotiated)\n }\n\n /**\n Tell actor that the ephemeral peer negotiation state changed.\n - Parameter key: the new key\n */\n\n nonisolated public func changeEphemeralPeerNegotiationState(\n configuration: EphemeralPeerNegotiationState,\n reconfigurationSemaphore: OneshotChannel\n ) {\n eventChannel.send(.ephemeralPeerNegotiationStateChanged(configuration, reconfigurationSemaphore))\n }\n\n /**\n Tell actor to enter error state.\n */\n nonisolated public func setErrorState(reason: BlockedStateReason) {\n eventChannel.send(.error(reason))\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+Public.swift
PacketTunnelActor+Public.swift
Swift
2,408
0.95
0.061728
0.343284
node-utils
871
2023-07-19T12:05:31.886202
GPL-3.0
false
98587fcb9d45757ff720742716bc5ecc
//\n// Actor+SleepCycle.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 26/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension PacketTunnelActor {\n /**\n Clients should call this method to notify actor when device wakes up.\n\n `NEPacketTunnelProvider` provides the corresponding lifecycle method.\n */\n public nonisolated func onWake() {\n tunnelMonitor.onWake()\n }\n\n /**\n Clients should call this method to notify actor when device is about to go to sleep.\n\n `NEPacketTunnelProvider` provides the corresponding lifecycle method.\n */\n public nonisolated func onSleep() {\n tunnelMonitor.onSleep()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor+SleepCycle.swift
PacketTunnelActor+SleepCycle.swift
Swift
712
0.95
0
0.458333
react-lib
960
2023-07-13T15:00:13.701061
MIT
false
59b348589b7433fa8eb9447eefe09113
//\n// PacketTunnelActor.swift\n// PacketTunnel\n//\n// Created by pronebird on 30/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@preconcurrency import MullvadLogging\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\nimport NetworkExtension\nimport WireGuardKitTypes\n\n/**\n Packet tunnel state machine implemented as an actor.\n\n - Actor receives events for execution over the `EventChannel`.\n\n - Events are consumed in a detached task via for-await loop over the channel. Each event, once received, is executed in its entirety before the next\n event is processed. See the implementation of `consumeEvents()` which is the central task dispatcher inside of actor.\n\n - Most of calls that actor performs suspend for a very short amount of time. `EventChannel` proactively discards unwanted tasks as they arrive to prevent\n future execution, such as repeating commands to reconnect are coalesced and all events prior to stop are discarded entirely as the outcome would be the\n same anyway.\n */\npublic actor PacketTunnelActor {\n var state: State = .initial {\n didSet(oldValue) {\n guard state != oldValue else { return }\n logger.debug("\(state.logFormat())")\n observedState = state.observedState\n }\n }\n\n @Published internal(set) public var observedState: ObservedState = .initial\n\n nonisolated(unsafe) let logger = Logger(label: "PacketTunnelActor")\n\n let timings: PacketTunnelActorTimings\n let tunnelAdapter: TunnelAdapterProtocol\n let tunnelMonitor: TunnelMonitorProtocol\n let defaultPathObserver: DefaultPathObserverProtocol\n let blockedStateErrorMapper: BlockedStateErrorMapperProtocol\n public let relaySelector: RelaySelectorProtocol\n let settingsReader: SettingsReaderProtocol\n let protocolObfuscator: ProtocolObfuscation\n\n nonisolated let eventChannel = EventChannel()\n\n public init(\n timings: PacketTunnelActorTimings,\n tunnelAdapter: TunnelAdapterProtocol,\n tunnelMonitor: TunnelMonitorProtocol,\n defaultPathObserver: DefaultPathObserverProtocol,\n blockedStateErrorMapper: BlockedStateErrorMapperProtocol,\n relaySelector: RelaySelectorProtocol,\n settingsReader: SettingsReaderProtocol,\n protocolObfuscator: ProtocolObfuscation\n ) {\n self.timings = timings\n self.tunnelAdapter = tunnelAdapter\n self.tunnelMonitor = tunnelMonitor\n self.defaultPathObserver = defaultPathObserver\n self.blockedStateErrorMapper = blockedStateErrorMapper\n self.relaySelector = relaySelector\n self.settingsReader = settingsReader\n self.protocolObfuscator = protocolObfuscator\n\n consumeEvents(channel: eventChannel)\n }\n\n deinit {\n eventChannel.finish()\n }\n\n /**\n Spawn a detached task that consumes events from the channel indefinitely until the channel is closed.\n Events are processed one at a time, so no suspensions should affect the order of execution and thus guarantee transactional execution.\n\n - Parameter channel: event channel.\n */\n private nonisolated func consumeEvents(channel: EventChannel) {\n Task.detached { [weak self] in\n for await event in channel {\n guard let self else { return }\n\n self.logger.debug("Received event: \(event.logFormat())")\n\n let effects = await self.runReducer(event)\n\n for effect in effects {\n await executeEffect(effect)\n }\n }\n }\n }\n\n // swiftlint:disable:next function_body_length\n func executeEffect(_ effect: Effect) async {\n switch effect {\n case .startDefaultPathObserver:\n startDefaultPathObserver()\n case .stopDefaultPathObserver:\n stopDefaultPathObserver()\n case .startTunnelMonitor:\n setTunnelMonitorEventHandler()\n case .stopTunnelMonitor:\n tunnelMonitor.stop()\n case let .updateTunnelMonitorPath(networkPath):\n handleDefaultPathChange(networkPath)\n case let .startConnection(nextRelays):\n do {\n try await tryStart(nextRelays: nextRelays)\n } catch {\n logger.error(error: error, message: "Failed to start the tunnel.")\n await setErrorStateInternal(with: error)\n }\n case let .restartConnection(nextRelays, reason):\n do {\n try await tryStart(nextRelays: nextRelays, reason: reason)\n } catch {\n logger.error(error: error, message: "Failed to reconnect the tunnel.")\n await setErrorStateInternal(with: error)\n }\n case let .reconnect(nextRelay):\n eventChannel.send(.reconnect(nextRelay))\n case .stopTunnelAdapter:\n do {\n try await tunnelAdapter.stop()\n } catch {\n logger.error(error: error, message: "Failed to stop adapter.")\n }\n state = .disconnected\n case let .configureForErrorState(reason):\n await setErrorStateInternal(with: reason)\n case let .cacheActiveKey(lastKeyRotation):\n cacheActiveKey(lastKeyRotation: lastKeyRotation)\n case let .reconfigureForEphemeralPeer(configuration, configurationSemaphore):\n do {\n try await updateEphemeralPeerNegotiationState(configuration: configuration)\n } catch {\n logger.error(error: error, message: "Failed to reconfigure tunnel after each hop negotiation.")\n await setErrorStateInternal(with: error)\n }\n configurationSemaphore.send()\n case .connectWithEphemeralPeer:\n await connectWithEphemeralPeer()\n case .setDisconnectedState:\n self.state = .disconnected\n }\n }\n}\n\n// MARK: -\n\nextension PacketTunnelActor {\n /**\n Start the tunnel.\n\n Can only be called once, all subsequent attempts are ignored. Use `reconnect()` if you wish to change relay.\n\n - Parameter options: start options produced by packet tunnel\n */\n private func start(options: StartOptions) async {\n guard case .initial = state else { return }\n\n logger.debug("\(options.logFormat())")\n\n // Start observing default network path to determine network reachability.\n startDefaultPathObserver()\n\n // Assign a closure receiving tunnel monitor events.\n setTunnelMonitorEventHandler()\n\n do {\n try await tryStart(nextRelays: options.selectedRelays.map { .preSelected($0) } ?? .random)\n } catch {\n logger.error(error: error, message: "Failed to start the tunnel.")\n\n await setErrorStateInternal(with: error)\n }\n }\n\n /// Stop the tunnel.\n private func stop() async {\n switch state {\n case let .connected(connState), let .connecting(connState), let .reconnecting(connState),\n let .negotiatingEphemeralPeer(connState, _):\n state = .disconnecting(connState)\n tunnelMonitor.stop()\n\n // Fallthrough to stop adapter and shift to `.disconnected` state.\n fallthrough\n\n case .error:\n stopDefaultPathObserver()\n\n do {\n try await tunnelAdapter.stop()\n } catch {\n logger.error(error: error, message: "Failed to stop adapter.")\n }\n state = .disconnected\n\n case .initial, .disconnected:\n break\n\n case .disconnecting:\n assertionFailure("stop(): out of order execution.")\n }\n }\n\n /**\n Reconnect tunnel to new relays. Enters error state on failure.\n\n - Parameters:\n - nextRelay: next relays to connect to\n - reason: reason for reconnect\n */\n private func reconnect(to nextRelays: NextRelays, reason: ActorReconnectReason) async {\n do {\n switch state {\n // There is no connection monitoring going on when exchanging keys.\n // The procedure starts from scratch for each reconnection attempts.\n case .connecting, .connected, .reconnecting, .error, .negotiatingEphemeralPeer:\n switch reason {\n case .connectionLoss:\n // Tunnel monitor is already paused at this point. Avoid calling stop() to prevent the reset of\n // internal state\n break\n case .userInitiated:\n tunnelMonitor.stop()\n }\n\n try await tryStart(nextRelays: nextRelays, reason: reason)\n\n case .disconnected, .disconnecting, .initial:\n break\n }\n } catch {\n logger.error(error: error, message: "Failed to reconnect the tunnel.")\n\n await setErrorStateInternal(with: error)\n }\n }\n\n /**\n Entry point for attempting to start the tunnel by performing the following steps:\n\n - Read settings\n - Start either a direct connection or the post-quantum key negotiation process, depending on settings.\n */\n private func tryStart(\n nextRelays: NextRelays,\n reason: ActorReconnectReason = .userInitiated\n ) async throws {\n let settings: Settings = try settingsReader.read()\n\n if settings.quantumResistance.isEnabled || settings.daita.daitaState.isEnabled {\n try await tryStartEphemeralPeerNegotiation(withSettings: settings, nextRelays: nextRelays, reason: reason)\n } else {\n try await tryStartConnection(withSettings: settings, nextRelays: nextRelays, reason: reason)\n }\n }\n\n /**\n Attempt to start a direct (non-quantum) connection to the tunnel by performing the following steps:\n\n - Determine target state, it can either be `.connecting` or `.reconnecting`. (See `TargetStateForReconnect`)\n - Bail if target state cannot be determined. That means that the actor is past the point when it could logically connect or reconnect, i.e it can already be in\n `.disconnecting` state.\n - Configure tunnel adapter.\n - Start tunnel monitor.\n - Reactivate default path observation (disabled when configuring tunnel adapter)\n\n - Parameters:\n - nextRelays: which relays should be selected next.\n - reason: reason for reconnect\n */\n private func tryStartConnection(\n withSettings settings: Settings,\n nextRelays: NextRelays,\n reason: ActorReconnectReason\n ) async throws {\n guard let connectionState = try obfuscateConnection(nextRelays: nextRelays, settings: settings, reason: reason),\n let targetState = state.targetStateForReconnect else { return }\n let configuration = try ConnectionConfigurationBuilder(\n type: .normal,\n settings: settings,\n connectionData: connectionState\n ).make()\n\n defer {\n // Restart default path observer and notify the observer with the current path that might have changed while\n // path observer was paused.\n startDefaultPathObserver()\n }\n\n // Daita parameters are gotten from an ephemeral peer\n try await tunnelAdapter.startMultihop(\n entryConfiguration: configuration.entryConfiguration,\n exitConfiguration: configuration.exitConfiguration,\n daita: nil\n )\n\n // Resume tunnel monitoring and use IPv4 gateway as a probe address.\n tunnelMonitor.start(probeAddress: connectionState.selectedRelays.exit.endpoint.ipv4Gateway)\n\n switch targetState {\n case .connecting:\n state = .connecting(connectionState)\n case .reconnecting:\n state = .reconnecting(connectionState)\n }\n }\n\n /**\n Derive `ConnectionState` from current `state` updating it with new relays and settings.\n\n - Parameters:\n - nextRelays: relay preference that should be used when selecting next relays.\n - settings: current settings\n - reason: reason for reconnect\n\n - Returns: New connection state or `nil` if current state is at or past `.disconnecting` phase.\n */\n // swiftlint:disable:next function_body_length\n internal func makeConnectionState(\n nextRelays: NextRelays,\n settings: Settings,\n reason: ActorReconnectReason\n ) throws -> State.ConnectionData? {\n var keyPolicy: State.KeyPolicy = .useCurrent\n var networkReachability = defaultPathObserver.currentPathStatus.networkReachability\n var lastKeyRotation: Date?\n\n let callRelaySelector = { [self] maybeCurrentRelays, connectionCount in\n try self.selectRelays(\n nextRelays: nextRelays,\n relayConstraints: settings.relayConstraints,\n currentRelays: maybeCurrentRelays,\n tunnelSettings: settings.tunnelSettings,\n connectionAttemptCount: connectionCount\n )\n }\n\n switch state {\n // Handle ephemeral peers separately as they don't interfere with either the `.connecting` or `.reconnecting` states.\n case var .negotiatingEphemeralPeer(connectionState, _):\n if reason == .connectionLoss {\n connectionState.incrementAttemptCount()\n }\n let selectedRelays = try callRelaySelector(\n connectionState.selectedRelays,\n connectionState.connectionAttemptCount\n )\n let connectedRelay = selectedRelays.entry ?? selectedRelays.exit\n connectionState.selectedRelays = selectedRelays\n connectionState.relayConstraints = settings.relayConstraints\n connectionState.connectedEndpoint = connectedRelay.endpoint\n connectionState.remotePort = connectedRelay.endpoint.ipv4Relay.port\n\n return connectionState\n case var .connecting(connectionState), var .reconnecting(connectionState):\n if reason == .connectionLoss {\n connectionState.incrementAttemptCount()\n }\n fallthrough\n case var .connected(connectionState):\n let selectedRelays = try callRelaySelector(\n connectionState.selectedRelays,\n connectionState.connectionAttemptCount\n )\n let connectedRelay = selectedRelays.entry ?? selectedRelays.exit\n connectionState.selectedRelays = selectedRelays\n connectionState.relayConstraints = settings.relayConstraints\n connectionState.currentKey = settings.privateKey\n connectionState.connectedEndpoint = connectedRelay.endpoint\n connectionState.remotePort = connectedRelay.endpoint.ipv4Relay.port\n return connectionState\n case let .error(blockedState):\n keyPolicy = blockedState.keyPolicy\n lastKeyRotation = blockedState.lastKeyRotation\n networkReachability = blockedState.networkReachability\n fallthrough\n case .initial:\n let selectedRelays = try callRelaySelector(nil, 0)\n let connectedRelay = selectedRelays.entry ?? selectedRelays.exit\n return State.ConnectionData(\n selectedRelays: selectedRelays,\n relayConstraints: settings.relayConstraints,\n currentKey: settings.privateKey,\n keyPolicy: keyPolicy,\n networkReachability: networkReachability,\n connectionAttemptCount: 0,\n lastKeyRotation: lastKeyRotation,\n connectedEndpoint: connectedRelay.endpoint,\n transportLayer: .udp,\n remotePort: connectedRelay.endpoint.ipv4Relay.port,\n isPostQuantum: settings.quantumResistance.isEnabled,\n isDaitaEnabled: settings.daita.daitaState.isEnabled,\n obfuscationMethod: .off\n )\n case .disconnecting, .disconnected:\n return nil\n }\n }\n\n internal func activeKey(from state: State.ConnectionData, in settings: Settings) -> PrivateKey {\n switch state.keyPolicy {\n case .useCurrent:\n settings.privateKey\n case let .usePrior(priorKey, _):\n priorKey\n }\n }\n\n internal func obfuscateConnection(\n nextRelays: NextRelays,\n settings: Settings,\n reason: ActorReconnectReason\n ) throws -> State.ConnectionData? {\n guard let connectionState = try makeConnectionState(nextRelays: nextRelays, settings: settings, reason: reason)\n else { return nil }\n\n let obfuscated = protocolObfuscator.obfuscate(\n connectionState.connectedEndpoint,\n settings: settings.tunnelSettings,\n retryAttempts: connectionState.selectedRelays.retryAttempt\n )\n let transportLayer = protocolObfuscator.transportLayer.map { $0 } ?? .udp\n\n return State.ConnectionData(\n selectedRelays: connectionState.selectedRelays,\n relayConstraints: connectionState.relayConstraints,\n currentKey: settings.privateKey,\n keyPolicy: connectionState.keyPolicy,\n networkReachability: connectionState.networkReachability,\n connectionAttemptCount: connectionState.connectionAttemptCount,\n lastKeyRotation: connectionState.lastKeyRotation,\n connectedEndpoint: obfuscated.endpoint,\n transportLayer: transportLayer,\n remotePort: protocolObfuscator.remotePort,\n isPostQuantum: settings.quantumResistance.isEnabled,\n isDaitaEnabled: settings.daita.daitaState.isEnabled,\n obfuscationMethod: obfuscated.method\n )\n }\n\n /**\n Select next relay to connect to based on `NextRelays` and other input parameters.\n\n - Parameters:\n - nextRelays: next relays to connect to.\n - relayConstraints: relay constraints.\n - currentRelays: currently selected relays.\n - connectionAttemptCount: number of failed connection attempts so far.\n\n - Returns: selector result that contains the credentials of the next relays that the tunnel should connect to.\n */\n private func selectRelays(\n nextRelays: NextRelays,\n relayConstraints: RelayConstraints,\n currentRelays: SelectedRelays?,\n tunnelSettings: LatestTunnelSettings,\n connectionAttemptCount: UInt\n ) throws -> SelectedRelays {\n switch nextRelays {\n case .current:\n if let currentRelays {\n return currentRelays\n } else {\n // Fallthrough to .random when current relays are not set.\n fallthrough\n }\n\n case .random:\n return try relaySelector.selectRelays(\n tunnelSettings: tunnelSettings,\n connectionAttemptCount: connectionAttemptCount\n )\n\n case let .preSelected(selectedRelays):\n return selectedRelays\n }\n }\n}\n\nextension PacketTunnelActor: PacketTunnelActorProtocol {}\n\n// swiftlint:disable:this file_length\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActor.swift
PacketTunnelActor.swift
Swift
19,199
0.95
0.105051
0.095349
awesome-app
985
2023-11-03T03:42:41.255516
GPL-3.0
false
c699399711e590ad8c9a3bf7693fc30a
//\n// Command.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 27/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\nimport WireGuardKitTypes\n\nextension PacketTunnelActor {\n /// Describes events that the state machine handles. These can be user commands or non-user-initiated events\n enum Event: Sendable {\n /// Start tunnel.\n case start(StartOptions)\n\n /// Stop tunnel.\n case stop\n\n /// Reconnect tunnel.\n case reconnect(NextRelays, reason: ActorReconnectReason = .userInitiated)\n\n /// Enter blocked state.\n case error(BlockedStateReason)\n\n /// Notify that key rotation took place\n case notifyKeyRotated(Date?)\n\n /// Switch to using the recently pushed WG key.\n case switchKey\n\n /// Monitor events.\n case monitorEvent(_ event: TunnelMonitorEvent)\n\n /// Network reachability events.\n case networkReachability(Network.NWPath.Status)\n\n /// Update the device private key, as per post-quantum protocols\n case ephemeralPeerNegotiationStateChanged(EphemeralPeerNegotiationState, OneshotChannel)\n\n /// Notify that an ephemeral peer exchanging took place\n case notifyEphemeralPeerNegotiated\n\n /// Format command for log output.\n func logFormat() -> String {\n switch self {\n case .start:\n return "start"\n case .stop:\n return "stop"\n case let .reconnect(nextRelays, stopTunnelMonitor):\n switch nextRelays {\n case .current:\n return "reconnect(current, \(stopTunnelMonitor))"\n case .random:\n return "reconnect(random, \(stopTunnelMonitor))"\n case let .preSelected(selectedRelays):\n return "reconnect(\(selectedRelays.exit.hostname)\(selectedRelays.entry.flatMap { " via \($0.hostname)" } ?? ""), \(stopTunnelMonitor))"\n }\n case let .error(reason):\n return "error(\(reason))"\n case .notifyKeyRotated:\n return "notifyKeyRotated"\n case let .monitorEvent(event):\n switch event {\n case .connectionEstablished:\n return "monitorEvent(connectionEstablished)"\n case .connectionLost:\n return "monitorEvent(connectionLost)"\n }\n case .networkReachability:\n return "networkReachability"\n case .switchKey:\n return "switchKey"\n case .ephemeralPeerNegotiationStateChanged:\n return "ephemeralPeerNegotiationStateChanged"\n case .notifyEphemeralPeerNegotiated:\n return "notifyEphemeralPeerNegotiated"\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActorCommand.swift
PacketTunnelActorCommand.swift
Swift
2,917
0.95
0.047059
0.260274
python-kit
925
2025-07-01T14:38:50.693122
BSD-3-Clause
false
2e3470cf37cdb5b352a1a2a9676c342a
//\n// PacketTunnelActorProtocol.swift\n// PacketTunnelCoreTests\n//\n// Created by Jon Petersson on 2023-10-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol PacketTunnelActorProtocol {\n var observedState: ObservedState { get async }\n\n func reconnect(to nextRelays: NextRelays, reconnectReason: ActorReconnectReason)\n func notifyKeyRotation(date: Date?)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActorProtocol.swift
PacketTunnelActorProtocol.swift
Swift
417
0.95
0
0.538462
python-kit
829
2024-01-04T21:09:17.209610
MIT
false
77f15c8c07751d401f1b0abcbbb589aa
//\n// PacketTunnelActorReducer.swift\n// PacketTunnelCore\n//\n// Created by Andrew Bulhak on 2024-05-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\nimport WireGuardKitTypes\n\nextension PacketTunnelActor {\n /// A structure encoding an effect; each event will yield zero or more of those, which can then be sequentially executed.\n enum Effect: Equatable, Sendable {\n case startDefaultPathObserver\n case stopDefaultPathObserver\n case startTunnelMonitor\n case stopTunnelMonitor\n case updateTunnelMonitorPath(Network.NWPath.Status)\n case startConnection(NextRelays)\n case restartConnection(NextRelays, ActorReconnectReason)\n\n // trigger a reconnect, which becomes several effects depending on the state\n case reconnect(NextRelays)\n case stopTunnelAdapter\n case configureForErrorState(BlockedStateReason)\n case cacheActiveKey(Date?)\n case reconfigureForEphemeralPeer(EphemeralPeerNegotiationState, OneshotChannel)\n case connectWithEphemeralPeer\n\n // acknowledge that the disconnection process has concluded, go to .disconnected.\n case setDisconnectedState\n\n // We cannot synthesise Equatable on Effect because NetworkPath is a protocol which cannot be easily made Equatable, so we need to do this for now.\n static func == (lhs: PacketTunnelActor.Effect, rhs: PacketTunnelActor.Effect) -> Bool {\n return switch (lhs, rhs) {\n case (.startDefaultPathObserver, .startDefaultPathObserver): true\n case (.stopDefaultPathObserver, .stopDefaultPathObserver): true\n case (.startTunnelMonitor, .startTunnelMonitor): true\n case (.stopTunnelMonitor, .stopTunnelMonitor): true\n case let (.updateTunnelMonitorPath(lp), .updateTunnelMonitorPath(rp)): lp == rp\n case let (.startConnection(nr0), .startConnection(nr1)): nr0 == nr1\n case let (.restartConnection(nr0, rr0), .restartConnection(nr1, rr1)): nr0 == nr1 && rr0 == rr1\n case let (.reconnect(nr0), .reconnect(nr1)): nr0 == nr1\n case (.stopTunnelAdapter, .stopTunnelAdapter): true\n case let (.configureForErrorState(r0), .configureForErrorState(r1)): r0 == r1\n case let (.cacheActiveKey(d0), .cacheActiveKey(d1)): d0 == d1\n case let (.reconfigureForEphemeralPeer(eph0, _), .reconfigureForEphemeralPeer(eph1, _)): eph0 == eph1\n case (.connectWithEphemeralPeer, .connectWithEphemeralPeer): true\n case (.setDisconnectedState, .setDisconnectedState): true\n default: false\n }\n }\n }\n\n struct Reducer: Sendable {\n static func reduce(_ state: inout State, _ event: Event) -> [Effect] {\n switch event {\n case let .start(options):\n guard case .initial = state else { return [] }\n return [\n .startDefaultPathObserver,\n .startTunnelMonitor,\n .startConnection(options.selectedRelays.map { .preSelected($0) } ?? .random),\n ]\n case .stop:\n return subreducerForStop(&state)\n\n case let .reconnect(nextRelay, reason: reason):\n return subreducerForReconnect(state, reason, nextRelay)\n\n case let .error(reason):\n // the transition from error to blocked state currently has side-effects, so will be handled as an effect for now.\n return [.configureForErrorState(reason)]\n\n case let .notifyKeyRotated(lastKeyRotation):\n // the cacheActiveKey operation is currently effectful, starting a key-switch task within the mutation of state, so this is entirely done in an effect. Perhaps teasing effects out of state mutation is a future refactoring?\n guard state.keyPolicy == .useCurrent else { return [] }\n return [.cacheActiveKey(lastKeyRotation)]\n\n case .switchKey:\n return subreducerForSwitchKey(&state)\n\n case let .monitorEvent(event):\n return subreducerForTunnelMonitorEvent(event, &state)\n\n case let .networkReachability(defaultPath):\n let newReachability = defaultPath.networkReachability\n state.mutateAssociatedData { $0.networkReachability = newReachability }\n return [.updateTunnelMonitorPath(defaultPath)]\n\n case let .ephemeralPeerNegotiationStateChanged(configuration, reconfigurationSemaphore):\n return [.reconfigureForEphemeralPeer(configuration, reconfigurationSemaphore)]\n\n case .notifyEphemeralPeerNegotiated:\n return [.connectWithEphemeralPeer]\n }\n }\n\n // Parts of the reducer path broken out for specific incoming events\n\n fileprivate static func subreducerForStop(_ state: inout State) -> [PacketTunnelActor.Effect] {\n // a call of the reducer produces one state transition and a sequence of effects. In the app, a stop transitions to .disconnecting, shuts down various processes, and finally transitions to .disconnected. We currently do this by having an effect which acknowledges the completion of disconnection and just sets the state. This is a bit messy, and could possibly do with some rethinking.\n switch state {\n case let .connected(connState), let .connecting(connState), let .reconnecting(connState),\n let .negotiatingEphemeralPeer(connState, _):\n state = .disconnecting(connState)\n return [\n .stopTunnelMonitor,\n .stopDefaultPathObserver,\n .stopTunnelAdapter,\n .setDisconnectedState,\n ]\n case .error:\n return [\n .stopDefaultPathObserver,\n .stopTunnelAdapter,\n .setDisconnectedState,\n ]\n\n case .initial, .disconnected:\n return []\n\n case .disconnecting:\n assertionFailure("stop(): out of order execution.")\n return []\n }\n }\n\n fileprivate static func subreducerForReconnect(\n _ state: State,\n _ reason: ActorReconnectReason,\n _ nextRelays: NextRelays\n ) -> [PacketTunnelActor.Effect] {\n switch state {\n case .disconnected, .disconnecting, .initial:\n // There is no connection monitoring going on when exchanging keys.\n // The procedure starts from scratch for each reconnection attempts.\n return []\n case .connecting, .connected, .reconnecting, .error, .negotiatingEphemeralPeer:\n if reason == .userInitiated {\n return [.stopTunnelMonitor, .restartConnection(nextRelays, reason)]\n } else {\n return [.restartConnection(nextRelays, reason)]\n }\n }\n }\n\n fileprivate static func subreducerForSwitchKey(_ state: inout State) -> [PacketTunnelActor.Effect] {\n let oldKeyPolicy = state.keyPolicy\n state.mutateKeyPolicy { keyPolicy in\n if case .usePrior = keyPolicy {\n keyPolicy = .useCurrent\n }\n }\n if case .error = state { return [] }\n return state.keyPolicy != oldKeyPolicy ? [.reconnect(.random)] : []\n }\n\n fileprivate static func subreducerForTunnelMonitorEvent(\n _ event: TunnelMonitorEvent,\n _ state: inout State\n ) -> [PacketTunnelActor.Effect] {\n switch event {\n case .connectionEstablished:\n switch state {\n case var .connecting(connState), var .reconnecting(connState):\n // Reset connection attempt once successfully connected.\n connState.connectionAttemptCount = 0\n state = .connected(connState)\n\n case .initial, .connected, .disconnecting, .disconnected, .error, .negotiatingEphemeralPeer:\n break\n }\n return []\n case .connectionLost:\n switch state {\n case .connecting, .reconnecting, .connected:\n return [.restartConnection(.random, .connectionLoss)]\n case .initial, .disconnected, .disconnecting, .error, .negotiatingEphemeralPeer:\n return []\n }\n }\n }\n }\n\n func runReducer(_ event: Event) -> [Effect] {\n PacketTunnelActor.Reducer.reduce(&state, event)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\PacketTunnelActorReducer.swift
PacketTunnelActorReducer.swift
Swift
8,823
0.95
0.078125
0.106509
react-lib
38
2023-11-20T11:12:01.526065
Apache-2.0
false
0ed33171876d8d4ad7bfdae517c0617b
//\n// ProtocolObfuscator.swift\n// PacketTunnelCore\n//\n// Created by Marco Nikic on 2023-11-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\n\npublic struct ProtocolObfuscationResult {\n let endpoint: MullvadEndpoint\n let method: WireGuardObfuscationState\n}\n\npublic protocol ProtocolObfuscation {\n func obfuscate(\n _ endpoint: MullvadEndpoint,\n settings: LatestTunnelSettings,\n retryAttempts: UInt\n ) -> ProtocolObfuscationResult\n var transportLayer: TransportLayer? { get }\n var remotePort: UInt16 { get }\n}\n\npublic class ProtocolObfuscator<Obfuscator: TunnelObfuscation>: ProtocolObfuscation {\n var tunnelObfuscator: TunnelObfuscation?\n\n public init() {}\n\n /// Obfuscates a Mullvad endpoint.\n ///\n /// - Parameters:\n /// - endpoint: The endpoint to obfuscate.\n /// - Returns: `endpoint` if obfuscation is disabled, or an obfuscated endpoint otherwise.\n public var transportLayer: TransportLayer? {\n return tunnelObfuscator?.transportLayer\n }\n\n private(set) public var remotePort: UInt16 = 0\n\n public func obfuscate(\n _ endpoint: MullvadEndpoint,\n settings: LatestTunnelSettings,\n retryAttempts: UInt = 0\n ) -> ProtocolObfuscationResult {\n let obfuscationMethod = ObfuscationMethodSelector.obfuscationMethodBy(\n connectionAttemptCount: retryAttempts,\n tunnelSettings: settings\n )\n\n remotePort = endpoint.ipv4Relay.port\n\n guard obfuscationMethod != .off else {\n tunnelObfuscator = nil\n return .init(endpoint: endpoint, method: .off)\n }\n\n // At this point, the only possible obfuscation methods should be either `.udpOverTcp` or `.shadowsocks`\n let obfuscator = Obfuscator(\n remoteAddress: endpoint.ipv4Relay.ip,\n tcpPort: remotePort,\n obfuscationProtocol: obfuscationMethod == .shadowsocks ? .shadowsocks : .udpOverTcp\n )\n\n obfuscator.start()\n tunnelObfuscator = obfuscator\n\n return .init(\n endpoint: MullvadEndpoint(\n ipv4Relay: IPv4Endpoint(ip: .loopback, port: obfuscator.localUdpPort),\n ipv4Gateway: endpoint.ipv4Gateway,\n ipv6Gateway: endpoint.ipv6Gateway,\n publicKey: endpoint.publicKey\n ),\n method: obfuscationMethod\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\ProtocolObfuscator.swift
ProtocolObfuscator.swift
Swift
2,518
0.95
0.024096
0.185714
python-kit
536
2025-06-14T22:40:36.207304
GPL-3.0
false
ba719a3457d6d68b814445a1e1610c79
//\n// StartOptions.swift\n// PacketTunnel\n//\n// Created by pronebird on 03/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n\n/// Packet tunnel start options parsed from dictionary passed to packet tunnel with a call to `startTunnel()`.\npublic struct StartOptions: Sendable {\n /// The system that triggered the launch of packet tunnel.\n public var launchSource: LaunchSource\n\n /// Pre-selected relays received from UI when available.\n public var selectedRelays: SelectedRelays?\n\n /// Designated initializer.\n public init(launchSource: LaunchSource, selectedRelays: SelectedRelays? = nil) {\n self.launchSource = launchSource\n self.selectedRelays = selectedRelays\n }\n\n /// Returns a brief description suitable for output to tunnel provider log.\n public func logFormat() -> String {\n var s = "Start the tunnel via \(launchSource)"\n if let selectedRelays {\n s += ", connect to \(selectedRelays.exit.hostname)"\n s += selectedRelays.entry.flatMap { " via \($0.hostname)" } ?? ""\n }\n s += "."\n return s\n }\n}\n\n/// The source facility that triggered a launch of packet tunnel extension.\npublic enum LaunchSource: String, CustomStringConvertible, Sendable {\n /// Launched by the main bundle app using network extension framework.\n case app\n\n /// Launched via on-demand rule.\n case onDemand\n\n /// Launched by system, either on boot or via system VPN settings.\n case system\n\n /// Returns a human readable description of launch source.\n public var description: String {\n switch self {\n case .app, .system:\n return rawValue\n case .onDemand:\n return "on-demand rule"\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\StartOptions.swift
StartOptions.swift
Swift
1,799
0.95
0.051724
0.346939
vue-tools
862
2025-06-09T05:53:08.421174
MIT
false
232a134613ee67979570fad3ef92ff8a
//\n// State+Extensions.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 08/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport WireGuardKitTypes\n\nextension State {\n /// Target state the actor should transition into upon request to either start (connect) or reconnect.\n enum TargetStateForReconnect {\n case reconnecting, connecting\n }\n\n /// Returns the target state to which the actor state should transition when requested to reconnect.\n /// It returns `nil` when reconnection is not supported such as when already `.disconnecting` or `.disconnected` states.\n var targetStateForReconnect: TargetStateForReconnect? {\n switch self {\n case .initial:\n return .connecting\n\n case .connecting, .negotiatingEphemeralPeer:\n return .connecting\n\n case .connected, .reconnecting:\n return .reconnecting\n\n case let .error(blockedState):\n switch blockedState.priorState {\n case .initial, .connecting:\n return .connecting\n case .connected, .reconnecting:\n return .reconnecting\n }\n\n case .disconnecting, .disconnected:\n return nil\n }\n }\n\n // MARK: - Logging\n\n func logFormat() -> String {\n switch self {\n case let .connecting(connState), let .connected(connState), let .reconnecting(connState):\n """\n \(name) to \(connState.selectedRelays.entry.flatMap { "entry location: \($0.hostname) " } ?? ""),\\n exit location: \(connState.selectedRelays.exit.hostname), \\n key: \(connState.keyPolicy.logFormat()), \\n net: \(connState.networkReachability), \\n attempt: \(connState.connectionAttemptCount)\n """\n\n case let .error(blockedState):\n "\(name): \(blockedState.reason)"\n\n case .initial, .disconnecting, .disconnected, .negotiatingEphemeralPeer:\n name\n }\n }\n\n var name: String {\n switch self {\n case let .negotiatingEphemeralPeer(connectionData, _):\n switch (connectionData.isPostQuantum, connectionData.isDaitaEnabled) {\n case (true, true):\n "Negotiating Post Quantum Key with Daita"\n case (true, false):\n "Negotiating Post Quantum Key"\n case (false, true):\n "Negotiating Daita peer without Post Quantum Key"\n case (false, false):\n "Negotiating ephemeral peer without Post Quantum Key or Daita -- Multihop exit relay probably"\n }\n case .connected:\n "Connected"\n case .connecting:\n "Connecting"\n case .reconnecting:\n "Reconnecting"\n case .disconnecting:\n "Disconnecting"\n case .disconnected:\n "Disconnected"\n case .initial:\n "Initial"\n case .error:\n "Error"\n }\n }\n\n var connectionData: State.ConnectionData? {\n switch self {\n case\n let .connecting(connState),\n let .connected(connState),\n let .reconnecting(connState),\n let .negotiatingEphemeralPeer(connState, _),\n let .disconnecting(connState): connState\n default: nil\n }\n }\n\n var blockedData: State.BlockingData? {\n switch self {\n case let .error(blockedState): blockedState\n default: nil\n }\n }\n\n var associatedData: StateAssociatedData? {\n self.connectionData ?? self.blockedData\n }\n\n var keyPolicy: KeyPolicy? {\n associatedData?.keyPolicy\n }\n\n /// Return a copy of this state with the associated value (if appropriate) replaced with a new value.\n /// If the value does not apply, this just returns the state as is, ignoring it.\n\n internal func replacingConnectionData(with newValue: State.ConnectionData) -> State {\n switch self {\n case .connecting: .connecting(newValue)\n case .connected: .connected(newValue)\n case .reconnecting: .reconnecting(newValue)\n case .disconnecting: .disconnecting(newValue)\n case let .negotiatingEphemeralPeer(_, privateKey): .negotiatingEphemeralPeer(newValue, privateKey)\n default: self\n }\n }\n\n /// Apply a mutating function to the connection/error state's associated data if this state has one,\n /// and replace its value. If not, this is a no-op.\n /// - parameter modifier: A function that takes an `inout ConnectionOrBlockedState` and modifies it\n mutating func mutateAssociatedData(_ modifier: (inout StateAssociatedData) -> Void) {\n switch self {\n case let .connecting(connState),\n let .connected(connState),\n let .reconnecting(connState),\n let .negotiatingEphemeralPeer(connState, _),\n let .disconnecting(connState):\n var associatedData: StateAssociatedData = connState\n modifier(&associatedData)\n // swiftlint:disable:next force_cast\n self = self.replacingConnectionData(with: associatedData as! ConnectionData)\n\n case let .error(blockedState):\n var associatedData: StateAssociatedData = blockedState\n modifier(&associatedData)\n // swiftlint:disable:next force_cast\n self = .error(associatedData as! BlockingData)\n\n default:\n break\n }\n }\n\n /// Apply a mutating function to the state's key policy\n /// - parameter modifier: A function that takes an `inout KeyPolicy` and modifies it\n mutating func mutateKeyPolicy(_ modifier: (inout KeyPolicy) -> Void) {\n self.mutateAssociatedData { modifier(&$0.keyPolicy) }\n }\n}\n\nextension State.KeyPolicy {\n func logFormat() -> String {\n switch self {\n case .useCurrent:\n return "current"\n case .usePrior:\n return "prior"\n }\n }\n}\n\nextension State.KeyPolicy: Equatable {\n static func == (lhs: State.KeyPolicy, rhs: State.KeyPolicy) -> Bool {\n switch (lhs, rhs) {\n case (.useCurrent, .useCurrent): true\n case let (.usePrior(priorA, _), .usePrior(priorB, _)): priorA == priorB\n default: false\n }\n }\n}\n\nextension BlockedStateReason {\n /**\n Returns true if the tunnel should attempt to restart periodically to recover from error that does not require explicit restart to be initiated by user.\n\n Common scenarios when tunnel will attempt to restart itself periodically:\n\n - Keychain and filesystem are locked on boot until user unlocks device in the very first time.\n - App update that requires settings schema migration. Packet tunnel will be automatically restarted after update but it would not be able to read settings until\n user opens the app which performs migration.\n - Packet tunnel will be automatically restarted when there is a tunnel adapter error.\n */\n var shouldRestartAutomatically: Bool {\n switch self {\n case .deviceLocked, .tunnelAdapter:\n return true\n case .noRelaysSatisfyingConstraints, .noRelaysSatisfyingFilterConstraints,\n .multihopEntryEqualsExit, .noRelaysSatisfyingObfuscationSettings,\n .noRelaysSatisfyingDaitaConstraints, .readSettings, .invalidAccount, .accountExpired, .deviceRevoked,\n .unknown, .deviceLoggedOut, .outdatedSchema, .invalidRelayPublicKey:\n return false\n }\n }\n}\n\nextension State.BlockingData: Equatable {\n static func == (lhs: State.BlockingData, rhs: State.BlockingData) -> Bool {\n lhs.reason == rhs.reason\n && lhs.relayConstraints == rhs.relayConstraints\n && lhs.currentKey == rhs.currentKey\n && lhs.keyPolicy == rhs.keyPolicy\n && lhs.networkReachability == rhs.networkReachability\n && lhs.lastKeyRotation == rhs.lastKeyRotation\n && lhs.priorState == rhs.priorState\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\State+Extensions.swift
State+Extensions.swift
Swift
8,047
0.95
0.084444
0.111675
python-kit
607
2023-07-12T15:29:38.459120
MIT
false
e3b30752476a2c3f010b520e812082d1
//\n// State.swift\n// PacketTunnel\n//\n// Created by pronebird on 07/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\n@preconcurrency import WireGuardKitTypes\n\n/**\n Tunnel actor state with metadata describing the current phase of packet tunnel lifecycle.\n\n ## General lifecycle\n\n Packet tunnel always begins in `.initial` state and ends `.disconnected` state over time. Packet tunnel process is not recycled and hence once\n the `.disconnected` state is reached, the process is terminated. The new process is started next time VPN is activated.\n\n ```\n .initial → .connecting → .connected → .disconnecting → .disconnected\n ```\n\n ## Reconnecting state\n\n `.reconnecting` can be entered from `.connected` state.\n\n ```\n .connected → .reconnecting -> .connected\n .reconnecting → .disconnecting → .disconnected\n ```\n\n ## Error state\n\n `.error` can be entered from nearly any other state except when the tunnel is at or past `.disconnecting` phase.\n\n A call to reconnect the tunnel while in error state can be used to attempt the recovery and exit the error state upon success.\n Note that actor decides the target state when transitioning from `.error` state forward based on state prior to error state.\n\n ```\n .error → .reconnecting\n .error → .connecting\n ```\n\n ### Packet tunnel considerations\n\n Packet tunnel should raise `NEPacketTunnelProvider.reasserting` when `reconnecting` but not when `connecting` since\n `reasserting = false` always leads to `NEVPNStatus.connected`.\n\n ## Interruption\n\n `.connecting`, `.reconnecting`, `.error` can be interrupted if the tunnel is requested to stop, which should segue actor towards `.disconnected` state.\n\n */\nenum State: Equatable {\n /// Initial state at the time when actor is initialized but before the first connection attempt.\n case initial\n\n /// Establish a connection to the gateway, and exchange an ephemeral wireguard peer with the GRPC service that resides there.\n case negotiatingEphemeralPeer(ConnectionData, PrivateKey)\n\n /// Tunnel is attempting to connect.\n /// The actor should remain in this state until the very first connection is established, i.e determined by tunnel monitor.\n case connecting(ConnectionData)\n\n /// Tunnel is connected.\n case connected(ConnectionData)\n\n /// Tunnel is attempting to reconnect.\n case reconnecting(ConnectionData)\n\n /// Tunnel is disconnecting.\n case disconnecting(ConnectionData)\n\n /// Tunnel is disconnected.\n /// Normally the process is shutdown after entering this state.\n case disconnected\n\n /// Error state.\n /// This state is normally entered when the tunnel is unable to start or reconnect.\n /// In this state the tunnel blocks all nework connectivity by setting up a peerless WireGuard tunnel, and either awaits user action or, in certain\n /// circumstances, attempts to recover automatically using a repeating timer.\n case error(BlockingData)\n}\n\n/// Enum describing network availability.\npublic enum NetworkReachability: Equatable, Codable, Sendable {\n case undetermined, reachable, unreachable\n}\n\nprotocol StateAssociatedData {\n var currentKey: PrivateKey? { get set }\n var keyPolicy: State.KeyPolicy { get set }\n var networkReachability: NetworkReachability { get set }\n var lastKeyRotation: Date? { get set }\n}\n\nextension State {\n /// Policy describing what WG key to use for tunnel communication.\n enum KeyPolicy: Sendable {\n /// Use current key stored in device data.\n case useCurrent\n\n /// Use prior key until timer fires.\n case usePrior(_ priorKey: PrivateKey, _ timerTask: AutoCancellingTask)\n }\n\n /// Data associated with states that hold connection data.\n struct ConnectionData: Equatable, StateAssociatedData {\n /// Current selected relays.\n public var selectedRelays: SelectedRelays\n\n /// Last relay constraints read from settings.\n /// This is primarily used by packet tunnel for updating constraints in tunnel provider.\n public var relayConstraints: RelayConstraints\n\n /// Last WG key read from settings.\n /// Can be `nil` if moved to `keyPolicy`.\n public var currentKey: PrivateKey?\n\n /// Policy describing the current key that should be used by the tunnel.\n public var keyPolicy: KeyPolicy\n\n /// Whether network connectivity outside of tunnel is available.\n public var networkReachability: NetworkReachability\n\n /// Connection attempt counter.\n /// Reset to zero once connection is established.\n public var connectionAttemptCount: UInt\n\n /// Last time packet tunnel rotated the key.\n public var lastKeyRotation: Date?\n\n /// Increment connection attempt counter by one, wrapping to zero on overflow.\n public mutating func incrementAttemptCount() {\n let (value, isOverflow) = connectionAttemptCount.addingReportingOverflow(1)\n connectionAttemptCount = isOverflow ? 0 : value\n }\n\n /// The actual endpoint fed to WireGuard, can be a local endpoint if obfuscation is used.\n public var connectedEndpoint: MullvadEndpoint\n /// Via which transport protocol was the connection made to the relay\n public let transportLayer: TransportLayer\n\n /// The remote port that was chosen to connect to `connectedEndpoint`\n public var remotePort: UInt16\n\n /// True if post-quantum key exchange is enabled\n public let isPostQuantum: Bool\n\n /// True if Daita is enabled\n public let isDaitaEnabled: Bool\n\n /// The obfuscation method in force on the connection\n public let obfuscationMethod: WireGuardObfuscationState\n }\n\n /// Data associated with error state.\n struct BlockingData: StateAssociatedData, Sendable {\n /// Reason why block state was entered.\n public var reason: BlockedStateReason\n\n /// Last relay constraints read from settings.\n /// This is primarily used by packet tunnel for updating constraints in tunnel provider.\n public var relayConstraints: RelayConstraints?\n\n /// Last WG key read from setings.\n /// Can be `nil` if moved to `keyPolicy` or when it's uknown.\n public var currentKey: PrivateKey?\n\n /// Policy describing the current key that should be used by the tunnel.\n public var keyPolicy: KeyPolicy\n\n /// Whether network connectivity outside of tunnel is available.\n public var networkReachability: NetworkReachability\n\n /// Last time packet tunnel rotated or attempted to rotate the key.\n /// This is used by `TunnelManager` to detect when it needs to refresh device state from Keychain.\n public var lastKeyRotation: Date?\n\n /// Task responsible for periodically calling actor to restart the tunnel.\n /// Initiated based on the error that led to blocked state.\n public var recoveryTask: AutoCancellingTask?\n\n /// Prior state of the actor before entering blocked state\n public var priorState: PriorState\n }\n}\n\n/// Reason why packet tunnel entered error state.\npublic enum BlockedStateReason: String, Codable, Equatable, Sendable {\n /// Device is locked.\n case deviceLocked\n\n /// Settings schema is outdated.\n case outdatedSchema\n\n /// General error for no relays satisfying constraints.\n case noRelaysSatisfyingConstraints\n\n /// No relays satisfying filter constraints.\n case noRelaysSatisfyingFilterConstraints\n\n /// No relays satisfying multihop constraints.\n case multihopEntryEqualsExit\n\n /// No relays satisfying DAITA constraints.\n case noRelaysSatisfyingDaitaConstraints\n\n /// No relays satisfying DAITA constraints.\n case noRelaysSatisfyingObfuscationSettings\n\n /// Any other failure when reading settings.\n case readSettings\n\n /// Invalid account.\n case invalidAccount\n\n /// Account is expired.\n case accountExpired\n\n /// Device revoked.\n case deviceRevoked\n\n /// Device is logged out.\n /// This is an extreme edge case, most likely means that main bundle forgot to delete the VPN configuration during logout.\n case deviceLoggedOut\n\n /// Tunnel adapter error.\n case tunnelAdapter\n\n /// Invalid public key.\n case invalidRelayPublicKey\n\n /// Unidentified reason.\n case unknown\n}\n\nextension State.BlockingData {\n /// Legal states that can precede error state.\n enum PriorState: Equatable {\n case initial, connecting, connected, reconnecting\n }\n}\n\n/// Describes which relay the tunnel should connect to next.\npublic enum NextRelays: Equatable, Codable, Sendable {\n /// Select next relays randomly.\n case random\n\n /// Use currently selected relays, fallback to random if not set.\n case current\n\n /// Use pre-selected relays.\n case preSelected(SelectedRelays)\n}\n\n/// Describes the reason for reconnection request.\npublic enum ActorReconnectReason: Equatable, Sendable {\n /// Initiated by user.\n case userInitiated\n\n /// Initiated by tunnel monitor due to loss of connectivity, or if ephemeral peer negotiation times out.\n /// Actor will increment the connection attempt counter before picking next relay.\n case connectionLoss\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\State.swift
State.swift
Swift
9,354
0.95
0.055556
0.44
awesome-app
161
2024-08-27T13:10:38.118194
MIT
false
f886edb0b5b55aa22c61456eb5b7b3a2
//\n// Task+.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 11/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nprivate typealias TaskCancellationError = CancellationError\n\nextension Task where Success == Never, Failure == Never {\n /**\n Suspends the current task for at least the given duration.\n\n Negative durations are clamped to zero.\n\n - Parameter duration: duration that determines how long the task should be suspended.\n */\n @available(iOS, introduced: 15.0, obsoleted: 16.0, message: "Replace with Task.sleep(for:tolerance:clock:).")\n static func sleep(duration: Duration) async throws {\n let millis = UInt64(max(0, duration.milliseconds))\n let nanos = millis.saturatingMultiplication(1_000_000)\n\n try await Task.sleep(nanoseconds: nanos)\n }\n\n /**\n Suspends the current task for the given duration.\n\n Negative durations are clamped to zero.\n\n - Parameter duration: duration that determines how long the task should be suspended.\n */\n @available(iOS, introduced: 15.0, obsoleted: 16.0, message: "Replace with Task.sleep(for:tolerance:clock:).")\n static func sleepUsingContinuousClock(for duration: Duration) async throws {\n nonisolated(unsafe) let timer = DispatchSource.makeTimerSource()\n\n try await withTaskCancellationHandler {\n try await withCheckedThrowingContinuation { continuation in\n // The `continuation` handler should never be `resume`'d more than once.\n // Setting the eventHandler on the timer after it has been cancelled will be ignored.\n // https://github.com/apple/swift-corelibs-libdispatch/blob/77766345740dfe3075f2f60bead854b29b0cfa24/src/source.c#L338\n // Therefore, set a flag indicating `resume` has already been called to avoid `resume`ing more than once.\n // Cancelling the timer does not cancel an event handler that is already running however,\n // the cancel handler will be scheduled after the event handler has finished.\n // https://developer.apple.com/documentation/dispatch/1385604-dispatch_source_cancel\n // Therefore, there it is safe to do this here.\n var hasResumed = false\n timer.setEventHandler {\n hasResumed = true\n continuation.resume()\n }\n timer.setCancelHandler {\n guard hasResumed == false else { return }\n continuation.resume(throwing: TaskCancellationError())\n }\n timer.schedule(wallDeadline: .now() + DispatchTimeInterval.milliseconds(duration.milliseconds))\n timer.activate()\n }\n } onCancel: {\n timer.cancel()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\Task+Duration.swift
Task+Duration.swift
Swift
2,883
0.95
0.119403
0.333333
vue-tools
247
2023-09-19T16:36:22.801292
Apache-2.0
false
95f172def5ba49a0bc59eb1d0958c571
//\n// Timings.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 21/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Struct holding all timings used by tunnel actor.\npublic struct PacketTunnelActorTimings: Sendable {\n /// Periodicity at which actor will attempt to restart when an error occurred on system boot when filesystem is locked until device is unlocked or tunnel adapter error.\n public var bootRecoveryPeriodicity: Duration\n\n /// Time that takes for new WireGuard key to propagate across relays.\n public var wgKeyPropagationDelay: Duration\n\n /// Designated initializer.\n public init(\n bootRecoveryPeriodicity: Duration = .seconds(5),\n wgKeyPropagationDelay: Duration = .seconds(120)\n ) {\n self.bootRecoveryPeriodicity = bootRecoveryPeriodicity\n self.wgKeyPropagationDelay = wgKeyPropagationDelay\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\Timings.swift
Timings.swift
Swift
936
0.95
0.035714
0.458333
vue-tools
417
2024-07-25T01:00:37.313560
GPL-3.0
false
b57f47b9a3899b48f3b19230b4e0a517
//\n// TunnelSettingsManager.swift\n// PacketTunnelCore\n//\n// Created by Mojgan on 2024-06-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic struct TunnelSettingsManager: SettingsReaderProtocol {\n let settingsReader: SettingsReaderProtocol\n let onLoadSettingsHandler: ((Settings) -> Void)?\n\n public init(settingsReader: SettingsReaderProtocol, onLoadSettingsHandler: ((Settings) -> Void)? = nil) {\n self.settingsReader = settingsReader\n self.onLoadSettingsHandler = onLoadSettingsHandler\n }\n\n public func read() throws -> Settings {\n let settings = try settingsReader.read()\n onLoadSettingsHandler?(settings)\n return settings\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\TunnelSettingsManager.swift
TunnelSettingsManager.swift
Swift
709
0.8
0.043478
0.35
node-utils
919
2024-02-07T19:07:48.847793
MIT
false
21bb2fe135b07efb1fd6851bee962e89
//\n// BlockedStateErrorMapperProtocol.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 14/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// A type responsible for mapping errors returned by dependencies of `PacketTunnelActor` to `BlockedStateReason`.\npublic protocol BlockedStateErrorMapperProtocol {\n func mapError(_ error: Error) -> BlockedStateReason\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\Protocols\BlockedStateErrorMapperProtocol.swift
BlockedStateErrorMapperProtocol.swift
Swift
434
0.95
0.066667
0.615385
react-lib
544
2024-07-19T20:16:00.283287
MIT
false
ae710a77f8f04b9b0f323ba5b2d3d3af
//\n// PostQuantumKeyExchangingProtocol.swift\n// PacketTunnel\n//\n// Created by Mojgan on 2024-07-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport WireGuardKitTypes\n\npublic protocol EphemeralPeerExchangingProtocol {\n func start() async\n func receivePostQuantumKey(\n _ preSharedKey: PreSharedKey,\n ephemeralKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async\n func receiveEphemeralPeerPrivateKey(_: PrivateKey, daitaParameters: DaitaV2Parameters?) async\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\Protocols\EphemeralPeerExchangingProtocol.swift
EphemeralPeerExchangingProtocol.swift
Swift
545
0.95
0
0.388889
python-kit
425
2025-02-18T14:45:09.169097
GPL-3.0
false
21bfc1590acb09c9c0aeac7544f5b99f
//\n// SettingsReaderProtocol.swift\n// PacketTunnel\n//\n// Created by pronebird on 25/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\nimport Network\n@preconcurrency import WireGuardKitTypes\n\n/// A type that implements a reader that can return settings required by `PacketTunnelActor` in order to configure the tunnel.\npublic protocol SettingsReaderProtocol {\n /**\n Read settings from storage.\n\n - Throws: an error thrown by this method is passed down to the implementation of `BlockedStateErrorMapperProtocol`.\n - Returns: `Settings` used to configure packet tunnel adapter.\n */\n func read() throws -> Settings\n}\n\n/// Struct holding settings necessary to configure packet tunnel adapter.\npublic struct Settings: Equatable, Sendable {\n /// Private key used by device.\n public var privateKey: PrivateKey\n\n /// IP addresses assigned for tunnel interface.\n public var interfaceAddresses: [IPAddressRange]\n\n public var tunnelSettings: LatestTunnelSettings\n\n public init(\n privateKey: PrivateKey,\n interfaceAddresses: [IPAddressRange],\n tunnelSettings: LatestTunnelSettings\n ) {\n self.privateKey = privateKey\n self.interfaceAddresses = interfaceAddresses\n self.tunnelSettings = tunnelSettings\n }\n}\n\nextension Settings {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints {\n tunnelSettings.relayConstraints\n }\n\n /// DNS servers selected by user.\n public var dnsServers: SelectedDNSServers {\n /**\n Converts `DNSSettings` to `SelectedDNSServers` structure.\n */\n if tunnelSettings.dnsSettings.effectiveEnableCustomDNS {\n let addresses = Array(\n tunnelSettings.dnsSettings.customDNSDomains\n .prefix(DNSSettings.maxAllowedCustomDNSDomains)\n )\n return .custom(addresses)\n } else if let serverAddress = tunnelSettings.dnsSettings.blockingOptions.serverAddress {\n return .blocking(serverAddress)\n } else {\n return .gateway\n }\n }\n\n /// Obfuscation settings\n public var obfuscation: WireGuardObfuscationSettings {\n tunnelSettings.wireGuardObfuscation\n }\n\n public var quantumResistance: TunnelQuantumResistance {\n tunnelSettings.tunnelQuantumResistance\n }\n\n /// Whether multi-hop is enabled.\n public var multihopState: MultihopState {\n tunnelSettings.tunnelMultihopState\n }\n\n /// DAITA settings.\n public var daita: DAITASettings {\n tunnelSettings.daita\n }\n}\n\n/// Enum describing selected DNS servers option.\npublic enum SelectedDNSServers: Equatable, Sendable {\n /// Custom DNS servers.\n case custom([IPAddress])\n /// Mullvad server acting as a blocking DNS proxy.\n case blocking(IPAddress)\n /// Gateway IP will be used as DNS automatically.\n case gateway\n\n public static func == (lhs: SelectedDNSServers, rhs: SelectedDNSServers) -> Bool {\n return switch (lhs, rhs) {\n case let (.custom(lhsAddresss), .custom(rhsAddresses)):\n lhsAddresss.map { $0.rawValue } == rhsAddresses.map { $0.rawValue }\n case let (.blocking(lhsAddress), .blocking(rhsAddress)):\n lhsAddress.rawValue == rhsAddress.rawValue\n case (.gateway, .gateway):\n true\n default: false\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\Protocols\SettingsReaderProtocol.swift
SettingsReaderProtocol.swift
Swift
3,456
0.95
0.036036
0.25
python-kit
193
2023-08-23T02:37:38.983509
MIT
false
60b8c0049ebaedaa087125ee976f22b9
//\n// TunnelAdapterProtocol.swift\n// PacketTunnel\n//\n// Created by pronebird on 08/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\n@preconcurrency import WireGuardKitTypes\n\n/// Protocol describing interface for any kind of adapter implementing a VPN tunnel.\npublic protocol TunnelAdapterProtocol: Sendable {\n /// Start tunnel adapter or update active configuration.\n func start(configuration: TunnelAdapterConfiguration, daita: DaitaConfiguration?) async throws\n\n /// Start tunnel adapter or update active configuration.\n func startMultihop(\n entryConfiguration: TunnelAdapterConfiguration?,\n exitConfiguration: TunnelAdapterConfiguration,\n daita: DaitaConfiguration?\n ) async throws\n\n /// Stop tunnel adapter with the given configuration.\n func stop() async throws\n}\n\n/// Struct describing tunnel adapter configuration.\npublic struct TunnelAdapterConfiguration {\n public var privateKey: PrivateKey\n public var interfaceAddresses: [IPAddressRange]\n public var dns: [IPAddress]\n public var peer: TunnelPeer?\n public var allowedIPs: [IPAddressRange]\n public var pingableGateway: IPv4Address\n}\n\n/// Struct describing a single peer.\npublic struct TunnelPeer {\n public var endpoint: AnyIPEndpoint\n public var publicKey: PublicKey\n public var preSharedKey: PreSharedKey?\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Actor\Protocols\TunnelAdapterProtocol.swift
TunnelAdapterProtocol.swift
Swift
1,417
0.95
0.021739
0.333333
react-lib
464
2023-07-17T21:58:54.054144
GPL-3.0
false
c5e6db9c1541b12b432d0bf419ce59f2
// swiftlint:disable line_length\n// This is an autogenerated file, do not edit\npublic struct Maybenot {\n public let machines="""\n02eNptjLsNwCAQQ++yQRZImTJlRIfYBDEJA7ERJQtQ0iC+dxSIJ1mWLcv5TsLH9wMmF4KLqwkRAawk2yPR00CHX3V3j1GziWvE09NBBWg9Fjk=\n02eNqFjLENwCAMBP8hC2SJlKnTsVr2zBKUaVACNgiBEJxknex/Oezv9fjjRCF8mXLY4pAEbpeFJFlFqJBGA7PqWQ3spCer4l3rnvGDH6+FGlE=\n02eNqFjDkOgDAMBL056PkEJTVdvsY/+URKmojDmwiBUDyStbJ35DLuy5anWRrlqLTDcA0AkTXVkDt01ZAHwLFwludZeMsLLILlRRax4+lKcnrnl/8HJzqIIG0=\n02eNpdjr0LQVEYxt9zGES5o4myKVksFM45lEHKx0LJYDAZ5C+QRTHIaGETViYDKYPp3ijFYLj3KkmGK2WwuVwiv3rrrafnA1Jm16ijKBQ+6NRDGPJ2E0Xe6YnAD0hFD9nm/ObIHumlv4imZ3Mm8DwvtaxB0Jy1IUex0pYIIB30lhuCYkYvwW6nQFSV41R1L8vkmwlgEOONVvEaYt1SwLhdhxn8gdBgEfXU7RFmzeR9YtPPxrbqOVkLsd29XJhIJfbqRomGheLcYUWeFgxQodrq9wcP1E88/w==\n"""\n public let maximumEvents: UInt32 = 2048\n public let maximumActions: UInt32 = 1024\n public let maximumPadding: Double = 1.0\n public let maximumBlocking: Double = 1.0\n}\n// swiftlint:enable line_length\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Daita\Maybenot.swift
Maybenot.swift
Swift
984
0.8
0
0.2
node-utils
165
2025-05-22T11:24:15.850452
MIT
false
17a4d63e210304976e57d40fafe3010a
//\n// AppMessageHandler.swift\n// PacketTunnel\n//\n// Created by pronebird on 19/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\n\n/**\n Actor handling packet tunnel IPC (app) messages and patching them through to the right facility.\n */\npublic struct AppMessageHandler {\n private let logger = Logger(label: "AppMessageHandler")\n private let packetTunnelActor: PacketTunnelActorProtocol\n private let urlRequestProxy: URLRequestProxyProtocol\n private let apiRequestProxy: APIRequestProxyProtocol\n\n public init(\n packetTunnelActor: PacketTunnelActorProtocol,\n urlRequestProxy: URLRequestProxyProtocol,\n apiRequestProxy: APIRequestProxyProtocol\n ) {\n self.packetTunnelActor = packetTunnelActor\n self.urlRequestProxy = urlRequestProxy\n self.apiRequestProxy = apiRequestProxy\n }\n\n /**\n Handle app message received via packet tunnel IPC.\n\n - Message data is expected to be a serialized `TunnelProviderMessage`.\n - Reply is expected to be wrapped in `TunnelProviderReply`.\n - Return `nil` in the event of error or when the call site does not expect any reply.\n\n Calls to reconnect and notify actor when private key is changed are meant to run in parallel because those tasks are serialized in `TunnelManager` and await\n the acknowledgment from IPC before starting next operation, hence it's critical to return as soon as possible.\n (See `TunnelManager.reconnectTunnel()`, `SendTunnelProviderMessageOperation`)\n */\n public func handleAppMessage(_ messageData: Data) async -> Data? {\n guard let message = decodeMessage(messageData) else { return nil }\n\n logger.debug("Received app message: \(message)")\n\n switch message {\n case let .sendURLRequest(request):\n return await encodeReply(urlRequestProxy.sendRequest(request))\n\n case let .sendAPIRequest(request):\n return await encodeReply(apiRequestProxy.sendRequest(request))\n\n case let .cancelURLRequest(id):\n urlRequestProxy.cancelRequest(identifier: id)\n return nil\n\n case let .cancelAPIRequest(id):\n apiRequestProxy.cancelRequest(identifier: id)\n return nil\n\n case .getTunnelStatus:\n return await encodeReply(packetTunnelActor.observedState)\n\n case .privateKeyRotation:\n packetTunnelActor.notifyKeyRotation(date: Date())\n return nil\n\n case let .reconnectTunnel(nextRelay):\n packetTunnelActor.reconnect(to: nextRelay, reconnectReason: ActorReconnectReason.userInitiated)\n return nil\n }\n }\n\n /// Deserialize `TunnelProviderMessage` or return `nil` on error. Errors are logged but ignored.\n private func decodeMessage(_ data: Data) -> TunnelProviderMessage? {\n do {\n return try TunnelProviderMessage(messageData: data)\n } catch {\n logger.error(error: error, message: "Failed to decode the app message.")\n return nil\n }\n }\n\n /// Encode `TunnelProviderReply` or return `nil` on error. Errors are logged but ignored.\n private func encodeReply<T: Codable>(_ reply: T) -> Data? {\n do {\n return try TunnelProviderReply(reply).encode()\n } catch {\n logger.error(error: error, message: "Failed to encode the app message reply.")\n return nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\IPC\AppMessageHandler.swift
AppMessageHandler.swift
Swift
3,489
0.95
0.052632
0.164557
awesome-app
492
2025-04-10T03:28:27.328300
MIT
false
7e8bcf429b899b9252cb85e2167422cd
//\n// PacketTunnelOptions.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 22/08/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n\npublic struct PacketTunnelOptions {\n /// Keys for options dictionary\n private enum Keys: String {\n /// Option key that holds serialized `SelectedRelay` value encoded using `JSONEncoder`.\n /// Used for passing the pre-selected relay in the GUI process to the Packet tunnel process.\n case selectedRelays = "selected-relays"\n\n /// Option key that holds an `NSNumber` value, which is when set to `1` indicates that the tunnel was started by the system.\n /// System automatically provides that flag to the tunnel.\n case isOnDemand = "is-on-demand"\n }\n\n private var _rawOptions: [String: NSObject]\n\n public func rawOptions() -> [String: NSObject] {\n _rawOptions\n }\n\n public init() {\n _rawOptions = [:]\n }\n\n public init(rawOptions: [String: NSObject]) {\n _rawOptions = rawOptions\n }\n\n public func getSelectedRelays() throws -> SelectedRelays? {\n guard let data = _rawOptions[Keys.selectedRelays.rawValue] as? Data else { return nil }\n\n return try Self.decode(SelectedRelays.self, data)\n }\n\n public mutating func setSelectedRelays(_ value: SelectedRelays) throws {\n _rawOptions[Keys.selectedRelays.rawValue] = try Self.encode(value) as NSData\n }\n\n public func isOnDemand() -> Bool {\n _rawOptions[Keys.isOnDemand.rawValue] as? Int == 1\n }\n\n /// Encode custom parameter value\n private static func encode(_ value: some Codable) throws -> Data {\n try JSONEncoder().encode(value)\n }\n\n /// Decode custom parameter value\n private static func decode<T: Codable>(_ type: T.Type, _ data: Data) throws -> T {\n try JSONDecoder().decode(T.self, from: data)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\IPC\PacketTunnelOptions.swift
PacketTunnelOptions.swift
Swift
1,910
0.95
0.098361
0.291667
vue-tools
366
2025-05-28T13:03:47.263291
MIT
false
7a6bf105bc51b6768b8deb250d533ab2
//\n// TunnelProviderMessage.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 27/07/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n\n/// Enum describing supported app messages handled by packet tunnel provider.\npublic enum TunnelProviderMessage: Codable, CustomStringConvertible {\n /// Request the tunnel to reconnect.\n case reconnectTunnel(NextRelays)\n\n /// Request the tunnel status.\n case getTunnelStatus\n\n /// Send HTTP request outside of VPN tunnel.\n case sendURLRequest(ProxyURLRequest)\n\n /// Send API request outside of VPN tunnel.\n case sendAPIRequest(ProxyAPIRequest)\n\n /// Cancel HTTP request sent outside of VPN tunnel.\n case cancelURLRequest(UUID)\n\n /// Cancel API request sent outside of VPN tunnel.\n case cancelAPIRequest(UUID)\n\n /// Notify tunnel about private key rotation.\n case privateKeyRotation\n\n public var description: String {\n switch self {\n case .reconnectTunnel:\n return "reconnect-tunnel"\n case .getTunnelStatus:\n return "get-tunnel-status"\n case .sendURLRequest:\n return "send-http-request"\n case .sendAPIRequest:\n return "send-api-request"\n case .cancelURLRequest:\n return "cancel-http-request"\n case .cancelAPIRequest:\n return "cancel-api-request"\n case .privateKeyRotation:\n return "private-key-rotation"\n }\n }\n\n public init(messageData: Data) throws {\n self = try JSONDecoder().decode(Self.self, from: messageData)\n }\n\n public func encode() throws -> Data {\n try JSONEncoder().encode(self)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\IPC\TunnelProviderMessage.swift
TunnelProviderMessage.swift
Swift
1,708
0.95
0.04918
0.3
react-lib
612
2024-12-19T19:21:40.715015
Apache-2.0
false
286d9cf0300ef040e129e957ef5b7afb
//\n// TunnelProviderReply.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 20/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Container type for tunnel provider reply.\npublic struct TunnelProviderReply<T: Codable>: Codable {\n public var value: T\n\n public init(_ value: T) {\n self.value = value\n }\n\n public init(messageData: Data) throws {\n self = try JSONDecoder().decode(Self.self, from: messageData)\n }\n\n public func encode() throws -> Data {\n try JSONEncoder().encode(self)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\IPC\TunnelProviderReply.swift
TunnelProviderReply.swift
Swift
581
0.95
0.115385
0.380952
vue-tools
227
2023-09-09T02:29:33.907691
Apache-2.0
false
b4bc058bfe6d3488e6cd5be8e4cf88eb
//\n// ICMP.swift\n// PacketTunnelCore\n//\n// Created by Andrew Bulhak on 2024-07-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nstruct ICMP {\n public enum Error: LocalizedError {\n case malformedResponse(MalformedResponseReason)\n\n public var errorDescription: String? {\n switch self {\n case let .malformedResponse(reason):\n return "Malformed response: \(reason)."\n }\n }\n }\n\n public enum MalformedResponseReason {\n case ipv4PacketTooSmall\n case icmpHeaderTooSmall\n case invalidIPVersion\n case checksumMismatch(UInt16, UInt16)\n }\n\n private static func in_chksum(_ data: some Sequence<UInt8>) -> UInt16 {\n var iterator = data.makeIterator()\n var words = [UInt16]()\n\n while let byte = iterator.next() {\n let nextByte = iterator.next() ?? 0\n let word = UInt16(byte) << 8 | UInt16(nextByte)\n\n words.append(word)\n }\n\n let sum = words.reduce(0, &+)\n\n return ~sum\n }\n\n static func createICMPPacket(identifier: UInt16, sequenceNumber: UInt16) -> Data {\n var header = ICMPHeader(\n type: UInt8(ICMP_ECHO),\n code: 0,\n checksum: 0,\n identifier: identifier.bigEndian,\n sequenceNumber: sequenceNumber.bigEndian\n )\n header.checksum = withUnsafeBytes(of: &header) { in_chksum($0).bigEndian }\n\n return withUnsafeBytes(of: &header) { Data($0) }\n }\n\n static func parseICMPResponse(buffer: inout [UInt8], length: Int) throws -> ICMPHeader {\n try buffer.withUnsafeMutableBytes { bufferPointer in\n // Check IP packet size.\n guard length >= MemoryLayout<IPv4Header>.size else {\n throw Error.malformedResponse(.ipv4PacketTooSmall)\n }\n\n // Verify IPv4 header.\n let ipv4Header = bufferPointer.load(as: IPv4Header.self)\n let payloadLength = length - ipv4Header.headerLength\n\n guard payloadLength >= MemoryLayout<ICMPHeader>.size else {\n throw Error.malformedResponse(.icmpHeaderTooSmall)\n }\n\n guard ipv4Header.isIPv4Version else {\n throw Error.malformedResponse(.invalidIPVersion)\n }\n\n // Parse ICMP header.\n let icmpHeaderPointer = bufferPointer.baseAddress!\n .advanced(by: ipv4Header.headerLength)\n .assumingMemoryBound(to: ICMPHeader.self)\n\n // Copy server checksum.\n let serverChecksum = icmpHeaderPointer.pointee.checksum.bigEndian\n\n // Reset checksum field before calculating checksum.\n icmpHeaderPointer.pointee.checksum = 0\n\n // Verify ICMP checksum.\n let payloadPointer = UnsafeRawBufferPointer(\n start: icmpHeaderPointer,\n count: payloadLength\n )\n let clientChecksum = ICMP.in_chksum(payloadPointer)\n if clientChecksum != serverChecksum {\n throw Error.malformedResponse(.checksumMismatch(clientChecksum, serverChecksum))\n }\n\n // Ensure endianness before returning ICMP packet to delegate.\n var icmpHeader = icmpHeaderPointer.pointee\n icmpHeader.identifier = icmpHeader.identifier.bigEndian\n icmpHeader.sequenceNumber = icmpHeader.sequenceNumber.bigEndian\n icmpHeader.checksum = serverChecksum\n return icmpHeader\n }\n }\n}\n\nprivate extension IPv4Header {\n /// Returns IPv4 header length.\n var headerLength: Int {\n Int(versionAndHeaderLength & 0x0F) * MemoryLayout<UInt32>.size\n }\n\n /// Returns `true` if version header indicates IPv4.\n var isIPv4Version: Bool {\n (versionAndHeaderLength & 0xF0) == 0x40\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Pinger\ICMP.swift
ICMP.swift
Swift
3,884
0.95
0.042017
0.164948
python-kit
94
2024-05-08T11:22:59.873719
BSD-3-Clause
false
af0160f0a7069b4ae9fc537d617665e2
//\n// PingerProtocol.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 10/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\n/// The result of processing ICMP reply.\npublic enum PingerReply {\n /// ICMP reply was successfully parsed.\n case success(_ sender: IPAddress, _ sequenceNumber: UInt16)\n\n /// ICMP reply couldn't be parsed.\n case parseError(Error)\n}\n\n/// The result of sending ICMP echo.\npublic struct PingerSendResult {\n /// Sequence id.\n public var sequenceNumber: UInt16\n\n public init(sequenceNumber: UInt16) {\n self.sequenceNumber = sequenceNumber\n }\n}\n\n/// A type capable of sending and receving ICMP traffic.\npublic protocol PingerProtocol {\n var onReply: ((PingerReply) -> Void)? { get set }\n\n func startPinging(destAddress: IPv4Address) throws\n func stopPinging()\n func send() throws -> PingerSendResult\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Pinger\PingerProtocol.swift
PingerProtocol.swift
Swift
928
0.95
0
0.419355
react-lib
351
2023-11-17T05:41:48.403626
Apache-2.0
false
0c4a6251f135cf8cbf141201c684e922
//\n// TunnelPinger.swift\n// PacketTunnelCore\n//\n// Created by Andrew Bulhak on 2024-07-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport Network\nimport PacketTunnelCore\nimport WireGuardKit\n\npublic final class TunnelPinger: PingerProtocol {\n private var sequenceNumber: UInt16 = 0\n private let stateLock = NSLock()\n private let pingReceiveQueue: DispatchQueue\n private let replyQueue: DispatchQueue\n private var destAddress: IPv4Address?\n /// Always accessed from the `replyQueue` and is assigned once, on the main thread of the PacketTunnel. It is thread safe.\n public var onReply: ((PingerReply) -> Void)?\n private var pingProvider: ICMPPingProvider\n\n private let logger: Logger\n\n init(pingProvider: ICMPPingProvider, replyQueue: DispatchQueue) {\n self.pingProvider = pingProvider\n self.replyQueue = replyQueue\n self.pingReceiveQueue = DispatchQueue(label: "PacketTunnel.Receive.icmp")\n self.logger = Logger(label: "TunnelPinger")\n }\n\n public func startPinging(destAddress: IPv4Address) throws {\n stateLock.withLock {\n self.destAddress = destAddress\n }\n pingReceiveQueue.async { [weak self] in\n while let self {\n do {\n let seq = try pingProvider.receiveICMP()\n\n replyQueue.async { [weak self] in\n self?.stateLock.withLock {\n self?.onReply?(PingerReply.success(destAddress, UInt16(seq)))\n }\n }\n } catch {\n replyQueue.async { [weak self] in\n self?.stateLock.withLock {\n if self?.destAddress != nil {\n self?.onReply?(PingerReply.parseError(error))\n }\n }\n }\n return\n }\n }\n }\n }\n\n public func stopPinging() {\n stateLock.withLock {\n self.destAddress = nil\n }\n }\n\n public func send() throws -> PingerSendResult {\n let sequenceNumber = nextSequenceNumber()\n\n stateLock.lock()\n defer { stateLock.unlock() }\n guard destAddress != nil else { throw WireGuardAdapterError.invalidState }\n // NOTE: we cheat here by returning the destination address we were passed, rather than parsing it from the packet on the other side of the FFI boundary.\n try pingProvider.sendICMPPing(seqNumber: sequenceNumber)\n\n return PingerSendResult(sequenceNumber: UInt16(sequenceNumber))\n }\n\n private func nextSequenceNumber() -> UInt16 {\n stateLock.lock()\n let (nextValue, _) = sequenceNumber.addingReportingOverflow(1)\n sequenceNumber = nextValue\n stateLock.unlock()\n\n return nextValue\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\Pinger\TunnelPinger.swift
TunnelPinger.swift
Swift
2,944
0.95
0.068182
0.118421
vue-tools
845
2024-03-07T22:07:17.090640
Apache-2.0
false
443dd7e3fb9a0b9b7377a5eb0c17242c
//\n// DefaultPathObserverProtocol.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 10/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\n/// A type providing default path access and observation.\npublic protocol DefaultPathObserverProtocol: Sendable {\n /// Returns current default path or `nil` if unknown yet.\n var currentPathStatus: Network.NWPath.Status { get }\n\n /// Start observing changes to `defaultPath`.\n /// This call must be idempotent. Multiple calls to start should replace the existing handler block.\n func start(_ body: @escaping @Sendable (Network.NWPath.Status) -> Void)\n\n /// Stop observing changes to `defaultPath`.\n func stop()\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\DefaultPathObserverProtocol.swift
DefaultPathObserverProtocol.swift
Swift
735
0.95
0.043478
0.631579
vue-tools
276
2024-02-13T04:13:41.304280
GPL-3.0
false
4858630b89409be74084faf219b5d5fd
//\n// PingStats.swift\n// PacketTunnelCore\n//\n// Created by Marco Nikic on 2024-02-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Ping statistics.\nstruct PingStats {\n /// Dictionary holding sequence and corresponding date when echo request took place.\n var requests = [UInt16: Date]()\n\n /// Timestamp when last echo request was sent.\n var lastRequestDate: Date?\n\n /// Timestamp when last echo reply was received.\n var lastReplyDate: Date?\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\PingStats.swift
PingStats.swift
Swift
504
0.95
0
0.647059
python-kit
388
2023-08-31T10:59:14.434447
MIT
false
0754ab90e273aa4bff0fd46ed5875599
//\n// TunnelDeviceInfoProtocol.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 08/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A type that can provide statistics and basic information about tunnel device.\npublic protocol TunnelDeviceInfoProtocol {\n /// Returns tunnel interface name (i.e utun0) if available.\n var interfaceName: String? { get }\n\n /// Returns tunnel statistics.\n func getStats() throws -> WgStats\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\TunnelDeviceInfoProtocol.swift
TunnelDeviceInfoProtocol.swift
Swift
488
0.95
0.055556
0.666667
awesome-app
319
2023-10-10T18:49:41.126554
MIT
false
85327f79221f8e1fa66cbfc4dc5b32c3
//\n// TunnelMonitor.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 09/02/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\nimport Network\nimport NetworkExtension\n\n/// Tunnel monitor.\npublic final class TunnelMonitor: TunnelMonitorProtocol {\n private let tunnelDeviceInfo: TunnelDeviceInfoProtocol\n\n private let nslock = NSLock()\n private let timerQueue = DispatchQueue(label: "TunnelMonitor-timerQueue")\n private let eventQueue: DispatchQueue\n private let timings: TunnelMonitorTimings\n\n private var pinger: PingerProtocol\n private var isObservingDefaultPath = false\n private var timer: DispatchSourceTimer?\n\n private var state: TunnelMonitorState\n private var probeAddress: IPv4Address?\n\n private let logger = Logger(label: "TunnelMonitor")\n\n private var _onEvent: ((TunnelMonitorEvent) -> Void)?\n public var onEvent: ((TunnelMonitorEvent) -> Void)? {\n get {\n nslock.withLock {\n return _onEvent\n }\n }\n set {\n nslock.withLock {\n _onEvent = newValue\n }\n }\n }\n\n public init(\n eventQueue: DispatchQueue,\n pinger: PingerProtocol,\n tunnelDeviceInfo: TunnelDeviceInfoProtocol,\n timings: TunnelMonitorTimings\n ) {\n self.eventQueue = eventQueue\n self.tunnelDeviceInfo = tunnelDeviceInfo\n\n self.timings = timings\n state = TunnelMonitorState(timings: timings)\n\n self.pinger = pinger\n self.pinger.onReply = { [weak self] reply in\n guard let self else { return }\n\n switch reply {\n case let .success(sender, sequenceNumber):\n didReceivePing(from: sender, sequenceNumber: sequenceNumber)\n\n case let .parseError(error):\n logger.error(error: error, message: "Failed to parse ICMP response.")\n }\n }\n }\n\n deinit {\n stop()\n }\n\n public func start(probeAddress: IPv4Address) {\n nslock.lock()\n defer { nslock.unlock() }\n\n if case .stopped = state.connectionState {\n logger.debug("Start with address: \(probeAddress).")\n } else {\n _stop(forRestart: true)\n logger.debug("Restart with address: \(probeAddress).")\n }\n\n self.probeAddress = probeAddress\n state.connectionState = .pendingStart\n\n startMonitoring()\n }\n\n public func stop() {\n nslock.lock()\n defer { nslock.unlock() }\n\n _stop()\n }\n\n public func onWake() {\n nslock.lock()\n defer { nslock.unlock() }\n\n logger.trace("Wake up.")\n\n switch state.connectionState {\n case .connecting, .connected:\n startConnectivityCheckTimer()\n\n case .waitingConnectivity, .pendingStart, .stopped, .recovering:\n break\n }\n }\n\n public func onSleep() {\n nslock.lock()\n defer { nslock.unlock() }\n\n logger.trace("Prepare to sleep.")\n\n stopConnectivityCheckTimer()\n }\n\n public func handleNetworkPathUpdate(_ networkPath: Network.NWPath.Status) {\n nslock.withLock {\n let isReachable = networkPath == .satisfied || networkPath == .requiresConnection\n\n switch state.connectionState {\n case .pendingStart:\n if isReachable {\n logger.debug("Start monitoring connection.")\n startMonitoring()\n } else {\n logger.debug("Wait for network to become reachable before starting monitoring.")\n state.connectionState = .waitingConnectivity\n }\n\n case .waitingConnectivity:\n guard isReachable else { return }\n\n logger.debug("Network is reachable. Resume monitoring.")\n startMonitoring()\n\n case .connecting, .connected:\n guard !isReachable else { return }\n\n logger.debug("Network is unreachable. Pause monitoring.")\n state.connectionState = .waitingConnectivity\n stopMonitoring(resetRetryAttempt: true)\n\n case .stopped, .recovering:\n break\n }\n }\n }\n\n // MARK: - Private\n\n private func _stop(forRestart: Bool = false) {\n if case .stopped = state.connectionState {\n return\n }\n\n if !forRestart {\n logger.debug("Stop tunnel monitor.")\n }\n\n probeAddress = nil\n\n stopMonitoring(resetRetryAttempt: !forRestart)\n\n state.connectionState = .stopped\n }\n\n private func checkConnectivity() {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard let newStats = getStats(),\n state.connectionState == .connecting || state.connectionState == .connected\n else { return }\n\n // Check if counters were reset.\n let isStatsReset = newStats.bytesReceived < state.netStats.bytesReceived ||\n newStats.bytesSent < state.netStats.bytesSent\n\n guard !isStatsReset else {\n logger.trace("Stats was being reset.")\n state.netStats = newStats\n return\n }\n\n #if DEBUG\n logCounters(currentStats: state.netStats, newStats: newStats)\n #endif\n\n let now = Date()\n state.updateNetStats(newStats: newStats, now: now)\n\n let timeout = state.getPingTimeout()\n let evaluation = state.evaluateConnection(now: now, pingTimeout: timeout)\n\n if evaluation != .ok {\n logger.trace("Evaluation: \(evaluation)")\n }\n\n switch evaluation {\n case .ok:\n break\n\n case .pingTimeout:\n startConnectionRecovery()\n\n case .suspendHeartbeat:\n state.isHeartbeatSuspended = true\n\n case .sendHeartbeatPing, .retryHeartbeatPing, .sendNextPing, .sendInitialPing,\n .inboundTrafficTimeout, .trafficTimeout:\n if state.isHeartbeatSuspended {\n state.isHeartbeatSuspended = false\n state.timeoutReference = now\n }\n sendPing(now: now)\n }\n }\n\n #if DEBUG\n private func logCounters(currentStats: WgStats, newStats: WgStats) {\n let rxDelta = newStats.bytesReceived.saturatingSubtraction(currentStats.bytesReceived)\n let txDelta = newStats.bytesSent.saturatingSubtraction(currentStats.bytesSent)\n\n guard rxDelta > 0 || txDelta > 0 else { return }\n\n logger.trace(\n """\n rx: \(newStats.bytesReceived) (+\(rxDelta)) \\n tx: \(newStats.bytesSent) (+\(txDelta))\n """\n )\n }\n #endif\n\n private func startConnectionRecovery() {\n stopMonitoring(resetRetryAttempt: false)\n\n state.retryAttempt = state.retryAttempt.saturatingAddition(1)\n state.connectionState = .recovering\n probeAddress = nil\n\n sendConnectionLostEvent()\n }\n\n private func sendPing(now: Date) {\n do {\n let sendResult = try pinger.send()\n state.updatePingStats(sendResult: sendResult, now: now)\n\n logger.trace("Send ping icmp_seq=\(sendResult.sequenceNumber).")\n } catch {\n logger.error(error: error, message: "Failed to send ping.")\n }\n }\n\n private func didReceivePing(from sender: IPAddress, sequenceNumber: UInt16) {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard let probeAddress else { return }\n\n if sender.rawValue != probeAddress.rawValue {\n logger.trace("Got reply from unknown sender: \(sender), expected: \(probeAddress).")\n }\n\n let now = Date()\n guard let pingTimestamp = state.setPingReplyReceived(sequenceNumber, now: now) else {\n logger.trace("Got unknown ping sequence: \(sequenceNumber).")\n return\n }\n\n logger.trace({\n let time = now.timeIntervalSince(pingTimestamp) * 1000\n let message = String(\n format: "Received reply icmp_seq=%d, time=%.2f ms.",\n sequenceNumber,\n time\n )\n return Logger.Message(stringLiteral: message)\n }())\n\n if case .connecting = state.connectionState {\n state.connectionState = .connected\n state.retryAttempt = 0\n sendConnectionEstablishedEvent()\n }\n }\n\n private func startMonitoring() {\n do {\n guard let probeAddress else {\n logger.debug("Failed to obtain probe address.")\n return\n }\n\n try pinger.startPinging(destAddress: probeAddress)\n\n state.connectionState = .connecting\n startConnectivityCheckTimer()\n } catch {\n logger.error(error: error, message: "Failed to open socket.")\n }\n }\n\n private func stopMonitoring(resetRetryAttempt: Bool) {\n stopConnectivityCheckTimer()\n pinger.stopPinging()\n\n state.netStats = WgStats()\n state.lastSeenRx = nil\n state.lastSeenTx = nil\n state.pingStats = PingStats()\n\n if resetRetryAttempt {\n state.retryAttempt = 0\n }\n\n state.isHeartbeatSuspended = false\n }\n\n private func startConnectivityCheckTimer() {\n let timer = DispatchSource.makeTimerSource(queue: timerQueue)\n timer.setEventHandler { [weak self] in\n self?.checkConnectivity()\n }\n timer.schedule(wallDeadline: .now(), repeating: timings.connectivityCheckInterval.timeInterval)\n timer.activate()\n\n self.timer?.cancel()\n self.timer = timer\n\n state.timeoutReference = Date()\n\n logger.trace("Start connectivity check timer.")\n }\n\n private func stopConnectivityCheckTimer() {\n guard let timer else { return }\n\n logger.trace("Stop connectivity check timer.")\n\n timer.cancel()\n self.timer = nil\n }\n\n private func sendConnectionEstablishedEvent() {\n eventQueue.async {\n self.onEvent?(.connectionEstablished)\n }\n }\n\n private func sendConnectionLostEvent() {\n eventQueue.async {\n self.onEvent?(.connectionLost)\n }\n }\n\n private func getStats() -> WgStats? {\n do {\n return try tunnelDeviceInfo.getStats()\n } catch {\n logger.error(error: error, message: "Failed to obtain adapter stats.")\n\n return nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\TunnelMonitor.swift
TunnelMonitor.swift
Swift
10,584
0.95
0.06383
0.047782
node-utils
781
2023-09-03T17:44:54.734456
BSD-3-Clause
false
a47df343f1f6101049532f09de9a4eda
//\n// TunnelMonitorProtocol.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 10/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\n/// Tunnel monitor event.\npublic enum TunnelMonitorEvent: Sendable {\n /// Dispatched after receiving the first ping response\n case connectionEstablished\n\n /// Dispatched when connection stops receiving ping responses.\n /// The handler is responsible to reconfigure the tunnel and call `TunnelMonitorProtocol.start(probeAddress:)` to resume connection monitoring.\n case connectionLost\n}\n\n/// A type that can provide tunnel monitoring.\npublic protocol TunnelMonitorProtocol: AnyObject, Sendable {\n /// Event handler that starts receiving events after the call to `start(probeAddress:)`.\n var onEvent: ((TunnelMonitorEvent) -> Void)? { get set }\n\n /// Start monitoring connection by pinging the given IP address.\n /// Normally we should only give an address of a tunnel gateway here which is reachable over tunnel interface.\n func start(probeAddress: IPv4Address)\n\n /// Stop monitoring connection.\n func stop()\n\n /// Restarts internal timers and gracefully handles transition from sleep to awake device state.\n /// Call this method when packet tunnel provider receives a wake event.\n func onWake()\n\n /// Cancels internal timers and time dependent data in preparation for device sleep.\n /// Call this method when packet tunnel provider receives a sleep event.\n func onSleep()\n\n /// Handle changes in network path, eg. update connection state and monitoring.\n func handleNetworkPathUpdate(_ networkPath: Network.NWPath.Status)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\TunnelMonitorProtocol.swift
TunnelMonitorProtocol.swift
Swift
1,680
0.95
0.022727
0.6
node-utils
949
2025-03-23T12:10:16.070215
GPL-3.0
false
421d39505ed1cd2ee7bf174cc73789de
//\n// TunnelMonitorState.swift\n// PacketTunnelCore\n//\n// Created by Marco Nikic on 2024-02-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Connection state.\nenum TunnelMonitorConnectionState {\n /// Initialized and doing nothing.\n case stopped\n\n /// Preparing to start.\n /// Intermediate state before receiving the first path update.\n case pendingStart\n\n /// Establishing connection.\n case connecting\n\n /// Connection is established.\n case connected\n\n /// Delegate is recovering connection.\n /// Delegate has to call `start(probeAddress:)` to complete recovery and resume monitoring.\n case recovering\n\n /// Waiting for network connectivity.\n case waitingConnectivity\n}\n\nenum ConnectionEvaluation {\n case ok\n case sendInitialPing\n case sendNextPing\n case sendHeartbeatPing\n case retryHeartbeatPing\n case suspendHeartbeat\n case inboundTrafficTimeout\n case trafficTimeout\n case pingTimeout\n}\n\n/// Tunnel monitor state.\nstruct TunnelMonitorState {\n /// Current connection state.\n var connectionState: TunnelMonitorConnectionState = .stopped\n\n /// Network counters.\n var netStats = WgStats()\n\n /// Ping stats.\n var pingStats = PingStats()\n\n /// Reference date used to determine if timeout has occurred.\n var timeoutReference = Date()\n\n /// Last seen change in rx counter.\n var lastSeenRx: Date?\n\n /// Last seen change in tx counter.\n var lastSeenTx: Date?\n\n /// Whether periodic heartbeat is suspended.\n var isHeartbeatSuspended = false\n\n /// Retry attempt.\n var retryAttempt: UInt32 = 0\n\n // Timings and timeouts.\n let timings: TunnelMonitorTimings\n\n func evaluateConnection(now: Date, pingTimeout: Duration) -> ConnectionEvaluation {\n switch connectionState {\n case .connecting:\n return handleConnectingState(now: now, pingTimeout: pingTimeout)\n case .connected:\n return handleConnectedState(now: now, pingTimeout: pingTimeout)\n default:\n return .ok\n }\n }\n\n func getPingTimeout() -> Duration {\n switch connectionState {\n case .connecting:\n let multiplier = timings.establishTimeoutMultiplier.saturatingPow(retryAttempt)\n let nextTimeout = timings.initialEstablishTimeout * Double(multiplier)\n\n if nextTimeout.isFinite, nextTimeout < timings.maxEstablishTimeout {\n return nextTimeout\n } else {\n return timings.maxEstablishTimeout\n }\n\n case .pendingStart, .connected, .waitingConnectivity, .stopped, .recovering:\n return timings.pingTimeout\n }\n }\n\n mutating func updateNetStats(newStats: WgStats, now: Date) {\n if newStats.bytesReceived > netStats.bytesReceived {\n lastSeenRx = now\n }\n\n if newStats.bytesSent > netStats.bytesSent {\n lastSeenTx = now\n }\n\n netStats = newStats\n }\n\n mutating func updatePingStats(sendResult: PingerSendResult, now: Date) {\n pingStats.requests.updateValue(now, forKey: sendResult.sequenceNumber)\n pingStats.lastRequestDate = now\n }\n\n mutating func setPingReplyReceived(_ sequenceNumber: UInt16, now: Date) -> Date? {\n guard let pingTimestamp = pingStats.requests.removeValue(forKey: sequenceNumber) else {\n return nil\n }\n\n pingStats.lastReplyDate = now\n timeoutReference = now\n\n return pingTimestamp\n }\n\n private func handleConnectingState(now: Date, pingTimeout: Duration) -> ConnectionEvaluation {\n if now.timeIntervalSince(timeoutReference) >= pingTimeout {\n return .pingTimeout\n }\n\n guard let lastRequestDate = pingStats.lastRequestDate else {\n return .sendInitialPing\n }\n\n if now.timeIntervalSince(lastRequestDate) >= timings.pingDelay {\n return .sendNextPing\n }\n\n return .ok\n }\n\n private func handleConnectedState(now: Date, pingTimeout: Duration) -> ConnectionEvaluation {\n if now.timeIntervalSince(timeoutReference) >= pingTimeout, !isHeartbeatSuspended {\n return .pingTimeout\n }\n\n guard let lastRequestDate = pingStats.lastRequestDate else {\n return .sendInitialPing\n }\n\n let timeSinceLastPing = now.timeIntervalSince(lastRequestDate)\n if let lastReplyDate = pingStats.lastReplyDate,\n lastRequestDate.timeIntervalSince(lastReplyDate) >= timings.heartbeatReplyTimeout,\n timeSinceLastPing >= timings.pingDelay, !isHeartbeatSuspended {\n return .retryHeartbeatPing\n }\n\n guard let lastSeenRx, let lastSeenTx else { return .ok }\n\n let rxTimeElapsed = now.timeIntervalSince(lastSeenRx)\n let txTimeElapsed = now.timeIntervalSince(lastSeenTx)\n\n if timeSinceLastPing >= timings.heartbeatPingInterval {\n // Send heartbeat if traffic is flowing.\n if rxTimeElapsed <= timings.trafficFlowTimeout || txTimeElapsed <= timings.trafficFlowTimeout {\n return .sendHeartbeatPing\n }\n\n if !isHeartbeatSuspended {\n return .suspendHeartbeat\n }\n }\n\n if timeSinceLastPing >= timings.pingDelay {\n if txTimeElapsed >= timings.trafficTimeout || rxTimeElapsed >= timings.trafficTimeout {\n return .trafficTimeout\n }\n\n if lastSeenTx > lastSeenRx, rxTimeElapsed >= timings.inboundTrafficTimeout {\n return .inboundTrafficTimeout\n }\n }\n\n return .ok\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\TunnelMonitorState.swift
TunnelMonitorState.swift
Swift
5,688
0.95
0.09375
0.18
node-utils
730
2023-07-11T15:12:01.831349
Apache-2.0
false
f8e9b29995ace0763c8884f6ad567f0b
//\n// TunnelMonitorTimings.swift\n// PacketTunnelCore\n//\n// Created by Jon Petersson on 2023-09-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\n\npublic struct TunnelMonitorTimings {\n /// Interval for periodic heartbeat ping issued when traffic is flowing.\n /// Should help to detect connectivity issues on networks that drop traffic in one of directions,\n /// regardless if tx/rx counters are being updated.\n let heartbeatPingInterval: Duration\n\n /// Heartbeat timeout that once exceeded triggers next heartbeat to be sent.\n let heartbeatReplyTimeout: Duration\n\n /// Timeout used to determine if there was a network activity lately.\n var trafficFlowTimeout: Duration { heartbeatPingInterval * 0.5 }\n\n /// Ping timeout.\n let pingTimeout: Duration\n\n /// Interval to wait before sending next ping.\n let pingDelay: Duration\n\n /// Initial timeout when establishing connection.\n let initialEstablishTimeout: Duration\n\n /// Multiplier applied to `establishTimeout` on each failed connection attempt.\n let establishTimeoutMultiplier: UInt32\n\n /// Maximum timeout when establishing connection.\n var maxEstablishTimeout: Duration { pingTimeout }\n\n /// Connectivity check periodicity.\n let connectivityCheckInterval: Duration\n\n /// Inbound traffic timeout used when outbound traffic was registered prior to inbound traffic.\n let inboundTrafficTimeout: Duration\n\n /// Traffic timeout applied when both tx/rx counters remain stale, i.e no traffic flowing.\n /// Ping is issued after that timeout is exceeded.s\n let trafficTimeout: Duration\n\n public init(\n heartbeatPingInterval: Duration = .seconds(10),\n heartbeatReplyTimeout: Duration = .seconds(3),\n pingTimeout: Duration = .seconds(15),\n pingDelay: Duration = .seconds(3),\n initialEstablishTimeout: Duration = .seconds(4),\n establishTimeoutMultiplier: UInt32 = 2,\n connectivityCheckInterval: Duration = .seconds(1),\n inboundTrafficTimeout: Duration = .seconds(5),\n trafficTimeout: Duration = .minutes(2)\n ) {\n self.heartbeatPingInterval = heartbeatPingInterval\n self.heartbeatReplyTimeout = heartbeatReplyTimeout\n self.pingTimeout = pingTimeout\n self.pingDelay = pingDelay\n self.initialEstablishTimeout = initialEstablishTimeout\n self.establishTimeoutMultiplier = establishTimeoutMultiplier\n self.connectivityCheckInterval = connectivityCheckInterval\n self.inboundTrafficTimeout = inboundTrafficTimeout\n self.trafficTimeout = trafficTimeout\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\TunnelMonitorTimings.swift
TunnelMonitorTimings.swift
Swift
2,637
0.95
0.043478
0.375
python-kit
560
2025-01-04T11:28:22.457947
Apache-2.0
false
5233dde018847e0963f5153ae61af4c4
//\n// WgStats.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 08/08/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct WgStats {\n public let bytesReceived: UInt64\n public let bytesSent: UInt64\n\n public init(bytesReceived: UInt64 = 0, bytesSent: UInt64 = 0) {\n self.bytesReceived = bytesReceived\n self.bytesSent = bytesSent\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\TunnelMonitor\WgStats.swift
WgStats.swift
Swift
416
0.95
0
0.4375
awesome-app
916
2024-10-10T00:14:48.310373
GPL-3.0
false
bfcb07e3bb72dfb2c484fc837027101d
//\n// ProxyURLRequest.swift\n// PacketTunnelCore\n//\n// Created by Sajad Vishkai on 2022-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Struct describing serializable URLRequest data.\npublic struct ProxyURLRequest: Codable {\n public let id: UUID\n public let url: URL\n public let method: String?\n public let httpBody: Data?\n public let httpHeaders: [String: String]?\n\n public var urlRequest: URLRequest {\n var urlRequest = URLRequest(url: url)\n urlRequest.httpMethod = method\n urlRequest.httpBody = httpBody\n urlRequest.allHTTPHeaderFields = httpHeaders\n return urlRequest\n }\n\n public init?(id: UUID, urlRequest: URLRequest) {\n guard let urlRequestUrl = urlRequest.url else { return nil }\n\n self.id = id\n url = urlRequestUrl\n method = urlRequest.httpMethod\n httpBody = urlRequest.httpBody\n httpHeaders = urlRequest.allHTTPHeaderFields\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\URLRequestProxy\ProxyURLRequest.swift
ProxyURLRequest.swift
Swift
990
0.95
0
0.258065
node-utils
4
2025-06-27T01:18:26.749949
Apache-2.0
false
6ea56ff5efcec0e54517951735e485cd
//\n// ProxyURLResponse.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 20/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n\n/// Struct describing serializable URLResponse data.\npublic struct ProxyURLResponse: Codable, Sendable {\n public let data: Data?\n public let response: HTTPURLResponseWrapper?\n public let error: URLErrorWrapper?\n\n public init(data: Data?, response: URLResponse?, error: Error?) {\n self.data = data\n self.response = response.flatMap { HTTPURLResponseWrapper($0) }\n self.error = error.flatMap { URLErrorWrapper($0) }\n }\n}\n\npublic struct URLErrorWrapper: Codable, Sendable {\n public let code: Int?\n public let localizedDescription: String\n\n public init?(_ error: Error) {\n localizedDescription = error.localizedDescription\n code = (error as? URLError)?.errorCode\n }\n\n public var originalError: Error? {\n guard let code else { return nil }\n\n return URLError(URLError.Code(rawValue: code))\n }\n}\n\npublic struct HTTPURLResponseWrapper: Codable, Sendable {\n public let url: URL?\n public let statusCode: Int\n public let headerFields: [String: String]?\n\n public init?(_ response: URLResponse) {\n guard let response = response as? HTTPURLResponse else { return nil }\n\n url = response.url\n statusCode = response.statusCode\n headerFields = Dictionary(\n uniqueKeysWithValues: response.allHeaderFields.map { ("\($0)", "\($1)") }\n )\n }\n\n public var originalResponse: HTTPURLResponse? {\n guard let url else { return nil }\n\n return HTTPURLResponse(\n url: url,\n statusCode: statusCode,\n httpVersion: nil,\n headerFields: headerFields\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\URLRequestProxy\ProxyURLResponse.swift
ProxyURLResponse.swift
Swift
1,830
0.95
0
0.148148
node-utils
105
2024-09-29T03:54:52.817634
GPL-3.0
false
fb36e3eb84184a970ac277bcbb73805b
//\n// URLRequestProxy.swift\n// PacketTunnelCore\n//\n// Created by pronebird on 03/02/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\n/// Network request proxy capable of passing serializable requests and responses over the given transport provider.\npublic final class URLRequestProxy: @unchecked Sendable {\n /// Serial queue used for synchronizing access to class members.\n private let dispatchQueue: DispatchQueue\n\n private let transportProvider: RESTTransportProvider\n\n /// List of all proxied network requests bypassing VPN.\n private var proxiedRequests: [UUID: Cancellable] = [:]\n\n public init(\n dispatchQueue: DispatchQueue,\n transportProvider: RESTTransportProvider\n ) {\n self.dispatchQueue = dispatchQueue\n self.transportProvider = transportProvider\n }\n\n public func sendRequest(\n _ proxyRequest: ProxyURLRequest,\n completionHandler: @escaping @Sendable (ProxyURLResponse) -> Void\n ) {\n dispatchQueue.async {\n guard let transportProvider = self.transportProvider.makeTransport() else {\n // Edge case in which case we return `ProxyURLResponse` with no data.\n completionHandler(ProxyURLResponse(data: nil, response: nil, error: nil))\n return\n }\n\n // The task sent by `transport.sendRequest` comes in an already resumed state\n let task = transportProvider.sendRequest(proxyRequest.urlRequest) { [self] data, response, error in\n // However there is no guarantee about which queue the execution resumes on\n // Use `dispatchQueue` to guarantee thread safe access to `proxiedRequests`\n dispatchQueue.async {\n let response = ProxyURLResponse(data: data, response: response, error: error)\n _ = self.removeRequest(identifier: proxyRequest.id)\n\n completionHandler(response)\n }\n }\n\n // All tasks should have unique identifiers, but if not, cancel the task scheduled\n // earlier.\n let oldTask = self.addRequest(identifier: proxyRequest.id, task: task)\n oldTask?.cancel()\n }\n }\n\n public func cancelRequest(identifier: UUID) {\n dispatchQueue.async {\n let task = self.removeRequest(identifier: identifier)\n\n task?.cancel()\n }\n }\n\n private func addRequest(identifier: UUID, task: Cancellable) -> Cancellable? {\n dispatchPrecondition(condition: .onQueue(dispatchQueue))\n return proxiedRequests.updateValue(task, forKey: identifier)\n }\n\n private func removeRequest(identifier: UUID) -> Cancellable? {\n dispatchPrecondition(condition: .onQueue(dispatchQueue))\n return proxiedRequests.removeValue(forKey: identifier)\n }\n}\n\nextension URLRequestProxy {\n public func sendRequest(_ proxyRequest: ProxyURLRequest) async -> ProxyURLResponse {\n return await withCheckedContinuation { continuation in\n sendRequest(proxyRequest) { proxyResponse in\n continuation.resume(returning: proxyResponse)\n }\n }\n }\n}\n\nextension URLRequestProxy: URLRequestProxyProtocol {}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\URLRequestProxy\URLRequestProxy.swift
URLRequestProxy.swift
Swift
3,308
0.95
0.044444
0.213333
react-lib
670
2023-09-23T22:29:45.023798
Apache-2.0
false
a93cfe2411e68e8170896b9827606400
//\n// URLRequestProxyProtocol.swift\n// PacketTunnelCore\n//\n// Created by Jon Petersson on 2023-10-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n\npublic protocol URLRequestProxyProtocol {\n func sendRequest(_ proxyRequest: ProxyURLRequest, completionHandler: @escaping @Sendable (ProxyURLResponse) -> Void)\n func sendRequest(_ proxyRequest: ProxyURLRequest) async -> ProxyURLResponse\n func cancelRequest(identifier: UUID)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCore\URLRequestProxy\URLRequestProxyProtocol.swift
URLRequestProxyProtocol.swift
Swift
492
0.95
0
0.5
awesome-app
695
2023-09-04T14:37:45.917765
Apache-2.0
false
2bda82c13c87873bb1985c406e42199e
//\n// BlockedStateErrorMapperStub.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 18/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport PacketTunnelCore\n\n/// Blocked state error mapper stub that can be configured with a block to simulate a desired behavior.\nclass BlockedStateErrorMapperStub: BlockedStateErrorMapperProtocol {\n let block: (Error) -> BlockedStateReason\n\n /// Initialize a stub that always returns .unknown block reason.\n init() {\n self.block = { _ in .unknown }\n }\n\n /// Initialize a stub with custom error mapper block.\n init(block: @escaping (Error) -> BlockedStateReason) {\n self.block = block\n }\n\n func mapError(_ error: Error) -> BlockedStateReason {\n return block(error)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\BlockedStateErrorMapperStub.swift
BlockedStateErrorMapperStub.swift
Swift
828
0.95
0.033333
0.4
awesome-app
294
2024-02-16T13:56:39.851050
GPL-3.0
true
d5ee452003671167e357901f598acf1b
//\n// DefaultPathObserverFake.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 16/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\nimport NetworkExtension\nimport PacketTunnelCore\n\n/// Default path observer fake that uses in-memory storage to keep current path and provides a method to simulate path change from tests.\nclass DefaultPathObserverFake: DefaultPathObserverProtocol, @unchecked Sendable {\n var currentPathStatus: Network.NWPath.Status { .satisfied }\n private var defaultPathHandler: ((Network.NWPath.Status) -> Void)?\n\n public var onStart: (() -> Void)?\n public var onStop: (() -> Void)?\n\n func start(_ body: @escaping (Network.NWPath.Status) -> Void) {\n defaultPathHandler = body\n onStart?()\n }\n\n func stop() {\n defaultPathHandler = nil\n onStop?()\n }\n\n /// Simulate network path update.\n func updatePath(_ newPath: Network.NWPath.Status) {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\DefaultPathObserverFake.swift
DefaultPathObserverFake.swift
Swift
984
0.95
0.029412
0.321429
python-kit
84
2025-06-02T21:24:05.527214
BSD-3-Clause
true
ad8a7a0ad65b4f935ddd5015c074f741
//\n// EphemeralPeerExchangeActorStub.swift\n// MullvadPostQuantumTests\n//\n// Created by Mojgan on 2024-07-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@testable import MullvadRustRuntime\n@testable import MullvadTypes\nimport NetworkExtension\n@testable import PacketTunnelCore\n@testable import WireGuardKitTypes\n\nfinal class EphemeralPeerExchangeActorStub: EphemeralPeerExchangeActorProtocol {\n typealias KeyNegotiationResult = Result<(PreSharedKey, PrivateKey), EphemeralPeerExchangeErrorStub>\n var result: KeyNegotiationResult = .failure(.unknown)\n\n var delegate: EphemeralPeerReceiving?\n\n func startNegotiation(with privateKey: PrivateKey, enablePostQuantum: Bool, enableDaita: Bool) {\n let daita = enableDaita\n ? DaitaV2Parameters(\n machines: "test",\n maximumEvents: 1,\n maximumActions: 1,\n maximumPadding: 1.0,\n maximumBlocking: 1.0\n )\n : nil\n switch result {\n case let .success((preSharedKey, ephemeralKey)):\n if enablePostQuantum {\n Task { await delegate?.receivePostQuantumKey(\n preSharedKey,\n ephemeralKey: ephemeralKey,\n daitaParameters: daita\n ) }\n } else {\n Task { await delegate?.receiveEphemeralPeerPrivateKey(ephemeralKey, daitaParameters: daita) }\n }\n case .failure:\n delegate?.ephemeralPeerExchangeFailed()\n }\n }\n\n func endCurrentNegotiation() {}\n\n func reset() {}\n}\n\nenum EphemeralPeerExchangeErrorStub: Error {\n case unknown\n case canceled\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\EphemeralPeerExchangeActorStub.swift
EphemeralPeerExchangeActorStub.swift
Swift
1,699
0.95
0.054545
0.145833
awesome-app
36
2025-03-06T00:56:40.804740
BSD-3-Clause
true
af3a55c58f8435e66cb9fbbbf589a440
//\n// KeyExchangingResultStub.swift\n// MullvadPostQuantumTests\n//\n// Created by Mojgan on 2024-07-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@testable import MullvadRustRuntime\n@testable import MullvadTypes\n@testable import WireGuardKitTypes\n\nstruct KeyExchangingResultStub: EphemeralPeerReceiving {\n var onFailure: (() -> Void)?\n var onReceivePostQuantumKey: ((PreSharedKey, PrivateKey, DaitaV2Parameters?) async -> Void)?\n var onReceiveEphemeralPeerPrivateKey: ((PrivateKey, DaitaV2Parameters?) async -> Void)?\n\n func receivePostQuantumKey(\n _ key: PreSharedKey,\n ephemeralKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) async {\n await onReceivePostQuantumKey?(key, ephemeralKey, daitaParameters)\n }\n\n public func receiveEphemeralPeerPrivateKey(\n _ ephemeralPeerPrivateKey: PrivateKey,\n daitaParameters daitaParamters: MullvadTypes.DaitaV2Parameters?\n ) async {\n await onReceiveEphemeralPeerPrivateKey?(ephemeralPeerPrivateKey, daitaParamters)\n }\n\n func ephemeralPeerExchangeFailed() {\n onFailure?()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\KeyExchangingResultStub.swift
KeyExchangingResultStub.swift
Swift
1,132
0.95
0
0.225806
react-lib
841
2023-08-06T05:50:24.185380
BSD-3-Clause
true
132404ac609f77a2325c36d3754f27c9
//\n// NetworkCounters.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 16/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A type capable of receiving and updating network counters.\nprotocol NetworkStatsReporting {\n /// Increment number of bytes sent.\n func reportBytesSent(_ byteCount: UInt64)\n\n /// Increment number of bytes received.\n func reportBytesReceived(_ byteCount: UInt64)\n}\n\n/// A type providing network statistics.\nprotocol NetworkStatsProviding {\n /// Returns number of bytes sent.\n var bytesSent: UInt64 { get }\n\n /// Returns number of bytes received.\n var bytesReceived: UInt64 { get }\n}\n\n/// Class that holds network statistics (bytes sent and received) for a simulated network adapter.\nfinal class NetworkCounters: NetworkStatsProviding, NetworkStatsReporting {\n private let stateLock = NSLock()\n private var _bytesSent: UInt64 = 0\n private var _bytesReceived: UInt64 = 0\n\n var bytesSent: UInt64 {\n stateLock.withLock { _bytesSent }\n }\n\n var bytesReceived: UInt64 {\n stateLock.withLock { _bytesReceived }\n }\n\n func reportBytesSent(_ byteCount: UInt64) {\n stateLock.withLock {\n _bytesSent += byteCount\n }\n }\n\n func reportBytesReceived(_ byteCount: UInt64) {\n stateLock.withLock {\n _bytesReceived += byteCount\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\NetworkCounters.swift
NetworkCounters.swift
Swift
1,416
0.95
0.037037
0.318182
awesome-app
289
2024-07-17T23:47:53.700073
BSD-3-Clause
true
f19516e8911bd5d7468e1da5c002e353