summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadREST/Relay/RelaySelector+Wireguard.swift
blob: aab6e73d0439ebd94108b736f7db104c5e47bc20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//
//  RelaySelector+Wireguard.swift
//  MullvadREST
//
//  Created by Mojgan on 2024-05-17.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import CoreLocation
import MullvadSettings
import MullvadTypes

extension RelaySelector {
    public enum WireGuard {
        /// Filters relay list using given constraints.
        public static func findCandidates(
            by relayConstraint: RelayConstraint<UserSelectedRelays>,
            in relays: REST.ServerRelaysResponse,
            filterConstraint: RelayConstraint<RelayFilter>,
            daitaEnabled: Bool
        ) throws -> [RelayWithLocation<REST.ServerRelay>] {
            let mappedRelays = RelayWithLocation.locateRelays(
                relays: relays.wireguard.relays,
                locations: relays.locations
            )

            return try applyConstraints(
                relayConstraint,
                filterConstraint: filterConstraint,
                daitaEnabled: daitaEnabled,
                relays: mappedRelays
            )
        }

        /// Picks a random relay from a list.
        public static func pickCandidate(
            from relayWithLocations: [RelayWithLocation<REST.ServerRelay>],
            wireguard: REST.ServerWireguardTunnels,
            portConstraint: RelayConstraint<UInt16>,
            numberOfFailedAttempts: UInt,
            closeTo referenceLocation: Location? = nil
        ) throws -> RelaySelectorMatch {
            let port = try evaluatePort(
                portConstraint: portConstraint,
                rawPortRanges: wireguard.portRanges,
                numberOfFailedAttempts: numberOfFailedAttempts
            )

            var relayWithLocation: RelayWithLocation<REST.ServerRelay>?
            if let referenceLocation {
                let relay = closestRelay(
                    to: CLLocationCoordinate2D(
                        latitude: referenceLocation.latitude, longitude: referenceLocation.longitude),
                    using: relayWithLocations
                )
                relayWithLocation = relayWithLocations.first(where: { $0.relay == relay })
            }

            guard
                let relayWithLocation = relayWithLocation ?? pickRandomRelayByWeight(relays: relayWithLocations)
            else {
                throw NoRelaysSatisfyingConstraintsError(.relayConstraintNotMatching)
            }

            return createMatch(for: relayWithLocation, port: port, wireguard: wireguard)
        }

        public static func closestRelay(
            to location: CLLocationCoordinate2D,
            using relayWithLocations: [RelayWithLocation<REST.ServerRelay>]
        ) -> REST.ServerRelay? {
            let relaysWithDistance = relayWithLocations.map {
                RelayWithDistance(
                    relay: $0.relay,
                    distance: Haversine.distance(
                        location.latitude,
                        location.longitude,
                        $0.serverLocation.latitude,
                        $0.serverLocation.longitude
                    )
                )
            }.sorted {
                $0.distance < $1.distance
            }.prefix(5)

            let relaysGroupedByDistance = Dictionary(grouping: relaysWithDistance, by: { $0.distance })
            guard let closetsRelayGroup = relaysGroupedByDistance.min(by: { $0.key < $1.key })?.value else {
                return nil
            }

            var greatestDistance = 0.0
            closetsRelayGroup.forEach {
                if $0.distance > greatestDistance {
                    greatestDistance = $0.distance
                }
            }

            let closestRelay = rouletteSelection(
                relays: closetsRelayGroup,
                weightFunction: { relay in
                    UInt64(1 + greatestDistance - relay.distance)
                })

            return closestRelay?.relay
        }
    }

    private static func evaluatePort(
        portConstraint: RelayConstraint<UInt16>,
        rawPortRanges: [[UInt16]],
        numberOfFailedAttempts: UInt
    ) throws -> UInt16 {
        let port = applyPortConstraint(
            portConstraint,
            rawPortRanges: rawPortRanges,
            numberOfFailedAttempts: numberOfFailedAttempts
        )

        guard let port else {
            throw NoRelaysSatisfyingConstraintsError(.invalidPort)
        }

        return port
    }

    private static func createMatch(
        for relayWithLocation: RelayWithLocation<REST.ServerRelay>,
        port: UInt16,
        wireguard: REST.ServerWireguardTunnels
    ) -> RelaySelectorMatch {
        let endpoint = MullvadEndpoint(
            ipv4Relay: IPv4Endpoint(
                ip: relayWithLocation.relay.ipv4AddrIn,
                port: port
            ),
            ipv6Relay: nil,
            ipv4Gateway: wireguard.ipv4Gateway,
            ipv6Gateway: wireguard.ipv6Gateway,
            publicKey: relayWithLocation.relay.publicKey
        )

        return RelaySelectorMatch(
            endpoint: endpoint,
            relay: relayWithLocation.relay,
            location: relayWithLocation.serverLocation
        )
    }
}