Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix(ios): autoreconnect without mdns

Zack Bartelf34c23d603b4
diff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swift
index 6a03149..1fd031c 100644
--- a/apple/Tether/ViewModels/TetherViewModel.swift
+++ b/apple/Tether/ViewModels/TetherViewModel.swift
@@ -131,10 +131,23 @@ final class TetherViewModel {
private let fileChunkSize = 48 * 1024
private var hasInitialized = false
private var pendingReconnectTask: Task<Void, Never>?
+ private var connectTimeoutTask: Task<Void, Never>?
private var autoConnectingFingerprint: String?
private var manualDisconnect = false
private var currentScenePhase: ScenePhase = .active
+ // Consecutive failed reconnect attempts, used to space out the retries.
+ private var reconnectAttempts = 0
+
+ // Base delay before a reconnect attempt, doubled per consecutive failure.
+ private static let reconnectBaseDelay: Double = 0.7
+
+ // capped exponential backoff.
+ private static let reconnectMaxDelay: Double = 30
+
+ // How long a dial may sit unanswered before it is treated as failed.
+ private static let connectTimeout: Double = 8
+
private struct IncomingTransferBuffer {
let filename: String
let expectedSize: Int64
@@ -189,10 +202,13 @@ final class TetherViewModel {
switch phase {
case .active:
manualDisconnect = false
+ reconnectAttempts = 0
refreshDiscovery()
case .background:
pendingReconnectTask?.cancel()
pendingReconnectTask = nil
+ connectTimeoutTask?.cancel()
+ connectTimeoutTask = nil
suspendForBackground()
default:
break
@@ -222,6 +238,7 @@ final class TetherViewModel {
// Persist the service name so the Share Extension can connect without discovery.
ShareSender.persistLastServiceName(host.name)
connection.connect(to: host.endpoint, identity: identity)
+ startConnectTimeout()
}
// Connect by IP address and port.
@@ -235,6 +252,7 @@ final class TetherViewModel {
appState = .connecting
connectedDeviceName = host
connection.connect(host: host, port: port, identity: identity)
+ startConnectTimeout()
}
// Disconnect from the daemon.
@@ -242,6 +260,9 @@ final class TetherViewModel {
manualDisconnect = true
pendingReconnectTask?.cancel()
pendingReconnectTask = nil
+ connectTimeoutTask?.cancel()
+ connectTimeoutTask = nil
+ reconnectAttempts = 0
autoConnectingFingerprint = nil
certificateManager.lastConnectedFingerprint = nil // Also clear last connection
connection.disconnect()
@@ -402,21 +423,31 @@ final class TetherViewModel {
guard let self else { return }
switch state {
case .connected(let isInbound):
+ if let expected = self.autoConnectingFingerprint, !isInbound,
+ self.connection.serverFingerprint != expected {
+ self.autoConnectingFingerprint = nil
+ self.connection.disconnect()
+ return
+ }
+ self.cancelConnectTimeout()
self.pendingReconnectTask?.cancel()
self.pendingReconnectTask = nil
self.autoConnectingFingerprint = nil
+ self.reconnectAttempts = 0
self.certificateManager.lastConnectedFingerprint = self.connection.serverFingerprint
if let endpoint = self.connection.resolvedEndpoint {
ShareSender.persistLastEndpoint(host: endpoint.host, port: endpoint.port)
}
self.handleConnected(isInbound: isInbound)
case .disconnected:
+ self.cancelConnectTimeout()
self.autoConnectingFingerprint = nil
self.appState = .disconnected
if self.currentScenePhase == .active {
self.scheduleAutoReconnectAttempt()
}
case .failed(let msg):
+ self.cancelConnectTimeout()
let wasAutoReconnect = self.autoConnectingFingerprint != nil
self.autoConnectingFingerprint = nil
self.appState = .disconnected
@@ -485,13 +516,19 @@ final class TetherViewModel {
}
private func scheduleAutoReconnectAttempt() {
- print("TetherViewModel: Scheduling auto-reconnect. shouldAutoReconnect: \(shouldAutoReconnect), autoConnectingFingerprint: \(String(describing: autoConnectingFingerprint))")
guard shouldAutoReconnect else { return }
guard autoConnectingFingerprint == nil else { return }
+ // delay is also mDNS's window to answer
+ let delay = min(
+ Self.reconnectBaseDelay * pow(2, Double(reconnectAttempts)),
+ Self.reconnectMaxDelay
+ )
+
pendingReconnectTask?.cancel()
pendingReconnectTask = Task { [weak self] in
- try? await Task.sleep(for: .milliseconds(700))
+ try? await Task.sleep(for: .seconds(delay))
+ guard !Task.isCancelled else { return }
await MainActor.run {
self?.attemptAutoReconnect()
}
@@ -512,12 +549,11 @@ final class TetherViewModel {
}
private func attemptAutoReconnect() {
- print("TetherViewModel: Attempting auto-reconnect. Last fingerprint: \(String(describing: certificateManager.lastConnectedFingerprint)), Found hosts: \(discovery.hosts.count)")
guard shouldAutoReconnect else { return }
-
+
// If we have a last connected fingerprint, prioritize it.
let targetFingerprint = certificateManager.lastConnectedFingerprint
-
+
let matchingHosts: [DiscoveredHost]
if let targetFingerprint {
matchingHosts = discovery.hosts.filter { $0.fingerprint == targetFingerprint }
@@ -526,17 +562,43 @@ final class TetherViewModel {
// but ONLY if there's exactly one host found.
matchingHosts = discovery.hosts.count == 1 ? discovery.hosts : []
}
-
- print("TetherViewModel: Found \(matchingHosts.count) matching hosts for auto-reconnect.")
- guard let targetHost = matchingHosts.first else { return }
// Stay silent when the identity is missing; the error belongs to a user-initiated
// connect, not to a background reconnect on every launch.
guard certificateManager.getIdentity() != nil else { return }
- print("TetherViewModel: Connecting to target host: \(targetHost.name)")
- autoConnectingFingerprint = targetHost.fingerprint
- connectTo(host: targetHost)
+ if let targetHost = matchingHosts.first {
+ reconnectAttempts += 1
+ autoConnectingFingerprint = targetHost.fingerprint
+ connectTo(host: targetHost)
+ return
+ }
+
+ // discovery found nothing.
+ guard let targetFingerprint, certificateManager.isHostKnown(targetFingerprint),
+ let endpoint = ShareSender.lastEndpoint() else { return }
+
+ reconnectAttempts += 1
+ autoConnectingFingerprint = targetFingerprint
+ connectTo(host: endpoint.host, port: endpoint.port)
+ }
+
+ // Fail a dial that the network never answers, so the reconnect loop can back off and try again.
+ private func startConnectTimeout() {
+ connectTimeoutTask?.cancel()
+ connectTimeoutTask = Task { [weak self] in
+ try? await Task.sleep(for: .seconds(Self.connectTimeout))
+ guard !Task.isCancelled else { return }
+ await MainActor.run {
+ guard let self, self.appState == .connecting else { return }
+ self.connection.disconnect()
+ }
+ }
+ }
+
+ private func cancelConnectTimeout() {
+ connectTimeoutTask?.cancel()
+ connectTimeoutTask = nil
}
private func suspendForBackground() {
diff --git a/apple/Tether/Views/DashboardView.swift b/apple/Tether/Views/DashboardView.swift
index 74320d0..d33bcaa 100644
--- a/apple/Tether/Views/DashboardView.swift
+++ b/apple/Tether/Views/DashboardView.swift
@@ -57,6 +57,7 @@ struct DashboardView: View {
}
.sheet(isPresented: $showManualConnect) {
manualConnectSheet
+ .onAppear(perform: prefillManualConnect)
}
}
}
@@ -276,8 +277,9 @@ struct DashboardView: View {
NavigationStack {
Form {
Section("Host") {
- TextField("IP Address", text: $manualHost)
- .keyboardType(.decimalPad)
+ TextField("Host or IP", text: $manualHost)
+ .keyboardType(.URL)
+ .textInputAutocapitalization(.never)
.autocorrectionDisabled()
TextField("Port", text: $manualPort)
@@ -306,6 +308,14 @@ struct DashboardView: View {
// MARK: - Helpers
+ // Seed the sheet with the address that last worked, so recovering a connection
+ // discovery cannot make is a tap rather than a retype.
+ private func prefillManualConnect() {
+ guard manualHost.isEmpty, let endpoint = ShareSender.lastEndpoint() else { return }
+ manualHost = endpoint.host
+ manualPort = String(endpoint.port)
+ }
+
private func formatFingerprint(_ fp: String) -> String {
var result = ""
for (i, char) in fp.enumerated() {
diff --git a/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift b/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift
index 91e8956..f52d7dd 100644
--- a/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift
+++ b/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift
@@ -289,4 +289,13 @@ extension ShareSender {
sharedDefaults.set(host, forKey: lastHostKey)
sharedDefaults.set(Int(port), forKey: lastPortKey)
}
+
+ /// The last endpoint a connection actually resolved to, if one was ever cached.
+ public static func lastEndpoint() -> (host: String, port: UInt16)? {
+ let sharedDefaults = UserDefaults(suiteName: CertificateManager.appGroupID) ?? .standard
+ guard let host = sharedDefaults.string(forKey: lastHostKey), !host.isEmpty,
+ let portInt = sharedDefaults.object(forKey: lastPortKey) as? Int,
+ portInt > 0, portInt <= Int(UInt16.max) else { return nil }
+ return (host, UInt16(portInt))
+ }
}
diff --git a/apple/TetherFramework/Sources/TetherFramework/TetherConnection.swift b/apple/TetherFramework/Sources/TetherFramework/TetherConnection.swift
index 17d192d..2adcca0 100644
--- a/apple/TetherFramework/Sources/TetherFramework/TetherConnection.swift
+++ b/apple/TetherFramework/Sources/TetherFramework/TetherConnection.swift
@@ -60,7 +60,7 @@ public final class TetherConnection {
// - endpoint: The Bonjour or direct `NWEndpoint` to connect to.
// - identity: The client's `SecIdentity` for mTLS authentication.
public func connect(to endpoint: NWEndpoint, identity: SecIdentity) {
- disconnect()
+ teardown()
let tlsOptions = NWProtocolTLS.Options()
let secOptions = tlsOptions.securityProtocolOptions
@@ -109,7 +109,7 @@ public final class TetherConnection {
// - connection: The `NWConnection` already established and in `.ready` state.
// - fingerprint: The verified TLS fingerprint of the incoming client.
public func accept(incomingConnection conn: NWConnection, fingerprint: String) {
- disconnect()
+ teardown()
self.serverFingerprint = fingerprint
self.connection = conn
@@ -125,11 +125,19 @@ public final class TetherConnection {
// Disconnect and tear down the connection.
public func disconnect() {
- connection?.cancel()
+ teardown()
+ updateState(.disconnected)
+ }
+
+ // Drop the socket without announcing a state.
+ private func teardown() {
+ if let conn = connection {
+ conn.stateUpdateHandler = nil
+ conn.cancel()
+ }
connection = nil
receiveBuffer = Data()
serverFingerprint = ""
- updateState(.disconnected)
}
// Send a protocol message to the daemon.
diff --git a/apple/TetherFramework/Tests/TetherFrameworkTests/ShareSenderTests.swift b/apple/TetherFramework/Tests/TetherFrameworkTests/ShareSenderTests.swift
new file mode 100644
index 0000000..2cf5ae9
--- /dev/null
+++ b/apple/TetherFramework/Tests/TetherFrameworkTests/ShareSenderTests.swift
@@ -0,0 +1,34 @@
+//
+// ShareSenderTests.swift
+// TetherFrameworkTests
+//
+
+import Foundation
+import Testing
+@testable import TetherFramework
+
+struct ShareSenderTests {
+ // The main app reconnects to this endpoint when discovery finds nothing, so a
+ // persisted host must come back as the same host and port.
+ @Test func lastEndpointRoundTrips() {
+ let defaults = UserDefaults(suiteName: CertificateManager.appGroupID) ?? .standard
+ let savedHost = defaults.string(forKey: "TetherLastHost")
+ let savedPort = defaults.object(forKey: "TetherLastPort")
+ defer {
+ defaults.set(savedHost, forKey: "TetherLastHost")
+ defaults.set(savedPort, forKey: "TetherLastPort")
+ }
+
+ ShareSender.persistLastEndpoint(host: "100.101.102.103", port: 5134)
+ let endpoint = ShareSender.lastEndpoint()
+ #expect(endpoint?.host == "100.101.102.103")
+ #expect(endpoint?.port == 5134)
+
+ ShareSender.persistLastEndpoint(host: "", port: 5134)
+ #expect(ShareSender.lastEndpoint() == nil)
+
+ defaults.set("100.101.102.103", forKey: "TetherLastHost")
+ defaults.set(99999, forKey: "TetherLastPort")
+ #expect(ShareSender.lastEndpoint() == nil)
+ }
+}
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 59fb13a..abd3b8a 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -148,6 +148,8 @@ Only the node with the **lower** fingerprint dials. Every node both listens and
The iPhone app dials on launch and is therefore reachable either way.
+mDNS is multicast, so it resolves nothing across a VPN such as Tailscale, or on Wi-Fi with AP isolation. When discovery returns no match, the iPhone app dials the address its last session resolved to, provided that peer's fingerprint is still in `known_hosts.json`. A handshake fingerprint that does not match the expected one means the address has moved to another machine; the session is dropped without a pairing prompt.
+
### `pair_request` (Untrusted Client -> Daemon)
**Description**: Emitted natively by a new client over standard TLS to gracefully present its identity and X.509 fingerprint. The Daemon immediately intercepts the payload, extracts the fingerprint natively from the `SSL*` pipe, and flags it locally as "Pending Authentication". Anything other than `pair_request` results in the TLS socket securely disconnecting.