Linux + iPhone Continuity / iMessage / SMS
fix: dial-out net pairing requests fail
Zack Bartel692d7374d229
diff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swiftindex 03fa8e4..6a03149 100644--- a/apple/Tether/ViewModels/TetherViewModel.swift+++ b/apple/Tether/ViewModels/TetherViewModel.swift@@ -113,6 +113,10 @@ final class TetherViewModel {// Status message for the pairing flow.private(set) var pairingStatus: String = ""+ // Which side asked. Inbound means a peer dialled us and this device is the+ // approver. Outbound means we asked and the peer's user decides.+ private(set) var pairingIsInbound = false+// Error message to display, if any.var errorMessage: String?@@ -397,7 +401,7 @@ final class TetherViewModel {connection.onStateChange = { [weak self] state inguard let self else { return }switch state {- case .connected:+ case .connected(let isInbound):self.pendingReconnectTask?.cancel()self.pendingReconnectTask = nilself.autoConnectingFingerprint = nil@@ -405,7 +409,7 @@ final class TetherViewModel {if let endpoint = self.connection.resolvedEndpoint {ShareSender.persistLastEndpoint(host: endpoint.host, port: endpoint.port)}- self.handleConnected() // TODO: isInbound+ self.handleConnected(isInbound: isInbound)case .disconnected:self.autoConnectingFingerprint = nilself.appState = .disconnected@@ -463,11 +467,12 @@ final class TetherViewModel {connectedDeviceName = certificateManager.knownHosts[serverFP] ?? connectedDeviceName} else {// Need to pair+ pairingIsInbound = isInboundif isInbound {// If it's an inbound connection, we wait for the client to send us a pair_request.// We don't send one ourselves over their established tunnel.appState = .pairing- // The UI will update when we actually receive the .pairRequest command+ // The UI will update when we actually receive the .pairRequest command} else {appState = .pairingshowPairingSheet = true@@ -585,10 +590,15 @@ final class TetherViewModel {if let targetName = message.deviceName {connectedDeviceName = targetNameappState = .pairing- pairingStatus = "Pairing request received from \(targetName)"+ pairingIsInbound = true+ pairingStatus = "\(targetName) wants to pair with this device."showPairingSheet = true}+ case .pairAccepted:+ // The peer's user approved. This, not our own tap, is what makes us paired.+ finishPairing()+case .fileStatus:if let transferId = message.transferId, message.status == "success" {if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {@@ -640,8 +650,11 @@ final class TetherViewModel {case .error:if message.message == "unauthorized" {- // The daemon rejected us — we're not paired yet.- // This can happen if the user hasn't accepted the pairing request.+ // The daemon rejects every command until it has pinned us, so we are+ // not connected no matter what the last state said.+ appState = .pairing+ pairingIsInbound = false+ showPairingSheet = truepairingStatus = "Pairing request sent. Waiting for approval...\n\nRun: tether --accept \(certificateManager.myFingerprint)"} else {errorMessage = message.message ?? "Unknown error from daemon"@@ -652,18 +665,31 @@ final class TetherViewModel {}}- // Call after the daemon accepts the pairing request.- // The daemon will start accepting our commands, so we just need to- // save the server fingerprint and transition to connected state.- func confirmPairing() {+ // Approve a request from a peer that dialled us. This device is the approver+ // here, so the tap is the real decision and the peer is told about it.+ func acceptIncomingPairing() {+ connection.send(.pairAccepted)+ finishPairing()+ }++ // Reject a request from a peer that dialled us.+ func rejectIncomingPairing() {+ showPairingSheet = false+ pairingStatus = ""+ disconnect()+ }++ // Pin the peer and go live. Reached only once the pairing is real: either the+ // peer sent pair_accepted, or this device approved an inbound request.+ private func finishPairing() {let serverFP = connection.serverFingerprint+ guard !serverFP.isEmpty else { return }+let name = connectedDeviceName ?? "Desktop"certificateManager.addKnownHost(fingerprint: serverFP, name: name)-- // Let's send pair_accepted to tell the daemon we successfully paired!- connection.send(.pairAccepted)-+showPairingSheet = false+ pairingStatus = ""appState = .connected}diff --git a/apple/Tether/Views/PairingView.swift b/apple/Tether/Views/PairingView.swiftindex de6cd1a..42c134f 100644--- a/apple/Tether/Views/PairingView.swift+++ b/apple/Tether/Views/PairingView.swift@@ -58,43 +58,55 @@ struct PairingView: View {}// Fingerprint Display- VStack(spacing: 8) {- Text("Your Device Fingerprint")- .font(.caption)- .foregroundStyle(.tertiary)- .textCase(.uppercase)-- Text(formatFingerprint(viewModel.certificateManager.myFingerprint))- .font(.system(.caption, design: .monospaced))- .foregroundStyle(.secondary)- .padding(.horizontal, 16)- .padding(.vertical, 10)- .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8))- .textSelection(.enabled)+ if !viewModel.pairingIsInbound {+ VStack(spacing: 8) {+ Text("Your Device Fingerprint")+ .font(.caption)+ .foregroundStyle(.tertiary)+ .textCase(.uppercase)++ Text(formatFingerprint(viewModel.certificateManager.myFingerprint))+ .font(.system(.caption, design: .monospaced))+ .foregroundStyle(.secondary)+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8))+ .textSelection(.enabled)+ }}Spacer()// ActionsVStack(spacing: 12) {- Button {- viewModel.confirmPairing()- } label: {- Text("I've Approved on Desktop")- .font(.body.weight(.semibold))- .frame(maxWidth: .infinity)- .padding(.vertical, 14)- }- .buttonStyle(.borderedProminent)- .tint(.teal)-- Button {- viewModel.disconnect()- viewModel.showPairingSheet = false- } label: {- Text("Cancel")- .font(.subheadline)- .foregroundStyle(.secondary)+ if viewModel.pairingIsInbound {+ Button {+ viewModel.acceptIncomingPairing()+ } label: {+ Text("Accept")+ .font(.body.weight(.semibold))+ .frame(maxWidth: .infinity)+ .padding(.vertical, 14)+ }+ .buttonStyle(.borderedProminent)+ .tint(.teal)++ Button {+ viewModel.rejectIncomingPairing()+ } label: {+ Text("Reject")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }+ } else {+ Button {+ viewModel.disconnect()+ viewModel.showPairingSheet = false+ } label: {+ Text("Cancel")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }}}.padding(.horizontal, 24)diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.mdindex b7b2841..a01e3d1 100644--- a/docs/PROTOCOL.md+++ b/docs/PROTOCOL.md@@ -132,6 +132,14 @@ Access control is trust-on-first-use fingerprint pinning. After the handshake thTLS still verifies the peer's `CertificateVerify` signature, so a pinned fingerprint proves the peer holds the matching private key. An attacker on the same network cannot impersonate a paired device without that key, but they can open a connection and sit at the pairing prompt.+Every node is a peer. A PC, iPhone or iPad all listen and all dial, and one certificate serves both roles, so a node's fingerprint is the same whether it opened the connection or accepted it. Pairing is therefore direction-agnostic but never symmetric in authority:++- The **dialling** node sends `pair_request` as soon as its handshake completes. Dialling is its own consent, so it prompts nobody locally.+- The **receiving** node prompts its user (the desktop dialog, or `tether --accept <fingerprint>`).+- Only the receiver's approval settles it. It replies `pair_accepted`, and **both** sides then write the other's fingerprint to their own `known_hosts.json`.++A node must never pin a peer on local assertion alone — a UI must not report a device paired or connected until `pair_accepted` has crossed the wire and the trust record exists.+### `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.@@ -155,7 +163,18 @@ TLS still verifies the peer's `CertificateVerify` signature, so a pinned fingerp}```-Once paired (via `tether --accept <fingerprint>`), the fingerprint is written to `known_hosts.json`. Later connections presenting that certificate are treated as paired and may issue any command.+### `pair_accepted` (Approving Node -> Requesting Node)++**Description**: The approver's verdict, sent on the same TLS session once its user accepts. The requesting node pins the approver's fingerprint on receipt and the session is promoted in place — no reconnect.++**Payload**:+```json+{+ "command": "pair_accepted"+}+```++Once paired (via `tether --accept <fingerprint>`, the desktop dialog, or the peer's `pair_accepted`), the fingerprint is written to `known_hosts.json`. Later connections presenting that certificate are treated as paired and may issue any command.---@@ -169,8 +188,9 @@ Instructs the daemon to perform a synchronous mDNS scan (3 seconds) in a backgro**Response**: The daemon broadcasts a `discovery_result` payload asynchronously containing an array of active `devices`.### `pair_request` (Local Client -> Daemon)-Instructs the daemon to asynchronously reach out to a specific host to initiate a TLS pairing request.-**Payload**: `{"command": "pair_request", "host": "192.168.1.5", "port": 5134}`+Instructs the daemon to dial a peer and hold the resulting TLS session itself, sending `pair_request` on it as described in §3. `device_name` is the peer's advertised mDNS name, used to label the trust record; it is optional and falls back to the address.+**Payload**: `{"command": "pair_request", "host": "192.168.1.5", "port": 5134, "device_name": "workstation"}`+**Response**: The daemon broadcasts `pair_outbound_pending` while the peer's user decides, then either `pair_accepted` (with `connected: true`) or `pair_rejected`. A dial to a peer the daemon already has a session with is a no-op.### `accept_device` (Local Client -> Daemon)Trusts a pending pair request by moving the target fingerprint into the daemon's internal secure `known_hosts.json`.diff --git a/po/cs.po b/po/cs.poindex 03bceb2..d5143cd 100644--- a/po/cs.po+++ b/po/cs.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Czech\n"@@ -1165,6 +1165,15 @@ msgstr "Částečně připojeno"msgid "Paired"msgstr "Spárováno"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Čeká se na schválení na {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Žádost o spárování byla odmítnuta."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Připraveno"diff --git a/po/de.po b/po/de.poindex 4052ce1..d518063 100644--- a/po/de.po+++ b/po/de.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-22\n""Last-Translator: Tether project\n""Language-Team: German\n"@@ -310,7 +310,8 @@ msgstr "in Verwendung"#: src/cli/main.cpp#, c++-formatmsgid "Controller {} is not present; using the first powered one instead."-msgstr "Adapter {} ist nicht vorhanden; es wird der erste eingeschaltete verwendet."+msgstr ""+"Adapter {} ist nicht vorhanden; es wird der erste eingeschaltete verwendet."#: src/cli/main.cpp#, c-format@@ -1191,6 +1192,15 @@ msgstr "Teilweise verbunden"msgid "Paired"msgstr "Gekoppelt"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Warten auf die Bestätigung auf {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Die Kopplungsanfrage wurde abgelehnt."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Bereit"diff --git a/po/es.po b/po/es.poindex 50cafd8..82392ea 100644--- a/po/es.po+++ b/po/es.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-22\n""Last-Translator: Tether project\n""Language-Team: Spanish\n"@@ -560,7 +560,8 @@ msgstr "Duplicación de notificaciones desactivada."#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "Se esperaba un adaptador, p. ej. --bt-adapter hci1, o --bt-adapter auto\n"+msgstr ""+"Se esperaba un adaptador, p. ej. --bt-adapter hci1, o --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -1183,6 +1184,15 @@ msgstr "Parcialmente conectado"msgid "Paired"msgstr "Emparejado"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Esperando la aprobación en {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "La solicitud de emparejamiento fue rechazada."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Listo"diff --git a/po/fr.po b/po/fr.poindex c6e5249..be5a0e2 100644--- a/po/fr.po+++ b/po/fr.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-22\n""Last-Translator: Tether project\n""Language-Team: French\n"@@ -1191,6 +1191,15 @@ msgstr "Partiellement connecté"msgid "Paired"msgstr "Appairé"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "En attente de l'approbation sur {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "La demande d'appairage a été refusée."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Prêt"diff --git a/po/it.po b/po/it.poindex 35f982c..fbfef6a 100644--- a/po/it.po+++ b/po/it.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Italian\n"@@ -561,7 +561,8 @@ msgstr "Mirroring delle notifiche disattivato."#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "Atteso un adattatore, ad es. --bt-adapter hci1, oppure --bt-adapter auto\n"+msgstr ""+"Atteso un adattatore, ad es. --bt-adapter hci1, oppure --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -1179,6 +1180,15 @@ msgstr "Parzialmente connesso"msgid "Paired"msgstr "Accoppiato"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "In attesa dell'approvazione su {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "La richiesta di accoppiamento è stata rifiutata."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Pronto"diff --git a/po/ja.po b/po/ja.poindex 1a8ae2b..5efde53 100644--- a/po/ja.po+++ b/po/ja.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Japanese\n"@@ -542,7 +542,8 @@ msgstr "通知のミラーリングを無効にしました。"#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "アダプタを指定してください。例: --bt-adapter hci1 または --bt-adapter auto\n"+msgstr ""+"アダプタを指定してください。例: --bt-adapter hci1 または --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -552,7 +553,8 @@ msgstr "「{}」に一致する Bluetooth アダプタがありません。利#: src/cli/main.cpp#, c-formatmsgid "Controller selection is automatic: the first powered one.\n"-msgstr "アダプタの選択は自動です。電源の入っている最初のアダプタを使用します。\n"+msgstr ""+"アダプタの選択は自動です。電源の入っている最初のアダプタを使用します。\n"#: src/cli/main.cpp#, c++-format@@ -1151,6 +1153,15 @@ msgstr "部分的に接続"msgid "Paired"msgstr "ペアリング済み"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "{0} での承認を待っています…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "ペアリング要求は拒否されました。"+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "準備完了"diff --git a/po/ko.po b/po/ko.poindex 8a8f2ec..5eb3edf 100644--- a/po/ko.po+++ b/po/ko.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Korean\n"@@ -1141,6 +1141,15 @@ msgstr "부분적으로 연결됨"msgid "Paired"msgstr "페어링됨"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "{0}에서 승인을 기다리는 중입니다…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "페어링 요청이 거부되었습니다."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "준비됨"diff --git a/po/nl.po b/po/nl.poindex c1970d5..61439cf 100644--- a/po/nl.po+++ b/po/nl.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Dutch\n"@@ -311,7 +311,8 @@ msgstr "in gebruik"#: src/cli/main.cpp#, c++-formatmsgid "Controller {} is not present; using the first powered one instead."-msgstr "Adapter {} is niet aanwezig; de eerste ingeschakelde adapter wordt gebruikt."+msgstr ""+"Adapter {} is niet aanwezig; de eerste ingeschakelde adapter wordt gebruikt."#: src/cli/main.cpp#, c-format@@ -1175,6 +1176,15 @@ msgstr "Gedeeltelijk verbonden"msgid "Paired"msgstr "Gekoppeld"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Wachten op goedkeuring op {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Het koppelverzoek is geweigerd."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Gereed"diff --git a/po/pl.po b/po/pl.poindex d254833..ddbea60 100644--- a/po/pl.po+++ b/po/pl.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Polish\n"@@ -1177,6 +1177,15 @@ msgstr "Częściowo połączono"msgid "Paired"msgstr "Sparowano"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Oczekiwanie na zatwierdzenie na {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Żądanie parowania zostało odrzucone."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Gotowe"diff --git a/po/pt_BR.po b/po/pt_BR.poindex f6ee9ca..d18391d 100644--- a/po/pt_BR.po+++ b/po/pt_BR.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Brazilian Portuguese\n"@@ -557,7 +557,8 @@ msgstr "Espelhamento de notificações desativado."#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "Esperado um adaptador, p. ex. --bt-adapter hci1, ou --bt-adapter auto\n"+msgstr ""+"Esperado um adaptador, p. ex. --bt-adapter hci1, ou --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -1175,6 +1176,15 @@ msgstr "Parcialmente conectado"msgid "Paired"msgstr "Pareado"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Aguardando a aprovação em {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "A solicitação de pareamento foi recusada."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Pronto"diff --git a/po/ru.po b/po/ru.poindex 77c73bc..b042a73 100644--- a/po/ru.po+++ b/po/ru.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Russian\n"@@ -1177,6 +1177,15 @@ msgstr "Подключено частично"msgid "Paired"msgstr "Сопряжено"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Ожидание подтверждения на {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Запрос на сопряжение отклонён."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Готово"diff --git a/po/sv.po b/po/sv.poindex 65badfc..8c09635 100644--- a/po/sv.po+++ b/po/sv.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Swedish\n"@@ -554,7 +554,8 @@ msgstr "Spegling av aviseringar avaktiverad."#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "Förväntade en adapter, t.ex. --bt-adapter hci1, eller --bt-adapter auto\n"+msgstr ""+"Förväntade en adapter, t.ex. --bt-adapter hci1, eller --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -1160,6 +1161,15 @@ msgstr "Delvis ansluten"msgid "Paired"msgstr "Parkopplad"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Väntar på godkännande på {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Parkopplingsförfrågan avvisades."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Redo"diff --git a/po/tether.pot b/po/tether.potindex 35d909f..fd3df4f 100644--- a/po/tether.pot+++ b/po/tether.pot@@ -6,9 +6,9 @@#, fuzzymsgid ""msgstr ""-"Project-Id-Version: tether 0.2.21\n"+"Project-Id-Version: tether 0.2.22\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n""Last-Translator: FULL NAME <EMAIL@ADDRESS>\n""Language-Team: LANGUAGE <[email protected]>\n"@@ -1056,6 +1056,15 @@ msgstr ""msgid "Paired"msgstr ""+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr ""++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr ""+#: src/gtk/devices_view.cppmsgid "Ready"msgstr ""diff --git a/po/tr.po b/po/tr.poindex aeac8dd..57d0af3 100644--- a/po/tr.po+++ b/po/tr.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Turkish\n"@@ -309,7 +309,8 @@ msgstr "kullanımda"#: src/cli/main.cpp#, c++-formatmsgid "Controller {} is not present; using the first powered one instead."-msgstr "{} bağdaştırıcısı yok; bunun yerine açık olan ilk bağdaştırıcı kullanılıyor."+msgstr ""+"{} bağdaştırıcısı yok; bunun yerine açık olan ilk bağdaştırıcı kullanılıyor."#: src/cli/main.cpp#, c-format@@ -553,7 +554,8 @@ msgstr "Bildirim yansıtma devre dışı bırakıldı."#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "Bir bağdaştırıcı bekleniyordu, ör. --bt-adapter hci1 veya --bt-adapter auto\n"+msgstr ""+"Bir bağdaştırıcı bekleniyordu, ör. --bt-adapter hci1 veya --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -1158,6 +1160,15 @@ msgstr "Kısmen bağlı"msgid "Paired"msgstr "Eşleşti"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "{0} aygıtında onay bekleniyor…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Eşleşme isteği reddedildi."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Hazır"diff --git a/po/uk.po b/po/uk.poindex 908dc56..5136b63 100644--- a/po/uk.po+++ b/po/uk.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Ukrainian\n"@@ -562,7 +562,8 @@ msgstr "Дублювання сповіщень вимкнено."#: src/cli/main.cppmsgid "Expected a controller, e.g. --bt-adapter hci1, or --bt-adapter auto\n"-msgstr "Очікувався адаптер, наприклад --bt-adapter hci1, або --bt-adapter auto\n"+msgstr ""+"Очікувався адаптер, наприклад --bt-adapter hci1, або --bt-adapter auto\n"#: src/cli/main.cpp#, c++-format@@ -1173,6 +1174,15 @@ msgstr "Під'єднано частково"msgid "Paired"msgstr "Спарено"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "Очікування підтвердження на {0}…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "Запит на створення пари відхилено."+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "Готово"diff --git a/po/zh_CN.po b/po/zh_CN.poindex a4367b5..8a690fc 100644--- a/po/zh_CN.po+++ b/po/zh_CN.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: tether\n""Report-Msgid-Bugs-To: [email protected]\n"-"POT-Creation-Date: 2026-09-01 13:57-0700\n"+"POT-Creation-Date: 2026-09-02 10:09-0700\n""PO-Revision-Date: 2026-08-23\n""Last-Translator: Tether project\n""Language-Team: Simplified Chinese\n"@@ -1117,6 +1117,15 @@ msgstr "部分连接"msgid "Paired"msgstr "已配对"+#: src/gtk/devices_view.cpp+#, c++-format+msgid "Waiting for approval on {0}..."+msgstr "正在等待 {0} 上的批准…"++#: src/gtk/devices_view.cpp+msgid "Pair request was rejected."+msgstr "配对请求被拒绝。"+#: src/gtk/devices_view.cppmsgid "Ready"msgstr "就绪"diff --git a/src/cli/main.cpp b/src/cli/main.cppindex 50f89a1..736defe 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -866,14 +866,15 @@ int main(int argc, char* argv[]) {} else if (action == "discover") {debug::log(INFO, "Scanning for tetherd instances on the local network...\n\n");+ tether::Crypto::instance().init();+tether::Discovery discovery;auto hosts = discovery.discover(timeout_ms);- auto devices = tether::group_discovered_hosts(hosts);+ auto devices = tether::group_discovered_hosts(hosts, tether::Crypto::instance().get_my_fingerprint());if (devices.empty()) {debug::log(INFO, _(" No tetherd instances found.\n"));} else {- tether::Crypto::instance().init();for (const auto& dev : devices) {std::string status = _("[new]");if (!dev.fingerprint.empty() && tether::Crypto::instance().is_host_known(dev.fingerprint)) {diff --git a/src/core/include/tether/discovery.hpp b/src/core/include/tether/discovery.hppindex dab7ba9..0500ba4 100644--- a/src/core/include/tether/discovery.hpp+++ b/src/core/include/tether/discovery.hpp@@ -31,7 +31,8 @@ namespace tether {};// Group raw per-interface results into logical devices by fingerprint.- std::vector<DiscoveredDevice> group_discovered_hosts(const std::vector<DiscoveredHost>& hosts);+ std::vector<DiscoveredDevice> group_discovered_hosts(const std::vector<DiscoveredHost>& hosts,+ const std::string& exclude_fingerprint = "");// mDNS service discovery using Avahi.//diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hppindex e62c789..c0e5496 100644--- a/src/core/include/tether/net.hpp+++ b/src/core/include/tether/net.hpp@@ -78,6 +78,9 @@ namespace tether {// Returns true when at least one connected client was promoted.bool accept_device(const std::string& fingerprint, const std::string& fallback_name = "Paired Device");+ // Dial a peer and add the session into this server's client tables+ bool connect_peer(const std::string& host, int port, const std::string& peer_name = "");+private:struct ConnectedClientInfo {std::string address;@@ -88,7 +91,12 @@ namespace tether {void handle_accept(int fd);void handle_client(int client_fd);+ void adopt_peer(int fd, const std::string& host, const std::string& peer_name);void spawn_pair_dialog(int client_fd, SSL* ssl, const std::string& fingerprint, const std::string& device_name);+ // Marks a session trusted and wires it into the broadcast registry.+ void promote_session(int client_fd, const std::string& fingerprint, const std::string& device_name);+ // Frees the SSL session, forgets every per-client table, and closes the fd.+ void drop_client(int fd);EpollEventLoop& loop_;int server_fd_ = -1;@@ -98,6 +106,8 @@ namespace tether {std::map<int, bool> ssl_handshake_complete_;std::map<int, bool> client_paired_;std::map<int, ConnectedClientInfo> client_info_;+ // fds we dialled+ std::map<int, bool> client_initiated_;// Track spawned dialog child processesstruct PendingPairDialog {diff --git a/src/core/src/discovery.cpp b/src/core/src/discovery.cppindex c604bac..30e6a82 100644--- a/src/core/src/discovery.cpp+++ b/src/core/src/discovery.cpp@@ -283,7 +283,7 @@ namespace tether {if (ctx->impl->browse_callback) {cb = ctx->impl->browse_callback;- grouped = group_discovered_hosts(ctx->impl->results);+ grouped = group_discovered_hosts(ctx->impl->results, ctx->impl->pub_fingerprint);}}@@ -329,7 +329,7 @@ namespace tether {if (ctx->impl->browse_callback) {cb = ctx->impl->browse_callback;- grouped = group_discovered_hosts(ctx->impl->results);+ grouped = group_discovered_hosts(ctx->impl->results, ctx->impl->pub_fingerprint);}}if (cb)@@ -629,12 +629,16 @@ namespace tether {// ─── Grouping helper ────────────────────────────────────────────- std::vector<DiscoveredDevice> group_discovered_hosts(const std::vector<DiscoveredHost>& hosts) {+ std::vector<DiscoveredDevice> group_discovered_hosts(const std::vector<DiscoveredHost>& hosts,+ const std::string& exclude_fingerprint) {// Use fingerprint as the grouping key. Maintain insertion order.std::vector<DiscoveredDevice> devices;std::map<std::string, size_t> fp_index; // fingerprint -> index into devicesfor (const auto& h : hosts) {+ if (!exclude_fingerprint.empty() && h.fingerprint == exclude_fingerprint)+ continue;+std::string key = h.fingerprint.empty() ? ("__nokey__" + h.name) : h.fingerprint;auto it = fp_index.find(key);diff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex baca121..7e66ae8 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -1090,39 +1090,15 @@ namespace tether {write_plain_packet(client_fd, response.dump() + "\n");continue;} else if (j.contains("command") && j["command"] == "pair_request" && j.contains("host")) {- std::string target_host = j["host"];- int target_port = j.value("port", 5134);- std::thread([target_host, target_port]() {- Client remote;- if (remote.connect(target_host, target_port)) {- char hostname[256] = {};- gethostname(hostname, sizeof(hostname) - 1);- std::string err;- std::string response = remote.pair(hostname, err);-- if (response.find("\"pair_accepted\"") != std::string::npos) {- std::string print = remote.get_peer_fingerprint();- if (!print.empty()) {- // The remote device accepted! Let's save its fingerprint.- // Since we dialed outbound, we don't necessarily know its mDNS name here- // But GTK can resolve it. For now let's just use the host IP/name.- Crypto::instance().add_known_host(target_host, print);-- nlohmann::json event;- event["command"] = "pair_accepted";- event["fingerprint"] = print;- event["device_name"] = target_host;- event["connected"] = false;- broadcast_local_event(event.dump());- }- }- }- }).detach();+ const std::string target_host = j["host"];+ const int target_port = j.value("port", 5134);+ const std::string peer_name = j.value("device_name", "");+ tcp_server_.connect_peer(target_host, target_port, peer_name);} else if (j.contains("command") && j["command"] == "discover") {std::thread([]() {Discovery discovery;auto hosts = discovery.discover(3000);- auto grouped = group_discovered_hosts(hosts);+ auto grouped = group_discovered_hosts(hosts, Crypto::instance().get_my_fingerprint());nlohmann::json payload;payload["command"] = "discovery_result";@@ -1265,21 +1241,28 @@ namespace tether {client_fds.push_back(fd);}for (int fd : client_fds) {- SSL* ssl = active_ssl_[fd];- if (ssl)- SSL_free(ssl);-- loop_.removeFd(fd);- close(fd);- unregister_client_fd(fd);+ drop_client(fd);+ }+ }- active_ssl_.erase(fd);- client_buffers_.erase(fd);- ssl_handshake_complete_.erase(fd);- client_paired_.erase(fd);- client_info_.erase(fd);- connected_remote_clients.erase(fd);+ void TcpServer::drop_client(int fd) {+ auto ssl_it = active_ssl_.find(fd);+ if (ssl_it != active_ssl_.end()) {+ if (ssl_it->second)+ SSL_free(ssl_it->second);+ active_ssl_.erase(ssl_it);}++ client_buffers_.erase(fd);+ ssl_handshake_complete_.erase(fd);+ client_paired_.erase(fd);+ client_info_.erase(fd);+ client_initiated_.erase(fd);+ connected_remote_clients.erase(fd);++ unregister_client_fd(fd);+ loop_.removeFd(fd);+ close(fd);}// Text form of an accepted peer.@@ -1330,6 +1313,81 @@ namespace tether {loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });}+ bool TcpServer::connect_peer(const std::string& host, int port, const std::string& peer_name) {+ if (host.empty())+ return false;++ for (auto const& [fd, remote] : connected_remote_clients) {+ (void)fd;+ if (remote.address == host) {+ debug::log(INFO, "TcpServer: Already holding a session with {}", host);+ return true;+ }+ }++ // connect() blocks, and the loop watches EPOLLIN only+ std::thread([this, host, port, peer_name]() {+ addrinfo hints{};+ hints.ai_family = AF_UNSPEC;+ hints.ai_socktype = SOCK_STREAM;+ hints.ai_flags = AI_NUMERICSERV;++ addrinfo* results = nullptr;+ const std::string service = std::to_string(port);+ if (int err = getaddrinfo(host.c_str(), service.c_str(), &hints, &results); err != 0 || !results) {+ debug::log(ERR, "TcpServer: Cannot resolve {}: {}", host, gai_strerror(err));+ return;+ }++ int sock = -1;+ for (addrinfo* ai = results; ai; ai = ai->ai_next) {+ sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);+ if (sock < 0)+ continue;+ if (::connect(sock, ai->ai_addr, ai->ai_addrlen) == 0)+ break;+ close(sock);+ sock = -1;+ }+ const int connect_errno = errno;+ freeaddrinfo(results);++ if (sock < 0) {+ debug::log(ERR, "TcpServer: Failed to dial {}:{}: {}", host, port, std::strerror(connect_errno));+ return;+ }++ loop_.post([this, sock, host, peer_name]() { adopt_peer(sock, host, peer_name); });+ }).detach();++ return true;+ }++ void TcpServer::adopt_peer(int fd, const std::string& host, const std::string& peer_name) {+ int flags = fcntl(fd, F_GETFL, 0);+ fcntl(fd, F_SETFL, flags | O_NONBLOCK);++ debug::log(INFO, "TcpServer: Dialled {} (fd: {})", host, fd);++ SSL* ssl = SSL_new(tether::Crypto::instance().get_client_context());+ SSL_set_fd(ssl, fd);+ SSL_set_connect_state(ssl);++ active_ssl_[fd] = ssl;+ ssl_handshake_complete_[fd] = false;+ client_paired_[fd] = false;+ client_initiated_[fd] = true;+ client_info_[fd].address = host;+ client_info_[fd].device_name = peer_name;+ connected_remote_clients[fd].address = host;+ connected_remote_clients[fd].device_name = peer_name;++ loop_.addFd(fd, [this](int cfd) { handle_client(cfd); });++ // Drive the ClientHello out; the peer's reply then arrives as EPOLLIN.+ handle_client(fd);+ }+void TcpServer::handle_client(int client_fd) {SSL* ssl = active_ssl_[client_fd];@@ -1338,30 +1396,29 @@ namespace tether {// handshake attempt so the diagnostics below reflect only this socket's// failure, not stale errors from earlier operations.ERR_clear_error();- int ret = SSL_accept(ssl);+ const bool initiated = client_initiated_[client_fd];+ int ret = initiated ? SSL_connect(ssl) : SSL_accept(ssl);if (ret == 1) {ssl_handshake_complete_[client_fd] = true;std::string print = Crypto::get_peer_fingerprint(ssl);client_info_[client_fd].fingerprint = print;connected_remote_clients[client_fd].fingerprint = print;if (Crypto::instance().is_host_known(print)) {- client_paired_[client_fd] = true;- client_info_[client_fd].paired = true;- connected_remote_clients[client_fd].paired = true;std::string device_name = lookup_known_host_name(print);- if (!device_name.empty()) {- client_info_[client_fd].device_name = device_name;- connected_remote_clients[client_fd].device_name = client_info_[client_fd].device_name;- }- register_client_ssl(client_fd, ssl);-- nlohmann::json event;- event["command"] = "client_connected";- event["address"] = client_info_[client_fd].address;- event["fingerprint"] = print;- event["device_name"] = client_info_[client_fd].device_name;- event["paired"] = true;- broadcast_local_event(event.dump());+ if (device_name.empty())+ device_name = client_info_[client_fd].device_name;+ promote_session(client_fd, print, device_name);+ } else if (initiated) {+ // We dialled, so we are the one asking. The peer prompts its user+ // and answers pair_accepted; we pin nothing until it does.+ char hostname[256] = {};+ gethostname(hostname, sizeof(hostname) - 1);++ nlohmann::json request{{"command", "pair_request"}, {"device_name", hostname}};+ const std::string payload = request.dump() + "\n";+ robust_ssl_write(ssl, payload.c_str(), payload.size());++ debug::log(INFO, "TcpServer: Pair request sent to {} ({})", client_info_[client_fd].address, print);} else {debug::log(INFO, "TcpServer: Untrusted client connected. Fingerprint: {}", print);nlohmann::json event;@@ -1404,16 +1461,7 @@ namespace tether {client_fd,reason);- SSL_free(ssl);- active_ssl_.erase(client_fd);- client_buffers_.erase(client_fd);- ssl_handshake_complete_.erase(client_fd);- client_paired_.erase(client_fd);- client_info_.erase(client_fd);- connected_remote_clients.erase(client_fd);- unregister_client_fd(client_fd);- loop_.removeFd(client_fd);- close(client_fd);+ drop_client(client_fd);return;}}@@ -1428,16 +1476,7 @@ namespace tether {buffer.append(buf, n);if (buffer.size() > MAX_CLIENT_BUFFER_BYTES) {debug::log(ERR, "TcpServer: client {} sent an unframed stream; dropping it", client_fd);- SSL_free(ssl);- active_ssl_.erase(client_fd);- client_buffers_.erase(client_fd);- ssl_handshake_complete_.erase(client_fd);- client_paired_.erase(client_fd);- client_info_.erase(client_fd);- connected_remote_clients.erase(client_fd);- unregister_client_fd(client_fd);- loop_.removeFd(client_fd);- close(client_fd);+ drop_client(client_fd);return;}@@ -1450,6 +1489,54 @@ namespace tether {try {nlohmann::json j = nlohmann::json::parse(msg);+ if (!client_paired_[client_fd] && client_initiated_[client_fd]) {+ // Our own pair_request is outstanding. The peer's user is the+ // approver, so only the peer's verdict pins anything here.+ const std::string command = j.value("command", "");+ const std::string print = Crypto::get_peer_fingerprint(ssl);++ if (command == "pair_accepted") {+ std::string dev_name = client_info_[client_fd].device_name;+ if (dev_name.empty())+ dev_name = client_info_[client_fd].address;++ Crypto::instance().add_known_host(dev_name, print);+ promote_session(client_fd, print, dev_name);++ debug::log(INFO, "[Pairing Accepted] by {} ({})", dev_name, print);++ nlohmann::json event{{"command", "pair_accepted"},+ {"fingerprint", print},+ {"device_name", dev_name},+ {"address", client_info_[client_fd].address},+ {"connected", true}};+ broadcast_local_event(event.dump());+ } else if (command == "pair_pending") {+ const std::string peer = j.value("device_name", client_info_[client_fd].address);+ client_info_[client_fd].device_name = peer;+ connected_remote_clients[client_fd].device_name = peer;++ nlohmann::json event{{"command", "pair_outbound_pending"},+ {"fingerprint", print},+ {"device_name", peer},+ {"address", client_info_[client_fd].address}};+ broadcast_local_event(event.dump());+ } else {+ debug::log(INFO,+ "TcpServer: {} refused the pair request ({})",+ client_info_[client_fd].address,+ command.empty() ? "no command" : command);+ nlohmann::json event{{"command", "pair_rejected"},+ {"fingerprint", print},+ {"device_name", client_info_[client_fd].device_name},+ {"address", client_info_[client_fd].address}};+ broadcast_local_event(event.dump());+ drop_client(client_fd);+ return;+ }+ continue;+ }+if (!client_paired_[client_fd]) {if (j.contains("command") && j["command"] == "pair_request") {std::string print = Crypto::get_peer_fingerprint(ssl);@@ -1571,19 +1658,37 @@ namespace tether {event["paired"] = it->second.paired;broadcast_local_event(event.dump());}- SSL_free(ssl);- active_ssl_.erase(client_fd);- client_buffers_.erase(client_fd);- ssl_handshake_complete_.erase(client_fd);- client_paired_.erase(client_fd);- client_info_.erase(client_fd);- connected_remote_clients.erase(client_fd);- unregister_client_fd(client_fd);- loop_.removeFd(client_fd);- close(client_fd);+ drop_client(client_fd);}}+ void TcpServer::promote_session(int client_fd, const std::string& fingerprint, const std::string& device_name) {+ auto ssl_it = active_ssl_.find(client_fd);+ auto paired_it = client_paired_.find(client_fd);+ auto info_it = client_info_.find(client_fd);+ auto remote_it = connected_remote_clients.find(client_fd);+ if (ssl_it == active_ssl_.end() || paired_it == client_paired_.end() || info_it == client_info_.end() ||+ remote_it == connected_remote_clients.end())+ return;++ paired_it->second = true;+ info_it->second.paired = true;+ info_it->second.device_name = device_name;+ remote_it->second.paired = true;+ remote_it->second.device_name = device_name;+ remote_it->second.fingerprint = fingerprint;++ // Only a trusted session joins the broadcast registry.+ register_client_ssl(client_fd, ssl_it->second);++ nlohmann::json connected_event{{"command", "client_connected"},+ {"fingerprint", fingerprint},+ {"device_name", device_name},+ {"address", remote_it->second.address},+ {"paired", true}};+ broadcast_local_event(connected_event.dump());+ }+bool TcpServer::accept_device(const std::string& fingerprint, const std::string& fallback_name) {if (fingerprint.empty())return false;@@ -1602,32 +1707,22 @@ namespace tether {bool promoted = false;std::string address;- for (auto& [client_fd, remote] : connected_remote_clients) {- if (remote.fingerprint != fingerprint)- continue;+ std::vector<int> matching_fds;+ for (auto const& [client_fd, remote] : connected_remote_clients) {+ if (remote.fingerprint == fingerprint)+ matching_fds.push_back(client_fd);+ }+ for (int client_fd : matching_fds) {auto ssl_it = active_ssl_.find(client_fd);- auto paired_it = client_paired_.find(client_fd);- auto info_it = client_info_.find(client_fd);- if (ssl_it == active_ssl_.end() || paired_it == client_paired_.end() || info_it == client_info_.end())+ if (ssl_it == active_ssl_.end())continue;- paired_it->second = true;- info_it->second.paired = true;- info_it->second.device_name = device_name;- remote.paired = true;- remote.device_name = device_name;- address = remote.address;- register_client_ssl(client_fd, ssl_it->second);+ promote_session(client_fd, fingerprint, device_name);+ address = connected_remote_clients[client_fd].address;promoted = true;- nlohmann::json connected_event{{"command", "client_connected"},- {"fingerprint", fingerprint},- {"device_name", device_name},- {"address", remote.address},- {"paired", true}};- broadcast_local_event(connected_event.dump());-+ // We are the approver here, so the peer is told its request went through.nlohmann::json response{{"command", "pair_accepted"}};const std::string payload = response.dump() + "\n";robust_ssl_write(ssl_it->second, payload.c_str(), payload.size());diff --git a/src/gtk/devices_view.cpp b/src/gtk/devices_view.cppindex 72a2f73..4046233 100644--- a/src/gtk/devices_view.cpp+++ b/src/gtk/devices_view.cpp@@ -394,6 +394,7 @@ namespace tether::ui {j["command"] = "pair_request";j["host"] = g_devices.selected_device_ip;j["port"] = g_devices.selected_device_port;+ j["device_name"] = g_devices.selected_device_name;daemon_send(j);set_status_main(_("Pair request sent. Approve on remote device!"));}@@ -899,6 +900,19 @@ namespace tether::ui {update_wifi_indicator();return true;}+ if (command == "pair_outbound_pending") {+ // TRANSLATORS: {0} is the name of the device being paired with.+ const std::string waiting =+ tether::tr_format(_("Waiting for approval on {0}..."), event.value("device_name", ""));+ set_text(g_devices.lbl_unpaired_ip, waiting);+ set_status_main(waiting);+ return true;+ }+ if (command == "pair_rejected") {+ set_text(g_devices.lbl_unpaired_ip, _("Pair request was rejected."));+ set_status_main(_("Pair request was rejected."));+ return true;+ }if (command == "pair_request_received" || command == "untrusted_client_connected") {tether::DiscoveredDevice req;req.fingerprint = event.value("fingerprint", "");@@ -929,24 +943,14 @@ namespace tether::ui {}if (command == "pair_accepted") {std::string fp = event.value("fingerprint", "");- std::string name = event.value("device_name", "");if (!fp.empty()) {if (event.value("connected", false) &&std::find(g_devices.connected_fps.begin(), g_devices.connected_fps.end(), fp) ==g_devices.connected_fps.end())g_devices.connected_fps.push_back(fp);- // Ensure it's in the paired devices list so the UI transitions- bool already_paired = false;- for (const auto& p : g_devices.paired_devices) {- if (p.first == fp) {- already_paired = true;- break;- }- }- if (!already_paired)- g_devices.paired_devices.push_back({fp, name});-+ // paired_devices is rebuilt from known_hosts.json on every refresh, and+ // the daemon only emits this after writing that file.g_devices.pending_pairing_requests.erase(std::remove_if(g_devices.pending_pairing_requests.begin(),g_devices.pending_pairing_requests.end(),diff --git a/test/test_discovery.cpp b/test/test_discovery.cppindex 3e4405b..f3a831f 100644--- a/test/test_discovery.cpp+++ b/test/test_discovery.cpp@@ -87,6 +87,23 @@ TEST(DiscoveryTest, GroupDiscoveredHosts_MixedFingerprintsAndNames) {ASSERT_EQ(result.size(), 2);}+// A node advertises itself on the same LAN it browses, so without this filter it+// lists itself as a pairable peer.+TEST(DiscoveryTest, GroupDiscoveredHosts_ExcludesOwnFingerprint) {+ std::vector<tether::DiscoveredHost> hosts = {+ {"self", "192.168.1.10", 5134, "mine"},+ {"peer", "192.168.1.20", 5134, "theirs"},+ {"self", "10.0.0.5", 5134, "mine"}+ };++ auto result = tether::group_discovered_hosts(hosts, "mine");+ ASSERT_EQ(result.size(), 1);+ EXPECT_EQ(result[0].fingerprint, "theirs");++ // An empty exclusion keeps every device, so non-daemon callers are unaffected.+ EXPECT_EQ(tether::group_discovered_hosts(hosts, "").size(), 2);+}+// Publishing and continuous browse both watch the same daemon and each walks// the same client states, so the availability report must collapse repeats:// consecutive identical values would flap the UI indicator.diff --git a/test/test_net.cpp b/test/test_net.cppindex 69cdafe..c1f8ac8 100644--- a/test/test_net.cpp+++ b/test/test_net.cpp@@ -5,6 +5,7 @@#include <tether/event_loop.hpp>#include <tether/log.hpp>#include <tether/net.hpp>+#include <nlohmann/json.hpp>#include <arpa/inet.h>#include <cerrno>@@ -327,4 +328,119 @@ namespace {GTEST_SKIP() << "no IPv6 loopback on this host";}+ size_t open_fd_count() {+ size_t count = 0;+ for (const auto& entry : std::filesystem::directory_iterator("/proc/self/fd"))+ (void)entry, ++count;+ return count;+ }++ // A dial that never lands must not strand a socket or a client-table entry;+ // every teardown path funnels through drop_client().+ TEST(TcpServerTest, DialToAClosedPortLeaksNothing) {+ const std::string home = unique_test_dir("tether_dial_fail_test");+ CleanupGuard cleanup_guard(home);+ std::filesystem::remove_all(home);+ std::filesystem::create_directories(home);+ ScopedEnvVar home_env("HOME", home);+ ASSERT_TRUE(tether::Crypto::instance().init());++ constexpr int port = 45137;+ constexpr int dead_port = 45138;+ tether::EpollEventLoop loop;+ tether::TcpServer server(loop, port);+ if (!server.start())+ GTEST_SKIP() << "port " << port << " is unavailable";++ CerrCapture captured;+ std::thread loop_thread([&loop] { loop.run(); });++ const size_t before = open_fd_count();+ EXPECT_TRUE(server.connect_peer("127.0.0.1", dead_port, "ghost"));++ std::string log;+ for (int attempt = 0; attempt < 200; ++attempt) {+ log = captured.str();+ if (log.find("Failed to dial") != std::string::npos)+ break;+ std::this_thread::sleep_for(std::chrono::milliseconds(10));+ }++ loop.post([&loop] { loop.stop(); });+ loop_thread.join();+ captured.restore();++ EXPECT_NE(log.find("Failed to dial"), std::string::npos) << "captured log:\n" << log;+ EXPECT_LE(open_fd_count(), before);+ }++ // The dialling side owns the pair request: it sends one unprompted once TLS is up,+ // which is what makes a desktop-initiated pair reach the peer's approval prompt.+ // The peer here is a bare TLS socket, not a second TcpServer, so nothing forks a+ // real approval dialog onto the machine running the suite.+ TEST(TcpServerTest, DiallingPeerSendsPairRequest) {+ const std::string home = unique_test_dir("tether_dial_pair_test");+ CleanupGuard cleanup_guard(home);+ std::filesystem::remove_all(home);+ std::filesystem::create_directories(home);+ ScopedEnvVar home_env("HOME", home);+ ASSERT_TRUE(tether::Crypto::instance().init());++ const int peer_fd = socket(AF_INET, SOCK_STREAM, 0);+ ASSERT_GE(peer_fd, 0);+ int reuse = 1;+ setsockopt(peer_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));++ sockaddr_in peer_addr{};+ peer_addr.sin_family = AF_INET;+ peer_addr.sin_port = 0; // let the kernel pick+ peer_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ ASSERT_EQ(bind(peer_fd, reinterpret_cast<sockaddr*>(&peer_addr), sizeof(peer_addr)), 0);+ ASSERT_EQ(listen(peer_fd, 1), 0);++ socklen_t addrlen = sizeof(peer_addr);+ ASSERT_EQ(getsockname(peer_fd, reinterpret_cast<sockaddr*>(&peer_addr), &addrlen), 0);+ const int peer_port = ntohs(peer_addr.sin_port);++ std::string received;+ std::thread peer_thread([peer_fd, &received] {+ const int conn = accept(peer_fd, nullptr, nullptr);+ if (conn < 0)+ return;++ SSL* ssl = SSL_new(tether::Crypto::instance().get_server_context());+ SSL_set_fd(ssl, conn);+ if (SSL_accept(ssl) == 1) {+ char buf[4096];+ const int n = SSL_read(ssl, buf, sizeof(buf));+ if (n > 0)+ received.assign(buf, n);+ }+ SSL_free(ssl);+ close(conn);+ });++ constexpr int dialler_port = 45139;+ tether::EpollEventLoop loop;+ tether::TcpServer dialler(loop, dialler_port);+ if (!dialler.start()) {+ close(peer_fd);+ peer_thread.join();+ GTEST_SKIP() << "port " << dialler_port << " is unavailable";+ }++ std::thread loop_thread([&loop] { loop.run(); });+ EXPECT_TRUE(dialler.connect_peer("127.0.0.1", peer_port, "peer"));++ peer_thread.join();+ loop.post([&loop] { loop.stop(); });+ loop_thread.join();+ close(peer_fd);++ ASSERT_FALSE(received.empty()) << "the dialler sent nothing after the handshake";+ const auto parsed = nlohmann::json::parse(received);+ EXPECT_EQ(parsed.value("command", ""), "pair_request");+ EXPECT_FALSE(parsed.value("device_name", "").empty());+ }+} // namespace