summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/RelayCache.swift
blob: 1aec01c72c8428d4673255476a28ddfaf8b0f813 (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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//
//  RelayCache.swift
//  MullvadVPN
//
//  Created by pronebird on 05/06/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import Foundation
import Combine
import os

/// Error emitted by read and write functions
enum RelayCacheError: Error {
    case defaultLocationNotFound
    case io(Error)
    case coding(Error)
    case network(MullvadAPI.Error)
    case server(JsonRpcResponseError<MullvadAPI.ResponseCode>)
}

/// A enum describing the source of the relay list
enum RelayListSource {
    /// The relay list was received from network
    case network

    /// The relay list was read from cache
    case cache
}

class RelayCache {

    /// Mullvad API client
    private let apiClient: MullvadAPI

    /// The cache location used by the class instance
    private let cacheFileURL: URL

    /// A queue used for running cache requests that require mutual exclusivity
    private let exclusivityQueue = DispatchQueue(label: "net.mullvad.vpn.relay-cache.exclusivity-queue")

    /// A queue used for execution
    private let executionQueue = DispatchQueue(label: "net.mullvad.vpn.relay-cache.execution-queue")

    /// The default cache file location
    static var defaultCacheFileURL: URL? {
        let appGroupIdentifier = ApplicationConfiguration.securityGroupIdentifier
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)

        return containerURL.flatMap { URL(fileURLWithPath: "relays.json", relativeTo: $0) }
    }

    init(cacheFileURL: URL, networkSession: URLSession = URLSession.shared) {
        apiClient = MullvadAPI(session: networkSession)
        self.cacheFileURL = cacheFileURL
    }

    class func withDefaultLocation() -> Result<RelayCache, RelayCacheError> {
        if let cacheFileURL = defaultCacheFileURL {
            return .success(RelayCache(cacheFileURL: cacheFileURL))
        } else {
            return .failure(.defaultLocationNotFound)
        }
    }

    /// Read the relay cache and update it from remote if needed.
    func read() -> AnyPublisher<CachedRelayList, RelayCacheError> {
        MutuallyExclusive(exclusivityQueue: exclusivityQueue, executionQueue: executionQueue) {
            self.makeReaderPublisher()
        }.eraseToAnyPublisher()
    }

    private func makeReaderPublisher() -> AnyPublisher<CachedRelayList, RelayCacheError> {
        // Create a deferred publisher that will execute once the subscriber is assigned
        let downloadAndSaveRelaysPublisher = Deferred {
            return self.downloadRelays()
                .map(self.filterRelayList)
                .flatMap(self.saveRelayListToCache)
                .mapError { (error) -> RelayCacheError in
                    os_log(.error, "Failed to update the relay cache: %{public}s", error.localizedDescription)

                    return error
            }
        }

        return Self.read(cacheFileURL: cacheFileURL).publisher
            .map { (RelayListSource.cache, $0) }
            .catch({ (readError) -> AnyPublisher<(RelayListSource, CachedRelayList), RelayCacheError> in
                switch readError {
                // Download relay list when unable to read the cache file
                case .io(let error as CocoaError) where error.code == .fileReadNoSuchFile:
                    os_log(.error, "Relay cache file does not exist. Initiating the download.")

                    return downloadAndSaveRelaysPublisher.map { (RelayListSource.network, $0) }
                        .eraseToAnyPublisher()

                case .coding(let decodingError):
                    os_log(.error, "Failed to decode the relay cache: %{public}s", decodingError.localizedDescription)

                    return downloadAndSaveRelaysPublisher.map { (RelayListSource.network, $0) }
                        .eraseToAnyPublisher()

                default:
                    os_log(.error, "Failed to read the relay cache: %{public}s", readError.localizedDescription)

                    return Fail(error: readError).eraseToAnyPublisher()
                }
            })
            .flatMap { (source, cachedRelays) -> AnyPublisher<CachedRelayList, RelayCacheError> in
                let cachedRelayPublisher = Result<CachedRelayList, RelayCacheError>.Publisher(cachedRelays)

                if source == .cache && cachedRelays.needsUpdate() {
                    return downloadAndSaveRelaysPublisher
                        .catch { (error) -> Result<CachedRelayList, RelayCacheError>.Publisher in
                            // Return the on-disk cache in the event of networking error
                            return cachedRelayPublisher
                    }.eraseToAnyPublisher()
                } else {
                    return cachedRelayPublisher
                        .eraseToAnyPublisher()
                }
        }.eraseToAnyPublisher()
    }

    /// Filters the given `RelayList` removing empty leaf nodes, relays without Wireguard tunnels or
    /// Wireguard tunnels without any available ports.
    private func filterRelayList(_ relayList: RelayList) -> RelayList {
        let filteredCountries = relayList.countries
            .map { (country) -> RelayList.Country in
                var filteredCountry = country

                filteredCountry.cities = country.cities.map { (city) -> RelayList.City in
                    var filteredCity = city

                    filteredCity.relays = city.relays
                        .map { (relay) -> RelayList.Hostname in
                            var filteredRelay = relay

                            // filter out tunnels without ports
                            filteredRelay.tunnels?.wireguard = relay.tunnels?.wireguard?
                                .filter { !$0.portRanges.isEmpty }

                            return filteredRelay
                    }.filter { $0.tunnels?.wireguard.flatMap { !$0.isEmpty } ?? false }

                    return filteredCity
                }.filter { !$0.relays.isEmpty }

                return filteredCountry
        }.filter { !$0.cities.isEmpty }

        return RelayList(countries: filteredCountries)
    }

    private func downloadRelays() -> AnyPublisher<RelayList, RelayCacheError> {
        apiClient.getRelayList()
            .mapError({ (networkError) -> RelayCacheError in
                return .network(networkError)
            })
            .flatMap({ (response) in
                return response.result.publisher
                    .mapError { RelayCacheError.server($0) }
            }).eraseToAnyPublisher()
    }

    private func saveRelayListToCache(relayList: RelayList) -> AnyPublisher<CachedRelayList, RelayCacheError> {
        Result.Publisher(relayList)
            .map({ CachedRelayList(relayList: $0, updatedAt: Date()) })
            .flatMap({ (cachedRelayList) in
                return Self.write(cacheFileURL: self.cacheFileURL, record: cachedRelayList)
                    .map { cachedRelayList }
                    .publisher
            }).eraseToAnyPublisher()
    }

    /// Safely read the cache file from disk using file coordinator
    private class func read(cacheFileURL: URL) -> Result<CachedRelayList, RelayCacheError> {
        var result: Result<CachedRelayList, RelayCacheError>?
        let fileCoordinator = NSFileCoordinator(filePresenter: nil)

        let accessor = { (fileURLForReading: URL) -> Void in
            // Decode data from disk
            result = Result { try Data(contentsOf: fileURLForReading) }
                .mapError { RelayCacheError.io($0) }
                .flatMap { (data) in
                    Result { try JSONDecoder().decode(CachedRelayList.self, from: data) }
                        .mapError { RelayCacheError.coding($0) }
                }
        }

        var error: NSError?
        fileCoordinator.coordinate(readingItemAt: cacheFileURL,
                                   options: [.withoutChanges],
                                   error: &error,
                                   byAccessor: accessor)

        if let error = error {
            result = .failure(.io(error))
        }

        return result!
    }

    /// Safely write the cache file on disk using file coordinator
    private class func write(cacheFileURL: URL, record: CachedRelayList) -> Result<(), RelayCacheError> {
        var result: Result<(), RelayCacheError>?
        let fileCoordinator = NSFileCoordinator(filePresenter: nil)

        let accessor = { (fileURLForWriting: URL) -> Void in
            result = Result { try JSONEncoder().encode(record) }
                .mapError { RelayCacheError.coding($0) }
                .flatMap { (data) in
                    Result { try data.write(to: fileURLForWriting) }
                        .mapError { RelayCacheError.io($0) }
                }
        }

        var error: NSError?
        fileCoordinator.coordinate(writingItemAt: cacheFileURL,
                                   options: [.forReplacing],
                                   error: &error,
                                   byAccessor: accessor)

        if let error = error {
            result = .failure(.io(error))
        }

        return result!
    }
}

/// A struct that represents the relay cache on disk
struct CachedRelayList: Codable {
    /// The relay list stored within the cache entry
    var relayList: RelayList

    /// The date when this cache was last updated
    var updatedAt: Date
}

private extension CachedRelayList {
    /// Returns true if it's time to refresh the relay list cache
    func needsUpdate() -> Bool {
        let now = Date()
        guard let nextUpdate = Calendar.current.date(byAdding: .hour, value: 1, to: updatedAt) else {
            return false
        }
        return now >= nextUpdate
    }
}