Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / Networking / RelaySocket.swift

RelaySocket.swift458 lines · 19.2 KiBRaw
1import Foundation
2import CryptoKit
3import OSLog
4import UIKit
5
6private let relayLog = Logger(subsystem: "cc.findfamily.ios.swift", category: "Relay")
7
8/// The one long-lived relay socket (`wss://api.maproj.org/api/ws`), mirroring the Android
9/// client (`Networking.kt` + `NetworkingLive.kt`) plus the server's reliable-delivery mode:
10///
11/// client→server SUB_RELIABLE : [0x0D][u8 version=1][u64 userid][PQC bundle…]
12/// server→client SUB_ACK : [0x10][u8 version][u16 idleTimeoutSecs][u16 inflightMax]
13/// server→client MSG_SEQ : [0x0E][flags][u64 seq][ciphertext…]
14/// client→server ACK : [0x0F][u64 seq] (cumulative)
15/// client→server PUB : [0x02][flags][u64 recipient][ciphertext…]
16/// client→server GETKEY : [0x04][u64 target]
17/// server→client KEYRESP : [0x05][status][u64 target][bundle…]
18/// legacy fallback : SUB [0x01][u64 userid][bundle…] / MSG [0x03][flags][ciphertext…]
19///
20/// All integers big-endian; flags bit0 = UWB envelope (else location).
21///
22/// Reliability contract (server side in location_share_server `findfamily.rs`): every
23/// MSG_SEQ stays on the server until we ACK it, and is requeued if the socket dies first.
24/// So each frame is ACKed only after it has been decrypted and stored, and a frame can
25/// arrive twice (ACK lost in a disconnect); `RelayDedup` drops repeats by ciphertext hash.
26///
27/// The HTTP `/api/location/receive_pqc` + `/api/uwb/receive_pqc` drain is kept as a safety
28/// net: once per wake, and on every heartbeat tick while the socket is not subscribed.
29@MainActor
30final class RelaySocket {
31 static let shared = RelaySocket()
32
33 private static let url = URL(string: "wss://api.maproj.org/api/ws")!
34
35 private static let opSub: UInt8 = 0x01
36 private static let opPub: UInt8 = 0x02
37 private static let opMsg: UInt8 = 0x03
38 private static let opGetKeyRequest: UInt8 = 0x04
39 private static let opGetKeyResponse: UInt8 = 0x05
40 private static let opSubReliable: UInt8 = 0x0D
41 private static let opMsgSeq: UInt8 = 0x0E
42 private static let opAck: UInt8 = 0x0F
43 private static let opSubAck: UInt8 = 0x10
44 private static let reliableVersion: UInt8 = 1
45 private static let flagUwb: UInt8 = 0x01
46
47 /// No SUB_ACK within this window means an older server that ignores 0x0D: fall back
48 /// to a plain SUB (no ACKs) on the same socket.
49 private static let subAckTimeout: TimeInterval = 10
50 /// Matches the Android client's GETKEY timeout.
51 private static let keyTimeout: TimeInterval = 5
52 /// Matches Android's reconnect backoff (1 s → 15 s).
53 private static let backoffInitial: TimeInterval = 1
54 private static let backoffMax: TimeInterval = 15
55 /// Ping cadence until SUB_ACK says otherwise: the server's 75 s idle timeout / 3.
56 private static let defaultPingInterval: TimeInterval = 25
57 /// A wake this long after the previous one means the app was suspended in between.
58 private static let wakeGap: TimeInterval = 30
59
60 private let session: URLSession
61
62 private var loopTask: Task<Void, Never>?
63 private var loopID = 0
64 private var wantRunning = false
65
66 /// The connected socket, if any.
67 private var task: URLSessionWebSocketTask?
68 /// True once the server accepted our subscription (SUB_ACK, or the legacy fallback SUB).
69 private(set) var isSubscribed = false
70 /// True when the server confirmed reliable mode (MSG_SEQ + ACK).
71 private var reliable = false
72 private var legacyFallbackSent = false
73 private var pingInterval: TimeInterval = RelaySocket.defaultPingInterval
74 /// Last time anything (frame or pong) arrived on the current socket.
75 private var lastInboundAt = Date.distantPast
76 /// Keepalive for the current socket; started once subscribed, so it uses the interval
77 /// the server advertised in SUB_ACK from the first ping.
78 private var pingTask: Task<Void, Never>?
79
80 private var lastWakeAt = Date.distantPast
81 private var httpDrainInFlight = false
82 private var lifecycleObservers: [NSObjectProtocol] = []
83
84 /// Outstanding GETKEYs on the live socket, keyed by target userid.
85 private var pendingKeys: [Int64: AsyncStream<RelayKeyLookup.KeyResult?>.Continuation] = [:]
86
87 private init() {
88 let cfg = URLSessionConfiguration.default
89 // Surface "offline" as a failed connect (handled by backoff) instead of parking
90 // the handshake until connectivity returns.
91 cfg.waitsForConnectivity = false
92 // Pongs every pingInterval keep traffic flowing well inside this.
93 cfg.timeoutIntervalForRequest = 120
94 self.session = URLSession(configuration: cfg)
95 }
96
97 // MARK: - Lifecycle
98
99 /// Called once after `Networking.start()`: connect now if the app is in the
100 /// foreground, connect whenever it becomes active, and close cleanly when it goes to
101 /// the background without location tracking (iOS would suspend it anyway; a clean
102 /// close lets the server requeue at once instead of after its idle timeout).
103 func beginLifecycle() {
104 guard lifecycleObservers.isEmpty else { return }
105 let center = NotificationCenter.default
106 lifecycleObservers.append(center.addObserver(
107 forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main
108 ) { _ in
109 Task { @MainActor in RelaySocket.shared.wake() }
110 })
111 lifecycleObservers.append(center.addObserver(
112 forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main
113 ) { _ in
114 Task { @MainActor in
115 if !BackgroundTask.shared.isHeartbeatRunning { RelaySocket.shared.stop() }
116 }
117 })
118 if UIApplication.shared.applicationState != .background {
119 wake()
120 }
121 }
122
123 /// Any sign of life: app became active, tracking started, a location update or
124 /// heartbeat tick. Cheap when already connected. Starts the socket if needed, forces
125 /// a reconnect if the current one has gone quiet (typical after suspension), and runs
126 /// one HTTP drain per wake as a safety net.
127 func wake() {
128 guard Networking.shared.isReady, Networking.shared.pqcAvailable else { return }
129 let now = Date()
130 if now.timeIntervalSince(lastWakeAt) > Self.wakeGap {
131 drainHttpOnce()
132 }
133 lastWakeAt = now
134 if let task, isSubscribed, now.timeIntervalSince(lastInboundAt) > pingInterval * 2 {
135 relayLog.notice("socket quiet for \(Int(now.timeIntervalSince(self.lastInboundAt)))s on wake; reconnecting")
136 task.cancel(with: .goingAway, reason: nil)
137 }
138 start()
139 }
140
141 /// Location tracking stopped (not sharing with anyone). Keep the socket unless the app
142 /// is in the background, so the map stays live on screen. Checks `.background` rather
143 /// than `!= .active`: at a cold start the sharing gate runs while the app is still
144 /// `.inactive`, possibly after `didBecomeActive` already fired.
145 func trackingStopped() {
146 guard UIApplication.shared.applicationState == .background else { return }
147 stop()
148 }
149
150 func start() {
151 guard Networking.shared.isReady, Networking.shared.pqcAvailable else { return }
152 wantRunning = true
153 guard loopTask == nil else { return }
154 loopID += 1
155 let id = loopID
156 loopTask = Task { [weak self] in
157 await self?.runLoop()
158 if self?.loopID == id { self?.loopTask = nil }
159 }
160 }
161
162 /// Closes the socket cleanly (the server then requeues anything we did not ACK).
163 func stop() {
164 wantRunning = false
165 loopID += 1
166 loopTask?.cancel()
167 loopTask = nil
168 if let task {
169 task.cancel(with: .normalClosure, reason: nil)
170 teardown(task)
171 }
172 }
173
174 // MARK: - Connection loop
175
176 private func runLoop() async {
177 var backoff = Self.backoffInitial
178 while wantRunning && !Task.isCancelled {
179 let subscribed = await runOneConnection()
180 if !wantRunning || Task.isCancelled { break }
181 if subscribed { backoff = Self.backoffInitial }
182 try? await Task.sleep(nanoseconds: UInt64(backoff * 1_000_000_000))
183 backoff = min(backoff * 2, Self.backoffMax)
184 }
185 }
186
187 /// One socket from connect to death. Returns whether it got subscribed.
188 private func runOneConnection() async -> Bool {
189 let task = session.webSocketTask(with: Self.url)
190 self.task = task
191 isSubscribed = false
192 reliable = false
193 legacyFallbackSent = false
194 pingInterval = Self.defaultPingInterval
195 lastInboundAt = Date()
196 task.resume()
197
198 var everSubscribed = false
199 defer { teardown(task) }
200
201 guard (try? await task.send(.data(subscribeFrame(op: Self.opSubReliable)))) != nil else {
202 return false
203 }
204 let fallback = Task { [weak self] in
205 guard let self else { return }
206 await self.legacyFallbackIfNoSubAck(task)
207 }
208 defer { fallback.cancel() }
209
210 do {
211 while true {
212 let message = try await task.receive()
213 lastInboundAt = Date()
214 guard case .data(let frame) = message else { continue }
215 await handle(frame, on: task)
216 if isSubscribed { everSubscribed = true }
217 }
218 } catch {
219 relayLog.notice("relay socket ended: \(error.localizedDescription)")
220 }
221 return everSubscribed
222 }
223
224 /// Clears per-socket state, but only if `task` is still the current socket (a stop()
225 /// followed by start() may already have replaced it).
226 private func teardown(_ task: URLSessionWebSocketTask) {
227 guard self.task === task else { return }
228 task.cancel(with: .goingAway, reason: nil)
229 self.task = nil
230 pingTask?.cancel()
231 pingTask = nil
232 isSubscribed = false
233 reliable = false
234 for (_, waiter) in pendingKeys { waiter.finish() }
235 pendingKeys.removeAll()
236 }
237
238 /// Pings every `pingInterval` (the server closes reliable sockets after 3 silent
239 /// intervals) and, like Android's supervisor, treats 3 intervals without any inbound
240 /// frame or pong as a half-open socket and forces a reconnect.
241 private func pingLoop(_ task: URLSessionWebSocketTask) async {
242 while !Task.isCancelled {
243 try? await Task.sleep(nanoseconds: UInt64(pingInterval * 1_000_000_000))
244 if Task.isCancelled || self.task !== task { return }
245 task.sendPing { error in
246 guard error == nil else { return }
247 Task { @MainActor in
248 if RelaySocket.shared.task === task { RelaySocket.shared.lastInboundAt = Date() }
249 }
250 }
251 let idle = Date().timeIntervalSince(lastInboundAt)
252 if idle > pingInterval * 3 {
253 relayLog.notice("no inbound for \(Int(idle))s; socket half-open, reconnecting")
254 task.cancel(with: .goingAway, reason: nil)
255 return
256 }
257 }
258 }
259
260 private func legacyFallbackIfNoSubAck(_ task: URLSessionWebSocketTask) async {
261 try? await Task.sleep(nanoseconds: UInt64(Self.subAckTimeout * 1_000_000_000))
262 guard !Task.isCancelled, self.task === task, !isSubscribed else { return }
263 relayLog.notice("no SUB_ACK; server predates reliable mode, falling back to plain SUB")
264 legacyFallbackSent = true
265 guard (try? await task.send(.data(subscribeFrame(op: Self.opSub)))) != nil else { return }
266 if self.task === task { markSubscribed(reliable: false, on: task) }
267 }
268
269 private func markSubscribed(reliable: Bool, on task: URLSessionWebSocketTask) {
270 self.reliable = reliable
271 isSubscribed = true
272 lastInboundAt = Date()
273 pingTask?.cancel()
274 pingTask = Task { [weak self] in
275 guard let self else { return }
276 await self.pingLoop(task)
277 }
278 relayLog.info("relay subscribed reliable=\(reliable) ping=\(Int(self.pingInterval))s")
279 }
280
281 // MARK: - Frames
282
283 /// `[op][(version)][u64 userid][PQC bundle…]` — SUB doubles as registration.
284 private func subscribeFrame(op: UInt8) -> Data {
285 var frame = Data([op])
286 if op == Self.opSubReliable { frame.append(Self.reliableVersion) }
287 Self.appendU64(&frame, UInt64(bitPattern: Networking.shared.userid))
288 if let bundle = Networking.shared.pqcPublicBundle { frame.append(bundle) }
289 return frame
290 }
291
292 private func handle(_ frame: Data, on task: URLSessionWebSocketTask) async {
293 let bytes = [UInt8](frame)
294 guard let op = bytes.first else { return }
295 switch op {
296 case Self.opSubAck:
297 // [0x10][version][u16 idleSecs][u16 inflightMax]
298 guard bytes.count >= 6, !legacyFallbackSent else { return }
299 let idle = TimeInterval(Self.readU16(bytes, 2))
300 if idle > 0 { pingInterval = min(max(idle / 3, 5), 60) }
301 markSubscribed(reliable: true, on: task)
302 case Self.opMsgSeq:
303 // [0x0E][flags][u64 seq][ciphertext…]
304 guard bytes.count >= 10 else { return }
305 let seq = Self.readU64(bytes, 2)
306 await deliver(Data(bytes[10...]), isUwb: bytes[1] & Self.flagUwb != 0)
307 // ACK only after the payload is processed and stored: an ACK is the server's
308 // licence to forget the frame.
309 var ack = Data([Self.opAck])
310 Self.appendU64(&ack, seq)
311 try? await task.send(.data(ack))
312 case Self.opMsg:
313 // Legacy fallback: [0x03][flags][ciphertext…], no ACK.
314 guard bytes.count >= 2 else { return }
315 await deliver(Data(bytes[2...]), isUwb: bytes[1] & Self.flagUwb != 0)
316 case Self.opGetKeyResponse:
317 guard let reply = RelayKeyLookup.parseAny(frame) else { return }
318 pendingKeys.removeValue(forKey: reply.target)?.yield(reply.result)
319 default:
320 break
321 }
322 }
323
324 /// Decrypts and hands one pushed payload to the same pipeline the HTTP drain feeds.
325 /// A repeat (redelivered after a lost ACK) is skipped but still ACKed by the caller.
326 private func deliver(_ sealed: Data, isUwb: Bool) async {
327 if RelayDedup.shared.contains(sealed) { return }
328 if isUwb {
329 if let env = Networking.shared.decodeUwb(sealed: sealed) {
330 BackgroundTask.shared.handleIncomingUwb([env])
331 }
332 } else if let loc = Networking.shared.decodeLocation(sealed: sealed) {
333 await BackgroundTask.shared.handleIncomingLocations([loc])
334 }
335 // Recorded even when decryption failed: a byte-identical retry fails the same way.
336 RelayDedup.shared.insert(sealed)
337 }
338
339 // MARK: - Requests
340
341 /// Sends an already-sealed payload as PUB. False when there is no fresh subscribed
342 /// socket — the caller then publishes over HTTP. PUB has no server acknowledgement, so
343 /// a socket that has been quiet longer than one ping interval (+10 s) is not trusted.
344 func publish(recipient: Int64, isUwb: Bool, sealed: Data) async -> Bool {
345 guard let task, isSubscribed,
346 Date().timeIntervalSince(lastInboundAt) < pingInterval + 10 else { return false }
347 var frame = Data([Self.opPub, isUwb ? Self.flagUwb : 0])
348 Self.appendU64(&frame, UInt64(bitPattern: recipient))
349 frame.append(sealed)
350 do {
351 try await task.send(.data(frame))
352 return true
353 } catch {
354 return false
355 }
356 }
357
358 /// GETKEY over the live socket. Nil when there is no subscribed socket, another
359 /// lookup for the same target is in flight, or no reply within the timeout.
360 func getKey(userId: Int64) async -> RelayKeyLookup.KeyResult? {
361 guard let task, isSubscribed, pendingKeys[userId] == nil else { return nil }
362 let (stream, continuation) = AsyncStream<RelayKeyLookup.KeyResult?>.makeStream()
363 pendingKeys[userId] = continuation
364 defer {
365 pendingKeys.removeValue(forKey: userId)?.finish()
366 }
367 var request = Data([Self.opGetKeyRequest])
368 Self.appendU64(&request, UInt64(bitPattern: userId))
369 guard (try? await task.send(.data(request))) != nil else { return nil }
370 let timeout = Self.keyTimeout
371 return await withTaskGroup(of: RelayKeyLookup.KeyResult?.self) { group in
372 group.addTask {
373 for await result in stream { return result }
374 return nil
375 }
376 group.addTask {
377 try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
378 return nil
379 }
380 let first = await group.next() ?? nil
381 group.cancelAll()
382 return first
383 }
384 }
385
386 // MARK: - HTTP safety net
387
388 /// One HTTP drain of both PQC queues, fed into the same pipeline as socket pushes.
389 private func drainHttpOnce() {
390 guard !httpDrainInFlight else { return }
391 httpDrainInFlight = true
392 Task {
393 if let locations = await Networking.shared.receiveLocations(), !locations.isEmpty {
394 await BackgroundTask.shared.handleIncomingLocations(locations)
395 }
396 if let envelopes = await Networking.shared.receiveUwbMessages(), !envelopes.isEmpty {
397 BackgroundTask.shared.handleIncomingUwb(envelopes)
398 }
399 self.httpDrainInFlight = false
400 }
401 }
402
403 // MARK: - Byte helpers
404
405 private static func appendU64(_ data: inout Data, _ value: UInt64) {
406 withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) }
407 }
408
409 private static func readU64(_ bytes: [UInt8], _ offset: Int) -> UInt64 {
410 var value: UInt64 = 0
411 for i in 0..<8 { value = (value << 8) | UInt64(bytes[offset + i]) }
412 return value
413 }
414
415 private static func readU16(_ bytes: [UInt8], _ offset: Int) -> UInt16 {
416 (UInt16(bytes[offset]) << 8) | UInt16(bytes[offset + 1])
417 }
418}
419
420/// Recently processed relay payloads, by ciphertext hash, so a frame redelivered after a
421/// lost ACK (or also drained over HTTP) is not stored or notified twice. Exact: every PQC
422/// seal has a fresh ML-KEM encapsulation and random IV, so equal bytes == same message.
423/// Persisted so a kill between "stored" and "ACKed" does not duplicate on relaunch.
424@MainActor
425final class RelayDedup {
426 static let shared = RelayDedup()
427
428 private static let defaultsKey = "relaySeenPayloads_v1"
429 private static let capacity = 512
430
431 private var order: [String]
432 private var seen: Set<String>
433
434 private init() {
435 order = UserDefaults.standard.stringArray(forKey: Self.defaultsKey) ?? []
436 seen = Set(order)
437 }
438
439 private static func digest(_ payload: Data) -> String {
440 Data(Array(SHA256.hash(data: payload)).prefix(16)).base64EncodedString()
441 }
442
443 func contains(_ payload: Data) -> Bool {
444 seen.contains(Self.digest(payload))
445 }
446
447 func insert(_ payload: Data) {
448 let d = Self.digest(payload)
449 guard seen.insert(d).inserted else { return }
450 order.append(d)
451 if order.count > Self.capacity {
452 let overflow = order.count - Self.capacity
453 for old in order.prefix(overflow) { seen.remove(old) }
454 order.removeFirst(overflow)
455 }
456 UserDefaults.standard.set(order, forKey: Self.defaultsKey)
457 }
458}