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// RelaySelector+Wireguard.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-05-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\nextension RelaySelector {\n public enum WireGuard {\n /// Filters relay list using given constraints.\n public static func findCandidates(\n by relayConstraint: RelayConstraint<UserSelectedRelays>,\n in relays: REST.ServerRelaysResponse,\n filterConstraint: RelayConstraint<RelayFilter>,\n daitaEnabled: Bool\n ) throws -> [RelayWithLocation<REST.ServerRelay>] {\n let mappedRelays = RelayWithLocation.locateRelays(\n relays: relays.wireguard.relays,\n locations: relays.locations\n )\n\n return try applyConstraints(\n relayConstraint,\n filterConstraint: filterConstraint,\n daitaEnabled: daitaEnabled,\n relays: mappedRelays\n )\n }\n\n /// Picks a random relay from a list.\n public static func pickCandidate(\n from relayWithLocations: [RelayWithLocation<REST.ServerRelay>],\n wireguard: REST.ServerWireguardTunnels,\n portConstraint: RelayConstraint<UInt16>,\n numberOfFailedAttempts: UInt,\n closeTo referenceLocation: Location? = nil\n ) throws -> RelaySelectorMatch {\n let port = try evaluatePort(\n portConstraint: portConstraint,\n rawPortRanges: wireguard.portRanges,\n numberOfFailedAttempts: numberOfFailedAttempts\n )\n\n var relayWithLocation: RelayWithLocation<REST.ServerRelay>?\n if let referenceLocation {\n let relay = closestRelay(to: referenceLocation, using: relayWithLocations)\n relayWithLocation = relayWithLocations.first(where: { $0.relay == relay })\n }\n\n guard\n let relayWithLocation = relayWithLocation ?? pickRandomRelayByWeight(relays: relayWithLocations)\n else {\n throw NoRelaysSatisfyingConstraintsError(.relayConstraintNotMatching)\n }\n\n return createMatch(for: relayWithLocation, port: port, wireguard: wireguard)\n }\n\n public static func closestRelay(\n to location: Location,\n using relayWithLocations: [RelayWithLocation<REST.ServerRelay>]\n ) -> REST.ServerRelay? {\n let relaysWithDistance = relayWithLocations.map {\n RelayWithDistance(\n relay: $0.relay,\n distance: Haversine.distance(\n location.latitude,\n location.longitude,\n $0.serverLocation.latitude,\n $0.serverLocation.longitude\n )\n )\n }.sorted {\n $0.distance < $1.distance\n }.prefix(5)\n\n let relaysGroupedByDistance = Dictionary(grouping: relaysWithDistance, by: { $0.distance })\n guard let closetsRelayGroup = relaysGroupedByDistance.min(by: { $0.key < $1.key })?.value else {\n return nil\n }\n\n var greatestDistance = 0.0\n closetsRelayGroup.forEach {\n if $0.distance > greatestDistance {\n greatestDistance = $0.distance\n }\n }\n\n let closestRelay = rouletteSelection(relays: closetsRelayGroup, weightFunction: { relay in\n UInt64(1 + greatestDistance - relay.distance)\n })\n\n return closestRelay?.relay\n }\n }\n\n private static func evaluatePort(\n portConstraint: RelayConstraint<UInt16>,\n rawPortRanges: [[UInt16]],\n numberOfFailedAttempts: UInt\n ) throws -> UInt16 {\n let port = applyPortConstraint(\n portConstraint,\n rawPortRanges: rawPortRanges,\n numberOfFailedAttempts: numberOfFailedAttempts\n )\n\n guard let port else {\n throw NoRelaysSatisfyingConstraintsError(.invalidPort)\n }\n\n return port\n }\n\n private static func createMatch(\n for relayWithLocation: RelayWithLocation<REST.ServerRelay>,\n port: UInt16,\n wireguard: REST.ServerWireguardTunnels\n ) -> RelaySelectorMatch {\n let endpoint = MullvadEndpoint(\n ipv4Relay: IPv4Endpoint(\n ip: relayWithLocation.relay.ipv4AddrIn,\n port: port\n ),\n ipv6Relay: nil,\n ipv4Gateway: wireguard.ipv4Gateway,\n ipv6Gateway: wireguard.ipv6Gateway,\n publicKey: relayWithLocation.relay.publicKey\n )\n\n return RelaySelectorMatch(\n endpoint: endpoint,\n relay: relayWithLocation.relay,\n location: relayWithLocation.serverLocation\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelaySelector+Wireguard.swift
RelaySelector+Wireguard.swift
Swift
4,963
0.95
0.042553
0.072581
vue-tools
93
2024-04-15T12:25:08.576829
Apache-2.0
false
0dabb1c815c0c666907d7feff072453c
//\n// RelaySelector.swift\n// RelaySelector\n//\n// Created by pronebird on 11/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\nprivate let defaultPort: UInt16 = 443\n\npublic enum RelaySelector {\n // MARK: - public\n\n /// Determines whether a `REST.ServerRelay` satisfies the given relay filter.\n public static func relayMatchesFilter(_ relay: AnyRelay, filter: RelayFilter) -> Bool {\n if case let .only(providers) = filter.providers, providers.contains(relay.provider) == false {\n return false\n }\n\n switch filter.ownership {\n case .any:\n return true\n case .owned:\n return relay.owned\n case .rented:\n return !relay.owned\n }\n }\n\n static func pickRandomRelayByWeight<T: AnyRelay>(relays: [RelayWithLocation<T>])\n -> RelayWithLocation<T>? {\n rouletteSelection(relays: relays, weightFunction: { relayWithLocation in relayWithLocation.relay.weight })\n }\n\n static func rouletteSelection<T>(relays: [T], weightFunction: (T) -> UInt64) -> T? {\n let totalWeight = relays.map { weightFunction($0) }.reduce(0) { accumulated, weight in\n accumulated + weight\n }\n // Return random relay when all relays within the list have zero weight.\n guard totalWeight > 0 else {\n return relays.randomElement()\n }\n\n // Pick a random number in the range 1 - totalWeight. This chooses the relay with a\n // non-zero weight.\n var i = (1 ... totalWeight).randomElement()!\n\n let randomRelay = relays.first { relay -> Bool in\n let (result, isOverflow) = i\n .subtractingReportingOverflow(weightFunction(relay))\n\n i = isOverflow ? 0 : result\n\n return i == 0\n }\n\n assert(randomRelay != nil, "At least one relay must've had a weight above 0")\n\n return randomRelay\n }\n\n /// Produce a list of `RelayWithLocation` items satisfying the given constraints\n static func applyConstraints<T: AnyRelay>(\n _ relayConstraint: RelayConstraint<UserSelectedRelays>,\n filterConstraint: RelayConstraint<RelayFilter>,\n daitaEnabled: Bool,\n relays: [RelayWithLocation<T>]\n ) throws -> [RelayWithLocation<T>] {\n // Filter on active status, daita support, filter constraint and relay constraint.\n var filteredRelays = try filterByActive(relays: relays)\n filteredRelays = try filterByFilterConstraint(relays: filteredRelays, constraint: filterConstraint)\n filteredRelays = try filterByLocationConstraint(relays: filteredRelays, constraint: relayConstraint)\n filteredRelays = try filterByDaita(relays: filteredRelays, daitaEnabled: daitaEnabled)\n return filterByCountryInclusion(relays: filteredRelays, constraint: relayConstraint)\n }\n\n /// Produce a port that is either user provided or randomly selected, satisfying the given constraints.\n static func applyPortConstraint(\n _ portConstraint: RelayConstraint<UInt16>,\n rawPortRanges: [[UInt16]],\n numberOfFailedAttempts: UInt\n ) -> UInt16? {\n switch portConstraint {\n case let .only(port):\n return port\n\n case .any:\n // 1. First attempt should pick a random port.\n // 2. The second should pick port 443.\n // 3. Repeat steps 1 and 2.\n let useDefaultPort = numberOfFailedAttempts.isOrdered(nth: 2, forEverySetOf: 2)\n\n return useDefaultPort ? defaultPort : pickRandomPort(rawPortRanges: rawPortRanges)\n }\n }\n\n // MARK: - private\n\n static func parseRawPortRanges(_ rawPortRanges: [[UInt16]]) -> [ClosedRange<UInt16>] {\n rawPortRanges.compactMap { inputRange -> ClosedRange<UInt16>? in\n guard inputRange.count == 2 else { return nil }\n\n let startPort = inputRange[0]\n let endPort = inputRange[1]\n\n if startPort <= endPort {\n return startPort ... endPort\n } else {\n return nil\n }\n }\n }\n\n static func pickRandomPort(rawPortRanges: [[UInt16]]) -> UInt16? {\n let portRanges = parseRawPortRanges(rawPortRanges)\n let portAmount = portRanges.reduce(0) { partialResult, closedRange in\n partialResult + closedRange.count\n }\n\n guard var portIndex = (0 ..< portAmount).randomElement() else {\n return nil\n }\n\n for range in portRanges {\n if portIndex < range.count {\n return UInt16(portIndex) + range.lowerBound\n } else {\n portIndex -= range.count\n }\n }\n\n assertionFailure("Port selection algorithm is broken!")\n\n return nil\n }\n\n private static func makeRelayWithLocationFrom<T: AnyRelay>(\n _ serverLocation: REST.ServerLocation,\n relay: T\n ) -> RelayWithLocation<T>? {\n let location = Location(\n country: serverLocation.country,\n countryCode: String(relay.location.country),\n city: serverLocation.city,\n cityCode: String(relay.location.city),\n latitude: serverLocation.latitude,\n longitude: serverLocation.longitude\n )\n\n return RelayWithLocation(relay: relay, serverLocation: location)\n }\n\n private static func filterByActive<T: AnyRelay>(\n relays: [RelayWithLocation<T>]\n ) throws -> [RelayWithLocation<T>] {\n let filteredRelays = relays.filter { relayWithLocation in\n relayWithLocation.relay.active\n }\n\n return if filteredRelays.isEmpty {\n throw NoRelaysSatisfyingConstraintsError(.noActiveRelaysFound)\n } else {\n filteredRelays\n }\n }\n\n private static func filterByDaita<T: AnyRelay>(\n relays: [RelayWithLocation<T>],\n daitaEnabled: Bool\n ) throws -> [RelayWithLocation<T>] {\n guard daitaEnabled else { return relays }\n\n let filteredRelays = relays.filter { relayWithLocation in\n relayWithLocation.relay.daita == true\n }\n\n return if filteredRelays.isEmpty {\n throw NoRelaysSatisfyingConstraintsError(.noDaitaRelaysFound)\n } else {\n filteredRelays\n }\n }\n\n private static func filterByFilterConstraint<T: AnyRelay>(\n relays: [RelayWithLocation<T>],\n constraint: RelayConstraint<RelayFilter>\n ) throws -> [RelayWithLocation<T>] {\n let filteredRelays = relays.filter { relayWithLocation in\n switch constraint {\n case .any:\n true\n case let .only(filter):\n relayMatchesFilter(relayWithLocation.relay, filter: filter)\n }\n }\n\n return if filteredRelays.isEmpty {\n throw NoRelaysSatisfyingConstraintsError(.filterConstraintNotMatching)\n } else {\n filteredRelays\n }\n }\n\n private static func filterByLocationConstraint<T: AnyRelay>(\n relays: [RelayWithLocation<T>],\n constraint: RelayConstraint<UserSelectedRelays>\n ) throws -> [RelayWithLocation<T>] {\n let filteredRelays = relays.filter { relayWithLocation in\n switch constraint {\n case .any:\n true\n case let .only(constraint):\n // At least one location must match the relay under test.\n constraint.locations.contains { location in\n relayWithLocation.matches(location: location)\n }\n }\n }\n\n return if filteredRelays.isEmpty {\n throw NoRelaysSatisfyingConstraintsError(.relayConstraintNotMatching)\n } else {\n filteredRelays\n }\n }\n\n private static func filterByCountryInclusion<T: AnyRelay>(\n relays: [RelayWithLocation<T>],\n constraint: RelayConstraint<UserSelectedRelays>\n ) -> [RelayWithLocation<T>] {\n let filteredRelays = relays.filter { relayWithLocation in\n return switch constraint {\n case .any:\n true\n case let .only(relayConstraint):\n relayConstraint.locations.contains { location in\n if case .country = location {\n relayWithLocation.relay.includeInCountry\n } else {\n false\n }\n }\n }\n }\n\n // If no relays are included in the matched country, instead accept all.\n return if filteredRelays.isEmpty {\n relays\n } else {\n filteredRelays\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelaySelector.swift
RelaySelector.swift
Swift
8,721
0.95
0.074219
0.096774
python-kit
430
2023-10-08T05:53:08.091425
Apache-2.0
false
c3f56c15e1df585ca3805fefa57ba113
//\n// RelaySelectorProtocol.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 MullvadSettings\nimport MullvadTypes\n\n/// Protocol describing a type that can select a relay.\npublic protocol RelaySelectorProtocol {\n var relayCache: RelayCacheProtocol { get }\n func selectRelays(\n tunnelSettings: LatestTunnelSettings,\n connectionAttemptCount: UInt\n ) throws -> SelectedRelays\n\n func findCandidates(\n tunnelSettings: LatestTunnelSettings\n ) throws -> RelayCandidates\n}\n\n/// Struct describing the selected relay.\npublic struct SelectedRelay: Equatable, Codable, Sendable {\n /// Selected relay endpoint.\n public let endpoint: MullvadEndpoint\n\n /// Relay hostname.\n public let hostname: String\n\n /// Relay geo location.\n public let location: Location\n\n /// Designated initializer.\n public init(endpoint: MullvadEndpoint, hostname: String, location: Location) {\n self.endpoint = endpoint\n self.hostname = hostname\n self.location = location\n }\n}\n\nextension SelectedRelay: CustomDebugStringConvertible {\n public var debugDescription: String {\n "\(hostname) -> \(endpoint.ipv4Relay.description)"\n }\n}\n\npublic struct SelectedRelays: Equatable, Codable, Sendable {\n public let entry: SelectedRelay?\n public let exit: SelectedRelay\n public let retryAttempt: UInt\n\n public init(entry: SelectedRelay?, exit: SelectedRelay, retryAttempt: UInt) {\n self.entry = entry\n self.exit = exit\n self.retryAttempt = retryAttempt\n }\n}\n\nextension SelectedRelays: CustomDebugStringConvertible {\n public var debugDescription: String {\n "Entry: \(entry?.hostname ?? "-") -> \(entry?.endpoint.ipv4Relay.description ?? "-"), " +\n "Exit: \(exit.hostname) -> \(exit.endpoint.ipv4Relay.description)"\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelaySelectorProtocol.swift
RelaySelectorProtocol.swift
Swift
1,928
0.95
0
0.22807
react-lib
989
2024-06-27T14:16:05.074845
MIT
false
b5ac3c9b10fe1495c7df0784153e7b3f
//\n// RelaySelectorResult.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-05-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic typealias RelaySelectorResult = RelaySelectorMatch\n\npublic struct RelaySelectorMatch: Codable, Equatable {\n public var endpoint: MullvadEndpoint\n public var relay: REST.ServerRelay\n public var location: Location\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelaySelectorResult.swift
RelaySelectorResult.swift
Swift
421
0.95
0
0.466667
python-kit
189
2023-07-22T03:18:18.089039
GPL-3.0
false
5e6d00e22f43fe5a651d1b2e53bd7351
//\n// RelaySelectorWrapper.swift\n// PacketTunnel\n//\n// Created by pronebird on 08/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\npublic final class RelaySelectorWrapper: RelaySelectorProtocol, Sendable {\n public let relayCache: RelayCacheProtocol\n\n public init(relayCache: RelayCacheProtocol) {\n self.relayCache = relayCache\n }\n\n public func selectRelays(\n tunnelSettings: LatestTunnelSettings,\n connectionAttemptCount: UInt\n ) throws -> SelectedRelays {\n let obfuscation = try prepareObfuscation(for: tunnelSettings, connectionAttemptCount: connectionAttemptCount)\n\n return switch tunnelSettings.tunnelMultihopState {\n case .off:\n try SinglehopPicker(\n obfuscation: obfuscation,\n constraints: tunnelSettings.relayConstraints,\n connectionAttemptCount: connectionAttemptCount,\n daitaSettings: tunnelSettings.daita\n ).pick()\n case .on:\n try MultihopPicker(\n obfuscation: obfuscation,\n constraints: tunnelSettings.relayConstraints,\n connectionAttemptCount: connectionAttemptCount,\n daitaSettings: tunnelSettings.daita\n ).pick()\n }\n }\n\n public func findCandidates(tunnelSettings: LatestTunnelSettings) throws -> RelayCandidates {\n let obfuscation = try prepareObfuscation(for: tunnelSettings, connectionAttemptCount: 0)\n\n let findCandidates: (REST.ServerRelaysResponse, Bool) throws\n -> [RelayWithLocation<REST.ServerRelay>] = { relays, daitaEnabled in\n try RelaySelector.WireGuard.findCandidates(\n by: .any,\n in: relays,\n filterConstraint: tunnelSettings.relayConstraints.filter,\n daitaEnabled: daitaEnabled\n )\n }\n\n if tunnelSettings.daita.isAutomaticRouting || tunnelSettings.tunnelMultihopState.isEnabled {\n let entryCandidates = try findCandidates(\n tunnelSettings.tunnelMultihopState.isEnabled ? obfuscation.entryRelays : obfuscation.exitRelays,\n tunnelSettings.daita.daitaState.isEnabled\n )\n let exitCandidates = try findCandidates(obfuscation.exitRelays, false)\n return RelayCandidates(entryRelays: entryCandidates, exitRelays: exitCandidates)\n } else {\n let exitCandidates = try findCandidates(obfuscation.exitRelays, tunnelSettings.daita.daitaState.isEnabled)\n return RelayCandidates(entryRelays: nil, exitRelays: exitCandidates)\n }\n }\n\n private func prepareObfuscation(\n for tunnelSettings: LatestTunnelSettings,\n connectionAttemptCount: UInt\n ) throws -> ObfuscatorPortSelection {\n let relays = try relayCache.read().relays\n return try ObfuscatorPortSelector(relays: relays).obfuscate(\n tunnelSettings: tunnelSettings,\n connectionAttemptCount: connectionAttemptCount\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelaySelectorWrapper.swift
RelaySelectorWrapper.swift
Swift
3,123
0.95
0.202532
0.1
python-kit
958
2023-09-24T03:07:52.543200
GPL-3.0
false
ad7c5f0e98df44bc115525c490de92c5
//\n// RelayWithDistance.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-05-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nstruct RelayWithDistance<T: AnyRelay> {\n let relay: T\n let distance: Double\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelayWithDistance.swift
RelayWithDistance.swift
Swift
252
0.95
0
0.583333
vue-tools
125
2023-10-08T04:42:24.189119
BSD-3-Clause
false
f9bf1dda2298d8d439938e5c10d78d4b
//\n// RelayWithLocation.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-05-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct RelayWithLocation<T: AnyRelay & Sendable>: Sendable {\n public let relay: T\n public let serverLocation: Location\n\n public func matches(location: RelayLocation) -> Bool {\n return switch location {\n case let .country(countryCode):\n serverLocation.countryCode == countryCode\n\n case let .city(countryCode, cityCode):\n serverLocation.countryCode == countryCode &&\n serverLocation.cityCode == cityCode\n\n case let .hostname(countryCode, cityCode, hostname):\n serverLocation.countryCode == countryCode &&\n serverLocation.cityCode == cityCode &&\n relay.hostname == hostname\n }\n }\n\n init(relay: T, serverLocation: Location) {\n self.relay = relay\n self.serverLocation = serverLocation\n }\n\n init?(_ relay: T, locations: [String: REST.ServerLocation]) {\n guard\n let serverLocation = locations[relay.location.rawValue]\n else { return nil }\n\n self.relay = relay\n self.serverLocation = Location(\n country: serverLocation.country,\n countryCode: String(relay.location.country),\n city: serverLocation.city,\n cityCode: String(relay.location.city),\n latitude: serverLocation.latitude,\n longitude: serverLocation.longitude\n )\n }\n\n /// given a list of `AnyRelay` values and a name to location mapping, produce a list of\n /// `RelayWithLocation`values for those whose locations have successfully been found.\n public static func locateRelays(\n relays: [T],\n locations: [String: REST.ServerLocation]\n ) -> [RelayWithLocation<T>] {\n relays.compactMap { RelayWithLocation($0, locations: locations) }\n }\n}\n\nextension RelayWithLocation: Hashable {\n public static func == (lhs: RelayWithLocation<T>, rhs: RelayWithLocation<T>) -> Bool {\n lhs.relay.hostname == rhs.relay.hostname\n }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(relay.hostname)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelayWithLocation.swift
RelayWithLocation.swift
Swift
2,264
0.95
0.028169
0.15
vue-tools
785
2025-01-12T16:43:05.089061
BSD-3-Clause
false
c6180ee8949009766fa40fa1bde6217f
//\n// StoredRelays.swift\n// MullvadVPNUITests\n//\n// Created by Jon Petersson on 2024-09-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A struct that represents the relay cache on disk\npublic struct StoredRelays: Codable, Equatable {\n /// E-tag returned by server\n public let etag: String?\n\n /// The raw relay JSON data stored within the cache entry\n public let rawData: Data\n\n /// The date when this cache was last updated\n public let updatedAt: Date\n\n /// Relays parsed from the JSON data\n public let relays: REST.ServerRelaysResponse\n\n /// `CachedRelays` representation\n public var cachedRelays: CachedRelays {\n CachedRelays(etag: etag, relays: relays, updatedAt: updatedAt)\n }\n\n public init(etag: String? = nil, rawData: Data, updatedAt: Date) throws {\n self.etag = etag\n self.rawData = rawData\n self.updatedAt = updatedAt\n relays = try REST.Coding.makeJSONDecoder().decode(REST.ServerRelaysResponse.self, from: rawData)\n }\n\n public init(cachedRelays: CachedRelays) throws {\n etag = cachedRelays.etag\n rawData = try REST.Coding.makeJSONEncoder().encode(cachedRelays.relays)\n updatedAt = cachedRelays.updatedAt\n relays = cachedRelays.relays\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\StoredRelays.swift
StoredRelays.swift
Swift
1,302
0.95
0.046512
0.371429
react-lib
868
2023-10-22T04:27:04.582572
MIT
false
418ae3e012a26af5d72ab9837081503e
//\n// MultihopPicker.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\nstruct MultihopPicker: RelayPicking {\n let obfuscation: ObfuscatorPortSelection\n let constraints: RelayConstraints\n let connectionAttemptCount: UInt\n let daitaSettings: DAITASettings\n\n func pick() throws -> SelectedRelays {\n let exitCandidates = try RelaySelector.WireGuard.findCandidates(\n by: constraints.exitLocations,\n in: obfuscation.exitRelays,\n filterConstraint: constraints.filter,\n daitaEnabled: false\n )\n\n /*\n Relay selection is prioritised in the following order:\n 1. Both entry and exit constraints match only a single relay. Both relays are selected.\n 2. Entry constraint matches only a single relay and the other multiple relays. The single relay\n is selected and excluded from the list of multiple relays.\n 3. Exit constraint matches multiple relays and the other a single relay. The single relay\n is selected and excluded from the list of multiple relays.\n 4. Both entry and exit constraints match multiple relays. Exit relay is picked first and then\n excluded from the list of entry relays.\n */\n let decisionFlow = OneToOne(\n next: OneToMany(\n next: ManyToOne(\n next: ManyToMany(\n next: nil,\n relayPicker: self\n ),\n relayPicker: self\n ),\n relayPicker: self\n ),\n relayPicker: self\n )\n\n do {\n let entryCandidates = try RelaySelector.WireGuard.findCandidates(\n by: daitaSettings.isAutomaticRouting ? .any : constraints.entryLocations,\n in: obfuscation.entryRelays,\n filterConstraint: constraints.filter,\n daitaEnabled: daitaSettings.daitaState.isEnabled\n )\n\n return try decisionFlow.pick(\n entryCandidates: entryCandidates,\n exitCandidates: exitCandidates,\n daitaAutomaticRouting: daitaSettings.isAutomaticRouting\n )\n }\n }\n\n func exclude(\n relay: SelectedRelay,\n from candidates: [RelayWithLocation<REST.ServerRelay>],\n closeTo location: Location? = nil,\n useObfuscatedPortIfAvailable: Bool\n ) throws -> SelectedRelay {\n let filteredCandidates = candidates.filter { relayWithLocation in\n relayWithLocation.relay.hostname != relay.hostname\n }\n\n return try findBestMatch(\n from: filteredCandidates,\n closeTo: location,\n useObfuscatedPortIfAvailable: useObfuscatedPortIfAvailable\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelayPicking\MultihopPicker.swift
MultihopPicker.swift
Swift
2,927
0.95
0.04878
0.121622
python-kit
764
2024-05-30T08:21:27.056994
MIT
false
268992756935c9695bf6398d661899de
//\n// RelaySelectorPicker.swift\n// MullvadREST\n//\n// Created by Jon Petersson on 2024-06-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\nimport Network\n\nprotocol RelayPicking {\n var obfuscation: ObfuscatorPortSelection { get }\n var constraints: RelayConstraints { get }\n var connectionAttemptCount: UInt { get }\n var daitaSettings: DAITASettings { get }\n func pick() throws -> SelectedRelays\n}\n\nextension RelayPicking {\n func findBestMatch(\n from candidates: [RelayWithLocation<REST.ServerRelay>],\n closeTo location: Location? = nil,\n useObfuscatedPortIfAvailable: Bool\n ) throws -> SelectedRelay {\n var match = try RelaySelector.WireGuard.pickCandidate(\n from: candidates,\n wireguard: obfuscation.wireguard,\n portConstraint: useObfuscatedPortIfAvailable ? obfuscation.port : constraints.port,\n numberOfFailedAttempts: connectionAttemptCount,\n closeTo: location\n )\n\n if useObfuscatedPortIfAvailable && obfuscation.method == .shadowsocks {\n match = applyShadowsocksIpAddress(in: match)\n }\n\n return SelectedRelay(\n endpoint: match.endpoint,\n hostname: match.relay.hostname,\n location: match.location\n )\n }\n\n private func applyShadowsocksIpAddress(in match: RelaySelectorMatch) -> RelaySelectorMatch {\n let port = match.endpoint.ipv4Relay.port\n let portRanges = RelaySelector.parseRawPortRanges(obfuscation.wireguard.shadowsocksPortRanges)\n let portIsWithinRange = portRanges.contains(where: { $0.contains(port) })\n\n var endpoint = match.endpoint\n\n // If the currently selected obfuscation port is not within the allowed range (as specified\n // in the relay list), we should use one of the extra Shadowsocks IP addresses instead of\n // the default one.\n if !portIsWithinRange {\n var ipv4Address = match.endpoint.ipv4Relay.ip\n if let shadowsocksAddress = match.relay.shadowsocksExtraAddrIn?.randomElement() {\n ipv4Address = IPv4Address(shadowsocksAddress) ?? ipv4Address\n }\n\n endpoint = match.endpoint.override(ipv4Relay: IPv4Endpoint(\n ip: ipv4Address,\n port: port\n ))\n }\n\n return RelaySelectorMatch(endpoint: endpoint, relay: match.relay, location: match.location)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelayPicking\RelayPicking.swift
RelayPicking.swift
Swift
2,495
0.95
0.057143
0.166667
python-kit
854
2025-04-08T06:54:44.914076
GPL-3.0
false
0afe4b6ef99ae55712f0b094750543dd
//\n// SinglehopPicker.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\nstruct SinglehopPicker: RelayPicking {\n let obfuscation: ObfuscatorPortSelection\n let constraints: RelayConstraints\n let connectionAttemptCount: UInt\n let daitaSettings: DAITASettings\n\n func pick() throws -> SelectedRelays {\n do {\n return try pick(from: obfuscation.exitRelays)\n } catch let error as NoRelaysSatisfyingConstraintsError where error.reason == .noDaitaRelaysFound {\n // If DAITA is on, Direct only is off and obfuscation is on, and no supported relays are found, we should see if\n // the obfuscated subset of exit relays is the cause of this. We can do this by checking if relay selection would\n // have been successful with all relays available. If that's the case, throw error and point to obfuscation.\n do {\n _ = try pick(from: obfuscation.unfilteredRelays)\n throw NoRelaysSatisfyingConstraintsError(.noObfuscatedRelaysFound)\n } catch let error as NoRelaysSatisfyingConstraintsError where error.reason == .noDaitaRelaysFound {\n // If DAITA is on, Direct only is off and obfuscation has been ruled out, and no supported relays are found,\n // we should try to find the nearest available relay that supports DAITA and use it as entry in a multihop selection.\n if daitaSettings.isAutomaticRouting {\n return try MultihopPicker(\n obfuscation: obfuscation,\n constraints: constraints,\n connectionAttemptCount: connectionAttemptCount,\n daitaSettings: daitaSettings\n ).pick()\n } else {\n throw error\n }\n }\n }\n }\n\n private func pick(from exitRelays: REST.ServerRelaysResponse) throws -> SelectedRelays {\n let exitCandidates = try RelaySelector.WireGuard.findCandidates(\n by: constraints.exitLocations,\n in: exitRelays,\n filterConstraint: constraints.filter,\n daitaEnabled: daitaSettings.daitaState.isEnabled\n )\n\n let match = try findBestMatch(from: exitCandidates, useObfuscatedPortIfAvailable: true)\n return SelectedRelays(entry: nil, exit: match, retryAttempt: connectionAttemptCount)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Relay\RelayPicking\SinglehopPicker.swift
SinglehopPicker.swift
Swift
2,542
0.95
0.196429
0.235294
awesome-app
913
2025-01-24T11:40:10.149721
Apache-2.0
false
b4c98c36e37b75051ce9baeb623fe480
//\n// ExponentialBackoff.swift\n// MullvadREST\n//\n// Created by pronebird on 03/11/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nstruct ExponentialBackoff: IteratorProtocol {\n private var _next: Duration\n private let multiplier: UInt64\n private let maxDelay: Duration\n\n init(initial: Duration, multiplier: UInt64, maxDelay: Duration) {\n _next = initial\n self.multiplier = multiplier\n self.maxDelay = maxDelay\n }\n\n mutating func next() -> Duration? {\n let next = _next\n\n if next > maxDelay {\n return maxDelay\n }\n\n _next = next * Int(multiplier)\n\n return next\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\RetryStrategy\ExponentialBackoff.swift
ExponentialBackoff.swift
Swift
715
0.95
0.029412
0.259259
vue-tools
742
2023-08-29T07:42:05.962396
Apache-2.0
false
7288f1de1becc1d1075f77a622dfe18b
//\n// Jittered.swift\n// MullvadREST\n//\n// Created by Mojgan on 2023-12-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nstruct Jittered<InnerIterator: IteratorProtocol>: IteratorProtocol\n where InnerIterator.Element == Duration {\n private var inner: InnerIterator\n\n init(_ inner: InnerIterator) {\n self.inner = inner\n }\n\n mutating func next() -> Duration? {\n guard let interval = inner.next() else { return nil }\n\n let jitter = Double.random(in: 0.0 ... 1.0)\n let millis = interval.milliseconds\n let millisWithJitter = millis.saturatingAddition(Int(Double(millis) * jitter))\n\n return .milliseconds(millisWithJitter)\n }\n}\n\n/// Iterator that applies a transform function to the result of another iterator.\nstruct Transformer<Inner: IteratorProtocol>: IteratorProtocol {\n typealias Element = Inner.Element\n private var inner: Inner\n private let transformer: (Inner.Element?) -> Inner.Element?\n\n init(inner: Inner, transform: @escaping @Sendable (Inner.Element?) -> Inner.Element?) {\n self.inner = inner\n self.transformer = transform\n }\n\n mutating func next() -> Inner.Element? {\n transformer(inner.next())\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\RetryStrategy\Jittered.swift
Jittered.swift
Swift
1,270
0.95
0.022222
0.222222
node-utils
194
2025-01-07T23:50:05.140577
GPL-3.0
false
0fabfd25d70bc396355a401a9847b299
//\n// RetryStrategy.swift\n// MullvadREST\n//\n// Created by pronebird on 09/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntime\nimport MullvadTypes\n\nextension REST {\n public struct RetryStrategy: Codable, Sendable {\n public var maxRetryCount: Int\n public var delay: RetryDelay\n public var applyJitter: Bool\n\n public init(maxRetryCount: Int, delay: RetryDelay, applyJitter: Bool) {\n self.maxRetryCount = maxRetryCount\n self.delay = delay\n self.applyJitter = applyJitter\n }\n\n /// The return value of this function *must* be passed to a Rust FFI function that will consume it, otherwise it will leak.\n public func toRustStrategy() -> SwiftRetryStrategy {\n switch delay {\n case .never:\n return mullvad_api_retry_strategy_never()\n case let .constant(duration):\n return mullvad_api_retry_strategy_constant(UInt(maxRetryCount), UInt64(duration.seconds))\n case let .exponentialBackoff(initial, multiplier, maxDelay):\n return mullvad_api_retry_strategy_exponential(\n UInt(maxRetryCount),\n UInt64(initial.seconds),\n UInt32(multiplier),\n UInt64(maxDelay.seconds)\n )\n }\n }\n\n public func makeDelayIterator() -> AnyIterator<Duration> {\n let inner = delay.makeIterator()\n\n if applyJitter {\n return switch delay {\n case .never:\n AnyIterator(inner)\n case .constant:\n AnyIterator(Jittered(inner))\n case let .exponentialBackoff(_, _, maxDelay):\n AnyIterator(Transformer(inner: Jittered(inner)) { nextValue in\n let maxDelay = maxDelay.duration\n\n guard let nextValue else { return maxDelay }\n return nextValue >= maxDelay ? maxDelay : nextValue\n })\n }\n } else {\n return AnyIterator(inner)\n }\n }\n\n /// Strategy configured to never retry.\n public static let noRetry = RetryStrategy(\n maxRetryCount: 0,\n delay: .never,\n applyJitter: false\n )\n\n /// Strategy configured with 2 retry attempts and exponential backoff.\n public static let `default` = RetryStrategy(\n maxRetryCount: 2,\n delay: defaultRetryDelay,\n applyJitter: true\n )\n\n /// Strategy configured with 10 retry attempts and exponential backoff.\n public static let aggressive = RetryStrategy(\n maxRetryCount: 10,\n delay: defaultRetryDelay,\n applyJitter: true\n )\n\n /// Default retry delay.\n public static let defaultRetryDelay: RetryDelay = .exponentialBackoff(\n initial: .seconds(2),\n multiplier: 2,\n maxDelay: .seconds(8)\n )\n\n public static let postQuantumKeyExchange = RetryStrategy(\n maxRetryCount: 10,\n delay: .exponentialBackoff(\n initial: .seconds(10),\n multiplier: UInt64(2),\n maxDelay: .seconds(30)\n ),\n applyJitter: true\n )\n\n public static let failedMigrationRecovery = RetryStrategy(\n maxRetryCount: .max,\n delay: .exponentialBackoff(\n initial: .seconds(5),\n multiplier: UInt64(1),\n maxDelay: .minutes(1)\n ),\n applyJitter: true\n )\n }\n\n public enum RetryDelay: Codable, Equatable, Sendable {\n /// Never wait to retry.\n case never\n\n /// Constant delay.\n case constant(CodableDuration)\n\n /// Exponential backoff.\n case exponentialBackoff(initial: CodableDuration, multiplier: UInt64, maxDelay: CodableDuration)\n\n func makeIterator() -> AnyIterator<Duration> {\n switch self {\n case .never:\n return AnyIterator {\n nil\n }\n\n case let .constant(duration):\n return AnyIterator {\n duration.duration\n }\n\n case let .exponentialBackoff(initial, multiplier, maxDelay):\n return AnyIterator(ExponentialBackoff(\n initial: initial.duration,\n multiplier: multiplier,\n maxDelay: maxDelay.duration\n ))\n }\n }\n }\n\n public struct CodableDuration: Codable, Equatable, Sendable {\n public var seconds: Int64\n public var attoseconds: Int64\n\n public var duration: Duration {\n Duration(secondsComponent: seconds, attosecondsComponent: attoseconds)\n }\n\n public static func seconds(_ seconds: Int) -> CodableDuration {\n return CodableDuration(seconds: Int64(seconds), attoseconds: 0)\n }\n\n public static func minutes(_ minutes: Int) -> CodableDuration {\n return .seconds(minutes.saturatingMultiplication(60))\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\RetryStrategy\RetryStrategy.swift
RetryStrategy.swift
Swift
5,290
0.95
0.037267
0.108696
vue-tools
97
2024-12-09T16:00:23.675700
GPL-3.0
false
cc0bc1f559d2784cca7f712cbe91fd6f
//\n// AccessMethodIterator.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\nimport MullvadSettings\n\nfinal class AccessMethodIterator: @unchecked Sendable {\n private let dataSource: AccessMethodRepositoryDataSource\n\n private var index = 0\n private var cancellables = Set<Combine.AnyCancellable>()\n\n private var enabledConfigurations: [PersistentAccessMethod] {\n dataSource.fetchAll().filter { $0.isEnabled }\n }\n\n private var lastReachableApiAccessId: UUID? {\n dataSource.fetchLastReachable().id\n }\n\n init(dataSource: AccessMethodRepositoryDataSource) {\n self.dataSource = dataSource\n\n self.dataSource\n .accessMethodsPublisher\n .sink { [weak self] _ in\n guard let self else { return }\n self.refreshCacheIfNeeded()\n }\n .store(in: &cancellables)\n }\n\n private func refreshCacheIfNeeded() {\n // Validating the index of `lastReachableApiAccessCache` after any changes in `AccessMethodRepository`\n if let firstIndex = enabledConfigurations.firstIndex(where: { $0.id == lastReachableApiAccessId }) {\n index = firstIndex\n }\n\n dataSource.saveLastReachable(pick())\n }\n\n func rotate() {\n let (partial, isOverflow) = index.addingReportingOverflow(1)\n index = isOverflow ? 0 : partial\n dataSource.saveLastReachable(pick())\n }\n\n func pick() -> PersistentAccessMethod {\n let configurations = enabledConfigurations\n if configurations.isEmpty {\n /// Returning `Default` strategy when all is disabled\n return dataSource.directAccess\n } else {\n /// Picking the next `Enabled` configuration in order they are added\n /// And starting from the beginning when it reaches end\n let circularIndex = index % configurations.count\n return configurations[circularIndex]\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\AccessMethodIterator.swift
AccessMethodIterator.swift
Swift
2,059
0.95
0.045455
0.2
awesome-app
651
2024-06-04T01:29:32.572671
MIT
false
893f35a90add3375fdea6fd7e370059c
//\n// APITransport.swift\n// MullvadVPNUITests\n//\n// Created by Jon Petersson on 2025-02-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadRustRuntime\nimport MullvadTypes\n\npublic protocol APITransportProtocol {\n var name: String { get }\n\n func sendRequest(_ request: APIRequest, completion: @escaping @Sendable (ProxyAPIResponse) -> Void)\n -> Cancellable\n}\n\npublic final class APITransport: APITransportProtocol {\n public var name: String {\n "app-transport"\n }\n\n public let requestFactory: MullvadApiRequestFactory\n\n public init(requestFactory: MullvadApiRequestFactory) {\n self.requestFactory = requestFactory\n }\n\n public func sendRequest(\n _ request: APIRequest,\n completion: @escaping @Sendable (ProxyAPIResponse) -> Void\n ) -> Cancellable {\n let apiRequest = requestFactory.makeRequest(request)\n\n return apiRequest { response in\n let error: APIError? = if !response.success {\n APIError(\n statusCode: Int(response.statusCode),\n errorDescription: response.errorDescription ?? "",\n serverResponseCode: response.serverResponseCode\n )\n } else { nil }\n\n completion(ProxyAPIResponse(\n data: response.body,\n error: error,\n etag: response.etag\n ))\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\APITransport.swift
APITransport.swift
Swift
1,446
0.95
0.038462
0.162791
awesome-app
449
2024-10-19T06:35:43.524751
GPL-3.0
false
dfe1b912b39c6835d9985445b605ad1c
//\n// APITransportProvider.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-02-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic protocol APITransportProviderProtocol {\n func makeTransport() -> APITransportProtocol?\n}\n\npublic final class APITransportProvider: APITransportProviderProtocol, Sendable {\n let requestFactory: MullvadApiRequestFactory\n\n public init(requestFactory: MullvadApiRequestFactory) {\n self.requestFactory = requestFactory\n }\n\n public func makeTransport() -> APITransportProtocol? {\n APITransport(requestFactory: requestFactory)\n }\n}\n\nextension REST {\n public struct AnyAPITransportProvider: APITransportProviderProtocol {\n private let block: () -> APITransportProtocol?\n\n public init(_ block: @escaping @Sendable () -> APITransportProtocol?) {\n self.block = block\n }\n\n public func makeTransport() -> APITransportProtocol? {\n block()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\APITransportProvider.swift
APITransportProvider.swift
Swift
994
0.95
0.027027
0.233333
node-utils
82
2024-04-04T06:27:52.500981
BSD-3-Clause
false
abf41937e635d6ba5b1ce7685ac7bef4
//\n// ProxyConfigurationTransportProvider.swift\n// MullvadREST\n//\n// Created by Marco Nikic on 2024-01-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\n/// Allows the creation of `RESTTransport` objects that bypass the network routing logic provided by `TransportProvider`.\npublic class ProxyConfigurationTransportProvider {\n private let shadowsocksLoader: ShadowsocksLoaderProtocol\n private let addressCache: REST.AddressCache\n private let encryptedDNSTransport: RESTTransport\n\n public init(\n shadowsocksLoader: ShadowsocksLoaderProtocol,\n addressCache: REST.AddressCache,\n encryptedDNSTransport: RESTTransport\n ) {\n self.shadowsocksLoader = shadowsocksLoader\n self.addressCache = addressCache\n self.encryptedDNSTransport = encryptedDNSTransport\n }\n\n public func makeTransport(with configuration: PersistentProxyConfiguration) throws -> RESTTransport {\n let urlSession = REST.makeURLSession(addressCache: addressCache)\n switch configuration {\n case .direct:\n return URLSessionTransport(urlSession: urlSession)\n case .bridges:\n let shadowsocksConfiguration = try shadowsocksLoader.load()\n return ShadowsocksTransport(\n urlSession: urlSession,\n configuration: shadowsocksConfiguration,\n addressCache: addressCache\n )\n case .encryptedDNS:\n return encryptedDNSTransport\n case let .shadowsocks(shadowSocksConfiguration):\n return ShadowsocksTransport(\n urlSession: urlSession,\n configuration: ShadowsocksConfiguration(\n address: shadowSocksConfiguration.server,\n port: shadowSocksConfiguration.port,\n password: shadowSocksConfiguration.password,\n cipher: shadowSocksConfiguration.cipher.rawValue.description\n ),\n addressCache: addressCache\n )\n case let .socks5(socksConfiguration):\n return URLSessionSocks5Transport(\n urlSession: urlSession,\n configuration: Socks5Configuration(\n proxyEndpoint: socksConfiguration.toAnyIPEndpoint,\n username: socksConfiguration.credential?.username,\n password: socksConfiguration.credential?.password\n ),\n addressCache: addressCache\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\ProxyConfigurationTransportProvider.swift
ProxyConfigurationTransportProvider.swift
Swift
2,574
0.95
0.045455
0.129032
python-kit
179
2025-02-13T14:32:40.265212
MIT
false
c9d802a5de65b27b468ae307aa9e0148
//\n// RESTTransport.swift\n// MullvadREST\n//\n// Created by Sajad Vishkai on 2022-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic protocol RESTTransport: Sendable {\n var name: String { get }\n\n func sendRequest(_ request: URLRequest, completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void)\n -> Cancellable\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\RESTTransport.swift
RESTTransport.swift
Swift
404
0.95
0
0.5
python-kit
149
2025-01-26T14:58:04.210925
Apache-2.0
false
247322106eca430c078bb6f0a3cef314
//\n// RESTTransportProvider.swift\n// MullvadREST\n//\n// Created by pronebird on 24/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\npublic protocol RESTTransportProvider {\n func makeTransport() -> RESTTransport?\n}\n\nextension REST {\n public struct AnyTransportProvider: RESTTransportProvider {\n private let block: () -> RESTTransport?\n\n public init(_ block: @escaping @Sendable () -> RESTTransport?) {\n self.block = block\n }\n\n public func makeTransport() -> RESTTransport? {\n return block()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\RESTTransportProvider.swift
RESTTransportProvider.swift
Swift
631
0.95
0
0.304348
node-utils
372
2023-08-08T05:43:24.390919
GPL-3.0
false
eae902556fb0b35bdbed1d047181c63c
//\n// TransportProvider.swift\n// MullvadTransport\n//\n// Created by Marco Nikic on 2023-05-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Logging\nimport MullvadRustRuntime\nimport MullvadTypes\n\npublic final class TransportProvider: RESTTransportProvider, Sendable {\n private let urlSessionTransport: URLSessionTransport\n private let addressCache: REST.AddressCache\n nonisolated(unsafe) private var transportStrategy: TransportStrategy\n nonisolated(unsafe) private var currentTransport: RESTTransport?\n nonisolated(unsafe) private var currentTransportType: TransportStrategy.Transport\n private let parallelRequestsMutex = NSLock()\n private let encryptedDNSTransport: RESTTransport\n\n public init(\n urlSessionTransport: URLSessionTransport,\n addressCache: REST.AddressCache,\n transportStrategy: TransportStrategy,\n encryptedDNSTransport: RESTTransport\n ) {\n self.urlSessionTransport = urlSessionTransport\n self.addressCache = addressCache\n self.transportStrategy = transportStrategy\n self.currentTransportType = transportStrategy.connectionTransport()\n self.encryptedDNSTransport = encryptedDNSTransport\n }\n\n public func makeTransport() -> RESTTransport? {\n parallelRequestsMutex.withLock {\n guard let actualTransport = makeTransportInner() else { return nil }\n\n let currentStrategy = transportStrategy\n return TransportWrapper(wrapped: actualTransport) { [weak self] error in\n if (error as? URLError)?.shouldResetNetworkTransport ?? false ||\n (error as? EncryptedDnsProxyError)?.shouldResetNetworkTransport ?? false {\n self?.resetTransportMatching(currentStrategy)\n }\n }\n }\n }\n\n /// When several requests fail at the same time, prevents the `transportStrategy` from switching multiple times.\n ///\n /// The `strategy` is checked against the `transportStrategy`. When several requests are made and fail in parallel,\n /// only the first failure will pass the equality check.\n /// Subsequent failures will not cause the strategy to change several times in a quick fashion.\n /// - Parameter strategy: The strategy object used when sending a request\n private func resetTransportMatching(_ strategy: TransportStrategy) {\n parallelRequestsMutex.lock()\n defer { parallelRequestsMutex.unlock() }\n\n if strategy == transportStrategy {\n if strategy.connectionTransport() == .encryptedDNS {\n (encryptedDNSTransport as? EncryptedDNSTransport)?.stop()\n }\n transportStrategy.didFail()\n currentTransport = nil\n }\n }\n\n /// Sets and returns the `currentTransport` according to the suggestion from `transportStrategy`\n ///\n /// > Warning: Do not lock the `parallelRequestsMutex` in this method\n ///\n /// - Returns: A `RESTTransport` object to make a connection\n private func makeTransportInner() -> RESTTransport? {\n if currentTransport == nil || shouldNotReuseCurrentTransport {\n currentTransportType = transportStrategy.connectionTransport()\n switch currentTransportType {\n case .direct:\n currentTransport = urlSessionTransport\n case let .shadowsocks(configuration):\n currentTransport = ShadowsocksTransport(\n urlSession: urlSessionTransport.urlSession,\n configuration: configuration,\n addressCache: addressCache\n )\n case let .socks5(configuration):\n currentTransport = URLSessionSocks5Transport(\n urlSession: urlSessionTransport.urlSession,\n configuration: configuration,\n addressCache: addressCache\n )\n case .encryptedDNS:\n currentTransport = encryptedDNSTransport\n case .none:\n currentTransport = nil\n }\n }\n return currentTransport\n }\n\n /// The `Main` allows modifications to access methods through the UI.\n /// The `TransportProvider` relies on a `CurrentTransport` value set during build time or network error.\n /// To ensure both process `Packet Tunnel` and `Main` uses the latest changes, the `TransportProvider` compares the `transportType` with the latest value in the cache and reuse it if it's still valid .\n private var shouldNotReuseCurrentTransport: Bool {\n currentTransportType != transportStrategy.connectionTransport()\n }\n}\n\nprivate extension EncryptedDnsProxyError {\n var shouldResetNetworkTransport: Bool {\n switch self {\n case .start:\n return true\n }\n }\n}\n\nprivate extension URLError {\n /// Whether the transport selection should be reset.\n ///\n /// `true` if the network request\n /// * Was not cancelled\n /// * Was not done during a phone call\n /// * Was made when internet connection was available\n /// * Was made in a context with data roaming, but international roaming was turned off\n var shouldResetNetworkTransport: Bool {\n code != .cancelled &&\n code != .notConnectedToInternet &&\n code != .internationalRoamingOff &&\n code != .callIsActive\n }\n}\n\n/// Interstitial implementation of `RESTTransport` that intercepts the completion of the wrapped transport.\nprivate struct TransportWrapper: RESTTransport {\n let wrapped: RESTTransport\n let onComplete: @Sendable (Error?) -> Void\n\n var name: String {\n return wrapped.name\n }\n\n func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n return wrapped.sendRequest(request) { data, response, error in\n onComplete(error)\n completion(data, response, error)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\TransportProvider.swift
TransportProvider.swift
Swift
6,032
0.95
0.059211
0.210145
node-utils
926
2025-03-17T07:44:24.828979
MIT
false
f2b0c1d1dc752761cf6aaabfc98da118
//\n// TransportStrategy.swift\n// MullvadREST\n//\n// Created by Marco Nikic on 2023-04-27.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Logging\nimport MullvadSettings\nimport MullvadTypes\n\npublic struct TransportStrategy: Equatable, Sendable {\n /// The different transports suggested by the strategy\n public enum Transport: Equatable {\n /// Connecting a direct connection\n case direct\n\n /// Connecting via shadowsocks proxy\n case shadowsocks(configuration: ShadowsocksConfiguration)\n\n /// Connecting via socks proxy\n case socks5(configuration: Socks5Configuration)\n\n /// Connecting via encrypted DNS proxy\n case encryptedDNS\n\n /// Failing to retrieve transport\n case none\n\n public static func == (lhs: Self, rhs: Self) -> Bool {\n switch (lhs, rhs) {\n case(.direct, .direct), (.none, .none):\n true\n case let (.shadowsocks(lhsConfiguration), .shadowsocks(rhsConfiguration)):\n lhsConfiguration == rhsConfiguration\n case let (.socks5(lhsConfiguration), .socks5(rhsConfiguration)):\n lhsConfiguration == rhsConfiguration\n case (.encryptedDNS, .encryptedDNS):\n true\n default:\n false\n }\n }\n }\n\n private let shadowsocksLoader: ShadowsocksLoaderProtocol\n\n private let accessMethodIterator: AccessMethodIterator\n\n public init(\n datasource: AccessMethodRepositoryDataSource,\n shadowsocksLoader: ShadowsocksLoaderProtocol\n ) {\n self.shadowsocksLoader = shadowsocksLoader\n self.accessMethodIterator = AccessMethodIterator(dataSource: datasource)\n }\n\n /// Rotating between enabled configurations by what order they were added in\n public func didFail() {\n let configuration = accessMethodIterator.pick()\n switch configuration.kind {\n case .bridges:\n try? shadowsocksLoader.clear()\n fallthrough\n default:\n self.accessMethodIterator.rotate()\n }\n }\n\n /// The suggested connection transport\n public func connectionTransport() -> Transport {\n let configuration = accessMethodIterator.pick()\n switch configuration.proxyConfiguration {\n case .direct:\n return .direct\n case .encryptedDNS:\n return .encryptedDNS\n case .bridges:\n do {\n let configuration = try shadowsocksLoader.load()\n return .shadowsocks(configuration: configuration)\n } catch {\n didFail()\n guard accessMethodIterator.pick().kind != .bridges else { return .none }\n return connectionTransport()\n }\n case let .shadowsocks(configuration):\n return .shadowsocks(configuration: ShadowsocksConfiguration(\n address: configuration.server,\n port: configuration.port,\n password: configuration.password,\n cipher: configuration.cipher.rawValue.description\n ))\n case let .socks5(configuration):\n return .socks5(configuration: Socks5Configuration(\n proxyEndpoint: configuration.toAnyIPEndpoint,\n username: configuration.credential?.username,\n password: configuration.credential?.password\n ))\n }\n }\n\n public static func == (lhs: TransportStrategy, rhs: TransportStrategy) -> Bool {\n lhs.accessMethodIterator.pick() == rhs.accessMethodIterator.pick()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\TransportStrategy.swift
TransportStrategy.swift
Swift
3,648
0.95
0.055556
0.157895
awesome-app
73
2023-10-11T10:04:21.872441
MIT
false
4313e9eeb2b9ec9b3cbcc2475d2ecc62
//\n// URLSessionTransport.swift\n// MullvadTransport\n//\n// Created by Mojgan on 2023-12-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nextension URLSessionTask: Cancellable {}\n\npublic final class URLSessionTransport: RESTTransport {\n public var name: String {\n "url-session"\n }\n\n public let urlSession: URLSession\n\n public init(urlSession: URLSession) {\n self.urlSession = urlSession\n }\n\n public func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Swift.Error?) -> Void\n ) -> Cancellable {\n let dataTask = urlSession.dataTask(with: request, completionHandler: completion)\n dataTask.resume()\n return dataTask\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Direct\URLSessionTransport.swift
URLSessionTransport.swift
Swift
792
0.95
0.030303
0.259259
vue-tools
439
2023-09-07T02:41:38.074050
GPL-3.0
false
c7560c5971d422b3e82b12e69224615c
//\n// EncryptedDNSTransport.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-09-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport Foundation\nimport MullvadRustRuntime\nimport MullvadTypes\n\npublic final class EncryptedDNSTransport: RESTTransport, @unchecked Sendable {\n public var name: String {\n "encrypted-dns-url-session"\n }\n\n /// The `URLSession` used to send requests via `encryptedDNSProxy`\n public let urlSession: URLSession\n private let encryptedDnsProxy: EncryptedDNSProxy\n private let dispatchQueue = DispatchQueue(label: "net.mullvad.EncryptedDNSTransport")\n private var dnsProxyTask: URLSessionTask?\n\n public init(urlSession: URLSession) {\n self.urlSession = urlSession\n self.encryptedDnsProxy = EncryptedDNSProxy(domain: REST.encryptedDNSHostname)\n }\n\n public func stop() {\n dispatchQueue.async { [weak self] in\n self?.encryptedDnsProxy.stop()\n self?.dnsProxyTask = nil\n }\n }\n\n /// Sends a request via the encrypted DNS proxy.\n ///\n /// Starting the proxy can take a very long time due to domain resolution\n /// Cancellation will only take place if the data task was already started, at which point,\n /// most of the time starting the DNS proxy was already spent.\n public func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void\n ) -> any Cancellable {\n dispatchQueue.async { [weak self] in\n guard let self else { return }\n do {\n try self.encryptedDnsProxy.start()\n } catch {\n completion(nil, nil, error)\n return\n }\n\n var urlRequestCopy = request\n urlRequestCopy.url = request.url.flatMap { url in\n var components = URLComponents(url: url, resolvingAgainstBaseURL: false)\n components?.host = "127.0.0.1"\n components?.port = Int(self.encryptedDnsProxy.localPort())\n return components?.url\n }\n\n let wrappedCompletionHandler: @Sendable (Data?, URLResponse?, (any Error)?)\n -> Void = { [weak self] data, response, maybeError in\n if maybeError != nil {\n self?.encryptedDnsProxy.stop()\n }\n // Do not call the completion handler if the request was cancelled in flight\n if let cancelledError = maybeError as? URLError, cancelledError.code == .cancelled {\n return\n }\n\n completion(data, response, maybeError)\n }\n\n let dataTask = urlSession.dataTask(with: urlRequestCopy, completionHandler: wrappedCompletionHandler)\n dataTask.resume()\n dnsProxyTask = dataTask\n }\n\n return AnyCancellable { [weak self] in\n self?.dispatchQueue.async { [weak self] in\n self?.dnsProxyTask?.cancel()\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\EncryptedDNS\EncryptedDNSTransport.swift
EncryptedDNSTransport.swift
Swift
3,090
0.95
0.082353
0.186667
react-lib
196
2024-02-10T12:39:11.703468
MIT
false
ce0bee51716081bbfe2d6d5cfe8a9a69
//\n// ShadowsocksConfiguration.swift\n// MullvadTransport\n//\n// Created by Marco Nikic on 2023-06-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\npublic struct ShadowsocksConfiguration: Codable, Equatable, Sendable {\n public let address: AnyIPAddress\n public let port: UInt16\n public let password: String\n public let cipher: String\n\n public init(address: AnyIPAddress, port: UInt16, password: String, cipher: String) {\n self.address = address\n self.port = port\n self.password = password\n self.cipher = cipher\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Shadowsocks\ShadowsocksConfiguration.swift
ShadowsocksConfiguration.swift
Swift
635
0.95
0
0.318182
awesome-app
190
2024-08-16T10:17:10.967695
BSD-3-Clause
false
69c74fdcce4a852a515b7e8f9a434f79
//\n// ShadowsocksConfigurationCache.swift\n// MullvadTransport\n//\n// Created by Marco Nikic on 2023-06-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic protocol ShadowsocksConfigurationCacheProtocol: Sendable {\n func read() throws -> ShadowsocksConfiguration\n func write(_ configuration: ShadowsocksConfiguration) throws\n func clear() throws\n}\n\n/// Holds a shadowsocks configuration object backed by a caching mechanism shared across processes\npublic final class ShadowsocksConfigurationCache: ShadowsocksConfigurationCacheProtocol, @unchecked Sendable {\n private let configurationLock = NSLock()\n private var cachedConfiguration: ShadowsocksConfiguration?\n private let fileCache: FileCache<ShadowsocksConfiguration>\n\n public init(cacheDirectory: URL) {\n fileCache = FileCache(\n fileURL: cacheDirectory.appendingPathComponent("shadowsocks-cache.json", isDirectory: false)\n )\n }\n\n /// Returns configuration from memory cache if available, otherwise attempts to load it from disk cache before\n /// returning.\n public func read() throws -> ShadowsocksConfiguration {\n configurationLock.lock()\n defer { configurationLock.unlock() }\n\n if let cachedConfiguration {\n return cachedConfiguration\n } else {\n let readConfiguration = try fileCache.read()\n cachedConfiguration = readConfiguration\n return readConfiguration\n }\n }\n\n /// Replace memory cache with new configuration and attempt to persist it on disk.\n public func write(_ configuration: ShadowsocksConfiguration) throws {\n configurationLock.lock()\n defer { configurationLock.unlock() }\n\n cachedConfiguration = configuration\n try fileCache.write(configuration)\n }\n\n /// Clear cached configuration.\n public func clear() throws {\n configurationLock.lock()\n defer { configurationLock.unlock() }\n cachedConfiguration = nil\n try fileCache.clear()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Shadowsocks\ShadowsocksConfigurationCache.swift
ShadowsocksConfigurationCache.swift
Swift
2,076
0.95
0.098361
0.230769
node-utils
939
2024-12-24T06:06:01.628301
MIT
false
f94ce5c9791e838cebacd24c415ce303
//\n// LocalShadowsocksLoader.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-01-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\npublic protocol ShadowsocksLoaderProtocol: Sendable {\n func load() throws -> ShadowsocksConfiguration\n func clear() throws\n}\n\npublic final class ShadowsocksLoader: ShadowsocksLoaderProtocol, Sendable {\n let cache: ShadowsocksConfigurationCacheProtocol\n let relaySelector: ShadowsocksRelaySelectorProtocol\n let settingsUpdater: SettingsUpdater\n\n nonisolated(unsafe) private var observer: SettingsObserverBlock!\n nonisolated(unsafe) private var tunnelSettings = LatestTunnelSettings()\n private let settingsStrategy = TunnelSettingsStrategy()\n\n deinit {\n self.settingsUpdater.removeObserver(observer)\n }\n\n public init(\n cache: ShadowsocksConfigurationCacheProtocol,\n relaySelector: ShadowsocksRelaySelectorProtocol,\n settingsUpdater: SettingsUpdater\n ) {\n self.cache = cache\n self.relaySelector = relaySelector\n self.settingsUpdater = settingsUpdater\n self.addObservers()\n }\n\n private func addObservers() {\n observer =\n SettingsObserverBlock(\n didUpdateSettings: { [weak self] latestTunnelSettings in\n guard let self else { return }\n if settingsStrategy.shouldReconnectToNewRelay(\n oldSettings: tunnelSettings,\n newSettings: latestTunnelSettings\n ) {\n try? clear()\n }\n tunnelSettings = latestTunnelSettings\n }\n )\n settingsUpdater.addObserver(self.observer)\n }\n\n public func clear() throws {\n try self.cache.clear()\n }\n\n /// Returns the last used shadowsocks configuration, otherwise a new randomized configuration.\n public func load() throws -> ShadowsocksConfiguration {\n do {\n // If a previous shadowsocks configuration was in cache, return it directly.\n return try cache.read()\n } catch {\n // There is no previous configuration either if this is the first time this code ran\n let newConfiguration = try create()\n try cache.write(newConfiguration)\n return newConfiguration\n }\n }\n\n /// Returns a randomly selected shadowsocks configuration.\n private func create() throws -> ShadowsocksConfiguration {\n let bridgeConfiguration = try relaySelector.getBridges()\n let closestRelay = try relaySelector.selectRelay(with: tunnelSettings)\n\n guard let bridgeAddress = closestRelay?.ipv4AddrIn,\n let bridgeConfiguration else { throw POSIXError(.ENOENT) }\n\n return ShadowsocksConfiguration(\n address: .ipv4(bridgeAddress),\n port: bridgeConfiguration.port,\n password: bridgeConfiguration.password,\n cipher: bridgeConfiguration.cipher\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Shadowsocks\ShadowsocksLoader.swift
ShadowsocksLoader.swift
Swift
3,086
0.95
0.120879
0.139241
node-utils
532
2024-12-13T16:09:39.390020
BSD-3-Clause
false
91a8c19fe544ce1f8a7ed0bda87f20bd
//\n// ShadowsocksRelaySelector.swift\n// MullvadREST\n//\n// Created by Mojgan on 2024-05-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\npublic protocol ShadowsocksRelaySelectorProtocol: Sendable {\n func selectRelay(with settings: LatestTunnelSettings) throws -> REST.BridgeRelay?\n\n func getBridges() throws -> REST.ServerShadowsocks?\n}\n\nfinal public class ShadowsocksRelaySelector: ShadowsocksRelaySelectorProtocol {\n let relayCache: RelayCacheProtocol\n\n public init(\n relayCache: RelayCacheProtocol\n ) {\n self.relayCache = relayCache\n }\n\n public func selectRelay(with settings: LatestTunnelSettings) throws -> REST.BridgeRelay? {\n let cachedRelays = try relayCache.read().relays\n\n let locationConstraint = switch settings.tunnelMultihopState {\n case .on: settings.relayConstraints.entryLocations\n case .off: settings.relayConstraints.exitLocations\n }\n\n return RelaySelector.Shadowsocks.closestRelay(\n location: locationConstraint,\n port: settings.relayConstraints.port,\n filter: settings.relayConstraints.filter,\n in: cachedRelays\n )\n }\n\n public func getBridges() throws -> REST.ServerShadowsocks? {\n let cachedRelays = try relayCache.read()\n return RelaySelector.Shadowsocks.tcpBridge(from: cachedRelays.relays)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Shadowsocks\ShadowsocksRelaySelector.swift
ShadowsocksRelaySelector.swift
Swift
1,453
0.95
0.083333
0.179487
awesome-app
34
2024-04-09T04:50:10.785318
Apache-2.0
false
2fc29c301a04b28ce2ec08ad52655832
//\n// ShadowsocksTransport.swift\n// MullvadTransport\n//\n// Created by pronebird on 12/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntime\nimport MullvadTypes\n\npublic final class ShadowsocksTransport: RESTTransport {\n /// The Shadowsocks proxy instance that proxies all the traffic it receives\n private let shadowsocksProxy: ShadowsocksProxy\n\n /// The IPv4 representation of the loopback address used by `shadowsocksProxy`\n private let localhost = "127.0.0.1"\n\n /// The `URLSession` used to send requests via `shadowsocksProxy`\n public let urlSession: URLSession\n\n public var name: String {\n "shadow-socks-url-session"\n }\n\n public init(\n urlSession: URLSession,\n configuration: ShadowsocksConfiguration,\n addressCache: REST.AddressCache\n ) {\n self.urlSession = urlSession\n let apiAddress = addressCache.getCurrentEndpoint()\n\n shadowsocksProxy = ShadowsocksProxy(\n forwardAddress: apiAddress.ip,\n forwardPort: apiAddress.port,\n bridgeAddress: configuration.address,\n bridgePort: configuration.port,\n password: configuration.password,\n cipher: configuration.cipher\n )\n }\n\n public func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Swift.Error?) -> Void\n ) -> Cancellable {\n // Start the Shadowsocks proxy in order to get a local port\n shadowsocksProxy.start()\n\n // Copy the URL request and rewrite the host and port to point to the Shadowsocks proxy instance\n var urlRequestCopy = request\n urlRequestCopy.url = request.url.flatMap { url in\n var components = URLComponents(url: url, resolvingAgainstBaseURL: false)\n components?.host = localhost\n components?.port = Int(shadowsocksProxy.localPort())\n return components?.url\n }\n\n let dataTask = urlSession.dataTask(with: urlRequestCopy, completionHandler: completion)\n dataTask.resume()\n return dataTask\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Shadowsocks\ShadowsocksTransport.swift
ShadowsocksTransport.swift
Swift
2,151
0.95
0.015385
0.218182
vue-tools
37
2025-03-08T07:02:34.775426
GPL-3.0
false
c143c1bf9f22a111aefabb5689adbf08
//\n// AnyIPEndpoint+Socks5.swift\n// MullvadTransport\n//\n// Created by pronebird on 23/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\nextension AnyIPEndpoint {\n /// Convert `AnyIPEndpoint` to `Socks5Endpoint`.\n var socksEndpoint: Socks5Endpoint {\n switch self {\n case let .ipv4(endpoint):\n .ipv4(endpoint)\n case let .ipv6(endpoint):\n .ipv6(endpoint)\n }\n }\n\n /// Convert `AnyIPEndpoint` to `NWEndpoint`.\n var nwEndpoint: NWEndpoint {\n switch self {\n case let .ipv4(endpoint):\n .hostPort(host: .ipv4(endpoint.ip), port: NWEndpoint.Port(integerLiteral: endpoint.port))\n case let .ipv6(endpoint):\n .hostPort(host: .ipv6(endpoint.ip), port: NWEndpoint.Port(integerLiteral: endpoint.port))\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\AnyIPEndpoint+Socks5.swift
AnyIPEndpoint+Socks5.swift
Swift
891
0.95
0.060606
0.3
react-lib
234
2025-06-09T10:58:50.391962
GPL-3.0
false
5d5befbb6cf678639c363d90f4f23962
//\n// CancellableChain.swift\n// MullvadTransport\n//\n// Created by pronebird on 23/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Cancellable object that cancels all cancellable objects linked to it.\nfinal class CancellableChain: Cancellable {\n private let stateLock = NSLock()\n private var isCancelled = false\n private var linkedTokens: [Cancellable] = []\n\n init() {}\n\n /// Link cancellation token with some other.\n ///\n /// The token is cancelled immediately, if the chain is already cancelled.\n func link(_ token: Cancellable) {\n stateLock.withLock {\n if isCancelled {\n token.cancel()\n } else {\n linkedTokens.append(token)\n }\n }\n }\n\n /// Request cancellation.\n ///\n /// Cancels and releases any of the connected tokens.\n func cancel() {\n stateLock.withLock {\n isCancelled = true\n linkedTokens.forEach { $0.cancel() }\n linkedTokens.removeAll()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\CancellableChain.swift
CancellableChain.swift
Swift
1,090
0.95
0.069767
0.368421
awesome-app
337
2023-11-25T11:05:59.866209
BSD-3-Clause
false
27ad07794a13c5a4055cc1c7afa8b4e0
//\n// NWConnection+Extensions.swift\n// MullvadTransport\n//\n// Created by pronebird on 20/10/2023.\n//\n\nimport Foundation\nimport Network\n\nextension NWConnection {\n /**\n Read exact number of bytes from connection.\n\n - Parameters:\n - exactLength: exact number of bytes to read.\n - completion: a completion handler.\n */\n func receive(exactLength: Int, completion: @Sendable @escaping (Data?, ContentContext?, Bool, NWError?) -> Void) {\n receive(minimumIncompleteLength: exactLength, maximumLength: exactLength, completion: completion)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\NWConnection+Extensions.swift
NWConnection+Extensions.swift
Swift
581
0.95
0
0.421053
node-utils
468
2024-11-08T18:27:05.834199
Apache-2.0
false
4fb02a0a989bbfe4e30695e582e938d6
//\n// Socks5AddressType.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\n\n/// Address type supported by socks protocol\nenum Socks5AddressType: UInt8, Sendable {\n case ipv4 = 0x01\n case domainName = 0x03\n case ipv6 = 0x04\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5AddressType.swift
Socks5AddressType.swift
Swift
276
0.95
0
0.538462
react-lib
697
2025-03-21T11:29:51.228342
MIT
false
4ad566196cb40aba824018b25c4f995b
//\n// Socks5Authentication.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// Authentication methods supported by socks protocol.\nenum Socks5AuthenticationMethod: UInt8 {\n case notRequired = 0x00\n case usernamePassword = 0x02\n}\n\nstruct Socks5Authentication: Sendable {\n let connection: NWConnection\n let endpoint: Socks5Endpoint\n let configuration: Socks5Configuration\n\n typealias AuthenticationComplete = @Sendable () -> Void\n typealias AuthenticationFailure = @Sendable (Error) -> Void\n\n func authenticate(onComplete: @escaping AuthenticationComplete, onFailure: @escaping AuthenticationFailure) {\n guard let username = configuration.username, let password = configuration.password else {\n onFailure(Socks5Error.invalidUsernameOrPassword)\n return\n }\n let authenticateCommand = Socks5UsernamePasswordCommand(username: username, password: password)\n\n connection.send(content: authenticateCommand.rawData, completion: .contentProcessed { error in\n if let error {\n onFailure(error)\n } else {\n readNegotiationReply(onComplete: onComplete, onFailure: onFailure)\n }\n })\n }\n\n func readNegotiationReply(\n onComplete: @escaping AuthenticationComplete,\n onFailure: @escaping AuthenticationFailure\n ) {\n let replySize = MemoryLayout<Socks5UsernamePasswordReply>.size\n\n // Read in one shot, the payload is very small to not care about a reading loop.\n connection.receive(exactLength: replySize) { data, _, _, error in\n guard let data else {\n if let error {\n onFailure(error)\n } else {\n onFailure(Socks5Error.unexpectedEndOfStream)\n }\n return\n }\n\n guard let reply = Socks5UsernamePasswordReply(from: data) else {\n onFailure(Socks5Error.unexpectedEndOfStream)\n return\n }\n\n guard reply.version == Socks5Constants.usernamePasswordAuthenticationProtocol else {\n onFailure(Socks5Error.invalidSocksVersion)\n return\n }\n\n onComplete()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Authentication.swift
Socks5Authentication.swift
Swift
2,318
0.95
0.028169
0.133333
vue-tools
594
2023-07-26T13:01:01.121424
GPL-3.0
false
0eb80292db9eb7f1c982669520ff0ee8
//\n// Socks5Command.swift\n// MullvadTransport\n//\n// Created by pronebird on 21/10/2023.\n//\n\nimport Foundation\n\n/// Commands supported in socks protocol.\nenum Socks5Command: UInt8 {\n case connect = 0x01\n case bind = 0x02\n case udpAssociate = 0x03\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Command.swift
Socks5Command.swift
Swift
260
0.95
0
0.538462
awesome-app
794
2024-11-25T08:35:12.414171
Apache-2.0
false
36af8611dda3ebfa16f38a7a2aeae08e
//\n// Socks5Configuration.swift\n// MullvadTransport\n//\n// Created by pronebird on 23/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Socks5 configuration.\n/// - See: ``URLSessionSocks5Transport``\npublic struct Socks5Configuration: Equatable, Sendable {\n /// The socks proxy endpoint.\n public var proxyEndpoint: AnyIPEndpoint\n\n public var username: String?\n public var password: String?\n\n public init(proxyEndpoint: AnyIPEndpoint, username: String? = nil, password: String? = nil) {\n self.proxyEndpoint = proxyEndpoint\n self.username = username\n self.password = password\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Configuration.swift
Socks5Configuration.swift
Swift
684
0.95
0
0.454545
react-lib
547
2024-02-10T18:08:06.589393
Apache-2.0
false
abd880e8de7e87d5998105cb36a0d3cc
//\n// Socks5ConnectCommand.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// The connect command message.\nstruct Socks5ConnectCommand {\n /// The remote endpoint to which the client wants to establish connection over the socks proxy.\n var endpoint: Socks5Endpoint\n\n /// The byte representation in socks protocol.\n var rawData: Data {\n var data = Data()\n\n // Socks version.\n data.append(Socks5Constants.socksVersion)\n\n // Command code.\n data.append(Socks5Command.connect.rawValue)\n\n // Reserved.\n data.append(0)\n\n // Address type.\n data.append(endpoint.addressType.rawValue)\n\n // Endpoint address.\n data.append(endpoint.rawData)\n\n return data\n }\n}\n\n/// The connect command reply message.\nstruct Socks5ConnectReply {\n /// The server status code.\n var status: Socks5StatusCode\n\n /// The server bound endpoint.\n var serverBoundEndpoint: Socks5Endpoint\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5ConnectCommand.swift
Socks5ConnectCommand.swift
Swift
1,023
0.95
0
0.485714
vue-tools
34
2024-07-22T12:08:47.414651
MIT
false
f4e86bc4cdf0564942ea4fb4c96359a7
//\n// Socks5Connection.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// A bidirectional data connection between a local endpoint and remote endpoint over socks proxy.\nfinal class Socks5Connection: Sendable {\n /// The remote endpoint to which the client wants to establish connection over the socks proxy.\n let remoteServerEndpoint: Socks5Endpoint\n let configuration: Socks5Configuration\n /**\n Initializes a new connection passing data between local and remote TCP connection over the socks proxy.\n\n - Parameters:\n - queue: the queue on which connection events are delivered.\n - localConnection: the local TCP connection.\n - socksProxyEndpoint: the socks proxy endpoint.\n - remoteServerEndpoint: the remote endpoint to which the client wants to establish connection over the socks proxy.\n */\n init(\n queue: DispatchQueue,\n localConnection: NWConnection,\n socksProxyEndpoint: NWEndpoint,\n remoteServerEndpoint: Socks5Endpoint,\n configuration: Socks5Configuration\n ) {\n self.queue = queue\n self.remoteServerEndpoint = remoteServerEndpoint\n self.localConnection = localConnection\n self.remoteConnection = NWConnection(to: socksProxyEndpoint, using: .tcp)\n self.configuration = configuration\n }\n\n /**\n Start establishing a connection.\n\n The start operation is asynchronous. Calls to start after the first one are ignored.\n */\n func start() {\n queue.async { [self] in\n guard case .initialized = state else { return }\n\n state = .started\n\n localConnection.stateUpdateHandler = onLocalConnectionState\n remoteConnection.stateUpdateHandler = onRemoteConnectionState\n localConnection.start(queue: queue)\n remoteConnection.start(queue: queue)\n }\n }\n\n /**\n Cancel the connection.\n\n Cancellation is asynchronous. All block handlers are released to break retain cycles once connection moved to stopped state. The object is not meant to be\n reused or restarted after cancellation.\n\n Calls to cancel after the first one are ignored.\n */\n func cancel() {\n queue.async { [self] in\n cancel(error: nil)\n }\n }\n\n /**\n Set a handler that receives connection state events.\n\n It's advised to set the state handler before starting the connection to avoid missing updates to the connection state.\n\n - Parameter newStateHandler: state handler block.\n */\n func setStateHandler(_ newStateHandler: (@Sendable (Socks5Connection, State) -> Void)?) {\n queue.async { [self] in\n stateHandler = newStateHandler\n }\n }\n\n // MARK: - Private\n\n /// Connection state.\n enum State {\n /// Connection object is initialized. Default state.\n case initialized\n\n /// Connection is started.\n case started\n\n /// Connection to socks proxy is initiated.\n case connectionInitiated\n\n /// Connection object is in stopped state.\n case stopped(Error?)\n\n /// Returns `true` if connection is in `.stopped` state.\n var isStopped: Bool {\n if case .stopped = self {\n return true\n } else {\n return false\n }\n }\n }\n\n private let queue: DispatchQueue\n private let localConnection: NWConnection\n private let remoteConnection: NWConnection\n nonisolated(unsafe) private var stateHandler: (@Sendable (Socks5Connection, State) -> Void)?\n nonisolated(unsafe) private var state: State = .initialized {\n didSet {\n stateHandler?(self, state)\n }\n }\n\n private func cancel(error: Error?) {\n guard !state.isStopped else { return }\n\n state = .stopped(error)\n stateHandler = nil\n\n localConnection.cancel()\n remoteConnection.cancel()\n }\n\n private func onLocalConnectionState(_ connectionState: NWConnection.State) {\n switch connectionState {\n case .setup, .preparing, .cancelled:\n break\n\n case .ready:\n initiateConnection()\n\n case let .waiting(error), let .failed(error):\n handleError(Socks5Error.localConnectionFailure(error))\n\n @unknown default:\n break\n }\n }\n\n private func onRemoteConnectionState(_ connectionState: NWConnection.State) {\n switch connectionState {\n case .setup, .preparing, .cancelled:\n break\n\n case .ready:\n initiateConnection()\n\n case let .waiting(error), let .failed(error):\n handleError(Socks5Error.remoteConnectionFailure(error))\n\n @unknown default:\n break\n }\n }\n\n /// Initiate connection to socks proxy if local and remote connections are both ready.\n /// Repeat calls to this method do nothing once connection to socks proxy is initiated.\n private func initiateConnection() {\n guard case .started = state else { return }\n guard case (.ready, .ready) = (localConnection.state, remoteConnection.state) else { return }\n\n state = .connectionInitiated\n sendHandshake()\n }\n\n private func handleError(_ error: Error) {\n cancel(error: error)\n }\n\n /// Start handshake with the socks proxy.\n private func sendHandshake() {\n var handshake = Socks5Handshake()\n if configuration.username != nil && configuration.password != nil {\n handshake.methods.append(.usernamePassword)\n }\n let negotiation = Socks5HandshakeNegotiation(\n connection: remoteConnection,\n handshake: handshake,\n onComplete: onHandshake,\n onFailure: handleError\n )\n negotiation.perform()\n }\n\n /// Handles handshake reply.\n /// Initiates authentication flow if indicated in reply, otherwise starts connection negotiation immediately.\n private func onHandshake(_ reply: Socks5HandshakeReply) {\n switch reply.method {\n case .notRequired:\n connect()\n\n case .usernamePassword:\n // Username + password authentication sends the data in plain text to the server\n // And then continues like the `notRequired` case after the server has authenticated the client.\n let authentication = Socks5Authentication(\n connection: remoteConnection,\n endpoint: remoteServerEndpoint,\n configuration: configuration\n )\n authentication.authenticate(onComplete: { [self] in\n connect()\n }, onFailure: { [self] error in\n handleError(error)\n })\n }\n }\n\n /// Start connection negotiation.\n /// Upon successful negotiation, the client can begin exchanging data with remote server.\n private func connect() {\n let negotiation = Socks5ConnectNegotiation(\n connection: remoteConnection,\n endpoint: remoteServerEndpoint,\n onComplete: { [self] reply in\n if case .succeeded = reply.status {\n stream()\n } else {\n handleError(Socks5Error.connectionRejected(reply.status))\n }\n },\n onFailure: handleError\n )\n negotiation.perform()\n }\n\n /// Start streaming data between local and remote endpoint.\n private func stream() {\n let streamHandler = Socks5DataStreamHandler(\n localConnection: localConnection,\n remoteConnection: remoteConnection\n ) { [self] error in\n self.handleError(error)\n }\n streamHandler.start()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Connection.swift
Socks5Connection.swift
Swift
7,791
0.95
0.041322
0.162562
react-lib
235
2025-07-09T11:20:55.458493
Apache-2.0
false
532bc4f11728d391ec6dd08176709121
//\n// Socks5ConnectNegotiation.swift\n// MullvadTransport\n//\n// Created by pronebird on 20/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// The object handling a connection negotiation with socks proxy.\nstruct Socks5ConnectNegotiation {\n /// Connection to the socks proxy.\n let connection: NWConnection\n\n /// Endpoint to which the client wants to initiate connection over socks proxy.\n let endpoint: Socks5Endpoint\n\n /// Completion handler invoked on success.\n let onComplete: @Sendable (Socks5ConnectReply) -> Void\n\n /// Failure handler invoked on error.\n let onFailure: @Sendable (Error) -> Void\n\n /// Initiate negotiation by sending a connect command to the socks proxy.\n func perform() {\n let connectCommand = Socks5ConnectCommand(endpoint: endpoint)\n\n connection.send(content: connectCommand.rawData, completion: .contentProcessed { [self] error in\n if let error {\n onFailure(Socks5Error.remoteConnectionFailure(error))\n } else {\n readPartialReply()\n }\n })\n }\n\n /// Read the preamble of the connect reply.\n private func readPartialReply() {\n // The length of the preamble of the CONNECT reply.\n let replyPreambleLength = 4\n\n connection.receive(exactLength: replyPreambleLength) { [self] data, _, _, error in\n if let error {\n onFailure(Socks5Error.remoteConnectionFailure(error))\n } else if let data {\n do {\n try handlePartialReply(data: data)\n } catch {\n onFailure(error)\n }\n } else {\n onFailure(Socks5Error.unexpectedEndOfStream)\n }\n }\n }\n\n /**\n Parse the bytes that comprise the preamble of a connect reply. Upon success read the endpoint data to produce the complete reply and finish negotiation.\n\n The following fields are contained within the first 4 bytes: socks version, status code, reserved field, address type.\n */\n private func handlePartialReply(data: Data) throws {\n // Parse partial reply that contains the status code and address type.\n let (statusCode, addressType) = try parsePartialReply(data: data)\n\n // Parse server bound endpoint to produce the complete reply.\n let endpointReader = Socks5EndpointReader(\n connection: connection,\n addressType: addressType,\n onComplete: { [self] endpoint in\n let reply = Socks5ConnectReply(status: statusCode, serverBoundEndpoint: endpoint)\n onComplete(reply)\n },\n onFailure: onFailure\n )\n endpointReader.perform()\n }\n\n /// Parse the bytes that comprise the preamble of reply without endpoint data.\n private func parsePartialReply(data: Data) throws -> (Socks5StatusCode, Socks5AddressType) {\n var iterator = data.makeIterator()\n\n // Read the protocol version.\n guard let version = iterator.next() else { throw Socks5Error.unexpectedEndOfStream }\n\n // Verify the protocol version.\n guard version == Socks5Constants.socksVersion else { throw Socks5Error.invalidSocksVersion }\n\n // Read status code, reserved field and address type from reply.\n guard let rawStatusCode = iterator.next(),\n iterator.next() != nil, // skip reserved field\n let rawAddressType = iterator.next() else {\n throw Socks5Error.unexpectedEndOfStream\n }\n\n // Parse the status code.\n guard let status = Socks5StatusCode(rawValue: rawStatusCode) else {\n throw Socks5Error.invalidStatusCode(rawStatusCode)\n }\n\n // Parse the address type.\n guard let addressType = Socks5AddressType(rawValue: rawAddressType) else {\n throw Socks5Error.invalidAddressType\n }\n\n return (status, addressType)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5ConnectNegotiation.swift
Socks5ConnectNegotiation.swift
Swift
3,952
0.95
0.055046
0.266667
awesome-app
622
2024-01-09T15:32:44.304314
BSD-3-Clause
false
3179bfe1387e40f56e25db03486998c3
//\n// Socks5Constants.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\n\nenum Socks5Constants {\n /// Socks version.\n static let socksVersion: UInt8 = 0x05\n\n static let usernamePasswordAuthenticationProtocol: UInt8 = 0x01\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Constants.swift
Socks5Constants.swift
Swift
275
0.95
0
0.583333
node-utils
545
2023-12-24T06:34:57.816608
GPL-3.0
false
ef65ae5a00678cb6ba82c9c3bd2d3604
//\n// Socks5DataStreamHandler.swift\n// MullvadTransport\n//\n// Created by pronebird on 20/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// The object handling bidirectional streaming of data between local and remote connection.\nstruct Socks5DataStreamHandler: Sendable {\n /// How many bytes the handler can receive at one time, when streaming data between local and remote connection.\n static let maxBytesToRead = Int(UInt16.max)\n\n /// Local TCP connection.\n let localConnection: NWConnection\n\n /// Remote TCP connection to the socks proxy.\n let remoteConnection: NWConnection\n\n /// Error handler.\n let errorHandler: @Sendable (Error) -> Void\n\n /// Start streaming data between local and remote connection.\n func start() {\n streamOutboundTraffic()\n streamInboundTraffic()\n }\n\n /// Pass outbound traffic from local to remote connection.\n private func streamOutboundTraffic() {\n localConnection.receive(\n minimumIncompleteLength: 1,\n maximumLength: Self.maxBytesToRead\n ) { [self] content, _, isComplete, error in\n if let error {\n errorHandler(Socks5Error.localConnectionFailure(error))\n return\n }\n\n remoteConnection.send(\n content: content,\n isComplete: isComplete,\n completion: .contentProcessed { [self] error in\n if let error {\n errorHandler(Socks5Error.remoteConnectionFailure(error))\n } else if !isComplete {\n streamOutboundTraffic()\n }\n }\n )\n }\n }\n\n /// Pass inbound traffic from remote to local connection.\n private func streamInboundTraffic() {\n remoteConnection.receive(\n minimumIncompleteLength: 1,\n maximumLength: Self.maxBytesToRead\n ) { [self] content, _, isComplete, error in\n if let error {\n errorHandler(Socks5Error.remoteConnectionFailure(error))\n return\n }\n\n localConnection.send(\n content: content,\n isComplete: isComplete,\n completion: .contentProcessed { [self] error in\n if let error {\n errorHandler(Socks5Error.localConnectionFailure(error))\n } else if !isComplete {\n streamInboundTraffic()\n }\n }\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5DataStreamHandler.swift
Socks5DataStreamHandler.swift
Swift
2,559
0.95
0.075
0.2
react-lib
162
2024-09-05T08:37:33.129773
MIT
false
793cf62728c158c26d10e4bec3ecf18d
//\n// Socks5Endpoint.swift\n// MullvadTransport\n//\n// Created by pronebird on 20/10/2023.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\n/// A network endpoint specified by DNS name and port.\npublic struct Socks5HostEndpoint: Sendable {\n /// The endpoint's hostname.\n public let hostname: String\n\n /// The endpoint's port.\n public let port: UInt16\n\n /**\n Initializes a new host endpoint.\n\n Returns `nil` when the hostname is either empty or longer than 255 bytes, because it cannot be represented in socks protocol.\n\n - Parameters:\n - hostname: the endpoint's hostname\n - port: the endpoint's port\n */\n public init?(hostname: String, port: UInt16) {\n // The maximum length of domain name in bytes.\n let maxHostnameLength = UInt8.max\n let hostnameByteLength = Data(hostname.utf8).count\n\n // Empty hostname is meaningless.\n guard hostnameByteLength > 0 else { return nil }\n\n // The length larger than 255 bytes cannot be represented in socks protocol.\n guard hostnameByteLength <= maxHostnameLength else { return nil }\n\n self.hostname = hostname\n self.port = port\n }\n}\n\n/// The endpoint type used by objects implementing socks protocol.\npublic enum Socks5Endpoint: Sendable {\n /// IPv4 endpoint.\n case ipv4(IPv4Endpoint)\n\n /// IPv6 endpoint.\n case ipv6(IPv6Endpoint)\n\n /// Domain name endpoint.\n case domain(Socks5HostEndpoint)\n\n /// The corresponding raw socks address type.\n var addressType: Socks5AddressType {\n switch self {\n case .ipv4:\n return .ipv4\n case .ipv6:\n return .ipv6\n case .domain:\n return .domainName\n }\n }\n\n /// The port associated with the underlying endpoint.\n var port: UInt16 {\n switch self {\n case let .ipv4(endpoint):\n endpoint.port\n case let .ipv6(endpoint):\n endpoint.port\n case let .domain(endpoint):\n endpoint.port\n }\n }\n\n /// The byte representation in socks protocol.\n var rawData: Data {\n var data = Data()\n\n switch self {\n case let .ipv4(endpoint):\n data.append(contentsOf: endpoint.ip.rawValue)\n\n case let .ipv6(endpoint):\n data.append(contentsOf: endpoint.ip.rawValue)\n\n case let .domain(endpoint):\n // Convert hostname to byte data without nul terminator.\n let domainNameBytes = Data(endpoint.hostname.utf8)\n\n // Append the length of domain name.\n // Host endpoint already ensures that the length of domain name does not exceed the maximum value that\n // single byte can hold.\n data.append(UInt8(domainNameBytes.count))\n\n // Append the domain name.\n data.append(contentsOf: domainNameBytes)\n }\n\n // Append port in network byte order.\n withUnsafeBytes(of: port.bigEndian) { buffer in\n data.append(contentsOf: buffer)\n }\n\n return data\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Endpoint.swift
Socks5Endpoint.swift
Swift
3,070
0.95
0.027027
0.303371
vue-tools
173
2024-10-19T14:48:45.033037
BSD-3-Clause
false
790051f1f84cc258b54ab21d9d7e8aea
//\n// Socks5EndpointReader.swift\n// MullvadTransport\n//\n// Created by pronebird on 21/10/2023.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\n/// The object reading the endpoint data from connection.\nstruct Socks5EndpointReader: Sendable {\n /// Connection to the socks proxy.\n let connection: NWConnection\n\n /// The expected address type.\n let addressType: Socks5AddressType\n\n /// Completion handler called upon success.\n let onComplete: @Sendable (Socks5Endpoint) -> Void\n\n /// Failure handler.\n let onFailure: @Sendable (Error) -> Void\n\n /// Start reading endpoint from connection.\n func perform() {\n // The length of IPv4 address in bytes.\n let ipv4AddressLength = 4\n\n // The length of IPv6 address in bytes.\n let ipv6AddressLength = 16\n\n switch addressType {\n case .ipv4:\n readBoundAddressAndPortInner(addressLength: ipv4AddressLength)\n\n case .ipv6:\n readBoundAddressAndPortInner(addressLength: ipv6AddressLength)\n\n case .domainName:\n readBoundDomainNameLength { [self] domainLength in\n readBoundAddressAndPortInner(addressLength: domainLength)\n }\n }\n }\n\n private func readBoundAddressAndPortInner(addressLength: Int) {\n // The length of port in bytes.\n let portLength = MemoryLayout<UInt16>.size\n\n // The entire length of address + port\n let byteSize = addressLength + portLength\n\n connection.receive(exactLength: byteSize) { [self] addressData, _, _, error in\n if let error {\n onFailure(Socks5Error.remoteConnectionFailure(error))\n } else if let addressData {\n do {\n let endpoint = try parseEndpoint(addressData: addressData, addressLength: addressLength)\n\n onComplete(endpoint)\n } catch {\n onFailure(error)\n }\n } else {\n onFailure(Socks5Error.unexpectedEndOfStream)\n }\n }\n }\n\n private func readBoundDomainNameLength(completion: @escaping @Sendable (Int) -> Void) {\n // The length of domain length parameter in bytes.\n let domainLengthLength = MemoryLayout<UInt8>.size\n\n connection.receive(exactLength: domainLengthLength) { [self] data, _, _, error in\n if let error {\n onFailure(Socks5Error.remoteConnectionFailure(error))\n } else if let domainNameLength = data?.first {\n completion(Int(domainNameLength))\n } else {\n onFailure(Socks5Error.unexpectedEndOfStream)\n }\n }\n }\n\n private func parseEndpoint(addressData: Data, addressLength: Int) throws -> Socks5Endpoint {\n // The length of port in bytes.\n let portLength = MemoryLayout<UInt16>.size\n\n guard addressData.count == addressLength + portLength else { throw Socks5Error.unexpectedEndOfStream }\n\n // Read address bytes.\n let addressBytes = addressData[0 ..< addressLength]\n\n // Read port bytes.\n let port = addressData[addressLength...].withUnsafeBytes { buffer in\n let value = buffer.load(as: UInt16.self)\n\n // Port is passed in network byte order. Convert it to host order.\n return UInt16(bigEndian: value)\n }\n\n // Parse address into endpoint.\n switch addressType {\n case .ipv4:\n guard let ipAddress = IPv4Address(addressBytes) else { throw Socks5Error.parseIPv4Address }\n\n return .ipv4(IPv4Endpoint(ip: ipAddress, port: port))\n\n case .ipv6:\n guard let ipAddress = IPv6Address(addressBytes) else { throw Socks5Error.parseIPv6Address }\n\n return .ipv6(IPv6Endpoint(ip: ipAddress, port: port))\n\n case .domainName:\n guard let hostname = String(bytes: addressBytes, encoding: .utf8),\n let endpoint = Socks5HostEndpoint(hostname: hostname, port: port) else {\n throw Socks5Error.decodeDomainName\n }\n return .domain(endpoint)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5EndpointReader.swift
Socks5EndpointReader.swift
Swift
4,150
0.95
0.064516
0.22449
react-lib
631
2024-09-14T22:38:16.413068
MIT
false
f027ec4a8d11a85d61c3701d8a7ace85
//\n// Socks5Error.swift\n// MullvadTransport\n//\n// Created by pronebird on 21/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// The errors returned by objects implementing socks proxy.\npublic enum Socks5Error: Error, Sendable {\n /// Unexpected end of stream.\n case unexpectedEndOfStream\n\n /// Failure to decode the domain name from byte stream into utf8 string.\n case decodeDomainName\n\n /// Failure to parse IPv4 address from raw data.\n case parseIPv4Address\n\n /// Failure to parse IPv6 address from raw data.\n case parseIPv6Address\n\n /// Server replied with invalid socks version.\n case invalidSocksVersion\n\n /// Server replied with unknown endpoint address type.\n case invalidAddressType\n\n /// Invalid (unassigned) status code is returned.\n case invalidStatusCode(UInt8)\n\n /// Server replied with unsupported authentication method.\n case unsupportedAuthMethod\n\n /// Invalid username or password was provided to the server\n case invalidUsernameOrPassword\n\n /// None of the auth methods listed by the client are acceptable.\n case unacceptableAuthMethods\n\n /// Connection request is rejected.\n case connectionRejected(Socks5StatusCode)\n\n /// Failure to instantiate a TCP listener.\n case createTcpListener(Error)\n\n /// Socks forwarding proxy was cancelled during startup.\n case cancelledDuringStartup\n\n /// Local connection failure.\n case localConnectionFailure(NWError)\n\n /// Remote connection failure.\n case remoteConnectionFailure(NWError)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Error.swift
Socks5Error.swift
Swift
1,536
0.95
0
0.536585
vue-tools
256
2024-05-12T02:15:48.347091
MIT
false
6820e2ea70a6daaa1bdc340c7b24019e
//\n// Socks5ForwardingProxy.swift\n// MullvadTransport\n//\n// Created by pronebird on 18/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/**\n The proxy that can forward data connection from local TCP port to remote TCP server over the socks proxy.\n\n The forwarding socks proxy acts as a transparent proxy. The HTTP/S clients that don't support proxy configuration can be configured to direct their traffic at the\n local TCP port opened by the forwarding socks proxy.\n\n The forwarding proxy then takes care of negotiating with the remote socks proxy and transparently handles all traffic as if the HTTP/S client talks directly to the remote\n server.\n\n Refer to RFC1928 for more info on socks5: <https://datatracker.ietf.org/doc/html/rfc1928>\n */\npublic final class Socks5ForwardingProxy: Sendable {\n /// Socks proxy endpoint.\n public let socksProxyEndpoint: NWEndpoint\n\n /// Remote server that socks proxy should connect to.\n public let remoteServerEndpoint: Socks5Endpoint\n\n public let configuration: Socks5Configuration\n\n /// Local TCP port that clients should use to communicate with the remote server.\n /// This property is set once the proxy is successfully started.\n public var listenPort: UInt16? {\n queue.sync {\n switch state {\n case let .started(listener, _):\n return listener.port?.rawValue\n case .stopped, .starting:\n return nil\n }\n }\n }\n\n /**\n Initializes a socks forwarding proxy accepting connections on local TCP port and establishing connection to the remote endpoint over socks proxy.\n\n - Parameters:\n - socksProxyEndpoint: socks proxy endpoint.\n - remoteServerEndpoint: remote server that socks proxy should connect to.\n */\n public init(\n socksProxyEndpoint: NWEndpoint,\n remoteServerEndpoint: Socks5Endpoint,\n configuration: Socks5Configuration\n ) {\n self.socksProxyEndpoint = socksProxyEndpoint\n self.remoteServerEndpoint = remoteServerEndpoint\n self.configuration = configuration\n }\n\n deinit {\n stopInner()\n }\n\n /**\n Start forwarding proxy.\n\n Repeat calls do nothing, but accumulate the completion handler for invocation once the proxy moves to the next state.\n\n - Parameter completion: completion handler that is called once the TCP listener is ready in the first time or failed before moving to the ready state.\n Invoked on main queue.\n */\n public func start(completion: @escaping @Sendable (Error?) -> Void) {\n queue.async {\n self.startListener { error in\n DispatchQueue.main.async {\n completion(error)\n }\n }\n }\n }\n\n /**\n Stop forwarding proxy.\n\n - Parameter completion: completion handler that's called immediately after cancelling the TCP listener. Invoked on main queue.\n */\n public func stop(completion: (@Sendable () -> Void)? = nil) {\n queue.async {\n self.stopInner()\n\n DispatchQueue.main.async {\n completion?()\n }\n }\n }\n\n /**\n Set error handler to receive unrecoverable errors at runtime.\n\n - Parameter errorHandler: an error handler block. Invoked on main queue.\n */\n public func setErrorHandler(_ errorHandler: (@Sendable (Error) -> Void)?) {\n queue.async {\n self.errorHandler = errorHandler\n }\n }\n\n // MARK: - Private\n\n private enum State: @unchecked Sendable {\n /// Proxy is starting up.\n case starting(listener: NWListener, completion: (Error?) -> Void)\n\n /// Proxy is ready.\n case started(listener: NWListener, openConnections: [Socks5Connection])\n\n /// Proxy is not running.\n case stopped\n }\n\n private let queue = DispatchQueue(label: "Socks5ForwardingProxy-queue")\n nonisolated(unsafe) private var state: State = .stopped\n nonisolated(unsafe) private var errorHandler: (@Sendable (Error) -> Void)?\n\n /**\n Start TCP listener.\n\n - Parameter completion: completion handler that is called once the TCP listener is ready or failed.\n */\n private func startListener(completion: @escaping @Sendable (Error?) -> Void) {\n switch state {\n case .started:\n completion(nil)\n\n case let .starting(listener, previousCompletion):\n // Accumulate completion handlers when requested to start multiple times in a row.\n self.state = .starting(listener: listener, completion: { error in\n previousCompletion(error)\n completion(error)\n })\n\n case .stopped:\n do {\n let tcpListener = try makeTCPListener()\n state = .starting(listener: tcpListener, completion: completion)\n tcpListener.start(queue: queue)\n } catch {\n completion(Socks5Error.createTcpListener(error))\n }\n }\n }\n\n /**\n Create new TCP listener.\n\n - Throws: an instance of `NWError` if unable to initialize `NWListener`.\n - Returns: a configured instance of `NWListener`.\n */\n private func makeTCPListener() throws -> NWListener {\n let tcpListener = try NWListener(using: .tcp)\n tcpListener.stateUpdateHandler = { [weak self] state in\n self?.onListenerState(state)\n }\n tcpListener.newConnectionHandler = { [weak self] connection in\n self?.onNewConnection(connection)\n }\n return tcpListener\n }\n\n /**\n Reset block handlers and cancel an instance of `NWListener`.\n\n - Parameter tcpListener: an instance of `NWListener`.\n */\n private func cancelListener(_ tcpListener: NWListener) {\n tcpListener.stateUpdateHandler = nil\n tcpListener.newConnectionHandler = nil\n tcpListener.cancel()\n }\n\n private func stopInner() {\n switch state {\n case let .starting(listener, completion):\n state = .stopped\n cancelListener(listener)\n DispatchQueue.main.async {\n completion(Socks5Error.cancelledDuringStartup)\n }\n\n case let .started(listener, openConnections):\n state = .stopped\n cancelListener(listener)\n openConnections.forEach { $0.cancel() }\n\n case .stopped:\n break\n }\n }\n\n private func onReady() {\n switch state {\n case let .starting(listener, completion):\n state = .started(listener: listener, openConnections: [])\n\n DispatchQueue.main.async {\n completion(nil)\n }\n\n case .started, .stopped:\n break\n }\n }\n\n private func onFailure(_ error: Error) {\n switch state {\n case let .starting(_, completion):\n state = .stopped\n\n DispatchQueue.main.async {\n completion(error)\n }\n\n case .started:\n state = .stopped\n DispatchQueue.main.async {\n self.errorHandler?(error)\n }\n\n case .stopped:\n break\n }\n }\n\n private func onListenerState(_ listenerState: NWListener.State) {\n switch listenerState {\n case .setup, .cancelled:\n break\n\n case .ready:\n onReady()\n\n case let .failed(error), let .waiting(error):\n onFailure(error)\n\n @unknown default:\n break\n }\n }\n\n private func onNewConnection(_ connection: NWConnection) {\n switch state {\n case .starting, .stopped:\n connection.cancel()\n\n case .started(let listener, var openConnections):\n let socks5Connection = Socks5Connection(\n queue: queue,\n localConnection: connection,\n socksProxyEndpoint: socksProxyEndpoint,\n remoteServerEndpoint: remoteServerEndpoint,\n configuration: configuration\n )\n socks5Connection.setStateHandler { [weak self] socks5Connection, state in\n if case let .stopped(error) = state {\n self?.onEndConnection(socks5Connection, error: error)\n }\n }\n\n openConnections.append(socks5Connection)\n state = .started(listener: listener, openConnections: openConnections)\n\n socks5Connection.start()\n }\n }\n\n private func onEndConnection(_ connection: Socks5Connection, error: Error?) {\n switch state {\n case .stopped, .starting:\n break\n\n case .started(let listener, var openConnections):\n guard let index = openConnections.firstIndex(where: { $0 === connection }) else { return }\n\n openConnections.remove(at: index)\n state = .started(listener: listener, openConnections: openConnections)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5ForwardingProxy.swift
Socks5ForwardingProxy.swift
Swift
8,981
0.95
0.058824
0.131356
python-kit
238
2023-10-27T15:20:08.836911
MIT
false
00eb224979e0e79f33c3b786c3788d2f
//\n// Socks5Handshake.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\n\n/// Handshake initiation message.\nstruct Socks5Handshake {\n /// Authentication methods supported by the client.\n /// Defaults to `.notRequired` when empty.\n var methods: [Socks5AuthenticationMethod] = []\n\n /// The byte representation in socks protocol.\n var rawData: Data {\n var data = Data()\n var methods = methods\n\n // Make sure to provide at least one supported authentication method.\n if methods.isEmpty {\n methods.append(.notRequired)\n }\n\n // Append socks version\n data.append(Socks5Constants.socksVersion)\n\n // Append number of suppported authentication methods supported.\n data.append(UInt8(methods.count))\n\n // Append authentication methods\n data.append(contentsOf: methods.map { $0.rawValue })\n\n return data\n }\n}\n\n/// Handshake reply message.\nstruct Socks5HandshakeReply {\n /// The authentication method accepted by the socks proxys.\n var method: Socks5AuthenticationMethod\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5Handshake.swift
Socks5Handshake.swift
Swift
1,120
0.95
0.023256
0.470588
node-utils
728
2023-07-17T08:04:19.133376
GPL-3.0
false
10928856893b0c70d3b754f184f665ed
//\n// Socks5HandshakeNegotiation.swift\n// MullvadTransport\n//\n// Created by pronebird on 20/10/2023.\n//\n\nimport Foundation\nimport Network\n\n/// The object handling a handshake negotiation with socks proxy.\nstruct Socks5HandshakeNegotiation: Sendable {\n let connection: NWConnection\n let handshake: Socks5Handshake\n let onComplete: @Sendable (Socks5HandshakeReply) -> Void\n let onFailure: @Sendable (Error) -> Void\n\n func perform() {\n connection.send(content: handshake.rawData, completion: .contentProcessed { [self] error in\n if let error {\n onFailure(Socks5Error.remoteConnectionFailure(error))\n } else {\n readReply()\n }\n })\n }\n\n private func readReply() {\n // The length of a handshake reply in bytes.\n let replyLength = 2\n\n connection.receive(exactLength: replyLength) { [self] data, _, _, error in\n if let error {\n onFailure(Socks5Error.remoteConnectionFailure(error))\n } else if let data {\n do {\n onComplete(try parseReply(data: data))\n } catch {\n onFailure(error)\n }\n } else {\n onFailure(Socks5Error.unexpectedEndOfStream)\n }\n }\n }\n\n private func parseReply(data: Data) throws -> Socks5HandshakeReply {\n var iterator = data.makeIterator()\n\n guard let version = iterator.next() else { throw Socks5Error.unexpectedEndOfStream }\n guard version == Socks5Constants.socksVersion else { throw Socks5Error.invalidSocksVersion }\n\n guard let rawMethod = iterator.next() else { throw Socks5Error.unexpectedEndOfStream }\n\n // The response code returned by the server when none of the auth methods listed by the client are acceptable.\n let authMethodsUnacceptableReplyCode: UInt8 = 0xff\n\n guard rawMethod != authMethodsUnacceptableReplyCode else {\n throw Socks5Error.unacceptableAuthMethods\n }\n\n guard let method = Socks5AuthenticationMethod(rawValue: rawMethod) else {\n throw Socks5Error.unsupportedAuthMethod\n }\n\n return Socks5HandshakeReply(method: method)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5HandshakeNegotiation.swift
Socks5HandshakeNegotiation.swift
Swift
2,252
0.95
0.073529
0.160714
vue-tools
669
2025-04-13T13:38:57.861048
GPL-3.0
false
118278412cbfc070400ee2bd5d9e7447
//\n// Socks5StatusCode.swift\n// MullvadTransport\n//\n// Created by pronebird on 19/10/2023.\n//\n\nimport Foundation\n\n/// Status code used in socks protocol.\npublic enum Socks5StatusCode: UInt8, Sendable {\n case succeeded = 0x00\n case failure = 0x01\n case connectionNotAllowedByRuleset = 0x02\n case networkUnreachable = 0x03\n case hostUnreachable = 0x04\n case connectionRefused = 0x05\n case ttlExpired = 0x06\n case commandNotSupported = 0x07\n case addressTypeNotSupported = 0x08\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5StatusCode.swift
Socks5StatusCode.swift
Swift
507
0.95
0
0.368421
node-utils
50
2024-03-13T14:49:05.943325
MIT
false
3a337b4b267a97842fda88b4fad92409
//\n// Socks5UsernamePasswordCommand.swift\n// MullvadREST\n//\n// Created by Marco Nikic on 2023-12-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/**\n The payload sent to the server is the following diagram\n +----+------+----------+------+----------+\n |VER | ULEN | UNAME | PLEN | PASSWD |\n +----+------+----------+------+----------+\n | 1 | 1 | 1 to 255 | 1 | 1 to 255 |\n +----+------+----------+------+----------+\n\n VER: The current version of this method, always 1\n ULEN: The length of `username`\n UNAME: The username\n PLEN: The length of `password`\n PASSWD: The password\n\n **/\nstruct Socks5UsernamePasswordCommand {\n let username: String\n let password: String\n\n var rawData: Data {\n var data = Data()\n guard username.count < UInt8.max,\n password.count < UInt8.max,\n let usernameData = username.data(using: .utf8),\n let passwordData = password.data(using: .utf8)\n else { return data }\n\n // Protocol version\n data.append(Socks5Constants.usernamePasswordAuthenticationProtocol)\n\n // Username length\n data.append(UInt8(username.count))\n\n // Username\n data.append(usernameData)\n\n // Password length\n data.append(UInt8(password.count))\n\n // Password\n data.append(passwordData)\n\n return data\n }\n}\n\n/**\n The expected answer payload looks like this\n +-----+--------+\n | VER | STATUS |\n +-----+--------+\n | 1 | 1 |\n +-----+--------+\n */\nstruct Socks5UsernamePasswordReply {\n let version: UInt8\n let status: Socks5StatusCode\n\n /// - Parameter data: The bytes read from the network connection sent by a socks5 server as a reply to a `Socks5UsernamePasswordCommand`.\n init?(from data: Data) {\n let expectedSize = MemoryLayout<Self>.size\n guard data.count == expectedSize else { return nil }\n var iterator = data.makeIterator()\n\n guard let readVersion = iterator.next(),\n readVersion == Socks5Constants.usernamePasswordAuthenticationProtocol else { return nil }\n self.version = readVersion\n\n guard let readStatus = iterator.next(),\n let statusCode = Socks5StatusCode(rawValue: readStatus) else { return nil }\n self.status = statusCode\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\Socks5UsernamePasswordCommand.swift
Socks5UsernamePasswordCommand.swift
Swift
2,327
0.95
0
0.25
python-kit
756
2024-12-17T16:03:29.720671
Apache-2.0
false
ae8930588e817a6bcf3eb711ade55cbb
//\n// URLSessionSocks5Transport.swift\n// MullvadTransport\n//\n// Created by pronebird on 23/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\n\n/// Transport that passes URL requests over the local socks forwarding proxy.\npublic final class URLSessionSocks5Transport: RESTTransport, Sendable {\n /// Socks5 forwarding proxy.\n private let socksProxy: Socks5ForwardingProxy\n\n /// The IPv4 representation of the loopback address used by `socksProxy`.\n private let localhost = "127.0.0.1"\n\n /// The `URLSession` used to send requests via `socksProxy`.\n public let urlSession: URLSession\n\n public var name: String {\n "socks5-url-session"\n }\n\n nonisolated(unsafe) private let logger = Logger(label: "URLSessionSocks5Transport")\n\n /**\n Instantiates new socks5 transport.\n\n - Parameters:\n - urlSession: an instance of URLSession used for sending requests.\n - configuration: SOCKS5 configuration\n - addressCache: an address cache\n */\n public init(\n urlSession: URLSession,\n configuration: Socks5Configuration,\n addressCache: REST.AddressCache\n ) {\n self.urlSession = urlSession\n\n let apiAddress = addressCache.getCurrentEndpoint()\n\n socksProxy = Socks5ForwardingProxy(\n socksProxyEndpoint: configuration.proxyEndpoint.nwEndpoint,\n remoteServerEndpoint: apiAddress.socksEndpoint,\n configuration: configuration\n )\n\n socksProxy.setErrorHandler { [weak self] error in\n self?.logger.error(error: error, message: "Socks proxy failed at runtime.")\n }\n }\n\n public func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n // Listen port should be set when socks proxy is ready. Otherwise start proxy and only then start the data task.\n if let localPort = socksProxy.listenPort {\n return startDataTask(request: request, localPort: localPort, completion: completion)\n } else {\n return sendDeferred(request: request, completion: completion)\n }\n }\n\n /// Starts socks proxy then executes the data task.\n private func sendDeferred(\n request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n nonisolated(unsafe) let chain = CancellableChain()\n\n socksProxy.start { [weak self, weak socksProxy] error in\n if let error {\n completion(nil, nil, error)\n } else if let self, let localPort = socksProxy?.listenPort {\n let token = self.startDataTask(request: request, localPort: localPort, completion: completion)\n\n // Propagate cancellation from the chain to the data task cancellation token.\n chain.link(token)\n } else {\n completion(nil, nil, URLError(.cancelled))\n }\n }\n\n return chain\n }\n\n /// Execute data task, rewriting the original URLRequest to communicate over the socks proxy listening on the local TCP port.\n private func startDataTask(\n request: URLRequest,\n localPort: UInt16,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n // Copy the URL request and rewrite the host and port to point to the socks5 forwarding proxy instance\n var newRequest = request\n\n newRequest.url = request.url.flatMap { url in\n var components = URLComponents(url: url, resolvingAgainstBaseURL: false)\n components?.host = localhost\n components?.port = Int(localPort)\n return components?.url\n }\n\n let dataTask = urlSession.dataTask(with: newRequest, completionHandler: completion)\n dataTask.resume()\n return dataTask\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadREST\Transport\Socks5\URLSessionSocks5Transport.swift
URLSessionSocks5Transport.swift
Swift
3,993
0.95
0.044248
0.191489
vue-tools
443
2024-06-14T16:39:25.311163
Apache-2.0
false
c93b29bacc2fbca351dfdd536a685ca6
//\n// ShadowsocksLoaderStub.swift\n// MullvadRESTTests\n//\n// Created by Mojgan on 2024-01-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadREST\nimport MullvadSettings\nimport MullvadTypes\n\nstruct ShadowsocksLoaderStub: ShadowsocksLoaderProtocol {\n var configuration: ShadowsocksConfiguration\n var error: Error?\n\n func clear() throws {\n try load()\n }\n\n @discardableResult\n func load() throws -> ShadowsocksConfiguration {\n if let error { throw error }\n return configuration\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRESTTests\ShadowsocksLoaderStub.swift
ShadowsocksLoaderStub.swift
Swift
581
0.95
0.074074
0.304348
node-utils
289
2024-05-26T12:05:46.201640
Apache-2.0
true
884f80385ec762b3302050b5bf4ace90
//\n// AnyTransport.swift\n// MullvadRESTTests\n//\n// Created by pronebird on 25/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@preconcurrency import Foundation\n@testable import MullvadREST\nimport MullvadTypes\n\n/// Mock implementation of REST transport that can be used to handle requests without doing any actual networking.\nclass AnyTransport: RESTTransport, @unchecked Sendable {\n typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void\n\n private let handleRequest: () -> AnyResponse\n\n private let completionLock = NSLock()\n private var completionHandlers: [UUID: CompletionHandler] = [:]\n\n init(block: @escaping @Sendable () -> AnyResponse) {\n handleRequest = block\n }\n\n var name: String {\n return "any-transport"\n }\n\n func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n let response = handleRequest()\n let id = storeCompletion(completionHandler: completion)\n\n let dispatchWork = DispatchWorkItem {\n let data = (try? response.encode()) ?? Data()\n let httpResponse = HTTPURLResponse(\n url: request.url!,\n statusCode: response.statusCode,\n httpVersion: "1.0",\n headerFields: [:]\n )!\n self.sendCompletion(requestID: id, completion: .success((data, httpResponse)))\n }\n\n DispatchQueue.global().asyncAfter(deadline: .now() + response.delay, execute: dispatchWork)\n\n return AnyCancellable {\n dispatchWork.cancel()\n\n self.sendCompletion(requestID: id, completion: .failure(URLError(.cancelled)))\n }\n }\n\n private func storeCompletion(completionHandler: @escaping CompletionHandler) -> UUID {\n return completionLock.withLock {\n let id = UUID()\n completionHandlers[id] = completionHandler\n return id\n }\n }\n\n private func sendCompletion(requestID: UUID, completion: Result<(Data, URLResponse), Error>) {\n let complationHandler = completionLock.withLock {\n return completionHandlers.removeValue(forKey: requestID)\n }\n switch completion {\n case let .success((data, response)):\n complationHandler?(data, response, nil)\n case let .failure(error):\n complationHandler?(nil, nil, error)\n }\n }\n}\n\nstruct Response<T: Encodable>: AnyResponse {\n var delay: TimeInterval\n var statusCode: Int\n var value: T\n\n func encode() throws -> Data {\n return try REST.Coding.makeJSONEncoder().encode(value)\n }\n}\n\nprotocol AnyResponse {\n var delay: TimeInterval { get }\n var statusCode: Int { get }\n\n func encode() throws -> Data\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRESTTests\Mocks\AnyTransport.swift
AnyTransport.swift
Swift
2,820
0.95
0.043011
0.105263
vue-tools
766
2023-12-14T17:09:32.724028
GPL-3.0
true
bbea50f11c5ff56d8cd6a4e2ff7fb965
//\n// MemoryCache.swift\n// MullvadRESTTests\n//\n// Created by pronebird on 25/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadREST\nimport MullvadTypes\n\n/// Mock implementation of a static memory cache passed to `AddressCache`.\n/// Since we don't do any actual networking in tests, the IP endpoint returned from cache is not important.\nstruct MemoryCache: FileCacheProtocol {\n func read() throws -> REST.StoredAddressCache {\n return .init(updatedAt: .distantFuture, endpoint: .ipv4(IPv4Endpoint(ip: .loopback, port: 80)))\n }\n\n func write(_ content: REST.StoredAddressCache) throws {}\n\n func clear() throws {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRESTTests\Mocks\MemoryCache.swift
MemoryCache.swift
Swift
697
0.95
0
0.473684
python-kit
217
2025-05-31T01:46:22.748797
MIT
true
3c4851c82fc0c887da7313399b77a9ba
//\n// RESTTransportStub.swift\n// MullvadRESTTests\n//\n// Created by Marco Nikic on 2024-01-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@testable import MullvadREST\n@testable import MullvadTypes\nimport XCTest\n\nstruct RESTTransportStub: RESTTransport {\n let name = "transport-stub"\n\n var data: Data?\n var response: URLResponse?\n var error: Error?\n\n func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n completion(data, response, error)\n return AnyCancellable()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRESTTests\Mocks\RESTTransportStub.swift
RESTTransportStub.swift
Swift
619
0.95
0
0.304348
vue-tools
518
2023-08-10T04:21:00.150583
GPL-3.0
true
78503fd9571e755246a365b24af8451f
//\n// TimeServerProxy.swift\n// MullvadRESTTests\n//\n// Created by pronebird on 25/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadREST\n\n/// Simple API proxy used for testing purposes.\nfinal class TimeServerProxy: REST.Proxy<REST.ProxyConfiguration>, @unchecked Sendable {\n init(configuration: REST.ProxyConfiguration) {\n super.init(\n name: "TimeServerProxy",\n configuration: configuration,\n requestFactory: REST.RequestFactory.withDefaultAPICredentials(\n pathPrefix: "",\n bodyEncoder: REST.Coding.makeJSONEncoder()\n ),\n responseDecoder: REST.Coding.makeJSONDecoder()\n )\n }\n\n func getDateTime() -> any RESTRequestExecutor<TimeResponse> {\n let requestHandler = REST.AnyRequestHandler { endpoint in\n return try self.requestFactory.createRequest(endpoint: endpoint, method: .get, pathTemplate: "date-time")\n }\n let responseHandler = REST.defaultResponseHandler(decoding: TimeResponse.self, with: responseDecoder)\n\n return makeRequestExecutor(\n name: "get-date-time",\n requestHandler: requestHandler,\n responseHandler: responseHandler\n )\n }\n}\n\nstruct TimeResponse: Codable {\n var dateTime: Date\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRESTTests\Mocks\TimeServerProxy.swift
TimeServerProxy.swift
Swift
1,353
0.95
0.071429
0.216216
awesome-app
379
2024-02-18T10:52:44.604092
BSD-3-Clause
true
ad17b8e8728ebcf9e2194c82fb48502a
//\n// EncryptedDNSProxy.swift\n// MullvadRustRuntime\n//\n// Created by Emils on 24/09/2024.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntimeProxy\n\npublic enum EncryptedDnsProxyError: Error {\n case start(err: Int32)\n}\n\npublic class EncryptedDNSProxy {\n private var proxyConfig: ProxyHandle\n private var stateLock = NSLock()\n private var didStart = false\n private let state: OpaquePointer\n private let domain: String\n\n public init(domain: String) {\n self.domain = domain\n state = encrypted_dns_proxy_init(domain)\n proxyConfig = ProxyHandle(context: nil, port: 0)\n }\n\n public func localPort() -> UInt16 {\n stateLock.lock()\n defer { stateLock.unlock() }\n return proxyConfig.port\n }\n\n public func start() throws {\n stateLock.lock()\n defer { stateLock.unlock() }\n guard didStart == false else { return }\n\n let err = encrypted_dns_proxy_start(state, &proxyConfig)\n if err != 0 {\n throw EncryptedDnsProxyError.start(err: err)\n }\n didStart = true\n }\n\n public func stop() {\n stateLock.lock()\n defer { stateLock.unlock() }\n guard didStart == true else { return }\n didStart = false\n\n encrypted_dns_proxy_stop(&proxyConfig)\n }\n\n deinit {\n if didStart {\n encrypted_dns_proxy_stop(&proxyConfig)\n }\n\n encrypted_dns_proxy_free(state)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\EncryptedDNSProxy.swift
EncryptedDNSProxy.swift
Swift
1,498
0.95
0.047619
0.134615
react-lib
946
2025-06-17T04:49:33.390026
Apache-2.0
false
b1680c23d32d1cfb6656291d18546e72
//\n// EphemeralPeerExchangeActor.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 EphemeralPeerExchangeActorProtocol {\n func startNegotiation(with privateKey: PrivateKey, enablePostQuantum: Bool, enableDaita: Bool)\n func endCurrentNegotiation()\n func reset()\n}\n\npublic class EphemeralPeerExchangeActor: EphemeralPeerExchangeActorProtocol {\n struct Negotiation {\n var negotiator: EphemeralPeerNegotiating\n\n func cancel() {\n negotiator.cancelKeyNegotiation()\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: EphemeralPeerNegotiating.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: EphemeralPeerNegotiating.Type = EphemeralPeerNegotiator.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 /// 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, enablePostQuantum: Bool, enableDaita: Bool) {\n endCurrentNegotiation()\n let negotiator = negotiationProvider.init()\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 let peerParameters = EphemeralPeerParameters(\n peer_exchange_timeout: UInt64(tcpConnectionTimeout.timeInterval),\n enable_post_quantum: enablePostQuantum,\n enable_daita: enableDaita,\n funcs: mapWgFunctions(functions: packetTunnel.wgFunctions())\n )\n\n if !negotiator.startNegotiation(\n devicePublicKey: privateKey.publicKey,\n presharedKey: ephemeralSharedKey,\n peerReceiver: packetTunnel,\n ephemeralPeerParams: peerParameters\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 )\n }\n\n private func mapWgFunctions(functions: WgFunctionPointers) -> WgTcpConnectionFunctions {\n var mappedFunctions = WgTcpConnectionFunctions()\n\n mappedFunctions.close_fn = functions.close\n mappedFunctions.open_fn = functions.open\n mappedFunctions.send_fn = functions.send\n mappedFunctions.recv_fn = functions.receive\n\n return mappedFunctions\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
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\EphemeralPeerExchangeActor.swift
EphemeralPeerExchangeActor.swift
Swift
4,167
0.95
0.043103
0.212121
vue-tools
420
2025-05-07T11:50:19.857523
GPL-3.0
false
a4f4e64a838c5917ab02b527efd3af9f
//\n// PostQuantumKeyNegotiator.swift\n// PacketTunnel\n//\n// Created by Marco Nikic on 2024-02-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport NetworkExtension\nimport WireGuardKitTypes\n\npublic protocol EphemeralPeerNegotiating {\n func startNegotiation(\n devicePublicKey: PublicKey,\n presharedKey: PrivateKey,\n peerReceiver: any TunnelProvider,\n ephemeralPeerParams: EphemeralPeerParameters\n ) -> Bool\n\n func cancelKeyNegotiation()\n\n init()\n}\n\n/// Requests an ephemeral peer asynchronously.\npublic class EphemeralPeerNegotiator: EphemeralPeerNegotiating {\n required public init() {}\n\n var cancelToken: OpaquePointer?\n\n public func startNegotiation(\n devicePublicKey: PublicKey,\n presharedKey: PrivateKey,\n peerReceiver: any TunnelProvider,\n ephemeralPeerParams: EphemeralPeerParameters\n ) -> Bool {\n // swiftlint:disable:next force_cast\n let ephemeralPeerReceiver = Unmanaged.passUnretained(peerReceiver as! EphemeralPeerReceiver)\n .toOpaque()\n\n guard let tunnelHandle = try? peerReceiver.tunnelHandle() else {\n return false\n }\n\n let cancelToken = request_ephemeral_peer(\n devicePublicKey.rawValue.map { $0 },\n presharedKey.rawValue.map { $0 },\n ephemeralPeerReceiver,\n tunnelHandle,\n ephemeralPeerParams\n )\n guard let cancelToken else {\n return false\n }\n self.cancelToken = cancelToken\n return true\n }\n\n public func cancelKeyNegotiation() {\n guard let cancelToken else { return }\n cancel_ephemeral_peer_exchange(cancelToken)\n self.cancelToken = nil\n }\n\n deinit {\n guard let cancelToken else { return }\n drop_ephemeral_peer_exchange_token(cancelToken)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\EphemeralPeerNegotiator.swift
EphemeralPeerNegotiator.swift
Swift
1,909
0.95
0.028169
0.15
awesome-app
313
2024-04-29T16:58:23.344047
Apache-2.0
false
c3729450082f88692ea2e6aaf8c61a4c
//\n// EphemeralPeerReceiver.swift\n// PacketTunnel\n//\n// Created by Marco Nikic on 2024-02-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntimeProxy\nimport MullvadTypes\nimport NetworkExtension\nimport WireGuardKitTypes\n\n/// End sequence of an ephemeral peer exchange.\n///\n/// This FFI function is called by Rust when an ephemeral peer negotiation succeeded or failed.\n/// When both the `rawPresharedKey` and the `rawEphemeralKey` are raw pointers to 32 bytes data arrays,\n/// the quantum-secure key exchange is considered successful.\n/// If the `rawPresharedKey` is nil, but there is a valid `rawEphemeralKey`, it means a Daita peer has been negotiated with.\n/// If `rawEphemeralKey` is nil, the negotiation is considered failed.\n///\n/// - Parameters:\n/// - rawEphemeralPeerReceiver: A raw pointer to the running instance of `NEPacketTunnelProvider`\n/// - rawPresharedKey: A raw pointer to the quantum-secure pre shared key\n/// - rawEphemeralKey: A raw pointer to the ephemeral private key of the device\n/// - rawDaitaParameters: A raw pointer to negotiated DAITA parameters\n@_silgen_name("swift_ephemeral_peer_ready")\nfunc receivePostQuantumKey(\n rawEphemeralPeerReceiver: UnsafeMutableRawPointer?,\n rawPresharedKey: UnsafeMutableRawPointer?,\n rawEphemeralKey: UnsafeMutableRawPointer?,\n rawDaitaParameters: UnsafePointer<DaitaV2Parameters>?\n) {\n guard let rawEphemeralPeerReceiver else { return }\n let ephemeralPeerReceiver = Unmanaged<EphemeralPeerReceiver>.fromOpaque(rawEphemeralPeerReceiver)\n .takeUnretainedValue()\n\n // If there are no private keys for the ephemeral peer, then the negotiation either failed, or timed out.\n guard let rawEphemeralKey,\n let ephemeralKey = PrivateKey(rawValue: Data(bytes: rawEphemeralKey, count: 32)) else {\n ephemeralPeerReceiver.ephemeralPeerExchangeFailed()\n return\n }\n\n let maybeNot = Maybenot()\n let daitaParameters: DaitaV2Parameters? = rawDaitaParameters?.withMemoryRebound(\n to: DaitaParameters.self,\n capacity: 1\n ) { body in\n let params = body.pointee\n guard params.machines != nil else { return nil }\n let machines = String(cString: params.machines)\n return DaitaV2Parameters(\n machines: machines,\n maximumEvents: maybeNot.maximumEvents,\n maximumActions: maybeNot.maximumActions,\n maximumPadding: params.max_padding_frac,\n maximumBlocking: params.max_blocking_frac\n )\n }\n\n // If there is a pre-shared key, an ephemeral peer was negotiated with Post Quantum options\n // Otherwise, a Daita enabled ephemeral peer was requested\n if let rawPresharedKey, let key = PreSharedKey(rawValue: Data(bytes: rawPresharedKey, count: 32)) {\n ephemeralPeerReceiver.receivePostQuantumKey(key, ephemeralKey: ephemeralKey, daitaParameters: daitaParameters)\n } else {\n ephemeralPeerReceiver.receiveEphemeralPeerPrivateKey(ephemeralKey, daitaParameters: daitaParameters)\n }\n return\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\EphemeralPeerReceiver.swift
EphemeralPeerReceiver.swift
Swift
3,085
0.95
0.042254
0.348485
node-utils
635
2025-04-13T20:47:00.585315
Apache-2.0
false
baf4c82e2989f0845654072127c86fc6
//\n// MullvadApiCancellable.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-02-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\n\npublic class MullvadApiCancellable: Cancellable {\n private let handle: SwiftCancelHandle\n\n public init(handle: consuming SwiftCancelHandle) {\n self.handle = handle\n }\n\n deinit {\n mullvad_api_cancel_task_drop(handle)\n }\n\n public func cancel() {\n mullvad_api_cancel_task(handle)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\MullvadApiCancellable.swift
MullvadApiCancellable.swift
Swift
505
0.95
0.04
0.35
awesome-app
342
2023-07-30T04:34:32.879797
GPL-3.0
false
27611230be6f7647225d131d9d3020a1
//\n// MullvadApiCompletion.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-01-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@_silgen_name("mullvad_api_completion_finish")\nfunc mullvadApiCompletionFinish(\n response: SwiftMullvadApiResponse,\n completionCookie: UnsafeMutableRawPointer\n) {\n let completionBridge = Unmanaged<MullvadApiCompletion>\n .fromOpaque(completionCookie)\n .takeRetainedValue()\n let apiResponse = MullvadApiResponse(response: response)\n\n completionBridge.completion(apiResponse)\n}\n\npublic class MullvadApiCompletion {\n public var completion: (MullvadApiResponse) -> Void\n\n public init(completion: @escaping ((MullvadApiResponse) -> Void)) {\n self.completion = completion\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\MullvadApiCompletion.swift
MullvadApiCompletion.swift
Swift
774
0.95
0.035714
0.291667
react-lib
581
2023-09-26T03:48:08.476014
GPL-3.0
false
e6f9c193901fa5f2bbc965ab0fee5e90
//\n// MullvadApiContext.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-01-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\n\npublic struct MullvadApiContext: Sendable {\n enum MullvadApiContextError: Error {\n case failedToConstructApiClient\n }\n\n public let context: SwiftApiContext\n\n public init(host: String, address: AnyIPEndpoint, disable_tls: Bool = false) throws {\n context = switch disable_tls {\n case true:\n mullvad_api_init_new_tls_disabled(host, address.description)\n case false:\n mullvad_api_init_new(host, address.description)\n }\n\n if context._0 == nil {\n throw MullvadApiContextError.failedToConstructApiClient\n }\n }\n}\n\nextension SwiftApiContext: @unchecked @retroactive Sendable {}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\MullvadApiContext.swift
MullvadApiContext.swift
Swift
843
0.95
0.0625
0.269231
vue-tools
841
2024-12-17T19:39:32.447091
Apache-2.0
false
22d4521e71f733f3cb5c4585885d990d
//\n// MullvadApiResponse.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-01-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic class MullvadApiResponse {\n private let response: SwiftMullvadApiResponse\n\n public init(response: consuming SwiftMullvadApiResponse) {\n self.response = response\n }\n\n deinit {\n mullvad_response_drop(response)\n }\n\n public var body: Data? {\n guard let body = response.body else {\n return nil\n }\n\n return Data(UnsafeBufferPointer(start: body, count: Int(response.body_size)))\n }\n\n public var etag: String? {\n return if response.etag == nil {\n nil\n } else {\n String(cString: response.etag)\n }\n }\n\n public var errorDescription: String? {\n return if response.error_description == nil {\n nil\n } else {\n String(cString: response.error_description)\n }\n }\n\n public var statusCode: UInt16 {\n response.status_code\n }\n\n public var serverResponseCode: String? {\n return if response.server_response_code == nil {\n nil\n } else {\n String(cString: response.server_response_code)\n }\n }\n\n public var success: Bool {\n response.success\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\MullvadApiResponse.swift
MullvadApiResponse.swift
Swift
1,322
0.95
0.067797
0.142857
node-utils
847
2024-12-08T15:35:17.787274
BSD-3-Clause
false
30e657e1adac6bbdda5caff087e00629
//\n// RustProblemReportRequest.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-03-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport MullvadLogging\nimport MullvadTypes\n\nfinal public class RustProblemReportRequest {\n private let logger = Logger(label: "RustProblemReportRequest")\n private let addressPointer: UnsafePointer<CChar>?\n private let messagePointer: UnsafePointer<CChar>?\n private let logPointer: UnsafePointer<CChar>?\n private let problemReportMetaData: ProblemReportMetadata\n\n public init(from request: ProblemReportRequest) {\n self.problemReportMetaData = swift_problem_report_metadata_new()\n self.addressPointer = request.address.toCStringPointer()\n self.messagePointer = request.message.toCStringPointer()\n self.logPointer = request.log.toCStringPointer()\n\n for (key, value) in request.metadata {\n let isAdded = swift_problem_report_metadata_add(problemReportMetaData, key, value)\n if !isAdded {\n logger\n .error("Failed to add metadata. Key: '\(key)' might be invalid or contain unsupported characters.")\n }\n }\n }\n\n public func toRust() -> SwiftProblemReportRequest {\n SwiftProblemReportRequest(\n address: addressPointer,\n message: messagePointer,\n log: logPointer,\n metadata: problemReportMetaData\n )\n }\n\n deinit {\n swift_problem_report_metadata_free(problemReportMetaData)\n addressPointer?.deallocate()\n messagePointer?.deallocate()\n logPointer?.deallocate()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\RustProblemReportRequest.swift
RustProblemReportRequest.swift
Swift
1,637
0.95
0.0625
0.162791
python-kit
779
2024-04-01T12:00:01.840820
GPL-3.0
false
5e0ff90e437e6a49c302caec41b5b251
//\n// ShadowsocksProxy.swift\n// MullvadREST\n//\n// Created by Emils on 19/04/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntimeProxy\nimport Network\n\n/// A Swift wrapper around a Rust implementation of Shadowsocks proxy instance\npublic class ShadowsocksProxy: @unchecked Sendable {\n private var proxyConfig: ProxyHandle\n private let forwardAddress: IPAddress\n private let forwardPort: UInt16\n private let bridgeAddress: IPAddress\n private let bridgePort: UInt16\n private let password: String\n private let cipher: String\n private var didStart = false\n private let stateLock = NSLock()\n\n public init(\n forwardAddress: IPAddress,\n forwardPort: UInt16,\n bridgeAddress: IPAddress,\n bridgePort: UInt16,\n password: String,\n cipher: String\n ) {\n proxyConfig = ProxyHandle(context: nil, port: 0)\n self.forwardAddress = forwardAddress\n self.forwardPort = forwardPort\n self.bridgeAddress = bridgeAddress\n self.bridgePort = bridgePort\n self.password = password\n self.cipher = cipher\n }\n\n /// The local port for the shadow socks proxy\n ///\n /// - Returns: The local port for the shadow socks proxy when it has started, 0 otherwise.\n public func localPort() -> UInt16 {\n stateLock.lock()\n defer { stateLock.unlock() }\n return proxyConfig.port\n }\n\n deinit {\n stop()\n }\n\n /// Starts the socks proxy\n public func start() {\n stateLock.lock()\n defer { stateLock.unlock() }\n guard didStart == false else { return }\n didStart = true\n\n // Get the raw bytes access to `proxyConfig`\n _ = withUnsafeMutablePointer(to: &proxyConfig) { config in\n start_shadowsocks_proxy(\n forwardAddress.rawValue.map { $0 },\n UInt(forwardAddress.rawValue.count),\n forwardPort,\n bridgeAddress.rawValue.map { $0 },\n UInt(bridgeAddress.rawValue.count),\n bridgePort,\n password,\n UInt(password.count),\n cipher,\n UInt(cipher.count),\n config\n )\n }\n }\n\n /// Stops the socks proxy\n public func stop() {\n stateLock.lock()\n defer { stateLock.unlock() }\n guard didStart == true else { return }\n didStart = false\n\n _ = withUnsafeMutablePointer(to: &proxyConfig) { config in\n stop_shadowsocks_proxy(config)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\ShadowSocksProxy.swift
ShadowSocksProxy.swift
Swift
2,604
0.95
0.032967
0.170732
node-utils
957
2024-01-19T11:09:56.618990
Apache-2.0
false
18283cc0e24aa333c639b30d7cd130bf
//\n// String+UnsafePointer.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-04-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension String {\n // Ensure the string is converted to a null-terminated C string\n // UnsafePointer provides no automated memory management or alignment guarantees.\n // The caller is responsible to manage the memory\n func toCStringPointer() -> UnsafePointer<CChar>? {\n // Convert the Swift string to a null-terminated UTF-8 C string\n guard let cString = cString(using: .utf8) else { return nil }\n\n // Allocate memory for characters + null terminator\n let pointer = UnsafeMutablePointer<CChar>.allocate(capacity: cString.count)\n\n // Copy the characters (including the null terminator)\n pointer.initialize(from: cString, count: cString.count)\n\n return UnsafePointer(pointer)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\String+UnsafePointer.swift
String+UnsafePointer.swift
Swift
915
0.95
0.037037
0.590909
vue-tools
132
2024-01-10T13:40:40.708478
BSD-3-Clause
false
f1b82d4f533d40e5c36b301573d62d26
//\n// TunnelObfuscator.swift\n// TunnelObfuscation\n//\n// Created by pronebird on 19/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadRustRuntimeProxy\nimport MullvadTypes\nimport Network\n\npublic enum TunnelObfuscationProtocol {\n case udpOverTcp\n case shadowsocks\n}\n\npublic protocol TunnelObfuscation {\n init(remoteAddress: IPAddress, tcpPort: UInt16, obfuscationProtocol: TunnelObfuscationProtocol)\n func start()\n func stop()\n var localUdpPort: UInt16 { get }\n var remotePort: UInt16 { get }\n\n var transportLayer: TransportLayer { get }\n}\n\n/// Class that implements obfuscation by accepting traffic on a local port and proxying it to the remote endpoint.\n///\n/// The obfuscation happens either by wrapping UDP traffic into TCP traffic, or by using a local shadowsocks server\n/// to encrypt the UDP traffic sent.\npublic final class TunnelObfuscator: TunnelObfuscation {\n private let stateLock = NSLock()\n private let remoteAddress: IPAddress\n internal let tcpPort: UInt16\n internal let obfuscationProtocol: TunnelObfuscationProtocol\n\n private var proxyHandle = ProxyHandle(context: nil, port: 0)\n private var isStarted = false\n\n /// Returns local UDP port used by proxy and bound to 127.0.0.1 (IPv4).\n /// The returned value can be zero if obfuscator hasn't started yet.\n public var localUdpPort: UInt16 {\n return stateLock.withLock { proxyHandle.port }\n }\n\n public var remotePort: UInt16 { tcpPort }\n\n public var transportLayer: TransportLayer {\n switch obfuscationProtocol {\n case .udpOverTcp:\n .tcp\n case .shadowsocks:\n .udp\n }\n }\n\n /// Initialize tunnel obfuscator with remote server address and TCP port where udp2tcp is running.\n public init(remoteAddress: IPAddress, tcpPort: UInt16, obfuscationProtocol: TunnelObfuscationProtocol) {\n self.remoteAddress = remoteAddress\n self.tcpPort = tcpPort\n self.obfuscationProtocol = obfuscationProtocol\n }\n\n deinit {\n stop()\n }\n\n public func start() {\n stateLock.withLock {\n guard !isStarted else { return }\n\n let obfuscationProtocol = switch obfuscationProtocol {\n case .udpOverTcp: TunnelObfuscatorProtocol(0)\n case .shadowsocks: TunnelObfuscatorProtocol(1)\n }\n\n let result = withUnsafeMutablePointer(to: &proxyHandle) { proxyHandlePointer in\n let addressData = remoteAddress.rawValue\n\n return start_tunnel_obfuscator_proxy(\n addressData.map { $0 },\n UInt(addressData.count),\n tcpPort,\n obfuscationProtocol,\n proxyHandlePointer\n )\n }\n\n assert(result == 0)\n\n isStarted = true\n }\n }\n\n public func stop() {\n stateLock.withLock {\n guard isStarted else { return }\n\n let result = withUnsafeMutablePointer(to: &proxyHandle) {\n stop_tunnel_obfuscator_proxy($0)\n }\n\n assert(result == 0)\n\n isStarted = false\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntime\TunnelObfuscator.swift
TunnelObfuscator.swift
Swift
3,220
0.95
0.036364
0.157303
python-kit
328
2025-03-17T15:20:56.454400
GPL-3.0
false
5f8c85693a1a4783a5799ccd43bb1496
//\n// MullvadPostQuantum+Stubs.swift\n// MullvadRustRuntimeTests\n//\n// Created by Marco Nikic on 2024-06-12.\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\nclass NWTCPConnectionStub: NWTCPConnection {\n var _isViable = false\n override var isViable: Bool {\n _isViable\n }\n\n func becomeViable() {\n willChangeValue(for: \.isViable)\n _isViable = true\n didChangeValue(for: \.isViable)\n }\n}\n\nclass TunnelProviderStub: TunnelProvider {\n func tunnelHandle() throws -> Int32 {\n 0\n }\n\n func wgFunctions() -> MullvadTypes.WgFunctionPointers {\n return MullvadTypes.WgFunctionPointers(\n open: { _, _, _ in return 0 },\n close: { _, _ in return 0 },\n receive: { _, _, _, _ in return 0 },\n send: { _, _, _, _ in return 0 }\n )\n }\n\n let tcpConnection: NWTCPConnectionStub\n\n init(tcpConnection: NWTCPConnectionStub) {\n self.tcpConnection = tcpConnection\n }\n\n func createTCPConnectionThroughTunnel(\n to remoteEndpoint: NWEndpoint,\n enableTLS: Bool,\n tlsParameters TLSParameters: NWTLSParameters?,\n delegate: Any?\n ) -> NWTCPConnection {\n tcpConnection\n }\n}\n\nclass FailedNegotiatorStub: EphemeralPeerNegotiating {\n var onCancelKeyNegotiation: (() -> Void)?\n\n required init() {\n onCancelKeyNegotiation = nil\n }\n\n init(onCancelKeyNegotiation: (() -> Void)? = nil) {\n self.onCancelKeyNegotiation = onCancelKeyNegotiation\n }\n\n func startNegotiation(\n devicePublicKey: WireGuardKitTypes.PublicKey,\n presharedKey: WireGuardKitTypes.PrivateKey,\n peerReceiver: any MullvadTypes.TunnelProvider,\n ephemeralPeerParams: EphemeralPeerParameters\n ) -> Bool {\n false\n }\n\n func cancelKeyNegotiation() {\n onCancelKeyNegotiation?()\n }\n}\n\nclass SuccessfulNegotiatorStub: EphemeralPeerNegotiating {\n var onCancelKeyNegotiation: (() -> Void)?\n required init() {\n onCancelKeyNegotiation = nil\n }\n\n init(onCancelKeyNegotiation: (() -> Void)? = nil) {\n self.onCancelKeyNegotiation = onCancelKeyNegotiation\n }\n\n func startNegotiation(\n devicePublicKey: WireGuardKitTypes.PublicKey,\n presharedKey: WireGuardKitTypes.PrivateKey,\n peerReceiver: any MullvadTypes.TunnelProvider,\n ephemeralPeerParams: EphemeralPeerParameters\n ) -> Bool {\n true\n }\n\n func cancelKeyNegotiation() {\n onCancelKeyNegotiation?()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntimeTests\MullvadPostQuantum+Stubs.swift
MullvadPostQuantum+Stubs.swift
Swift
2,689
0.95
0.057143
0.079545
awesome-app
609
2023-09-30T10:00:04.468223
Apache-2.0
true
ddb813b190b545d2976318773a970d76
//\n// TCPConnection.swift\n// MullvadRustRuntimeTests\n//\n// Created by pronebird on 27/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\n/// Minimal implementation of TCP connection capable of receiving data.\n/// > Warning: Do not use this implementation in production code. See the warning in `start()`.\nclass TCPConnection: Connection {\n private let dispatchQueue = DispatchQueue(label: "TCPConnection")\n private let nwConnection: NWConnection\n\n required init(nwConnection: NWConnection) {\n self.nwConnection = nwConnection\n }\n\n static var connectionParameters: NWParameters { .tcp }\n\n deinit {\n cancel()\n }\n\n /// Establishes the TCP connection.\n ///\n /// > Warning: This implementation is **not safe to use in production**\n /// It will cancel the `listener.stateUpdateHandler` after it becomes ready and ignore future updates.\n ///\n /// Waits for the underlying connection to become ready before returning control to the caller, otherwise throws an\n /// error if connection state indicates as such.\n func start() async throws {\n try await withCheckedThrowingContinuation { continuation in\n nwConnection.stateUpdateHandler = { state in\n switch state {\n case .ready:\n continuation.resume(returning: ())\n case let .failed(error):\n continuation.resume(throwing: error)\n case .cancelled:\n continuation.resume(throwing: CancellationError())\n default:\n return\n }\n // Reset state update handler after resuming continuation.\n self.nwConnection.stateUpdateHandler = nil\n }\n nwConnection.start(queue: dispatchQueue)\n }\n }\n\n func cancel() {\n nwConnection.cancel()\n }\n\n func receiveData(minimumLength: Int, maximumLength: Int) async throws -> Data {\n return try await withCheckedThrowingContinuation { continuation in\n nwConnection.receive(\n minimumIncompleteLength: minimumLength,\n maximumLength: maximumLength\n ) { content, _, isComplete, error in\n if let error {\n continuation.resume(throwing: error)\n } else if let content {\n continuation.resume(returning: content)\n } else if isComplete {\n continuation.resume(returning: Data())\n }\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntimeTests\TCPConnection.swift
TCPConnection.swift
Swift
2,614
0.95
0.12
0.253731
node-utils
393
2025-02-27T22:11:19.884423
MIT
true
5eec06be0e49a5fa0b22fb2e95a9e037
//\n// UDPConnection.swift\n// MullvadRustRuntimeTests\n//\n// Created by pronebird on 27/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\nprotocol Connection {\n init(nwConnection: NWConnection)\n static var connectionParameters: NWParameters { get }\n}\n\n/// Minimal implementation of UDP connection capable of sending data.\n/// > Warning: Do not use this implementation in production code. See the warning in `start()`.\nclass UDPConnection: Connection {\n private let dispatchQueue = DispatchQueue(label: "UDPConnection")\n private let nwConnection: NWConnection\n\n convenience init(remote: IPAddress, port: UInt16) {\n self.init(nwConnection: NWConnection(\n host: NWEndpoint.Host("\(remote)"),\n port: NWEndpoint.Port(integerLiteral: port),\n using: .udp\n ))\n }\n\n required init(nwConnection: NWConnection) {\n self.nwConnection = nwConnection\n }\n\n static var connectionParameters: NWParameters { .udp }\n\n deinit {\n cancel()\n }\n\n /// Establishes the UDP connection.\n ///\n /// > Warning: This implementation is **not safe to use in production**\n /// It will cancel the `listener.stateUpdateHandler` after it becomes ready and ignore future updates.\n ///\n /// Waits for the underlying connection to become ready before returning control to the caller, otherwise throws an\n /// error if connection state indicates as such.\n func start() async throws {\n return try await withCheckedThrowingContinuation { continuation in\n nwConnection.stateUpdateHandler = { state in\n switch state {\n case .ready:\n continuation.resume(returning: ())\n case let .failed(error):\n continuation.resume(throwing: error)\n case .cancelled:\n continuation.resume(throwing: CancellationError())\n default:\n return\n }\n // Reset state update handler after resuming continuation.\n self.nwConnection.stateUpdateHandler = nil\n }\n nwConnection.start(queue: dispatchQueue)\n }\n }\n\n func cancel() {\n nwConnection.cancel()\n }\n\n func readSingleDatagram() async throws -> Data {\n return try await withCheckedThrowingContinuation { continuation in\n nwConnection.receiveMessage { data, _, _, error in\n guard let data else {\n continuation.resume(throwing: POSIXError(.EIO))\n return\n }\n if let error {\n continuation.resume(throwing: error)\n return\n }\n continuation.resume(with: .success(data))\n }\n }\n }\n\n func sendData(_ data: Data) async throws {\n return try await withCheckedThrowingContinuation { continuation in\n nwConnection.send(content: data, completion: .contentProcessed { 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\MullvadRustRuntimeTests\UDPConnection.swift
UDPConnection.swift
Swift
3,300
0.95
0.090909
0.193182
python-kit
177
2024-11-02T19:48:58.121991
MIT
true
d21d6092fef5b008f8d6c26f55653fd4
//\n// UnsafeListener.swift\n// MullvadRustRuntimeTests\n//\n// Created by pronebird on 27/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Network\n\n/// > Warning: Do not use this implementation in production code. See the warning in `start()`.\nclass UnsafeListener<T: Connection>: @unchecked Sendable {\n private let dispatchQueue = DispatchQueue(label: "com.test.unsafeListener")\n private let listener: NWListener\n\n /// A stream of new connections.\n /// The caller may iterate over this stream to accept new connections.\n ///\n /// `Connection` objects are returned unopen, so the caller has to call `Connection.start()` to accept the\n /// connection before initiating the data exchange.\n let newConnections: AsyncStream<T>\n\n init() throws {\n let listener = try NWListener(using: T.connectionParameters)\n\n newConnections = AsyncStream { continuation in\n listener.newConnectionHandler = { nwConnection in\n continuation.yield(T(nwConnection: nwConnection))\n }\n continuation.onTermination = { @Sendable _ in\n listener.newConnectionHandler = nil\n }\n }\n\n self.listener = listener\n }\n\n deinit {\n cancel()\n }\n\n /// Local port bound by listener on which it accepts new connections.\n var listenPort: UInt16 {\n return listener.port?.rawValue ?? 0\n }\n\n /// Start listening on a randomly assigned port which should be available via `listenPort` once this call returns\n /// control back to the caller.\n ///\n /// > Warning: This implementation is **not safe to use in production**\n /// It will cancel the `listener.stateUpdateHandler` after it becomes ready and ignore future updates.\n ///\n /// Waits for the underlying connection to become ready before returning control to the caller, otherwise throws an\n /// error if connection state indicates as such.\n func start() async throws {\n try await withCheckedThrowingContinuation { continuation in\n listener.stateUpdateHandler = { state in\n switch state {\n case .ready:\n continuation.resume(returning: ())\n case let .failed(error):\n continuation.resume(throwing: error)\n case let .waiting(error):\n continuation.resume(throwing: error)\n case .cancelled:\n continuation.resume(throwing: CancellationError())\n default:\n return\n }\n // Reset state update handler after resuming continuation.\n self.listener.stateUpdateHandler = nil\n }\n listener.start(queue: dispatchQueue)\n }\n }\n\n func cancel() {\n listener.cancel()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadRustRuntimeTests\UnsafeListener.swift
UnsafeListener.swift
Swift
2,860
0.95
0.075
0.328571
python-kit
879
2024-03-16T03:35:29.399813
GPL-3.0
true
0f253b9af445a73656584e57d0753796
//\n// AccessMethodKind.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A kind of API access method.\npublic enum AccessMethodKind: Equatable, Hashable, CaseIterable {\n /// Direct communication.\n case direct\n\n /// Communication over bridges.\n case bridges\n\n /// Communication over proxy address from a DNS.\n case encryptedDNS\n\n /// Communication over shadowsocks.\n case shadowsocks\n\n /// Communication over socks v5 proxy.\n case socks5\n}\n\npublic extension AccessMethodKind {\n /// Returns `true` if the method is permanent and cannot be deleted.\n var isPermanent: Bool {\n switch self {\n case .direct, .bridges, .encryptedDNS:\n true\n case .shadowsocks, .socks5:\n false\n }\n }\n\n /// Returns all access method kinds that can be added by user.\n static var allUserDefinedKinds: [AccessMethodKind] {\n allCases.filter { !$0.isPermanent }\n }\n}\n\nextension PersistentAccessMethod {\n /// A kind of access method.\n public var kind: AccessMethodKind {\n switch proxyConfiguration {\n case .direct:\n .direct\n case .bridges:\n .bridges\n case .encryptedDNS:\n .encryptedDNS\n case .shadowsocks:\n .shadowsocks\n case .socks5:\n .socks5\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\AccessMethodKind.swift
AccessMethodKind.swift
Swift
1,437
0.95
0.048387
0.301887
node-utils
135
2024-05-22T23:13:21.187702
MIT
false
49c075cf7df7eb1289e583d7b9245683
//\n// AccessMethodRepository.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 12/12/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\n\npublic class AccessMethodRepository: AccessMethodRepositoryProtocol, @unchecked Sendable {\n public static let directId = UUID(uuidString: "C9DB7457-2A55-42C3-A926-C07F82131994")!\n public static let bridgeId = UUID(uuidString: "8586E75A-CA7B-4432-B70D-EE65F3F95084")!\n public static let encryptedDNSId = UUID(uuidString: "831CB1F8-1829-42DD-B9DC-82902F298EC0")!\n\n private let logger = Logger(label: "AccessMethodRepository")\n\n private let direct = PersistentAccessMethod(\n id: AccessMethodRepository.directId,\n name: "Direct",\n isEnabled: true,\n proxyConfiguration: .direct\n )\n\n private let bridge = PersistentAccessMethod(\n id: AccessMethodRepository.bridgeId,\n name: "Mullvad bridges",\n isEnabled: true,\n proxyConfiguration: .bridges\n )\n\n private let encryptedDNS = PersistentAccessMethod(\n id: AccessMethodRepository.encryptedDNSId,\n name: "Encrypted DNS proxy",\n isEnabled: true,\n proxyConfiguration: .encryptedDNS\n )\n\n private let accessMethodsSubject: CurrentValueSubject<[PersistentAccessMethod], Never>\n public var accessMethodsPublisher: AnyPublisher<[PersistentAccessMethod], Never> {\n accessMethodsSubject.eraseToAnyPublisher()\n }\n\n private let lastReachableAccessMethodSubject: CurrentValueSubject<PersistentAccessMethod, Never>\n public var lastReachableAccessMethodPublisher: AnyPublisher<PersistentAccessMethod, Never> {\n lastReachableAccessMethodSubject.eraseToAnyPublisher()\n }\n\n public var directAccess: PersistentAccessMethod {\n direct\n }\n\n public init() {\n accessMethodsSubject = CurrentValueSubject([])\n lastReachableAccessMethodSubject = CurrentValueSubject(direct)\n\n addDefaultsMethods()\n\n accessMethodsSubject.send(fetchAll())\n lastReachableAccessMethodSubject.send(fetchLastReachable())\n }\n\n public func save(_ method: PersistentAccessMethod) {\n var methodStore = readApiAccessMethodStore()\n\n var method = method\n method.name = method.name.trimmingCharacters(in: .whitespaces)\n\n if let index = methodStore.accessMethods.firstIndex(where: { $0.id == method.id }) {\n methodStore.accessMethods[index] = method\n } else {\n methodStore.accessMethods.append(method)\n }\n\n do {\n try writeApiAccessMethodStore(methodStore)\n accessMethodsSubject.send(methodStore.accessMethods)\n } catch {\n logger.error("Could not save access method: \(method) \nError: \(error)")\n }\n }\n\n public func saveLastReachable(_ method: PersistentAccessMethod) {\n var methodStore = readApiAccessMethodStore()\n methodStore.lastReachableAccessMethod = method\n\n do {\n try writeApiAccessMethodStore(methodStore)\n lastReachableAccessMethodSubject.send(method)\n } catch {\n logger.error("Could not save last reachable access method: \(method) \nError: \(error)")\n }\n }\n\n public func delete(id: UUID) {\n var methodStore = readApiAccessMethodStore()\n guard let index = methodStore.accessMethods.firstIndex(where: { $0.id == id }) else { return }\n\n // Prevent removing methods that have static UUIDs and are always present.\n let method = methodStore.accessMethods[index]\n if !method.kind.isPermanent {\n methodStore.accessMethods.remove(at: index)\n }\n\n do {\n try writeApiAccessMethodStore(methodStore)\n accessMethodsSubject.send(methodStore.accessMethods)\n } catch {\n logger.error("Could not delete access method with id: \(id) \nError: \(error)")\n }\n }\n\n public func fetch(by id: UUID) -> PersistentAccessMethod? {\n fetchAll().first { $0.id == id }\n }\n\n public func fetchAll() -> [PersistentAccessMethod] {\n readApiAccessMethodStore().accessMethods\n }\n\n public func fetchLastReachable() -> PersistentAccessMethod {\n readApiAccessMethodStore().lastReachableAccessMethod\n }\n\n public func addDefaultsMethods() {\n add([\n direct,\n bridge,\n encryptedDNS,\n ])\n }\n\n private func add(_ methods: [PersistentAccessMethod]) {\n var methodStore = readApiAccessMethodStore()\n\n methods.forEach { method in\n if !methodStore.accessMethods.contains(where: { $0.id == method.id }) {\n methodStore.accessMethods.append(method)\n }\n }\n\n do {\n try writeApiAccessMethodStore(methodStore)\n accessMethodsSubject.send(methods)\n } catch {\n logger.error("Could not update access methods: \(methods) \nError: \(error)")\n }\n }\n\n private func readApiAccessMethodStore() -> PersistentAccessMethodStore {\n let parser = makeParser()\n\n do {\n let data = try SettingsManager.store.read(key: .apiAccessMethods)\n return try parser.parseUnversionedPayload(as: PersistentAccessMethodStore.self, from: data)\n } catch {\n logger.error("Could not load access method store: \(error)")\n return PersistentAccessMethodStore(lastReachableAccessMethod: direct, accessMethods: [])\n }\n }\n\n private func writeApiAccessMethodStore(_ store: PersistentAccessMethodStore) throws {\n let parser = makeParser()\n let data = try parser.produceUnversionedPayload(store)\n\n try SettingsManager.store.write(data, for: .apiAccessMethods)\n }\n\n private func makeParser() -> SettingsParser {\n SettingsParser(decoder: JSONDecoder(), encoder: JSONEncoder())\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\AccessMethodRepository.swift
AccessMethodRepository.swift
Swift
5,940
0.95
0.102857
0.056338
react-lib
84
2024-12-30T05:21:32.469723
MIT
false
1af9ec5ccbea4536c7c7995d37bae24c
//\n// AccessMethodRepositoryProtocol.swift\n// MullvadVPN\n//\n// Created by pronebird on 28/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\n\npublic protocol AccessMethodRepositoryDataSource: Sendable {\n /// Publisher that propagates a snapshot of all access methods upon modifications.\n var accessMethodsPublisher: AnyPublisher<[PersistentAccessMethod], Never> { get }\n\n /// - Returns: the default strategy.\n var directAccess: PersistentAccessMethod { get }\n\n /// Fetch all access method from the persistent store.\n /// - Returns: an array of all persistent access method.\n func fetchAll() -> [PersistentAccessMethod]\n\n /// Save last reachable access method to the persistent store.\n func saveLastReachable(_ method: PersistentAccessMethod)\n\n /// Fetch last reachable access method from the persistent store.\n func fetchLastReachable() -> PersistentAccessMethod\n}\n\npublic protocol AccessMethodRepositoryProtocol: AccessMethodRepositoryDataSource {\n /// Publisher that propagates a snapshot of last reachable access method upon modifications.\n var lastReachableAccessMethodPublisher: AnyPublisher<PersistentAccessMethod, Never> { get }\n\n /// Add new access method.\n /// - Parameter method: persistent access method model.\n func save(_ method: PersistentAccessMethod)\n\n /// Delete access method by id.\n /// - Parameter id: an access method id.\n func delete(id: UUID)\n\n /// Fetch access method by id.\n /// - Parameter id: an access method id.\n /// - Returns: a persistent access method model upon success, otherwise `nil`.\n func fetch(by id: UUID) -> PersistentAccessMethod?\n\n /// Refreshes the storage with default values.\n func addDefaultsMethods()\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\AccessMethodRepositoryProtocol.swift
AccessMethodRepositoryProtocol.swift
Swift
1,766
0.95
0
0.594595
python-kit
521
2024-08-05T05:04:35.424736
GPL-3.0
false
3f2b5dd65c376eaad163824221347add
//\n// AppStorage.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-01-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@propertyWrapper\npublic struct AppStorage<Value> {\n let key: String\n let defaultValue: Value\n let container: UserDefaults\n\n public var wrappedValue: Value {\n get {\n container.value(forKey: key) as? Value ?? defaultValue\n }\n set {\n if let anyOptional = newValue as? AnyOptional,\n anyOptional.isNil {\n container.removeObject(forKey: key)\n } else {\n container.set(newValue, forKey: key)\n }\n }\n }\n\n public init(wrappedValue: Value, key: String, container: UserDefaults) {\n self.defaultValue = wrappedValue\n self.container = container\n self.key = key\n }\n}\n\nprotocol AnyOptional {\n var isNil: Bool { get }\n}\n\nextension Optional: AnyOptional {\n var isNil: Bool { self == nil }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\AppStorage.swift
AppStorage.swift
Swift
1,001
0.95
0.023256
0.184211
awesome-app
142
2024-03-09T17:13:30.686646
GPL-3.0
false
1212564988e542569dd90791caed95f6
//\n// CustomList.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct CustomList: Codable, Equatable {\n public let id: UUID\n public var name: String\n public var locations: [RelayLocation]\n\n public init(id: UUID = UUID(), name: String, locations: [RelayLocation]) {\n self.id = id\n self.name = name\n self.locations = locations\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\CustomList.swift
CustomList.swift
Swift
491
0.95
0
0.368421
react-lib
543
2023-10-23T10:12:55.072266
GPL-3.0
false
aae01cd56d62bd4f4fd71008d57faa0a
//\n// CustomListRepository.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\n\npublic enum CustomRelayListError: LocalizedError, Hashable {\n case duplicateName\n case nameTooLong\n\n public var errorDescription: String? {\n switch self {\n case .duplicateName:\n NSLocalizedString(\n "DUPLICATE_CUSTOM_LISTS_ERROR",\n tableName: "CustomLists",\n value: "A custom list with this name exists, please choose a unique name.",\n comment: ""\n )\n case .nameTooLong:\n String(\n format: NSLocalizedString(\n "CUSTOM_LIST_NAME_TOO_LONG_ERROR",\n tableName: "CustomLists",\n value: "Name should be no longer than %i characters.",\n comment: ""\n ),\n NameInputFormatter.maxLength\n )\n }\n }\n}\n\npublic struct CustomListRepository: CustomListRepositoryProtocol {\n private let logger = Logger(label: "CustomListRepository")\n\n private let settingsParser: SettingsParser = {\n SettingsParser(decoder: JSONDecoder(), encoder: JSONEncoder())\n }()\n\n public init() {}\n\n public func save(list: CustomList) throws {\n guard list.name.count <= NameInputFormatter.maxLength else {\n throw CustomRelayListError.nameTooLong\n }\n\n var lists = fetchAll()\n\n var list = list\n list.name = list.name.trimmingCharacters(in: .whitespaces)\n\n if let listWithSameName = lists.first(where: { $0.name.compare(list.name) == .orderedSame }),\n listWithSameName.id != list.id {\n throw CustomRelayListError.duplicateName\n } else if let index = lists.firstIndex(where: { $0.id == list.id }) {\n lists[index] = list\n try write(lists)\n } else {\n lists.append(list)\n try write(lists)\n }\n }\n\n public func delete(id: UUID) {\n do {\n var lists = fetchAll()\n if let index = lists.firstIndex(where: { $0.id == id }) {\n lists.remove(at: index)\n try write(lists)\n }\n } catch {\n logger.error(error: error)\n }\n }\n\n public func fetch(by id: UUID) -> CustomList? {\n try? read().first(where: { $0.id == id })\n }\n\n public func fetchAll() -> [CustomList] {\n (try? read()) ?? []\n }\n}\n\nextension CustomListRepository {\n private func read() throws -> [CustomList] {\n let data = try SettingsManager.store.read(key: .customRelayLists)\n\n return try settingsParser.parseUnversionedPayload(as: [CustomList].self, from: data)\n }\n\n private func write(_ list: [CustomList]) throws {\n let data = try settingsParser.produceUnversionedPayload(list)\n\n try SettingsManager.store.write(data, for: .customRelayLists)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\CustomListRepository.swift
CustomListRepository.swift
Swift
3,062
0.95
0.142857
0.079545
node-utils
908
2025-04-26T03:57:10.785257
MIT
false
25567c4b05f0297522866568577fe577
//\n// CustomListRepositoryProtocol.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\nimport MullvadTypes\npublic protocol CustomListRepositoryProtocol {\n /// Save a custom list. If the list doesn't already exist, it must have a unique name.\n /// - Parameter list: a custom list.\n func save(list: CustomList) throws\n\n /// Delete custom list by id.\n /// - Parameter id: an access method id.\n func delete(id: UUID)\n\n /// Fetch custom list by id.\n /// - Parameter id: a custom list id.\n /// - Returns: a persistent custom list model upon success, otherwise `nil`.\n func fetch(by id: UUID) -> CustomList?\n\n /// Fetch all custom list.\n /// - Returns: all custom list model .\n func fetchAll() -> [CustomList]\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\CustomListRepositoryProtocol.swift
CustomListRepositoryProtocol.swift
Swift
852
0.95
0
0.64
python-kit
90
2023-10-22T15:06:56.056488
MIT
false
1c555f29d23385de7d14618b01ea5a1b
//\n// DAITASettings.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-08-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Whether DAITA is enabled.\npublic enum DAITAState: Codable, Sendable {\n case on\n case off\n\n public var isEnabled: Bool {\n get {\n self == .on\n }\n set {\n self = newValue ? .on : .off\n }\n }\n}\n\n/// Whether "direct only" is enabled, meaning no automatic routing to DAITA relays.\npublic enum DirectOnlyState: Codable, Sendable {\n case on\n case off\n\n public var isEnabled: Bool {\n get {\n self == .on\n }\n set {\n self = newValue ? .on : .off\n }\n }\n}\n\n/// Selected relay is incompatible with DAITA, either through singlehop or multihop.\npublic enum DAITASettingsCompatibilityError {\n case singlehop, multihop\n}\n\npublic struct DAITASettings: Codable, Equatable, Sendable {\n @available(*, deprecated, renamed: "daitaState")\n public let state: DAITAState = .off\n\n public var daitaState: DAITAState\n public var directOnlyState: DirectOnlyState\n\n public var isAutomaticRouting: Bool {\n daitaState.isEnabled && !directOnlyState.isEnabled\n }\n\n public var isDirectOnly: Bool {\n daitaState.isEnabled && directOnlyState.isEnabled\n }\n\n public init(daitaState: DAITAState = .off, directOnlyState: DirectOnlyState = .off) {\n self.daitaState = daitaState\n self.directOnlyState = directOnlyState\n }\n\n public init(from decoder: any Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n daitaState = try container.decodeIfPresent(DAITAState.self, forKey: .daitaState)\n ?? container.decodeIfPresent(DAITAState.self, forKey: .state)\n ?? .off\n\n directOnlyState = try container.decodeIfPresent(DirectOnlyState.self, forKey: .directOnlyState)\n ?? .off\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\DAITASettings.swift
DAITASettings.swift
Swift
1,973
0.95
0.039474
0.16129
python-kit
323
2024-12-24T02:47:45.773615
MIT
false
f2760d2931b04e4d414576fcf3f65f63
//\n// DeviceState.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-07-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum DeviceState: Codable, Equatable, Sendable {\n case loggedIn(StoredAccountData, StoredDeviceData)\n case loggedOut\n case revoked\n\n private enum LoggedInCodableKeys: String, CodingKey {\n case _0 = "account"\n case _1 = "device"\n }\n\n public var isLoggedIn: Bool {\n switch self {\n case .loggedIn:\n return true\n case .loggedOut, .revoked:\n return false\n }\n }\n\n public var accountData: StoredAccountData? {\n switch self {\n case let .loggedIn(accountData, _):\n return accountData\n case .loggedOut, .revoked:\n return nil\n }\n }\n\n public var deviceData: StoredDeviceData? {\n switch self {\n case let .loggedIn(_, deviceData):\n return deviceData\n case .loggedOut, .revoked:\n return nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\DeviceState.swift
DeviceState.swift
Swift
1,055
0.95
0.06383
0.170732
node-utils
285
2024-06-17T22:35:39.511078
MIT
false
b2f731fbf047b1298ac56216944fdba4
//\n// DNSSettings.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/04/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\n/// A struct describing Mullvad DNS blocking options.\npublic struct DNSBlockingOptions: OptionSet, Codable, Sendable {\n public let rawValue: UInt32\n\n public static let blockAdvertising = DNSBlockingOptions(rawValue: 1 << 0)\n public static let blockTracking = DNSBlockingOptions(rawValue: 1 << 1)\n public static let blockMalware = DNSBlockingOptions(rawValue: 1 << 2)\n public static let blockAdultContent = DNSBlockingOptions(rawValue: 1 << 3)\n public static let blockGambling = DNSBlockingOptions(rawValue: 1 << 4)\n public static let blockSocialMedia = DNSBlockingOptions(rawValue: 1 << 5)\n\n public var serverAddress: IPv4Address? {\n if isEmpty {\n return nil\n } else {\n return IPv4Address("100.64.0.\(rawValue)")\n }\n }\n\n public init(rawValue: UInt32) {\n self.rawValue = rawValue\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let rawValue = try container.decode(RawValue.self)\n\n self.init(rawValue: rawValue)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n try container.encode(rawValue)\n }\n}\n\n/// A struct that holds DNS settings.\npublic struct DNSSettings: Codable, Equatable, Sendable {\n /// Maximum number of allowed DNS domains.\n public static let maxAllowedCustomDNSDomains = 3\n\n /// DNS blocking options.\n public var blockingOptions: DNSBlockingOptions = []\n\n /// Enable custom DNS.\n public var enableCustomDNS = false\n\n /// Custom DNS domains.\n public var customDNSDomains: [AnyIPAddress] = []\n\n /// Effective state of the custom DNS setting.\n public var effectiveEnableCustomDNS: Bool {\n blockingOptions.isEmpty && enableCustomDNS && !customDNSDomains.isEmpty\n }\n\n private enum CodingKeys: String, CodingKey {\n // Removed in 2022.1 in favor of `blockingOptions`\n case blockAdvertising, blockTracking\n\n // Added in 2022.1\n case blockingOptions\n\n case enableCustomDNS, customDNSDomains\n }\n\n public init() {}\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n // Added in 2022.1\n if let storedBlockingOptions = try container.decodeIfPresent(\n DNSBlockingOptions.self,\n forKey: .blockingOptions\n ) {\n blockingOptions = storedBlockingOptions\n }\n\n if let storedBlockAdvertising = try container.decodeIfPresent(\n Bool.self,\n forKey: .blockAdvertising\n ), storedBlockAdvertising {\n blockingOptions.insert(.blockAdvertising)\n }\n\n if let storedBlockTracking = try container.decodeIfPresent(\n Bool.self,\n forKey: .blockTracking\n ), storedBlockTracking {\n blockingOptions.insert(.blockTracking)\n }\n\n if let storedEnableCustomDNS = try container.decodeIfPresent(\n Bool.self,\n forKey: .enableCustomDNS\n ) {\n enableCustomDNS = storedEnableCustomDNS\n }\n\n if let storedCustomDNSDomains = try container.decodeIfPresent(\n [AnyIPAddress].self,\n forKey: .customDNSDomains\n ) {\n customDNSDomains = storedCustomDNSDomains\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n try container.encode(blockingOptions, forKey: .blockingOptions)\n try container.encode(enableCustomDNS, forKey: .enableCustomDNS)\n try container.encode(customDNSDomains, forKey: .customDNSDomains)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\DNSSettings.swift
DNSSettings.swift
Swift
3,940
0.95
0.140625
0.166667
python-kit
882
2023-10-23T09:25:56.711277
BSD-3-Clause
false
de47f6237c75c219403bbe0e783667f8
//\n// InfoHeaderConfig.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-01.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic struct InfoHeaderConfig {\n public let body: String\n public let link: String\n\n public init(body: String, link: String) {\n self.body = body\n self.link = link\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\InfoHeaderConfig.swift
InfoHeaderConfig.swift
Swift
349
0.8
0
0.466667
awesome-app
583
2023-08-18T12:00:12.596909
MIT
false
feff9997aeefbf586ffebe5e1d1ae220
//\n// InfoModalConfig.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic struct InfoModalConfig {\n public let header: String\n public let preamble: String\n public let body: [String]\n\n public init(header: String, preamble: String, body: [String]) {\n self.header = header\n self.preamble = preamble\n self.body = body\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\InfoModalConfig.swift
InfoModalConfig.swift
Swift
442
0.8
0
0.411765
react-lib
429
2024-04-23T14:35:24.628754
Apache-2.0
false
5e57efe8e8a904996e94ee03f3b3a187
//\n// IPOverride.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Network\n\npublic struct RelayOverrides: Codable, Sendable {\n public let overrides: [IPOverride]\n\n private enum CodingKeys: String, CodingKey {\n case overrides = "relay_overrides"\n }\n}\n\npublic struct IPOverrideFormatError: LocalizedError {\n public let errorDescription: String?\n}\n\npublic struct IPOverride: Codable, Equatable, Sendable {\n public let hostname: String\n public var ipv4Address: IPv4Address?\n public var ipv6Address: IPv6Address?\n\n private enum CodingKeys: String, CodingKey {\n case hostname\n case ipv4Address = "ipv4_addr_in"\n case ipv6Address = "ipv6_addr_in"\n }\n\n public init(hostname: String, ipv4Address: IPv4Address?, ipv6Address: IPv6Address?) throws {\n self.hostname = hostname\n self.ipv4Address = ipv4Address\n self.ipv6Address = ipv6Address\n\n if self.ipv4Address.isNil && self.ipv6Address.isNil {\n throw IPOverrideFormatError(errorDescription: "ipv4Address and ipv6Address cannot both be nil.")\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n self.hostname = try container.decode(String.self, forKey: .hostname)\n self.ipv4Address = try container.decodeIfPresent(IPv4Address.self, forKey: .ipv4Address)\n self.ipv6Address = try container.decodeIfPresent(IPv6Address.self, forKey: .ipv6Address)\n\n if self.ipv4Address.isNil && self.ipv6Address.isNil {\n throw IPOverrideFormatError(errorDescription: "ipv4Address and ipv6Address cannot both be nil.")\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\IPOverride.swift
IPOverride.swift
Swift
1,767
0.95
0.109091
0.159091
awesome-app
349
2023-12-23T12:48:12.674891
GPL-3.0
false
7bba358f27ca3ebf2b4b845462e50eeb
//\n// IPOverrideRepository.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@preconcurrency import Combine\nimport MullvadLogging\n\npublic protocol IPOverrideRepositoryProtocol: Sendable {\n var overridesPublisher: AnyPublisher<[IPOverride], Never> { get }\n func add(_ overrides: [IPOverride])\n func fetchAll() -> [IPOverride]\n func deleteAll()\n func parse(data: Data) throws -> [IPOverride]\n}\n\npublic final class IPOverrideRepository: IPOverrideRepositoryProtocol {\n private let overridesSubject: CurrentValueSubject<[IPOverride], Never> = .init([])\n public var overridesPublisher: AnyPublisher<[IPOverride], Never> {\n overridesSubject.eraseToAnyPublisher()\n }\n\n nonisolated(unsafe) private let logger = Logger(label: "IPOverrideRepository")\n private let readWriteLock = NSLock()\n\n public init() {}\n\n public func add(_ overrides: [IPOverride]) {\n var storedOverrides = fetchAll()\n\n overrides.forEach { override in\n if let existingOverrideIndex = storedOverrides.firstIndex(where: { $0.hostname == override.hostname }) {\n var existingOverride = storedOverrides[existingOverrideIndex]\n\n if let ipv4Address = override.ipv4Address {\n existingOverride.ipv4Address = ipv4Address\n }\n\n if let ipv6Address = override.ipv6Address {\n existingOverride.ipv6Address = ipv6Address\n }\n\n storedOverrides[existingOverrideIndex] = existingOverride\n } else {\n storedOverrides.append(override)\n }\n }\n\n do {\n try writeIpOverrides(storedOverrides)\n } catch {\n logger.error("Could not add override(s): \(overrides) \nError: \(error)")\n }\n }\n\n public func fetchAll() -> [IPOverride] {\n return (try? readIpOverrides()) ?? []\n }\n\n public func deleteAll() {\n do {\n try readWriteLock.withLock {\n try SettingsManager.store.delete(key: .ipOverrides)\n overridesSubject.send([])\n }\n } catch {\n logger.error("Could not delete all overrides. \nError: \(error)")\n }\n }\n\n public func parse(data: Data) throws -> [IPOverride] {\n let decoder = JSONDecoder()\n let jsonData = try decoder.decode(RelayOverrides.self, from: data)\n\n return jsonData.overrides\n }\n\n private func readIpOverrides() throws -> [IPOverride] {\n try readWriteLock.withLock {\n let parser = makeParser()\n let data = try SettingsManager.store.read(key: .ipOverrides)\n return try parser.parseUnversionedPayload(as: [IPOverride].self, from: data)\n }\n }\n\n private func writeIpOverrides(_ overrides: [IPOverride]) throws {\n let parser = makeParser()\n let data = try parser.produceUnversionedPayload(overrides)\n\n try readWriteLock.withLock {\n try SettingsManager.store.write(data, for: .ipOverrides)\n overridesSubject.send(overrides)\n }\n }\n\n private func makeParser() -> SettingsParser {\n SettingsParser(decoder: JSONDecoder(), encoder: JSONEncoder())\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\IPOverrideRepository.swift
IPOverrideRepository.swift
Swift
3,299
0.95
0.176471
0.084337
awesome-app
985
2023-08-07T01:50:37.077366
MIT
false
b82deb112fdf0bd0f11a0040dafbcfa2
//\n// KeychainSettingsStore.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-11-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Security\n\nfinal public class KeychainSettingsStore: SettingsStore, Sendable {\n public let serviceName: String\n public let accessGroup: String\n\n public init(serviceName: String, accessGroup: String) {\n self.serviceName = serviceName\n self.accessGroup = accessGroup\n }\n\n public func read(key: SettingsKey) throws -> Data {\n try readItemData(key)\n }\n\n public func write(_ data: Data, for key: SettingsKey) throws {\n try addOrUpdateItem(key, data: data)\n }\n\n public func delete(key: SettingsKey) throws {\n try deleteItem(key)\n }\n\n private func addItem(_ item: SettingsKey, data: Data) throws {\n var query = createDefaultAttributes(item: item)\n query.merge(createAccessAttributes()) { current, _ in\n current\n }\n query[kSecValueData] = data\n\n let status = SecItemAdd(query as CFDictionary, nil)\n if status != errSecSuccess {\n throw KeychainError(code: status)\n }\n }\n\n private func updateItem(_ item: SettingsKey, data: Data) throws {\n let query = createDefaultAttributes(item: item)\n let status = SecItemUpdate(\n query as CFDictionary,\n [kSecValueData: data] as CFDictionary\n )\n\n if status != errSecSuccess {\n throw KeychainError(code: status)\n }\n }\n\n private func addOrUpdateItem(_ item: SettingsKey, data: Data) throws {\n do {\n try updateItem(item, data: data)\n } catch let error as KeychainError where error == .itemNotFound {\n try addItem(item, data: data)\n } catch {\n throw error\n }\n }\n\n private func readItemData(_ item: SettingsKey) throws -> Data {\n var query = createDefaultAttributes(item: item)\n query[kSecReturnData] = true\n\n var result: CFTypeRef?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n\n if status == errSecSuccess {\n return result as? Data ?? Data()\n } else {\n throw KeychainError(code: status)\n }\n }\n\n private func deleteItem(_ item: SettingsKey) throws {\n let query = createDefaultAttributes(item: item)\n let status = SecItemDelete(query as CFDictionary)\n if status != errSecSuccess {\n throw KeychainError(code: status)\n }\n }\n\n private func createDefaultAttributes(item: SettingsKey) -> [CFString: Any] {\n [\n kSecClass: kSecClassGenericPassword,\n kSecAttrService: serviceName,\n kSecAttrAccount: item.rawValue,\n ]\n }\n\n private func createAccessAttributes() -> [CFString: Any] {\n [\n kSecAttrAccessGroup: accessGroup,\n kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock,\n ]\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\KeychainSettingsStore.swift
KeychainSettingsStore.swift
Swift
3,023
0.95
0.12381
0.079545
node-utils
444
2024-07-08T22:55:01.622457
MIT
false
7959ddcc83430332c3577a4f1645b0aa
//\n// Migration.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-11-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol Migration {\n func migrate(\n with store: SettingsStore,\n parser: SettingsParser,\n completion: @escaping @Sendable (Error?) -> Void\n )\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\Migration.swift
Migration.swift
Swift
345
0.95
0
0.466667
node-utils
712
2023-08-20T10:33:03.501009
BSD-3-Clause
false
5b704b9bfc29c6eb81f05c689d6f434f
//\n// MigrationManager.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-08-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\n\npublic enum SettingsMigrationResult: Sendable {\n /// Nothing to migrate.\n case nothing\n\n /// Successfully performed migration.\n case success\n\n /// Failure when migrating store.\n case failure(Error)\n}\n\npublic struct MigrationManager {\n private let logger = Logger(label: "MigrationManager")\n private let cacheDirectory: URL\n\n public init(cacheDirectory: URL) {\n self.cacheDirectory = cacheDirectory.appendingPathComponent("migrationState.json")\n }\n\n /// Migrate settings store if needed.\n ///\n /// Reads the current settings, upgrades them to the latest version if needed\n /// and writes back to `store` when settings are updated.\n ///\n /// In order to avoid migration happening from both the VPN and the host processes at the same time,\n /// a non existant file path is used as a lock to synchronize access between the processes.\n /// This file is accessed by `NSFileCoordinator` in order to prevent multiple processes accessing at the same time.\n /// - Parameters:\n /// - store: The store to from which settings are read and written to.\n /// - migrationCompleted: Completion handler called with a migration result.\n public func migrateSettings(\n store: SettingsStore,\n migrationCompleted: @escaping @Sendable (SettingsMigrationResult) -> Void\n ) {\n let fileCoordinator = NSFileCoordinator(filePresenter: nil)\n var error: NSError?\n\n // This will block the calling thread if another process is currently running the same code.\n // This is intentional to avoid TOCTOU issues, and guaranteeing settings cannot be read\n // in a half written state.\n // The resulting effect is that only one process at a time can do settings migrations.\n // The other process will be blocked, and will have nothing to do as long as settings were successfully upgraded.\n fileCoordinator.coordinate(writingItemAt: cacheDirectory, error: &error) { _ in\n let resetStoreHandler = { (result: SettingsMigrationResult) in\n // Reset store upon failure to migrate settings.\n if case .failure = result {\n SettingsManager.resetStore()\n }\n migrationCompleted(result)\n }\n\n do {\n try upgradeSettingsToLatestVersion(\n store: store,\n migrationCompleted: migrationCompleted\n )\n } catch .itemNotFound as KeychainError {\n migrationCompleted(.nothing)\n } catch let couldNotReadKeychainError as KeychainError\n where couldNotReadKeychainError == .interactionNotAllowed {\n migrationCompleted(.failure(couldNotReadKeychainError))\n } catch {\n resetStoreHandler(.failure(error))\n }\n }\n }\n\n private func upgradeSettingsToLatestVersion(\n store: SettingsStore,\n migrationCompleted: @escaping @Sendable (SettingsMigrationResult) -> Void\n ) throws {\n let parser = SettingsParser(decoder: JSONDecoder(), encoder: JSONEncoder())\n let settingsData = try store.read(key: SettingsKey.settings)\n let settingsVersion = try parser.parseVersion(data: settingsData)\n\n guard settingsVersion != SchemaVersion.current.rawValue else {\n migrationCompleted(.nothing)\n return\n }\n\n // Corrupted settings version (i.e. negative values, or downgrade from a future version) should fail\n guard var savedSchema = SchemaVersion(rawValue: settingsVersion) else {\n migrationCompleted(.failure(UnsupportedSettingsVersionError(\n storedVersion: settingsVersion,\n currentVersion: SchemaVersion.current\n )))\n return\n }\n\n var savedSettings = try parser.parsePayload(as: savedSchema.settingsType, from: settingsData)\n\n repeat {\n let upgradedVersion = savedSettings.upgradeToNextVersion()\n savedSchema = savedSchema.nextVersion\n savedSettings = upgradedVersion\n } while savedSchema.rawValue < SchemaVersion.current.rawValue\n\n // Write the latest settings back to the store\n let latestVersionPayload = try parser.producePayload(savedSettings, version: SchemaVersion.current.rawValue)\n try store.write(latestVersionPayload, for: .settings)\n migrationCompleted(.success)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\MigrationManager.swift
MigrationManager.swift
Swift
4,689
0.95
0.130435
0.29
python-kit
560
2023-09-05T19:04:00.111548
BSD-3-Clause
false
9f98411bb96925b303dbc284b451cb59
//\n// MultihopSettings.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-04-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Whether Multi-hop is enabled\npublic enum MultihopState: Codable, Sendable {\n case on\n case off\n\n public var isEnabled: Bool {\n get {\n self == .on\n }\n set {\n self = newValue ? .on : .off\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\MultihopSettings.swift
MultihopSettings.swift
Swift
452
0.95
0
0.363636
react-lib
699
2024-04-23T07:05:09.553328
Apache-2.0
false
6d7eaf3518eaa5bbc32558cd500a3277
//\n// PersistentAccessMethod.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n\n/// Persistent access method container model.\npublic struct PersistentAccessMethodStore: Codable {\n /// The last successfully reached access method.\n public var lastReachableAccessMethod: PersistentAccessMethod\n\n /// Persistent access method models.\n public var accessMethods: [PersistentAccessMethod]\n}\n\n/// Persistent access method model.\npublic struct PersistentAccessMethod: Identifiable, Codable, Equatable {\n /// The unique identifier used for referencing the access method entry in a persistent store.\n public var id: UUID\n\n /// The user-defined name for access method.\n public var name: String\n\n /// The flag indicating whether configuration is enabled.\n public var isEnabled: Bool\n\n /// Proxy configuration.\n public var proxyConfiguration: PersistentProxyConfiguration\n\n public init(id: UUID, name: String, isEnabled: Bool, proxyConfiguration: PersistentProxyConfiguration) {\n self.id = id\n self.name = name\n self.isEnabled = isEnabled\n self.proxyConfiguration = proxyConfiguration\n }\n\n public init(from decoder: any Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n self.id = try container.decode(UUID.self, forKey: .id)\n self.isEnabled = try container.decode(Bool.self, forKey: .isEnabled)\n self.proxyConfiguration = try container.decode(PersistentProxyConfiguration.self, forKey: .proxyConfiguration)\n\n // Added after release of API access methods feature. There was previously no limitation on text input length,\n // so this formatting has been added to prevent already stored names from being too long when displayed.\n let name = try container.decode(String.self, forKey: .name)\n self.name = NameInputFormatter.format(name)\n }\n\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.id == rhs.id\n }\n}\n\n/// Persistent proxy configuration.\npublic enum PersistentProxyConfiguration: Codable {\n /// Direct communication without proxy.\n case direct\n\n /// Communication over bridges.\n case bridges\n\n /// Communication over proxy address from a DNS.\n case encryptedDNS\n\n /// Communication over shadowsocks.\n case shadowsocks(ShadowsocksConfiguration)\n\n /// Communication over socks5 proxy.\n case socks5(SocksConfiguration)\n}\n\nextension PersistentProxyConfiguration {\n /// Socks autentication method.\n public enum SocksAuthentication: Codable {\n case noAuthentication\n case authentication(UserCredential)\n }\n\n public struct UserCredential: Codable {\n public let username: String\n public let password: String\n\n public init(username: String, password: String) {\n self.username = username\n self.password = password\n }\n }\n\n /// Socks v5 proxy configuration.\n public struct SocksConfiguration: Codable {\n /// Proxy server address.\n public var server: AnyIPAddress\n\n /// Proxy server port.\n public var port: UInt16\n\n /// Authentication method.\n public var authentication: SocksAuthentication\n\n public init(server: AnyIPAddress, port: UInt16, authentication: SocksAuthentication) {\n self.server = server\n self.port = port\n self.authentication = authentication\n }\n\n public var credential: UserCredential? {\n guard case let .authentication(credential) = authentication else {\n return nil\n }\n return credential\n }\n\n public var toAnyIPEndpoint: AnyIPEndpoint {\n switch server {\n case let .ipv4(ip):\n return .ipv4(IPv4Endpoint(ip: ip, port: port))\n case let .ipv6(ip):\n return .ipv6(IPv6Endpoint(ip: ip, port: port))\n }\n }\n }\n\n /// Shadowsocks configuration.\n public struct ShadowsocksConfiguration: Codable {\n /// Server address.\n public var server: AnyIPAddress\n\n /// Server port.\n public var port: UInt16\n\n /// Server password.\n public var password: String\n\n /// Server cipher.\n public var cipher: ShadowsocksCipherOptions\n\n public init(server: AnyIPAddress, port: UInt16, password: String, cipher: ShadowsocksCipherOptions) {\n self.server = server\n self.port = port\n self.password = password\n self.cipher = cipher\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\PersistentAccessMethod.swift
PersistentAccessMethod.swift
Swift
4,697
0.95
0.05298
0.275
vue-tools
402
2023-07-14T23:02:42.449455
Apache-2.0
false
9d68dd499ba8fb74f967d810fcec6a88
//\n// QuantumResistanceSettings.swift\n// MullvadSettings\n//\n// Created by Andrew Bulhak on 2024-02-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum TunnelQuantumResistance: Codable, Sendable {\n case automatic\n case on\n case off\n}\n\npublic extension TunnelQuantumResistance {\n /// A single source of truth for whether the current state counts as on\n var isEnabled: Bool {\n self == .on\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\QuantumResistanceSettings.swift
QuantumResistanceSettings.swift
Swift
465
0.95
0.045455
0.421053
react-lib
731
2024-10-09T07:47:57.995680
Apache-2.0
false
a7d00f77f834377511867deeb4a9d0a1
//\n// SettingsManager.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/04/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\n\nprivate let keychainServiceName = "Mullvad VPN"\nprivate let accountTokenKey = "accountToken"\nprivate let accountExpiryKey = "accountExpiry"\n\npublic enum SettingsManager {\n nonisolated(unsafe) private static let logger = Logger(label: "SettingsManager")\n\n #if DEBUG\n nonisolated(unsafe) private static var _store = KeychainSettingsStore(\n serviceName: keychainServiceName,\n accessGroup: ApplicationConfiguration.securityGroupIdentifier\n )\n\n /// Alternative store used for tests.\n nonisolated(unsafe) internal static var unitTestStore: SettingsStore?\n\n public static var store: SettingsStore {\n if let unitTestStore { return unitTestStore }\n return _store\n }\n\n #else\n public static let store: SettingsStore = KeychainSettingsStore(\n serviceName: keychainServiceName,\n accessGroup: ApplicationConfiguration.securityGroupIdentifier\n )\n\n #endif\n\n private static func makeParser() -> SettingsParser {\n SettingsParser(decoder: JSONDecoder(), encoder: JSONEncoder())\n }\n\n // MARK: - Last used account\n\n public static func getLastUsedAccount() throws -> String {\n let data = try store.read(key: .lastUsedAccount)\n guard let result = String(bytes: data, encoding: .utf8) else {\n throw StringDecodingError(data: data)\n }\n return result\n }\n\n public static func setLastUsedAccount(_ string: String?) throws {\n if let string {\n guard let data = string.data(using: .utf8) else {\n throw StringEncodingError(string: string)\n }\n\n try store.write(data, for: .lastUsedAccount)\n } else {\n do {\n try store.delete(key: .lastUsedAccount)\n } catch let error as KeychainError where error == .itemNotFound {\n return\n } catch {\n throw error\n }\n }\n }\n\n // MARK: - Should wipe settings\n\n public static func getShouldWipeSettings() -> Bool {\n (try? store.read(key: .shouldWipeSettings)) != nil\n }\n\n public static func setShouldWipeSettings() {\n do {\n try store.write(Data(), for: .shouldWipeSettings)\n } catch {\n logger.error(\n error: error,\n message: "Failed to set should wipe settings."\n )\n }\n }\n\n // MARK: - Settings\n\n public static func readSettings() throws -> LatestTunnelSettings {\n let storedVersion: Int\n let data: Data\n let parser = makeParser()\n\n do {\n data = try store.read(key: .settings)\n storedVersion = try parser.parseVersion(data: data)\n } catch {\n throw ReadSettingsVersionError(underlyingError: error)\n }\n\n let currentVersion = SchemaVersion.current\n\n if storedVersion == currentVersion.rawValue {\n return try parser.parsePayload(as: LatestTunnelSettings.self, from: data)\n } else {\n throw UnsupportedSettingsVersionError(\n storedVersion: storedVersion,\n currentVersion: currentVersion\n )\n }\n }\n\n public static func writeSettings(_ settings: LatestTunnelSettings) throws {\n let parser = makeParser()\n let data = try parser.producePayload(settings, version: SchemaVersion.current.rawValue)\n\n try store.write(data, for: .settings)\n }\n\n // MARK: - Device state\n\n public static func readDeviceState() throws -> DeviceState {\n let data = try store.read(key: .deviceState)\n let parser = makeParser()\n\n return try parser.parseUnversionedPayload(as: DeviceState.self, from: data)\n }\n\n public static func writeDeviceState(_ deviceState: DeviceState) throws {\n let parser = makeParser()\n let data = try parser.produceUnversionedPayload(deviceState)\n\n try store.write(data, for: .deviceState)\n }\n\n /// Removes all legacy settings, device state, tunnel settings and API access methods but keeps\n /// the last used account number stored.\n public static func resetStore(completely: Bool = false) {\n logger.debug("Reset store.")\n\n let keys = completely\n ? SettingsKey.allCases\n : [\n .settings,\n .deviceState,\n .apiAccessMethods,\n .ipOverrides,\n .customRelayLists,\n ]\n\n keys.forEach { key in\n do {\n try store.delete(key: key)\n } catch {\n if (error as? KeychainError) != .itemNotFound {\n logger.error(error: error, message: "Failed to delete \(key.rawValue).")\n }\n }\n }\n }\n\n // MARK: - Private\n\n private static func checkLatestSettingsVersion() throws {\n let settingsVersion: Int\n do {\n let parser = makeParser()\n let settingsData = try store.read(key: .settings)\n settingsVersion = try parser.parseVersion(data: settingsData)\n } catch .itemNotFound as KeychainError {\n return\n } catch {\n throw ReadSettingsVersionError(underlyingError: error)\n }\n\n guard settingsVersion != SchemaVersion.current.rawValue else {\n return\n }\n\n let error = UnsupportedSettingsVersionError(\n storedVersion: settingsVersion,\n currentVersion: SchemaVersion.current\n )\n\n logger.error(error: error, message: "Encountered an unknown version.")\n\n throw error\n }\n}\n\n// MARK: - Supporting types\n\n/// An error type describing a failure to read or parse settings version.\npublic struct ReadSettingsVersionError: LocalizedError, WrappingError {\n private let inner: Error\n\n public var underlyingError: Error? {\n inner\n }\n\n public var errorDescription: String? {\n "Failed to read settings version."\n }\n\n public init(underlyingError: Error) {\n inner = underlyingError\n }\n}\n\n/// An error returned when stored settings version is unknown to the currently running app.\npublic struct UnsupportedSettingsVersionError: LocalizedError {\n public let storedVersion: Int\n public let currentVersion: SchemaVersion\n\n public var errorDescription: String? {\n """\n Stored settings version was not the same as current version, \\n stored version: \(storedVersion), current version: \(currentVersion)\n """\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\SettingsManager.swift
SettingsManager.swift
Swift
6,711
0.95
0.151111
0.116022
react-lib
568
2024-05-10T10:53:39.056084
BSD-3-Clause
false
8345c42424a50fb1da4bf36d434940e1
//\n// SettingsParser.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-11-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprivate struct VersionHeader: Codable {\n var version: Int\n}\n\nprivate struct Payload<T: Codable>: Codable {\n var data: T\n}\n\nprivate struct VersionedPayload<T: Codable>: Codable {\n var version: Int\n var data: T\n}\n\npublic struct SettingsParser {\n /// The decoder used to decode values.\n private let decoder: JSONDecoder\n\n /// The encoder used to encode values.\n private let encoder: JSONEncoder\n\n public init(decoder: JSONDecoder, encoder: JSONEncoder) {\n self.decoder = decoder\n self.encoder = encoder\n }\n\n /// Produces versioned data encoded as the given type\n public func producePayload(_ payload: some Codable, version: Int) throws -> Data {\n try encoder.encode(VersionedPayload(version: version, data: payload))\n }\n\n /// Produces unversioned data encoded as the given type\n public func produceUnversionedPayload(_ payload: some Codable) throws -> Data {\n try encoder.encode(payload)\n }\n\n /// Returns settings version if found inside the stored data.\n public func parseVersion(data: Data) throws -> Int {\n let header = try decoder.decode(VersionHeader.self, from: data)\n\n return header.version\n }\n\n /// Returns unversioned payload parsed as the given type.\n public func parseUnversionedPayload<T: Codable>(\n as type: T.Type,\n from data: Data\n ) throws -> T {\n try decoder.decode(T.self, from: data)\n }\n\n /// Returns data from versioned payload parsed as the given type.\n public func parsePayload<T: Codable>(\n as type: T.Type,\n from data: Data\n ) throws -> T {\n try decoder.decode(Payload<T>.self, from: data).data\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\SettingsParser.swift
SettingsParser.swift
Swift
1,858
0.95
0.088235
0.254545
vue-tools
348
2024-05-31T02:55:02.232983
BSD-3-Clause
false
4745306931da76959a65b3364e589bf4
//\n// SettingsStore.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-11-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum SettingsKey: String, CaseIterable, Sendable {\n case settings = "Settings"\n case deviceState = "DeviceState"\n case apiAccessMethods = "ApiAccessMethods"\n case ipOverrides = "IPOverrides"\n case customRelayLists = "CustomRelayLists"\n case lastUsedAccount = "LastUsedAccount"\n case shouldWipeSettings = "ShouldWipeSettings"\n}\n\npublic protocol SettingsStore: Sendable {\n func read(key: SettingsKey) throws -> Data\n func write(_ data: Data, for key: SettingsKey) throws\n func delete(key: SettingsKey) throws\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\SettingsStore.swift
SettingsStore.swift
Swift
717
0.95
0.04
0.318182
node-utils
447
2024-05-07T03:53:58.991174
BSD-3-Clause
false
df96a2950caa5a8d321e65fdfa3c5efc
//\n// ShadowsocksCipherOptions.swift\n// MullvadVPN\n//\n// Created by pronebird on 13/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct ShadowsocksCipherOptions: RawRepresentable, Codable, Hashable, Sendable {\n public let rawValue: CipherIdentifiers\n\n public init(rawValue: CipherIdentifiers) {\n self.rawValue = rawValue\n }\n\n /// Default cipher.\n public static let `default` = ShadowsocksCipherOptions(rawValue: .CHACHA20)\n\n /// All supported ciphers.\n public static let all = CipherIdentifiers.allCases.map { ShadowsocksCipherOptions(rawValue: $0) }\n}\n\npublic enum CipherIdentifiers: String, CaseIterable, CustomStringConvertible, Codable, Sendable {\n // Stream ciphers.\n case CFB_AES128 = "aes-128-cfb"\n case CFB1_AES128 = "aes-128-cfb1"\n case CFB8_AES128 = "aes-128-cfb8"\n case CFB128_AES128 = "aes-128-cfb128"\n case CFB_AES256 = "aes-256-cfb"\n case CFB1_AES256 = "aes-256-cfb1"\n case CFB8_AES256 = "aes-256-cfb8"\n case CFB128_AES256 = "aes-256-cfb128"\n case RC4 = "rc4"\n case RC4_MD5 = "rc4-md5"\n case CHACHA20 = "chacha20"\n case SALSA20 = "salsa20"\n case CHACHA20_IETF = "chacha20-ietf"\n\n // AEAD ciphers.\n case GCM_AES128 = "aes-128-gcm"\n case GCM_AES256 = "aes-256-gcm"\n case CHACHA20_IETF_POLY1305 = "chacha20-ietf-poly1305"\n case XCHACHA20_IETF_POLY1305 = "xchacha20-ietf-poly1305"\n case PMAC_SIV_AES128 = "aes-128-pmac-siv"\n case GPMAC_SIV_AES256 = "aes-256-pmac-siv"\n\n public var description: String {\n rawValue\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\ShadowsocksCipherOptions.swift
ShadowsocksCipherOptions.swift
Swift
1,588
0.95
0
0.25
awesome-app
837
2023-07-12T00:28:31.506055
GPL-3.0
false
2a17c57977f792e0f30284f8e93cfa7f
//\n// StoredAccountData.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-07-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct StoredAccountData: Codable, Equatable, Sendable {\n /// Account identifier.\n public var identifier: String\n\n /// Account number.\n public var number: String\n\n /// Account expiry.\n public var expiry: Date\n\n /// Returns `true` if account has expired.\n public var isExpired: Bool {\n expiry <= Date()\n }\n\n public init(identifier: String, number: String, expiry: Date) {\n self.identifier = identifier\n self.number = number\n self.expiry = expiry\n }\n}\n\nextension StoredAccountData {\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n self.identifier = try container.decode(String.self, forKey: .identifier)\n self.number = try container.decode(String.self, forKey: .number)\n self.expiry = try container.decode(Date.self, forKey: .expiry)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\StoredAccountData.swift
StoredAccountData.swift
Swift
1,075
0.95
0.125
0.333333
vue-tools
654
2024-03-31T07:23:42.155653
MIT
false
d6bae516ead516d469594871226229c9
//\n// StoredDeviceData.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-07-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n@preconcurrency import WireGuardKitTypes\n\npublic struct StoredDeviceData: Codable, Equatable, Sendable {\n /// Device creation date.\n public var creationDate: Date\n\n /// Device identifier.\n public var identifier: String\n\n /// Device name.\n public var name: String\n\n /// Whether relay hijacks DNS from this device.\n public var hijackDNS: Bool\n\n /// IPv4 address + mask assigned to device.\n public var ipv4Address: IPAddressRange\n\n /// IPv6 address + mask assigned to device.\n public var ipv6Address: IPAddressRange\n\n /// WireGuard key data.\n public var wgKeyData: StoredWgKeyData\n\n /// Returns capitalized device name.\n public var capitalizedName: String {\n name.capitalized\n }\n\n public init(\n creationDate: Date,\n identifier: String,\n name: String,\n hijackDNS: Bool,\n ipv4Address: IPAddressRange,\n ipv6Address: IPAddressRange,\n wgKeyData: StoredWgKeyData\n ) {\n self.creationDate = creationDate\n self.identifier = identifier\n self.name = name\n self.hijackDNS = hijackDNS\n self.ipv4Address = ipv4Address\n self.ipv6Address = ipv6Address\n self.wgKeyData = wgKeyData\n }\n\n /// Fill in part of the structure that contains device related properties from `Device` struct.\n public mutating func update(from device: Device) {\n identifier = device.id\n name = device.name\n creationDate = device.created\n hijackDNS = device.hijackDNS\n ipv4Address = device.ipv4Address\n ipv6Address = device.ipv6Address\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\StoredDeviceData.swift
StoredDeviceData.swift
Swift
1,799
0.95
0
0.285714
node-utils
808
2024-01-26T17:46:27.905340
Apache-2.0
false
561e145981488587357c72ac594fee1f
//\n// StoredWgKeyData.swift\n// MullvadSettings\n//\n// Created by Marco Nikic on 2023-10-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@preconcurrency import WireGuardKitTypes\n\npublic struct StoredWgKeyData: Codable, Equatable, Sendable {\n /// Private key creation date.\n public var creationDate: Date\n\n /// Last date a rotation was attempted. Nil if last attempt was successful.\n public var lastRotationAttemptDate: Date?\n\n /// Private key.\n public var privateKey: PrivateKey\n\n /// Next private key we're trying to rotate to.\n /// Added in 2023.3\n public var nextPrivateKey: PrivateKey?\n\n public init(\n creationDate: Date,\n lastRotationAttemptDate: Date? = nil,\n privateKey: PrivateKey,\n nextPrivateKey: PrivateKey? = nil\n ) {\n self.creationDate = creationDate\n self.lastRotationAttemptDate = lastRotationAttemptDate\n self.privateKey = privateKey\n self.nextPrivateKey = nextPrivateKey\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\StoredWgKeyData.swift
StoredWgKeyData.swift
Swift
1,023
0.95
0.027027
0.387097
vue-tools
61
2023-07-21T15:27:31.638240
BSD-3-Clause
false
908be9d1eee12de4f4df502547270e52
//\n// TunnelSettings.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-07-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Alias to the latest version of the `TunnelSettings`.\npublic typealias LatestTunnelSettings = TunnelSettingsV7\n\n/// Protocol all TunnelSettings must adhere to, for upgrade purposes.\npublic protocol TunnelSettings: Codable, Sendable {\n func upgradeToNextVersion() -> any TunnelSettings\n}\n\n/// Settings and device state schema versions.\npublic enum SchemaVersion: Int, Equatable, Sendable {\n /// Legacy settings format, stored as `TunnelSettingsV1`.\n case v1 = 1\n\n /// New settings format, stored as `TunnelSettingsV2`.\n case v2 = 2\n\n /// V2 format with WireGuard obfuscation options, stored as `TunnelSettingsV3`.\n case v3 = 3\n\n /// V3 format with post quantum options, stored as `TunnelSettingsV4`.\n case v4 = 4\n\n /// V4 format with multi-hop options, stored as `TunnelSettingsV5`.\n case v5 = 5\n\n /// V5 format with DAITA settings, stored as `TunnelSettingsV6`.\n case v6 = 6\n\n /// V6 format with Local network sharing, stored as `TunnelSettingsV7`.\n case v7 = 7\n\n var settingsType: any TunnelSettings.Type {\n switch self {\n case .v1: return TunnelSettingsV1.self\n case .v2: return TunnelSettingsV2.self\n case .v3: return TunnelSettingsV3.self\n case .v4: return TunnelSettingsV4.self\n case .v5: return TunnelSettingsV5.self\n case .v6: return TunnelSettingsV6.self\n case .v7: return TunnelSettingsV7.self\n }\n }\n\n var nextVersion: Self {\n switch self {\n case .v1: return .v2\n case .v2: return .v3\n case .v3: return .v4\n case .v4: return .v5\n case .v5: return .v6\n case .v6: return .v7\n case .v7: return .v7\n }\n }\n\n /// Current schema version.\n public static let current = SchemaVersion.v7\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettings.swift
TunnelSettings.swift
Swift
1,950
0.95
0.044118
0.327273
react-lib
592
2024-06-06T07:47:30.260359
Apache-2.0
false
6db9091c7462f6e2374ddd8e82ab854e
//\n// TunnelSettingsPropagator.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-08-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\n\npublic protocol SettingsPropagation: Sendable {\n typealias SettingsHandler = (LatestTunnelSettings) -> Void\n var onNewSettings: SettingsHandler? { get set }\n}\n\npublic protocol SettingsObserver: AnyObject {\n func didUpdateSettings(_ settings: LatestTunnelSettings)\n}\n\npublic class SettingsObserverBlock: SettingsObserver {\n public typealias DidUpdateSettingsHandler = (LatestTunnelSettings) -> Void\n public var onNewSettings: DidUpdateSettingsHandler\n\n public init(didUpdateSettings: @escaping DidUpdateSettingsHandler) {\n self.onNewSettings = didUpdateSettings\n }\n\n public func didUpdateSettings(_ settings: LatestTunnelSettings) {\n self.onNewSettings(settings)\n }\n}\n\npublic final class TunnelSettingsListener: SettingsPropagation, @unchecked Sendable {\n public var onNewSettings: SettingsHandler?\n\n public init(onNewSettings: SettingsHandler? = nil) {\n self.onNewSettings = onNewSettings\n }\n}\n\npublic final class SettingsUpdater: Sendable {\n /// Observers.\n private let observerList = ObserverList<SettingsObserver>()\n nonisolated(unsafe) private var listener: SettingsPropagation\n\n public init(listener: SettingsPropagation) {\n self.listener = listener\n self.listener.onNewSettings = { [weak self] settings in\n guard let self else { return }\n self.observerList.notify {\n $0.didUpdateSettings(settings)\n }\n }\n }\n\n // MARK: - Multihop observations\n\n public func addObserver(_ observer: SettingsObserver) {\n observerList.append(observer)\n }\n\n public func removeObserver(_ observer: SettingsObserver) {\n observerList.remove(observer)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsPropagator.swift
TunnelSettingsPropagator.swift
Swift
1,889
0.95
0.046154
0.173077
vue-tools
537
2025-04-08T03:02:51.908782
BSD-3-Clause
false
cf9a59072f966fd422740779d4a32bc6