@mentra/bluetooth-sdk 3.5.0-dev.1518 → 3.5.0-dev.1520
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +9 -0
- package/README.md +64 -11
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +10 -0
- package/build/BluetoothSdk.types.d.ts +23 -5
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js +5 -0
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_internal.d.ts +1 -0
- package/build/_internal.d.ts.map +1 -1
- package/build/_internal.js +1 -0
- package/build/_internal.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +20 -9
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +21 -0
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/glasses-wifi/connection.d.ts +6 -0
- package/build/glasses-wifi/connection.d.ts.map +1 -0
- package/build/glasses-wifi/connection.js +44 -0
- package/build/glasses-wifi/connection.js.map +1 -0
- package/build/glasses-wifi/continuous.d.ts +39 -0
- package/build/glasses-wifi/continuous.d.ts.map +1 -0
- package/build/glasses-wifi/continuous.js +151 -0
- package/build/glasses-wifi/continuous.js.map +1 -0
- package/build/glasses-wifi/files.d.ts +11 -0
- package/build/glasses-wifi/files.d.ts.map +1 -0
- package/build/glasses-wifi/files.js +33 -0
- package/build/glasses-wifi/files.js.map +1 -0
- package/build/glasses-wifi/index.d.ts +20 -0
- package/build/glasses-wifi/index.d.ts.map +1 -0
- package/build/glasses-wifi/index.js +15 -0
- package/build/glasses-wifi/index.js.map +1 -0
- package/build/glasses-wifi/link.d.ts +31 -0
- package/build/glasses-wifi/link.d.ts.map +1 -0
- package/build/glasses-wifi/link.js +71 -0
- package/build/glasses-wifi/link.js.map +1 -0
- package/build/glasses-wifi/native.d.ts +63 -0
- package/build/glasses-wifi/native.d.ts.map +1 -0
- package/build/glasses-wifi/native.js +138 -0
- package/build/glasses-wifi/native.js.map +1 -0
- package/build/glasses-wifi/service.d.ts +86 -0
- package/build/glasses-wifi/service.d.ts.map +1 -0
- package/build/glasses-wifi/service.js +497 -0
- package/build/glasses-wifi/service.js.map +1 -0
- package/build/index.d.ts +4 -2
- package/build/index.d.ts.map +1 -1
- package/build/index.js +24 -6
- package/build/index.js.map +1 -1
- package/build/ota-transport/index.d.ts +2 -43
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +3 -49
- package/build/ota-transport/index.js.map +1 -1
- package/build/react/useBluetoothStatus.d.ts.map +1 -1
- package/build/react/useBluetoothStatus.js +5 -24
- package/build/react/useBluetoothStatus.js.map +1 -1
- package/build/react/useMentraBluetooth.d.ts +1 -2
- package/build/react/useMentraBluetooth.d.ts.map +1 -1
- package/build/react/useMentraBluetooth.js +0 -1
- package/build/react/useMentraBluetooth.js.map +1 -1
- package/expo-module.config.json +1 -1
- package/ios/MentraBluetoothSDK.podspec +5 -4
- package/ios/MentraLocalNetworkModule.swift +264 -0
- package/ios/Source/BluetoothSdkDefaults.swift +1 -1
- package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
- package/ios/Source/hotspot/GlassesHotspotNetwork.swift +563 -0
- package/ios/Source/hotspot/HotspotAccessPurpose.swift +5 -0
- package/ios/Source/hotspot/HotspotAddressPolicy.swift +50 -0
- package/ios/Source/hotspot/HotspotInterfacePolicy.swift +155 -0
- package/ios/Source/hotspot/HotspotJoinFailure.swift +27 -0
- package/ios/Source/hotspot/HotspotLeaveCompletion.swift +24 -0
- package/ios/Source/hotspot/HotspotNetworkOwnership.swift +22 -0
- package/ios/Source/hotspot/HotspotReapplyPolicy.swift +26 -0
- package/ios/Source/hotspot/LocalNetworkAccessRequest.swift +160 -0
- package/ios/Source/hotspot/MacHotspotAssociation.swift +415 -0
- package/ios/Source/hotspot/MacHotspotAuthorization.swift +126 -0
- package/ios/Source/hotspot/MacHotspotAuthorizationFacts.swift +51 -0
- package/ios/Source/hotspot/MacHotspotCleanupContinuation.swift +35 -0
- package/ios/Tests/HotspotAddressPolicyTests.swift +30 -0
- package/ios/Tests/HotspotInterfacePolicyTests.swift +304 -0
- package/ios/Tests/HotspotJoinFailureTests.swift +37 -0
- package/ios/Tests/HotspotLeaveCompletionTests.swift +29 -0
- package/ios/Tests/HotspotReapplyPolicyTests.swift +18 -0
- package/ios/Tests/LocalNetworkAccessRequestTests.swift +237 -0
- package/ios/Tests/MacHotspotAssociationTests.swift +521 -0
- package/ios/Tests/MacHotspotAuthorizationFactsTests.swift +62 -0
- package/ios/Tests/MacHotspotAuthorizationTests.swift +348 -0
- package/ios/Tests/MacWifiInvocationTests.swift +76 -0
- package/package.json +7 -2
- package/plugin/build/withIos.d.ts +4 -0
- package/plugin/build/withIos.js +20 -1
- package/src/BluetoothSdk.types.ts +27 -5
- package/src/_internal.ts +1 -0
- package/src/_private/BluetoothSdkModule.ts +20 -10
- package/src/_private/MentraLocalNetworkModule.ts +22 -0
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/glasses-wifi/connection.ts +47 -0
- package/src/glasses-wifi/continuous.ts +177 -0
- package/src/glasses-wifi/files.ts +32 -0
- package/src/glasses-wifi/index.ts +24 -0
- package/src/glasses-wifi/link.ts +94 -0
- package/src/glasses-wifi/native.ts +193 -0
- package/src/glasses-wifi/service.ts +554 -0
- package/src/index.ts +34 -10
- package/src/ota-transport/index.ts +3 -85
- package/src/react/useBluetoothStatus.ts +5 -26
- package/src/react/useMentraBluetooth.ts +0 -3
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
// NEHotspotConfiguration exists only on iOS (an iOS app on a Mac included).
|
|
2
|
+
// swiftformat:options --ifdef no-indent
|
|
3
|
+
#if os(iOS)
|
|
4
|
+
import Darwin
|
|
5
|
+
import Foundation
|
|
6
|
+
import Network
|
|
7
|
+
import NetworkExtension
|
|
8
|
+
|
|
9
|
+
/// Shared hotspot association owner. Only local glasses traffic uses Wi-Fi.
|
|
10
|
+
public final class GlassesHotspotNetwork {
|
|
11
|
+
private let queue = DispatchQueue(label: "com.mentra.bluetoothsdk.hotspot")
|
|
12
|
+
private var ssid: String?
|
|
13
|
+
/// The verified Wi-Fi interface and DHCP address. Every later check uses this exact pair.
|
|
14
|
+
private var binding: HotspotInterfaceBinding?
|
|
15
|
+
private var accessPurpose: HotspotAccessPurpose = .outgoingClient
|
|
16
|
+
private var gatewayAddress: String?
|
|
17
|
+
private var generation = 0
|
|
18
|
+
private var applying = false
|
|
19
|
+
private var ownsConfiguration = false
|
|
20
|
+
private var applies = 0
|
|
21
|
+
/// When the pending apply() started: iOS answers it only once the person answers its join prompt.
|
|
22
|
+
private var promptSince: TimeInterval?
|
|
23
|
+
private var joinDeadline: TimeInterval = 0
|
|
24
|
+
private let reapplyPolicy = HotspotReapplyPolicy()
|
|
25
|
+
private var cancelled = false
|
|
26
|
+
private var joinReply: ((Result<String, Error>) -> Void)?
|
|
27
|
+
private var leaveCompletion: HotspotLeaveCompletion?
|
|
28
|
+
private var interfaceMonitors: [NWPathMonitor] = []
|
|
29
|
+
/// Wi-Fi identity learned since this join started; replaced on every join and cleared on leave.
|
|
30
|
+
private var wifiIdentity = HotspotWifiIdentity()
|
|
31
|
+
private var localAccess: LocalNetworkAccessRequest?
|
|
32
|
+
private var localAddress: String? {
|
|
33
|
+
binding?.address
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private let macWorker = DispatchQueue(label: "com.mentra.bluetoothsdk.mac-wifi")
|
|
37
|
+
private var macAssociation: MacHotspotAssociation?
|
|
38
|
+
private var macAuthorization: MacHotspotAuthorization?
|
|
39
|
+
private var macCleanupContinuation: MacHotspotCleanupContinuation?
|
|
40
|
+
private var ownershipToken: UUID?
|
|
41
|
+
private var finishingLeave = false
|
|
42
|
+
public var onLost: ((String) -> Void)?
|
|
43
|
+
/// Gets the system's answer that left the join waiting for Local Network access.
|
|
44
|
+
public var onPermissionRequired: ((String) -> Void)?
|
|
45
|
+
public init() { _ = Self.startupCleanup }
|
|
46
|
+
|
|
47
|
+
/// The process's one glasses network: the glasses Wi-Fi service joins it through the
|
|
48
|
+
/// `MentraLocalNetwork` module, and Mentra Call and the managed relay read its verified
|
|
49
|
+
/// address instead of joining themselves.
|
|
50
|
+
public static let shared = GlassesHotspotNetwork()
|
|
51
|
+
|
|
52
|
+
/// iOS keeps every applied configuration and joins it again by itself whenever that hotspot is up.
|
|
53
|
+
/// A configuration left by a crash or a kill mid-session would let a phone near many pairs wander onto
|
|
54
|
+
/// one it is not using. This app's configurations are all glasses hotspots, so each join removes the
|
|
55
|
+
/// others, and this clears leftovers once per launch, unless a join already owns the network: that join clears them itself.
|
|
56
|
+
private static let startupCleanup: Void = {
|
|
57
|
+
guard !ProcessInfo.processInfo.isiOSAppOnMac else { return }
|
|
58
|
+
NEHotspotConfigurationManager.shared.getConfiguredSSIDs { saved in
|
|
59
|
+
guard !saved.isEmpty, let token = HotspotNetworkOwnership.shared.acquire() else { return }
|
|
60
|
+
saved.forEach { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: $0) }
|
|
61
|
+
HotspotNetworkOwnership.shared.release(token)
|
|
62
|
+
}
|
|
63
|
+
}()
|
|
64
|
+
|
|
65
|
+
public func join(ssid: String, passphrase: String, gateway: String? = nil, frequency: Int? = nil, purpose: HotspotAccessPurpose = .outgoingClient,
|
|
66
|
+
completion: @escaping (Result<String, Error>) -> Void) {
|
|
67
|
+
queue.async {
|
|
68
|
+
guard self.ssid == nil, !self.applying else { completion(.failure(HotspotError("Previous hotspot session has not finished cleaning up"))); return }
|
|
69
|
+
if let gateway, !HotspotAddressPolicy.isPrivate(gateway) {
|
|
70
|
+
completion(.failure(HotspotError("The glasses reported an invalid hotspot gateway"))); return
|
|
71
|
+
}
|
|
72
|
+
if ProcessInfo.processInfo.isiOSAppOnMac, gateway == nil {
|
|
73
|
+
completion(.failure(HotspotError("The glasses did not report their hotspot gateway"))); return
|
|
74
|
+
}
|
|
75
|
+
guard let token = HotspotNetworkOwnership.shared.acquire() else {
|
|
76
|
+
completion(.failure(HotspotError("The glasses hotspot is already in use"))); return
|
|
77
|
+
}
|
|
78
|
+
self.ownershipToken = token
|
|
79
|
+
self.generation += 1
|
|
80
|
+
let gen = self.generation
|
|
81
|
+
let window = ProcessInfo.processInfo.isiOSAppOnMac ? MacHotspotAssociation.joinWindow : 60
|
|
82
|
+
let deadline = ProcessInfo.processInfo.systemUptime + window
|
|
83
|
+
self.joinDeadline = deadline
|
|
84
|
+
self.promptSince = nil
|
|
85
|
+
self.ssid = ssid
|
|
86
|
+
self.gatewayAddress = gateway
|
|
87
|
+
self.accessPurpose = purpose
|
|
88
|
+
self.cancelled = false
|
|
89
|
+
self.applying = false
|
|
90
|
+
self.ownsConfiguration = false
|
|
91
|
+
self.applies = 0
|
|
92
|
+
self.joinReply = completion
|
|
93
|
+
self.startInterfaceMonitors(generation: gen)
|
|
94
|
+
if ProcessInfo.processInfo.isiOSAppOnMac {
|
|
95
|
+
self.authorizeMacAssociation(ssid: ssid, passphrase: passphrase, frequency: frequency, generation: gen, deadline: deadline)
|
|
96
|
+
} else {
|
|
97
|
+
NEHotspotConfigurationManager.shared.getConfiguredSSIDs { saved in
|
|
98
|
+
self.queue.async {
|
|
99
|
+
// A cancelled join's late answer must not remove the next pair's configuration.
|
|
100
|
+
guard gen == self.generation, !self.cancelled else { return }
|
|
101
|
+
for other in saved where other != ssid { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: other) }
|
|
102
|
+
self.applyConfiguration(ssid: ssid, passphrase: passphrase, generation: gen)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
self.scheduleJoinDeadline(ssid: ssid, generation: gen)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// Time to associate after the person answers a join prompt late in the join.
|
|
111
|
+
private static let afterAnswer: TimeInterval = 30
|
|
112
|
+
/// Time for a Mac that has associated to get its hotspot address. Each Mac scan takes about
|
|
113
|
+
/// 23 s while it is on another network, so it can find the hotspot near the join deadline.
|
|
114
|
+
private static let macAddressWait: TimeInterval = 30
|
|
115
|
+
|
|
116
|
+
/// The join gets 60 s of its own (a Mac's longer scan window on a Mac), plus however long the person takes to answer iOS's join
|
|
117
|
+
/// prompt, or a Mac's address wait once it has associated. The engine keeps the glasses AP up meanwhile.
|
|
118
|
+
private func scheduleJoinDeadline(ssid: String, generation gen: Int) {
|
|
119
|
+
queue.asyncAfter(deadline: .now() + max(1, joinDeadline - ProcessInfo.processInfo.systemUptime)) {
|
|
120
|
+
// Once associated, the user may still be reading the Local Network alert.
|
|
121
|
+
// Its response time is not a hotspot association timeout.
|
|
122
|
+
guard gen == self.generation, self.joinReply != nil, self.localAccess == nil else { return }
|
|
123
|
+
let now = ProcessInfo.processInfo.systemUptime
|
|
124
|
+
if self.promptSince != nil { self.joinDeadline = max(self.joinDeadline, now + 1) }
|
|
125
|
+
if now < self.joinDeadline { self.scheduleJoinDeadline(ssid: ssid, generation: gen); return }
|
|
126
|
+
Bridge.log("HOTSPOT_JOIN timed_out prompt_pending=\(self.promptSince != nil)")
|
|
127
|
+
self.cancelled = true
|
|
128
|
+
self.macAssociation?.cancel()
|
|
129
|
+
self.macAuthorization?.cancelPending()
|
|
130
|
+
self.finishJoin(.failure(HotspotError("Hotspot join timed out")))
|
|
131
|
+
// apply() cannot be cancelled. Retain the reservation until its callback and remove the
|
|
132
|
+
// late configuration before another call is permitted to acquire the network.
|
|
133
|
+
if self.ownsConfiguration { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ssid) }
|
|
134
|
+
if !self.applying { self.finishLeave() }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
public func leave(completion: @escaping (Result<Void, Error>) -> Void) {
|
|
139
|
+
queue.async {
|
|
140
|
+
self.cancelled = true
|
|
141
|
+
self.macAssociation?.cancel()
|
|
142
|
+
self.macAuthorization?.cancelPending()
|
|
143
|
+
if self.leaveCompletion == nil {
|
|
144
|
+
self.leaveCompletion = HotspotLeaveCompletion {
|
|
145
|
+
if let token = self.ownershipToken { HotspotNetworkOwnership.shared.release(token) }
|
|
146
|
+
self.ownershipToken = nil
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
self.leaveCompletion?.append(completion)
|
|
150
|
+
self.finishJoin(.failure(HotspotError("Hotspot join cancelled")))
|
|
151
|
+
if let ssid = self.ssid, self.ownsConfiguration { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ssid) }
|
|
152
|
+
if !self.applying { self.finishLeave() }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// The verified hotspot address while its own Wi-Fi interface still holds it; nil after
|
|
157
|
+
/// loss, leave or an address change. Never falls back to another interface.
|
|
158
|
+
public func verifiedAddress(completion: @escaping (String?) -> Void) {
|
|
159
|
+
queue.async {
|
|
160
|
+
guard let binding = self.binding, !self.cancelled, self.isBindingIntact(binding) else { completion(nil); return }
|
|
161
|
+
if let association = self.macAssociation {
|
|
162
|
+
let ssid = self.ssid
|
|
163
|
+
let gen = self.generation
|
|
164
|
+
self.macWorker.async {
|
|
165
|
+
let matched = (try? association.currentSSID()) == ssid
|
|
166
|
+
self.queue.async {
|
|
167
|
+
completion(gen == self.generation && !self.cancelled && matched && self.isBindingIntact(binding) ? binding.address : nil)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
} else { completion(binding.address) }
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
public func info(completion: @escaping ([String: Any]) -> Void) {
|
|
175
|
+
queue.async {
|
|
176
|
+
var value: [String: Any] = ["available": self.localAddress != nil]
|
|
177
|
+
if let address = self.localAddress {
|
|
178
|
+
value["localIpv4"] = address
|
|
179
|
+
value["prefix"] = address.split(separator: ".").prefix(3).joined(separator: ".") + ".0/24"
|
|
180
|
+
}
|
|
181
|
+
completion(value)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
public func probeGateway(completion: @escaping (Bool, String) -> Void) {
|
|
186
|
+
queue.async {
|
|
187
|
+
guard let address = self.localAddress else { completion(false, "No joined hotspot"); return }
|
|
188
|
+
let gateway = self.gatewayAddress ?? address.split(separator: ".").prefix(3).joined(separator: ".") + ".1"
|
|
189
|
+
let parameters = NWParameters.tcp
|
|
190
|
+
if ProcessInfo.processInfo.isiOSAppOnMac {
|
|
191
|
+
// The Mac route probe rejects the Wi-Fi type constraint on an otherwise
|
|
192
|
+
// usable hotspot route. Restrict this connection to the verified source IP.
|
|
193
|
+
parameters.requiredLocalEndpoint = .hostPort(host: NWEndpoint.Host(address), port: .any)
|
|
194
|
+
} else {
|
|
195
|
+
parameters.requiredInterfaceType = .wifi
|
|
196
|
+
}
|
|
197
|
+
let connection = NWConnection(host: NWEndpoint.Host(gateway), port: 8089, using: parameters)
|
|
198
|
+
var finished = false
|
|
199
|
+
let finish: (Bool, String) -> Void = { reachable, detail in
|
|
200
|
+
guard !finished else { return }
|
|
201
|
+
finished = true
|
|
202
|
+
connection.stateUpdateHandler = nil
|
|
203
|
+
connection.cancel()
|
|
204
|
+
completion(reachable, detail)
|
|
205
|
+
}
|
|
206
|
+
connection.stateUpdateHandler = { state in
|
|
207
|
+
switch state {
|
|
208
|
+
case .ready: finish(true, "\(gateway):8089")
|
|
209
|
+
case let .failed(error): finish(false, error.localizedDescription)
|
|
210
|
+
default: break
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
connection.start(queue: self.queue)
|
|
214
|
+
self.queue.asyncAfter(deadline: .now() + 3) { finish(false, "Gateway probe timed out") }
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private func authorizeMacAssociation(ssid: String, passphrase: String, frequency: Int?, generation gen: Int, deadline: TimeInterval) {
|
|
219
|
+
let facts = MacHotspotAuthorizationFacts()
|
|
220
|
+
let authorization = MacHotspotAuthorization(facts: facts)
|
|
221
|
+
macAuthorization = authorization
|
|
222
|
+
authorization.onRevoked = { [weak self] error in
|
|
223
|
+
guard let self else { return }
|
|
224
|
+
self.queue.async {
|
|
225
|
+
guard gen == self.generation, !self.cancelled else { return }
|
|
226
|
+
self.cancelled = true
|
|
227
|
+
self.macAssociation?.cancel()
|
|
228
|
+
self.finishJoin(.failure(error))
|
|
229
|
+
self.onLost?("Glasses hotspot Location authorization was revoked")
|
|
230
|
+
if !self.applying { self.finishLeave() }
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
macCleanupContinuation = MacHotspotCleanupContinuation(authorization: authorization, queue: queue,
|
|
234
|
+
isCurrentCancelledSession: { [weak self] in
|
|
235
|
+
guard let self else { return false }
|
|
236
|
+
return gen == self.generation && self.cancelled
|
|
237
|
+
}, requestCleanup: { [weak self] in
|
|
238
|
+
guard let self, !self.applying else { return }
|
|
239
|
+
self.finishLeave()
|
|
240
|
+
})
|
|
241
|
+
authorization.start { result in
|
|
242
|
+
self.queue.async {
|
|
243
|
+
guard gen == self.generation, !self.cancelled else { return }
|
|
244
|
+
switch result {
|
|
245
|
+
case .success:
|
|
246
|
+
self.applyMacAssociation(ssid: ssid, passphrase: passphrase, frequency: frequency, generation: gen, deadline: deadline,
|
|
247
|
+
authorizationFacts: facts, authorization: authorization)
|
|
248
|
+
case let .failure(error):
|
|
249
|
+
self.finishJoin(.failure(error)); self.finishLeave()
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private func applyMacAssociation(ssid: String, passphrase: String, frequency: Int?, generation gen: Int, deadline: TimeInterval,
|
|
256
|
+
authorizationFacts: MacHotspotAuthorizationFacts, authorization: MacHotspotAuthorization) {
|
|
257
|
+
let association = MacHotspotAssociation(deadline: deadline, authorizationFacts: authorizationFacts, authorization: authorization)
|
|
258
|
+
macAssociation = association
|
|
259
|
+
applying = true
|
|
260
|
+
macWorker.async {
|
|
261
|
+
let result = Result { try association.associate(ssid: ssid, password: passphrase, frequency: frequency) }
|
|
262
|
+
self.queue.async {
|
|
263
|
+
guard gen == self.generation else { return }
|
|
264
|
+
self.applying = false
|
|
265
|
+
if self.cancelled { self.finishLeave(); return }
|
|
266
|
+
switch result {
|
|
267
|
+
case let .success(name):
|
|
268
|
+
let index = Int(if_nametoindex(name))
|
|
269
|
+
guard index > 0 else {
|
|
270
|
+
self.finishJoin(.failure(HotspotError("Mac Wi-Fi interface disappeared during association")))
|
|
271
|
+
self.finishLeave(); return
|
|
272
|
+
}
|
|
273
|
+
self.wifiIdentity.observe([HotspotInterfaceReport(name: name, index: index, isWifi: true)])
|
|
274
|
+
self.joinDeadline = max(self.joinDeadline, ProcessInfo.processInfo.systemUptime + Self.macAddressWait)
|
|
275
|
+
self.waitForMacAddress(ssid: ssid, association: association, generation: gen,
|
|
276
|
+
remaining: Int(Self.macAddressWait * 2))
|
|
277
|
+
case let .failure(error):
|
|
278
|
+
self.finishJoin(.failure(error)); self.finishLeave()
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private func waitForMacAddress(ssid: String, association: MacHotspotAssociation, generation gen: Int, remaining: Int) {
|
|
285
|
+
guard gen == generation, !cancelled else { return }
|
|
286
|
+
macWorker.async {
|
|
287
|
+
let membership = Result { try association.currentSSID() == ssid }
|
|
288
|
+
self.queue.async {
|
|
289
|
+
guard gen == self.generation, !self.cancelled else { return }
|
|
290
|
+
if case let .failure(error) = membership {
|
|
291
|
+
self.finishJoin(.failure(error)); self.finishLeave(); return
|
|
292
|
+
}
|
|
293
|
+
if (try? membership.get()) == true, let selected = self.selectBinding() {
|
|
294
|
+
self.bind(selected)
|
|
295
|
+
self.finishAssociation(address: selected.address, generation: gen)
|
|
296
|
+
} else if remaining > 0 {
|
|
297
|
+
self.queue.asyncAfter(deadline: .now() + 0.5) {
|
|
298
|
+
self.waitForMacAddress(ssid: ssid, association: association, generation: gen, remaining: remaining - 1)
|
|
299
|
+
}
|
|
300
|
+
} else {
|
|
301
|
+
self.finishJoin(.failure(HotspotError("Mac Wi-Fi has no verified glasses hotspot address")))
|
|
302
|
+
self.finishLeave()
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private func applyConfiguration(ssid: String, passphrase: String, generation gen: Int, remaining: Int = 60) {
|
|
309
|
+
let config = NEHotspotConfiguration(ssid: ssid, passphrase: passphrase, isWEP: false)
|
|
310
|
+
config.joinOnce = false
|
|
311
|
+
applying = true
|
|
312
|
+
ownsConfiguration = true
|
|
313
|
+
applies += 1
|
|
314
|
+
promptSince = ProcessInfo.processInfo.systemUptime
|
|
315
|
+
Bridge.log("HOTSPOT_JOIN apply_start attempt=\(self.applies) ios_on_mac=\(ProcessInfo.processInfo.isiOSAppOnMac)")
|
|
316
|
+
NEHotspotConfigurationManager.shared.apply(config) { error in
|
|
317
|
+
self.queue.async {
|
|
318
|
+
guard gen == self.generation else { return }
|
|
319
|
+
self.applying = false
|
|
320
|
+
if let asked = self.promptSince {
|
|
321
|
+
let now = ProcessInfo.processInfo.systemUptime
|
|
322
|
+
self.promptSince = nil
|
|
323
|
+
self.joinDeadline = max(self.joinDeadline, now + Self.afterAnswer)
|
|
324
|
+
Bridge.log("HOTSPOT_JOIN apply_answered after_s=\(Int(now - asked))")
|
|
325
|
+
}
|
|
326
|
+
if self.cancelled { self.finishLeave(); return }
|
|
327
|
+
if let error {
|
|
328
|
+
let nativeError = error as NSError
|
|
329
|
+
let alreadyAssociated = nativeError.domain == NEHotspotConfigurationErrorDomain &&
|
|
330
|
+
nativeError.code == NEHotspotConfigurationError.alreadyAssociated.rawValue
|
|
331
|
+
if !alreadyAssociated {
|
|
332
|
+
// Error identifiers are useful without credentials or full userInfo.
|
|
333
|
+
let underlying = nativeError.userInfo[NSUnderlyingErrorKey] as? NSError
|
|
334
|
+
Bridge.log("HOTSPOT_JOIN apply_failed domain=\(nativeError.domain) code=\(nativeError.code) underlying_domain=\(underlying?.domain ?? "none") underlying_code=\(underlying.map { String($0.code) } ?? "none")")
|
|
335
|
+
self.finishJoin(.failure(error)); self.finishLeave(); return
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
Bridge.log("HOTSPOT_JOIN apply_accepted")
|
|
339
|
+
self.waitForAddress(ssid: ssid, passphrase: passphrase, generation: gen, remaining: remaining, pollsSinceApply: 0)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
private func waitForAddress(ssid: String, passphrase: String, generation gen: Int, remaining: Int, pollsSinceApply: Int) {
|
|
345
|
+
guard gen == generation, !cancelled else { return }
|
|
346
|
+
NEHotspotNetwork.fetchCurrent { [weak self] network in
|
|
347
|
+
self?.queue.async {
|
|
348
|
+
guard let self, gen == self.generation, !self.cancelled else { return }
|
|
349
|
+
// The selection applies the BLE gateway's client check when one was reported.
|
|
350
|
+
if network?.ssid == ssid, let selected = self.selectBinding() {
|
|
351
|
+
self.bind(selected)
|
|
352
|
+
self.finishAssociation(address: selected.address, generation: gen)
|
|
353
|
+
} else if remaining > 0, network?.ssid != ssid,
|
|
354
|
+
self.reapplyPolicy.shouldReapply(applies: self.applies, pollsSinceApply: pollsSinceApply) {
|
|
355
|
+
// iOS reports the request applied even when its one scan missed the hotspot.
|
|
356
|
+
Bridge.log("HOTSPOT_JOIN reapply after_polls=\(pollsSinceApply)")
|
|
357
|
+
self.applyConfiguration(ssid: ssid, passphrase: passphrase, generation: gen, remaining: remaining)
|
|
358
|
+
} else if remaining > 0 {
|
|
359
|
+
self.queue.asyncAfter(deadline: .now() + 0.5) {
|
|
360
|
+
self.waitForAddress(ssid: ssid, passphrase: passphrase, generation: gen, remaining: remaining - 1, pollsSinceApply: pollsSinceApply + 1)
|
|
361
|
+
}
|
|
362
|
+
} else {
|
|
363
|
+
let association = network == nil ? "unavailable" : (network?.ssid == ssid ? "matched" : "different")
|
|
364
|
+
self.finishJoin(.failure(HotspotError("Glasses hotspot has no verified Wi-Fi address (SSID=\(association), \(self.wifiDiagnostic()))")))
|
|
365
|
+
self.finishLeave()
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/// iOS can omit an internet-less Wi-Fi from its default path, and iOS-on-Mac has rejected
|
|
372
|
+
/// a Wi-Fi type constraint on a usable hotspot route. Both paths' interface types feed one
|
|
373
|
+
/// session identity (HotspotWifiIdentity): a positive Wi-Fi report outlives later omission
|
|
374
|
+
/// only while the same interface stays attached; contrary reports and replacement fail closed.
|
|
375
|
+
/// A phone that starts on cellular never gets a report; HotspotInterfacePolicy then uses
|
|
376
|
+
/// the hotspot client address as the evidence.
|
|
377
|
+
private func startInterfaceMonitors(generation gen: Int) {
|
|
378
|
+
interfaceMonitors.forEach { $0.cancel() }
|
|
379
|
+
let monitors = [NWPathMonitor(requiredInterfaceType: .wifi), NWPathMonitor()]
|
|
380
|
+
interfaceMonitors = monitors
|
|
381
|
+
wifiIdentity = HotspotWifiIdentity()
|
|
382
|
+
for monitor in monitors {
|
|
383
|
+
monitor.pathUpdateHandler = { [weak self] path in
|
|
384
|
+
guard let self, gen == self.generation else { return }
|
|
385
|
+
self.wifiIdentity.observe(path.availableInterfaces.map {
|
|
386
|
+
HotspotInterfaceReport(name: $0.name, index: $0.index, isWifi: $0.type == .wifi)
|
|
387
|
+
})
|
|
388
|
+
// This AP intentionally has no internet. Loss of its default internet path is not
|
|
389
|
+
// loss of the local link; check the verified interface and address instead.
|
|
390
|
+
if let binding = self.binding, !self.cancelled, !self.isBindingIntact(binding) {
|
|
391
|
+
self.onLost?("Glasses hotspot connection was lost")
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
monitor.start(queue: queue)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/// Every check samples interfaces first, so a detach or replacement between path updates
|
|
399
|
+
/// is recorded in the session identity before it is used.
|
|
400
|
+
private func observeInterfaces() -> HotspotInterfaceSnapshot {
|
|
401
|
+
let snapshot = Self.interfaceSnapshot()
|
|
402
|
+
wifiIdentity.observe(snapshot)
|
|
403
|
+
return snapshot
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private func selectBinding() -> HotspotInterfaceBinding? {
|
|
407
|
+
HotspotInterfacePolicy.select(snapshot: observeInterfaces(), identity: wifiIdentity, gateway: gatewayAddress)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
private func isBindingIntact(_ binding: HotspotInterfaceBinding) -> Bool {
|
|
411
|
+
let snapshot = observeInterfaces()
|
|
412
|
+
return HotspotInterfacePolicy.isIntact(binding, snapshot: snapshot, identity: wifiIdentity)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private func bind(_ selected: HotspotInterfaceBinding) {
|
|
416
|
+
let evidence = wifiIdentity.trusted[selected.interface] == selected.index ? "wifi_report" : "hotspot_client"
|
|
417
|
+
wifiIdentity.adopt(selected)
|
|
418
|
+
binding = selected
|
|
419
|
+
Bridge.log("HOTSPOT_JOIN address_verified interface=\(selected.interface) evidence=\(evidence)")
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/// Interface names and their IPv4 addresses only; never credentials or SSIDs.
|
|
423
|
+
private func wifiDiagnostic() -> String {
|
|
424
|
+
let snapshot = observeInterfaces()
|
|
425
|
+
let wifi = Set(wifiIdentity.trusted.keys)
|
|
426
|
+
let addresses = snapshot.addresses.filter { wifi.contains($0.name) }.map { "\($0.name)=\($0.ipv4)" }
|
|
427
|
+
let other = snapshot.addresses.filter { !wifi.contains($0.name) && HotspotAddressPolicy.isPrivate($0.ipv4) }
|
|
428
|
+
.map { "\($0.name)\(snapshot.ethernetLinks.contains($0.name) ? "" : "(non-ethernet)")=\($0.ipv4)" }
|
|
429
|
+
return "Wi-Fi interfaces=\(wifi.isEmpty ? "none" : wifi.sorted().joined(separator: ",")), " +
|
|
430
|
+
"Wi-Fi IPv4=\(addresses.isEmpty ? "none" : addresses.sorted().joined(separator: ",")), " +
|
|
431
|
+
"other private IPv4=\(other.isEmpty ? "none" : other.sorted().joined(separator: ","))"
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private func finishAssociation(address: String, generation gen: Int) {
|
|
435
|
+
// OTA serves incoming TCP. Its native listener proves server readiness; dialing
|
|
436
|
+
// the glasses' unrelated Gallery server would add a client permission dependency.
|
|
437
|
+
// TN3179: accepting incoming TCP does not require Local Network access.
|
|
438
|
+
if accessPurpose == .incomingServer {
|
|
439
|
+
finishJoin(.success(address))
|
|
440
|
+
} else {
|
|
441
|
+
waitForLocalAccess(address: address, generation: gen)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
private func waitForLocalAccess(address: String, generation gen: Int) {
|
|
446
|
+
let gateway = gatewayAddress ?? address.split(separator: ".").prefix(3).joined(separator: ".") + ".1"
|
|
447
|
+
let request = LocalNetworkAccessRequest(localAddress: address, gateway: gateway, queue: queue)
|
|
448
|
+
localAccess = request
|
|
449
|
+
request.start(onPermissionRequired: { [weak self] systemAnswer in
|
|
450
|
+
guard let self, gen == generation, !cancelled else { return }
|
|
451
|
+
Bridge.log("GLASSES-MEDIA local_network_permission=waiting \(systemAnswer)")
|
|
452
|
+
onPermissionRequired?(systemAnswer)
|
|
453
|
+
}) { [weak self] result in
|
|
454
|
+
guard let self, gen == generation, !cancelled else { return }
|
|
455
|
+
switch result {
|
|
456
|
+
case .success:
|
|
457
|
+
Bridge.log("GLASSES-MEDIA local_network_permission=ready")
|
|
458
|
+
finishJoin(.success(address))
|
|
459
|
+
case let .failure(error):
|
|
460
|
+
finishJoin(.failure(error))
|
|
461
|
+
finishLeave()
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private func finishJoin(_ result: Result<String, Error>) {
|
|
467
|
+
let reply = joinReply
|
|
468
|
+
joinReply = nil
|
|
469
|
+
reply?(result)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private func finishLeave() {
|
|
473
|
+
guard !finishingLeave else { return }
|
|
474
|
+
finishingLeave = true
|
|
475
|
+
macCleanupContinuation?.cleanupStarted()
|
|
476
|
+
if let association = macAssociation {
|
|
477
|
+
association.cancel()
|
|
478
|
+
// This queue is also the association queue: cleanup cannot overtake
|
|
479
|
+
// a blocking scan/join, and process-wide ownership remains held, including
|
|
480
|
+
// while leave() forgets the hotspot and returns the Mac to its previous Wi-Fi.
|
|
481
|
+
macWorker.async {
|
|
482
|
+
let result = Result { try association.leave() }
|
|
483
|
+
self.queue.async {
|
|
484
|
+
switch result {
|
|
485
|
+
case let .success(report):
|
|
486
|
+
if report.restore != .notNeeded { Bridge.log("HOTSPOT_LEAVE mac_wifi \(report.summary)") }
|
|
487
|
+
self.macAssociation = nil
|
|
488
|
+
self.completeLeave()
|
|
489
|
+
case let .failure(error):
|
|
490
|
+
// Retain the owner when we cannot prove which association
|
|
491
|
+
// cleanup would disconnect. A later leave can retry safely.
|
|
492
|
+
self.finishingLeave = false
|
|
493
|
+
let completion = self.leaveCompletion
|
|
494
|
+
self.leaveCompletion = nil
|
|
495
|
+
completion?.complete(.failure(error))
|
|
496
|
+
self.macCleanupContinuation?.cleanupFailed()
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
} else { completeLeave() }
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
private func completeLeave() {
|
|
504
|
+
macCleanupContinuation = nil
|
|
505
|
+
generation += 1
|
|
506
|
+
macAuthorization?.cancel(); macAuthorization = nil
|
|
507
|
+
localAccess?.cancel(); localAccess = nil
|
|
508
|
+
interfaceMonitors.forEach { $0.cancel() }
|
|
509
|
+
interfaceMonitors = []
|
|
510
|
+
wifiIdentity = HotspotWifiIdentity()
|
|
511
|
+
if let ssid, ownsConfiguration { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ssid) }
|
|
512
|
+
ownsConfiguration = false
|
|
513
|
+
ssid = nil
|
|
514
|
+
binding = nil
|
|
515
|
+
gatewayAddress = nil
|
|
516
|
+
let finish = {
|
|
517
|
+
self.finishingLeave = false
|
|
518
|
+
let completion = self.leaveCompletion
|
|
519
|
+
self.leaveCompletion = nil
|
|
520
|
+
if let completion { completion.complete(.success(())) } else {
|
|
521
|
+
if let token = self.ownershipToken { HotspotNetworkOwnership.shared.release(token) }
|
|
522
|
+
self.ownershipToken = nil
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
finish()
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/// Every attached interface's kernel index and link type (its AF_LINK row) and every IPv4
|
|
529
|
+
/// address with its interface name and up state. Selection belongs to HotspotInterfacePolicy;
|
|
530
|
+
/// an interface name alone never identifies Wi-Fi. A failed read yields an empty sample, which
|
|
531
|
+
/// fails closed.
|
|
532
|
+
static func interfaceSnapshot() -> HotspotInterfaceSnapshot {
|
|
533
|
+
var interfaces: UnsafeMutablePointer<ifaddrs>?
|
|
534
|
+
guard getifaddrs(&interfaces) == 0 else { return HotspotInterfaceSnapshot(links: [:], addresses: []) }
|
|
535
|
+
defer { freeifaddrs(interfaces) }
|
|
536
|
+
var links: [String: Int] = [:]
|
|
537
|
+
var ethernetLinks: Set<String> = []
|
|
538
|
+
var rows: [HotspotInterfaceAddress] = []
|
|
539
|
+
var cursor = interfaces
|
|
540
|
+
while let item = cursor {
|
|
541
|
+
defer { cursor = item.pointee.ifa_next }
|
|
542
|
+
let value = item.pointee
|
|
543
|
+
guard let address = value.ifa_addr else { continue }
|
|
544
|
+
let name = String(cString: value.ifa_name)
|
|
545
|
+
if address.pointee.sa_family == UInt8(AF_LINK) {
|
|
546
|
+
let (index, type) = address.withMemoryRebound(to: sockaddr_dl.self, capacity: 1) {
|
|
547
|
+
(Int($0.pointee.sdl_index), Int32($0.pointee.sdl_type))
|
|
548
|
+
}
|
|
549
|
+
if index > 0 {
|
|
550
|
+
links[name] = index
|
|
551
|
+
if type == IFT_ETHER { ethernetLinks.insert(name) }
|
|
552
|
+
}
|
|
553
|
+
continue
|
|
554
|
+
}
|
|
555
|
+
guard address.pointee.sa_family == UInt8(AF_INET) else { continue }
|
|
556
|
+
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
|
557
|
+
guard getnameinfo(address, socklen_t(address.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 else { continue }
|
|
558
|
+
rows.append(HotspotInterfaceAddress(name: name, isUp: value.ifa_flags & UInt32(IFF_UP) != 0, ipv4: String(cString: host)))
|
|
559
|
+
}
|
|
560
|
+
return HotspotInterfaceSnapshot(links: links, addresses: rows, ethernetLinks: ethernetLinks)
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
#endif
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// A failure the hotspot implementation authored itself, never a native error description.
|
|
4
|
+
public struct HotspotError: LocalizedError {
|
|
5
|
+
public let message: String
|
|
6
|
+
public init(_ message: String) {
|
|
7
|
+
self.message = message
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
public var errorDescription: String? {
|
|
11
|
+
message
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/// The glasses' DHCP server uses a /24. Never substitute an unrelated private interface.
|
|
16
|
+
public enum HotspotAddressPolicy {
|
|
17
|
+
public static func ipv4(_ value: String) -> [UInt8]? {
|
|
18
|
+
let parts = value.split(separator: ".", omittingEmptySubsequences: false)
|
|
19
|
+
guard parts.count == 4 else { return nil }
|
|
20
|
+
let bytes = parts.compactMap { UInt8($0) }
|
|
21
|
+
return bytes.count == 4 ? bytes : nil
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
public static func sameSubnet(_ lhs: String, _ rhs: String) -> Bool {
|
|
25
|
+
guard let a = ipv4(lhs), let b = ipv4(rhs) else { return false }
|
|
26
|
+
return a.prefix(3) == b.prefix(3)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
public static func isPrivate(_ address: String) -> Bool {
|
|
30
|
+
guard let bytes = ipv4(address) else { return false }
|
|
31
|
+
return bytes[0] == 10 || (bytes[0] == 172 && (16 ... 31).contains(bytes[1])) ||
|
|
32
|
+
(bytes[0] == 192 && bytes[1] == 168)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// SSID association can finish before DHCP replaces the previous Wi-Fi address.
|
|
36
|
+
/// Accept only a client address on the /24 advertised by the glasses over BLE.
|
|
37
|
+
public static func isHotspotClientAddress(_ address: String, gateway: String) -> Bool {
|
|
38
|
+
guard isPrivate(gateway), sameSubnet(address, gateway), address != gateway,
|
|
39
|
+
let bytes = ipv4(address) else { return false }
|
|
40
|
+
return bytes[3] > 0 && bytes[3] < 255
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/// A Mac may join through its host network controls. Reuse that connection only
|
|
44
|
+
/// after both its SSID and DHCP address match the hotspot advertised over BLE.
|
|
45
|
+
public static func canReuseHotspot(requestedSSID: String, currentSSID: String?, address: String?, gateway: String?) -> Bool {
|
|
46
|
+
guard !requestedSSID.isEmpty, requestedSSID == currentSSID,
|
|
47
|
+
let address, let gateway else { return false }
|
|
48
|
+
return isHotspotClientAddress(address, gateway: gateway)
|
|
49
|
+
}
|
|
50
|
+
}
|