summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/RelayCache.swift
blob: c561303e49041854be808b09581ae3dedeed5daf (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//
//  RelayCache.swift
//  MullvadVPN
//
//  Created by pronebird on 05/06/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import Foundation
import Logging

/// Periodic update interval
private let kUpdateIntervalSeconds = 3600

/// Error emitted by read and write functions
enum RelayCacheError: ChainedError {
    case readCache(Error)
    case readPrebundledRelays(Error)
    case decodePrebundledRelays(Error)
    case writeCache(Error)
    case encodeCache(Error)
    case decodeCache(Error)
    case rest(RestError)

    var errorDescription: String? {
        switch self {
        case .encodeCache:
            return "Encode cache error"
        case .decodeCache:
            return "Decode cache error"
        case .readCache:
            return "Read cache error"
        case .readPrebundledRelays:
            return "Read pre-bundled relays error"
        case .decodePrebundledRelays:
            return "Decode pre-bundled relays error"
        case .writeCache:
            return "Write cache error"
        case .rest:
            return "REST error"
        }
    }
}

protocol RelayCacheObserver: class {
    func relayCache(_ relayCache: RelayCache, didUpdateCachedRelays cachedRelays: CachedRelays)
}

private class AnyRelayCacheObserver: WeakObserverBox, RelayCacheObserver {

    typealias Wrapped = RelayCacheObserver

    private(set) weak var inner: RelayCacheObserver?

    init<T: RelayCacheObserver>(_ inner: T) {
        self.inner = inner
    }

    func relayCache(_ relayCache: RelayCache, didUpdateCachedRelays cachedRelays: CachedRelays) {
        inner?.relayCache(relayCache, didUpdateCachedRelays: cachedRelays)
    }

    static func == (lhs: AnyRelayCacheObserver, rhs: AnyRelayCacheObserver) -> Bool {
        return lhs.inner === rhs.inner
    }
}

class RelayCache {
    private let logger = Logger(label: "RelayCache")

    /// Mullvad REST client
    private let rest: MullvadRest

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

    /// A dispatch queue used for thread synchronization
    private let dispatchQueue = DispatchQueue(label: "net.mullvad.MullvadVPN.RelayCache")

    /// A timer source used for periodic updates
    private var timerSource: DispatchSourceTimer?

    /// A flag that indicates whether periodic updates are running
    private var isPeriodicUpdatesEnabled = false

    /// A download task used for relay RPC request
    private var downloadTask: URLSessionTask?

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

        return containerURL.appendingPathComponent("relays.json")
    }

    /// The path to the pre-bundled relays.json file
    private static var preBundledRelaysFileURL: URL {
        return Bundle.main.url(forResource: "relays", withExtension: "json")!
    }

    /// Observers
    private let observerList = ObserverList<AnyRelayCacheObserver>()

    /// A shared instance of `RelayCache`
    static let shared = RelayCache(cacheFileURL: defaultCacheFileURL, networkSession: URLSession(configuration: .ephemeral))

    private init(cacheFileURL: URL, networkSession: URLSession) {
        rest = MullvadRest(session: networkSession)
        self.cacheFileURL = cacheFileURL
    }

    func startPeriodicUpdates(queue: DispatchQueue?, completionHandler: (() -> Void)?) {
        dispatchQueue.async {
            if !self.isPeriodicUpdatesEnabled {
                self.isPeriodicUpdatesEnabled = true

                switch Self.read(cacheFileURL: self.cacheFileURL) {
                case .success(let cachedRelayList):
                    if let nextUpdate = Self.nextUpdateDate(lastUpdatedAt: cachedRelayList.updatedAt) {
                        let startTime = Self.makeWalltime(fromDate: nextUpdate)
                        self.scheduleRepeatingTimer(startTime: startTime)
                    }

                case .failure(let readError):
                    self.logger.error(chainedError: readError, message: "Failed to read the relay cache")

                    if Self.shouldDownloadRelaysOnReadFailure(readError) {
                        self.scheduleRepeatingTimer(startTime: .now())
                    }
                }
            }

            queue.performOnWrappedOrCurrentQueue {
                completionHandler?()
            }
        }
    }

    func stopPeriodicUpdates(queue: DispatchQueue?, completionHandler: (() -> Void)?) {
        dispatchQueue.async {
            self.isPeriodicUpdatesEnabled = false

            self.timerSource?.cancel()
            self.timerSource = nil
            self.downloadTask?.cancel()

            queue.performOnWrappedOrCurrentQueue {
                completionHandler?()
            }
        }
    }

    func updateRelays() {
        dispatchQueue.async {
            self._updateRelays()
        }
    }

    /// Read the relay cache from disk
    func read(completionHandler: @escaping (Result<CachedRelays, RelayCacheError>) -> Void) {
        dispatchQueue.async {
            let result = Self.read(cacheFileURL: self.cacheFileURL)
                .flatMapError { (error) -> Result<CachedRelays, RelayCacheError> in
                    switch error {
                    case .decodeCache, .readCache(CocoaError.fileReadNoSuchFile):
                        return Self.readPrebundledRelays(fileURL: Self.preBundledRelaysFileURL)
                    default:
                        return .failure(error)
                    }
            }
            completionHandler(result)
        }
    }

    // MARK: - Observation

    func addObserver<T: RelayCacheObserver>(_ observer: T) {
        observerList.append(AnyRelayCacheObserver(observer))
    }

    func removeObserver<T: RelayCacheObserver>(_ observer: T) {
        observerList.remove(AnyRelayCacheObserver(observer))
    }

    // MARK: - Private instance methods

    private func _updateRelays() {
        switch Self.read(cacheFileURL: self.cacheFileURL) {
        case .success(let cachedRelays):
            let nextUpdate = Self.nextUpdateDate(lastUpdatedAt: cachedRelays.updatedAt)

            if let nextUpdate = nextUpdate, nextUpdate <= Date() {
                self.downloadRelays()
            }

        case .failure(let readError):
            self.logger.error(chainedError: readError, message: "Failed to read the relay cache")

            if Self.shouldDownloadRelaysOnReadFailure(readError) {
                self.downloadRelays()
            }
        }
    }

    private func downloadRelays() {
        let taskResult = makeDownloadTask { (result) in
            let result = result.flatMap { (relays) -> Result<CachedRelays, RelayCacheError> in
                let cachedRelays = CachedRelays(relays: relays, updatedAt: Date())

                return Self.write(cacheFileURL: self.cacheFileURL, record: cachedRelays)
                    .map { cachedRelays }
            }

            switch result {
            case .success(let cachedRelays):
                let numRelays = cachedRelays.relays.wireguard.relays.count

                self.logger.info("Downloaded \(numRelays) relays")

                self.observerList.forEach { (observer) in
                    observer.relayCache(self, didUpdateCachedRelays: cachedRelays)
                }

            case .failure(let error):
                self.logger.error(chainedError: error, message: "Failed to update the relays")
            }
        }

        downloadTask?.cancel()

        switch taskResult {
        case .success(let newDownloadTask):
            downloadTask = newDownloadTask
            newDownloadTask.resume()

        case .failure(let restError):
            self.logger.error(chainedError: restError, message: "Failed to create a REST request for updating relays")
            downloadTask = nil
        }
    }

    private func scheduleRepeatingTimer(startTime: DispatchWallTime) {
        let timerSource = DispatchSource.makeTimerSource(queue: dispatchQueue)
        timerSource.setEventHandler { [weak self] in
            guard let self = self else { return }

            if self.isPeriodicUpdatesEnabled {
                self._updateRelays()
            }
        }

        timerSource.schedule(wallDeadline: startTime, repeating: .seconds(kUpdateIntervalSeconds))
        timerSource.activate()

        self.timerSource = timerSource
    }

    private func makeDownloadTask(completionHandler: @escaping (Result<ServerRelaysResponse, RelayCacheError>) -> Void) -> Result<URLSessionDataTask, RestError> {
        return rest.getRelays().dataTask(payload: EmptyPayload()) { (result) in
            self.dispatchQueue.async {
                completionHandler(result.mapError { RelayCacheError.rest($0) })
            }
        }
    }

    // MARK: - Private class methods

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

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

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

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

        return result!
    }

    private class func readPrebundledRelays(fileURL: URL) -> Result<CachedRelays, RelayCacheError> {
        return Result { try Data(contentsOf: fileURL) }
            .mapError { RelayCacheError.readPrebundledRelays($0) }
            .flatMap { (data) -> Result<CachedRelays, RelayCacheError> in
                return Result { try MullvadRest.makeJSONDecoder().decode(ServerRelaysResponse.self, from: data) }
                    .mapError { RelayCacheError.decodePrebundledRelays($0) }
                    .map { (relays) -> CachedRelays in
                        return CachedRelays(
                            relays: relays,
                            updatedAt: Date(timeIntervalSince1970: 0)
                        )
                }
        }
    }

    /// Safely write the cache file on disk using file coordinator
    private class func write(cacheFileURL: URL, record: CachedRelays) -> 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.encodeCache($0) }
                .flatMap { (data) in
                    Result { try data.write(to: fileURLForWriting) }
                        .mapError { RelayCacheError.writeCache($0) }
                }
        }

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

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

        return result!
    }

    private class func makeWalltime(fromDate date: Date) -> DispatchWallTime {
        let (seconds, frac) = modf(date.timeIntervalSince1970)

        let nsec: Double = frac * Double(NSEC_PER_SEC)
        let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec))

        return DispatchWallTime(timespec: walltime)
    }

    private class func nextUpdateDate(lastUpdatedAt: Date) -> Date? {
        return Calendar.current.date(
            byAdding: .second,
            value: kUpdateIntervalSeconds,
            to: lastUpdatedAt
        )
    }

    private class func shouldDownloadRelaysOnReadFailure(_ error: RelayCacheError) -> Bool {
        switch error {
        case .readPrebundledRelays, .decodePrebundledRelays, .decodeCache:
            return true

        case .readCache(CocoaError.fileReadNoSuchFile):
            return true

        default:
            return false
        }
    }
}

/// A struct that represents the relay cache on disk
struct CachedRelays: Codable {
    /// The relay list stored within the cache entry
    var relays: ServerRelaysResponse

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