Linux + iPhone Continuity / iMessage / SMS
first shot at bi-directional
Zack Bartel07090ede7bff
diff --git a/apple/Tether/Services/TetherConnection.swift b/apple/Tether/Services/TetherConnection.swiftindex 78f4bfe..db4d643 100644--- a/apple/Tether/Services/TetherConnection.swift+++ b/apple/Tether/Services/TetherConnection.swift@@ -92,6 +92,26 @@ final class TetherConnection {connect(to: endpoint, identity: identity)}+ /// Accept a pre-established incoming connection from `TetherServer`.+ ///+ /// - Parameters:+ /// - connection: The `NWConnection` already established and in `.ready` state.+ /// - fingerprint: The verified TLS fingerprint of the incoming client.+ func accept(incomingConnection conn: NWConnection, fingerprint: String) {+ disconnect()+ self.serverFingerprint = fingerprint+ self.connection = conn++ // Re-bind the state update handler for the accepted connection+ conn.stateUpdateHandler = { [weak self] nwState in+ self?.handleStateUpdate(nwState)+ }++ // It's already ready, so we just jump straight to receiving+ updateState(.connected)+ startReceiving()+ }+/// Disconnect and tear down the connection.func disconnect() {connection?.cancel()diff --git a/apple/Tether/Services/TetherServer.swift b/apple/Tether/Services/TetherServer.swiftnew file mode 100644index 0000000..e42acf7--- /dev/null+++ b/apple/Tether/Services/TetherServer.swift@@ -0,0 +1,134 @@+//+// TetherServer.swift+// Tether+//+// NWListener-based TCP + TLS server to accept incoming connections+// from `tetherd` instances (making iOS a symmetrical peer).+//++import Foundation+import Network+import Security++@Observable+final class TetherServer: NSObject, NetServiceDelegate {+ private var listener: NWListener?+ private var netService: NetService?++ var isListening = false++ /// Callback when a verified inbound connection is received+ var onNewConnection: ((NWConnection, String) -> Void)?++ func start(identity: SecIdentity, localDeviceName: String, fingerprint: String) {+ stop()++ let tlsOptions = NWProtocolTLS.Options()+ let secOptions = tlsOptions.securityProtocolOptions++ let secIdentity = sec_identity_create(identity)!+ sec_protocol_options_set_local_identity(secOptions, secIdentity)++ sec_protocol_options_set_min_tls_protocol_version(secOptions, .TLSv12)+ sec_protocol_options_set_max_tls_protocol_version(secOptions, .TLSv12)++ // As a server, require the client to present its certificate+ sec_protocol_options_set_peer_authentication_required(secOptions, true)++ // Temporarily store the fingerprint. In a high-concurrency server we'd use a robust map,+ // but for a single peer-to-peer mobile app, a simple property is more than sufficient.+ var temporaryHandshakeFingerprint = ""++ // Accept the certificate and capture the fingerprint+ sec_protocol_options_set_verify_block(secOptions, { metadata, trust, completion in+ let secTrust = sec_trust_copy_ref(trust).takeRetainedValue()+ if let certChain = SecTrustCopyCertificateChain(secTrust) as? [SecCertificate],+ let clientCert = certChain.first {+ temporaryHandshakeFingerprint = CertificateManager.fingerprint(ofCertificate: clientCert)+ }+ completion(true)+ }, .main)++ let params = NWParameters(tls: tlsOptions, tcp: .init())+ params.includePeerToPeer = true++ do {+ let nwListener = try NWListener(using: params)++ nwListener.newConnectionHandler = { [weak self] connection in+ self?.handleNewConnection(connection, capturedFingerprint: temporaryHandshakeFingerprint)+ }++ nwListener.stateUpdateHandler = { [weak self] state in+ guard let self = self else { return }+ switch state {+ case .ready:+ self.isListening = true+ if let port = nwListener.port?.rawValue {+ print("TetherServer: Listening on port \(port)")+ self.publishBonjour(port: port, deviceName: localDeviceName, fingerprint: fingerprint)+ }+ case .failed(let error):+ print("TetherServer: Listener failed with error: \(error)")+ self.isListening = false+ self.stop()+ case .cancelled:+ self.isListening = false+ default:+ break+ }+ }++ nwListener.start(queue: .main)+ self.listener = nwListener++ } catch {+ print("TetherServer: Failed to create listener: \(error)")+ }+ }++ func stop() {+ listener?.cancel()+ listener = nil++ netService?.stop()+ netService = nil++ isListening = false+ }++ private func publishBonjour(port: UInt16, deviceName: String, fingerprint: String) {+ netService = NetService(domain: "local.", type: "_tether._tcp", name: deviceName, port: Int32(port))++ if let fpData = fingerprint.data(using: .utf8) {+ let txtDict = ["fp": fpData]+ let txtRecord = NetService.data(fromTXTRecord: txtDict)+ netService?.setTXTRecord(txtRecord)+ }++ netService?.delegate = self+ netService?.publish()+ }++ private func handleNewConnection(_ connection: NWConnection, capturedFingerprint: @escaping @autoclosure () -> String) {+ connection.stateUpdateHandler = { [weak self] state in+ guard let self = self else { return }+ print("TetherServer: Inbound connection state: \(state)")+ if case .ready = state {+ print("TetherServer: Inbound connection established and ready.")+ self.onNewConnection?(connection, capturedFingerprint())+ }+ }++ connection.start(queue: .main)+ }++ // NetServiceDelegate+ func netServiceDidPublish(_ sender: NetService) {+ print("TetherServer: Bonjour service published successfully.")+ }++ func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) {+ print("TetherServer: Bonjour publish failed: \(errorDict)")+ }+}diff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swiftindex 9828721..9147bf6 100644--- a/apple/Tether/ViewModels/TetherViewModel.swift+++ b/apple/Tether/ViewModels/TetherViewModel.swift@@ -109,6 +109,7 @@ final class TetherViewModel {let certificateManager = CertificateManager()let discovery = BonjourDiscovery()let connection = TetherConnection()+ let server = TetherServer()/// The chunk size for file transfers (48KB raw → 64KB base64).private let fileChunkSize = 48 * 1024@@ -139,7 +140,9 @@ final class TetherViewModel {certificateManager.initialize()setupConnectionHandlers()+ setupServerHandlers()startDiscovery()+ startServer()scheduleAutoReconnectAttempt()}@@ -214,6 +217,7 @@ final class TetherViewModel {connection.disconnect()appState = .disconnectedconnectedDeviceName = nil+ pairingStatus = ""}// MARK: - Clipboard@@ -392,6 +396,28 @@ final class TetherViewModel {}}+ private func setupServerHandlers() {+ server.onNewConnection = { [weak self] incomingConn, incomingFingerprint in+ guard let self = self else { return }++ // We just received an incoming connection from a peer!+ // We give it to our connection manager and start decoding.+ self.connection.accept(incomingConnection: incomingConn, fingerprint: incomingFingerprint)++ // Note: `onStateChange` will automatically transition us to .connected+ // and trigger `handleConnected()` which checks if it's already paired.+ }+ }++ private func startServer() {+ guard let identity = certificateManager.getIdentity() else { return }+ server.start(+ identity: identity,+ localDeviceName: certificateManager.localDeviceName,+ fingerprint: certificateManager.myFingerprint+ )+ }+private func handleConnected() {let serverFP = connection.serverFingerprint@@ -465,6 +491,7 @@ final class TetherViewModel {autoConnectingFingerprint = nilconnection.disconnect()+ server.stop()appState = .disconnectedconnectedDeviceName = nil}@@ -502,6 +529,14 @@ final class TetherViewModel {case .pairPending:pairingStatus = "Waiting for approval on your desktop...\n\nRun: tether --accept \(certificateManager.myFingerprint)"+ case .pairRequest:+ if let targetName = message.deviceName {+ connectedDeviceName = targetName+ appState = .pairing+ pairingStatus = "Pairing request received from \(targetName)"+ showPairingSheet = true+ }+case .fileStatus:if let transferId = message.transferId, message.status == "success" {if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {@@ -572,6 +607,12 @@ final class TetherViewModel {let serverFP = connection.serverFingerprintlet name = connectedDeviceName ?? "Desktop"certificateManager.addKnownHost(fingerprint: serverFP, name: name)++ // If we received an inbound pair_request, we must respond back with pair_accepted!+ // But the original tether daemon protocol relies on disconnecting if rejected, and+ // the client isn't expected to send pair_accepted, the desktop daemon sends pair_accepted.+ // Let's send a simple OK or just leave it. If the connection drops we assume rejected.+ // Actually, let's just save it.showPairingSheet = falseappState = .connected}