Skip to content

Linux + iPhone Continuity / iMessage / SMS

Revert "exp: bluetooth messages and notifications (#7)" (#8)

Zack Bartel00bec891e307
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f0c74f0..2565342 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -127,11 +127,6 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/man/tether.1" "${CMAKE_CURRENT_BINARY
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/man/tetherd.8"
DESTINATION ${CMAKE_INSTALL_MANDIR}/man8)
-# Bluetooth CoD unit. Installed but not enabled: it changes how the machine presents itself over Bluetooth, so turning it on is the user's call.
-set(SYSTEMD_UNIT_DIR "${CMAKE_INSTALL_LIBDIR}/systemd/system" CACHE PATH "systemd system unit directory")
-install(FILES packaging/systemd/[email protected]
- DESTINATION "${SYSTEMD_UNIT_DIR}")
-
# Extension Building only if npm is available
option(TETHER_BUILD_EXTENSIONS "Build browser and mail extensions automatically" ON)
@@ -175,12 +170,12 @@ set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
# DEB
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "[email protected]")
-set(CPACK_DEBIAN_PACKAGE_DEPENDS "libgtk-3-0, libnotify4, openssl, libwayland-client0, libavahi-client3, libglib2.0-0, bluez, bluez-obexd")
+set(CPACK_DEBIAN_PACKAGE_DEPENDS "libgtk-3-0, libnotify4, openssl, libwayland-client0, libavahi-client3")
set(CPACK_DEBIAN_PACKAGE_SECTION "utils")
set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/zackb/tether")
# RPM
-set(CPACK_RPM_PACKAGE_REQUIRES "gtk3, libnotify, openssl, wayland-client, avahi-client, glib2, bluez, bluez-obexd")
+set(CPACK_RPM_PACKAGE_REQUIRES "gtk3, libnotify, openssl, wayland-client, avahi-client")
set(CPACK_RPM_PACKAGE_LICENSE "MIT")
set(CPACK_RPM_PACKAGE_RELOCATABLE FALSE)
diff --git a/PKGBUILD b/PKGBUILD
index f83863c..9f07a92 100644
--- a/PKGBUILD
+++ b/PKGBUILD
@@ -1,11 +1,11 @@
pkgname=tether-git
pkgver=r1.1234
pkgrel=1
-pkgdesc="Bridge an iPhone to the Linux desktop: clipboard, files, messages, and notifications"
+pkgdesc="A Wayland-native local file transfer and clipboard sync tool over mDNS"
arch=('x86_64')
url="https://github.com/zackb/tether"
license=('MIT')
-depends=('gtk3' 'libnotify' 'openssl' 'wayland' 'avahi' 'glib2' 'bluez' 'bluez-utils' 'bluez-obex')
+depends=('gtk3' 'libnotify' 'openssl' 'wayland' 'avahi')
makedepends=('cmake' 'ninja' 'git')
provides=('tether' 'tether-bin')
conflicts=('tether' 'tether-bin')
diff --git a/README.md b/README.md
index 5137379..e5e0a3a 100644
--- a/README.md
+++ b/README.md
@@ -27,8 +27,6 @@
| **iOS App** | ✅ Stable |
| **Browser Extension** | ✅ Stable |
| **Mail Extension** | ✅ Stable |
-| **Messages (SMS/iMessage)** | 🧪 Beta |
-| **Notification Mirroring** | 🧪 Beta Bluetooth |
| **TOTP/OTP Vault** | 🗓️ Planning |
### Clipboard Sync
@@ -37,12 +35,6 @@ Seamlessly share your Wayland compositor (`wlr-data-control`) clipboard over the
### File Transfer
Drag and drop files from Linux directly into the iPhone app, or receive files automatically deposited to your `$XDG_DOWNLOAD_DIR`.
-### Messages and Notifications
-
-Read and reply to SMS and iMessage conversations, and see notifications from any app on the phone, on the Linux desktop.
-
-iOS permits no app to touch messages or other apps' notifications. A Bluetooth accessory can, however, receive messages and notifications from the phone.
-
### Device Pairing
Securely pair devices using **Mutually Authenticated TLS (mTLS)**, restricting TCP traffic securely using X.509 RSA certificates.
@@ -68,7 +60,7 @@ Tether uses a multi-component architecture:
2. **`tether` (CLI)** — A lightweight C++ CLI program to communicate with the daemon. This also allows the WebExtension to interface with the daemon via native messaging.
-3. **`tether-gtk` (GTK App)** — A native GTK3 application for Linux that provides a graphical interface to manage devices, send files, trigger clipboard sync, read and reply to iPhone messages, see mirrored notifications, and monitor connection status.
+3. **`tether-gtk` (GTK App)** — A native GTK4 application for Linux that provides a graphical interface to manage devices, send files, trigger clipboard sync, and monitor connection status.
4. **iPhone App** — Native SwiftUI iOS 16+ app that discovers the daemon via Bonjour/mDNS, utilizing Apple's `Network.framework` for secure TLS negotiation.
@@ -86,16 +78,9 @@ Tether uses a multi-component architecture:
- `openssl`
- `pkg-config`
- `ninja`
-- `gtk3` (for `tether-gtk`)
+- `gtk4` (for `tether-gtk`)
- `nlohmann-json`
- `glib2`
-- `avahi`
-- `bluez`, `bluez-utils`, and `bluez-obex` (for messages and notifications)
-
-### Bluetooth (for Messages and Notifications)
-- BlueZ 5.86+ running with experimental bearer API, for notification mirroring.
-- A controller with BR/EDR, LE, and advertising support.
-- Notification mirroring does not work on iOS 18 and earlier.
### iOS
- iOS 16+
@@ -152,16 +137,12 @@ The daemon uses an advisory lock (`$XDG_RUNTIME_DIR/tether/tetherd.lock`) ensuri
5. **Start syncing** clipboard and transferring files
-6. **For messages and notifications**, (TODO: Bluetooth pairing instructions)
-
## Roadmap
- [x] Complete iOS app development
- [x] Add end-to-end encryption for file transfers
- [x] Release browser extension for Firefox
- [x] Release mail extension for Thunderbird
-- [x] Read and reply to iPhone messages over Bluetooth
-- [x] Mirror iPhone notifications over Bluetooth
- [ ] Implement TOTP/OTP vault with Safari autofill
- [ ] Explore macOS support
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.md
deleted file mode 100644
index 79d98a7..0000000
--- a/docs/BLUETOOTH.md
+++ /dev/null
@@ -1,328 +0,0 @@
-# Bluetooth: iPhone messages and notifications
-
-Tether accesses SMS/iMessage and other apps' notifications via Bluetooth because iOS apps are
-not allowed to access these. It presents the Linux machine to iOS as a paired
-Bluetooth accessory. No iOS-side code is involved.
-
-| Feature | Mechanism | Transport | Linux role |
-|---|---|---|---|
-| SMS / iMessage, read + send | **MAP** (Message Access Profile) via BlueZ `obexd` | BR/EDR | OBEX client |
-| Contacts, for sender names | **PBAP** (Phonebook Access Profile) via `obexd` | BR/EDR | OBEX client |
-| Notifications from any app | **ANCS** (Apple Notification Center Service) | BLE / GATT | GATT central |
-
-The Tether iOS app is unrelated to these features and just keeps handling clipboard sync and file transfer over TCP + mTLS.
-
-## Delivery modes
-
-Not every machine can do all of it, so Tether resolves one of two modes from live capabilities.
-
-- Full mode: MAP + PBAP + ANCS. Requires BR/EDR, LE, and advertising support, plus
- BlueZ >= 5.86 running with its experimental bearer API (org.bluez.Bearer.LE1).
-- Compatibility mode: MAP + PBAP only. Messages and contacts work, notification mirroring does not (older BlueZ).
-
-Run the probe to find out which applies:
-
-```bash
-./scripts/bt-probe.sh # read-only
-./scripts/bt-probe.sh --set-class # also fixes the adapter Class of Device
-```
-
-## Setup requirements
-
-Class of Device must be A/V Hands-Free (major 4, minor 8). iOS only offers the
-"Show Message Notifications" and "Sync Contacts" permissions to a device presenting this
-class. `sudo btmgmt class 4 8` sets it for now.
-
-**It does not survive a `bluetoothd` restart**. bluetoothd rewrites the
-class from its own default every time it starts. Already-granted session survives that, but a phone that has not yet granted the permissions will refuse MAP and PBAP with an OBEX error that seems like a missing service record rather than
-like a permissions problem.
-The packaged unit handles that:
-
-```bash
-sudo systemctl enable --now tether-btclass@hci0
-```
-
-`PartOf=bluetooth.service` re-runs it on every `bluetooth.service` restart. It writes the
-class, reads it back, and retries for ten seconds.
-
-**BlueZ needs the experimental bearer API** for ANCS. On Arch:
-
-```bash
-sudo mkdir -p /etc/systemd/system/bluetooth.service.d
-printf '[Service]\nExecStart=\nExecStart=/usr/lib/bluetooth/bluetoothd --experimental\n' \
- | sudo tee /etc/systemd/system/bluetooth.service.d/experimental.conf
-sudo systemctl daemon-reload && sudo systemctl restart bluetooth
-```
-
-The executable lives at `/usr/libexec/bluetooth/bluetoothd` on Debian based.
-
-**`obexd` must be running** (user service `obex`) for MAP and PBAP. It is socket-activated under normal use.
-
-## Permissions on the phone
-
-After pairing, the iPhone offers "Show Message Notifications" and "Sync Contacts" under
-Settings -> Bluetooth -> (i) for the computer's entry. Off by default.
-
-- The toggles can take minutes to appear after paring, and appear only while the ANCS
- advertisement is actively broadcasting. Failed MAP connection attempts alone do not surface them.
-- Closing and reopening the entry's detail page refreshes what iOS shows.
-- A failed pairing can leave two records for the same computer, the toggles may appear
- under either one. Check both, and delete both before retrying a clean pairing.
-
-Without the relevant permission, MAP or PBAP is visible at the SDP level but rejects the
-OBEX connection with `Forbidden` / `0x43`. That is a permissions state, not a pairing
-failure (do not re-pair). A transport-level `Connection refused (111)` is different and
-usually means another computer already owns the iPhone's single MAP session.
-
-## Conflicts
-
-The iPhone serves one MAP session at a time. Any other program on any machine holding it will block Tether.
-
-## Known limits
-
-These are properties of what iOS exposes:
-
-- MAP reports both SMS and iMessage as `Type: sms-gsm`. The transport a message used is not knowable.
-- The iPhone's MAP sent folder is empty and sending produces no useful outgoing event, so sent history cannot be recovered from the phone. Tether records its own sends.
-- ANCS supports positive/negative notification actions only. There is no free-text reply over ANCS, replies go through MAP.
-- No attachments, reactions, typing indicators, or read receipts.
-- MAP gives no conversation identifier and no participant list for group messages, so group support is a guess and is conservative by default.
-
-## Troubleshooting
-
-Start with the two read-only checks. `./scripts/bt-probe.sh` says what the hardware and the
-stack can do. `tether --bt-connection` says what is actually up right now.
-
-| Symptom | Cause | What to do |
-|---|---|---|
-| Messages and contacts worked, then stopped, and the error mentions a service record | `bluetoothd` restarted and reset the Class of Device | `sudo systemctl enable --now tether-btclass@hci0`, then re-pair if the phone dropped the bond |
-| The phone never offers notifications / Sync Contacts | The class is wrong, or the ANCS advertisement is not running | Check for `class=ok` in `tether --bt-status`, can take minutes |
-| MAP or PBAP reports `forbidden` | The matching toggle on the phone is off | Turn it on. This is not a pairing failure |
-| MAP reports `busy`, or the transport says `Connection refused (111)` | Another computer holds the iPhone's single MAP session | Stop the other client |
-| Pairing fails with `br-connection-key-missing` | A stale bond on one side, or the adapter is not `Pairable` | Delete the computer's entry on the phone (Forget This Device) and `tether --bt-unpair <addr>` locally, then pair again |
-| The phone shows two entries for this computer | A failed pairing left both a Classic and an LE record | Delete both on the phone before retrying |
-| LE never connects and the log repeats `org.bluez.Error.InProgress` | BlueZ is holding a connect operation that never completed | `sudo systemctl restart bluetooth`. Disconnecting the device does not clear it. With `tether-btclass@hci0` enabled the class survives the restart |
-| Everything connects but `ancs_ready` stays false | Compatibility mode, or iOS has not authorized notification content yet | Check `Mode:` in `tether --bt-status`. In full mode the daemon retries, the first request returns `NotPermitted` until the prompt on the phone is approved |
-| A group conversation cannot be replied to | Working as designed until the route is unambiguous | The thread's `reply_reason` says which condition failed |
-
-### Reporting a problem
-
-```bash
-tether --bt-diagnostics
-```
-
-Prints the delivery mode, auth strategy, Bluetooth settings, current connection state, and timeline of recent link and pairing transitions.
-
-It is redacted for pasting into an issue. Bluetooth addresses, phone numbers, email
-addresses, and home and runtime directories become numbered placeholders.
-Messages, contact names, and notification content are dropped, and message and notification events never enter the timeline at all. Read it before
-you post it anyway.
-
-## Recorded results
-
-Per the maintenance rule below, every entry records phone model, iOS version, BlueZ
-version, and controller, and distinguishes what was captured from what was inferred.
-
-### 2026-07-11 — MediaTek MT7925, BlueZ 5.87, iPhone 15 Pro full mode
-
-| | |
-|---|---|
-| Controller | MediaTek MT7925 (RZ717) Wi-Fi 7 |
-| Kernel | 7.1.8-arch1-3 (Arch Linux) |
-| BlueZ | 5.87, running with `-E` |
-| Adapter roles | central + peripheral; 15 advertising instances |
-| Adapter class | `0x7c0408` — A/V Hands-Free |
-| Phone | iPhone 15 Pro, iOS _(version not recorded - fill in)_ |
-
-Captured observations against the bonded phone:
-
-- Dual bond confirmed. `Device1` reports `Paired`, `Bonded`, `Connected`, and `Trusted` all true, and `org.bluez.Bearer.LE1` independently reports `Paired`, `Bonded`, and `Connected` all true. One bond covers BR/EDR and LE.
-- ANCS is live. Service `7905f431-b5ce-4e99-a40f-4b1e122d00d0` is in the GATT tree along with all three characteristics: Notification Source
- `9fbf120d-6301-42d9-8c58-25e699a21dbd`, Control Point
- `69d1d8f3-45e1-49a8-9821-9bbdfdaad9d9`, and Data Source
- `22eac6e9-24d6-4bb5-be44-b36ace7c7bfb`.
-- MAP and PBAP are advertised in the device's profile UUID list: `0x1132` (Message Access Server), `0x1133` (Message Notification Server), and `0x112f` (Phonebook Access Server).
-- Apple Media Service `89d3502b-0f36-433a-8ef4-c502ad55f8dc` is also present.
-
-### 2026-07-13 — MAP/PBAP refused while ANCS worked
-
-Captured with the bond fully connected (`Connected` and `ServicesResolved` true, `Bearer.LE1` connected) and the phone unlocked and attended:
-
-- Opening either OBEX session failed with `org.bluez.obex.Error.Failed: Unable to find service record`.
-- The same call made by hand with `busctl --user call org.bluez.obex ... CreateSession` failed identically, so this is obexd's SDP lookup, not a Tether problem.
-- `bluetoothd` logged the layer underneath:
- `record_cb() Unable to get Hands-Free unit SDP record: Connection refused`
- and `connect to <phone>: Connection refused (111)`. obexd reports a missing
- record whenever its SDP fetch is refused, so "Unable to find service record"
- can be a refusal with a misleading name.
-- A full `Disconnect()` / `Connect()` cycle forced fresh SDP discovery. BlueZ
- still reported `0x1132`, `0x1133`, and `0x112f` afterwards, so those UUIDs were
- not stale, yet obexd still could not fetch the records. BlueZ's device
- discovery and obexd's record fetch can disagree even on fresh data.
-- ANCS worked throughout. The LE/GATT half of the bond is healthy while the BR/EDR profile half is refused, independent.
-
-Resolved on 2026-07-13. The cause was neither candidate listed at the time:
-the adapter's Class of Device had reverted to Computer/Laptop, so iOS
-no longer treated the machine as an eligible accessory and refused the record
-fetch.
-
-Also worth knowing: a `Connect()` that times out leaves an attempt in flight, and
-further attempts fail fast with `br-connection-busy`. Retrying through that state
-prolongs it, which is why the bearer supervisor backs off exponentially
-instead of retrying on a fixed interval.
-
-### 2026-07-16 - Cause of the OBEX refusal
-
-Same hardware as above. The phone was made to forget this computer and its Bluetooth
-stack was reset, which cleared the condition and allowed a clean re-pair through
-Tether's own `bt_pair` for the first time.
-
-Class of Device is the cause of the refused record fetch. `btmgmt class 4 8` does
-not persist across a `bluetoothd` restart! The adapter reverts to Computer/Laptop
-(`0x...010c`). iOS declines to serve MAP and PBAP SDP records and the
-refusal is a `Connection refused (111)` under obexd's misleading "Unable to find
-service record". Restoring the class and re-pairing opened PBAP immediately. This makes
-the CoD a runtime dependency, not a one-time setup step. Anything that restarts
-`bluetoothd` silently breaks messages and contacts until it is set again.
-
-The adapter must be `Pairable` for connect-first to work. Idles with `Pairable: no`.
-Because connect-first deliberately makes the iPhone the authentication initiator, BlueZ then refuses the inbound pairing request: the Linux side
-displays its numeric comparison, iPhone never shows one at all, and fails with `br-connection-key-missing`.
-Tether now turns `Pairable` and `Discoverable` on for the duration of the transaction and restores both afterwards.
-
-A stale record on the phone reproduces `br-connection-key-missing` indefinitely. A
-failed authentication can leave iOS holding a record for the computer while Linux has
-none. The bond must be removed on both sides (Forget This Device and `bluetoothctl remove`) before retrying.
-iOS shows no prompt in this state, which is what distinguishes it from a user-cancelled pairing.
-
-Results of the successful transaction:
-
-- Discovery -> `Device1.Connect()` on the unpaired device -> numeric check on both screens -> `Paired`,
-then the ANCS solicitation.
-- `Device1` and `org.bluez.Bearer.LE1` both report `Paired` and `Bonded`, and
- `BREDR.Connected` and `LE.Connected` are both true. Connect-first produced the
- cross-transport bond on this controller, upgrading the previous line's inference to a capture.
-- PBAP opened on the first attempt. MAP reported `Forbidden`, which is a permission
- rather than the transport refusal above, and exactly the distinction `classify_obex_error()` exists to make.
- Granting "Show Message Notifications" cleared it within one poll, with no re-pair and no session restart.
-- Messages then listed from `telecom/msg/inbox` and threaded correctly.
-
-Obexd API details, both on BlueZ 5.87 and neither matching what the D-Bus documentation says (shocker):
-
-- `ListMessages` returns `(a{oa{sv}})`: dict keyed by message object path,
- not the `(a(oa{sv}))` array of structs that the API reference says. GDBus rejects the reply on type mismatch(!!?!)
-- `MessageAccess1.SetFolder` walks from the session root. `"inbox"`
- alone fails with `Internal Server Error`. `"telecom/msg/inbox"` succeeds, as does
- `"/telecom/msg/inbox"` and a `"telecom"` step. `ListMessages` takes a folder arg relative to the current folder, so an empty string lists the folder
- `SetFolder` already selected.
-
-Message listing fields as actually delivered: `Subject` (body),
-`Timestamp` (ISO-8601) local time with no zone suffix (`20254816T509517`),
-`Sender`, `SenderAddress`, `Recipient`, `RecipientAddress`, `Type` (`sms-gsm` for both SMS and iMessage),
-`Read`, `Sent`, `Folder`, `Size`, and `ConversationId`.
-`ConversationId` present but zero on every message, confirming IT CANNOT BE a thread identifier(?!?).
-
-`SenderAddress` is in whatever form the phone has (both bare national number (`5129328901`) and (`+15129328901`) in the same inbox (!?!).
-Tether does not invent a country code, so the same person can appear as two threads if their number is in the phone both ways.
-
-A message's D-Bus object path is not a stable identifier. obexd names messages
-`/org/bluez/obex/client/session<N>/message<id>`, and `<N>` is the OBEX session number,
-which increments on every reconnect. Same message observed as `session9/message…` and `session11/message…` across a restart.
-Only the trailing `<id>` is stable, so it is what Tether dedupes and persists on.
-The full path is kept separately and refreshed on each re-listing, because it is what `Message1` calls must
-address. Keying history on the path instead duplicates the entire mailbox on every reconnect.
-
-### Sending
-
-`MessageAccess1.PushMessage(sourcefile, folder, args)` takes a file, so the
-bMessage is staged in `$XDG_RUNTIME_DIR` mode 0600 and removed afterwards (`Charset` must be `utf8`,
-let obexd transcode to the native charset mangles anything outside the phone's default encoding.)
-
-Success means the phone accepted the message, not that it delivered it. MAP reports
-nothing back about delivery. Tether records its own sends locally, and that record is the
-only evidence they happened. A push that times out is reported.
-
-`TYPE` is always `SMS_GSM`, including for AppleID recipients: iOS decides between SMS
-and iMessage on its own, and nothing on the Linux side can force or check that choice.
-
-### ANCS
-
-On the same hardware: after the LE bearer connects, BlueZ enumerates the ANCS
-service and all three characteristics: Notification Source, Control Point and Data Source, under the device object, and `StartNotify` succeeds on both notifying
-characteristics.
-
-The permission is in Settings -> Bluetooth -> (i) -> Share System Notifications, and it is separate from the Message Notifications toggle that MAP needs.
-
-Control Point responses have no request identifier, so only one request may be out at a time. And Data Source
-responses carry no total length (?!?) and come back fragmented, so the only way to know
-response has ended is to know exactly which attributes were requested. Those two facts
-are why the sequencer exists.
-
-### Group messages
-
-Off by default, `group_messages_enabled` and
-`ancs_content_enabled` in `~/.config/tether/bluetooth.json`, so group support cannot work without content mirroring.
-
-MAP delivers a group message with one sender, no participant list and no conversation
-identifier. The only other hint is to correlate Apple Messages ANCS notification:
-its title is the sender, and its subtitle is either `To you & ...` for an unnamed group or
-the group's name. Neither form contains a member list...
-
-- Correlation is bounded to a 30-second window, and two notifications with the same
- text are refused instead of guessing, the wrong choice would put a message in the wrong conversation and send a reply at the wrong people.
-- An unnamed group is repliable only when **every** participant name resolves to exactly one contact address. A name matching several contacts is refused.
-- A named group stays read-only until we figure out the member list in `~/.config/tether/groups.json`.
- That list affects Tether's reply routing only and never modifies the group on the phone.
-- iOS reports nothing when a member is added or removed, so an unknown sender is the only available signal that a member list has gone stale.
-- Because iOS supplies a name but no conversation identifier, distinct named groups
- sharing a name collapse into one local thread. There is no way to tell them apart.
-
-Repeated recipient vCards were observed to enter an existing iMessage group when the
-recipient set matched, rather than fanning out into separate one-to-one threads. That is
-an observation, not a guarantee.
-
-### 2026-07-16: a reverted Class of Device does not revoke a granted session
-
-Same hardware. `systemctl restart bluetooth` reverted the class from
-`0x7c0408` to `0x7c010c` (Computer / Laptop), exactly as expected. MAP, PBAP, and ANCS
-then reconnected and stayed up, with `tether --bt-status` reporting `class=wrong`
-throughout.
-
-So the class governs whether iOS offers and grants the Messages and Contacts permissions,
-not whether it keeps honoring permissions it has already granted. The earlier refusal
-recorded above happened while those grants were being established. Setting the class is
-still required, just not continuously, which is why the breakage is delayed
-and looks unrelated to the restart that caused it.
-
-### 2026-07-16: LE bearer stuck on `InProgress`
-
-Same hardware. After the daemon stopped and restarted twice within about twenty seconds while an LE bearer
-connect was outstanding, every subsequent `Bearer.LE1.Connect` returned
-`org.bluez.Error.InProgress` indefinitely. BR/EDR, MAP, and PBAP were unaffected and stayed up throughout, only ANCS was lost.
-
-`bluetoothctl disconnect` on the device did not clear it, so the stuck state lives above
-the ACL. `systemctl restart bluetooth` did clear it: LE connected and ANCS reported
-`Notification mirroring is active` on the first attempt afterwards, with no other change.
-
-The supervisor previously did its retry backoff on this error the same way it does on a
-refusal. It now retries `InProgress` at the base interval and reserves the exponential growth for refusals,
-which is what the phone actually sends when it declines. That does not fix the stuck state, but it stops the daemon from
-sleeping through the recovery.
-
-### PBAP
-
-`Select("int", "pb")` followed by `PullAll` with `Format: vcard30` and `MaxCount` returned 456 contacts on the first attempt.
-
-The transfer object disappears from D-Bus the moment it finishes, so a vanished object
-is a normal terminal state rather than a failure (file may still take a bit to appear afterwards),
-which is why the pull waits instead of giving up. Contacts are staged in `$XDG_RUNTIME_DIR` rather than `/tmp`, since a
-phonebook is personal data, and the cache and journal are both written mode 0600.
-
-***THIS HAS TO CHANGE BEFORE PUBLIC RELEASE.***
-
-## Credits
-
-[BlueFerry](https://github.com/erikwb/blueferry) (Erik Bourget and contributors), `PROTOCOL.md` records the findings this implementation relies on.
-Tether's Bluetooth support is an independent implementation written against those published
-findings, Apple's ANCS specification, the Bluetooth SIG MAP and PBAP specifications, and
-the BlueZ D-Bus API.
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 33c9942..28b4851 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -212,150 +212,3 @@ Tether uses the local UNIX socket to coordinate OTP syncing between mail clients
"otp": "123456"
}
```
-
----
-
-## 6. Bluetooth: iPhone Messages and Notifications
-
-These commands ride the same UNIX socket and the same newline-delimited JSON. They are
-local-only: nothing here is reachable over TCP, because everything here is personal data.
-
-Two transports sit behind them, and they fail independently: MAP and PBAP are OBEX
-sessions over BR/EDR, while ANCS is a GATT client over BLE. See [BLUETOOTH.md](BLUETOOTH.md) for how they are set up.
-
-Some commands answer on the requesting socket, and some broadcast to every local
-subscriber. Anything a second client would want to see is broadcast.
-
-### Adapter and pairing
-
-#### `bt_status` (Client -> Daemon, answered directly)
-Reports adapter capability and the resolved delivery mode.
-**Payload**: `{"command": "bt_status"}`
-**Response**: `available`, `capability` (`mode` is `full` or `compatibility`, plus
-`bearer_api`, `powered`, `le_central`, `le_peripheral`, `advertising`, `class_ok`, and a
-`reasons` array naming anything missing), and an `adapters` array.
-
-#### `bt_list_devices` (Client -> Daemon, answered directly)
-**Payload**: `{"command": "bt_list_devices"}`
-**Response**: `{"command": "bt_devices", "devices": [...]}`, each entry carrying address,
-name, `paired`, `bonded`, `connected`, `le_bearer`, and whether the device advertises
-`map`, `pbap`, and `ancs`.
-
-#### `bt_pair` / `bt_unpair` (Client -> Daemon, broadcast)
-**Payload**: `{"command": "bt_pair", "address": "AA:BB:CC:DD:EE:FF"}`
-Runs asynchronously and reports through `bt_pair_progress` events, then one
-`bt_pair_result` (or `bt_unpair_result`). Only one pairing transaction runs at a time; a
-second returns `{"status": "busy"}`. A successful pair selects the device and starts
-supervision.
-
-#### `bt_set_device` (Client -> Daemon)
-**Payload**: `{"command": "bt_set_device", "address": "AA:BB:CC:DD:EE:FF"}`
-Points supervision at an already-bonded phone.
-
-#### `bt_pair_progress` / `bt_pair_result` (Daemon -> Clients)
-`bt_pair_progress` carries `step` and `detail` for display during the transaction.
-`bt_pair_result` carries `success`, `status`, `message`, and `dual_bond` — the last being
-whether the bond covers LE as well as BR/EDR, which is what decides if ANCS is reachable.
-
-### Connection state
-
-#### `bt_connection` (Client -> Daemon, answered directly)
-**Payload**: `{"command": "bt_connection"}`
-Returns the same object the daemon broadcasts as `bt_connection_changed`.
-
-#### `bt_connection_changed` (Daemon -> Clients)
-Broadcast when the published state actually changes, not on a timer.
-
-```json
-{
- "command": "bt_connection_changed",
- "device_present": true,
- "device_paired": true,
- "classic_connected": true,
- "le_available": true,
- "le_connected": false,
- "map_open": true,
- "pbap_open": true,
- "map_error": "none",
- "pbap_error": "none",
- "ancs_ready": false,
- "link_reason": "Connected. Bringing up the LE link for notifications...",
- "profile_reason": "Messages and contacts are connected."
-}
-```
-
-The two `*_reason` strings are written for display (permission is off or a transport that is busy).
-`map_error` and `pbap_error` name the classification: `forbidden` means the toggle on the phone is off,
-`busy` means another computer holds the phone's single MAP session.
-
-### Messages
-
-#### `bt_list_threads` (Client -> Daemon, answered directly)
-**Payload**: `{"command": "bt_list_threads"}`
-**Response**: `{"command": "bt_threads", "threads": [...]}`. Each thread carries `thread`
-(the key), `name`, `address`, `preview`, `timestamp`, `unread`, `count`, `group`, and
-`repliable`. Group threads add `reply_status` and, when they cannot be replied to, a
-`reply_reason` written for display.
-
-Thread keys are derived from the normalized peer address — `tel:+15035550101` for a phone
-number, the lowercased address for an Apple ID — because MAP provides no conversation
-identifier. Group keys are `group:name:<slug>` or `group:members:<slugs>`.
-
-#### `bt_list_messages` (Client -> Daemon, answered directly)
-**Payload**: `{"command": "bt_list_messages", "thread": "tel:+15035550101"}`
-**Response**: `{"command": "bt_messages", "thread": ..., "messages": [...]}` with `handle`,
-`body`, `timestamp`, `outgoing`, `read`, and `folder` per message.
-
-#### `bt_mark_read` (Client -> Daemon, broadcast)
-**Payload**: `{"command": "bt_mark_read", "handle": "...", "read": true}`
-Writes through to the phone over OBEX, so it answers asynchronously with a
-`bt_message_read` event carrying `success` and, on failure, `message`.
-
-#### `bt_send_message` (Client -> Daemon, broadcast)
-**Payload**: `{"command": "bt_send_message", "thread": "tel:+15035550101", "body": "on my way"}`
-Builds a bMessage and pushes it to the phone's outbox. Answers asynchronously with
-`bt_send_result` (`success`, and `message` when it failed).
-
-Recipients are validated before they are interpolated into the bMessage: an address
-containing CR, LF, or a vCard delimiter is rejected rather than escaped, because such an
-address could otherwise add a recipient and deliver the message to someone else. Body lines
-beginning with a bMessage structural token are byte-stuffed.
-
-A successful send also broadcasts a `bt_message` event. That is the only record the send
-happened — the iPhone's MAP sent folder stays empty and no outgoing notification arrives.
-
-#### `bt_message` (Daemon -> Clients)
-Broadcast once per newly observed message, incoming or locally sent.
-
-### Notifications
-
-#### `bt_list_notifications` (Client -> Daemon, answered directly)
-**Payload**: `{"command": "bt_list_notifications"}`
-**Response**: `{"command": "bt_notifications", "notifications": [...]}` with `uid`,
-`app_id`, `app_name`, `title`, `subtitle`, `body`, `category`, `timestamp`, and which
-actions the notification offers.
-
-Bodies are present only when notification content mirroring is enabled; by default the
-daemon requests the owning app and nothing more. Messages notifications
-(`com.apple.MobileSMS`) are retained but never raise a desktop popup, since MAP already
-delivers those with working read state.
-
-#### `bt_notification_action` (Client -> Daemon, broadcast)
-**Payload**: `{"command": "bt_notification_action", "uid": 42, "action": "positive"}`
-ANCS offers positive and negative actions only — there is no free-text reply on a mirrored
-notification. Answers with `bt_notification_action_result`.
-
-### Diagnostics
-
-#### `bt_diagnostics` (Client -> Daemon, answered directly)
-**Payload**: `{"command": "bt_diagnostics"}`
-Returns a report intended to be pasted into a bug report: version, auth strategy, the
-Bluetooth settings in effect, the current capability and connection state, and an ordered
-timeline of recent link and pairing transitions stamped in milliseconds.
-
-The daemon redacts before answering. Bluetooth addresses, phone numbers, email addresses,
-and home and runtime directories become numbered placeholders — `<address-1>` recurs for
-one device, so a reader can still follow which device a line refers to without learning
-which device it is. Message bodies, contact names, and notification content are dropped
-outright rather than redacted, and message and notification events never enter the timeline
-in the first place.
diff --git a/packaging/systemd/[email protected] b/packaging/systemd/[email protected]
deleted file mode 100644
index f8cd204..0000000
--- a/packaging/systemd/[email protected]
+++ /dev/null
@@ -1,22 +0,0 @@
-[Unit]
-# set Class of Device A/V Hands-Free (major 4, minor 8).
-# bluetoothd resets the class to its own default every time it
-# starts, and when it does, MAP and PBAP stop working with an OBEX error.
-#
-# %i is the adapter, e.g. [email protected].
-Description=Set Bluetooth Class of Device to A/V Hands-Free on %i for Tether
-Documentation=https://github.com/zackb/tether/blob/main/docs/BLUETOOTH.md
-After=bluetooth.service
-PartOf=bluetooth.service
-
-[Service]
-Type=oneshot
-RemainAfterExit=yes
-ExecStart=/bin/sh -c 'for i in 1 2 3 4 5 6 7 8 9 10; do \
- btmgmt --index %i class 4 8 >/dev/null 2>&1; \
- btmgmt --index %i info 2>/dev/null | grep -q "class 0x..0408" && exit 0; \
- sleep 1; \
-done; exit 1'
-
-[Install]
-WantedBy=bluetooth.service
diff --git a/scripts/bt-probe.sh b/scripts/bt-probe.sh
deleted file mode 100755
index d192e26..0000000
--- a/scripts/bt-probe.sh
+++ /dev/null
@@ -1,185 +0,0 @@
-#!/usr/bin/env bash
-# Report whether this machine can carry Tether's iPhone Bluetooth features.
-#
-# Full mode = MAP + PBAP (messages, contacts) + ANCS (notifications)
-# Compatibility = MAP + PBAP only; no notification mirroring
-#
-# Read-only unless --set-class is given.
-
-set -uo pipefail
-
-ADAPTER=${ADAPTER:-hci0}
-ADAPTER_PATH="/org/bluez/$ADAPTER"
-
-# A/V Hands-Free. iOS only offers the Messages/Contacts permission toggles to a
-# device presenting this class. BlueZ ORs service bits on top, so only the low
-# 13 bits (format + major + minor) are comparable.
-TARGET_COD_LOW=0x0408
-COD_MASK=0x1fff
-
-set_class=0
-[[ ${1:-} == --set-class ]] && set_class=1
-
-red=$'\e[31m'; grn=$'\e[32m'; ylw=$'\e[33m'; dim=$'\e[2m'; rst=$'\e[0m'
-[[ -t 1 ]] || { red=; grn=; ylw=; dim=; rst=; }
-
-blockers=0 # hardware/stack cannot do the job at all
-degraded=0 # capable of MAP/PBAP but not ANCS
-conflicts=0 # capable, but something else is in the way right now
-
-ok() { printf ' %s✓%s %s\n' "$grn" "$rst" "$1"; }
-warn() { printf ' %s!%s %s\n' "$ylw" "$rst" "$1"; degraded=$((degraded + 1)); }
-clash() { printf ' %s!%s %s\n' "$ylw" "$rst" "$1"; conflicts=$((conflicts + 1)); }
-bad() { printf ' %s✗%s %s\n' "$red" "$rst" "$1"; blockers=$((blockers + 1)); }
-note() { printf ' %s%s%s\n' "$dim" "$1" "$rst"; }
-
-prop() {
- busctl --system get-property org.bluez "$ADAPTER_PATH" "$1" "$2" 2>/dev/null |
- awk '{ $1=""; sub(/^ /,""); gsub(/"/,""); print }'
-}
-
-echo
-echo "Tether Bluetooth capability probe"
-echo "================================="
-
-# --- tools ---------------------------------------------------------------
-echo
-echo "Tooling"
-for t in busctl btmgmt bluetoothctl; do
- if command -v "$t" >/dev/null; then ok "$t"; else bad "$t not found"; fi
-done
-command -v btmon >/dev/null || note "btmon not installed; useful for debugging pairing"
-
-# --- bluez ---------------------------------------------------------------
-echo
-echo "BlueZ"
-bluez_ver=$(bluetoothctl --version 2>/dev/null | awk '{print $2}')
-if [[ -z $bluez_ver ]]; then
- bad "could not determine BlueZ version"
-elif [[ $(printf '%s\n5.86\n' "$bluez_ver" | sort -V | head -1) == "5.86" ]]; then
- ok "version $bluez_ver (>= 5.86)"
-else
- warn "version $bluez_ver is older than 5.86 — ANCS unavailable"
- note "MAP and PBAP still work; notification mirroring does not"
-fi
-
-# org.bluez.Bearer.LE1 appears only on bonded devices, and only when bluetoothd
-# runs with --experimental (short form -E). A live interface on an existing bond
-# is ground truth; the daemon command line is the fallback before anything is
-# paired. Do not test for the long form alone, Arch's packaging uses -E.
-bearer_seen=$(busctl --system call org.bluez / org.freedesktop.DBus.ObjectManager \
- GetManagedObjects 2>/dev/null | grep -c 'org\.bluez\.Bearer\.LE1')
-if (( bearer_seen > 0 )); then
- ok "Bearer.LE1 present on a bonded device (Bearer API confirmed live)"
-elif pgrep -af 'bluetoothd' | grep -qE -- '(^|[[:space:]])(-E|--experimental)([[:space:]]|$)'; then
- ok "bluetoothd running with --experimental (Bearer API available)"
-else
- warn "bluetoothd is NOT running with --experimental — Bearer.LE1 unavailable"
- note "ANCS needs it to drive the LE half of the bond. To enable:"
- note " sudo mkdir -p /etc/systemd/system/bluetooth.service.d"
- note " printf '[Service]\\nExecStart=\\nExecStart=/usr/lib/bluetooth/bluetoothd --experimental\\n' \\"
- note " | sudo tee /etc/systemd/system/bluetooth.service.d/experimental.conf"
- note " sudo systemctl daemon-reload && sudo systemctl restart bluetooth"
-fi
-
-# --- adapter -------------------------------------------------------------
-echo
-echo "Adapter ($ADAPTER)"
-if ! busctl --system introspect org.bluez "$ADAPTER_PATH" >/dev/null 2>&1; then
- bad "adapter $ADAPTER not present on the system bus"
- echo
- echo "Set ADAPTER=hciN to probe a different adapter."
- exit 1
-fi
-
-addr=$(prop org.bluez.Adapter1 Address)
-name=$(prop org.bluez.Adapter1 Alias)
-ok "$addr ($name)"
-
-[[ $(prop org.bluez.Adapter1 Powered) == true ]] && ok "powered on" || bad "powered off (bluetoothctl power on)"
-
-roles=$(prop org.bluez.Adapter1 Roles)
-# BR/EDR is implied by a working Adapter1; LE requires both GATT roles. Peripheral
-# is what lets us broadcast the post-bond ANCS solicitation advert that makes iOS
-# surface its permission toggles.
-[[ $roles == *central* ]] && ok "LE central role" || bad "no LE central role — ANCS impossible"
-[[ $roles == *peripheral* ]] && ok "LE peripheral role" || warn "no LE peripheral role — cannot solicit ANCS"
-
-instances=$(prop org.bluez.LEAdvertisingManager1 SupportedInstances)
-if [[ -n ${instances:-} && $instances -gt 0 ]]; then
- ok "advertising supported ($instances instances)"
-else
- warn "no advertising instances — iOS may never show the permission toggles"
-fi
-
-# --- class of device -----------------------------------------------------
-echo
-echo "Class of Device"
-cod=$(prop org.bluez.Adapter1 Class)
-if [[ -z ${cod:-} ]]; then
- warn "could not read adapter class"
-else
- printf -v cod_hex '0x%06x' "$cod"
- low=$(( cod & COD_MASK ))
- if (( low == TARGET_COD_LOW )); then
- ok "$cod_hex — A/V Hands-Free (major 4, minor 8)"
- else
- major=$(( (cod >> 8) & 0x1f ))
- warn "$cod_hex — major $major, expected A/V Hands-Free (major 4, minor 8)"
- note "iOS will not treat this machine as an eligible accessory."
- if (( set_class )); then
- echo
- note "running: btmgmt class 4 8"
- if sudo btmgmt --index "${ADAPTER#hci}" class 4 8; then
- note "class set; re-run this probe to confirm"
- note "Make it stick: sudo systemctl enable --now tether-btclass@$ADAPTER"
- else
- note "failed — run 'sudo btmgmt class 4 8' by hand"
- fi
- else
- note "Fix with: $0 --set-class (or: sudo btmgmt class 4 8)"
- note "That lasts until bluetoothd restarts. To make it stick:"
- note " sudo systemctl enable --now tether-btclass@$ADAPTER"
- fi
- fi
-fi
-
-# --- conflicts -----------------------------------------------------------
-# The iPhone serves exactly one MAP session at a time. Any other local process
-# holding it makes Tether's MAP connect fail with "Connection refused (111)",
-# which looks nothing like a permissions problem and wastes a lot of debugging.
-echo
-echo "Conflicts"
-if systemctl --user is-active --quiet blueferry.service 2>/dev/null; then
- clash "blueferry.service is running and will hold the iPhone's MAP session"
- note "Stop it while testing Tether: systemctl --user stop blueferry.service"
-else
- ok "no other known MAP consumer running"
-fi
-
-if systemctl --user is-active --quiet obex.service 2>/dev/null; then
- ok "obexd active (required for MAP and PBAP)"
-else
- warn "obexd is not active — MAP and PBAP will not connect"
- note "It is socket-activated; 'systemctl --user start obex' forces it up."
-fi
-
-# --- verdict -------------------------------------------------------------
-echo
-echo "Verdict"
-if (( blockers > 0 )); then
- printf ' %sBLOCKED%s — %d hard problem(s) above must be resolved first.\n' "$red" "$rst" "$blockers"
- exit 1
-fi
-
-if (( degraded > 0 )); then
- printf ' %sCOMPATIBILITY MODE%s — messages and contacts (MAP/PBAP) should work;\n' "$ylw" "$rst"
- printf ' notification mirroring (ANCS) will not, until the %d capability gap(s) above are fixed.\n' "$degraded"
-else
- printf ' %sFULL MODE%s — this machine can carry MAP, PBAP, and ANCS.\n' "$grn" "$rst"
-fi
-
-if (( conflicts > 0 )); then
- printf ' %s%d conflict(s)%s must be cleared before Tether can connect right now.\n' "$ylw" "$conflicts" "$rst"
-fi
-exit 0
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index 166c4b4..fc4d7a7 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -1,8 +1,6 @@
#include <atomic>
#include <csignal>
-#include <ctime>
#include <iostream>
-#include <nlohmann/json.hpp>
#include <string>
#include <tether/client.hpp>
#include <tether/crypto.hpp>
@@ -106,15 +104,6 @@ void print_help() {
<< " --port <num> Connect over TCP port (default 5134).\n"
<< " --timeout <ms> Discovery scan duration in milliseconds (default 3000).\n"
<< " --list-devices List all paired connection devices.\n"
- << " --bt-status Show Bluetooth adapter capability and delivery mode.\n"
- << " --bt-devices List Bluetooth devices known to BlueZ.\n"
- << " --bt-connection Show Bluetooth link and profile connection state.\n"
- << " --bt-threads List iPhone message conversations.\n"
- << " --bt-messages <thread> Show messages in one conversation.\n"
- << " --bt-send <thread> <text> Reply in one conversation.\n"
- << " --bt-pair <addr> Pair with an iPhone over Bluetooth.\n"
- << " --bt-unpair <addr> Remove a Bluetooth bond.\n"
- << " --bt-diagnostics Print a redacted Bluetooth report for a bug report.\n"
<< " --accept <fingerprint> Accept a pending pairing request locally.\n"
<< " --pair Send a pair_request over TCP to the daemon.\n\n"
<< "Examples:\n"
@@ -127,321 +116,13 @@ void print_help() {
<< " tether --accept 9a4f21...\n";
}
-static int print_bt_status(tether::Client& client) {
- nlohmann::json resp;
- try {
- resp = nlohmann::json::parse(client.send_and_wait("{\"command\":\"bt_status\"}\n"));
- } catch (const std::exception&) {
- debug::log(ERR, "Could not read Bluetooth status from the daemon.\n");
- return 1;
- }
-
- if (!resp.value("available", false)) {
- fprintf(stdout, "Bluetooth: unavailable (is bluetoothd running?)\n");
- return 1;
- }
-
- const auto& cap = resp["capability"];
- fprintf(stdout, "Mode: %s\n", cap.value("mode", "unknown").c_str());
- fprintf(stdout, "Bearer API: %s\n", cap.value("bearer_api", "unknown").c_str());
- fprintf(stdout,
- "Adapter: powered=%s central=%s peripheral=%s advertising=%s class=%s\n",
- cap.value("powered", false) ? "yes" : "no",
- cap.value("le_central", false) ? "yes" : "no",
- cap.value("le_peripheral", false) ? "yes" : "no",
- cap.value("advertising", false) ? "yes" : "no",
- cap.value("class_ok", false) ? "ok" : "wrong");
-
- for (const auto& adapter : resp["adapters"]) {
- fprintf(stdout, " %s %s\n", adapter.value("address", "").c_str(), adapter.value("name", "").c_str());
- }
-
- if (cap.contains("reasons") && !cap["reasons"].empty()) {
- fprintf(stdout, "\n");
- for (const auto& reason : cap["reasons"])
- fprintf(stdout, " - %s\n", reason.get<std::string>().c_str());
- }
- return 0;
-}
-
-static int print_bt_devices(tether::Client& client) {
- nlohmann::json resp;
- try {
- resp = nlohmann::json::parse(client.send_and_wait("{\"command\":\"bt_list_devices\"}\n"));
- } catch (const std::exception&) {
- debug::log(ERR, "Could not read Bluetooth devices from the daemon.\n");
- return 1;
- }
-
- const auto& devices = resp["devices"];
- if (devices.empty()) {
- fprintf(stdout, "No Bluetooth devices known to BlueZ.\n");
- return 0;
- }
-
- for (const auto& d : devices) {
- std::string flags;
- auto add = [&flags](const char* name) {
- if (!flags.empty())
- flags += ",";
- flags += name;
- };
- if (d.value("bonded", false))
- add("bonded");
- if (d.value("connected", false))
- add("connected");
- if (d.value("le_connected", false))
- add("le");
- if (d.value("map", false))
- add("map");
- if (d.value("pbap", false))
- add("pbap");
- if (d.value("ancs", false))
- add("ancs");
-
- fprintf(stdout,
- " %-18s %-24s %s%s\n",
- d.value("address", "").c_str(),
- d.value("name", "").c_str(),
- flags.c_str(),
- d.value("iphone", false) ? " <- iPhone" : "");
- }
- return 0;
-}
-
-// Pairing takes tens of seconds and reports progress as it goes, so this
-// subscribes and streams events until the terminal result arrives.
-static int run_bt_transaction(tether::Client& client, const std::string& command, const std::string& address) {
- const std::string result_command = command == "bt_pair" ? "bt_pair_result" : "bt_unpair_result";
-
- client.send("{\"command\":\"subscribe\"}\n");
- nlohmann::json request;
- request["command"] = command;
- request["address"] = address;
- if (!client.send(request.dump() + "\n")) {
- debug::log(ERR, "Could not reach the daemon.\n");
- return 1;
- }
-
- std::string buffer;
- char buf[8192];
- while (true) {
- ssize_t n = client.read(buf, sizeof(buf));
- if (n <= 0) {
- debug::log(ERR, "Daemon closed the connection before the operation finished.\n");
- return 1;
- }
- buffer.append(buf, n);
-
- size_t pos;
- while ((pos = buffer.find('\n')) != std::string::npos) {
- std::string line = buffer.substr(0, pos);
- buffer.erase(0, pos + 1);
- if (line.empty())
- continue;
-
- nlohmann::json event;
- try {
- event = nlohmann::json::parse(line);
- } catch (const std::exception&) {
- continue;
- }
-
- const std::string cmd = event.value("command", "");
- if (cmd == "bt_pair_progress") {
- fprintf(stdout, " %-12s %s\n", event.value("step", "").c_str(), event.value("detail", "").c_str());
- fflush(stdout);
- } else if (cmd == result_command) {
- fprintf(stdout, "\n%s\n", event.value("message", "").c_str());
- return event.value("success", false) ? 0 : 1;
- }
- }
- }
-}
-
-static int print_bt_connection(tether::Client& client) {
- nlohmann::json resp;
- try {
- resp = nlohmann::json::parse(client.send_and_wait("{\"command\":\"bt_connection\"}\n"));
- } catch (const std::exception&) {
- debug::log(ERR, "Could not read Bluetooth connection state from the daemon.\n");
- return 1;
- }
-
- auto yn = [](bool v) { return v ? "yes" : "no"; };
- fprintf(stdout, "Device present: %s\n", yn(resp.value("device_present", false)));
- fprintf(stdout, "BR/EDR: %s\n", yn(resp.value("classic_connected", false)));
- fprintf(stdout,
- "LE: %s%s\n",
- yn(resp.value("le_connected", false)),
- resp.value("le_available", false) ? "" : " (bearer unavailable)");
- fprintf(stdout, "Messages (MAP): %s", yn(resp.value("map_open", false)));
- if (resp.value("map_error", std::string("none")) != "none")
- fprintf(stdout, " [%s]", resp.value("map_error", "").c_str());
- fprintf(stdout, "\nContacts (PBAP): %s", yn(resp.value("pbap_open", false)));
- if (resp.value("pbap_error", std::string("none")) != "none")
- fprintf(stdout, " [%s]", resp.value("pbap_error", "").c_str());
- fprintf(stdout, "\n");
-
- const std::string link = resp.value("link_reason", "");
- const std::string profiles = resp.value("profile_reason", "");
- if (!link.empty())
- fprintf(stdout, "\n %s\n", link.c_str());
- if (!profiles.empty())
- fprintf(stdout, " %s\n", profiles.c_str());
- return 0;
-}
-
-// The daemon redacts; this only formats. Anything printed here is already safe
-// to paste into an issue.
-static int print_bt_diagnostics(tether::Client& client) {
- nlohmann::json resp;
- try {
- resp = nlohmann::json::parse(client.send_and_wait("{\"command\":\"bt_diagnostics\"}\n"));
- } catch (const std::exception&) {
- debug::log(ERR, "Could not read Bluetooth diagnostics from the daemon.\n");
- return 1;
- }
-
- fprintf(stdout, "%s\n", resp.dump(2).c_str());
- return 0;
-}
-
-static std::string format_time(int64_t epoch) {
- if (epoch <= 0)
- return "";
- std::time_t t = static_cast<std::time_t>(epoch);
- std::tm tm{};
- localtime_r(&t, &tm);
- char buf[32];
- std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", &tm);
- return buf;
-}
-
-static int print_bt_threads(tether::Client& client) {
- nlohmann::json resp;
- try {
- resp = nlohmann::json::parse(client.send_and_wait("{\"command\":\"bt_list_threads\"}\n"));
- } catch (const std::exception&) {
- debug::log(ERR, "Could not read conversations from the daemon.\n");
- return 1;
- }
-
- const auto& threads = resp["threads"];
- if (threads.empty()) {
- fprintf(stdout, "No conversations yet. Check 'tether --bt-connection'.\n");
- return 0;
- }
-
- for (const auto& t : threads) {
- const int unread = t.value("unread", 0);
- std::string preview = t.value("preview", "");
- if (preview.size() > 48)
- preview = preview.substr(0, 45) + "...";
- for (char& c : preview)
- if (c == '\n' || c == '\r')
- c = ' ';
-
- const std::string unread_note = unread > 0 ? " (" + std::to_string(unread) + " unread)" : "";
- fprintf(stdout,
- " %-24s %-18s %s%s\n",
- t.value("name", "").c_str(),
- format_time(t.value("timestamp", (int64_t)0)).c_str(),
- preview.c_str(),
- unread_note.c_str());
- fprintf(stdout, " %s\n", t.value("thread", "").c_str());
- }
- return 0;
-}
-
-static int print_bt_messages(tether::Client& client, const std::string& thread) {
- nlohmann::json request;
- request["command"] = "bt_list_messages";
- request["thread"] = thread;
-
- nlohmann::json resp;
- try {
- resp = nlohmann::json::parse(client.send_and_wait(request.dump() + "\n"));
- } catch (const std::exception&) {
- debug::log(ERR, "Could not read messages from the daemon.\n");
- return 1;
- }
-
- const auto& messages = resp["messages"];
- if (messages.empty()) {
- fprintf(stdout, "No messages in %s\n", thread.c_str());
- return 0;
- }
-
- for (const auto& m : messages) {
- fprintf(stdout,
- "%s %-8s %s%s\n",
- format_time(m.value("timestamp", (int64_t)0)).c_str(),
- m.value("outgoing", false) ? "me" : "them",
- m.value("body", "").c_str(),
- m.value("read", true) ? "" : " *");
- }
- return 0;
-}
-
-static int send_bt_message(tether::Client& client, const std::string& thread, const std::string& body) {
- nlohmann::json request;
- request["command"] = "bt_send_message";
- request["thread"] = thread;
- request["body"] = body;
-
- // The daemon answers asynchronously once the phone has accepted or refused
- // the message, so the result arrives on the event stream rather than as a
- // reply to the request.
- client.send("{\"command\":\"subscribe\"}\n");
- if (!client.send(request.dump() + "\n")) {
- debug::log(ERR, "Could not reach the daemon.\n");
- return 1;
- }
-
- std::string buffer;
- char buf[8192];
- while (true) {
- ssize_t n = client.read(buf, sizeof(buf));
- if (n <= 0) {
- debug::log(ERR, "Daemon closed the connection before the message was sent.\n");
- return 1;
- }
- buffer.append(buf, n);
-
- size_t pos;
- while ((pos = buffer.find('\n')) != std::string::npos) {
- std::string line = buffer.substr(0, pos);
- buffer.erase(0, pos + 1);
- if (line.empty())
- continue;
-
- nlohmann::json event;
- try {
- event = nlohmann::json::parse(line);
- } catch (const std::exception&) {
- continue;
- }
-
- if (event.value("command", "") != "bt_send_result")
- continue;
- if (event.value("success", false)) {
- fprintf(stdout, "Sent to %s\n", thread.c_str());
- return 0;
- }
- debug::log(ERR, "{}\n", event.value("message", "The message was not sent."));
- return 1;
- }
- }
-}
-
int main(int argc, char* argv[]) {
if (argc < 2) {
print_help();
return 0;
}
- std::string action, arg_val, arg_val2, host = "";
+ std::string action, arg_val, host = "";
int port = 5134;
int timeout_ms = 3000;
@@ -456,34 +137,6 @@ int main(int argc, char* argv[]) {
action = "discover";
} else if (arg == "--list-devices") {
action = "list";
- } else if (arg == "--bt-status") {
- action = "bt_status";
- } else if (arg == "--bt-devices") {
- action = "bt_devices";
- } else if (arg == "--bt-connection") {
- action = "bt_connection";
- } else if (arg == "--bt-diagnostics") {
- action = "bt_diagnostics";
- } else if (arg == "--bt-threads") {
- action = "bt_threads";
- } else if (arg == "--bt-messages") {
- action = "bt_messages";
- if (i + 1 < argc && argv[i + 1][0] != '-')
- arg_val = argv[++i];
- } else if (arg == "--bt-send") {
- action = "bt_send";
- if (i + 1 < argc && argv[i + 1][0] != '-')
- arg_val = argv[++i];
- if (i + 1 < argc)
- arg_val2 = argv[++i];
- } else if (arg == "--bt-pair") {
- action = "bt_pair";
- if (i + 1 < argc && argv[i + 1][0] != '-')
- arg_val = argv[++i];
- } else if (arg == "--bt-unpair") {
- action = "bt_unpair";
- if (i + 1 < argc && argv[i + 1][0] != '-')
- arg_val = argv[++i];
} else if (arg == "--pair") {
action = "pair";
} else if (arg == "--accept") {
@@ -602,34 +255,6 @@ int main(int argc, char* argv[]) {
debug::log(INFO, "File transfer delivered.\n");
} else if (action == "native") {
run_native_messaging_host(client);
- } else if (action == "bt_status") {
- return print_bt_status(client);
- } else if (action == "bt_devices") {
- return print_bt_devices(client);
- } else if (action == "bt_connection") {
- return print_bt_connection(client);
- } else if (action == "bt_diagnostics") {
- return print_bt_diagnostics(client);
- } else if (action == "bt_threads") {
- return print_bt_threads(client);
- } else if (action == "bt_messages") {
- if (arg_val.empty()) {
- debug::log(ERR, "A thread key is required, e.g. --bt-messages tel:+15551234567\n");
- return 1;
- }
- return print_bt_messages(client, arg_val);
- } else if (action == "bt_send") {
- if (arg_val.empty() || arg_val2.empty()) {
- debug::log(ERR, "A conversation and a message are required, e.g. --bt-send tel:+15551234567 \"hi\"\n");
- return 1;
- }
- return send_bt_message(client, arg_val, arg_val2);
- } else if (action == "bt_pair" || action == "bt_unpair") {
- if (arg_val.empty()) {
- debug::log(ERR, "A Bluetooth address is required, e.g. --bt-pair AA:BB:CC:DD:EE:FF\n");
- return 1;
- }
- return run_bt_transaction(client, action == "bt_pair" ? "bt_pair" : "bt_unpair", arg_val);
}
return 0;
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index d137478..247bc47 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -9,29 +9,6 @@ add_library(tether STATIC
src/crypto.cpp
src/client.cpp
src/discovery.cpp
- src/bluetooth/objects.cpp
- src/bluetooth/monitor.cpp
- src/bluetooth/config.cpp
- src/bluetooth/agent.cpp
- src/bluetooth/advert.cpp
- src/bluetooth/pairing.cpp
- src/bluetooth/bearer_supervisor.cpp
- src/bluetooth/profile_supervisor.cpp
- src/bluetooth/vcard.cpp
- src/bluetooth/bmessage.cpp
- src/bluetooth/messages.cpp
- src/bluetooth/map_session.cpp
- src/bluetooth/contacts.cpp
- src/bluetooth/journal.cpp
- src/bluetooth/pbap_session.cpp
- src/bluetooth/obex_transfer.cpp
- src/bluetooth/ancs/parser.cpp
- src/bluetooth/ancs/notifications.cpp
- src/bluetooth/ancs/sequencer.cpp
- src/bluetooth/ancs/client.cpp
- src/bluetooth/groups.cpp
- src/bluetooth/connection.cpp
- src/bluetooth/diagnostics.cpp
src/wayland.cpp
src/wayland_protocols/wayland.cpp
src/wayland_protocols/wlr-data-control-unstable-v1.cpp
diff --git a/src/core/include/tether/bluetooth/advert.hpp b/src/core/include/tether/bluetooth/advert.hpp
deleted file mode 100644
index 71d6d01..0000000
--- a/src/core/include/tether/bluetooth/advert.hpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#pragma once
-
-#include <gio/gio.h>
-#include <memory>
-#include <string>
-
-namespace tether::bluetooth {
-
- struct AdvertState;
-
- // Broadcasts an LE advertisement soliciting the ANCS service.
- class AncsAdvertisement {
- public:
- AncsAdvertisement(GDBusConnection* connection, std::string adapter_path);
- ~AncsAdvertisement();
-
- AncsAdvertisement(const AncsAdvertisement&) = delete;
- AncsAdvertisement& operator=(const AncsAdvertisement&) = delete;
-
- // Registration is two-phase, and the phases must run on different threads.
- bool export_object();
- bool register_with_bluez();
- void unregister_with_bluez();
- void unexport_object();
-
- bool active() const;
-
- private:
- std::unique_ptr<AdvertState> state_;
- };
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/agent.hpp b/src/core/include/tether/bluetooth/agent.hpp
deleted file mode 100644
index 460c692..0000000
--- a/src/core/include/tether/bluetooth/agent.hpp
+++ /dev/null
@@ -1,57 +0,0 @@
-#pragma once
-
-#include <functional>
-#include <gio/gio.h>
-#include <memory>
-#include <string>
-
-namespace tether::bluetooth {
-
- // Services Tether uses. Anything else the phone asks us to authorize during
- // pairing is refused: an accessory should not be granted profiles it has no
- // reason to consume.
- // 0x112E PBAP client, 0x112F PBAP server,
- // 0x1132 MAP server, 0x1133 MAP notification server, 0x1134 MAP client
- bool is_authorized_service(const std::string& uuid);
-
- // BlueZ hands passkeys over as a plain integer; Apple shows six digits with
- // leading zeros, and a mismatch here reads to the user as a failed pairing.
- std::string format_passkey(uint32_t passkey);
-
- struct AgentState;
-
- // Implements org.bluez.Agent1 for exactly one device.
- //
- // Numeric comparison only: this agent never invents, displays, or accepts a
- // PIN or passkey, and it refuses every request naming a device other than its
- // target. Confirmation is delegated to the out-of-process dialog so the
- // daemon never blocks on a user decision.
- class PairingAgent {
- public:
- // Called with the six-digit comparison code; returns true to accept.
- // Runs on the thread dispatching the agent's callbacks and may block
- // while the user decides, stalls BlueZ monitoring for the duration
- // of the prompt, which is harmless during a foreground pairing.
- using ConfirmHandler = std::function<bool(const std::string& code)>;
-
- PairingAgent(GDBusConnection* connection, std::string device_path, ConfirmHandler on_confirm);
- ~PairingAgent();
-
- PairingAgent(const PairingAgent&) = delete;
- PairingAgent& operator=(const PairingAgent&) = delete;
-
- // Two-phase, and the phases must run on different threads
- // export_object() binds callbacks to the calling thread's context
- // register_with_bluez() blocks on BlueZ and so must not run on that same thread.
- bool export_object();
- bool register_with_bluez();
- void unregister_with_bluez();
- void unexport_object();
-
- const std::string& path() const;
-
- private:
- std::unique_ptr<AgentState> state_;
- };
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/ancs/client.hpp b/src/core/include/tether/bluetooth/ancs/client.hpp
deleted file mode 100644
index 8831258..0000000
--- a/src/core/include/tether/bluetooth/ancs/client.hpp
+++ /dev/null
@@ -1,61 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/ancs/notifications.hpp"
-
-#include <functional>
-#include <memory>
-#include <string>
-
-namespace tether::bluetooth {
- class BluezMonitor;
-}
-
-namespace tether::bluetooth::ancs {
-
- // How often to retry discovery, subscription and the readiness probe.
- inline constexpr int ANCS_RETRY_SECONDS = 5;
-
- // Defined in client.cpp.
- struct AncsClientState;
-
- // GATT client for Apple's notification service.
- //
- // Everything here is driven from one thread by tick(). BlueZ delivers
- // characteristic values on the GLib thread, which only buffers the bytes;
- // the sequencer and all D-Bus writes stay on the caller's thread, so no ANCS
- // state is touched from two places at once.
- class AncsClient {
- public:
- using NotificationFn = std::function<void(const Notification&)>;
- using WithdrawFn = std::function<void(uint32_t uid)>;
- // Reported when readiness changes; `reason` is shown to the user.
- using StatusFn = std::function<void(bool ready, const std::string& reason)>;
-
- AncsClient(BluezMonitor& monitor, NotificationFn on_notification, WithdrawFn on_withdraw, StatusFn on_status);
- ~AncsClient();
-
- AncsClient(const AncsClient&) = delete;
- AncsClient& operator=(const AncsClient&) = delete;
-
- // The BlueZ object path of the connected iPhone, or empty when LE drops.
- void set_device(const std::string& device_path);
-
- // Whether to ask for notification contents or only which app sent them.
- void set_content_enabled(bool enabled);
-
- void tick(int64_t now);
-
- bool ready() const;
- const std::string& status_reason() const;
-
- // Invokes a notification's positive or negative action. ANCS offers only
- // these two — there is no free-text reply.
- bool perform_action(uint32_t uid, ActionId action);
-
- const NotificationRegistry& registry() const;
-
- private:
- std::unique_ptr<AncsClientState> state_;
- };
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/include/tether/bluetooth/ancs/notifications.hpp b/src/core/include/tether/bluetooth/ancs/notifications.hpp
deleted file mode 100644
index 2c846af..0000000
--- a/src/core/include/tether/bluetooth/ancs/notifications.hpp
+++ /dev/null
@@ -1,74 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/ancs/protocol.hpp"
-
-#include <cstdint>
-#include <map>
-#include <nlohmann/json.hpp>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth::ancs {
-
- // A mirrored notification, as far as it has been resolved.
- struct Notification {
- uint32_t uid = 0;
- std::string app_id;
- // The app's display name once resolved; falls back to the identifier.
- std::string app_name;
- std::string title;
- std::string subtitle;
- std::string body;
- CategoryId category = CategoryId::Other;
- int64_t received = 0;
- bool silent = false;
- bool has_positive_action = false;
- bool has_negative_action = false;
-
- bool operator==(const Notification&) const = default;
- };
-
- // Whether a Source event should be resolved and shown.
- enum class Decision {
- Fetch, // new or genuinely updated: ask for its attributes
- Ignore, // a replay, or something deliberately not mirrored
- Withdraw // removed on the phone: drop the desktop copy
- };
-
- // Applies the delivery rules that keep the desktop from being flooded.
- //
- // iOS replays every existing notification whenever the subscription comes
- // up, so the same notification arrives again after each reconnect. Dedupe is
- // on the notification UID, but a Modified event is a genuine update the user
- // should see, so it is never suppressed by having seen the UID before.
- class NotificationRegistry {
- public:
- // `initial` marks the first subscription of a session, where
- // pre-existing notifications are the phone's backlog rather than news.
- Decision classify(const SourceEvent& event, bool initial) const;
-
- void remember(const SourceEvent& event);
- void forget(uint32_t uid);
- void clear();
-
- void store(const Notification& notification);
- const Notification* find(uint32_t uid) const;
- // Newest first.
- std::vector<Notification> recent(size_t limit = 50) const;
-
- size_t size() const { return notifications_.size(); }
-
- private:
- // UIDs seen this session, to recognize a replay.
- std::map<uint32_t, int64_t> seen_;
- std::map<uint32_t, Notification> notifications_;
- std::vector<uint32_t> order_;
- };
-
- // Messages arrive over MAP already, with read state that stays in sync. The
- // ANCS copy is kept for correlation but must never raise a second popup.
- bool should_show_desktop_popup(const Notification& notification);
-
- nlohmann::json to_json(const Notification& notification);
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/include/tether/bluetooth/ancs/parser.hpp b/src/core/include/tether/bluetooth/ancs/parser.hpp
deleted file mode 100644
index 02f60a6..0000000
--- a/src/core/include/tether/bluetooth/ancs/parser.hpp
+++ /dev/null
@@ -1,55 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/ancs/protocol.hpp"
-
-#include <cstddef>
-#include <cstdint>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth::ancs {
-
- // No attribute we ask for can legitimately be this large; anything claiming
- // more is malformed or hostile and the response is dropped.
- inline constexpr uint16_t MAX_ATTRIBUTE_LENGTH = 1024;
- // Hard ceiling on one reassembled response, so a peer cannot make us buffer
- // without bound by never completing one.
- inline constexpr size_t MAX_RESPONSE_BYTES = 4096;
-
- // Parses one Notification Source packet. Returns false unless the packet is
- // exactly the eight bytes the specification defines — a short read here
- // would otherwise be interpreted as a different notification.
- bool parse_source_event(const uint8_t* data, size_t length, SourceEvent& out);
-
- // Reassembles a Data Source response.
- //
- // Data Source responses carry no total length and arrive split across GATT
- // notifications, so the only way to know a response has ended is to know
- // exactly what was asked for: the echoed command byte plus the attribute
- // sequence of the request in flight. That is why the sequencer allows only
- // one request at a time.
- class DataSourceAssembler {
- public:
- enum class Result { NeedMore, Complete, Error };
-
- // Declares the request whose response is now expected. Resets any
- // partial buffer, since a new request invalidates it.
- void expect(CommandId command, std::vector<uint8_t> attribute_ids);
- void reset();
- bool expecting() const { return expecting_; }
-
- // Feeds one fragment. On Complete, `out` holds the response and the
- // assembler is ready for the next request. On Error the buffer is
- // dropped: a response that cannot be trusted must not be half-applied.
- Result append(const uint8_t* data, size_t length, Response& out, std::string& err);
-
- private:
- Result parse(Response& out, std::string& err);
-
- bool expecting_ = false;
- CommandId command_ = CommandId::GetNotificationAttributes;
- std::vector<uint8_t> attribute_ids_;
- std::vector<uint8_t> buffer_;
- };
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/include/tether/bluetooth/ancs/protocol.hpp b/src/core/include/tether/bluetooth/ancs/protocol.hpp
deleted file mode 100644
index 67ede61..0000000
--- a/src/core/include/tether/bluetooth/ancs/protocol.hpp
+++ /dev/null
@@ -1,119 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-// Apple Notification Center Service. Constants and wire types from Apple's
-// published ANCS specification.
-namespace tether::bluetooth::ancs {
-
- inline constexpr const char* UUID_SERVICE = "7905f431-b5ce-4e99-a40f-4b1e122d00d0";
- inline constexpr const char* UUID_NOTIFICATION_SOURCE = "9fbf120d-6301-42d9-8c58-25e699a21dbd";
- inline constexpr const char* UUID_CONTROL_POINT = "69d1d8f3-45e1-49a8-9821-9bbdfdaad9d9";
- inline constexpr const char* UUID_DATA_SOURCE = "22eac6e9-24d6-4bb5-be44-b36ace7c7bfb";
-
- // Messages already arrive over MAP with proper read-state sync, so ANCS
- // copies of them must never produce a second desktop popup.
- inline constexpr const char* APP_ID_MESSAGES = "com.apple.MobileSMS";
-
- enum class EventId : uint8_t { Added = 0, Modified = 1, Removed = 2 };
-
- enum EventFlags : uint8_t {
- FlagSilent = 1 << 0,
- FlagImportant = 1 << 1,
- // Set on notifications that were already on the phone when we
- // subscribed. Delivering these would replay the lock screen as a burst
- // of desktop popups.
- FlagPreExisting = 1 << 2,
- FlagPositiveAction = 1 << 3,
- FlagNegativeAction = 1 << 4,
- };
-
- enum class CategoryId : uint8_t {
- Other = 0,
- IncomingCall = 1,
- MissedCall = 2,
- Voicemail = 3,
- Social = 4,
- Schedule = 5,
- Email = 6,
- News = 7,
- HealthAndFitness = 8,
- BusinessAndFinance = 9,
- Location = 10,
- Entertainment = 11,
- };
-
- enum class CommandId : uint8_t {
- GetNotificationAttributes = 0,
- GetAppAttributes = 1,
- PerformNotificationAction = 2,
- };
-
- enum class NotificationAttributeId : uint8_t {
- AppIdentifier = 0,
- Title = 1,
- Subtitle = 2,
- Message = 3,
- MessageSize = 4,
- Date = 5,
- PositiveActionLabel = 6,
- NegativeActionLabel = 7,
- };
-
- enum class AppAttributeId : uint8_t { DisplayName = 0 };
-
- enum class ActionId : uint8_t { Positive = 0, Negative = 1 };
-
- // Title, Subtitle and Message are the only attributes that take a maximum
- // length, and it is mandatory for them.
- inline constexpr bool attribute_takes_length(NotificationAttributeId id) {
- return id == NotificationAttributeId::Title || id == NotificationAttributeId::Subtitle ||
- id == NotificationAttributeId::Message;
- }
-
- // Bodies are capped rather than requested whole. The cap also fixes the
- // prefix that Phase 9 correlates a group message against.
- inline constexpr uint16_t MAX_BODY_LENGTH = 256;
- inline constexpr uint16_t MAX_TITLE_LENGTH = 128;
-
- // One Notification Source packet, which is always exactly eight bytes.
- struct SourceEvent {
- EventId event = EventId::Added;
- uint8_t flags = 0;
- CategoryId category = CategoryId::Other;
- uint8_t category_count = 0;
- uint32_t uid = 0;
-
- bool pre_existing() const { return (flags & FlagPreExisting) != 0; }
- bool silent() const { return (flags & FlagSilent) != 0; }
- bool has_positive_action() const { return (flags & FlagPositiveAction) != 0; }
- bool has_negative_action() const { return (flags & FlagNegativeAction) != 0; }
-
- bool operator==(const SourceEvent&) const = default;
- };
-
- struct Attribute {
- uint8_t id = 0;
- std::string value;
-
- bool operator==(const Attribute&) const = default;
- };
-
- // A reassembled Data Source response.
- struct Response {
- CommandId command = CommandId::GetNotificationAttributes;
- // Set for GetNotificationAttributes.
- uint32_t uid = 0;
- // Set for GetAppAttributes.
- std::string app_id;
- std::vector<Attribute> attributes;
-
- // Empty when the attribute was absent or the phone withheld it.
- std::string attribute(uint8_t id) const;
-
- bool operator==(const Response&) const = default;
- };
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/include/tether/bluetooth/ancs/sequencer.hpp b/src/core/include/tether/bluetooth/ancs/sequencer.hpp
deleted file mode 100644
index 703fc32..0000000
--- a/src/core/include/tether/bluetooth/ancs/sequencer.hpp
+++ /dev/null
@@ -1,93 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/ancs/parser.hpp"
-
-#include <cstdint>
-#include <deque>
-#include <functional>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth::ancs {
-
- // A response that never arrives must not wedge the queue forever.
- inline constexpr int REQUEST_TIMEOUT_SECONDS = 15;
- // Bounds how much work a burst of notifications can queue up.
- inline constexpr size_t MAX_QUEUED_REQUESTS = 64;
-
- struct Request {
- CommandId command = CommandId::GetNotificationAttributes;
- // The Control Point payload, already encoded.
- std::vector<uint8_t> payload;
- // The attribute sequence this request asked for, which is the only way
- // to know where its response ends.
- std::vector<uint8_t> attribute_ids;
- // Echoed back to the caller so a completion can be matched to what it
- // was for without ANCS providing any correlation of its own.
- uint32_t uid = 0;
- };
-
- // Serializes Control Point requests.
- //
- // ANCS responses carry no request identifier, so with two requests in flight
- // there is no way to tell which response belongs to which — the attributes
- // of one notification would be attached to another. Exactly one request is
- // outstanding at a time, and the rest wait in a queue.
- class ControlPointSequencer {
- public:
- // Returns false when the write could not be issued, which fails the
- // request rather than leaving it silently outstanding.
- using WriteFn = std::function<bool(const std::vector<uint8_t>&)>;
- using CompleteFn = std::function<void(const Request&, const Response&)>;
- using FailFn = std::function<void(const Request&, const std::string& reason)>;
-
- ControlPointSequencer(WriteFn write, CompleteFn on_complete, FailFn on_fail);
-
- // Dropped when the queue is full; a caller cannot make the daemon grow
- // without bound by generating notifications.
- bool submit(Request request);
-
- // Drive with a monotonic clock. Starts the next request when idle and
- // times out one that has gone unanswered.
- void tick(int64_t now);
-
- // Feeds a Data Source fragment.
- void on_data_source(const uint8_t* data, size_t length, int64_t now);
-
- // Clears everything after a disconnect: any outstanding response belongs
- // to a session that no longer exists.
- void reset();
-
- bool in_flight() const { return in_flight_; }
- size_t queued() const { return queue_.size(); }
-
- private:
- void start_next(int64_t now);
-
- WriteFn write_;
- CompleteFn on_complete_;
- FailFn on_fail_;
-
- std::deque<Request> queue_;
- Request current_;
- bool in_flight_ = false;
- int64_t deadline_ = 0;
- DataSourceAssembler assembler_;
- };
-
- // --- Request builders ---------------------------------------------------
-
- // Asks for the attributes of one notification. Title, subtitle and message
- // are length-capped; the caller chooses which attributes to request, because
- // asking for content at all is a privacy decision.
- Request build_notification_request(uint32_t uid, const std::vector<NotificationAttributeId>& attributes);
-
- // Asks for an app's display name.
- Request build_app_request(const std::string& app_id);
-
- // Performs a notification's positive or negative action. ANCS offers only
- // these two; there is no free-text reply, so no reply affordance can be
- // built on a mirrored notification.
- Request build_action_request(uint32_t uid, ActionId action);
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hpp
deleted file mode 100644
index d379c0f..0000000
--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp
+++ /dev/null
@@ -1,71 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <string>
-
-namespace tether::bluetooth {
-
- inline constexpr int BEARER_POLL_SECONDS = 5;
- inline constexpr int BEARER_SETTLE_SECONDS = 3;
- inline constexpr int BEARER_BACKOFF_MIN_SECONDS = 5;
- inline constexpr int BEARER_BACKOFF_MAX_SECONDS = 300;
-
- // The BlueZ operations the supervisor performs.
- class BearerOps {
- public:
- virtual ~BearerOps() = default;
-
- virtual bool device_present() const = 0;
- virtual bool device_paired() const = 0;
- virtual bool classic_connected() const = 0;
- virtual bool le_bearer_available() const = 0;
- virtual bool le_connected() const = 0;
-
- virtual void set_preferred_bearer(const std::string& bearer) = 0;
-
- virtual bool connect_classic(std::string& err) = 0;
- virtual bool connect_le(std::string& err) = 0;
- };
-
- struct BearerStatus {
- bool device_present = false;
- bool device_paired = false;
- bool classic_connected = false;
- bool le_connected = false;
- bool le_available = false;
- int classic_backoff = 0;
- int le_backoff = 0;
- std::string reason;
-
- bool operator==(const BearerStatus&) const = default;
- };
-
- // Keeps the Classic and LE halves of one bond connected.
- //
- // Order is important: BR/EDR first, a settling interval, then LE
- class BearerSupervisor {
- public:
- BearerSupervisor(BearerOps& ops, bool ancs_enabled);
-
- // Drive once per BEARER_POLL_SECONDS with a monotonic clock. Returns true
- // when the reported status changed, so callers only broadcast on change.
- bool tick(int64_t now);
-
- // Clears connection state and backoff after a disconnect or a resume, so
- // recovery starts immediately instead of waiting out a stale backoff.
- void reset();
-
- void set_ancs_enabled(bool enabled);
- const BearerStatus& status() const { return status_; }
-
- private:
- BearerOps& ops_;
- bool ancs_enabled_ = true;
-
- BearerStatus status_;
- int64_t classic_connected_since_ = -1;
- int64_t next_classic_attempt_ = 0;
- int64_t next_le_attempt_ = 0;
- };
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/bmessage.hpp b/src/core/include/tether/bluetooth/bmessage.hpp
deleted file mode 100644
index 7910e13..0000000
--- a/src/core/include/tether/bluetooth/bmessage.hpp
+++ /dev/null
@@ -1,91 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- // One party in a bMessage, decoded from its embedded vCard.
- //
- // A telephone number in TEL and an AppleID destination in EMAIL;
- // both must be saved, because contacts that exist only as an AppleID have
- // no phone number at all.
- struct VCardParty {
- // Display only.
- std::string name;
- std::string tel;
- std::string email;
-
- bool empty() const { return tel.empty() && email.empty(); }
- bool operator==(const VCardParty&) const = default;
- };
-
- struct BMessage {
- bool valid = false;
- // READ or UNREAD as reported by the phone.
- bool read = false;
- // Always SMS_GSM for both SMS and iMessage.
- std::string type;
- std::string folder;
- VCardParty originator;
- std::vector<VCardParty> recipients;
- std::string body;
-
- bool operator==(const BMessage&) const = default;
- };
-
- // Tolerant parser: accepts CRLF or LF, missing optional fields, and unknown
- // properties. Returns valid=false rather than throwing on malformed input.
- // This is untrusted data arriving from a phone.
- BMessage parse_bmessage(const std::string& text);
-
- // Addresses are identity; names are display. These normalizations decide
- // which messages group into one conversation, so they must be stable and
- // must not merge two different people.
-
- // Strips formatting from a phone number, keeping a leading '+'. Does not
- // invent a country code: "555-1234" stays national, because guessing one
- // could route a reply to a different person.
- std::string normalize_phone(const std::string& raw);
-
- // Lowercases and trims an email/AppleID address.
- std::string normalize_email(const std::string& raw);
-
- // The stable key for one conversation.
- std::string thread_key_for(const VCardParty& party);
-
- // Parses MAP's basic-ISO timestamp (optionally with a trailing offset) into a Unix epoch.
- // Returns 0 when unparseable.
- int64_t parse_map_timestamp(const std::string& text);
-
- enum class RecipientKind { Tel, Email };
-
- struct Recipient {
- RecipientKind kind = RecipientKind::Tel;
- std::string address;
-
- bool operator==(const Recipient&) const = default;
- };
-
- // Returns false with err_out set when the address must not be used.
- bool validate_recipient(const Recipient& recipient, std::string& err_out);
-
- // Parses a namespaced thread key ("tel:+15551234567", "email:[email protected]") into a
- // validated recipient. Returns false for unknown prefixes.
- bool recipient_from_thread_key(const std::string& thread_key, Recipient& out, std::string& err_out);
-
- // MAP byte-stuffing: a body line that would otherwise a structural
- // token is prefixed with a space. Mirrors what the parser undoes, so a body
- // does a round trip unchanged.
- std::string stuff_body(const std::string& body);
-
- // Builds a MAP 1.4 bMessage for PushMessage. Recipients must already be
- // validated
- //
- // TYPE is always SMS_GSM, including for AppleID recipients: iOS decides
- // between SMS and iMessage itself, and nothing here can force or observe
- // that choice.
- std::string build_bmessage(const std::vector<Recipient>& recipients, const std::string& body);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/config.hpp b/src/core/include/tether/bluetooth/config.hpp
deleted file mode 100644
index ebd04c4..0000000
--- a/src/core/include/tether/bluetooth/config.hpp
+++ /dev/null
@@ -1,47 +0,0 @@
-#pragma once
-
-#include <string>
-
-namespace tether::bluetooth {
-
- // Which pairing transaction to run.
- //
- // ConnectFirst calls Device1.Connect() on the unpaired device and lets iOS
- // initiate authentication. A Linux-initiated Pair() can
- // yield a BR/EDR-only bond, which can never carry ANCS.
- //
- // ExplicitPair calls Device1.Pair() directly. Some controllers cancel the
- // Connect-first transaction, and headless callers cannot show a confirmation
- // prompt, so it stays available as a workaround.
- enum class AuthStrategy { ConnectFirst, ExplicitPair };
-
- // Persisted at ~/.config/tether/bluetooth.json.
- struct Config {
- // Address of the selected iPhone, e.g. "81:71:C8:30:6A:F3".
- std::string device_address;
- AuthStrategy auth_strategy = AuthStrategy::ConnectFirst;
- // Cleared when pairing resolves to compatibility mode, so later runs do
- // not keep trying to bring up an LE bearer the phone will not answer.
- bool ancs_enabled = true;
- // Whether to request notification contents rather than only the app
- // they came from. Off by default.
- bool ancs_content_enabled = false;
- // Group replies are off until deliberately enabled
- bool group_messages_enabled = false;
-
- bool operator==(const Config&) const = default;
- };
-
- const char* to_string(AuthStrategy strategy);
- AuthStrategy auth_strategy_from_string(const std::string& value);
-
- std::string config_path();
-
- Config load_config();
- bool save_config(const Config& config);
-
- // exposed for tests without touching fs
- std::string serialize_config(const Config& config);
- Config deserialize_config(const std::string& text);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/connection.hpp b/src/core/include/tether/bluetooth/connection.hpp
deleted file mode 100644
index 729c82c..0000000
--- a/src/core/include/tether/bluetooth/connection.hpp
+++ /dev/null
@@ -1,92 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/ancs/notifications.hpp"
-#include "tether/bluetooth/bearer_supervisor.hpp"
-#include "tether/bluetooth/groups.hpp"
-#include "tether/bluetooth/messages.hpp"
-#include "tether/bluetooth/profile_supervisor.hpp"
-
-#include <functional>
-#include <memory>
-#include <mutex>
-#include <nlohmann/json.hpp>
-#include <string>
-
-namespace tether::bluetooth {
-
- class BluezMonitor;
-
- struct ConnectionState;
-
- // Drives the bearer and profile supervisors against the real BlueZ and obexd,
- // on its own thread, for the daemon's lifetime.
- class ConnectionManager {
- public:
- // Reports a combined status whenever it changes.
- using StatusFn = std::function<void(const nlohmann::json&)>;
- // Called once per newly seen message. `backfill` marks the first listing
- // after a MAP session opens (phone's existing inbox), so they belong in the UI but must not each do desktop
- // notification.
- using MessageFn = std::function<void(const Message& message, bool backfill)>;
- // Called once per mirrored notification, and when one is dismissed on
- // the phone.
- using NotificationFn = std::function<void(const ancs::Notification&)>;
- using WithdrawFn = std::function<void(uint32_t uid)>;
-
- ConnectionManager(BluezMonitor& monitor, StatusFn on_change, MessageFn on_message = {});
-
- // Enables notification mirroring. Without a handler the ANCS client is
- // never started, so a caller that cannot show notifications does not pay
- // for a GATT session it will not use.
- void set_notification_handlers(NotificationFn on_notification, WithdrawFn on_withdraw);
-
- // Invokes a mirrored notification's action.
- bool perform_notification_action(uint32_t uid, ancs::ActionId action);
-
- nlohmann::json notifications(size_t limit = 50) const;
- ~ConnectionManager();
-
- ConnectionManager(const ConnectionManager&) = delete;
- ConnectionManager& operator=(const ConnectionManager&) = delete;
-
- // address is the bonded iPhone; empty disables supervision until set.
- bool start(const std::string& address, bool ancs_enabled);
- void stop();
-
- void set_device(const std::string& address, bool ancs_enabled);
-
- nlohmann::json status() const;
-
- private:
- std::unique_ptr<ConnectionState> state_;
- };
-
- nlohmann::json to_json(const BearerStatus& bearer, const ProfileStatus& profiles);
-
- // Conversation history for the selected iPhone.
- MessageStore& message_store();
- std::mutex& message_store_mutex();
-
- // Marks a message read on the phone as well as locally. Returns false with
- // err_out set when MAP is not currently open.
- bool mark_message_read(const std::string& handle, bool read, std::string& err_out);
-
- // Sends a reply to a one-to-one conversation. Returns false with err_out set
- // when MAP is down, the thread cannot be replied to, or the phone refused.
- bool send_message(const std::string& thread_key, const std::string& body, Message& sent_out, std::string& err_out);
-
- // Feeds the group correlator with an Apple Messages notification.
- void observe_message_notification(const std::string& sender,
- const std::string& subtitle,
- const std::string& body,
- int64_t now);
-
- // Why a group thread can or cannot be replied to, for the UI to show.
- ReplyEligibility group_reply_status(const std::string& thread_key, std::string& reason);
-
- void set_group_replies_enabled(bool enabled);
- void reload_group_rosters();
-
- extern ConnectionManager* g_bt_connections;
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/contacts.hpp b/src/core/include/tether/bluetooth/contacts.hpp
deleted file mode 100644
index f0f3fe1..0000000
--- a/src/core/include/tether/bluetooth/contacts.hpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/vcard.hpp"
-
-#include <map>
-#include <nlohmann/json.hpp>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- // Resolves a thread key to a display name.
- class ContactStore {
- public:
- void set(std::vector<VCard> contacts);
-
- // Empty when the address is unknown. Keys are the same namespaced form
- // messages use, e.g. "tel:+15551234567" or "email:[email protected]".
- std::string name_for(const std::string& thread_key) const;
-
- // Every address a display name maps to. Returns all matches.
- std::vector<std::string> addresses_for_name(const std::string& name) const;
-
- size_t size() const { return contacts_.size(); }
- size_t indexed() const { return by_key_.size(); }
- const std::vector<VCard>& contacts() const { return contacts_; }
-
- private:
- std::vector<VCard> contacts_;
- std::map<std::string, std::string> by_key_;
- };
-
- // Cached at ~/.local/share/tether/contacts.json so names survive a restart
- // and are available before PBAP reconnects.
- std::string contacts_path();
- bool save_contacts(const ContactStore& store);
- ContactStore load_contacts();
-
- std::string serialize_contacts(const ContactStore& store);
- ContactStore deserialize_contacts(const std::string& text);
-
- // Set by the daemon; command handlers read it to label threads.
- ContactStore& contact_store();
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/diagnostics.hpp b/src/core/include/tether/bluetooth/diagnostics.hpp
deleted file mode 100644
index f4b330d..0000000
--- a/src/core/include/tether/bluetooth/diagnostics.hpp
+++ /dev/null
@@ -1,40 +0,0 @@
-#pragma once
-
-#include <map>
-#include <nlohmann/json.hpp>
-#include <string>
-
-namespace tether::bluetooth {
-
- // Removes identifying values from text destined for a bug report: Bluetooth
- // addresses (bare, or spelled as a D-Bus device node), phone numbers, email
- // addresses, and the user's home and runtime directories.
- class Redactor {
- public:
- std::string text(const std::string& in);
-
- // Recursively redacts strings
- nlohmann::json value(const nlohmann::json& in);
-
- private:
- std::string placeholder(const std::string& kind, const std::string& key);
-
- std::map<std::string, std::string> assigned_;
- };
-
- // True for keys whose values are personal content and must never appear in
- // a report.
- bool is_content_key(const std::string& key);
-
- // Appends a daemon event to the bounded diagnostic timeline, stamped with
- // milliseconds since the first recorded event.
- void record_diagnostic_event(const nlohmann::json& event);
-
- // Oldest first
- nlohmann::json diagnostic_timeline();
- void clear_diagnostic_timeline();
-
- // Assembles a redacted report from the caller's live status payloads.
- nlohmann::json build_diagnostics(const nlohmann::json& status, const nlohmann::json& connection);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/groups.hpp b/src/core/include/tether/bluetooth/groups.hpp
deleted file mode 100644
index 9b34ae5..0000000
--- a/src/core/include/tether/bluetooth/groups.hpp
+++ /dev/null
@@ -1,116 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/bmessage.hpp"
-#include "tether/bluetooth/contacts.hpp"
-
-#include <cstdint>
-#include <map>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- inline constexpr int GROUP_CORRELATION_WINDOW_SECONDS = 30;
-
- // What the Messages notification revealed about a conversation.
- struct GroupInfo {
- bool is_group = false;
- // when the group has a name
- bool named = false;
- std::string name;
- // display names parsed from an unnamed group's subtitle, excluding the user.
- std::vector<std::string> participants;
- // Display only. Never part of thread identity or reply routing.
- std::string sender;
-
- bool operator==(const GroupInfo&) const = default;
- };
-
- // Parses a Messages notification into group information.
- //
- // An unnamed group's subtitle is like "To you & Alice", with further
- // names separated by commas or ampersands. Anything else is treated as a
- // group name. Returns false when the notification describes a one-to-one
- // conversation, which has no subtitle of either.
- bool parse_group_notification(const std::string& title, const std::string& subtitle, GroupInfo& out);
-
- // The local thread key for a group.
- std::string group_thread_key(const GroupInfo& info);
-
- // One observed Apple Messages notification
- struct MessageNotification {
- std::string sender;
- std::string subtitle;
- std::string body;
- int64_t received = 0;
- };
-
- enum class Correlation {
- Matched,
- NoMatch,
- Ambiguous,
- };
-
- // Matches arriving MAP messages against recent Messages notifications.
- class GroupCorrelator {
- public:
- void observe(const MessageNotification& notification);
- void expire(int64_t now);
- void clear();
-
- Correlation correlate(const std::string& body, int64_t now, GroupInfo& out) const;
-
- size_t size() const { return recent_.size(); }
-
- private:
- std::vector<MessageNotification> recent_;
- };
-
- // Why a group cannot be replied to
- enum class ReplyEligibility {
- Allowed,
- // Group messaging is switched off.
- Disabled,
- // A named group with no user-supplied roster.
- NeedsRoster,
- // A participant name matched no contact, or more than one.
- Unresolved,
- // A sender appeared who is not in the known member set.
- RouteInvalidated,
- };
-
- const char* to_string(ReplyEligibility eligibility);
-
- // Rosters the user supplies for named groups, keyed by thread key.
- class GroupRoster {
- public:
- void set(const std::string& thread_key, std::vector<std::string> addresses);
- const std::vector<std::string>* find(const std::string& thread_key) const;
- bool empty() const { return rosters_.empty(); }
-
- std::string serialize() const;
- static GroupRoster deserialize(const std::string& text);
-
- private:
- std::map<std::string, std::vector<std::string>> rosters_;
- };
-
- std::string roster_path();
- GroupRoster load_rosters();
- bool save_rosters(const GroupRoster& roster);
-
- // Resolves who a group reply would actually go to.
- // Every participant name must resolve to exactly one address. A name that
- // matches several contacts is refused rather than guessed.
- ReplyEligibility resolve_group_recipients(const GroupInfo& info,
- const std::string& thread_key,
- const ContactStore& contacts,
- const GroupRoster& rosters,
- bool group_replies_enabled,
- std::vector<Recipient>& out,
- std::string& reason);
-
- // True when `sender` is not among the addresses a reply would be sent to.
- bool sender_invalidates_route(const std::string& sender_address, const std::vector<Recipient>& recipients);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/journal.hpp b/src/core/include/tether/bluetooth/journal.hpp
deleted file mode 100644
index 80c9c6d..0000000
--- a/src/core/include/tether/bluetooth/journal.hpp
+++ /dev/null
@@ -1,47 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/messages.hpp"
-
-#include <cstdint>
-#include <fstream>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- inline constexpr size_t JOURNAL_MAX_MESSAGES = 10000;
- inline constexpr int64_t JOURNAL_MAX_AGE_SECONDS = 90LL * 24 * 3600;
-
- std::string journal_path();
-
- // Append-only newline-delimited JSON at ~/.local/share/tether/messages.ndjson.
- class MessageJournal {
- public:
- // Creates the directory and opens the file for appending, mode 0600
- bool open();
- bool is_open() const { return out_.is_open(); }
- void close();
-
- void append(const Message& message);
-
- // Malformed lines are skipped rather than aborting the load
- std::vector<Message> load(int64_t now) const;
-
- // Rewrites the file to exactly `messages`, atomically.
- bool compact(const std::vector<Message>& messages);
-
- private:
- std::ofstream out_;
- std::string path_;
- };
-
- std::string serialize_message_line(const Message& message);
- bool deserialize_message_line(const std::string& line, Message& out);
-
- // Drops anything older than max_age, then keeps the newest max_messages.
- std::vector<Message> apply_retention(std::vector<Message> messages,
- int64_t now,
- size_t max_messages = JOURNAL_MAX_MESSAGES,
- int64_t max_age = JOURNAL_MAX_AGE_SECONDS);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/map_session.hpp b/src/core/include/tether/bluetooth/map_session.hpp
deleted file mode 100644
index 84c2fe6..0000000
--- a/src/core/include/tether/bluetooth/map_session.hpp
+++ /dev/null
@@ -1,73 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/messages.hpp"
-
-#include <functional>
-#include <gio/gio.h>
-#include <memory>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- // One entry from MessageAccess1.ListMessages.
- struct MapListing {
- std::string handle;
- std::string subject;
- std::string sender_address;
- std::string sender_name;
- std::string timestamp;
- std::string type;
- std::string folder;
- bool read = false;
- bool sent = false;
- };
-
- // Converts a listing into a Message without a bMessage round trip.
- Message message_from_listing(const MapListing& listing);
-
- // Extracts the stable message id from an obexd object path. The path's
- // session number changes on every reconnect, so only the id can be used to
- // recognize a message we already have.
- std::string map_handle_from_path(const std::string& object_path);
-
- struct MapSessionState;
-
- // Drives org.bluez.obex.MessageAccess1 for one open OBEX session.
- class MapSession {
- public:
- // Called for each new or updated message.
- using MessageFn = std::function<void(const Message&)>;
-
- MapSession(GDBusConnection* session_bus, std::string session_path);
- ~MapSession();
-
- MapSession(const MapSession&) = delete;
- MapSession& operator=(const MapSession&) = delete;
-
- // Selects a MAP folder. SetFolder walks the hierarchy from the session
- // root, so this takes a path like "telecom/msg/inbox"
- bool set_folder(const std::string& folder, std::string& err);
-
- // Lists the current folder. `max` bounds the transfer
- std::vector<MapListing> list_messages(const std::string& folder, int max, std::string& err);
-
- // Fetches and parses the full bMessage for one handle
- bool fetch_bmessage(const std::string& message_path, BMessage& out, std::string& err);
-
- // Writes Message1.Read, which is reflected on the phone.
- bool set_read(const std::string& message_path, bool read, std::string& err);
-
- // Hands a built bMessage to the phone for delivery. `folder` is a MAP
- // path such as "telecom/msg/outbox".
- //
- // Success means the phone accepted the message, not that it was delivered.
- bool push_message(const std::string& folder, const std::string& bmessage, std::string& err);
-
- const std::string& path() const;
-
- private:
- std::unique_ptr<MapSessionState> state_;
- };
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/messages.hpp b/src/core/include/tether/bluetooth/messages.hpp
deleted file mode 100644
index 46fa556..0000000
--- a/src/core/include/tether/bluetooth/messages.hpp
+++ /dev/null
@@ -1,79 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/bmessage.hpp"
-
-#include <cstdint>
-#include <map>
-#include <nlohmann/json.hpp>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- struct Message {
- std::string handle;
- std::string object_path;
- std::string thread_key;
- std::string peer_address;
- // display only
- std::string peer_name;
- std::string body;
- int64_t timestamp = 0;
- bool outgoing = false;
- bool read = false;
- std::string folder;
-
- bool operator==(const Message&) const = default;
- };
-
- struct Thread {
- std::string key;
- // best display name seen for this peer, falling back to the address.
- std::string display_name;
- std::string peer_address;
- std::string last_body;
- int64_t last_timestamp = 0;
- int unread = 0;
- int count = 0;
- };
-
- // In-memory conversation store: dedupes by handle, groups into threads, and
- // tracks read state.
- class MessageStore {
- public:
- explicit MessageStore(size_t max_messages = 10000);
-
- // Returns false when the handle was already known, so callers can avoid
- // re-announcing a message the phone replayed.
- bool add(const Message& message);
-
- // Returns false when the handle is unknown or the state already matched,
- // so an echo of our own change does not loop.
- bool set_read(const std::string& handle, bool read);
-
- const Message* find(const std::string& handle) const;
-
- // Newest activity first.
- std::vector<Thread> threads() const;
- // Oldest first within a thread, limited to the most recent `limit`.
- std::vector<Message> messages(const std::string& thread_key, size_t limit = 200) const;
-
- size_t size() const { return by_handle_.size(); }
-
- private:
- void trim();
-
- size_t max_messages_;
- std::map<std::string, Message> by_handle_;
- // Insertion order, used to evict the oldest when the cap is reached.
- std::vector<std::string> order_;
- };
-
- nlohmann::json to_json(const Message& message);
- nlohmann::json to_json(const Thread& thread);
-
- // Builds a Message from a parsed bMessage plus the metadata MAP supplies
- // alongside it. `handle` and `folder` come from the MAP listing.
- Message message_from_bmessage(const BMessage& parsed, const std::string& handle, int64_t timestamp);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/monitor.hpp b/src/core/include/tether/bluetooth/monitor.hpp
deleted file mode 100644
index e898255..0000000
--- a/src/core/include/tether/bluetooth/monitor.hpp
+++ /dev/null
@@ -1,48 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/objects.hpp"
-
-#include <functional>
-#include <gio/gio.h>
-#include <memory>
-
-namespace tether::bluetooth {
-
- struct MonitorState;
-
- // Watches BlueZ on the system bus and keeps a current snapshot of its object tree.
- class BluezMonitor {
- public:
- BluezMonitor();
- ~BluezMonitor();
-
- BluezMonitor(const BluezMonitor&) = delete;
- BluezMonitor& operator=(const BluezMonitor&) = delete;
-
- // Connects to the system bus and starts the watcher thread. Returns false
- // if BlueZ is unreachable; the daemon runs on without Bluetooth support.
- bool start();
- void stop();
- bool running() const;
-
- // Level-triggered eventfd, readable whenever the snapshot has changed.
- // Register with EpollEventLoop::addFd and call drain() from the callback.
- int event_fd() const;
- void drain();
-
- BluezObjects snapshot() const;
- Capability capability() const;
-
- // Shared system-bus connection. GDBusConnection is thread-safe for call.
- GDBusConnection* connection() const;
-
- // Runs fn on the watcher thread and waits for it to finish.
- void invoke_sync(const std::function<void()>& fn);
-
- private:
- std::unique_ptr<MonitorState> impl_;
- };
-
- extern BluezMonitor* g_bluez;
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/obex_transfer.hpp b/src/core/include/tether/bluetooth/obex_transfer.hpp
deleted file mode 100644
index 15e63cf..0000000
--- a/src/core/include/tether/bluetooth/obex_transfer.hpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#pragma once
-
-#include <gio/gio.h>
-#include <string>
-
-namespace tether::bluetooth {
-
- // obexd removes a transfer object as soon as it finishes, so an object that
- // has disappeared is a normal terminal state rather than a failure.
- enum class TransferState { Active, Complete, Error, Gone };
-
- // Polls a transfer to completion. Returns Active only when the timeout ran
- // out with the transfer still in progress.
- TransferState wait_for_transfer(GDBusConnection* bus, const std::string& path, int timeout_seconds);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/objects.hpp b/src/core/include/tether/bluetooth/objects.hpp
deleted file mode 100644
index 7d34149..0000000
--- a/src/core/include/tether/bluetooth/objects.hpp
+++ /dev/null
@@ -1,114 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <glib.h>
-#include <nlohmann/json.hpp>
-#include <string>
-#include <vector>
-
-// Plain-data view of BlueZ's object tree, decoded from org.freedesktop.DBus
-// ObjectManager payloads. Deliberately free of any bus or threading concern so
-// it can be tested against recorded payloads.
-namespace tether::bluetooth {
-
- // Services the iPhone exposes that we care about
- inline constexpr const char* UUID_MAP_MAS = "00001132-0000-1000-8000-00805f9b34fb";
- inline constexpr const char* UUID_MAP_MNS = "00001133-0000-1000-8000-00805f9b34fb";
- inline constexpr const char* UUID_PBAP_PSE = "0000112f-0000-1000-8000-00805f9b34fb";
- inline constexpr const char* UUID_ANCS = "7905f431-b5ce-4e99-a40f-4b1e122d00d0";
-
- inline constexpr uint32_t COD_TARGET = 0x0408;
- inline constexpr uint32_t COD_MASK = 0x1fff;
-
- struct Adapter {
- std::string path;
- std::string address;
- std::string name;
- uint32_t device_class = 0;
- bool powered = false;
- std::vector<std::string> roles;
- // org.bluez.LEAdvertisingManager1 is a separate interface on the same object.
- bool has_advertising_manager = false;
- uint8_t advertising_instances = 0;
-
- bool has_role(const std::string& role) const;
- bool class_is_handsfree() const { return (device_class & COD_MASK) == COD_TARGET; }
-
- bool operator==(const Adapter&) const = default;
- };
-
- struct Device {
- std::string path;
- std::string adapter_path;
- std::string address;
- std::string name;
- bool paired = false;
- bool bonded = false;
- bool trusted = false;
- bool connected = false;
- std::vector<std::string> uuids;
-
- bool has_le_bearer = false;
- bool le_paired = false;
- bool le_bonded = false;
- bool le_connected = false;
-
- bool has_uuid(const std::string& uuid) const;
- bool supports_map() const { return has_uuid(UUID_MAP_MAS); }
- bool supports_pbap() const { return has_uuid(UUID_PBAP_PSE); }
- bool supports_ancs() const { return has_uuid(UUID_ANCS); }
- bool looks_like_iphone() const;
-
- bool operator==(const Device&) const = default;
- };
-
- struct BluezObjects {
- std::vector<Adapter> adapters;
- std::vector<Device> devices;
-
- // Whether bluetoothd was started with --experimental. Bearer.LE1 exists only under that flag
- bool experimental_api = false;
-
- const Adapter* find_adapter(const std::string& path) const;
- const Device* find_device(const std::string& path) const;
-
- bool operator==(const BluezObjects&) const = default;
- };
-
- // Whether the machine can carry ANCS, or only MAP and PBAP.
- enum class DeliveryMode { Blocked, Compatibility, Full };
-
- // Bearer.LE1 cannot be observed until something is bonded, so its absence is
- // only meaningful once a bond exists.
- enum class BearerApi { Unknown, Confirmed, Absent };
-
- struct Capability {
- DeliveryMode mode = DeliveryMode::Blocked;
- BearerApi bearer_api = BearerApi::Unknown;
- bool adapter_present = false;
- bool powered = false;
- bool le_central = false;
- bool le_peripheral = false;
- bool advertising = false;
- bool class_ok = false;
- // Human-readable explanations for anything short of full mode, shown verbatim
- std::vector<std::string> reasons;
-
- bool operator==(const Capability&) const = default;
- };
-
- const char* to_string(DeliveryMode mode);
- const char* to_string(BearerApi api);
-
- // Decodes an ObjectManager.GetManagedObjects reply, a{oa{sa{sv}}}. Accepts
- // either the raw reply tuple or the unwrapped dictionary. Returns an empty
- // result for null or unexpected input rather than throwing.
- BluezObjects parse_managed_objects(GVariant* reply);
-
- Capability resolve_capability(const BluezObjects& objects);
-
- nlohmann::json to_json(const Adapter& adapter);
- nlohmann::json to_json(const Device& device);
- nlohmann::json to_json(const Capability& capability);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/pairing.hpp b/src/core/include/tether/bluetooth/pairing.hpp
deleted file mode 100644
index b1b086e..0000000
--- a/src/core/include/tether/bluetooth/pairing.hpp
+++ /dev/null
@@ -1,50 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/config.hpp"
-
-#include <functional>
-#include <nlohmann/json.hpp>
-#include <string>
-
-namespace tether::bluetooth {
-
- class BluezMonitor;
-
- struct PairResult {
- bool success = false;
- // Machine-readable outcome: "paired", "already_paired", "not_found",
- // "rejected", "timeout", "busy", "error".
- std::string status;
- std::string message;
- std::string device_path;
- std::string device_address;
- // True when the resulting bond covers LE as well as BR/EDR.
- bool dual_bond = false;
- };
-
- // Reports progress steps so the CLI and GTK app can show what is happening
- // during a transaction that legitimately takes tens of seconds.
- using ProgressFn = std::function<void(const std::string& step, const std::string& detail)>;
-
- // Asks the user to confirm a six-digit numeric comparison code. Returns true
- // to accept. Runs on the monitor's GLib thread.
- using ConfirmFn = std::function<bool(const std::string& code)>;
-
- // Runs the full pairing transaction against `address`, blocking until it
- // resolves. Intended to be called from a worker thread: GDBusConnection is
- // thread-safe for calls, while the agent's callbacks land on the monitor's
- // GLib thread.
- PairResult pair_device(BluezMonitor& monitor,
- const std::string& address,
- AuthStrategy strategy,
- const ProgressFn& progress,
- const ConfirmFn& confirm);
-
- // Removes the bond so a clean pairing can be retried.
- PairResult unpair_device(BluezMonitor& monitor, const std::string& address);
-
- nlohmann::json to_json(const PairResult& result);
-
- bool confirm_with_dialog(const std::string& device_name, const std::string& code);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/pbap_session.hpp b/src/core/include/tether/bluetooth/pbap_session.hpp
deleted file mode 100644
index ddb1ad8..0000000
--- a/src/core/include/tether/bluetooth/pbap_session.hpp
+++ /dev/null
@@ -1,47 +0,0 @@
-#pragma once
-
-#include "tether/bluetooth/vcard.hpp"
-
-#include <gio/gio.h>
-#include <memory>
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- // Pulling a large phonebook is a real OBEX transfer.
- inline constexpr int PBAP_CALL_TIMEOUT_MS = 60000;
- inline constexpr int PBAP_TRANSFER_TIMEOUT_SECONDS = 60;
- inline constexpr int PBAP_FILE_GRACE_SECONDS = 3;
- inline constexpr int PBAP_MAX_CONTACTS = 5000;
-
- struct PbapSessionState;
-
- // Drives org.bluez.obex.PhonebookAccess1 for one open OBEX session.
- class PbapSession {
- public:
- PbapSession(GDBusConnection* session_bus, std::string session_path);
- ~PbapSession();
-
- PbapSession(const PbapSession&) = delete;
- PbapSession& operator=(const PbapSession&) = delete;
-
- // Selects the phonebook. This is PBAP's Select("int", "pb")
- // (not MAP's SetFolder)
- bool select_phonebook(std::string& err,
- const std::string& location = "int",
- const std::string& phonebook = "pb");
-
- // Pulls the selected phonebook and parses it.
- //
- // Uses PullAll's MaxCount filter. MaxListCount is MAP's option and makes a
- // PBAP transfer fail or return nothing at all.
- std::vector<VCard> pull_all(std::string& err, int max = PBAP_MAX_CONTACTS);
-
- const std::string& path() const;
-
- private:
- std::unique_ptr<PbapSessionState> state_;
- };
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/profile_supervisor.hpp b/src/core/include/tether/bluetooth/profile_supervisor.hpp
deleted file mode 100644
index 61472ad..0000000
--- a/src/core/include/tether/bluetooth/profile_supervisor.hpp
+++ /dev/null
@@ -1,86 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <string>
-
-namespace tether::bluetooth {
-
- // Poll fast until the first session opens, then slowly.
- inline constexpr int PROFILE_INITIAL_POLL_SECONDS = 5;
- inline constexpr int PROFILE_STEADY_POLL_SECONDS = 15;
-
- // Why an OBEX session could not be opened. Forbidden and Busy look alike from a distance, and reporting one as the
- // other sends the user off re-pairing for nothing.
- enum class ObexError {
- None,
- // OBEX Forbidden / 0x43: the iPhone's permission toggle is off. Not a pairing failure
- Forbidden,
- // Transport-level "Connection refused (111)": another computer probably
- // owns the iPhone's single MAP session. Keep polling; do not re-pair.
- Busy,
- // obexd's live SDP query found no MAS/PSE record. NOT a permissions failure. Recovers on its own once the phone
- // serves them again.
- NoRecord,
- // The phone is not reachable right now.
- Unavailable,
- Other,
- };
-
- const char* to_string(ObexError error);
-
- // Maps an obexd/D-Bus error message onto the cases above. Pure so the
- // classification can be pinned down by tests against real message text.
- ObexError classify_obex_error(const std::string& message);
-
- // Advice for the user, phrased so it can be shown verbatim.
- std::string obex_error_advice(ObexError error, const std::string& profile);
-
- // Session operations on obexd.
- class ProfileOps {
- public:
- virtual ~ProfileOps() = default;
-
- // Returns the new session's object path, or an empty string with err set.
- virtual std::string create_session(const std::string& target, std::string& err) = 0;
- virtual void remove_session(const std::string& path) = 0;
- };
-
- struct ProfileStatus {
- bool map_open = false;
- bool pbap_open = false;
- ObexError map_error = ObexError::None;
- ObexError pbap_error = ObexError::None;
- std::string reason;
-
- bool operator==(const ProfileStatus&) const = default;
- };
-
- // Keeps exactly one MAP and one PBAP session alive for the daemon's lifetime.
- class ProfileSupervisor {
- public:
- explicit ProfileSupervisor(ProfileOps& ops);
-
- // Drive periodically with a monotonic clock.
- bool tick(int64_t now, bool link_ready);
-
- // Drops both sessions after a disconnect so the next tick reopens them.
- void reset();
-
- const ProfileStatus& status() const { return status_; }
- const std::string& map_session() const { return map_path_; }
- const std::string& pbap_session() const { return pbap_path_; }
-
- private:
- bool open_profile(const std::string& target, std::string& path, ObexError& error, bool& retried);
-
- ProfileOps& ops_;
- ProfileStatus status_;
- std::string map_path_;
- std::string pbap_path_;
- bool map_retried_ = false;
- bool pbap_retried_ = false;
- int64_t next_attempt_ = 0;
- bool opened_once_ = false;
- };
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/bluetooth/vcard.hpp b/src/core/include/tether/bluetooth/vcard.hpp
deleted file mode 100644
index 30b8eb1..0000000
--- a/src/core/include/tether/bluetooth/vcard.hpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#pragma once
-
-#include <string>
-#include <vector>
-
-namespace tether::bluetooth {
-
- // One contact as PBAP delivers it.
- //
- // Name is display data. The tel and email lists are the identity keys, and a contact routinely has several of each.
- struct VCard {
- std::string name;
- std::vector<std::string> tels;
- std::vector<std::string> emails;
-
- bool empty() const { return name.empty() && tels.empty() && emails.empty(); }
- };
-
- // Parses a vCard 3.0 document containing any number of cards.
- std::vector<VCard> parse_vcards(const std::string& text);
-
- // Undoes RFC 2425 line folding: a line beginning with a space or tab
- // continues the previous one. Also normalizes CRLF to LF.
- std::vector<std::string> vcard_unfold(const std::string& text);
-
- // "TEL;TYPE=CELL:+15551234567" -> name "TEL", value "+15551234567".
- // Parameters after ';' are discarded; only the property name matters.
- bool vcard_split_property(const std::string& line, std::string& name, std::string& value);
-
- // vCard N is structured "Family;Given;Middle;Prefix;Suffix".
- std::string vcard_name_from_n(const std::string& value);
-
- // vCard 3.0 escapes \, \; \n and \\ in values.
- std::string vcard_unescape(const std::string& value);
-
-} // namespace tether::bluetooth
diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hpp
index fd1d616..644d110 100644
--- a/src/core/include/tether/net.hpp
+++ b/src/core/include/tether/net.hpp
@@ -3,7 +3,6 @@
#include "tether/event_loop.hpp"
#include <filesystem>
#include <map>
-#include <nlohmann/json.hpp>
#include <openssl/ssl.h>
#include <string>
#include <sys/types.h>
@@ -28,10 +27,6 @@ namespace tether {
void record_received_file(const std::filesystem::path& path, size_t bytes_written);
size_t broadcast_tcp_message(const std::string& msg, int exclude_fd = -1);
- // Bluetooth state, read from the BluezMonitor snapshot.
- nlohmann::json build_bt_status();
- nlohmann::json build_bt_devices();
-
class UnixServer {
public:
UnixServer(EpollEventLoop& loop);
diff --git a/src/core/src/bluetooth/advert.cpp b/src/core/src/bluetooth/advert.cpp
deleted file mode 100644
index 9075401..0000000
--- a/src/core/src/bluetooth/advert.cpp
+++ /dev/null
@@ -1,203 +0,0 @@
-#include "tether/bluetooth/advert.hpp"
-#include "tether/bluetooth/objects.hpp"
-#include "tether/log.hpp"
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* BLUEZ_NAME = "org.bluez";
- constexpr const char* ADVERT_PATH = "/org/tether/bt_advert";
- constexpr const char* ADVERT_MANAGER = "org.bluez.LEAdvertisingManager1";
-
- // Private/test identifiers that claim no Apple or hardware-vendor
- // identity, following the convention ancs4linux established. No meaning; they exist because the advert iOS
- // responds to carries them.
- constexpr guint16 INERT_MANUFACTURER_ID = 0xffff;
- constexpr const char* INERT_SERVICE_UUID = "00009999-0000-1000-8000-00805f9b34fb";
-
- // iOS needs the it running long enough to notice
- constexpr guint16 ADVERT_TIMEOUT_SECONDS = 180;
-
- constexpr const char* ADVERT_XML = R"XML(
-<node>
- <interface name='org.bluez.LEAdvertisement1'>
- <method name='Release'/>
- <property name='Type' type='s' access='read'/>
- <property name='SolicitUUIDs' type='as' access='read'/>
- <property name='ManufacturerData' type='a{qv}' access='read'/>
- <property name='ServiceData' type='a{sv}' access='read'/>
- <property name='Discoverable' type='b' access='read'/>
- <property name='Timeout' type='q' access='read'/>
- <property name='LocalName' type='s' access='read'/>
- </interface>
-</node>)XML";
-
- GVariant* inert_bytes() {
- const guint8 payload[] = {0x00};
- return g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, payload, sizeof(payload), sizeof(guint8));
- }
-
- void handle_method(GDBusConnection*,
- const gchar*,
- const gchar*,
- const gchar*,
- const gchar* method,
- GVariant*,
- GDBusMethodInvocation* invocation,
- gpointer) {
- // BlueZ calls Release when it drops the advertisement on its own.
- if (g_strcmp0(method, "Release") == 0)
- debug::log(INFO, "bluetooth: ANCS advertisement released by BlueZ");
- g_dbus_method_invocation_return_value(invocation, nullptr);
- }
-
- GVariant* handle_get_property(
- GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* name, GError**, gpointer) {
- const std::string prop = name ? name : "";
-
- if (prop == "Type")
- return g_variant_new_string("peripheral");
-
- if (prop == "SolicitUUIDs") {
- GVariantBuilder builder;
- g_variant_builder_init(&builder, G_VARIANT_TYPE("as"));
- g_variant_builder_add(&builder, "s", UUID_ANCS);
- return g_variant_builder_end(&builder);
- }
-
- if (prop == "ManufacturerData") {
- GVariantBuilder builder;
- g_variant_builder_init(&builder, G_VARIANT_TYPE("a{qv}"));
- g_variant_builder_add(&builder, "{qv}", INERT_MANUFACTURER_ID, inert_bytes());
- return g_variant_builder_end(&builder);
- }
-
- if (prop == "ServiceData") {
- GVariantBuilder builder;
- g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
- g_variant_builder_add(&builder, "{sv}", INERT_SERVICE_UUID, inert_bytes());
- return g_variant_builder_end(&builder);
- }
-
- if (prop == "Discoverable")
- return g_variant_new_boolean(TRUE);
-
- if (prop == "Timeout")
- return g_variant_new_uint16(ADVERT_TIMEOUT_SECONDS);
-
- if (prop == "LocalName")
- return g_variant_new_string("Tether");
-
- return nullptr;
- }
-
- const GDBusInterfaceVTable ADVERT_VTABLE = {handle_method, handle_get_property, nullptr, {nullptr}};
-
- } // namespace
-
- struct AdvertState {
- GDBusConnection* conn = nullptr;
- std::string adapter_path;
- guint registration_id = 0;
- bool registered_with_bluez = false;
- };
-
- AncsAdvertisement::AncsAdvertisement(GDBusConnection* connection, std::string adapter_path)
- : state_(std::make_unique<AdvertState>()) {
- state_->conn = connection;
- state_->adapter_path = std::move(adapter_path);
- }
-
- AncsAdvertisement::~AncsAdvertisement() {
- unregister_with_bluez();
- unexport_object();
- }
-
- bool AncsAdvertisement::active() const { return state_->registered_with_bluez; }
-
- bool AncsAdvertisement::export_object() {
- if (state_->registration_id != 0)
- return true;
-
- GError* error = nullptr;
- GDBusNodeInfo* info = g_dbus_node_info_new_for_xml(ADVERT_XML, &error);
- if (!info) {
- debug::log(ERR, "bluetooth: bad advertisement introspection: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
-
- state_->registration_id = g_dbus_connection_register_object(
- state_->conn, ADVERT_PATH, info->interfaces[0], &ADVERT_VTABLE, state_.get(), nullptr, &error);
- g_dbus_node_info_unref(info);
-
- if (state_->registration_id == 0) {
- debug::log(ERR, "bluetooth: cannot export advertisement: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
- return true;
- }
-
- bool AncsAdvertisement::register_with_bluez() {
- if (state_->registered_with_bluez)
- return true;
- if (state_->registration_id == 0)
- return false;
-
- GError* error = nullptr;
- GVariantBuilder options;
- g_variant_builder_init(&options, G_VARIANT_TYPE("a{sv}"));
- GVariant* reply = g_dbus_connection_call_sync(state_->conn,
- BLUEZ_NAME,
- state_->adapter_path.c_str(),
- ADVERT_MANAGER,
- "RegisterAdvertisement",
- g_variant_new("(oa{sv})", ADVERT_PATH, &options),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 10000,
- nullptr,
- &error);
- if (!reply) {
- debug::log(ERR, "bluetooth: RegisterAdvertisement failed: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
- g_variant_unref(reply);
-
- state_->registered_with_bluez = true;
- debug::log(INFO, "bluetooth: soliciting ANCS for {}s", ADVERT_TIMEOUT_SECONDS);
- return true;
- }
-
- void AncsAdvertisement::unregister_with_bluez() {
- if (state_->registered_with_bluez) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->conn,
- BLUEZ_NAME,
- state_->adapter_path.c_str(),
- ADVERT_MANAGER,
- "UnregisterAdvertisement",
- g_variant_new("(o)", ADVERT_PATH),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (reply)
- g_variant_unref(reply);
- g_clear_error(&error);
- state_->registered_with_bluez = false;
- }
- }
-
- void AncsAdvertisement::unexport_object() {
- if (state_->registration_id != 0) {
- g_dbus_connection_unregister_object(state_->conn, state_->registration_id);
- state_->registration_id = 0;
- }
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/agent.cpp b/src/core/src/bluetooth/agent.cpp
deleted file mode 100644
index 2e94afa..0000000
--- a/src/core/src/bluetooth/agent.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-#include "tether/bluetooth/agent.hpp"
-#include "tether/log.hpp"
-
-#include <algorithm>
-#include <array>
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* BLUEZ_NAME = "org.bluez";
- constexpr const char* AGENT_PATH = "/org/tether/bt_agent";
- constexpr const char* AGENT_MANAGER = "org.bluez.AgentManager1";
- // DisplayYesNo yields numeric comparison, the only method Tether supports.
- constexpr const char* AGENT_CAPABILITY = "DisplayYesNo";
-
- constexpr const char* AGENT_XML = R"XML(
-<node>
- <interface name='org.bluez.Agent1'>
- <method name='Release'/>
- <method name='RequestPinCode'>
- <arg type='o' name='device' direction='in'/>
- <arg type='s' name='pincode' direction='out'/>
- </method>
- <method name='DisplayPinCode'>
- <arg type='o' name='device' direction='in'/>
- <arg type='s' name='pincode' direction='in'/>
- </method>
- <method name='RequestPasskey'>
- <arg type='o' name='device' direction='in'/>
- <arg type='u' name='passkey' direction='out'/>
- </method>
- <method name='DisplayPasskey'>
- <arg type='o' name='device' direction='in'/>
- <arg type='u' name='passkey' direction='in'/>
- <arg type='q' name='entered' direction='in'/>
- </method>
- <method name='RequestConfirmation'>
- <arg type='o' name='device' direction='in'/>
- <arg type='u' name='passkey' direction='in'/>
- </method>
- <method name='RequestAuthorization'>
- <arg type='o' name='device' direction='in'/>
- </method>
- <method name='AuthorizeService'>
- <arg type='o' name='device' direction='in'/>
- <arg type='s' name='uuid' direction='in'/>
- </method>
- <method name='Cancel'/>
- </interface>
-</node>)XML";
-
- constexpr const char* ERROR_REJECTED = "org.bluez.Error.Rejected";
-
- bool iequals(const std::string& a, const std::string& b) {
- return a.size() == b.size() &&
- std::equal(a.begin(), a.end(), b.begin(), [](unsigned char x, unsigned char y) {
- return std::tolower(x) == std::tolower(y);
- });
- }
-
- } // namespace
-
- bool is_authorized_service(const std::string& uuid) {
- static const std::array<const char*, 5> allowed = {
- "0000112e-0000-1000-8000-00805f9b34fb", // PBAP client
- "0000112f-0000-1000-8000-00805f9b34fb", // PBAP server
- "00001132-0000-1000-8000-00805f9b34fb", // MAP server
- "00001133-0000-1000-8000-00805f9b34fb", // MAP notification server
- "00001134-0000-1000-8000-00805f9b34fb", // MAP client
- };
- return std::any_of(allowed.begin(), allowed.end(), [&](const char* u) { return iequals(uuid, u); });
- }
-
- std::string format_passkey(uint32_t passkey) {
- std::string digits = std::to_string(passkey % 1000000u);
- return std::string(6 - digits.size(), '0') + digits;
- }
-
- struct AgentState {
- GDBusConnection* conn = nullptr;
- std::string device_path;
- PairingAgent::ConfirmHandler on_confirm;
- std::string path = AGENT_PATH;
- guint registration_id = 0;
- bool registered_with_bluez = false;
- };
-
- namespace {
-
- void reject(GDBusMethodInvocation* invocation, const char* why) {
- g_dbus_method_invocation_return_dbus_error(invocation, ERROR_REJECTED, why);
- }
-
- void handle_method(GDBusConnection*,
- const gchar*,
- const gchar*,
- const gchar*,
- const gchar* method,
- GVariant* params,
- GDBusMethodInvocation* invocation,
- gpointer user_data) {
- auto* state = static_cast<AgentState*>(user_data);
- std::string name = method ? method : "";
-
- if (name == "Release") {
- g_dbus_method_invocation_return_value(invocation, nullptr);
- return;
- }
-
- if (name == "Cancel") {
- g_dbus_method_invocation_return_value(invocation, nullptr);
- return;
- }
-
- // Every remaining method names a device first. Refuse anything that is
- // not the device this agent was created for, so an unrelated phone or
- // headset cannot ride along on a pairing the user started.
- const gchar* device = nullptr;
- g_variant_get_child(params, 0, "&o", &device);
- const std::string device_path = device ? device : "";
- if (device_path != state->device_path) {
- debug::log(WARN, "bluetooth: agent refused {} for unexpected device {}", name, device_path);
- reject(invocation, "Not the device being paired");
- return;
- }
-
- if (name == "RequestPinCode" || name == "DisplayPinCode" || name == "RequestPasskey" ||
- name == "DisplayPasskey") {
- debug::log(WARN, "bluetooth: agent refused unsupported pairing method {}", name);
- reject(invocation, "Only numeric comparison pairing is supported");
- return;
- }
-
- if (name == "AuthorizeService") {
- const gchar* uuid = nullptr;
- g_variant_get_child(params, 1, "&s", &uuid);
- const std::string service = uuid ? uuid : "";
- if (!is_authorized_service(service)) {
- debug::log(INFO, "bluetooth: agent refused service {}", service);
- reject(invocation, "Service not used by Tether");
- return;
- }
- g_dbus_method_invocation_return_value(invocation, nullptr);
- return;
- }
-
- if (name == "RequestAuthorization") {
- // Pairing with no comparison to show the user. Accepting silently
- // would defeat the confirmation this agent exists to provide.
- reject(invocation, "Numeric comparison is required");
- return;
- }
-
- if (name == "RequestConfirmation") {
- guint32 passkey = 0;
- g_variant_get_child(params, 1, "u", &passkey);
-
- if (state->on_confirm && state->on_confirm(format_passkey(passkey)))
- g_dbus_method_invocation_return_value(invocation, nullptr);
- else
- reject(invocation, "Rejected by the user");
- return;
- }
-
- reject(invocation, "Unsupported method");
- }
-
- const GDBusInterfaceVTable AGENT_VTABLE = {handle_method, nullptr, nullptr, {nullptr}};
-
- } // namespace
-
- PairingAgent::PairingAgent(GDBusConnection* connection, std::string device_path, ConfirmHandler on_confirm)
- : state_(std::make_unique<AgentState>()) {
- state_->conn = connection;
- state_->device_path = std::move(device_path);
- state_->on_confirm = std::move(on_confirm);
- }
-
- PairingAgent::~PairingAgent() {
- unregister_with_bluez();
- unexport_object();
- }
-
- const std::string& PairingAgent::path() const { return state_->path; }
-
- bool PairingAgent::export_object() {
- if (state_->registration_id != 0)
- return true;
-
- GError* error = nullptr;
- GDBusNodeInfo* info = g_dbus_node_info_new_for_xml(AGENT_XML, &error);
- if (!info) {
- debug::log(ERR, "bluetooth: bad agent introspection: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
-
- state_->registration_id = g_dbus_connection_register_object(
- state_->conn, state_->path.c_str(), info->interfaces[0], &AGENT_VTABLE, state_.get(), nullptr, &error);
- g_dbus_node_info_unref(info);
-
- if (state_->registration_id == 0) {
- debug::log(ERR, "bluetooth: cannot export agent: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
- return true;
- }
-
- bool PairingAgent::register_with_bluez() {
- if (state_->registered_with_bluez)
- return true;
- if (state_->registration_id == 0)
- return false;
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->conn,
- BLUEZ_NAME,
- "/org/bluez",
- AGENT_MANAGER,
- "RegisterAgent",
- g_variant_new("(os)", state_->path.c_str(), AGENT_CAPABILITY),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- debug::log(ERR, "bluetooth: RegisterAgent failed: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
- g_variant_unref(reply);
- state_->registered_with_bluez = true;
-
- reply = g_dbus_connection_call_sync(state_->conn,
- BLUEZ_NAME,
- "/org/bluez",
- AGENT_MANAGER,
- "RequestDefaultAgent",
- g_variant_new("(o)", state_->path.c_str()),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- debug::log(WARN, "bluetooth: RequestDefaultAgent failed: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- // Keep going: pairing can still succeed if no other agent competes.
- } else {
- g_variant_unref(reply);
- }
- return true;
- }
-
- void PairingAgent::unregister_with_bluez() {
- if (state_->registered_with_bluez) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->conn,
- BLUEZ_NAME,
- "/org/bluez",
- AGENT_MANAGER,
- "UnregisterAgent",
- g_variant_new("(o)", state_->path.c_str()),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (reply)
- g_variant_unref(reply);
- g_clear_error(&error);
- state_->registered_with_bluez = false;
- }
- }
-
- void PairingAgent::unexport_object() {
- if (state_->registration_id != 0) {
- g_dbus_connection_unregister_object(state_->conn, state_->registration_id);
- state_->registration_id = 0;
- }
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/ancs/client.cpp b/src/core/src/bluetooth/ancs/client.cpp
deleted file mode 100644
index 9e195f1..0000000
--- a/src/core/src/bluetooth/ancs/client.cpp
+++ /dev/null
@@ -1,492 +0,0 @@
-#include "tether/bluetooth/ancs/client.hpp"
-#include "tether/bluetooth/ancs/sequencer.hpp"
-#include "tether/bluetooth/monitor.hpp"
-#include "tether/log.hpp"
-
-#include <ctime>
-#include <deque>
-#include <gio/gio.h>
-#include <mutex>
-
-namespace tether::bluetooth::ancs {
-
- namespace {
-
- constexpr const char* BLUEZ_NAME = "org.bluez";
- constexpr const char* IFACE_CHARACTERISTIC = "org.bluez.GattCharacteristic1";
- constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";
- constexpr const char* OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager";
-
- constexpr int CALL_TIMEOUT_MS = 10000;
-
- } // namespace
-
- struct AncsClientState {
- BluezMonitor* monitor = nullptr;
- AncsClient::NotificationFn on_notification;
- AncsClient::WithdrawFn on_withdraw;
- AncsClient::StatusFn on_status;
-
- std::string device_path;
- std::string notification_source_path;
- std::string control_point_path;
- std::string data_source_path;
-
- bool subscribed = false;
- bool ready = false;
- bool initial_sync = true;
- bool content_enabled = false;
- std::string reason = "Waiting for the iPhone's notification service.";
-
- int64_t next_discover = 0;
- int64_t next_subscribe = 0;
- int64_t next_probe = 0;
-
- // Filled on the GLib thread, drained on the caller's thread. Only these
- // two buffers cross the boundary.
- std::mutex inbox;
- std::deque<std::vector<uint8_t>> pending_source;
- std::deque<std::vector<uint8_t>> pending_data;
-
- guint source_signal = 0;
- guint data_signal = 0;
-
- NotificationRegistry registry;
- std::unique_ptr<ControlPointSequencer> sequencer;
-
- // UIDs whose attributes are being fetched, so a notification can be
- // rebuilt when its response lands.
- std::map<uint32_t, SourceEvent> in_progress;
-
- bool write_control_point(const std::vector<uint8_t>& payload);
- void set_status(bool now_ready, const std::string& text);
- bool discover();
- bool subscribe();
- void unsubscribe();
- void handle_source_event(const SourceEvent& event, int64_t now);
- void handle_response(const Request& request, const Response& response, int64_t now);
- };
-
- namespace {
-
- void on_properties_changed(GDBusConnection*,
- const gchar*,
- const gchar* object_path,
- const gchar*,
- const gchar*,
- GVariant* parameters,
- gpointer user_data) {
- auto* state = static_cast<AncsClientState*>(user_data);
- if (!state || !object_path)
- return;
-
- const gchar* iface = nullptr;
- GVariant* changed = nullptr;
- GVariantIter* invalidated = nullptr;
- g_variant_get(parameters, "(&s@a{sv}as)", &iface, &changed, &invalidated);
- if (invalidated)
- g_variant_iter_free(invalidated);
- if (!changed)
- return;
-
- GVariant* value = g_variant_lookup_value(changed, "Value", G_VARIANT_TYPE("ay"));
- g_variant_unref(changed);
- if (!value)
- return;
-
- gsize length = 0;
- const guchar* bytes = static_cast<const guchar*>(g_variant_get_fixed_array(value, &length, 1));
- if (bytes && length) {
- std::vector<uint8_t> copy(bytes, bytes + length);
- std::lock_guard<std::mutex> lock(state->inbox);
- if (state->notification_source_path == object_path)
- state->pending_source.push_back(std::move(copy));
- else if (state->data_source_path == object_path)
- state->pending_data.push_back(std::move(copy));
- }
- g_variant_unref(value);
- }
-
- } // namespace
-
- void AncsClientState::set_status(bool now_ready, const std::string& text) {
- if (ready == now_ready && reason == text)
- return;
- ready = now_ready;
- reason = text;
- if (on_status)
- on_status(ready, reason);
- }
-
- bool AncsClientState::write_control_point(const std::vector<uint8_t>& payload) {
- if (control_point_path.empty() || !monitor || !monitor->connection())
- return false;
-
- GVariantBuilder options;
- g_variant_builder_init(&options, G_VARIANT_TYPE("a{sv}"));
-
- GVariant* value =
- g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, payload.data(), payload.size(), sizeof(uint8_t));
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(monitor->connection(),
- BLUEZ_NAME,
- control_point_path.c_str(),
- IFACE_CHARACTERISTIC,
- "WriteValue",
- g_variant_new("(@aya{sv})", value, &options),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- const std::string message = error ? error->message : "unknown error";
- g_clear_error(&error);
- // Until the user approves the phone's prompt, the control point
- // refuses every write. That is a pending permission, not a fault.
- debug::log(WARN, "ancs: control point write failed: {}", message);
- return false;
- }
- g_variant_unref(reply);
- return true;
- }
-
- bool AncsClientState::discover() {
- if (!monitor || !monitor->connection() || device_path.empty())
- return false;
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(monitor->connection(),
- BLUEZ_NAME,
- "/",
- OBJECT_MANAGER,
- "GetManagedObjects",
- nullptr,
- G_VARIANT_TYPE("(a{oa{sa{sv}}})"),
- G_DBUS_CALL_FLAGS_NONE,
- CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- g_clear_error(&error);
- return false;
- }
-
- notification_source_path.clear();
- control_point_path.clear();
- data_source_path.clear();
-
- GVariant* objects = g_variant_get_child_value(reply, 0);
- GVariantIter iter;
- const gchar* path = nullptr;
- GVariant* interfaces = nullptr;
- g_variant_iter_init(&iter, objects);
- while (g_variant_iter_loop(&iter, "{&o@a{sa{sv}}}", &path, &interfaces)) {
- const std::string object_path = path ? path : "";
- // Characteristics live under the device that owns them.
- if (object_path.rfind(device_path + "/", 0) != 0)
- continue;
-
- GVariant* props = g_variant_lookup_value(interfaces, IFACE_CHARACTERISTIC, G_VARIANT_TYPE("a{sv}"));
- if (!props)
- continue;
-
- GVariant* uuid_value = g_variant_lookup_value(props, "UUID", G_VARIANT_TYPE_STRING);
- if (uuid_value) {
- const std::string uuid = g_variant_get_string(uuid_value, nullptr);
- if (uuid == UUID_NOTIFICATION_SOURCE)
- notification_source_path = object_path;
- else if (uuid == UUID_CONTROL_POINT)
- control_point_path = object_path;
- else if (uuid == UUID_DATA_SOURCE)
- data_source_path = object_path;
- g_variant_unref(uuid_value);
- }
- g_variant_unref(props);
- }
- g_variant_unref(objects);
- g_variant_unref(reply);
-
- // All three are needed. A partial tree means BlueZ is still enumerating.
- return !notification_source_path.empty() && !control_point_path.empty() && !data_source_path.empty();
- }
-
- bool AncsClientState::subscribe() {
- if (!monitor || !monitor->connection())
- return false;
-
- GDBusConnection* conn = monitor->connection();
- auto start_notify = [&](const std::string& path) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn,
- BLUEZ_NAME,
- path.c_str(),
- IFACE_CHARACTERISTIC,
- "StartNotify",
- nullptr,
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- // StartNotify can race GATT readiness even after the
- // characteristics appear, so this is retried rather than treated
- // as a reason to rediscover.
- const std::string message = error ? error->message : "unknown";
- g_clear_error(&error);
- debug::log(INFO, "ancs: StartNotify not ready yet ({})", message);
- return false;
- }
- g_variant_unref(reply);
- return true;
- };
-
- if (!start_notify(data_source_path))
- return false;
- if (!start_notify(notification_source_path))
- return false;
-
- monitor->invoke_sync([this] {
- GDBusConnection* bus = monitor->connection();
- if (!source_signal) {
- source_signal = g_dbus_connection_signal_subscribe(bus,
- BLUEZ_NAME,
- IFACE_PROPS,
- "PropertiesChanged",
- notification_source_path.c_str(),
- nullptr,
- G_DBUS_SIGNAL_FLAGS_NONE,
- on_properties_changed,
- this,
- nullptr);
- }
- if (!data_signal) {
- data_signal = g_dbus_connection_signal_subscribe(bus,
- BLUEZ_NAME,
- IFACE_PROPS,
- "PropertiesChanged",
- data_source_path.c_str(),
- nullptr,
- G_DBUS_SIGNAL_FLAGS_NONE,
- on_properties_changed,
- this,
- nullptr);
- }
- });
- return true;
- }
-
- void AncsClientState::unsubscribe() {
- if (!monitor || !monitor->connection())
- return;
- GDBusConnection* conn = monitor->connection();
- if (source_signal) {
- g_dbus_connection_signal_unsubscribe(conn, source_signal);
- source_signal = 0;
- }
- if (data_signal) {
- g_dbus_connection_signal_unsubscribe(conn, data_signal);
- data_signal = 0;
- }
- }
-
- void AncsClientState::handle_source_event(const SourceEvent& event, int64_t now) {
- (void)now;
- switch (registry.classify(event, initial_sync)) {
- case Decision::Ignore:
- registry.remember(event);
- return;
- case Decision::Withdraw:
- registry.forget(event.uid);
- if (on_withdraw)
- on_withdraw(event.uid);
- return;
- case Decision::Fetch:
- break;
- }
-
- std::vector<NotificationAttributeId> attributes{NotificationAttributeId::AppIdentifier};
- if (content_enabled) {
- attributes.push_back(NotificationAttributeId::Title);
- attributes.push_back(NotificationAttributeId::Subtitle);
- attributes.push_back(NotificationAttributeId::Message);
- }
-
- in_progress[event.uid] = event;
- registry.remember(event);
- if (!sequencer->submit(build_notification_request(event.uid, attributes)))
- in_progress.erase(event.uid);
- }
-
- void AncsClientState::handle_response(const Request& request, const Response& response, int64_t now) {
- if (response.command == CommandId::GetAppAttributes) {
- // The readiness probe: a Data Source answer proves the phone has
- // authorized notification access, which StartNotify alone does not.
- if (!ready)
- set_status(true, "Notification mirroring is active.");
- return;
- }
- if (response.command != CommandId::GetNotificationAttributes)
- return;
-
- auto found = in_progress.find(request.uid);
- if (found == in_progress.end())
- return;
- const SourceEvent event = found->second;
- in_progress.erase(found);
-
- Notification notification;
- notification.uid = request.uid;
- notification.app_id = response.attribute(static_cast<uint8_t>(NotificationAttributeId::AppIdentifier));
- notification.app_name = notification.app_id;
- notification.title = response.attribute(static_cast<uint8_t>(NotificationAttributeId::Title));
- notification.subtitle = response.attribute(static_cast<uint8_t>(NotificationAttributeId::Subtitle));
- notification.body = response.attribute(static_cast<uint8_t>(NotificationAttributeId::Message));
- notification.category = event.category;
- notification.silent = event.silent();
- notification.has_positive_action = event.has_positive_action();
- notification.has_negative_action = event.has_negative_action();
- notification.received = now;
-
- registry.store(notification);
- if (on_notification)
- on_notification(notification);
- }
-
- AncsClient::AncsClient(BluezMonitor& monitor,
- NotificationFn on_notification,
- WithdrawFn on_withdraw,
- StatusFn on_status)
- : state_(std::make_unique<AncsClientState>()) {
- state_->monitor = &monitor;
- state_->on_notification = std::move(on_notification);
- state_->on_withdraw = std::move(on_withdraw);
- state_->on_status = std::move(on_status);
-
- AncsClientState* raw = state_.get();
- state_->sequencer = std::make_unique<ControlPointSequencer>(
- [raw](const std::vector<uint8_t>& payload) { return raw->write_control_point(payload); },
- [raw](const Request& request, const Response& response) {
- raw->handle_response(request, response, static_cast<int64_t>(std::time(nullptr)));
- },
- [raw](const Request& request, const std::string& reason) {
- raw->in_progress.erase(request.uid);
- debug::log(WARN, "ancs: request failed: {}", reason);
- });
- }
-
- AncsClient::~AncsClient() {
- if (state_)
- state_->unsubscribe();
- }
-
- void AncsClient::set_device(const std::string& device_path) {
- if (state_->device_path == device_path)
- return;
-
- state_->unsubscribe();
- state_->device_path = device_path;
- state_->subscribed = false;
- state_->notification_source_path.clear();
- state_->control_point_path.clear();
- state_->data_source_path.clear();
- state_->next_discover = 0;
- state_->next_subscribe = 0;
- state_->next_probe = 0;
- state_->sequencer->reset();
- state_->in_progress.clear();
- // A new LE session replays the phone's backlog, so the next batch of
- // pre-existing notifications is a sync rather than news.
- state_->initial_sync = true;
- state_->registry.clear();
- {
- std::lock_guard<std::mutex> lock(state_->inbox);
- state_->pending_source.clear();
- state_->pending_data.clear();
- }
-
- if (device_path.empty())
- state_->set_status(false, "The iPhone is not connected over LE.");
- else
- state_->set_status(false, "Waiting for the iPhone's notification service.");
- }
-
- void AncsClient::set_content_enabled(bool enabled) { state_->content_enabled = enabled; }
-
- bool AncsClient::ready() const { return state_->ready; }
-
- const std::string& AncsClient::status_reason() const { return state_->reason; }
-
- const NotificationRegistry& AncsClient::registry() const { return state_->registry; }
-
- bool AncsClient::perform_action(uint32_t uid, ActionId action) {
- if (!state_->ready)
- return false;
- return state_->sequencer->submit(build_action_request(uid, action));
- }
-
- void AncsClient::tick(int64_t now) {
- auto* s = state_.get();
- if (s->device_path.empty())
- return;
-
- if (s->notification_source_path.empty()) {
- if (now < s->next_discover)
- return;
- s->next_discover = now + ANCS_RETRY_SECONDS;
- if (!s->discover()) {
- s->set_status(false, "Waiting for the iPhone's notification service.");
- return;
- }
- }
-
- if (!s->subscribed) {
- if (now < s->next_subscribe)
- return;
- s->next_subscribe = now + ANCS_RETRY_SECONDS;
- if (!s->subscribe()) {
- s->set_status(false, "Subscribing to the iPhone's notifications...");
- return;
- }
- s->subscribed = true;
- }
-
- // Drain what the GLib thread buffered.
- std::deque<std::vector<uint8_t>> source, data;
- {
- std::lock_guard<std::mutex> lock(s->inbox);
- source.swap(s->pending_source);
- data.swap(s->pending_data);
- }
-
- for (const auto& packet : data)
- s->sequencer->on_data_source(packet.data(), packet.size(), now);
-
- for (const auto& packet : source) {
- SourceEvent event;
- if (!parse_source_event(packet.data(), packet.size(), event)) {
- debug::log(WARN, "ancs: discarding a malformed notification packet");
- continue;
- }
- s->handle_source_event(event, now);
- }
-
- // The phone's backlog arrives immediately after subscribing, so once a
- // batch has been processed anything later is genuinely new.
- if (!source.empty())
- s->initial_sync = false;
-
- s->sequencer->tick(now);
-
- // A successful StartNotify proves only that the subscription exists, not
- // that iOS authorized notification access.
- if (!s->ready && now >= s->next_probe) {
- s->next_probe = now + ANCS_RETRY_SECONDS;
- s->set_status(false, "Waiting for notification access to be allowed on the iPhone.");
- s->sequencer->submit(build_app_request(APP_ID_MESSAGES));
- }
- }
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/src/bluetooth/ancs/notifications.cpp b/src/core/src/bluetooth/ancs/notifications.cpp
deleted file mode 100644
index edaf418..0000000
--- a/src/core/src/bluetooth/ancs/notifications.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-#include "tether/bluetooth/ancs/notifications.hpp"
-
-#include <algorithm>
-
-namespace tether::bluetooth::ancs {
-
- namespace {
- constexpr size_t MAX_RETAINED = 200;
- } // namespace
-
- Decision NotificationRegistry::classify(const SourceEvent& event, bool initial) const {
- if (event.event == EventId::Removed)
- return Decision::Withdraw;
-
- if (initial && event.pre_existing())
- return Decision::Ignore;
-
- if (event.event == EventId::Modified)
- return Decision::Fetch;
-
- return seen_.count(event.uid) ? Decision::Ignore : Decision::Fetch;
- }
-
- void NotificationRegistry::remember(const SourceEvent& event) { seen_[event.uid] = 0; }
-
- void NotificationRegistry::forget(uint32_t uid) {
- seen_.erase(uid);
- notifications_.erase(uid);
- order_.erase(std::remove(order_.begin(), order_.end(), uid), order_.end());
- }
-
- void NotificationRegistry::clear() {
- seen_.clear();
- notifications_.clear();
- order_.clear();
- }
-
- void NotificationRegistry::store(const Notification& notification) {
- if (!notifications_.count(notification.uid))
- order_.push_back(notification.uid);
- notifications_[notification.uid] = notification;
-
- while (order_.size() > MAX_RETAINED) {
- const uint32_t oldest = order_.front();
- order_.erase(order_.begin());
- notifications_.erase(oldest);
- }
- }
-
- const Notification* NotificationRegistry::find(uint32_t uid) const {
- auto it = notifications_.find(uid);
- return it == notifications_.end() ? nullptr : &it->second;
- }
-
- std::vector<Notification> NotificationRegistry::recent(size_t limit) const {
- std::vector<Notification> out;
- for (auto it = order_.rbegin(); it != order_.rend() && out.size() < limit; ++it) {
- auto found = notifications_.find(*it);
- if (found != notifications_.end())
- out.push_back(found->second);
- }
- return out;
- }
-
- bool should_show_desktop_popup(const Notification& notification) {
- if (notification.app_id == APP_ID_MESSAGES)
- return false;
- return !notification.silent;
- }
-
- nlohmann::json to_json(const Notification& notification) {
- return {
- {"uid", notification.uid},
- {"app_id", notification.app_id},
- {"app_name", notification.app_name},
- {"title", notification.title},
- {"subtitle", notification.subtitle},
- {"body", notification.body},
- {"category", static_cast<int>(notification.category)},
- {"timestamp", notification.received},
- {"silent", notification.silent},
- {"positive_action", notification.has_positive_action},
- {"negative_action", notification.has_negative_action},
- };
- }
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/src/bluetooth/ancs/parser.cpp b/src/core/src/bluetooth/ancs/parser.cpp
deleted file mode 100644
index c5a661a..0000000
--- a/src/core/src/bluetooth/ancs/parser.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-#include "tether/bluetooth/ancs/parser.hpp"
-
-namespace tether::bluetooth::ancs {
-
- std::string Response::attribute(uint8_t id) const {
- for (const auto& attribute : attributes) {
- if (attribute.id == id)
- return attribute.value;
- }
- return {};
- }
-
- bool parse_source_event(const uint8_t* data, size_t length, SourceEvent& out) {
- // exactly eight bytes
- if (!data || length != 8)
- return false;
-
- if (data[0] > static_cast<uint8_t>(EventId::Removed))
- return false;
-
- out.event = static_cast<EventId>(data[0]);
- out.flags = data[1];
- out.category = static_cast<CategoryId>(data[2]);
- out.category_count = data[3];
- out.uid = static_cast<uint32_t>(data[4]) | (static_cast<uint32_t>(data[5]) << 8) |
- (static_cast<uint32_t>(data[6]) << 16) | (static_cast<uint32_t>(data[7]) << 24);
- return true;
- }
-
- void DataSourceAssembler::expect(CommandId command, std::vector<uint8_t> attribute_ids) {
- expecting_ = true;
- command_ = command;
- attribute_ids_ = std::move(attribute_ids);
- buffer_.clear();
- }
-
- void DataSourceAssembler::reset() {
- expecting_ = false;
- attribute_ids_.clear();
- buffer_.clear();
- }
-
- DataSourceAssembler::Result
- DataSourceAssembler::append(const uint8_t* data, size_t length, Response& out, std::string& err) {
- if (!expecting_) {
- err = "Data Source fragment arrived with no request in flight.";
- return Result::Error;
- }
- if (data && length)
- buffer_.insert(buffer_.end(), data, data + length);
-
- if (buffer_.size() > MAX_RESPONSE_BYTES) {
- err = "Data Source response exceeded the size limit.";
- reset();
- return Result::Error;
- }
-
- Result result = parse(out, err);
- if (result == Result::Complete) {
- expecting_ = false;
- attribute_ids_.clear();
- buffer_.clear();
- } else if (result == Result::Error) {
- reset();
- }
- return result;
- }
-
- DataSourceAssembler::Result DataSourceAssembler::parse(Response& out, std::string& err) {
- size_t at = 0;
- const size_t size = buffer_.size();
-
- if (size < 1)
- return Result::NeedMore;
- if (buffer_[0] != static_cast<uint8_t>(command_)) {
- err = "Data Source response does not echo the requested command.";
- return Result::Error;
- }
- at = 1;
-
- Response response;
- response.command = command_;
-
- if (command_ == CommandId::GetNotificationAttributes) {
- if (size < at + 4)
- return Result::NeedMore;
- response.uid = static_cast<uint32_t>(buffer_[at]) | (static_cast<uint32_t>(buffer_[at + 1]) << 8) |
- (static_cast<uint32_t>(buffer_[at + 2]) << 16) |
- (static_cast<uint32_t>(buffer_[at + 3]) << 24);
- at += 4;
- } else if (command_ == CommandId::GetAppAttributes) {
- // A NUL-terminated identifier, which may still be arriving.
- size_t nul = at;
- while (nul < size && buffer_[nul] != 0)
- ++nul;
- if (nul >= size)
- return Result::NeedMore;
- response.app_id.assign(buffer_.begin() + static_cast<long>(at), buffer_.begin() + static_cast<long>(nul));
- at = nul + 1;
- } else {
- err = "Data Source response for a command that returns none.";
- return Result::Error;
- }
-
- // Attributes come back in the order they were requested, so the count is
- // what marks the end of a response that declares no length.
- for (uint8_t expected_id : attribute_ids_) {
- if (size < at + 3)
- return Result::NeedMore;
-
- const uint8_t id = buffer_[at];
- const uint16_t declared =
- static_cast<uint16_t>(buffer_[at + 1]) | static_cast<uint16_t>(buffer_[at + 2] << 8);
- at += 3;
-
- if (id != expected_id) {
- err = "Data Source returned attributes out of order.";
- return Result::Error;
- }
- if (declared > MAX_ATTRIBUTE_LENGTH) {
- err = "Data Source attribute claimed an implausible length.";
- return Result::Error;
- }
- if (size < at + declared)
- return Result::NeedMore;
-
- Attribute attribute;
- attribute.id = id;
- attribute.value.assign(buffer_.begin() + static_cast<long>(at),
- buffer_.begin() + static_cast<long>(at + declared));
- response.attributes.push_back(std::move(attribute));
- at += declared;
- }
-
- if (at != size) {
- err = "Data Source response had unexpected trailing bytes.";
- return Result::Error;
- }
-
- out = std::move(response);
- return Result::Complete;
- }
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/src/bluetooth/ancs/sequencer.cpp b/src/core/src/bluetooth/ancs/sequencer.cpp
deleted file mode 100644
index c22aa22..0000000
--- a/src/core/src/bluetooth/ancs/sequencer.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-#include "tether/bluetooth/ancs/sequencer.hpp"
-
-namespace tether::bluetooth::ancs {
-
- namespace {
-
- void append_u32_le(std::vector<uint8_t>& out, uint32_t value) {
- out.push_back(static_cast<uint8_t>(value & 0xff));
- out.push_back(static_cast<uint8_t>((value >> 8) & 0xff));
- out.push_back(static_cast<uint8_t>((value >> 16) & 0xff));
- out.push_back(static_cast<uint8_t>((value >> 24) & 0xff));
- }
-
- void append_u16_le(std::vector<uint8_t>& out, uint16_t value) {
- out.push_back(static_cast<uint8_t>(value & 0xff));
- out.push_back(static_cast<uint8_t>((value >> 8) & 0xff));
- }
-
- uint16_t cap_for(NotificationAttributeId id) {
- return id == NotificationAttributeId::Message ? MAX_BODY_LENGTH : MAX_TITLE_LENGTH;
- }
-
- } // namespace
-
- ControlPointSequencer::ControlPointSequencer(WriteFn write, CompleteFn on_complete, FailFn on_fail)
- : write_(std::move(write)), on_complete_(std::move(on_complete)), on_fail_(std::move(on_fail)) {}
-
- bool ControlPointSequencer::submit(Request request) {
- if (queue_.size() >= MAX_QUEUED_REQUESTS)
- return false;
- queue_.push_back(std::move(request));
- return true;
- }
-
- void ControlPointSequencer::start_next(int64_t now) {
- while (!in_flight_ && !queue_.empty()) {
- current_ = std::move(queue_.front());
- queue_.pop_front();
-
- const bool expects_response = !current_.attribute_ids.empty();
- if (expects_response) {
- assembler_.expect(current_.command, current_.attribute_ids);
- in_flight_ = true;
- deadline_ = now + REQUEST_TIMEOUT_SECONDS;
- }
-
- if (!write_ || !write_(current_.payload)) {
- in_flight_ = false;
- assembler_.reset();
- if (on_fail_)
- on_fail_(current_, "Could not write to the ANCS control point.");
- continue;
- }
-
- if (expects_response)
- return;
-
- if (on_complete_) {
- Response acknowledged;
- acknowledged.command = current_.command;
- acknowledged.uid = current_.uid;
- on_complete_(current_, acknowledged);
- }
- }
- }
-
- void ControlPointSequencer::tick(int64_t now) {
- if (in_flight_ && now >= deadline_) {
- Request timed_out = current_;
- in_flight_ = false;
- assembler_.reset();
- if (on_fail_)
- on_fail_(timed_out, "The phone did not answer within the timeout.");
- }
- start_next(now);
- }
-
- void ControlPointSequencer::on_data_source(const uint8_t* data, size_t length, int64_t now) {
- if (!in_flight_)
- return;
-
- Response response;
- std::string err;
- switch (assembler_.append(data, length, response, err)) {
- case DataSourceAssembler::Result::NeedMore:
- return;
- case DataSourceAssembler::Result::Complete: {
- Request done = current_;
- in_flight_ = false;
- if (on_complete_)
- on_complete_(done, response);
- break;
- }
- case DataSourceAssembler::Result::Error: {
- Request failed = current_;
- in_flight_ = false;
- if (on_fail_)
- on_fail_(failed, err);
- break;
- }
- }
- start_next(now);
- }
-
- void ControlPointSequencer::reset() {
- queue_.clear();
- in_flight_ = false;
- assembler_.reset();
- }
-
- Request build_notification_request(uint32_t uid, const std::vector<NotificationAttributeId>& attributes) {
- Request request;
- request.command = CommandId::GetNotificationAttributes;
- request.uid = uid;
-
- request.payload.push_back(static_cast<uint8_t>(CommandId::GetNotificationAttributes));
- append_u32_le(request.payload, uid);
- for (NotificationAttributeId id : attributes) {
- request.payload.push_back(static_cast<uint8_t>(id));
- // Only the three text attributes take a length, and for them it is
- // mandatory; sending one for the others corrupts the request.
- if (attribute_takes_length(id))
- append_u16_le(request.payload, cap_for(id));
- request.attribute_ids.push_back(static_cast<uint8_t>(id));
- }
- return request;
- }
-
- Request build_app_request(const std::string& app_id) {
- Request request;
- request.command = CommandId::GetAppAttributes;
-
- request.payload.push_back(static_cast<uint8_t>(CommandId::GetAppAttributes));
- request.payload.insert(request.payload.end(), app_id.begin(), app_id.end());
- request.payload.push_back(0);
- request.payload.push_back(static_cast<uint8_t>(AppAttributeId::DisplayName));
- request.attribute_ids.push_back(static_cast<uint8_t>(AppAttributeId::DisplayName));
- return request;
- }
-
- Request build_action_request(uint32_t uid, ActionId action) {
- Request request;
- request.command = CommandId::PerformNotificationAction;
- request.uid = uid;
-
- request.payload.push_back(static_cast<uint8_t>(CommandId::PerformNotificationAction));
- append_u32_le(request.payload, uid);
- request.payload.push_back(static_cast<uint8_t>(action));
-
- return request;
- }
-
-} // namespace tether::bluetooth::ancs
diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cpp
deleted file mode 100644
index cc6ed77..0000000
--- a/src/core/src/bluetooth/bearer_supervisor.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-#include "tether/bluetooth/bearer_supervisor.hpp"
-#include "tether/log.hpp"
-
-#include <algorithm>
-
-namespace tether::bluetooth {
-
- namespace {
-
- int grow_backoff(int current) {
- if (current <= 0)
- return BEARER_BACKOFF_MIN_SECONDS;
- return std::min(current * 2, BEARER_BACKOFF_MAX_SECONDS);
- }
-
- // BlueZ answers InProgress while one of its own connect operations is
- // still pending on the device. That clears on its own, unlike a refusal
- // from the phone, so backing off for minutes leaves the link down long
- // after the reason for it is gone.
- bool is_transient(const std::string& err) {
- return err.find("org.bluez.Error.InProgress") != std::string::npos;
- }
-
- int next_backoff(int current, const std::string& err) {
- return is_transient(err) ? BEARER_BACKOFF_MIN_SECONDS : grow_backoff(current);
- }
-
- } // namespace
-
- BearerSupervisor::BearerSupervisor(BearerOps& ops, bool ancs_enabled) : ops_(ops), ancs_enabled_(ancs_enabled) {}
-
- void BearerSupervisor::set_ancs_enabled(bool enabled) { ancs_enabled_ = enabled; }
-
- void BearerSupervisor::reset() {
- classic_connected_since_ = -1;
- next_classic_attempt_ = 0;
- next_le_attempt_ = 0;
- status_.classic_backoff = 0;
- status_.le_backoff = 0;
- }
-
- bool BearerSupervisor::tick(int64_t now) {
- BearerStatus previous = status_;
-
- status_.device_present = ops_.device_present();
- status_.device_paired = status_.device_present && ops_.device_paired();
- if (!status_.device_present || !status_.device_paired) {
- status_.classic_connected = false;
- status_.le_connected = false;
- status_.le_available = false;
- classic_connected_since_ = -1;
- status_.reason = status_.device_present ? "iPhone is not paired." : "iPhone not known to BlueZ.";
- return !(status_ == previous);
- }
-
- status_.classic_connected = ops_.classic_connected();
- status_.le_available = ops_.le_bearer_available();
- status_.le_connected = status_.le_available && ops_.le_connected();
-
- if (status_.classic_connected) {
- if (classic_connected_since_ < 0)
- classic_connected_since_ = now;
- status_.classic_backoff = 0;
- } else {
- // A dropped link invalidates the settle window and any LE state that
- // depended on it.
- classic_connected_since_ = -1;
- status_.le_connected = false;
-
- if (now >= next_classic_attempt_) {
- ops_.set_preferred_bearer("bredr");
- std::string err;
- if (ops_.connect_classic(err)) {
- status_.classic_backoff = 0;
- next_classic_attempt_ = 0;
- } else {
- status_.classic_backoff = next_backoff(status_.classic_backoff, err);
- next_classic_attempt_ = now + status_.classic_backoff;
- debug::log(
- WARN, "bluetooth: BR/EDR connect failed ({}), retrying in {}s", err, status_.classic_backoff);
- }
- }
- status_.reason = "Connecting to the iPhone over Bluetooth...";
- return !(status_ == previous);
- }
-
- // Classic is up. LE is only worth attempting once the ACL has settled.
- if (!ancs_enabled_) {
- status_.reason = "Connected. Notification mirroring is disabled.";
- return !(status_ == previous);
- }
-
- if (!status_.le_available) {
- status_.reason = "Connected. BlueZ is not exposing an LE bearer, so notifications are unavailable.";
- return !(status_ == previous);
- }
-
- if (!status_.le_connected) {
- const bool settled =
- classic_connected_since_ >= 0 && now - classic_connected_since_ >= BEARER_SETTLE_SECONDS;
- if (settled && now >= next_le_attempt_) {
- // Select LE only for this attempt, then hand the preference back
- // so LE is never left preferred while idle.
- ops_.set_preferred_bearer("le");
- std::string err;
- const bool ok = ops_.connect_le(err);
- ops_.set_preferred_bearer("bredr");
-
- if (ok) {
- status_.le_backoff = 0;
- next_le_attempt_ = 0;
- status_.le_connected = true;
- } else {
- status_.le_backoff = next_backoff(status_.le_backoff, err);
- next_le_attempt_ = now + status_.le_backoff;
- debug::log(WARN, "bluetooth: LE connect failed ({}), retrying in {}s", err, status_.le_backoff);
- }
- }
- if (!status_.le_connected) {
- status_.reason = "Connected. Bringing up the LE link for notifications...";
- return !(status_ == previous);
- }
- }
-
- status_.reason = "Connected over BR/EDR and LE.";
- return !(status_ == previous);
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/bmessage.cpp b/src/core/src/bluetooth/bmessage.cpp
deleted file mode 100644
index 3cdd221..0000000
--- a/src/core/src/bluetooth/bmessage.cpp
+++ /dev/null
@@ -1,440 +0,0 @@
-#include "tether/bluetooth/bmessage.hpp"
-#include "tether/bluetooth/vcard.hpp"
-
-#include <algorithm>
-#include <cctype>
-#include <cstdio>
-#include <ctime>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string trim(const std::string& text) {
- size_t begin = text.find_first_not_of(" \t\r\n");
- if (begin == std::string::npos)
- return {};
- size_t end = text.find_last_not_of(" \t\r\n");
- return text.substr(begin, end - begin + 1);
- }
-
- std::string upper(std::string text) {
- std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
- return static_cast<char>(std::toupper(c));
- });
- return text;
- }
-
- // Splits on LF and drops a trailing CR, so CRLF and LF payloads parse the
- // same way.
- std::vector<std::string> split_lines(const std::string& text) {
- std::vector<std::string> lines;
- size_t start = 0;
- while (start <= text.size()) {
- size_t nl = text.find('\n', start);
- if (nl == std::string::npos) {
- lines.push_back(text.substr(start));
- break;
- }
- std::string line = text.substr(start, nl - start);
- if (!line.empty() && line.back() == '\r')
- line.pop_back();
- lines.push_back(std::move(line));
- start = nl + 1;
- }
- return lines;
- }
-
- // The vCards embedded in a bMessage are the same grammar PBAP delivers,
- // so both share one implementation.
- using tether::bluetooth::vcard_name_from_n;
- using tether::bluetooth::vcard_split_property;
-
- // Reads one BEGIN:VCARD..END:VCARD block starting at `index`, which must
- // point at the BEGIN line. Leaves `index` on the END line.
- VCardParty read_vcard(const std::vector<std::string>& lines, size_t& index) {
- VCardParty party;
- std::string structured_name;
-
- for (++index; index < lines.size(); ++index) {
- const std::string line = trim(lines[index]);
- if (upper(line) == "END:VCARD")
- break;
-
- std::string name, value;
- if (!vcard_split_property(line, name, value) || value.empty())
- continue;
-
- if (name == "TEL" && party.tel.empty())
- party.tel = value;
- else if (name == "EMAIL" && party.email.empty())
- party.email = value;
- else if (name == "FN")
- party.name = value;
- else if (name == "N")
- structured_name = vcard_name_from_n(value);
- }
-
- if (party.name.empty())
- party.name = structured_name;
- return party;
- }
-
- // True when the line is a structural token possibly already behind some
- // stuffing spaces. Looking past every leading space, rather than just
- // one, is what makes stuffing and unstuffing exact inverses: a body line
- // of " BEGIN:MSG" is stuffed to " BEGIN:MSG" and has to come back with
- // its own space intact.
- bool is_stuffable_token(const std::string& line) {
- size_t at = line.find_first_not_of(' ');
- if (at == std::string::npos)
- return false;
- const std::string token = upper(line.substr(at));
- return token.rfind("BEGIN:", 0) == 0 || token.rfind("END:", 0) == 0;
- }
-
- // MAP byte-stuffing: a body line that would otherwise look like a
- // structural token is prefixed with a space by the sender.
- std::string unstuff(const std::string& line) {
- if (!line.empty() && line[0] == ' ' && is_stuffable_token(line))
- return line.substr(1);
- return line;
- }
-
- } // namespace
-
- BMessage parse_bmessage(const std::string& text) {
- BMessage message;
- if (text.empty())
- return message;
-
- const std::vector<std::string> lines = split_lines(text);
-
- bool seen_begin = false;
- int envelope_depth = 0;
- bool in_body = false;
- bool in_msg = false;
- std::vector<std::string> body_lines;
-
- for (size_t i = 0; i < lines.size(); ++i) {
- const std::string raw = lines[i];
- const std::string line = trim(raw);
- const std::string token = upper(line);
-
- // Inside MSG everything is payload until the closing token, so the
- // body is captured before any structural interpretation.
- //
- // The terminator must be matched against the *raw* line: byte-stuffing
- // marks a literal "END:MSG" in the body with a leading space, and
- // trimming first would make it end the body instead.
- if (in_msg) {
- const bool stuffed = !raw.empty() && raw[0] == ' ';
- if (!stuffed && token == "END:MSG") {
- in_msg = false;
- continue;
- }
- body_lines.push_back(unstuff(raw));
- continue;
- }
-
- if (token == "BEGIN:BMSG") {
- seen_begin = true;
- continue;
- }
- if (token == "END:BMSG")
- break;
- if (token == "BEGIN:BENV") {
- ++envelope_depth;
- continue;
- }
- if (token == "END:BENV") {
- if (envelope_depth > 0)
- --envelope_depth;
- continue;
- }
- if (token == "BEGIN:BBODY") {
- in_body = true;
- continue;
- }
- if (token == "END:BBODY") {
- in_body = false;
- continue;
- }
- if (token == "BEGIN:MSG") {
- in_msg = true;
- continue;
- }
-
- if (token == "BEGIN:VCARD") {
- VCardParty party = read_vcard(lines, i);
- // The originator sits outside BENV; recipients sit inside it.
- if (envelope_depth == 0) {
- if (message.originator.empty())
- message.originator = party;
- } else if (!party.empty()) {
- message.recipients.push_back(std::move(party));
- }
- continue;
- }
-
- if (in_body)
- continue;
-
- std::string name, value;
- if (!vcard_split_property(line, name, value))
- continue;
- if (name == "STATUS")
- message.read = upper(value) == "READ";
- else if (name == "TYPE")
- message.type = value;
- else if (name == "FOLDER")
- message.folder = value;
- }
-
- // Join without a trailing newline; the body is displayed, not re-emitted.
- for (size_t i = 0; i < body_lines.size(); ++i) {
- if (i)
- message.body += "\n";
- message.body += body_lines[i];
- }
- // Trailing blank lines are an artifact of the container, not content.
- while (!message.body.empty() && (message.body.back() == '\n' || message.body.back() == '\r'))
- message.body.pop_back();
-
- message.valid = seen_begin;
- return message;
- }
-
- std::string normalize_phone(const std::string& raw) {
- std::string out;
- bool first = true;
- for (char c : raw) {
- if (std::isdigit(static_cast<unsigned char>(c))) {
- out += c;
- } else if (c == '+' && first && out.empty()) {
- out += c;
- }
- if (!std::isspace(static_cast<unsigned char>(c)))
- first = false;
- }
- return out;
- }
-
- std::string normalize_email(const std::string& raw) {
- std::string out = trim(raw);
- std::transform(
- out.begin(), out.end(), out.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
- return out;
- }
-
- std::string thread_key_for(const VCardParty& party) {
- // A phone number wins when both are present: it is what the phone routes
- // SMS on, and it is the more stable of the two.
- if (!party.tel.empty()) {
- std::string tel = normalize_phone(party.tel);
- if (!tel.empty())
- return "tel:" + tel;
- }
- if (!party.email.empty()) {
- std::string email = normalize_email(party.email);
- if (!email.empty())
- return "email:" + email;
- }
- return {};
- }
-
- namespace {
-
- // Anything below 0x20, plus DEL. CR and LF are the injection vector, but
- // no control character has a legitimate place in an address.
- bool has_control_character(const std::string& text) {
- for (unsigned char c : text) {
- if (c < 0x20 || c == 0x7f)
- return true;
- }
- return false;
- }
-
- // ';' separates vCard parameters, ':' ends the property name, ',' and '\'
- // are value delimiters and the escape character.
- bool has_vcard_delimiter(const std::string& text) { return text.find_first_of(";:,\\") != std::string::npos; }
-
- // Longer than any real address; a bound keeps a pathological value from
- // reaching the phone at all.
- constexpr size_t MAX_ADDRESS_LENGTH = 254;
-
- // A line already beginning with spaces is stuffed again, so a body
- // containing " BEGIN:X" survives the receiver's unstuffing instead of
- // silently losing its leading space.
- bool line_needs_stuffing(const std::string& line) { return is_stuffable_token(line); }
-
- } // namespace
-
- bool validate_recipient(const Recipient& recipient, std::string& err_out) {
- const std::string& address = recipient.address;
-
- if (address.empty()) {
- err_out = "Recipient address is empty.";
- return false;
- }
- if (address.size() > MAX_ADDRESS_LENGTH) {
- err_out = "Recipient address is too long.";
- return false;
- }
- if (has_control_character(address)) {
- err_out = "Recipient address contains a control character.";
- return false;
- }
- if (has_vcard_delimiter(address)) {
- err_out = "Recipient address contains a vCard delimiter.";
- return false;
- }
-
- if (recipient.kind == RecipientKind::Tel) {
- bool digit = false;
- for (char c : address) {
- if (std::isdigit(static_cast<unsigned char>(c))) {
- digit = true;
- continue;
- }
- // The punctuation people actually write numbers with, and nothing
- // else. '+' is only meaningful leading, but it is harmless
- // anywhere and the phone is the authority on the rest.
- if (c == '+' || c == '-' || c == '(' || c == ')' || c == ' ' || c == '.')
- continue;
- err_out = "Phone number contains an unexpected character.";
- return false;
- }
- if (!digit) {
- err_out = "Phone number contains no digits.";
- return false;
- }
- return true;
- }
-
- const size_t at = address.find('@');
- if (at == std::string::npos || address.find('@', at + 1) != std::string::npos) {
- err_out = "Email address must contain exactly one '@'.";
- return false;
- }
- if (at == 0 || at + 1 >= address.size()) {
- err_out = "Email address is missing a local part or a domain.";
- return false;
- }
- if (address.find(' ') != std::string::npos) {
- err_out = "Email address contains a space.";
- return false;
- }
- return true;
- }
-
- bool recipient_from_thread_key(const std::string& thread_key, Recipient& out, std::string& err_out) {
- if (thread_key.rfind("tel:", 0) == 0) {
- out.kind = RecipientKind::Tel;
- out.address = thread_key.substr(4);
- } else if (thread_key.rfind("email:", 0) == 0) {
- out.kind = RecipientKind::Email;
- out.address = thread_key.substr(6);
- } else {
- err_out = "Unsupported conversation type; only one-to-one threads can be replied to.";
- return false;
- }
- return validate_recipient(out, err_out);
- }
-
- std::string stuff_body(const std::string& body) {
- std::string out;
- for (const std::string& line : split_lines(body)) {
- if (line_needs_stuffing(line))
- out += ' ';
- out += line;
- out += "\r\n";
- }
- // split_lines yields a trailing empty element for a body ending in a
- // newline; drop the extra break it would introduce.
- if (!body.empty() && body.back() != '\n' && out.size() >= 2)
- out.erase(out.size() - 2);
- return out;
- }
-
- std::string build_bmessage(const std::vector<Recipient>& recipients, const std::string& body) {
- if (recipients.empty())
- return {};
- for (const auto& recipient : recipients) {
- std::string err;
- if (!validate_recipient(recipient, err))
- return {};
- }
-
- const std::string stuffed = stuff_body(body);
- std::string message_block = "BEGIN:MSG\r\n";
- message_block += stuffed;
- if (!stuffed.empty())
- message_block += "\r\n";
- message_block += "END:MSG\r\n";
-
- std::string out;
- out += "BEGIN:BMSG\r\n";
- out += "VERSION:1.0\r\n";
- out += "STATUS:UNREAD\r\n";
- // Always SMS_GSM, even for an Apple-ID recipient; iOS picks the transport.
- out += "TYPE:SMS_GSM\r\n";
- out += "FOLDER:telecom/msg/outbox\r\n";
-
- // The originator vCard is empty and sits outside the envelope: the phone
- // fills in its own identity.
- out += "BEGIN:VCARD\r\n";
- out += "VERSION:3.0\r\n";
- out += "N:\r\n";
- out += "END:VCARD\r\n";
-
- out += "BEGIN:BENV\r\n";
- for (const auto& recipient : recipients) {
- out += "BEGIN:VCARD\r\n";
- out += "VERSION:3.0\r\n";
- out += "N:\r\n";
- out += (recipient.kind == RecipientKind::Tel ? "TEL:" : "EMAIL:");
- out += recipient.address;
- out += "\r\n";
- out += "END:VCARD\r\n";
- }
-
- out += "BEGIN:BBODY\r\n";
- out += "CHARSET:UTF-8\r\n";
- // LENGTH counts the whole message block, delimiters included.
- out += "LENGTH:" + std::to_string(message_block.size()) + "\r\n";
- out += message_block;
- out += "END:BBODY\r\n";
- out += "END:BENV\r\n";
- out += "END:BMSG\r\n";
- return out;
- }
-
- int64_t parse_map_timestamp(const std::string& text) {
- // Basic ISO 8601: YYYYMMDDTHHMMSS, optionally followed by Z or an offset.
- if (text.size() < 15 || text[8] != 'T')
- return 0;
-
- std::tm tm{};
- int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
- if (std::sscanf(text.c_str(), "%4d%2d%2dT%2d%2d%2d", &year, &month, &day, &hour, &minute, &second) != 6)
- return 0;
- if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 60)
- return 0;
-
- tm.tm_year = year - 1900;
- tm.tm_mon = month - 1;
- tm.tm_mday = day;
- tm.tm_hour = hour;
- tm.tm_min = minute;
- tm.tm_sec = second;
- tm.tm_isdst = -1;
-
- // A trailing Z means UTC; anything else is local time on the phone, which
- // is the same zone as the desktop in every case worth supporting.
- const bool utc = text.size() > 15 && (text[15] == 'Z' || text[15] == 'z');
- const std::time_t epoch = utc ? timegm(&tm) : std::mktime(&tm);
- return epoch == static_cast<std::time_t>(-1) ? 0 : static_cast<int64_t>(epoch);
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/config.cpp b/src/core/src/bluetooth/config.cpp
deleted file mode 100644
index 4919d31..0000000
--- a/src/core/src/bluetooth/config.cpp
+++ /dev/null
@@ -1,115 +0,0 @@
-#include "tether/bluetooth/config.hpp"
-#include "tether/log.hpp"
-
-#include <cstdlib>
-#include <filesystem>
-#include <fstream>
-#include <nlohmann/json.hpp>
-#include <pwd.h>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string home_dir() {
- if (const char* home = getenv("HOME"); home && *home)
- return home;
- if (const passwd* pw = getpwuid(getuid()); pw && pw->pw_dir)
- return pw->pw_dir;
- return {};
- }
-
- } // namespace
-
- const char* to_string(AuthStrategy strategy) {
- return strategy == AuthStrategy::ExplicitPair ? "explicit-pair" : "connect-first";
- }
-
- AuthStrategy auth_strategy_from_string(const std::string& value) {
- return value == "explicit-pair" ? AuthStrategy::ExplicitPair : AuthStrategy::ConnectFirst;
- }
-
- std::string config_path() {
- std::string home = home_dir();
- if (home.empty())
- return {};
- return (std::filesystem::path(home) / ".config" / "tether" / "bluetooth.json").string();
- }
-
- std::string serialize_config(const Config& config) {
- nlohmann::json j;
- j["device_address"] = config.device_address;
- j["auth_strategy"] = to_string(config.auth_strategy);
- j["ancs_enabled"] = config.ancs_enabled;
- j["ancs_content_enabled"] = config.ancs_content_enabled;
- j["group_messages_enabled"] = config.group_messages_enabled;
- return j.dump(2);
- }
-
- Config deserialize_config(const std::string& text) {
- Config config;
- try {
- auto j = nlohmann::json::parse(text);
- if (!j.is_object())
- return config;
- config.device_address = j.value("device_address", "");
- config.auth_strategy = auth_strategy_from_string(j.value("auth_strategy", ""));
- config.ancs_enabled = j.value("ancs_enabled", true);
- config.ancs_content_enabled = j.value("ancs_content_enabled", false);
- config.group_messages_enabled = j.value("group_messages_enabled", false);
- } catch (const std::exception&) {
- // A corrupt file must not stop the daemon; defaults are safe.
- }
- return config;
- }
-
- Config load_config() {
- std::string path = config_path();
- if (path.empty())
- return {};
- std::ifstream in(path);
- if (!in.is_open())
- return {};
- std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
- return deserialize_config(text);
- }
-
- bool save_config(const Config& config) {
- std::string path = config_path();
- if (path.empty())
- return false;
-
- std::error_code ec;
- std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec);
-
- // Write-then-rename so a crash mid-write cannot leave a truncated config,
- // matching how Crypto persists known_hosts.json.
- std::string tmp = path + ".tmp";
- {
- std::ofstream out(tmp, std::ios::trunc);
- if (!out.is_open()) {
- debug::log(ERR, "bluetooth: cannot write {}", tmp);
- return false;
- }
- out << serialize_config(config);
- if (!out) {
- debug::log(ERR, "bluetooth: failed writing {}", tmp);
- return false;
- }
- }
-
- std::filesystem::permissions(tmp,
- std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
- std::filesystem::perm_options::replace,
- ec);
- std::filesystem::rename(tmp, path, ec);
- if (ec) {
- debug::log(ERR, "bluetooth: cannot replace {}: {}", path, ec.message());
- std::filesystem::remove(tmp, ec);
- return false;
- }
- return true;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cpp
deleted file mode 100644
index c06b6bc..0000000
--- a/src/core/src/bluetooth/connection.cpp
+++ /dev/null
@@ -1,792 +0,0 @@
-#include "tether/bluetooth/connection.hpp"
-#include "tether/bluetooth/ancs/client.hpp"
-#include "tether/bluetooth/config.hpp"
-#include "tether/bluetooth/contacts.hpp"
-#include "tether/bluetooth/groups.hpp"
-#include "tether/bluetooth/journal.hpp"
-#include "tether/bluetooth/map_session.hpp"
-#include "tether/bluetooth/monitor.hpp"
-#include "tether/bluetooth/pbap_session.hpp"
-#include "tether/log.hpp"
-
-#include <atomic>
-#include <chrono>
-#include <condition_variable>
-#include <ctime>
-#include <gio/gio.h>
-#include <mutex>
-#include <thread>
-
-namespace tether::bluetooth {
-
- ConnectionManager* g_bt_connections = nullptr;
-
- namespace {
- MessageStore g_messages;
- std::mutex g_messages_mutex;
- MessageJournal g_journal;
- std::mutex g_map_mutex;
- std::shared_ptr<MapSession> g_map_session;
-
- std::mutex g_group_mutex;
- GroupCorrelator g_correlator;
- GroupRoster g_rosters;
- std::map<std::string, GroupInfo> g_group_info;
- std::atomic<bool> g_group_replies_enabled{false};
-
- // MAP folders are navigated from the session root one level at a time.
- constexpr const char* MAP_INBOX = "telecom/msg/inbox";
- constexpr const char* MAP_OUTBOX = "telecom/msg/outbox";
- } // namespace
-
- MessageStore& message_store() { return g_messages; }
- std::mutex& message_store_mutex() { return g_messages_mutex; }
-
- bool send_message(const std::string& thread_key, const std::string& body, Message& sent_out, std::string& err_out) {
- if (body.empty()) {
- err_out = "Nothing to send.";
- return false;
- }
-
- std::vector<Recipient> recipients;
- if (thread_key.rfind("group:", 0) == 0) {
- GroupInfo info;
- GroupRoster rosters;
- {
- std::lock_guard<std::mutex> lock(g_group_mutex);
- auto found = g_group_info.find(thread_key);
- if (found != g_group_info.end())
- info = found->second;
- rosters = g_rosters;
- }
- const ReplyEligibility eligibility = resolve_group_recipients(
- info, thread_key, contact_store(), rosters, g_group_replies_enabled, recipients, err_out);
- if (eligibility != ReplyEligibility::Allowed)
- return false;
- } else {
- Recipient recipient;
- if (!recipient_from_thread_key(thread_key, recipient, err_out))
- return false;
- recipients.push_back(recipient);
- }
-
- std::shared_ptr<MapSession> session;
- {
- std::lock_guard<std::mutex> lock(g_map_mutex);
- session = g_map_session;
- }
- if (!session) {
- err_out = "Messages are not connected.";
- return false;
- }
-
- const std::string bmessage = build_bmessage(recipients, body);
- if (bmessage.empty()) {
- err_out = "Could not build a message for this conversation.";
- return false;
- }
-
- if (!session->push_message(MAP_OUTBOX, bmessage, err_out))
- return false;
-
- Message sent;
- sent.handle = "local-" + std::to_string(std::time(nullptr)) + "-" + std::to_string(g_messages.size());
- sent.thread_key = thread_key;
- sent.peer_address = recipients.size() == 1 ? recipients.front().address : std::string{};
- sent.body = body;
- sent.timestamp = static_cast<int64_t>(std::time(nullptr));
- sent.outgoing = true;
- sent.read = true;
- sent.folder = "outbox";
-
- {
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- g_messages.add(sent);
- g_journal.append(sent);
- }
- sent_out = sent;
- return true;
- }
-
- void observe_message_notification(const std::string& sender,
- const std::string& subtitle,
- const std::string& body,
- int64_t now) {
- std::lock_guard<std::mutex> lock(g_group_mutex);
- g_correlator.observe({sender, subtitle, body, now});
- g_correlator.expire(now);
- }
-
- ReplyEligibility group_reply_status(const std::string& thread_key, std::string& reason) {
- GroupInfo info;
- GroupRoster rosters;
- {
- std::lock_guard<std::mutex> lock(g_group_mutex);
- auto found = g_group_info.find(thread_key);
- if (found != g_group_info.end())
- info = found->second;
- rosters = g_rosters;
- }
- std::vector<Recipient> recipients;
- return resolve_group_recipients(
- info, thread_key, contact_store(), rosters, g_group_replies_enabled, recipients, reason);
- }
-
- void set_group_replies_enabled(bool enabled) {
- std::lock_guard<std::mutex> lock(g_group_mutex);
- g_group_replies_enabled = enabled;
- }
-
- void reload_group_rosters() {
- std::lock_guard<std::mutex> lock(g_group_mutex);
- g_rosters = load_rosters();
- }
-
- bool mark_message_read(const std::string& handle, bool read, std::string& err_out) {
- std::shared_ptr<MapSession> session;
- {
- std::lock_guard<std::mutex> lock(g_map_mutex);
- session = g_map_session;
- }
- if (!session) {
- err_out = "Messages are not connected.";
- return false;
- }
-
- // The stored path is what obexd currently answers on. A message replayed
- // from the journal has none until the phone lists it again this session.
- std::string object_path;
- {
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- if (const Message* message = g_messages.find(handle))
- object_path = message->object_path;
- }
- if (object_path.empty()) {
- err_out = "That message is not available in the current session yet.";
- return false;
- }
-
- // write through to the phone first; only mirror locally once it took.
- if (!session->set_read(object_path, read, err_out))
- return false;
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- g_messages.set_read(handle, read);
- return true;
- }
-
- namespace {
-
- constexpr const char* BLUEZ_NAME = "org.bluez";
- constexpr const char* IFACE_DEVICE = "org.bluez.Device1";
- constexpr const char* IFACE_BEARER_LE = "org.bluez.Bearer.LE1";
- constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";
-
- constexpr const char* OBEX_NAME = "org.bluez.obex";
- constexpr const char* OBEX_ROOT = "/org/bluez/obex";
- constexpr const char* OBEX_CLIENT = "org.bluez.obex.Client1";
-
- constexpr int CONNECT_TIMEOUT_MS = 30000;
-
- constexpr int MESSAGE_POLL_SECONDS = 15;
- constexpr int MESSAGE_LIST_MAX = 200;
- constexpr int SUPERVISOR_TICK_SECONDS = 1;
-
- std::string normalize_address(std::string address) {
- for (char& c : address)
- c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
- return address;
- }
-
- // Bearer operations backed by BlueZ on the system bus.
- class BluezBearerOps : public BearerOps {
- public:
- BluezBearerOps(BluezMonitor& monitor, std::string address)
- : monitor_(monitor), address_(normalize_address(std::move(address))) {}
-
- void set_address(const std::string& address) { address_ = normalize_address(address); }
-
- bool device_present() const override { return lookup().has_value(); }
-
- bool device_paired() const override {
- auto device = lookup();
- return device && device->paired;
- }
-
- bool classic_connected() const override {
- auto device = lookup();
- return device && device->connected;
- }
-
- bool le_bearer_available() const override {
- auto device = lookup();
- return device && device->has_le_bearer;
- }
-
- bool le_connected() const override {
- auto device = lookup();
- return device && device->le_connected;
- }
-
- void set_preferred_bearer(const std::string& bearer) override {
- auto device = lookup();
- if (!device)
- return;
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(
- monitor_.connection(),
- BLUEZ_NAME,
- device->path.c_str(),
- IFACE_PROPS,
- "Set",
- g_variant_new("(ssv)", IFACE_DEVICE, "PreferredBearer", g_variant_new_string(bearer.c_str())),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (reply)
- g_variant_unref(reply);
- // Absent on older BlueZ; not having it is not an error.
- g_clear_error(&error);
- }
-
- bool connect_classic(std::string& err) override {
- auto device = lookup();
- if (!device) {
- err = "device not present";
- return false;
- }
- return call(device->path, IFACE_DEVICE, "Connect", err);
- }
-
- bool connect_le(std::string& err) override {
- auto device = lookup();
- if (!device) {
- err = "device not present";
- return false;
- }
- if (!device->has_le_bearer) {
- err = "no LE bearer";
- return false;
- }
- return call(device->path, IFACE_BEARER_LE, "Connect", err);
- }
-
- private:
- std::optional<Device> lookup() const {
- for (const auto& device : monitor_.snapshot().devices) {
- if (normalize_address(device.address) == address_)
- return device;
- }
- return std::nullopt;
- }
-
- bool call(const std::string& path, const char* iface, const char* method, std::string& err) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(monitor_.connection(),
- BLUEZ_NAME,
- path.c_str(),
- iface,
- method,
- nullptr,
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- CONNECT_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- err = error ? error->message : "unknown error";
- g_clear_error(&error);
- return false;
- }
- g_variant_unref(reply);
- return true;
- }
-
- BluezMonitor& monitor_;
- std::string address_;
- };
-
- // OBEX sessions live on the session bus, not the system bus.
- class ObexProfileOps : public ProfileOps {
- public:
- explicit ObexProfileOps(std::string address) : address_(normalize_address(std::move(address))) {}
-
- ~ObexProfileOps() override { g_clear_object(&conn_); }
-
- void set_address(const std::string& address) { address_ = normalize_address(address); }
-
- // The MAP session driver reuses this connection rather than opening a
- // second one to the same bus.
- GDBusConnection* bus() const { return conn_; }
-
- std::string create_session(const std::string& target, std::string& err) override {
- if (!ensure_connection(err))
- return {};
-
- GVariantBuilder args;
- g_variant_builder_init(&args, G_VARIANT_TYPE("a{sv}"));
- g_variant_builder_add(&args, "{sv}", "Target", g_variant_new_string(target.c_str()));
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn_,
- OBEX_NAME,
- OBEX_ROOT,
- OBEX_CLIENT,
- "CreateSession",
- g_variant_new("(sa{sv})", address_.c_str(), &args),
- G_VARIANT_TYPE("(o)"),
- G_DBUS_CALL_FLAGS_NONE,
- CONNECT_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- err = error ? error->message : "unknown error";
- g_clear_error(&error);
- return {};
- }
-
- const gchar* path = nullptr;
- g_variant_get(reply, "(&o)", &path);
- std::string session = path ? path : "";
- g_variant_unref(reply);
- return session;
- }
-
- void remove_session(const std::string& path) override {
- if (path.empty() || !conn_)
- return;
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn_,
- OBEX_NAME,
- OBEX_ROOT,
- OBEX_CLIENT,
- "RemoveSession",
- g_variant_new("(o)", path.c_str()),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (reply)
- g_variant_unref(reply);
- g_clear_error(&error);
- }
-
- private:
- bool ensure_connection(std::string& err) {
- if (conn_)
- return true;
- GError* error = nullptr;
- conn_ = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error);
- if (!conn_) {
- err = std::string("session bus unavailable: ") + (error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
- return true;
- }
-
- GDBusConnection* conn_ = nullptr;
- std::string address_;
- };
-
- } // namespace
-
- struct ConnectionState {
- BluezMonitor* monitor = nullptr;
- ConnectionManager::StatusFn on_change;
- ConnectionManager::MessageFn on_message;
-
- std::unique_ptr<BluezBearerOps> bearer_ops;
- std::unique_ptr<ObexProfileOps> profile_ops;
- std::unique_ptr<BearerSupervisor> bearers;
- std::unique_ptr<ProfileSupervisor> profiles;
-
- std::thread thread;
- std::atomic<bool> running{false};
- std::mutex mutex;
- std::condition_variable wake;
-
- std::string address;
- bool ancs_enabled = true;
- bool link_was_ready = false;
- int64_t next_message_poll = 0;
- std::string open_map_path;
- // The first listing on a new MAP session returns the phone's existing
- // inbox, which on a first run is every message it holds.
- bool map_session_backfill = true;
- std::string pulled_pbap_path;
-
- std::unique_ptr<ancs::AncsClient> ancs_client;
- ConnectionManager::NotificationFn on_notification;
- ConnectionManager::WithdrawFn on_withdraw;
- bool ancs_ready = false;
- std::string ancs_reason;
-
- void run();
- void sync_messages(int64_t now);
- void sync_contacts();
- void sync_ancs(int64_t now);
- nlohmann::json status_payload() const;
- // Hands the status to the subscriber only when it differs from the last
- // one published. The supervisors report their own internal transitions
- // as changes, and most of those are invisible in the payload, so without
- // this a subscriber receives the same status every few seconds.
- void publish();
-
- // Guards last_published: publish() is reached from the supervisor thread
- // and from the ANCS readiness callback on the GLib thread.
- std::mutex publish_mutex;
- nlohmann::json last_published;
- };
-
- void ConnectionState::publish() {
- if (!on_change)
- return;
-
- nlohmann::json payload = status_payload();
- {
- std::lock_guard<std::mutex> lock(publish_mutex);
- if (payload == last_published)
- return;
- last_published = payload;
- }
- on_change(payload);
- }
-
- nlohmann::json ConnectionState::status_payload() const {
- nlohmann::json payload = to_json(bearers->status(), profiles->status());
- payload["ancs_ready"] = ancs_ready;
- payload["ancs_reason"] = ancs_reason;
- return payload;
- }
-
- nlohmann::json to_json(const BearerStatus& bearer, const ProfileStatus& profiles) {
- return {
- {"command", "bt_connection_changed"},
- {"device_present", bearer.device_present},
- {"device_paired", bearer.device_paired},
- {"classic_connected", bearer.classic_connected},
- {"le_available", bearer.le_available},
- {"le_connected", bearer.le_connected},
- {"map_open", profiles.map_open},
- {"pbap_open", profiles.pbap_open},
- {"map_error", to_string(profiles.map_error)},
- {"pbap_error", to_string(profiles.pbap_error)},
- // Two independent halves, so both reasons are reported; the UI shows
- // whichever is actionable.
- {"link_reason", bearer.reason},
- {"profile_reason", profiles.reason},
- };
- }
-
- // Pulls the inbox and folds it into the store, announcing anything new.
- //
- // ponytail: polling only. MAP's notification service would push new mail
- // instead, but obexd surfaces it as ObjectManager signals on the session bus,
- // which is a second watcher to build and maintain. Dedupe by handle makes
- // polling correct either way; add MNS if the poll latency proves annoying.
- void ConnectionState::sync_messages(int64_t now) {
- if (!profiles->status().map_open) {
- if (!open_map_path.empty()) {
- std::lock_guard<std::mutex> lock(g_map_mutex);
- g_map_session.reset();
- open_map_path.clear();
- }
- return;
- }
-
- if (open_map_path != profiles->map_session()) {
- open_map_path = profiles->map_session();
- auto session = std::make_shared<MapSession>(profile_ops->bus(), open_map_path);
- {
- std::lock_guard<std::mutex> lock(g_map_mutex);
- g_map_session = session;
- }
- // A freshly opened session starts at the root, and SetFolder walks the
- // MAP hierarchy from there — "inbox" on its own is not a valid step.
- std::string err;
- if (!session->set_folder(MAP_INBOX, err))
- debug::log(WARN, "bluetooth: SetFolder({}) failed: {}", MAP_INBOX, err);
- next_message_poll = 0;
- map_session_backfill = true;
- }
-
- if (now < next_message_poll)
- return;
- next_message_poll = now + MESSAGE_POLL_SECONDS;
-
- std::shared_ptr<MapSession> session;
- {
- std::lock_guard<std::mutex> lock(g_map_mutex);
- session = g_map_session;
- }
- if (!session)
- return;
-
- std::string err;
- // Empty means the current folder, which SetFolder already selected.
- auto listings = session->list_messages("", MESSAGE_LIST_MAX, err);
- if (!err.empty()) {
- debug::log(WARN, "bluetooth: ListMessages failed: {}", err);
- return;
- }
-
- std::vector<Message> fresh;
- {
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- for (const auto& listing : listings) {
- Message message = message_from_listing(listing);
- if (message.thread_key.empty())
- continue;
-
- // MAP gives a group message one sender and no conversation
- // identifier. The correlated Messages notification is the only
- // side channel, and an ambiguous match is refused rather than
- // guessed: filing it wrongly would also aim a reply wrongly.
- if (g_group_replies_enabled) {
- GroupInfo info;
- std::lock_guard<std::mutex> group_lock(g_group_mutex);
- if (g_correlator.correlate(message.body, now, info) == Correlation::Matched) {
- const std::string key = group_thread_key(info);
- if (!key.empty()) {
- // The sender label is display only and never becomes
- // part of the thread identity or the reply route.
- message.peer_name = info.sender;
- message.thread_key = key;
- g_group_info[key] = info;
- }
- }
- }
- if (g_messages.add(message))
- fresh.push_back(message);
- else
- g_messages.set_read(message.handle, message.read);
- }
- }
-
- const bool backfill = map_session_backfill;
- map_session_backfill = false;
-
- for (const auto& message : fresh) {
- {
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- g_journal.append(message);
- }
- if (on_message)
- on_message(message, backfill);
- }
- }
-
- // Pulls the phonebook once per PBAP session. Contacts change far more slowly
- // than messages, and a full pull is an expensive transfer to repeat.
- void ConnectionState::sync_contacts() {
- if (!profiles->status().pbap_open) {
- pulled_pbap_path.clear();
- return;
- }
- if (pulled_pbap_path == profiles->pbap_session())
- return;
- pulled_pbap_path = profiles->pbap_session();
-
- PbapSession session(profile_ops->bus(), pulled_pbap_path);
- std::string err;
- if (!session.select_phonebook(err)) {
- debug::log(WARN, "bluetooth: PBAP Select failed: {}", err);
- return;
- }
-
- auto contacts = session.pull_all(err);
- if (!err.empty()) {
- debug::log(WARN, "bluetooth: PBAP PullAll failed: {}", err);
- return;
- }
-
- {
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- contact_store().set(std::move(contacts));
- }
- save_contacts(contact_store());
- debug::log(INFO, "bluetooth: pulled {} contacts", contact_store().size());
- }
-
- // Keeps the ANCS client pointed at the LE session and drains its work.
- void ConnectionState::sync_ancs(int64_t now) {
- if (!ancs_client)
- return;
-
- // ANCS rides the LE bearer. Without it there is nothing to talk to, and
- // pointing the client at an empty path is what makes it forget a session
- // that no longer exists.
- std::string device_path;
- if (bearers->status().le_connected) {
- auto objects = monitor->snapshot();
- for (const auto& device : objects.devices) {
- if (device.address == address || normalize_address(device.address) == normalize_address(address)) {
- device_path = device.path;
- break;
- }
- }
- }
-
- ancs_client->set_device(device_path);
- ancs_client->tick(now);
- }
-
- void ConnectionState::run() {
- using namespace std::chrono;
- const auto started = steady_clock::now();
-
- while (running) {
- const int64_t now = duration_cast<seconds>(steady_clock::now() - started).count();
-
- bool changed = bearers->tick(now);
- const bool link_ready = bearers->status().classic_connected;
-
- // A dropped Classic link invalidates every OBEX session on top of it.
- if (link_was_ready && !link_ready) {
- profiles->reset();
- changed = true;
- }
- link_was_ready = link_ready;
-
- changed = profiles->tick(now, link_ready) || changed;
-
- if (changed)
- publish();
-
- sync_contacts();
- sync_messages(now);
- sync_ancs(now);
-
- std::unique_lock<std::mutex> lock(mutex);
- wake.wait_for(lock, seconds(SUPERVISOR_TICK_SECONDS), [this] { return !running; });
- }
- }
-
- ConnectionManager::ConnectionManager(BluezMonitor& monitor, StatusFn on_change, MessageFn on_message)
- : state_(std::make_unique<ConnectionState>()) {
- state_->monitor = &monitor;
- state_->on_change = std::move(on_change);
- state_->on_message = std::move(on_message);
- }
-
- ConnectionManager::~ConnectionManager() { stop(); }
-
- bool ConnectionManager::start(const std::string& address, bool ancs_enabled) {
- if (state_->running)
- return true;
- if (address.empty()) {
- debug::log(INFO, "bluetooth: no paired iPhone selected; supervision idle");
- return false;
- }
-
- state_->address = address;
- state_->ancs_enabled = ancs_enabled;
-
- // Replay history before the first poll so the store is never briefly
- // empty, and so previously seen handles dedupe instead of re-announcing.
- {
- std::lock_guard<std::mutex> lock(g_messages_mutex);
- contact_store() = load_contacts();
- if (g_journal.open()) {
- const int64_t now = static_cast<int64_t>(std::time(nullptr));
- auto history = g_journal.load(now);
- for (const auto& message : history)
- g_messages.add(message);
- // load() already applied retention, so writing back what survived
- // is what actually trims the file. Idempotent when nothing aged out.
- g_journal.compact(history);
- debug::log(INFO, "bluetooth: replayed {} message(s) from the journal", history.size());
- }
- }
- state_->bearer_ops = std::make_unique<BluezBearerOps>(*state_->monitor, address);
- state_->profile_ops = std::make_unique<ObexProfileOps>(address);
- state_->bearers = std::make_unique<BearerSupervisor>(*state_->bearer_ops, ancs_enabled);
- state_->profiles = std::make_unique<ProfileSupervisor>(*state_->profile_ops);
-
- // Only built when the caller can actually show notifications and the
- // bond can carry them.
- if (ancs_enabled && state_->on_notification) {
- auto* raw = state_.get();
- state_->ancs_client = std::make_unique<ancs::AncsClient>(
- *state_->monitor,
- [raw](const ancs::Notification& notification) {
- if (raw->on_notification)
- raw->on_notification(notification);
- },
- [raw](uint32_t uid) {
- if (raw->on_withdraw)
- raw->on_withdraw(uid);
- },
- [raw](bool ready, const std::string& reason) {
- raw->ancs_ready = ready;
- raw->ancs_reason = reason;
- debug::log(INFO, "ancs: {}", reason);
- raw->publish();
- });
- state_->ancs_client->set_content_enabled(load_config().ancs_content_enabled);
- }
-
- state_->running = true;
- state_->thread = std::thread([this] { state_->run(); });
- debug::log(INFO, "bluetooth: supervising {} (ANCS {})", address, ancs_enabled ? "enabled" : "disabled");
- return true;
- }
-
- void ConnectionManager::stop() {
- if (!state_->running && !state_->thread.joinable())
- return;
- {
- std::lock_guard<std::mutex> lock(state_->mutex);
- state_->running = false;
- }
- state_->wake.notify_all();
- if (state_->thread.joinable())
- state_->thread.join();
- }
-
- void ConnectionManager::set_notification_handlers(NotificationFn on_notification, WithdrawFn on_withdraw) {
- state_->on_notification = std::move(on_notification);
- state_->on_withdraw = std::move(on_withdraw);
- }
-
- bool ConnectionManager::perform_notification_action(uint32_t uid, ancs::ActionId action) {
- return state_->ancs_client && state_->ancs_client->perform_action(uid, action);
- }
-
- nlohmann::json ConnectionManager::notifications(size_t limit) const {
- nlohmann::json out = nlohmann::json::array();
- if (!state_->ancs_client)
- return out;
- for (const auto& notification : state_->ancs_client->registry().recent(limit))
- out.push_back(ancs::to_json(notification));
- return out;
- }
-
- void ConnectionManager::set_device(const std::string& address, bool ancs_enabled) {
- // Restarting is simpler than mutating supervisor state under the worker,
- // and selecting a device is rare.
- stop();
- state_->running = false;
- start(address, ancs_enabled);
- }
-
- nlohmann::json ConnectionManager::status() const {
- if (!state_->bearers || !state_->profiles) {
- nlohmann::json idle;
- idle["command"] = "bt_connection_changed";
- idle["device_present"] = false;
- idle["device_paired"] = false;
- idle["link_reason"] = "No paired iPhone selected.";
- idle["profile_reason"] = "";
- return idle;
- }
- nlohmann::json payload = to_json(state_->bearers->status(), state_->profiles->status());
- payload["ancs_ready"] = state_->ancs_ready;
- payload["ancs_reason"] = state_->ancs_reason;
- return payload;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/contacts.cpp b/src/core/src/bluetooth/contacts.cpp
deleted file mode 100644
index 6a599af..0000000
--- a/src/core/src/bluetooth/contacts.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-#include "tether/bluetooth/contacts.hpp"
-#include "tether/bluetooth/bmessage.hpp"
-#include "tether/log.hpp"
-
-#include <algorithm>
-#include <cctype>
-#include <cstdlib>
-#include <filesystem>
-#include <fstream>
-#include <pwd.h>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string home_dir() {
- if (const char* home = getenv("HOME"); home && *home)
- return home;
- if (const passwd* pw = getpwuid(getuid()); pw && pw->pw_dir)
- return pw->pw_dir;
- return {};
- }
-
- } // namespace
-
- void ContactStore::set(std::vector<VCard> contacts) {
- contacts_ = std::move(contacts);
- by_key_.clear();
-
- for (const auto& card : contacts_) {
- if (card.name.empty())
- continue;
- for (const auto& tel : card.tels) {
- std::string normalized = normalize_phone(tel);
- if (!normalized.empty())
- by_key_.emplace("tel:" + normalized, card.name);
- }
- for (const auto& email : card.emails) {
- std::string normalized = normalize_email(email);
- if (!normalized.empty())
- by_key_.emplace("email:" + normalized, card.name);
- }
- }
- }
-
- std::string ContactStore::name_for(const std::string& thread_key) const {
- auto it = by_key_.find(thread_key);
- return it == by_key_.end() ? std::string{} : it->second;
- }
-
- std::vector<std::string> ContactStore::addresses_for_name(const std::string& name) const {
- std::vector<std::string> out;
- if (name.empty())
- return out;
-
- std::string wanted = name;
- std::transform(wanted.begin(), wanted.end(), wanted.begin(), [](unsigned char c) {
- return static_cast<char>(std::tolower(c));
- });
-
- for (const auto& card : contacts_) {
- std::string candidate = card.name;
- std::transform(candidate.begin(), candidate.end(), candidate.begin(), [](unsigned char c) {
- return static_cast<char>(std::tolower(c));
- });
- if (candidate != wanted)
- continue;
-
- // A phone number is what Messages routes on, so it wins when a
- // contact has both.
- for (const auto& tel : card.tels) {
- std::string normalized = normalize_phone(tel);
- if (!normalized.empty())
- out.push_back("tel:" + normalized);
- }
- for (const auto& email : card.emails) {
- std::string normalized = normalize_email(email);
- if (!normalized.empty())
- out.push_back("email:" + normalized);
- }
- }
- return out;
- }
-
- std::string contacts_path() {
- std::string home = home_dir();
- if (home.empty())
- return {};
- return (std::filesystem::path(home) / ".local" / "share" / "tether" / "contacts.json").string();
- }
-
- std::string serialize_contacts(const ContactStore& store) {
- nlohmann::json j;
- j["contacts"] = nlohmann::json::array();
- for (const auto& card : store.contacts()) {
- nlohmann::json c;
- c["name"] = card.name;
- c["tels"] = card.tels;
- c["emails"] = card.emails;
- j["contacts"].push_back(std::move(c));
- }
- return j.dump(2);
- }
-
- ContactStore deserialize_contacts(const std::string& text) {
- ContactStore store;
- std::vector<VCard> cards;
- try {
- auto j = nlohmann::json::parse(text);
- for (const auto& c : j.value("contacts", nlohmann::json::array())) {
- VCard card;
- card.name = c.value("name", "");
- card.tels = c.value("tels", std::vector<std::string>{});
- card.emails = c.value("emails", std::vector<std::string>{});
- if (!card.empty())
- cards.push_back(std::move(card));
- }
- } catch (const std::exception&) {
- // A corrupt cache costs display names, not correctness. Threads fall
- // back to raw addresses until PBAP refreshes.
- return store;
- }
- store.set(std::move(cards));
- return store;
- }
-
- ContactStore load_contacts() {
- std::string path = contacts_path();
- if (path.empty())
- return {};
- std::ifstream in(path);
- if (!in.is_open())
- return {};
- std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
- return deserialize_contacts(text);
- }
-
- bool save_contacts(const ContactStore& store) {
- std::string path = contacts_path();
- if (path.empty())
- return false;
-
- std::error_code ec;
- std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec);
-
- // Write-then-rename, matching how the Bluetooth config is persisted.
- std::string tmp = path + ".tmp";
- {
- std::ofstream out(tmp, std::ios::trunc);
- if (!out.is_open()) {
- debug::log(ERR, "bluetooth: cannot write {}", tmp);
- return false;
- }
- out << serialize_contacts(store);
- if (!out) {
- debug::log(ERR, "bluetooth: failed writing {}", tmp);
- return false;
- }
- }
-
- // The phonebook is personal data, so it gets the same mode as the key.
- std::filesystem::permissions(tmp,
- std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
- std::filesystem::perm_options::replace,
- ec);
- std::filesystem::rename(tmp, path, ec);
- if (ec) {
- debug::log(ERR, "bluetooth: cannot replace {}: {}", path, ec.message());
- std::filesystem::remove(tmp, ec);
- return false;
- }
- return true;
- }
-
- ContactStore& contact_store() {
- static ContactStore store;
- return store;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/diagnostics.cpp b/src/core/src/bluetooth/diagnostics.cpp
deleted file mode 100644
index eebccb2..0000000
--- a/src/core/src/bluetooth/diagnostics.cpp
+++ /dev/null
@@ -1,199 +0,0 @@
-#include "tether/bluetooth/diagnostics.hpp"
-
-#include "tether/bluetooth/config.hpp"
-#include "tether/version.hpp"
-
-#include <algorithm>
-#include <chrono>
-#include <cstdlib>
-#include <deque>
-#include <functional>
-#include <mutex>
-#include <regex>
-
-namespace tether::bluetooth {
-
- namespace {
-
- // A pairing attempt is a few dozen events; this holds several attempts
- // without letting a long-running daemon accumulate a report nobody reads.
- constexpr size_t TIMELINE_CAPACITY = 200;
-
- const std::regex kDevNode(R"(dev_[0-9A-Fa-f]{2}(?:_[0-9A-Fa-f]{2}){5})");
- const std::regex kAddress(R"([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})");
- const std::regex kEmail(R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})");
- const std::regex kNumber(R"(\+[0-9]{7,15})");
- const std::regex kRuntimeDir(R"(/run/user/[0-9]+)");
-
- std::string upper(std::string s) {
- std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::toupper(c); });
- return s;
- }
-
- std::string lower(std::string s) {
- std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
- return s;
- }
-
- std::string replace_all(const std::string& in,
- const std::regex& re,
- const std::function<std::string(const std::string&)>& fn) {
- std::string out;
- size_t last = 0;
- for (auto it = std::sregex_iterator(in.begin(), in.end(), re); it != std::sregex_iterator(); ++it) {
- out.append(in, last, static_cast<size_t>(it->position()) - last);
- out += fn(it->str());
- last = static_cast<size_t>(it->position()) + static_cast<size_t>(it->length());
- }
- out.append(in, last, std::string::npos);
- return out;
- }
-
- std::string replace_literal(std::string in, const std::string& needle, const std::string& with) {
- if (needle.empty())
- return in;
- for (size_t at = in.find(needle); at != std::string::npos; at = in.find(needle, at + with.size()))
- in.replace(at, needle.size(), with);
- return in;
- }
-
- // Events describing link and pairing state. Everything else the daemon
- // broadcasts carries message or notification content.
- bool is_state_event(const std::string& command) {
- return command == "bt_pair_progress" || command == "bt_pair_result" || command == "bt_unpair_result" ||
- command == "bt_connection_changed" || command == "bt_send_result" || command == "bt_message_read";
- }
-
- std::mutex g_timeline_mutex;
- std::deque<nlohmann::json> g_timeline;
- std::chrono::steady_clock::time_point g_timeline_origin;
- bool g_timeline_started = false;
-
- } // namespace
-
- bool is_content_key(const std::string& key) {
- return key == "body" || key == "sender" || key == "subject" || key == "name" || key == "title" ||
- key == "preview" || key == "alias";
- }
-
- std::string Redactor::placeholder(const std::string& kind, const std::string& key) {
- const std::string prefix = "<" + kind + "-";
- if (auto it = assigned_.find(key); it != assigned_.end())
- return it->second;
-
- size_t n = 1;
- for (const auto& [existing, token] : assigned_)
- if (token.rfind(prefix, 0) == 0)
- ++n;
-
- std::string token = prefix + std::to_string(n) + ">";
- assigned_.emplace(key, token);
- return token;
- }
-
- std::string Redactor::text(const std::string& in) {
- std::string out = in;
-
- // Directories first: a path under $HOME can contain anything below.
- if (const char* runtime = std::getenv("XDG_RUNTIME_DIR"); runtime && *runtime)
- out = replace_literal(out, runtime, "<runtime>");
- out = replace_all(out, kRuntimeDir, [](const std::string&) { return "<runtime>"; });
- if (const char* home = std::getenv("HOME"); home && *home)
- out = replace_literal(out, home, "<home>");
-
- // Normalized to the colon form so one device gets one placeholder
- // however the address was spelled.
- out = replace_all(out, kDevNode, [this](const std::string& match) {
- std::string address = match.substr(4);
- std::replace(address.begin(), address.end(), '_', ':');
- return "dev_" + placeholder("address", upper(address));
- });
- out = replace_all(
- out, kAddress, [this](const std::string& match) { return placeholder("address", upper(match)); });
- out = replace_all(out, kEmail, [this](const std::string& match) { return placeholder("email", lower(match)); });
- out = replace_all(out, kNumber, [this](const std::string& match) { return placeholder("number", match); });
- return out;
- }
-
- nlohmann::json Redactor::value(const nlohmann::json& in) {
- if (in.is_string())
- return text(in.get<std::string>());
-
- if (in.is_array()) {
- nlohmann::json out = nlohmann::json::array();
- for (const auto& element : in)
- out.push_back(value(element));
- return out;
- }
-
- if (in.is_object()) {
- nlohmann::json out = nlohmann::json::object();
- for (const auto& [key, element] : in.items()) {
- if (is_content_key(key))
- continue;
- out[key] = value(element);
- }
- return out;
- }
-
- return in;
- }
-
- void record_diagnostic_event(const nlohmann::json& event) {
- if (!event.is_object() || !is_state_event(event.value("command", "")))
- return;
-
- nlohmann::json entry = nlohmann::json::object();
- for (const auto& [key, value] : event.items()) {
- if (!is_content_key(key))
- entry[key] = value;
- }
-
- std::lock_guard<std::mutex> lock(g_timeline_mutex);
- const auto now = std::chrono::steady_clock::now();
- if (!g_timeline_started) {
- g_timeline_origin = now;
- g_timeline_started = true;
- }
- entry["at_ms"] = std::chrono::duration_cast<std::chrono::milliseconds>(now - g_timeline_origin).count();
-
- g_timeline.push_back(std::move(entry));
- if (g_timeline.size() > TIMELINE_CAPACITY)
- g_timeline.pop_front();
- }
-
- nlohmann::json diagnostic_timeline() {
- std::lock_guard<std::mutex> lock(g_timeline_mutex);
- nlohmann::json out = nlohmann::json::array();
- for (const auto& entry : g_timeline)
- out.push_back(entry);
- return out;
- }
-
- void clear_diagnostic_timeline() {
- std::lock_guard<std::mutex> lock(g_timeline_mutex);
- g_timeline.clear();
- g_timeline_started = false;
- }
-
- nlohmann::json build_diagnostics(const nlohmann::json& status, const nlohmann::json& connection) {
- const Config config = load_config();
- Redactor redactor;
-
- nlohmann::json report;
- report["command"] = "bt_diagnostics";
- report["version"] = TETHER_VERSION;
- report["auth_strategy"] = to_string(config.auth_strategy);
- // The address itself is never reported; whether one is selected is what
- // matters for reading the rest.
- report["device_selected"] = !config.device_address.empty();
- report["ancs_enabled"] = config.ancs_enabled;
- report["ancs_content_enabled"] = config.ancs_content_enabled;
- report["group_messages_enabled"] = config.group_messages_enabled;
- report["status"] = redactor.value(status);
- report["connection"] = redactor.value(connection);
- report["timeline"] = redactor.value(diagnostic_timeline());
- return report;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/groups.cpp b/src/core/src/bluetooth/groups.cpp
deleted file mode 100644
index 38bad64..0000000
--- a/src/core/src/bluetooth/groups.cpp
+++ /dev/null
@@ -1,357 +0,0 @@
-#include "tether/bluetooth/groups.hpp"
-
-#include <algorithm>
-#include <cctype>
-#include <cstdlib>
-#include <filesystem>
-#include <fstream>
-#include <nlohmann/json.hpp>
-#include <pwd.h>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string home_dir() {
- if (const char* home = getenv("HOME"); home && *home)
- return home;
- if (const passwd* pw = getpwuid(getuid()); pw && pw->pw_dir)
- return pw->pw_dir;
- return {};
- }
-
- std::string trim(const std::string& text) {
- size_t begin = text.find_first_not_of(" \t\r\n");
- if (begin == std::string::npos)
- return {};
- size_t end = text.find_last_not_of(" \t\r\n");
- return text.substr(begin, end - begin + 1);
- }
-
- std::string lower(std::string text) {
- std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
- return static_cast<char>(std::tolower(c));
- });
- return text;
- }
-
- // Collapses case and whitespace so a group name is a stable key.
- std::string normalize_name(const std::string& text) {
- std::string out;
- bool space = false;
- for (char c : lower(trim(text))) {
- if (std::isspace(static_cast<unsigned char>(c))) {
- space = true;
- continue;
- }
- if (space && !out.empty())
- out += '-';
- space = false;
- out += c;
- }
- return out;
- }
-
- // Splits "you, Alice & Bob" on commas and ampersands.
- std::vector<std::string> split_participants(const std::string& text) {
- std::vector<std::string> parts;
- std::string current;
- for (size_t i = 0; i < text.size(); ++i) {
- if (text[i] == ',' || text[i] == '&') {
- parts.push_back(trim(current));
- current.clear();
- continue;
- }
- current += text[i];
- }
- parts.push_back(trim(current));
-
- std::vector<std::string> out;
- for (auto& part : parts) {
- if (part.empty())
- continue;
- // The user is always a member and is never a reply recipient.
- if (lower(part) == "you")
- continue;
- out.push_back(std::move(part));
- }
- return out;
- }
-
- } // namespace
-
- bool parse_group_notification(const std::string& title, const std::string& subtitle, GroupInfo& out) {
- const std::string clean_subtitle = trim(subtitle);
- if (clean_subtitle.empty())
- return false;
-
- out = GroupInfo{};
- out.sender = trim(title);
- out.is_group = true;
-
- // "To you & Alice" marks an unnamed group. Anything else is a name.
- const std::string lowered = lower(clean_subtitle);
- if (lowered.rfind("to ", 0) == 0) {
- out.named = false;
- out.participants = split_participants(clean_subtitle.substr(3));
- // "To Alice" with nobody else is a one-to-one conversation.
- if (out.participants.empty())
- return false;
- return true;
- }
-
- out.named = true;
- out.name = clean_subtitle;
- return true;
- }
-
- std::string group_thread_key(const GroupInfo& info) {
- if (!info.is_group)
- return {};
- if (info.named)
- return "group:name:" + normalize_name(info.name);
-
- std::vector<std::string> slugs;
- slugs.reserve(info.participants.size());
- for (const auto& participant : info.participants)
- slugs.push_back(normalize_name(participant));
- std::sort(slugs.begin(), slugs.end());
-
- std::string key = "group:members:";
- for (size_t i = 0; i < slugs.size(); ++i) {
- if (i)
- key += "+";
- key += slugs[i];
- }
- return key;
- }
-
- void GroupCorrelator::observe(const MessageNotification& notification) { recent_.push_back(notification); }
-
- void GroupCorrelator::expire(int64_t now) {
- std::erase_if(
- recent_, [&](const MessageNotification& n) { return now - n.received > GROUP_CORRELATION_WINDOW_SECONDS; });
- }
-
- void GroupCorrelator::clear() { recent_.clear(); }
-
- Correlation GroupCorrelator::correlate(const std::string& body, int64_t now, GroupInfo& out) const {
- const MessageNotification* match = nullptr;
- size_t matches = 0;
-
- for (const auto& candidate : recent_) {
- if (now - candidate.received > GROUP_CORRELATION_WINDOW_SECONDS)
- continue;
- if (candidate.body.empty())
- continue;
- // ANCS bodies are capped at what was requested, so a longer MAP body
- // matches the notification as a prefix rather than exactly.
- if (body.rfind(candidate.body, 0) != 0)
- continue;
-
- ++matches;
- match = &candidate;
- }
-
- if (matches == 0)
- return Correlation::NoMatch;
-
- // two notifications with same text cannot be told apart
- if (matches > 1)
- return Correlation::Ambiguous;
-
- GroupInfo info;
- if (!parse_group_notification(match->sender, match->subtitle, info))
- return Correlation::NoMatch;
- out = info;
- return Correlation::Matched;
- }
-
- const char* to_string(ReplyEligibility eligibility) {
- switch (eligibility) {
- case ReplyEligibility::Allowed:
- return "allowed";
- case ReplyEligibility::Disabled:
- return "disabled";
- case ReplyEligibility::NeedsRoster:
- return "needs-roster";
- case ReplyEligibility::Unresolved:
- return "unresolved";
- case ReplyEligibility::RouteInvalidated:
- return "route-invalidated";
- }
- return "unknown";
- }
-
- void GroupRoster::set(const std::string& thread_key, std::vector<std::string> addresses) {
- rosters_[thread_key] = std::move(addresses);
- }
-
- const std::vector<std::string>* GroupRoster::find(const std::string& thread_key) const {
- auto it = rosters_.find(thread_key);
- return it == rosters_.end() ? nullptr : &it->second;
- }
-
- std::string GroupRoster::serialize() const {
- nlohmann::json j;
- for (const auto& [key, addresses] : rosters_)
- j[key] = addresses;
- return j.dump(2);
- }
-
- GroupRoster GroupRoster::deserialize(const std::string& text) {
- GroupRoster roster;
- try {
- auto j = nlohmann::json::parse(text);
- if (!j.is_object())
- return roster;
- for (auto& [key, value] : j.items()) {
- if (value.is_array())
- roster.set(key, value.get<std::vector<std::string>>());
- }
- } catch (const std::exception&) {
- // A corrupt roster must leave groups read-only rather than routing a
- // reply to whatever survived parsing.
- return GroupRoster{};
- }
- return roster;
- }
-
- std::string roster_path() {
- std::string home = home_dir();
- if (home.empty())
- return {};
- return (std::filesystem::path(home) / ".config" / "tether" / "groups.json").string();
- }
-
- GroupRoster load_rosters() {
- std::string path = roster_path();
- if (path.empty())
- return {};
- std::ifstream in(path);
- if (!in.is_open())
- return {};
- std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
- return GroupRoster::deserialize(text);
- }
-
- bool save_rosters(const GroupRoster& roster) {
- std::string path = roster_path();
- if (path.empty())
- return false;
-
- std::error_code ec;
- std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec);
-
- std::string tmp = path + ".tmp";
- {
- std::ofstream out(tmp, std::ios::trunc);
- if (!out.is_open())
- return false;
- out << roster.serialize();
- if (!out)
- return false;
- }
- std::filesystem::permissions(tmp,
- std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
- std::filesystem::perm_options::replace,
- ec);
- std::filesystem::rename(tmp, path, ec);
- if (ec) {
- std::filesystem::remove(tmp, ec);
- return false;
- }
- return true;
- }
-
- ReplyEligibility resolve_group_recipients(const GroupInfo& info,
- const std::string& thread_key,
- const ContactStore& contacts,
- const GroupRoster& rosters,
- bool group_replies_enabled,
- std::vector<Recipient>& out,
- std::string& reason) {
- out.clear();
- if (!group_replies_enabled) {
- reason = "Group replies are turned off.";
- return ReplyEligibility::Disabled;
- }
-
- // user-supplied roster is authoritative for either kind of group
- if (const std::vector<std::string>* roster = rosters.find(thread_key)) {
- for (const auto& address : *roster) {
- Recipient recipient;
- std::string err;
- if (!recipient_from_thread_key(address, recipient, err)) {
- reason = "The roster for this group contains an unusable address: " + err;
- out.clear();
- return ReplyEligibility::Unresolved;
- }
- out.push_back(recipient);
- }
- if (out.empty()) {
- reason = "The roster for this group is empty.";
- return ReplyEligibility::NeedsRoster;
- }
- return ReplyEligibility::Allowed;
- }
-
- // thread with no correlated notification behind it
- if (!info.is_group) {
- reason = "This conversation has not been identified as a group yet, so there is nobody to reply to.";
- return ReplyEligibility::NeedsRoster;
- }
-
- if (info.named) {
- reason = "This group has a name but no member list. Add its members before replying.";
- return ReplyEligibility::NeedsRoster;
- }
-
- for (const auto& participant : info.participants) {
- std::vector<std::string> addresses = contacts.addresses_for_name(participant);
- if (addresses.empty()) {
- reason = "\"" + participant + "\" is not in your contacts.";
- out.clear();
- return ReplyEligibility::Unresolved;
- }
- if (addresses.size() > 1) {
- reason = "\"" + participant + "\" matches more than one contact address.";
- out.clear();
- return ReplyEligibility::Unresolved;
- }
-
- Recipient recipient;
- std::string err;
- if (!recipient_from_thread_key(addresses.front(), recipient, err)) {
- reason = "\"" + participant + "\" resolved to an unusable address: " + err;
- out.clear();
- return ReplyEligibility::Unresolved;
- }
- out.push_back(recipient);
- }
-
- if (out.empty()) {
- reason = "No recipients could be resolved for this group.";
- return ReplyEligibility::Unresolved;
- }
- return ReplyEligibility::Allowed;
- }
-
- bool sender_invalidates_route(const std::string& sender_address, const std::vector<Recipient>& recipients) {
- if (sender_address.empty() || recipients.empty())
- return false;
-
- Recipient sender;
- std::string err;
- if (!recipient_from_thread_key(sender_address, sender, err))
- return true;
-
- for (const auto& recipient : recipients) {
- if (recipient.kind == sender.kind && recipient.address == sender.address)
- return false;
- }
- return true;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/journal.cpp b/src/core/src/bluetooth/journal.cpp
deleted file mode 100644
index fbf0232..0000000
--- a/src/core/src/bluetooth/journal.cpp
+++ /dev/null
@@ -1,197 +0,0 @@
-#include "tether/bluetooth/journal.hpp"
-#include "tether/log.hpp"
-
-#include <algorithm>
-#include <cstdlib>
-#include <filesystem>
-#include <map>
-#include <nlohmann/json.hpp>
-#include <pwd.h>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string home_dir() {
- if (const char* home = getenv("HOME"); home && *home)
- return home;
- if (const passwd* pw = getpwuid(getuid()); pw && pw->pw_dir)
- return pw->pw_dir;
- return {};
- }
-
- void restrict_permissions(const std::string& path) {
- std::error_code ec;
- std::filesystem::permissions(path,
- std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
- std::filesystem::perm_options::replace,
- ec);
- }
-
- } // namespace
-
- std::string journal_path() {
- std::string home = home_dir();
- if (home.empty())
- return {};
- return (std::filesystem::path(home) / ".local" / "share" / "tether" / "messages.ndjson").string();
- }
-
- std::string serialize_message_line(const Message& message) {
- return to_json(message).dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
- }
-
- bool deserialize_message_line(const std::string& line, Message& out) {
- try {
- auto j = nlohmann::json::parse(line);
- if (!j.is_object())
- return false;
- Message message;
- message.handle = j.value("handle", "");
- message.thread_key = j.value("thread", "");
- message.peer_address = j.value("address", "");
- message.peer_name = j.value("name", "");
- message.body = j.value("body", "");
- message.timestamp = j.value("timestamp", static_cast<int64_t>(0));
- message.outgoing = j.value("outgoing", false);
- message.read = j.value("read", false);
- message.folder = j.value("folder", "");
- // A message with no handle cannot be deduped and would replay forever.
- if (message.handle.empty() || message.thread_key.empty())
- return false;
- out = std::move(message);
- return true;
- } catch (const std::exception&) {
- return false;
- }
- }
-
- std::vector<Message>
- apply_retention(std::vector<Message> messages, int64_t now, size_t max_messages, int64_t max_age) {
- {
- std::map<std::string, size_t> newest;
- for (size_t i = 0; i < messages.size(); ++i)
- newest[messages[i].handle] = i;
- std::vector<Message> unique;
- unique.reserve(newest.size());
- for (size_t i = 0; i < messages.size(); ++i) {
- if (newest[messages[i].handle] == i)
- unique.push_back(std::move(messages[i]));
- }
- messages = std::move(unique);
- }
-
- if (max_age > 0) {
- const int64_t cutoff = now - max_age;
- // zero timestamp means the phone gave us nothing usable
- std::erase_if(messages, [&](const Message& m) { return m.timestamp > 0 && m.timestamp < cutoff; });
- }
-
- if (messages.size() > max_messages) {
- std::stable_sort(messages.begin(), messages.end(), [](const Message& a, const Message& b) {
- return a.timestamp < b.timestamp;
- });
- messages.erase(messages.begin(), messages.begin() + static_cast<long>(messages.size() - max_messages));
- }
- return messages;
- }
-
- bool MessageJournal::open() {
- path_ = journal_path();
- if (path_.empty())
- return false;
-
- std::error_code ec;
- std::filesystem::create_directories(std::filesystem::path(path_).parent_path(), ec);
-
- out_.open(path_, std::ios::app);
- if (!out_.is_open()) {
- debug::log(ERR, "bluetooth: cannot open journal {}", path_);
- return false;
- }
- restrict_permissions(path_);
- return true;
- }
-
- void MessageJournal::close() {
- if (out_.is_open())
- out_.close();
- }
-
- void MessageJournal::append(const Message& message) {
- if (!out_.is_open())
- return;
- out_ << serialize_message_line(message) << "\n";
- out_.flush();
- }
-
- std::vector<Message> MessageJournal::load(int64_t now) const {
- std::vector<Message> messages;
- const std::string path = path_.empty() ? journal_path() : path_;
- if (path.empty())
- return messages;
-
- std::ifstream in(path);
- if (!in.is_open())
- return messages;
-
- std::string line;
- size_t skipped = 0;
- while (std::getline(in, line)) {
- if (line.empty())
- continue;
- Message message;
- if (deserialize_message_line(line, message))
- messages.push_back(std::move(message));
- else
- ++skipped;
- }
- if (skipped)
- debug::log(WARN, "bluetooth: skipped {} unreadable journal line(s)", skipped);
-
- return apply_retention(std::move(messages), now);
- }
-
- bool MessageJournal::compact(const std::vector<Message>& messages) {
- const std::string path = path_.empty() ? journal_path() : path_;
- if (path.empty())
- return false;
-
- std::error_code ec;
- std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec);
-
- const std::string tmp = path + ".tmp";
- {
- std::ofstream out(tmp, std::ios::trunc);
- if (!out.is_open()) {
- debug::log(ERR, "bluetooth: cannot write {}", tmp);
- return false;
- }
- for (const auto& message : messages)
- out << serialize_message_line(message) << "\n";
- if (!out) {
- debug::log(ERR, "bluetooth: failed writing {}", tmp);
- return false;
- }
- }
- restrict_permissions(tmp);
-
- const bool was_open = out_.is_open();
- if (was_open)
- out_.close();
-
- std::filesystem::rename(tmp, path, ec);
- if (ec) {
- debug::log(ERR, "bluetooth: cannot replace {}: {}", path, ec.message());
- std::filesystem::remove(tmp, ec);
- }
-
- if (was_open) {
- out_.open(path, std::ios::app);
- restrict_permissions(path);
- }
- return !ec;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/map_session.cpp b/src/core/src/bluetooth/map_session.cpp
deleted file mode 100644
index b957b9f..0000000
--- a/src/core/src/bluetooth/map_session.cpp
+++ /dev/null
@@ -1,335 +0,0 @@
-#include "tether/bluetooth/map_session.hpp"
-#include "tether/bluetooth/obex_transfer.hpp"
-
-#include <cstdlib>
-#include <filesystem>
-#include <fstream>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* OBEX_NAME = "org.bluez.obex";
- constexpr const char* IFACE_MAP = "org.bluez.obex.MessageAccess1";
- constexpr const char* IFACE_MESSAGE = "org.bluez.obex.Message1";
- constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";
-
- // Listing a large mailbox is a real OBEX transfer; give it room.
- constexpr int MAP_CALL_TIMEOUT_MS = 60000;
- // Sending is interactive; the user is waiting on the answer.
- constexpr int MAP_PUSH_TIMEOUT_SECONDS = 30;
-
- std::string variant_string(GVariant* value) {
- if (!value)
- return {};
- if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING))
- return g_variant_get_string(value, nullptr);
- return {};
- }
-
- bool variant_bool(GVariant* value) {
- return value && g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN) && g_variant_get_boolean(value);
- }
-
- bool take_error(GError*& error, std::string& err_out) {
- err_out = error ? error->message : "unknown error";
- g_clear_error(&error);
- return false;
- }
-
- } // namespace
-
- struct MapSessionState {
- GDBusConnection* bus = nullptr;
- std::string path;
- };
-
- MapSession::MapSession(GDBusConnection* session_bus, std::string session_path)
- : state_(std::make_unique<MapSessionState>()) {
- state_->bus = session_bus;
- state_->path = std::move(session_path);
- }
-
- MapSession::~MapSession() = default;
-
- const std::string& MapSession::path() const { return state_->path; }
-
- bool MapSession::set_folder(const std::string& folder, std::string& err) {
- GError* error = nullptr;
- // MessageAccess1.SetFolder, deliberately not PBAP's Select.
- GVariant* reply = g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- state_->path.c_str(),
- IFACE_MAP,
- "SetFolder",
- g_variant_new("(s)", folder.c_str()),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- MAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply)
- return take_error(error, err);
- g_variant_unref(reply);
- return true;
- }
-
- std::vector<MapListing> MapSession::list_messages(const std::string& folder, int max, std::string& err) {
- std::vector<MapListing> listings;
-
- GVariantBuilder filter;
- g_variant_builder_init(&filter, G_VARIANT_TYPE("a{sv}"));
- g_variant_builder_add(&filter, "{sv}", "MaxCount", g_variant_new_uint16(static_cast<guint16>(max)));
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- state_->path.c_str(),
- IFACE_MAP,
- "ListMessages",
- g_variant_new("(sa{sv})", folder.c_str(), &filter),
- // obexd returns a dict of object path -> properties,
- // not an array of (path, properties) structs.
- G_VARIANT_TYPE("(a{oa{sv}})"),
- G_DBUS_CALL_FLAGS_NONE,
- MAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- take_error(error, err);
- return listings;
- }
-
- GVariant* array = g_variant_get_child_value(reply, 0);
- GVariantIter iter;
- const gchar* object_path = nullptr;
- GVariant* props = nullptr;
- g_variant_iter_init(&iter, array);
- while (g_variant_iter_loop(&iter, "{&o@a{sv}}", &object_path, &props)) {
- MapListing listing;
- listing.handle = object_path ? object_path : "";
-
- GVariantIter prop_iter;
- const gchar* key = nullptr;
- GVariant* value = nullptr;
- g_variant_iter_init(&prop_iter, props);
- while (g_variant_iter_loop(&prop_iter, "{&sv}", &key, &value)) {
- const std::string name = key ? key : "";
- // The message text lives in Subject for a listing; a full
- // bMessage download is only needed when this is truncated.
- if (name == "Subject")
- listing.subject = variant_string(value);
- else if (name == "Sender")
- listing.sender_name = variant_string(value);
- else if (name == "SenderAddress")
- listing.sender_address = variant_string(value);
- else if (name == "Timestamp")
- listing.timestamp = variant_string(value);
- else if (name == "Type")
- listing.type = variant_string(value);
- else if (name == "Folder")
- listing.folder = variant_string(value);
- else if (name == "Read")
- listing.read = variant_bool(value);
- else if (name == "Sent")
- listing.sent = variant_bool(value);
- }
-
- if (listing.folder.empty())
- listing.folder = folder;
- listings.push_back(std::move(listing));
- }
-
- g_variant_unref(array);
- g_variant_unref(reply);
- return listings;
- }
-
- bool MapSession::fetch_bmessage(const std::string& message_path, BMessage& out, std::string& err) {
- // Message1.Get writes the bMessage to a file and returns the transfer
- // object plus its properties.
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- message_path.c_str(),
- IFACE_MESSAGE,
- "Get",
- g_variant_new("(sb)", "", TRUE),
- G_VARIANT_TYPE("(oa{sv})"),
- G_DBUS_CALL_FLAGS_NONE,
- MAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply)
- return take_error(error, err);
-
- GVariant* props = g_variant_get_child_value(reply, 1);
- GVariant* filename = g_variant_lookup_value(props, "Filename", G_VARIANT_TYPE_STRING);
- const std::string path = filename ? g_variant_get_string(filename, nullptr) : "";
- if (filename)
- g_variant_unref(filename);
- g_variant_unref(props);
- g_variant_unref(reply);
-
- if (path.empty()) {
- err = "transfer returned no filename";
- return false;
- }
-
- std::ifstream in(path, std::ios::binary);
- if (!in.is_open()) {
- err = "cannot read " + path;
- return false;
- }
- std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
- out = parse_bmessage(text);
- if (!out.valid) {
- err = "unparseable bMessage";
- return false;
- }
- return true;
- }
-
- bool MapSession::set_read(const std::string& message_path, bool read, std::string& err) {
- GError* error = nullptr;
- GVariant* reply =
- g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- message_path.c_str(),
- IFACE_PROPS,
- "Set",
- g_variant_new("(ssv)", IFACE_MESSAGE, "Read", g_variant_new_boolean(read)),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- MAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply)
- return take_error(error, err);
- g_variant_unref(reply);
- return true;
- }
-
- bool MapSession::push_message(const std::string& folder, const std::string& bmessage, std::string& err) {
- if (bmessage.empty()) {
- err = "Refusing to send an empty message.";
- return false;
- }
-
- // obexd reads the message from a file. It is staged in the per-user
- // runtime directory rather than a shared temp directory, since it holds
- // the message text and the recipient.
- const char* runtime = getenv("XDG_RUNTIME_DIR");
- std::filesystem::path source =
- (runtime && *runtime ? std::filesystem::path(runtime) : std::filesystem::temp_directory_path()) /
- ("tether-send-" + std::to_string(getpid()) + ".bmsg");
-
- std::error_code ec;
- {
- std::ofstream out(source, std::ios::binary | std::ios::trunc);
- if (!out.is_open()) {
- err = "Cannot stage the message for sending.";
- return false;
- }
- out << bmessage;
- if (!out) {
- err = "Failed writing the staged message.";
- std::filesystem::remove(source, ec);
- return false;
- }
- }
- std::filesystem::permissions(source,
- std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
- std::filesystem::perm_options::replace,
- ec);
-
- GVariantBuilder args;
- g_variant_builder_init(&args, G_VARIANT_TYPE("a{sv}"));
- // The body is UTF-8; letting obexd transcode to the native charset would
- // mangle anything outside the phone's default encoding.
- g_variant_builder_add(&args, "{sv}", "Charset", g_variant_new_string("utf8"));
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- state_->path.c_str(),
- IFACE_MAP,
- "PushMessage",
- g_variant_new("(ssa{sv})", source.c_str(), folder.c_str(), &args),
- G_VARIANT_TYPE("(oa{sv})"),
- G_DBUS_CALL_FLAGS_NONE,
- MAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- take_error(error, err);
- std::filesystem::remove(source, ec);
- return false;
- }
-
- const gchar* transfer_path = nullptr;
- GVariant* props = nullptr;
- g_variant_get(reply, "(&o@a{sv})", &transfer_path, &props);
- const std::string transfer = transfer_path ? transfer_path : "";
- if (props)
- g_variant_unref(props);
- g_variant_unref(reply);
-
- if (transfer.empty()) {
- err = "obexd returned no transfer object.";
- std::filesystem::remove(source, ec);
- return false;
- }
-
- const TransferState state = wait_for_transfer(state_->bus, transfer, MAP_PUSH_TIMEOUT_SECONDS);
- std::filesystem::remove(source, ec);
-
- if (state == TransferState::Error) {
- err = "The phone rejected the message.";
- return false;
- }
- if (state == TransferState::Active) {
- // The transfer is still running, so the message may yet be sent.
- err = "Timed out waiting for the phone to accept the message; it may still be sent.";
- return false;
- }
- return true;
- }
-
- std::string map_handle_from_path(const std::string& object_path) {
- // "/org/bluez/obex/client/session5/message1086086778701665313" -> the
- // trailing id. The session number in the prefix changes on every
- // reconnect; the id does not.
- size_t slash = object_path.rfind('/');
- std::string tail = slash == std::string::npos ? object_path : object_path.substr(slash + 1);
- if (tail.rfind("message", 0) == 0)
- tail = tail.substr(7);
- return tail.empty() ? object_path : tail;
- }
-
- Message message_from_listing(const MapListing& listing) {
- VCardParty peer;
- peer.name = listing.sender_name;
- // MAP reports the address in one field without saying which kind it is;
- // an '@' is the only available discriminator.
- if (listing.sender_address.find('@') != std::string::npos)
- peer.email = listing.sender_address;
- else
- peer.tel = listing.sender_address;
-
- Message message;
- message.handle = map_handle_from_path(listing.handle);
- message.object_path = listing.handle;
- message.body = listing.subject;
- message.timestamp = parse_map_timestamp(listing.timestamp);
- message.read = listing.read;
- message.outgoing = listing.sent;
- message.folder = listing.folder;
- message.thread_key = thread_key_for(peer);
- message.peer_address = peer.tel.empty() ? normalize_email(peer.email) : normalize_phone(peer.tel);
- message.peer_name = peer.name;
- return message;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/messages.cpp b/src/core/src/bluetooth/messages.cpp
deleted file mode 100644
index fb3d7d8..0000000
--- a/src/core/src/bluetooth/messages.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-#include "tether/bluetooth/messages.hpp"
-
-#include <algorithm>
-
-namespace tether::bluetooth {
-
- namespace {
-
- bool is_outgoing_folder(const std::string& folder) {
- return folder.find("sent") != std::string::npos || folder.find("outbox") != std::string::npos;
- }
-
- std::string display_address(const VCardParty& party) {
- if (!party.tel.empty())
- return normalize_phone(party.tel);
- return normalize_email(party.email);
- }
-
- } // namespace
-
- MessageStore::MessageStore(size_t max_messages) : max_messages_(max_messages) {}
-
- bool MessageStore::add(const Message& message) {
- if (message.handle.empty())
- return false;
- if (auto it = by_handle_.find(message.handle); it != by_handle_.end()) {
- // re-listing after reconnect has a fresh object path for the same message
- if (!message.object_path.empty())
- it->second.object_path = message.object_path;
- return false;
- }
-
- by_handle_.emplace(message.handle, message);
- order_.push_back(message.handle);
- trim();
- return true;
- }
-
- bool MessageStore::set_read(const std::string& handle, bool read) {
- auto it = by_handle_.find(handle);
- if (it == by_handle_.end() || it->second.read == read)
- return false;
- it->second.read = read;
- return true;
- }
-
- const Message* MessageStore::find(const std::string& handle) const {
- auto it = by_handle_.find(handle);
- return it == by_handle_.end() ? nullptr : &it->second;
- }
-
- void MessageStore::trim() {
- while (order_.size() > max_messages_) {
- by_handle_.erase(order_.front());
- order_.erase(order_.begin());
- }
- }
-
- std::vector<Thread> MessageStore::threads() const {
- std::map<std::string, Thread> grouped;
-
- for (const auto& [handle, message] : by_handle_) {
- if (message.thread_key.empty())
- continue;
- Thread& thread = grouped[message.thread_key];
- thread.key = message.thread_key;
- thread.peer_address = message.peer_address;
- ++thread.count;
-
- if (thread.display_name.empty() ||
- (!message.peer_name.empty() && thread.display_name == thread.peer_address))
- if (!message.peer_name.empty())
- thread.display_name = message.peer_name;
-
- if (!message.read && !message.outgoing)
- ++thread.unread;
-
- if (message.timestamp >= thread.last_timestamp) {
- thread.last_timestamp = message.timestamp;
- thread.last_body = message.body;
- }
- }
-
- std::vector<Thread> result;
- result.reserve(grouped.size());
- for (auto& [key, thread] : grouped) {
- if (thread.display_name.empty())
- thread.display_name = thread.peer_address;
- result.push_back(thread);
- }
-
- std::sort(result.begin(), result.end(), [](const Thread& a, const Thread& b) {
- if (a.last_timestamp != b.last_timestamp)
- return a.last_timestamp > b.last_timestamp;
- return a.key < b.key;
- });
- return result;
- }
-
- std::vector<Message> MessageStore::messages(const std::string& thread_key, size_t limit) const {
- std::vector<Message> result;
- for (const auto& [handle, message] : by_handle_) {
- if (message.thread_key == thread_key)
- result.push_back(message);
- }
-
- std::sort(result.begin(), result.end(), [](const Message& a, const Message& b) {
- if (a.timestamp != b.timestamp)
- return a.timestamp < b.timestamp;
- return a.handle < b.handle;
- });
-
- if (result.size() > limit)
- result.erase(result.begin(), result.end() - static_cast<long>(limit));
- return result;
- }
-
- Message message_from_bmessage(const BMessage& parsed, const std::string& handle, int64_t timestamp) {
- Message message;
- message.handle = handle;
- message.timestamp = timestamp;
- message.read = parsed.read;
- message.folder = parsed.folder;
- message.body = parsed.body;
- message.outgoing = is_outgoing_folder(parsed.folder);
-
- const VCardParty& peer =
- message.outgoing && !parsed.recipients.empty() ? parsed.recipients.front() : parsed.originator;
-
- message.thread_key = thread_key_for(peer);
- message.peer_address = display_address(peer);
- message.peer_name = peer.name;
- return message;
- }
-
- nlohmann::json to_json(const Message& message) {
- return {
- {"handle", message.handle},
- {"thread", message.thread_key},
- {"address", message.peer_address},
- {"name", message.peer_name},
- {"body", message.body},
- {"timestamp", message.timestamp},
- {"outgoing", message.outgoing},
- {"read", message.read},
- {"folder", message.folder},
- };
- }
-
- nlohmann::json to_json(const Thread& thread) {
- return {
- {"thread", thread.key},
- {"name", thread.display_name},
- {"address", thread.peer_address},
- {"preview", thread.last_body},
- {"timestamp", thread.last_timestamp},
- {"unread", thread.unread},
- {"count", thread.count},
- };
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/monitor.cpp b/src/core/src/bluetooth/monitor.cpp
deleted file mode 100644
index b4a0beb..0000000
--- a/src/core/src/bluetooth/monitor.cpp
+++ /dev/null
@@ -1,323 +0,0 @@
-#include "tether/bluetooth/monitor.hpp"
-#include "tether/log.hpp"
-
-#include <atomic>
-#include <condition_variable>
-#include <filesystem>
-#include <fstream>
-#include <gio/gio.h>
-#include <mutex>
-#include <sys/eventfd.h>
-#include <thread>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- BluezMonitor* g_bluez = nullptr;
-
- namespace {
- constexpr const char* BLUEZ_NAME = "org.bluez";
- constexpr const char* OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager";
-
- // BlueZ emits PropertiesChanged continuously during discovery (RSSI churn
- // above all). Coalesce bursts into one refresh instead of re-reading the
- // whole object tree per signal.
- constexpr guint REFRESH_DEBOUNCE_MS = 250;
- } // namespace
-
- struct MonitorState {
- std::thread thread;
- GMainContext* context = nullptr;
- GMainLoop* loop = nullptr;
- GDBusConnection* conn = nullptr;
- std::atomic<bool> running{false};
-
- int efd = -1;
- guint pending_refresh = 0;
- std::vector<guint> subscriptions;
-
- mutable std::mutex mutex;
- BluezObjects objects;
- Capability cap;
-
- void run();
- void refresh();
- void schedule_refresh();
- void notify();
- };
-
- namespace {
-
- gboolean on_refresh_timeout(gpointer user_data) {
- auto* impl = static_cast<MonitorState*>(user_data);
- impl->pending_refresh = 0;
- impl->refresh();
- return G_SOURCE_REMOVE;
- }
-
- void on_bluez_signal(
- GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant*, gpointer user_data) {
- static_cast<MonitorState*>(user_data)->schedule_refresh();
- }
-
- // on watcher thread once it iterates its context
- gboolean quit_loop(gpointer user_data) {
- auto* state = static_cast<MonitorState*>(user_data);
- if (state->loop)
- g_main_loop_quit(state->loop);
- return G_SOURCE_REMOVE;
- }
-
- } // namespace
-
- void MonitorState::notify() {
- if (efd < 0)
- return;
- uint64_t one = 1;
- if (write(efd, &one, sizeof(one)) < 0)
- debug::log(WARN, "bluetooth: failed to signal event fd");
- }
-
- void MonitorState::schedule_refresh() {
- if (pending_refresh != 0)
- return;
- GSource* source = g_timeout_source_new(REFRESH_DEBOUNCE_MS);
- g_source_set_callback(source, on_refresh_timeout, this, nullptr);
- pending_refresh = g_source_attach(source, context);
- g_source_unref(source);
- }
-
- // bluetoothd exposes no property for its own flags, so the argument vector is
- // the only place to read it. Accepts both spellings; Arch's unit uses -E.
- bool bluetoothd_has_experimental() {
- std::error_code ec;
- for (const auto& entry : std::filesystem::directory_iterator("/proc", ec)) {
- std::ifstream comm(entry.path() / "comm");
- std::string name;
- if (!comm || !std::getline(comm, name) || name != "bluetoothd")
- continue;
-
- std::ifstream cmdline(entry.path() / "cmdline", std::ios::binary);
- if (!cmdline)
- continue;
- // Arguments are NUL-separated, so each one compares exactly.
- std::string arg;
- while (std::getline(cmdline, arg, '\0')) {
- if (arg == "-E" || arg == "--experimental")
- return true;
- }
- return false;
- }
- return false;
- }
-
- void MonitorState::refresh() {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn,
- BLUEZ_NAME,
- "/",
- OBJECT_MANAGER,
- "GetManagedObjects",
- nullptr,
- G_VARIANT_TYPE("(a{oa{sa{sv}}})"),
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- debug::log(WARN, "bluetooth: GetManagedObjects failed: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return;
- }
-
- BluezObjects parsed = parse_managed_objects(reply);
- g_variant_unref(reply);
- parsed.experimental_api = bluetoothd_has_experimental();
- Capability resolved = resolve_capability(parsed);
-
- {
- std::lock_guard<std::mutex> lock(mutex);
- if (parsed == objects && resolved == cap)
- return;
- objects = std::move(parsed);
- cap = std::move(resolved);
- }
- notify();
- }
-
- void MonitorState::run() {
- g_main_context_push_thread_default(context);
-
- for (const char* signal : {"InterfacesAdded", "InterfacesRemoved"}) {
- subscriptions.push_back(g_dbus_connection_signal_subscribe(conn,
- BLUEZ_NAME,
- OBJECT_MANAGER,
- signal,
- "/",
- nullptr,
- G_DBUS_SIGNAL_FLAGS_NONE,
- on_bluez_signal,
- this,
- nullptr));
- }
- subscriptions.push_back(g_dbus_connection_signal_subscribe(conn,
- BLUEZ_NAME,
- "org.freedesktop.DBus.Properties",
- "PropertiesChanged",
- nullptr,
- nullptr,
- G_DBUS_SIGNAL_FLAGS_NONE,
- on_bluez_signal,
- this,
- nullptr));
-
- refresh();
-
- loop = g_main_loop_new(context, FALSE);
- g_main_loop_run(loop);
- running = false;
-
- for (guint id : subscriptions)
- g_dbus_connection_signal_unsubscribe(conn, id);
- subscriptions.clear();
-
- if (pending_refresh != 0) {
- if (GSource* s = g_main_context_find_source_by_id(context, pending_refresh))
- g_source_destroy(s);
- pending_refresh = 0;
- }
-
- g_main_context_pop_thread_default(context);
- }
-
- BluezMonitor::BluezMonitor() : impl_(std::make_unique<MonitorState>()) {}
-
- BluezMonitor::~BluezMonitor() { stop(); }
-
- bool BluezMonitor::start() {
- if (impl_->running)
- return true;
-
- GError* error = nullptr;
- impl_->conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
- if (!impl_->conn) {
- debug::log(WARN, "bluetooth: cannot reach the system bus: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
-
- // fail fast when bluetoothd is not present
- GVariant* probe = g_dbus_connection_call_sync(impl_->conn,
- BLUEZ_NAME,
- "/",
- OBJECT_MANAGER,
- "GetManagedObjects",
- nullptr,
- G_VARIANT_TYPE("(a{oa{sa{sv}}})"),
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!probe) {
- debug::log(WARN, "bluetooth: BlueZ unavailable: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- g_clear_object(&impl_->conn);
- return false;
- }
- impl_->objects = parse_managed_objects(probe);
- impl_->objects.experimental_api = bluetoothd_has_experimental();
- impl_->cap = resolve_capability(impl_->objects);
- g_variant_unref(probe);
-
- impl_->efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
- if (impl_->efd < 0) {
- debug::log(ERR, "bluetooth: eventfd() failed");
- g_clear_object(&impl_->conn);
- return false;
- }
-
- impl_->context = g_main_context_new();
- impl_->running = true;
- impl_->thread = std::thread([this] { impl_->run(); });
- return true;
- }
-
- void BluezMonitor::stop() {
- if (impl_->thread.joinable()) {
- g_main_context_invoke(impl_->context, quit_loop, impl_.get());
- impl_->thread.join();
- }
- if (impl_->loop) {
- g_main_loop_unref(impl_->loop);
- impl_->loop = nullptr;
- }
- if (impl_->context) {
- g_main_context_unref(impl_->context);
- impl_->context = nullptr;
- }
- g_clear_object(&impl_->conn);
- if (impl_->efd >= 0) {
- close(impl_->efd);
- impl_->efd = -1;
- }
- }
-
- bool BluezMonitor::running() const { return impl_->running; }
-
- int BluezMonitor::event_fd() const { return impl_->efd; }
-
- void BluezMonitor::drain() {
- if (impl_->efd < 0)
- return;
- uint64_t counter = 0;
- while (read(impl_->efd, &counter, sizeof(counter)) > 0) {
- // Drain every pending wakeup; the snapshot is read separately.
- }
- }
-
- GDBusConnection* BluezMonitor::connection() const { return impl_->conn; }
-
- void BluezMonitor::invoke_sync(const std::function<void()>& fn) {
- if (!impl_->context) {
- fn();
- return;
- }
-
- struct Job {
- const std::function<void()>* fn;
- std::mutex mutex;
- std::condition_variable done;
- bool finished = false;
- } job{&fn, {}, {}, false};
-
- g_main_context_invoke_full(
- impl_->context,
- G_PRIORITY_DEFAULT,
- [](gpointer data) -> gboolean {
- auto* j = static_cast<Job*>(data);
- (*j->fn)();
- {
- std::lock_guard<std::mutex> lock(j->mutex);
- j->finished = true;
- }
- j->done.notify_all();
- return G_SOURCE_REMOVE;
- },
- &job,
- nullptr);
-
- std::unique_lock<std::mutex> lock(job.mutex);
- job.done.wait(lock, [&job] { return job.finished; });
- }
-
- BluezObjects BluezMonitor::snapshot() const {
- std::lock_guard<std::mutex> lock(impl_->mutex);
- return impl_->objects;
- }
-
- Capability BluezMonitor::capability() const {
- std::lock_guard<std::mutex> lock(impl_->mutex);
- return impl_->cap;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/obex_transfer.cpp b/src/core/src/bluetooth/obex_transfer.cpp
deleted file mode 100644
index be9805a..0000000
--- a/src/core/src/bluetooth/obex_transfer.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-#include "tether/bluetooth/obex_transfer.hpp"
-
-#include <chrono>
-#include <thread>
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* OBEX_NAME = "org.bluez.obex";
- constexpr const char* IFACE_TRANSFER = "org.bluez.obex.Transfer1";
- constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";
- constexpr int POLL_INTERVAL_MS = 200;
-
- TransferState poll_once(GDBusConnection* bus, const std::string& path) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(bus,
- OBEX_NAME,
- path.c_str(),
- IFACE_PROPS,
- "Get",
- g_variant_new("(ss)", IFACE_TRANSFER, "Status"),
- G_VARIANT_TYPE("(v)"),
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- g_clear_error(&error);
- return TransferState::Gone;
- }
-
- GVariant* boxed = nullptr;
- g_variant_get(reply, "(v)", &boxed);
- std::string status;
- if (boxed && g_variant_is_of_type(boxed, G_VARIANT_TYPE_STRING))
- status = g_variant_get_string(boxed, nullptr);
- if (boxed)
- g_variant_unref(boxed);
- g_variant_unref(reply);
-
- if (status == "complete")
- return TransferState::Complete;
- if (status == "error")
- return TransferState::Error;
- return TransferState::Active;
- }
-
- } // namespace
-
- TransferState wait_for_transfer(GDBusConnection* bus, const std::string& path, int timeout_seconds) {
- const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_seconds);
- TransferState state = TransferState::Active;
- while (std::chrono::steady_clock::now() < deadline) {
- state = poll_once(bus, path);
- if (state != TransferState::Active)
- return state;
- std::this_thread::sleep_for(std::chrono::milliseconds(POLL_INTERVAL_MS));
- }
- return state;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/objects.cpp b/src/core/src/bluetooth/objects.cpp
deleted file mode 100644
index b00cf8a..0000000
--- a/src/core/src/bluetooth/objects.cpp
+++ /dev/null
@@ -1,358 +0,0 @@
-#include "tether/bluetooth/objects.hpp"
-
-#include <algorithm>
-#include <cstring>
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* IFACE_ADAPTER = "org.bluez.Adapter1";
- constexpr const char* IFACE_DEVICE = "org.bluez.Device1";
- constexpr const char* IFACE_LE_ADV_MGR = "org.bluez.LEAdvertisingManager1";
- constexpr const char* IFACE_BEARER_LE = "org.bluez.Bearer.LE1";
-
- bool iequals(const std::string& a, const std::string& b) {
- return a.size() == b.size() &&
- std::equal(a.begin(), a.end(), b.begin(), [](unsigned char x, unsigned char y) {
- return std::tolower(x) == std::tolower(y);
- });
- }
-
- // Property lookup helpers. Every one tolerates a missing key or an
- // unexpected type.
- GVariant* lookup(GVariant* props, const char* key) {
- if (!props || !g_variant_is_of_type(props, G_VARIANT_TYPE("a{sv}")))
- return nullptr;
- return g_variant_lookup_value(props, key, nullptr);
- }
-
- std::string get_string(GVariant* props, const char* key) {
- GVariant* v = lookup(props, key);
- if (!v)
- return {};
- std::string out;
- if (g_variant_is_of_type(v, G_VARIANT_TYPE_STRING))
- out = g_variant_get_string(v, nullptr);
- g_variant_unref(v);
- return out;
- }
-
- bool get_bool(GVariant* props, const char* key, bool fallback = false) {
- GVariant* v = lookup(props, key);
- if (!v)
- return fallback;
- bool out = fallback;
- if (g_variant_is_of_type(v, G_VARIANT_TYPE_BOOLEAN))
- out = g_variant_get_boolean(v);
- g_variant_unref(v);
- return out;
- }
-
- uint32_t get_uint32(GVariant* props, const char* key) {
- GVariant* v = lookup(props, key);
- if (!v)
- return 0;
- uint32_t out = 0;
- if (g_variant_is_of_type(v, G_VARIANT_TYPE_UINT32))
- out = g_variant_get_uint32(v);
- g_variant_unref(v);
- return out;
- }
-
- uint8_t get_byte(GVariant* props, const char* key) {
- GVariant* v = lookup(props, key);
- if (!v)
- return 0;
- uint8_t out = 0;
- if (g_variant_is_of_type(v, G_VARIANT_TYPE_BYTE))
- out = g_variant_get_byte(v);
- g_variant_unref(v);
- return out;
- }
-
- std::vector<std::string> get_strv(GVariant* props, const char* key) {
- std::vector<std::string> out;
- GVariant* v = lookup(props, key);
- if (!v)
- return out;
- if (g_variant_is_of_type(v, G_VARIANT_TYPE_STRING_ARRAY)) {
- gsize n = 0;
- const gchar** items = g_variant_get_strv(v, &n);
- if (items) {
- out.reserve(n);
- for (gsize i = 0; i < n; ++i)
- out.emplace_back(items[i]);
- g_free(items);
- }
- }
- g_variant_unref(v);
- return out;
- }
-
- // BlueZ nests the object path under the adapter, e.g.
- // /org/bluez/hci0/dev_AA_BB_.. the parent path is the owning adapter.
- std::string parent_path(const std::string& path) {
- size_t slash = path.rfind('/');
- if (slash == std::string::npos || slash == 0)
- return {};
- return path.substr(0, slash);
- }
-
- void read_adapter(const std::string& path, GVariant* ifaces, BluezObjects& out) {
- GVariant* props = g_variant_lookup_value(ifaces, IFACE_ADAPTER, G_VARIANT_TYPE("a{sv}"));
- if (!props)
- return;
-
- Adapter a;
- a.path = path;
- a.address = get_string(props, "Address");
- a.name = get_string(props, "Alias");
- if (a.name.empty())
- a.name = get_string(props, "Name");
- a.device_class = get_uint32(props, "Class");
- a.powered = get_bool(props, "Powered");
- a.roles = get_strv(props, "Roles");
- g_variant_unref(props);
-
- if (GVariant* adv = g_variant_lookup_value(ifaces, IFACE_LE_ADV_MGR, G_VARIANT_TYPE("a{sv}"))) {
- a.has_advertising_manager = true;
- a.advertising_instances = get_byte(adv, "SupportedInstances");
- g_variant_unref(adv);
- }
-
- out.adapters.push_back(std::move(a));
- }
-
- void read_device(const std::string& path, GVariant* ifaces, BluezObjects& out) {
- GVariant* props = g_variant_lookup_value(ifaces, IFACE_DEVICE, G_VARIANT_TYPE("a{sv}"));
- if (!props)
- return;
-
- Device d;
- d.path = path;
- d.adapter_path = get_string(props, "Adapter");
- if (d.adapter_path.empty())
- d.adapter_path = parent_path(path);
- d.address = get_string(props, "Address");
- d.name = get_string(props, "Alias");
- if (d.name.empty())
- d.name = get_string(props, "Name");
- d.paired = get_bool(props, "Paired");
- // Older BlueZ has no Bonded property; a paired device is bonded there.
- d.bonded = get_bool(props, "Bonded", d.paired);
- d.trusted = get_bool(props, "Trusted");
- d.connected = get_bool(props, "Connected");
- d.uuids = get_strv(props, "UUIDs");
- g_variant_unref(props);
-
- if (GVariant* le = g_variant_lookup_value(ifaces, IFACE_BEARER_LE, G_VARIANT_TYPE("a{sv}"))) {
- d.has_le_bearer = true;
- d.le_paired = get_bool(le, "Paired");
- d.le_bonded = get_bool(le, "Bonded", d.le_paired);
- d.le_connected = get_bool(le, "Connected");
- g_variant_unref(le);
- }
-
- out.devices.push_back(std::move(d));
- }
-
- } // namespace
-
- bool Adapter::has_role(const std::string& role) const {
- return std::find(roles.begin(), roles.end(), role) != roles.end();
- }
-
- bool Device::has_uuid(const std::string& uuid) const {
- return std::any_of(uuids.begin(), uuids.end(), [&](const std::string& u) { return iequals(u, uuid); });
- }
-
- bool Device::looks_like_iphone() const { return supports_ancs() || (supports_map() && supports_pbap()); }
-
- const Adapter* BluezObjects::find_adapter(const std::string& path) const {
- auto it = std::find_if(adapters.begin(), adapters.end(), [&](const Adapter& a) { return a.path == path; });
- return it == adapters.end() ? nullptr : &*it;
- }
-
- const Device* BluezObjects::find_device(const std::string& path) const {
- auto it = std::find_if(devices.begin(), devices.end(), [&](const Device& d) { return d.path == path; });
- return it == devices.end() ? nullptr : &*it;
- }
-
- const char* to_string(DeliveryMode mode) {
- switch (mode) {
- case DeliveryMode::Full:
- return "full";
- case DeliveryMode::Compatibility:
- return "compatibility";
- default:
- return "blocked";
- }
- }
-
- const char* to_string(BearerApi api) {
- switch (api) {
- case BearerApi::Confirmed:
- return "confirmed";
- case BearerApi::Absent:
- return "absent";
- default:
- return "unknown";
- }
- }
-
- BluezObjects parse_managed_objects(GVariant* reply) {
- BluezObjects out;
- if (!reply)
- return out;
-
- // g_dbus_connection_call returns the reply wrapped in a single-element
- // tuple; tests and callers may pass the dictionary directly.
- GVariant* dict = nullptr;
- if (g_variant_is_of_type(reply, G_VARIANT_TYPE("(a{oa{sa{sv}}})")))
- dict = g_variant_get_child_value(reply, 0);
- else if (g_variant_is_of_type(reply, G_VARIANT_TYPE("a{oa{sa{sv}}}")))
- dict = g_variant_ref(reply);
- else
- return out;
-
- GVariantIter iter;
- const gchar* path = nullptr;
- GVariant* ifaces = nullptr;
- g_variant_iter_init(&iter, dict);
- while (g_variant_iter_loop(&iter, "{&o@a{sa{sv}}}", &path, &ifaces)) {
- read_adapter(path, ifaces, out);
- read_device(path, ifaces, out);
- }
- g_variant_unref(dict);
-
- // BlueZ enumerates in a stable but unspecified order; sorting keeps
- // snapshot comparison and UI listing deterministic.
- std::sort(out.adapters.begin(), out.adapters.end(), [](const Adapter& a, const Adapter& b) {
- return a.path < b.path;
- });
- std::sort(
- out.devices.begin(), out.devices.end(), [](const Device& a, const Device& b) { return a.path < b.path; });
- return out;
- }
-
- Capability resolve_capability(const BluezObjects& objects) {
- Capability cap;
-
- // prefer powered adapter, fall back to the first so the reasons below
- // can explain an unpowered one rather than reporting nothing at all.
- const Adapter* adapter = nullptr;
- for (const auto& a : objects.adapters) {
- if (a.powered) {
- adapter = &a;
- break;
- }
- }
- if (!adapter && !objects.adapters.empty())
- adapter = &objects.adapters.front();
-
- if (!adapter) {
- cap.reasons.emplace_back("No Bluetooth adapter found.");
- return cap;
- }
-
- cap.adapter_present = true;
- cap.powered = adapter->powered;
- cap.le_central = adapter->has_role("central");
- cap.le_peripheral = adapter->has_role("peripheral");
- cap.advertising = adapter->has_advertising_manager && adapter->advertising_instances > 0;
- cap.class_ok = adapter->class_is_handsfree();
-
- for (const auto& d : objects.devices) {
- if (d.has_le_bearer)
- cap.bearer_api = BearerApi::Confirmed;
- }
- if (cap.bearer_api != BearerApi::Confirmed)
- cap.bearer_api = objects.experimental_api ? BearerApi::Unknown : BearerApi::Absent;
-
- if (!cap.powered) {
- cap.reasons.emplace_back("Bluetooth adapter is powered off.");
- cap.mode = DeliveryMode::Blocked;
- return cap;
- }
- if (!cap.le_central) {
- cap.reasons.emplace_back("Adapter has no LE central role; ANCS is impossible.");
- cap.mode = DeliveryMode::Blocked;
- return cap;
- }
-
- // Past this point messages and contacts are reachable; only ANCS is at risk.
- cap.mode = DeliveryMode::Full;
-
- if (!cap.le_peripheral) {
- cap.reasons.emplace_back("Adapter cannot advertise as a peripheral, so ANCS cannot be solicited.");
- cap.mode = DeliveryMode::Compatibility;
- }
- if (!cap.advertising) {
- cap.reasons.emplace_back("No LE advertising instances available; the iPhone may never show its "
- "Bluetooth permission toggles.");
- cap.mode = DeliveryMode::Compatibility;
- }
- if (cap.bearer_api == BearerApi::Absent) {
- cap.reasons.emplace_back("BlueZ is not exposing org.bluez.Bearer.LE1. Run bluetoothd with "
- "--experimental to enable notification mirroring.");
- cap.mode = DeliveryMode::Compatibility;
- } else if (cap.bearer_api == BearerApi::Unknown) {
- cap.reasons.emplace_back("Bearer API support is unconfirmed until a device is bonded.");
- }
- if (!cap.class_ok) {
- cap.reasons.emplace_back("Adapter Class of Device is not A/V Hands-Free (major 4, minor 8); "
- "the iPhone will not offer its Messages and Contacts permissions.");
- }
-
- return cap;
- }
-
- nlohmann::json to_json(const Adapter& a) {
- return {
- {"path", a.path},
- {"address", a.address},
- {"name", a.name},
- {"class", a.device_class},
- {"powered", a.powered},
- {"roles", a.roles},
- {"advertising_instances", a.advertising_instances},
- {"class_ok", a.class_is_handsfree()},
- };
- }
-
- nlohmann::json to_json(const Device& d) {
- return {
- {"path", d.path},
- {"adapter", d.adapter_path},
- {"address", d.address},
- {"name", d.name},
- {"paired", d.paired},
- {"bonded", d.bonded},
- {"trusted", d.trusted},
- {"connected", d.connected},
- {"le_bearer", d.has_le_bearer},
- {"le_bonded", d.le_bonded},
- {"le_connected", d.le_connected},
- {"map", d.supports_map()},
- {"pbap", d.supports_pbap()},
- {"ancs", d.supports_ancs()},
- {"iphone", d.looks_like_iphone()},
- };
- }
-
- nlohmann::json to_json(const Capability& c) {
- return {
- {"mode", to_string(c.mode)},
- {"bearer_api", to_string(c.bearer_api)},
- {"adapter_present", c.adapter_present},
- {"powered", c.powered},
- {"le_central", c.le_central},
- {"le_peripheral", c.le_peripheral},
- {"advertising", c.advertising},
- {"class_ok", c.class_ok},
- {"reasons", c.reasons},
- };
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/pairing.cpp b/src/core/src/bluetooth/pairing.cpp
deleted file mode 100644
index dad6994..0000000
--- a/src/core/src/bluetooth/pairing.cpp
+++ /dev/null
@@ -1,516 +0,0 @@
-#include "tether/bluetooth/pairing.hpp"
-#include "tether/bluetooth/advert.hpp"
-#include "tether/bluetooth/agent.hpp"
-#include "tether/bluetooth/monitor.hpp"
-#include "tether/log.hpp"
-
-#include <chrono>
-#include <filesystem>
-#include <sys/wait.h>
-#include <thread>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* BLUEZ_NAME = "org.bluez";
- constexpr const char* IFACE_DEVICE = "org.bluez.Device1";
- constexpr const char* IFACE_ADAPTER = "org.bluez.Adapter1";
- constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";
-
- // iphone shows its confirmation prompt and waits for a slow human
- constexpr int PAIR_TIMEOUT_SECONDS = 90;
- constexpr int DIALOG_TIMEOUT_SECONDS = 60;
-
- constexpr int CLASSIC_SETTLE_SECONDS = 3;
- constexpr int DISCOVERY_TIMEOUT_SECONDS = 30;
-
- std::string normalize_address(std::string address) {
- for (char& c : address)
- c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
- return address;
- }
-
- void notify(const ProgressFn& progress, const std::string& step, const std::string& detail) {
- debug::log(INFO, "bluetooth: {} {}", step, detail);
- if (progress)
- progress(step, detail);
- }
-
- bool set_property(GDBusConnection* conn,
- const std::string& path,
- const char* iface,
- const char* name,
- GVariant* value,
- std::string* err_out = nullptr) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn,
- BLUEZ_NAME,
- path.c_str(),
- IFACE_PROPS,
- "Set",
- g_variant_new("(ssv)", iface, name, value),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- if (err_out)
- *err_out = error ? error->message : "unknown";
- g_clear_error(&error);
- return false;
- }
- g_variant_unref(reply);
- return true;
- }
-
- bool call_device(
- GDBusConnection* conn, const std::string& path, const char* method, int timeout_ms, std::string& err_out) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn,
- BLUEZ_NAME,
- path.c_str(),
- IFACE_DEVICE,
- method,
- nullptr,
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- timeout_ms,
- nullptr,
- &error);
- if (!reply) {
- err_out = error ? error->message : "unknown error";
- g_clear_error(&error);
- return false;
- }
- g_variant_unref(reply);
- return true;
- }
-
- const Device* find_by_address(const BluezObjects& objects, const std::string& address) {
- for (const auto& d : objects.devices) {
- if (normalize_address(d.address) == address)
- return &d;
- }
- return nullptr;
- }
-
- // Copies out the device record rather than holding a pointer into a
- // snapshot that the watcher thread replaces underneath us.
- bool lookup(BluezMonitor& monitor, const std::string& address, Device& out) {
- auto objects = monitor.snapshot();
- if (const Device* d = find_by_address(objects, address)) {
- out = *d;
- return true;
- }
- return false;
- }
-
- bool call_adapter(GDBusConnection* conn, const std::string& path, const char* method) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn,
- BLUEZ_NAME,
- path.c_str(),
- IFACE_ADAPTER,
- method,
- nullptr,
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- debug::log(WARN, "bluetooth: {} failed: {}", method, error ? error->message : "unknown");
- g_clear_error(&error);
- return false;
- }
- g_variant_unref(reply);
- return true;
- }
-
- // Scans until the device shows up. Needed because an unpair makes BlueZ
- // forget the device entirely, which would otherwise leave no way to pair
- // again from inside the app.
- bool discover(BluezMonitor& monitor, GDBusConnection* conn, const std::string& address, Device& out) {
- auto objects = monitor.snapshot();
- if (objects.adapters.empty())
- return false;
- const std::string adapter = objects.adapters.front().path;
-
- if (!call_adapter(conn, adapter, "StartDiscovery"))
- return false;
-
- const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(DISCOVERY_TIMEOUT_SECONDS);
- bool found = false;
- while (std::chrono::steady_clock::now() < deadline) {
- if (lookup(monitor, address, out)) {
- found = true;
- break;
- }
- std::this_thread::sleep_for(std::chrono::milliseconds(500));
- }
-
- // discovery must stop before pairing
- call_adapter(conn, adapter, "StopDiscovery");
- return found;
- }
-
- // Connect-first makes the iPhone the authentication initiator, so BlueZ
- // must accept an inbound pairing request for the transaction to complete.
- // A desktop adapter normally sits with Pairable off, in which case iOS
- // never shows its half of the numeric comparison and the link fails with
- // br-connection-key-missing.
- //
- // Restores the previous values on every exit path, including the early
- // returns and the timeout.
- class PairableWindow {
- public:
- PairableWindow(GDBusConnection* conn, std::string adapter) : conn_(conn), adapter_(std::move(adapter)) {
- if (adapter_.empty())
- return;
- was_pairable_ = get_bool(IFACE_ADAPTER, "Pairable");
- was_discoverable_ = get_bool(IFACE_ADAPTER, "Discoverable");
- set_bool("Pairable", true);
- set_bool("Discoverable", true);
- }
-
- ~PairableWindow() {
- if (adapter_.empty())
- return;
- set_bool("Pairable", was_pairable_);
- set_bool("Discoverable", was_discoverable_);
- }
-
- PairableWindow(const PairableWindow&) = delete;
- PairableWindow& operator=(const PairableWindow&) = delete;
-
- private:
- bool get_bool(const char* iface, const char* name) const {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn_,
- BLUEZ_NAME,
- adapter_.c_str(),
- IFACE_PROPS,
- "Get",
- g_variant_new("(ss)", iface, name),
- G_VARIANT_TYPE("(v)"),
- G_DBUS_CALL_FLAGS_NONE,
- 5000,
- nullptr,
- &error);
- if (!reply) {
- g_clear_error(&error);
- return false;
- }
- GVariant* boxed = nullptr;
- g_variant_get(reply, "(v)", &boxed);
- const bool value = boxed && g_variant_get_boolean(boxed);
- if (boxed)
- g_variant_unref(boxed);
- g_variant_unref(reply);
- return value;
- }
-
- void set_bool(const char* name, bool value) const {
- set_property(conn_, adapter_, IFACE_ADAPTER, name, g_variant_new_boolean(value));
- }
-
- GDBusConnection* conn_;
- std::string adapter_;
- bool was_pairable_ = false;
- bool was_discoverable_ = false;
- };
-
- std::string adapter_for(BluezMonitor& monitor, const Device& device) {
- if (!device.adapter_path.empty())
- return device.adapter_path;
- auto objects = monitor.snapshot();
- return objects.adapters.empty() ? std::string{} : objects.adapters.front().path;
- }
-
- // The solicitation advertise outlives the transaction that started it, so it
- // is owned here rather than on a stack frame.
- AncsAdvertisement* g_advert = nullptr;
-
- // An advert soliciting ANCS must never be on air while Classic pairing is in flight
- void stop_advert(BluezMonitor& monitor) {
- if (!g_advert)
- return;
- g_advert->unregister_with_bluez();
- monitor.invoke_sync([&] { g_advert->unexport_object(); });
- delete g_advert;
- g_advert = nullptr;
- }
-
- } // namespace
-
- bool confirm_with_dialog(const std::string& device_name, const std::string& code) {
- std::string body =
- device_name + " wants to pair.\n\nConfirm this code matches the one on your iPhone:\n\n" + code;
-
- pid_t pid = fork();
- if (pid < 0) {
- debug::log(ERR, "bluetooth: fork() for confirmation dialog failed");
- return false;
- }
-
- if (pid == 0) {
- std::filesystem::path self_path;
- try {
- self_path = std::filesystem::read_symlink("/proc/self/exe");
- } catch (...) {
- }
- std::string sibling = (self_path.parent_path() / "tether-dialog").string();
- std::string timeout = std::to_string(DIALOG_TIMEOUT_SECONDS);
-
- execl(sibling.c_str(),
- "tether-dialog",
- "--title",
- "Bluetooth Pairing",
- "--body",
- body.c_str(),
- "--accept",
- "Confirm",
- "--reject",
- "Cancel",
- "--timeout",
- timeout.c_str(),
- nullptr);
- execlp("tether-dialog",
- "tether-dialog",
- "--title",
- "Bluetooth Pairing",
- "--body",
- body.c_str(),
- "--accept",
- "Confirm",
- "--reject",
- "Cancel",
- "--timeout",
- timeout.c_str(),
- nullptr);
- _exit(3);
- }
-
- int status = 0;
- if (waitpid(pid, &status, 0) < 0)
- return false;
- // Exit 0 is the only acceptance. A dialog that could not be shown exits 3,
- // which must reject rather than silently bond.
- return WIFEXITED(status) && WEXITSTATUS(status) == 0;
- }
-
- nlohmann::json to_json(const PairResult& result) {
- return {
- {"command", "bt_pair_result"},
- {"success", result.success},
- {"status", result.status},
- {"message", result.message},
- {"address", result.device_address},
- {"dual_bond", result.dual_bond},
- };
- }
-
- PairResult pair_device(BluezMonitor& monitor,
- const std::string& address,
- AuthStrategy strategy,
- const ProgressFn& progress,
- const ConfirmFn& confirm) {
- PairResult result;
- result.device_address = normalize_address(address);
-
- GDBusConnection* conn = monitor.connection();
- if (!conn) {
- result.status = "error";
- result.message = "Bluetooth is unavailable.";
- return result;
- }
-
- PairableWindow pairable(conn, [&] {
- auto objects = monitor.snapshot();
- return objects.adapters.empty() ? std::string{} : objects.adapters.front().path;
- }());
-
- Device device;
- if (!lookup(monitor, result.device_address, device)) {
- notify(progress, "discovering", result.device_address);
- if (!discover(monitor, conn, result.device_address, device)) {
- result.status = "not_found";
- result.message = "Device " + result.device_address +
- " is not visible to BlueZ. Unlock the iPhone and open its Bluetooth settings so it "
- "is discoverable, then try again.";
- return result;
- }
- }
- result.device_path = device.path;
-
- const std::string adapter_path = adapter_for(monitor, device);
- const std::string display_name = device.name.empty() ? result.device_address : device.name;
-
- if (device.paired) {
- notify(progress, "already_paired", display_name);
- result.success = true;
- result.status = "already_paired";
- result.dual_bond = device.has_le_bearer && device.le_bonded;
- result.message = display_name + " is already paired.";
- } else {
- auto cap = monitor.capability();
- if (!cap.class_ok) {
- notify(progress,
- "warning",
- "Adapter class is not A/V Hands-Free; the iPhone may not offer its permissions. "
- "Run scripts/bt-probe.sh --set-class.");
- }
-
- // Silence any advert left over from an earlier pairing before
- // authentication starts.
- stop_advert(monitor);
-
- PairingAgent agent(conn, device.path, [&](const std::string& code) {
- notify(progress, "confirm", code);
- return confirm ? confirm(code) : confirm_with_dialog(display_name, code);
- });
-
- bool exported = false;
- monitor.invoke_sync([&] { exported = agent.export_object(); });
- if (!exported || !agent.register_with_bluez()) {
- monitor.invoke_sync([&] { agent.unexport_object(); });
- result.status = "error";
- result.message = "Could not register a Bluetooth pairing agent.";
- return result;
- }
-
- std::string err;
- bool initiated = false;
- if (strategy == AuthStrategy::ConnectFirst) {
- notify(progress, "connecting", display_name);
- initiated = call_device(conn, device.path, "Connect", PAIR_TIMEOUT_SECONDS * 1000, err);
- } else {
- notify(progress, "pairing", display_name);
- initiated = call_device(conn, device.path, "Pair", PAIR_TIMEOUT_SECONDS * 1000, err);
- }
-
- // Connect() can report failure while authentication still completes
- auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(PAIR_TIMEOUT_SECONDS);
- bool paired = false;
- while (std::chrono::steady_clock::now() < deadline) {
- Device current;
- if (lookup(monitor, result.device_address, current) && current.paired) {
- paired = true;
- device = current;
- break;
- }
- std::this_thread::sleep_for(std::chrono::milliseconds(500));
- }
-
- agent.unregister_with_bluez();
- monitor.invoke_sync([&] { agent.unexport_object(); });
-
- if (!paired) {
- result.status = err.find("Rejected") != std::string::npos ? "rejected" : "timeout";
- result.message = initiated ? "Pairing did not complete. Confirm the prompt on the iPhone."
- : ("Pairing failed: " + err);
- return result;
- }
-
- notify(progress, "paired", display_name);
- result.success = true;
- result.status = "paired";
- result.message = "Paired with " + display_name + ".";
- }
-
- // Trusting the bond lets BlueZ reconnect without asking again.
- std::string trust_err;
- if (!set_property(conn, device.path, IFACE_DEVICE, "Trusted", g_variant_new_boolean(TRUE), &trust_err))
- debug::log(WARN, "bluetooth: could not trust device: {}", trust_err);
-
- // Prefer BR/EDR for the next outbound connection, then let the Classic ACL
- // settle before anything touches LE. Older BlueZ has no such property.
- set_property(conn, device.path, IFACE_DEVICE, "PreferredBearer", g_variant_new_string("bredr"));
- notify(progress, "settling", "waiting for the Classic link to settle");
- std::this_thread::sleep_for(std::chrono::seconds(CLASSIC_SETTLE_SECONDS));
-
- Device settled;
- if (lookup(monitor, result.device_address, settled))
- result.dual_bond = settled.has_le_bearer && settled.le_bonded;
-
- // Only now solicit ANCS. This advert is what makes iOS reveal its
- // "Show Message Notifications" and "Sync Contacts" toggles, and it is safe
- // to broadcast because the bond already exists.
- if (!adapter_path.empty() && monitor.capability().advertising) {
- stop_advert(monitor);
- auto* advert = new AncsAdvertisement(conn, adapter_path);
-
- bool exported = false;
- monitor.invoke_sync([&] { exported = advert->export_object(); });
- // BlueZ reads the advertisement's properties back before returning, so
- // this call must stay off the thread that answers those reads.
- if (exported && advert->register_with_bluez()) {
- g_advert = advert;
- notify(progress,
- "soliciting",
- "Open Settings > Bluetooth > (i) on the iPhone and enable Show Message Notifications and "
- "Sync Contacts. They can take a few minutes to appear.");
- } else {
- monitor.invoke_sync([&] { advert->unexport_object(); });
- delete advert;
- notify(progress, "warning", "Could not advertise for ANCS; notification permissions may not appear.");
- }
- }
-
- if (!result.dual_bond) {
- result.message += " The bond covers BR/EDR only, so messages and contacts will work but notification "
- "mirroring will not.";
- }
- return result;
- }
-
- PairResult unpair_device(BluezMonitor& monitor, const std::string& address) {
- PairResult result;
- result.device_address = normalize_address(address);
-
- GDBusConnection* conn = monitor.connection();
- if (!conn) {
- result.status = "error";
- result.message = "Bluetooth is unavailable.";
- return result;
- }
-
- Device device;
- if (!lookup(monitor, result.device_address, device)) {
- result.status = "not_found";
- result.message = "Device " + result.device_address + " is not known to BlueZ.";
- return result;
- }
-
- const std::string adapter_path = adapter_for(monitor, device);
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(conn,
- BLUEZ_NAME,
- adapter_path.c_str(),
- IFACE_ADAPTER,
- "RemoveDevice",
- g_variant_new("(o)", device.path.c_str()),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- 10000,
- nullptr,
- &error);
- if (!reply) {
- result.status = "error";
- result.message = std::string("Could not remove the bond: ") + (error ? error->message : "unknown");
- g_clear_error(&error);
- return result;
- }
- g_variant_unref(reply);
-
- result.success = true;
- result.status = "unpaired";
- result.message = "Removed the bond. Also delete this computer from the iPhone's Bluetooth settings before "
- "pairing again — a stale record there will block a clean retry.";
- return result;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/pbap_session.cpp b/src/core/src/bluetooth/pbap_session.cpp
deleted file mode 100644
index 4fbf61c..0000000
--- a/src/core/src/bluetooth/pbap_session.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-#include "tether/bluetooth/pbap_session.hpp"
-#include "tether/bluetooth/obex_transfer.hpp"
-
-#include <chrono>
-#include <cstdlib>
-#include <filesystem>
-#include <fstream>
-#include <thread>
-#include <unistd.h>
-
-namespace tether::bluetooth {
-
- namespace {
-
- constexpr const char* OBEX_NAME = "org.bluez.obex";
- constexpr const char* IFACE_PBAP = "org.bluez.obex.PhonebookAccess1";
-
- constexpr int POLL_INTERVAL_MS = 200;
-
- bool take_error(GError*& error, std::string& err_out) {
- err_out = error ? error->message : "unknown error";
- g_clear_error(&error);
- return false;
- }
-
- // The phonebook is personal data, so it is staged in the per-user runtime
- // directory rather than a world-readable /tmp.
- std::filesystem::path staging_file() {
- const char* runtime = getenv("XDG_RUNTIME_DIR");
- std::filesystem::path dir =
- runtime && *runtime ? std::filesystem::path(runtime) : std::filesystem::temp_directory_path();
- return dir / ("tether-pbap-" + std::to_string(getpid()) + ".vcf");
- }
-
- std::string read_file(const std::filesystem::path& path) {
- std::ifstream in(path, std::ios::binary);
- if (!in.is_open())
- return {};
- return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
- }
-
- } // namespace
-
- struct PbapSessionState {
- GDBusConnection* bus = nullptr;
- std::string path;
- };
-
- PbapSession::PbapSession(GDBusConnection* session_bus, std::string session_path)
- : state_(std::make_unique<PbapSessionState>()) {
- state_->bus = session_bus;
- state_->path = std::move(session_path);
- }
-
- PbapSession::~PbapSession() = default;
-
- const std::string& PbapSession::path() const { return state_->path; }
-
- bool PbapSession::select_phonebook(std::string& err, const std::string& location, const std::string& phonebook) {
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- state_->path.c_str(),
- IFACE_PBAP,
- "Select",
- g_variant_new("(ss)", location.c_str(), phonebook.c_str()),
- nullptr,
- G_DBUS_CALL_FLAGS_NONE,
- PBAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply)
- return take_error(error, err);
- g_variant_unref(reply);
- return true;
- }
-
- std::vector<VCard> PbapSession::pull_all(std::string& err, int max) {
- std::vector<VCard> contacts;
-
- const std::filesystem::path target = staging_file();
- std::error_code ec;
- std::filesystem::remove(target, ec);
-
- GVariantBuilder filter;
- g_variant_builder_init(&filter, G_VARIANT_TYPE("a{sv}"));
- g_variant_builder_add(&filter, "{sv}", "Format", g_variant_new_string("vcard30"));
- // MaxCount, not MAP's MaxListCount.
- g_variant_builder_add(&filter, "{sv}", "MaxCount", g_variant_new_uint16(static_cast<guint16>(max)));
-
- GError* error = nullptr;
- GVariant* reply = g_dbus_connection_call_sync(state_->bus,
- OBEX_NAME,
- state_->path.c_str(),
- IFACE_PBAP,
- "PullAll",
- g_variant_new("(sa{sv})", target.c_str(), &filter),
- G_VARIANT_TYPE("(oa{sv})"),
- G_DBUS_CALL_FLAGS_NONE,
- PBAP_CALL_TIMEOUT_MS,
- nullptr,
- &error);
- if (!reply) {
- take_error(error, err);
- return contacts;
- }
-
- const gchar* transfer_path = nullptr;
- GVariant* props = nullptr;
- g_variant_get(reply, "(&o@a{sv})", &transfer_path, &props);
- const std::string transfer = transfer_path ? transfer_path : "";
- if (props)
- g_variant_unref(props);
- g_variant_unref(reply);
-
- if (transfer.empty()) {
- err = "obexd returned no transfer object";
- return contacts;
- }
-
- const TransferState state = wait_for_transfer(state_->bus, transfer, PBAP_TRANSFER_TIMEOUT_SECONDS);
-
- if (state == TransferState::Error) {
- err = "phonebook transfer failed";
- std::filesystem::remove(target, ec);
- return contacts;
- }
- if (state == TransferState::Active) {
- err = "phonebook transfer timed out";
- std::filesystem::remove(target, ec);
- return contacts;
- }
-
- // Both Complete and Gone are terminal, and in either case the file can
- // still be a moment behind, so wait a bounded time for it to appear.
- const auto grace = std::chrono::steady_clock::now() + std::chrono::seconds(PBAP_FILE_GRACE_SECONDS);
- while (!std::filesystem::exists(target, ec) && std::chrono::steady_clock::now() < grace)
- std::this_thread::sleep_for(std::chrono::milliseconds(POLL_INTERVAL_MS));
-
- const std::string text = read_file(target);
- std::filesystem::remove(target, ec);
-
- if (text.empty()) {
- err = "phonebook transfer produced no data";
- return contacts;
- }
-
- contacts = parse_vcards(text);
- return contacts;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/profile_supervisor.cpp b/src/core/src/bluetooth/profile_supervisor.cpp
deleted file mode 100644
index 4e4b7df..0000000
--- a/src/core/src/bluetooth/profile_supervisor.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-#include "tether/bluetooth/profile_supervisor.hpp"
-#include "tether/log.hpp"
-
-#include <algorithm>
-#include <cctype>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string lowered(std::string text) {
- std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
- return static_cast<char>(std::tolower(c));
- });
- return text;
- }
-
- bool contains(const std::string& haystack, const char* needle) {
- return haystack.find(needle) != std::string::npos;
- }
-
- } // namespace
-
- const char* to_string(ObexError error) {
- switch (error) {
- case ObexError::None:
- return "none";
- case ObexError::Forbidden:
- return "forbidden";
- case ObexError::Busy:
- return "busy";
- case ObexError::NoRecord:
- return "no_record";
- case ObexError::Unavailable:
- return "unavailable";
- default:
- return "other";
- }
- }
-
- ObexError classify_obex_error(const std::string& message) {
- if (message.empty())
- return ObexError::None;
-
- const std::string text = lowered(message);
-
- // permission toggle is off on the phone
- if (contains(text, "forbidden") || contains(text, "0x43"))
- return ObexError::Forbidden;
-
- if (contains(text, "connection refused") || contains(text, "(111)"))
- return ObexError::Busy;
-
- if (contains(text, "unable to find service record") || contains(text, "no such service"))
- return ObexError::NoRecord;
-
- if (contains(text, "host is down") || contains(text, "no route to host") || contains(text, "not connected") ||
- contains(text, "page timeout"))
- return ObexError::Unavailable;
-
- return ObexError::Other;
- }
-
- std::string obex_error_advice(ObexError error, const std::string& profile) {
- const std::string label = profile == "map" ? "Messages" : "Contacts";
- switch (error) {
- case ObexError::Forbidden:
- return "Enable \"" +
- (profile == "map" ? std::string("Show Message Notifications") : std::string("Sync Contacts")) +
- "\" for this computer in the iPhone's Settings > Bluetooth > (i). "
- "This is a permission, not a pairing problem.";
- case ObexError::Busy:
- return label + " is unavailable because another computer is using the iPhone's " + profile +
- " session. Disconnect it there, then this will connect on its own.";
- case ObexError::NoRecord:
- // obexd reports a missing record whenever its SDP fetch is refused, so the real cause is usually one layer
- // down.
- return label +
- " could not be fetched from the iPhone. Usually another computer holds the phone's "
- "Bluetooth session, or \"" +
- (profile == "map" ? std::string("Show Message Notifications") : std::string("Sync Contacts")) +
- "\" is off in Settings > Bluetooth > (i). Check both; re-pairing is not the fix.";
- case ObexError::Unavailable:
- return label + " is unreachable; waiting for the iPhone to come back.";
- case ObexError::Other:
- return label + " could not be opened.";
- default:
- return {};
- }
- }
-
- ProfileSupervisor::ProfileSupervisor(ProfileOps& ops) : ops_(ops) {}
-
- void ProfileSupervisor::reset() {
- if (!map_path_.empty())
- ops_.remove_session(map_path_);
- if (!pbap_path_.empty())
- ops_.remove_session(pbap_path_);
- map_path_.clear();
- pbap_path_.clear();
- map_retried_ = false;
- pbap_retried_ = false;
- next_attempt_ = 0;
- status_.map_open = false;
- status_.pbap_open = false;
- }
-
- bool
- ProfileSupervisor::open_profile(const std::string& target, std::string& path, ObexError& error, bool& retried) {
- std::string err;
- path = ops_.create_session(target, err);
- if (!path.empty()) {
- error = ObexError::None;
- retried = false;
- return true;
- }
-
- error = classify_obex_error(err);
- debug::log(WARN, "bluetooth: {} session failed ({}): {}", target, to_string(error), err);
-
- // A stale session from a previous run can present as Forbidden. Drop only
- // this profile's session and try once more, rather than restarting obexd.
- if (error == ObexError::Forbidden && !retried) {
- retried = true;
- ops_.remove_session(path);
- path = ops_.create_session(target, err);
- if (!path.empty()) {
- error = ObexError::None;
- return true;
- }
- error = classify_obex_error(err);
- }
- return false;
- }
-
- bool ProfileSupervisor::tick(int64_t now, bool link_ready) {
- ProfileStatus previous = status_;
-
- if (!link_ready) {
- // Nothing to do until the Classic bearer is up; hold what we have and
- // let reset() handle an actual disconnect.
- status_.reason = "Waiting for the Bluetooth link.";
- return !(status_ == previous);
- }
-
- if (status_.map_open && status_.pbap_open) {
- status_.reason = "Messages and contacts are connected.";
- return !(status_ == previous);
- }
-
- if (now < next_attempt_)
- return !(status_ == previous);
-
- if (!status_.map_open)
- status_.map_open = open_profile("map", map_path_, status_.map_error, map_retried_);
- if (!status_.pbap_open)
- status_.pbap_open = open_profile("pbap", pbap_path_, status_.pbap_error, pbap_retried_);
-
- if (status_.map_open || status_.pbap_open)
- opened_once_ = true;
- next_attempt_ = now + (opened_once_ ? PROFILE_STEADY_POLL_SECONDS : PROFILE_INITIAL_POLL_SECONDS);
-
- if (status_.map_open && status_.pbap_open) {
- status_.reason = "Messages and contacts are connected.";
- } else if (!status_.map_open && status_.map_error != ObexError::None) {
- // MAP is the feature people notice, so its problem leads.
- status_.reason = obex_error_advice(status_.map_error, "map");
- } else if (!status_.pbap_open && status_.pbap_error != ObexError::None) {
- status_.reason = obex_error_advice(status_.pbap_error, "pbap");
- } else {
- status_.reason = "Opening messages and contacts...";
- }
-
- return !(status_ == previous);
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/bluetooth/vcard.cpp b/src/core/src/bluetooth/vcard.cpp
deleted file mode 100644
index 8a360e7..0000000
--- a/src/core/src/bluetooth/vcard.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-#include "tether/bluetooth/vcard.hpp"
-
-#include <algorithm>
-#include <cctype>
-
-namespace tether::bluetooth {
-
- namespace {
-
- std::string trim(const std::string& text) {
- size_t begin = text.find_first_not_of(" \t\r\n");
- if (begin == std::string::npos)
- return {};
- size_t end = text.find_last_not_of(" \t\r\n");
- return text.substr(begin, end - begin + 1);
- }
-
- std::string upper(std::string text) {
- std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
- return static_cast<char>(std::toupper(c));
- });
- return text;
- }
-
- } // namespace
-
- std::vector<std::string> vcard_unfold(const std::string& text) {
- std::vector<std::string> lines;
- size_t start = 0;
- while (start <= text.size()) {
- size_t nl = text.find('\n', start);
- std::string line = nl == std::string::npos ? text.substr(start) : text.substr(start, nl - start);
- if (!line.empty() && line.back() == '\r')
- line.pop_back();
-
- // A leading space or tab means this line continues the previous one.
- if (!line.empty() && (line[0] == ' ' || line[0] == '\t') && !lines.empty())
- lines.back() += line.substr(1);
- else
- lines.push_back(std::move(line));
-
- if (nl == std::string::npos)
- break;
- start = nl + 1;
- }
- return lines;
- }
-
- bool vcard_split_property(const std::string& line, std::string& name, std::string& value) {
- size_t colon = line.find(':');
- if (colon == std::string::npos)
- return false;
- std::string left = line.substr(0, colon);
- size_t semi = left.find(';');
- name = upper(trim(semi == std::string::npos ? left : left.substr(0, semi)));
- value = trim(line.substr(colon + 1));
- return !name.empty();
- }
-
- std::string vcard_name_from_n(const std::string& value) {
- std::vector<std::string> parts;
- size_t start = 0;
- while (true) {
- size_t semi = value.find(';', start);
- parts.push_back(value.substr(start, semi == std::string::npos ? std::string::npos : semi - start));
- if (semi == std::string::npos)
- break;
- start = semi + 1;
- }
- std::string given = parts.size() > 1 ? trim(parts[1]) : std::string{};
- std::string family = parts.empty() ? std::string{} : trim(parts[0]);
- if (!given.empty() && !family.empty())
- return given + " " + family;
- return given.empty() ? family : given;
- }
-
- std::string vcard_unescape(const std::string& value) {
- std::string out;
- out.reserve(value.size());
- for (size_t i = 0; i < value.size(); ++i) {
- if (value[i] != '\\' || i + 1 >= value.size()) {
- out += value[i];
- continue;
- }
- switch (value[i + 1]) {
- case 'n':
- case 'N':
- out += '\n';
- break;
- case ',':
- out += ',';
- break;
- case ';':
- out += ';';
- break;
- case '\\':
- out += '\\';
- break;
- default:
- // Not an escape we know; keep both characters verbatim.
- out += value[i];
- out += value[i + 1];
- break;
- }
- ++i;
- }
- return out;
- }
-
- std::vector<VCard> parse_vcards(const std::string& text) {
- std::vector<VCard> cards;
- if (text.empty())
- return cards;
-
- VCard current;
- std::string structured_name;
- bool in_card = false;
-
- auto flush = [&] {
- if (current.name.empty())
- current.name = structured_name;
- if (!current.empty())
- cards.push_back(current);
- current = VCard{};
- structured_name.clear();
- };
-
- for (const auto& raw : vcard_unfold(text)) {
- const std::string line = trim(raw);
- const std::string token = upper(line);
-
- if (token == "BEGIN:VCARD") {
- // An unterminated card still yields what it had, rather than
- // being silently merged into the next one.
- if (in_card)
- flush();
- in_card = true;
- continue;
- }
- if (token == "END:VCARD") {
- if (in_card)
- flush();
- in_card = false;
- continue;
- }
- if (!in_card)
- continue;
-
- std::string name, value;
- if (!vcard_split_property(line, name, value) || value.empty())
- continue;
-
- if (name == "TEL")
- current.tels.push_back(vcard_unescape(value));
- else if (name == "EMAIL")
- current.emails.push_back(vcard_unescape(value));
- else if (name == "FN")
- current.name = vcard_unescape(value);
- else if (name == "N")
- structured_name = vcard_name_from_n(vcard_unescape(value));
- }
-
- if (in_card)
- flush();
- return cards;
- }
-
-} // namespace tether::bluetooth
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index e929847..da193a8 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -10,19 +10,12 @@
#include <sys/wait.h>
#include <unistd.h>
-#include "tether/bluetooth/config.hpp"
-#include "tether/bluetooth/connection.hpp"
-#include "tether/bluetooth/contacts.hpp"
-#include "tether/bluetooth/diagnostics.hpp"
-#include "tether/bluetooth/monitor.hpp"
-#include "tether/bluetooth/pairing.hpp"
#include "tether/client.hpp"
#include "tether/crypto.hpp"
#include "tether/discovery.hpp"
#include "tether/file_transfer.hpp"
#include "tether/otp.hpp"
#include "tether/wayland.hpp"
-#include <atomic>
#include <cstring>
#include <filesystem>
#include <fstream>
@@ -165,14 +158,6 @@ namespace tether {
if (packet.empty() || packet.back() != '\n')
packet += '\n';
- // Bluetooth state events feed the diagnostic timeline.
- if (packet.find("\"bt_") != std::string::npos) {
- try {
- bluetooth::record_diagnostic_event(nlohmann::json::parse(packet));
- } catch (...) {
- }
- }
-
std::lock_guard<std::mutex> lock(g_subscribers_mutex);
for (int fd : local_subscribers) {
if (fd == exclude_fd)
@@ -211,152 +196,6 @@ namespace tether {
return "";
}
- nlohmann::json build_bt_status() {
- nlohmann::json status;
- status["command"] = "bt_status";
- status["available"] = bluetooth::g_bluez != nullptr && bluetooth::g_bluez->running();
- if (!bluetooth::g_bluez) {
- status["capability"] = nullptr;
- status["adapters"] = nlohmann::json::array();
- return status;
- }
-
- status["capability"] = bluetooth::to_json(bluetooth::g_bluez->capability());
- nlohmann::json adapters = nlohmann::json::array();
- for (const auto& adapter : bluetooth::g_bluez->snapshot().adapters)
- adapters.push_back(bluetooth::to_json(adapter));
- status["adapters"] = adapters;
- return status;
- }
-
- // Guards against two pairing transactions racing for the same agent and
- // advertisement object paths.
- static std::atomic<bool> g_bt_pair_busy{false};
-
- static void run_bt_pair(const std::string& address) {
- if (!bluetooth::g_bluez) {
- nlohmann::json event;
- event["command"] = "bt_pair_result";
- event["success"] = false;
- event["status"] = "error";
- event["message"] = "Bluetooth is unavailable.";
- broadcast_local_event(event.dump());
- return;
- }
-
- if (g_bt_pair_busy.exchange(true)) {
- nlohmann::json event;
- event["command"] = "bt_pair_result";
- event["success"] = false;
- event["status"] = "busy";
- event["message"] = "Another pairing attempt is already in progress.";
- broadcast_local_event(event.dump());
- return;
- }
-
- auto config = bluetooth::load_config();
- auto result = bluetooth::pair_device(
- *bluetooth::g_bluez,
- address,
- config.auth_strategy,
- [](const std::string& step, const std::string& detail) {
- nlohmann::json event;
- event["command"] = "bt_pair_progress";
- event["step"] = step;
- event["detail"] = detail;
- broadcast_local_event(event.dump());
- },
- nullptr);
-
- if (result.success) {
- config.device_address = result.device_address;
- // A BR/EDR-only bond can never have ANCS. Remember so later runs do not keep trying to bring up an LE
- // bearer the phone will not answer.
- config.ancs_enabled = result.dual_bond;
- bluetooth::save_config(config);
- // Point supervision at the device we just bonded with.
- if (bluetooth::g_bt_connections)
- bluetooth::g_bt_connections->set_device(config.device_address, config.ancs_enabled);
- }
-
- g_bt_pair_busy = false;
- broadcast_local_event(bluetooth::to_json(result).dump());
- broadcast_local_event(build_bt_status().dump());
- }
-
- static void run_bt_unpair(const std::string& address) {
- if (!bluetooth::g_bluez)
- return;
- auto result = bluetooth::unpair_device(*bluetooth::g_bluez, address);
- nlohmann::json event = bluetooth::to_json(result);
- event["command"] = "bt_unpair_result";
- broadcast_local_event(event.dump());
- broadcast_local_event(build_bt_status().dump());
- }
-
- nlohmann::json build_bt_threads() {
- nlohmann::json result;
- result["command"] = "bt_threads";
- nlohmann::json threads = nlohmann::json::array();
- {
- std::lock_guard<std::mutex> lock(bluetooth::message_store_mutex());
- for (const auto& thread : bluetooth::message_store().threads()) {
- auto entry = bluetooth::to_json(thread);
- // Contact names are applied for display only. Key on addresses, so a renamed or ambiguous contact can
- // never change which conversation a message belongs to.
- if (auto name = bluetooth::contact_store().name_for(thread.key); !name.empty())
- entry["name"] = name;
-
- if (thread.key.rfind("group:", 0) == 0) {
- entry["group"] = true;
- std::string reason;
- const auto eligibility = bluetooth::group_reply_status(thread.key, reason);
- entry["repliable"] = eligibility == bluetooth::ReplyEligibility::Allowed;
- entry["reply_status"] = bluetooth::to_string(eligibility);
- if (!reason.empty())
- entry["reply_reason"] = reason;
- } else {
- entry["group"] = false;
- entry["repliable"] = true;
- }
- threads.push_back(std::move(entry));
- }
- }
- result["threads"] = threads;
- return result;
- }
-
- nlohmann::json build_bt_messages(const std::string& thread_key) {
- nlohmann::json result;
- result["command"] = "bt_messages";
- result["thread"] = thread_key;
- nlohmann::json messages = nlohmann::json::array();
- {
- std::lock_guard<std::mutex> lock(bluetooth::message_store_mutex());
- const std::string name = bluetooth::contact_store().name_for(thread_key);
- for (const auto& message : bluetooth::message_store().messages(thread_key)) {
- auto entry = bluetooth::to_json(message);
- if (!name.empty() && !message.outgoing)
- entry["name"] = name;
- messages.push_back(std::move(entry));
- }
- }
- result["messages"] = messages;
- return result;
- }
-
- nlohmann::json build_bt_devices() {
- nlohmann::json result;
- result["command"] = "bt_devices";
- nlohmann::json devices = nlohmann::json::array();
- if (bluetooth::g_bluez) {
- for (const auto& device : bluetooth::g_bluez->snapshot().devices)
- devices.push_back(bluetooth::to_json(device));
- }
- result["devices"] = devices;
- return result;
- }
-
static nlohmann::json build_local_state_snapshot() {
nlohmann::json snapshot;
snapshot["command"] = "state_snapshot";
@@ -616,131 +455,6 @@ namespace tether {
debug::log(ERR, "net write error\n");
}
continue;
- } else if (j.contains("command") && j["command"] == "bt_status") {
- std::string payload = build_bt_status().dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
- } else if (j.contains("command") && j["command"] == "bt_list_devices") {
- std::string payload = build_bt_devices().dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
- } else if (j.contains("command") && j["command"] == "bt_pair" && j.contains("address")) {
- // Pairing waits on the user and the phone, so it runs on
- // its own thread; progress and the result arrive as events.
- std::string address = j["address"];
- std::thread([address]() { run_bt_pair(address); }).detach();
- } else if (j.contains("command") && j["command"] == "bt_unpair" && j.contains("address")) {
- std::string address = j["address"];
- std::thread([address]() { run_bt_unpair(address); }).detach();
- } else if (j.contains("command") && j["command"] == "bt_set_device" && j.contains("address")) {
- auto config = bluetooth::load_config();
- config.device_address = j["address"];
- bluetooth::save_config(config);
- if (bluetooth::g_bt_connections)
- bluetooth::g_bt_connections->set_device(config.device_address, config.ancs_enabled);
- broadcast_local_event(build_bt_status().dump());
- } else if (j.contains("command") && j["command"] == "bt_list_threads") {
- std::string payload = build_bt_threads().dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
- } else if (j.contains("command") && j["command"] == "bt_list_messages" && j.contains("thread")) {
- std::string payload = build_bt_messages(j["thread"]).dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
- } else if (j.contains("command") && j["command"] == "bt_mark_read" && j.contains("handle")) {
- std::string handle = j["handle"];
- bool read = j.value("read", true);
- // Writing through to the phone is a blocking OBEX call.
- std::thread([handle, read]() {
- std::string err;
- nlohmann::json event;
- event["command"] = "bt_message_read";
- event["handle"] = handle;
- event["read"] = read;
- event["success"] = bluetooth::mark_message_read(handle, read, err);
- if (!err.empty())
- event["message"] = err;
- broadcast_local_event(event.dump());
- }).detach();
- } else if (j.contains("command") && j["command"] == "bt_send_message" && j.contains("thread") &&
- j.contains("body")) {
- std::string thread = j["thread"];
- std::string body = j["body"];
- // PushMessage is a blocking OBEX transfer, so it cannot
- // run on the loop that has to keep serving the UI.
- std::thread([thread, body]() {
- std::string err;
- bluetooth::Message sent;
- nlohmann::json event;
- event["command"] = "bt_send_result";
- event["thread"] = thread;
- event["success"] = bluetooth::send_message(thread, body, sent, err);
- if (event["success"]) {
- // The phone reports nothing about a sent message,
- // so the local record is announced the same way an
- // incoming one would be.
- nlohmann::json message = bluetooth::to_json(sent);
- message["command"] = "bt_message";
- broadcast_local_event(message.dump());
- } else {
- event["message"] = err;
- }
- broadcast_local_event(event.dump());
- }).detach();
- } else if (j.contains("command") && j["command"] == "bt_list_notifications") {
- nlohmann::json payload;
- payload["command"] = "bt_notifications";
- payload["notifications"] = bluetooth::g_bt_connections
- ? bluetooth::g_bt_connections->notifications()
- : nlohmann::json::array();
- std::string out = payload.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace) + "\n";
- if (write(client_fd, out.c_str(), out.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
- } else if (j.contains("command") && j["command"] == "bt_notification_action" && j.contains("uid")) {
- // ANCS offers positive and negative only; there is no
- // free-text reply to expose here.
- const bool positive = j.value("action", "positive") == "positive";
- nlohmann::json payload;
- payload["command"] = "bt_notification_action_result";
- payload["uid"] = j["uid"];
- payload["success"] =
- bluetooth::g_bt_connections &&
- bluetooth::g_bt_connections->perform_notification_action(
- j["uid"].get<uint32_t>(),
- positive ? bluetooth::ancs::ActionId::Positive : bluetooth::ancs::ActionId::Negative);
- broadcast_local_event(payload.dump());
- } else if (j.contains("command") && j["command"] == "bt_connection") {
- nlohmann::json payload = bluetooth::g_bt_connections
- ? bluetooth::g_bt_connections->status()
- : nlohmann::json{{"command", "bt_connection_changed"},
- {"device_present", false},
- {"link_reason", "Bluetooth is unavailable."},
- {"profile_reason", ""}};
- std::string out = payload.dump() + "\n";
- if (write(client_fd, out.c_str(), out.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
- } else if (j.contains("command") && j["command"] == "bt_diagnostics") {
- nlohmann::json connection =
- bluetooth::g_bt_connections
- ? bluetooth::g_bt_connections->status()
- : nlohmann::json{{"command", "bt_connection_changed"}, {"device_present", false}};
- std::string out = bluetooth::build_diagnostics(build_bt_status(), connection).dump() + "\n";
- if (write(client_fd, out.c_str(), out.size()) < 0) {
- debug::log(ERR, "net write error\n");
- }
- continue;
} else if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {
std::string content = j["content"];
if (g_wayland)
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 59741ea..b5acf91 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -1,11 +1,6 @@
#include "notification.hpp"
#include <csignal>
-#include <ctime>
#include <nlohmann/json.hpp>
-#include <tether/bluetooth/config.hpp>
-#include <tether/bluetooth/connection.hpp>
-#include <tether/bluetooth/contacts.hpp>
-#include <tether/bluetooth/monitor.hpp>
#include <tether/core.hpp>
#include <tether/crypto.hpp>
#include <tether/discovery.hpp>
@@ -106,7 +101,7 @@ int main(int argc, char** argv) {
}
tether::FileReceiveManager file_mgr;
- tether::DesktopNotifier notifier;
+ tether::FileArrivalNotifier notifier;
if (!notifier.init()) {
debug::log(ERR, "Warning: desktop notifications unavailable");
} else {
@@ -117,86 +112,6 @@ int main(int argc, char** argv) {
}
tether::g_file_manager = &file_mgr;
- // BlueZ runs on its own GLib thread and wakes the loop through an eventfd
- // whenever the adapter or device set changes.
- tether::bluetooth::BluezMonitor bluez;
- tether::bluetooth::ConnectionManager connections(
- bluez,
- [](const nlohmann::json& status) { tether::broadcast_local_event(status.dump()); },
- [&notifier](const tether::bluetooth::Message& message, bool backfill) {
- nlohmann::json event = tether::bluetooth::to_json(message);
- event["command"] = "bt_message";
- tether::broadcast_local_event(event.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace));
-
- // ANCS deliberately shows no popup for Messages, because MAP is the
- // copy whose read state stays in sync with the phone. This is that popup.
- if (backfill || message.outgoing || message.read)
- return;
-
- std::string who = tether::bluetooth::contact_store().name_for(message.thread_key);
- if (who.empty())
- who = message.peer_name.empty() ? message.peer_address : message.peer_name;
- notifier.notify(who.empty() ? "iPhone" : who, message.body);
- });
- if (bluez.start()) {
- tether::bluetooth::g_bluez = &bluez;
- loop.addFd(bluez.event_fd(), [&bluez](int) {
- bluez.drain();
- tether::broadcast_local_event(tether::build_bt_status().dump());
- });
- auto cap = bluez.capability();
- debug::log(INFO, "Bluetooth: {} mode", tether::bluetooth::to_string(cap.mode));
- for (const auto& reason : cap.reasons)
- debug::log(INFO, "Bluetooth: {}", reason);
-
- // Supervise the selected iPhone's bearers and OBEX sessions. ANCS is only
- // attempted when the controller can carry it and pairing produced a bond
- // that covers LE.
- auto bt_config = tether::bluetooth::load_config();
- const bool ancs = bt_config.ancs_enabled && cap.mode == tether::bluetooth::DeliveryMode::Full;
- tether::bluetooth::g_bt_connections = &connections;
-
- tether::bluetooth::set_group_replies_enabled(bt_config.group_messages_enabled &&
- bt_config.ancs_content_enabled);
- tether::bluetooth::reload_group_rosters();
-
- if (ancs) {
- connections.set_notification_handlers(
- [&notifier](const tether::bluetooth::ancs::Notification& notification) {
- // Messages notifications are the only side channel that says
- // which conversation a MAP message belongs to.
- if (notification.app_id == tether::bluetooth::ancs::APP_ID_MESSAGES) {
- tether::bluetooth::observe_message_notification(notification.title,
- notification.subtitle,
- notification.body,
- static_cast<int64_t>(std::time(nullptr)));
- }
-
- nlohmann::json event = tether::bluetooth::ancs::to_json(notification);
- event["command"] = "bt_notification";
- tether::broadcast_local_event(event.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace));
-
- // Messages already arrive over MAP with read state that stays
- // in sync, so a popup here would be the second copy.
- if (!tether::bluetooth::ancs::should_show_desktop_popup(notification))
- return;
-
- const std::string title = notification.title.empty() ? notification.app_name : notification.title;
- notifier.notify(title.empty() ? "iPhone" : title, notification.body);
- },
- [](uint32_t uid) {
- nlohmann::json event;
- event["command"] = "bt_notification_removed";
- event["uid"] = uid;
- tether::broadcast_local_event(event.dump());
- });
- }
-
- connections.start(bt_config.device_address, ancs);
- } else {
- debug::log(INFO, "Bluetooth unavailable; messages and notifications are disabled");
- }
-
debug::log(INFO, "tetherd is running. Press Ctrl-C to stop.");
loop.run();
@@ -204,10 +119,6 @@ int main(int argc, char** argv) {
debug::log(INFO, "tetherd shutdown complete.");
// explicitly null globals to be safe during final stack unwinding
- tether::bluetooth::g_bt_connections = nullptr;
- connections.stop();
- tether::bluetooth::g_bluez = nullptr;
- bluez.stop();
tether::g_wayland = nullptr;
tether::g_file_manager = nullptr;
g_loop = nullptr;
diff --git a/src/daemon/notification.cpp b/src/daemon/notification.cpp
index 45bf950..d07b7e8 100644
--- a/src/daemon/notification.cpp
+++ b/src/daemon/notification.cpp
@@ -103,16 +103,16 @@ namespace tether {
} // namespace
- struct DesktopNotifier::Impl {
+ struct FileArrivalNotifier::Impl {
GMainContext* context = nullptr;
GMainLoop* loop = nullptr;
std::thread thread;
bool initialized = false;
};
- DesktopNotifier::DesktopNotifier() : impl_(std::make_unique<Impl>()) {}
+ FileArrivalNotifier::FileArrivalNotifier() : impl_(std::make_unique<Impl>()) {}
- DesktopNotifier::~DesktopNotifier() {
+ FileArrivalNotifier::~FileArrivalNotifier() {
if (!impl_->initialized) {
return;
}
@@ -135,7 +135,7 @@ namespace tether {
notify_uninit();
}
- bool DesktopNotifier::init() {
+ bool FileArrivalNotifier::init() {
if (impl_->initialized) {
return true;
}
@@ -156,26 +156,7 @@ namespace tether {
return true;
}
- void DesktopNotifier::notify(const std::string& summary, const std::string& body) {
- if (!impl_ || !impl_->initialized) {
- return;
- }
-
- NotifyNotification* notification =
- notify_notification_new(summary.c_str(), body.empty() ? nullptr : body.c_str(), "phone-symbolic");
- if (!notification) {
- return;
- }
-
- GError* error = nullptr;
- if (!notify_notification_show(notification, &error)) {
- debug::log(ERR, "Failed to show notification: {}", error ? error->message : "unknown");
- g_clear_error(&error);
- }
- g_object_unref(notification);
- }
-
- void DesktopNotifier::notify_file_arrived(const std::filesystem::path& path) {
+ void FileArrivalNotifier::notify_file_arrived(const std::filesystem::path& path) {
if (!impl_->initialized) {
return;
}
diff --git a/src/daemon/notification.hpp b/src/daemon/notification.hpp
index bae89d3..8493e15 100644
--- a/src/daemon/notification.hpp
+++ b/src/daemon/notification.hpp
@@ -2,24 +2,20 @@
#include <filesystem>
#include <memory>
-#include <string>
namespace tether {
- class DesktopNotifier {
+ class FileArrivalNotifier {
public:
- DesktopNotifier();
- ~DesktopNotifier();
+ FileArrivalNotifier();
+ ~FileArrivalNotifier();
- DesktopNotifier(const DesktopNotifier&) = delete;
- DesktopNotifier& operator=(const DesktopNotifier&) = delete;
+ FileArrivalNotifier(const FileArrivalNotifier&) = delete;
+ FileArrivalNotifier& operator=(const FileArrivalNotifier&) = delete;
bool init();
void notify_file_arrived(const std::filesystem::path& path);
- // A plain notification with no actions.
- void notify(const std::string& summary, const std::string& body);
-
private:
struct Impl;
std::unique_ptr<Impl> impl_;
diff --git a/src/gtk/CMakeLists.txt b/src/gtk/CMakeLists.txt
index 23a5ba2..c5905c7 100644
--- a/src/gtk/CMakeLists.txt
+++ b/src/gtk/CMakeLists.txt
@@ -3,11 +3,6 @@ pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
add_executable(tether-gtk
main.cpp
- ui_util.cpp
- daemon_client.cpp
- devices_view.cpp
- messages_view.cpp
- notifications_view.cpp
)
target_include_directories(tether-gtk PRIVATE ${GTK3_INCLUDE_DIRS})
diff --git a/src/gtk/daemon_client.cpp b/src/gtk/daemon_client.cpp
deleted file mode 100644
index a51e5a8..0000000
--- a/src/gtk/daemon_client.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-#include "daemon_client.hpp"
-#include "ui_util.hpp"
-
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <filesystem>
-#include <gtk/gtk.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <sys/wait.h>
-#include <tether/core.hpp>
-#include <tether/log.hpp>
-#include <tether/net.hpp>
-#include <unistd.h>
-
-namespace tether::ui {
-
- namespace {
-
- int g_event_fd = -1;
- GIOChannel* g_event_channel = nullptr;
- guint g_event_watch_id = 0;
- guint g_event_retry_id = 0;
- DaemonEventFn g_on_event;
-
- gboolean start_event_subscription(gpointer);
-
- void stop_event_subscription() {
- if (g_event_watch_id != 0) {
- g_source_remove(g_event_watch_id);
- g_event_watch_id = 0;
- }
- if (g_event_channel) {
- g_io_channel_shutdown(g_event_channel, TRUE, nullptr);
- g_io_channel_unref(g_event_channel);
- g_event_channel = nullptr;
- } else if (g_event_fd >= 0) {
- close(g_event_fd);
- }
- g_event_fd = -1;
- }
-
- void schedule_event_retry() {
- if (g_event_retry_id == 0)
- g_event_retry_id = g_timeout_add_seconds(2, start_event_subscription, nullptr);
- }
-
- gboolean on_event_channel(GIOChannel* source, GIOCondition condition, gpointer) {
- if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
- stop_event_subscription();
- schedule_event_retry();
- set_status_main("Daemon Offline");
- return FALSE;
- }
- if (condition & G_IO_IN) {
- gchar* line = nullptr;
- gsize length = 0;
- GError* error = nullptr;
- while (true) {
- GIOStatus status = g_io_channel_read_line(source, &line, &length, nullptr, &error);
- if (status == G_IO_STATUS_AGAIN) {
- if (line)
- g_free(line);
- break;
- }
- if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR) {
- if (error) {
- debug::log(ERR, "Stream err: {}", error->message);
- g_error_free(error);
- }
- if (line)
- g_free(line);
- stop_event_subscription();
- schedule_event_retry();
- set_status_main("Daemon Offline");
- return FALSE;
- }
- if (line && length > 0) {
- try {
- if (g_on_event)
- g_on_event(nlohmann::json::parse(std::string(line, length)));
- } catch (...) {
- }
- }
- if (line)
- g_free(line);
- }
- }
- return TRUE;
- }
-
- gboolean start_event_subscription(gpointer) {
- if (g_event_retry_id != 0) {
- g_source_remove(g_event_retry_id);
- g_event_retry_id = 0;
- }
- stop_event_subscription();
- int fd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (fd < 0) {
- schedule_event_retry();
- return G_SOURCE_REMOVE;
- }
-
- sockaddr_un addr{};
- addr.sun_family = AF_UNIX;
- std::string path = tether::get_runtime_dir() + "/tetherd.sock";
- std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
-
- if (::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
- close(fd);
- static bool autostart_attempted = false;
- if (!autostart_attempted) {
- autostart_attempted = true;
- pid_t pid = fork();
- if (pid == 0) {
- std::filesystem::path self_path = std::filesystem::read_symlink("/proc/self/exe");
- std::string daemon_path = (self_path.parent_path() / "tetherd").string();
- if (fork() == 0) {
- if (freopen("/dev/null", "w", stdout) == nullptr) {
- }
- if (freopen("/dev/null", "w", stderr) == nullptr) {
- }
- if (freopen("/dev/null", "r", stdin) == nullptr) {
- }
- execl(daemon_path.c_str(), "tetherd", nullptr);
- execlp("tetherd", "tetherd", nullptr);
- exit(1);
- }
- exit(0);
- } else if (pid > 0) {
- int status;
- waitpid(pid, &status, 0);
- }
- }
- schedule_event_retry();
- set_status_main("Daemon Offline");
- return G_SOURCE_REMOVE;
- }
-
- g_event_fd = fd;
- g_event_channel = g_io_channel_unix_new(fd);
- g_io_channel_set_encoding(g_event_channel, nullptr, nullptr);
- g_io_channel_set_buffered(g_event_channel, TRUE);
- g_io_channel_set_flags(g_event_channel, G_IO_FLAG_NONBLOCK, nullptr);
- g_event_watch_id = g_io_add_watch(g_event_channel,
- static_cast<GIOCondition>(G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL),
- on_event_channel,
- nullptr);
- static const char kSubscribe[] = "{\"command\":\"subscribe\"}\n";
- if (write(fd, kSubscribe, sizeof(kSubscribe) - 1) < 0) {
- debug::log(ERR, "subscribe write error\n");
- }
- set_status_main("Daemon Online");
- return G_SOURCE_REMOVE;
- }
-
- } // namespace
-
- void daemon_client_start(DaemonEventFn on_event) {
- g_on_event = std::move(on_event);
- start_event_subscription(nullptr);
- }
-
- void daemon_client_stop() {
- stop_event_subscription();
- if (g_event_retry_id != 0) {
- g_source_remove(g_event_retry_id);
- g_event_retry_id = 0;
- }
- }
-
- void daemon_send(const nlohmann::json& message) {
- if (g_event_fd >= 0) {
- std::string payload = message.dump() + "\n";
- if (::write(g_event_fd, payload.c_str(), payload.size()) < 0) {
- debug::log(ERR, "daemon write error\n");
- }
- }
- }
-
- bool daemon_connected() { return g_event_fd >= 0; }
-
-} // namespace tether::ui
diff --git a/src/gtk/daemon_client.hpp b/src/gtk/daemon_client.hpp
deleted file mode 100644
index f066386..0000000
--- a/src/gtk/daemon_client.hpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#pragma once
-
-#include <functional>
-#include <nlohmann/json.hpp>
-
-namespace tether::ui {
-
- using DaemonEventFn = std::function<void(const nlohmann::json&)>;
-
- // Connects to unix socket, subscribes to the local event feed, and dispatches each nd event. Starts the daemon once
- // if it is not running, and reconnects on its own after it goes away.
- void daemon_client_start(DaemonEventFn on_event);
- void daemon_client_stop();
-
- void daemon_send(const nlohmann::json& message);
- bool daemon_connected();
-
-} // namespace tether::ui
diff --git a/src/gtk/devices_view.cpp b/src/gtk/devices_view.cpp
deleted file mode 100644
index 6409b38..0000000
--- a/src/gtk/devices_view.cpp
+++ /dev/null
@@ -1,539 +0,0 @@
-#include "devices_view.hpp"
-#include "daemon_client.hpp"
-#include "ui_util.hpp"
-
-#include <algorithm>
-#include <filesystem>
-#include <string>
-#include <tether/crypto.hpp>
-#include <tether/discovery.hpp>
-#include <vector>
-
-namespace tether::ui {
-
- namespace {
-
- struct DevicesState {
- std::vector<tether::DiscoveredDevice> discovered_devices;
- std::vector<tether::DiscoveredDevice> pending_pairing_requests;
- std::vector<std::pair<std::string, std::string>> paired_devices; // fp, name
- std::vector<std::string> connected_fps; // active connections
-
- GtkWidget* list_devices = nullptr;
- GtkWidget* right_pane_stack = nullptr;
-
- std::string selected_device_fp;
- std::string selected_device_name;
- std::string selected_device_ip;
- uint16_t selected_device_port = 5134;
-
- GtkWidget* lbl_action_name = nullptr;
- GtkWidget* lbl_action_status = nullptr;
- GtkWidget* btn_grid = nullptr;
-
- GtkWidget* lbl_unpaired_name = nullptr;
- GtkWidget* lbl_unpaired_ip = nullptr;
- };
-
- DevicesState g_devices;
-
- void set_status_action(const std::string& text) { set_text(g_devices.lbl_action_status, text); }
-
- void update_right_pane() {
- if (g_devices.selected_device_fp.empty()) {
- gtk_stack_set_visible_child_name(GTK_STACK(g_devices.right_pane_stack), "placeholder");
- return;
- }
-
- bool is_paired = false;
- for (const auto& p : g_devices.paired_devices) {
- if (p.first == g_devices.selected_device_fp)
- is_paired = true;
- }
-
- if (is_paired) {
- gtk_stack_set_visible_child_name(GTK_STACK(g_devices.right_pane_stack), "action");
- set_markup(g_devices.lbl_action_name, ("<b>" + escape_markup(g_devices.selected_device_name) + "</b>"));
- bool online = std::find(g_devices.connected_fps.begin(),
- g_devices.connected_fps.end(),
- g_devices.selected_device_fp) != g_devices.connected_fps.end();
- set_status_action(online ? "Connected and ready."
- : "Device is offline. Pair again or wait for network.");
- if (g_devices.btn_grid) {
- gtk_widget_set_visible(g_devices.btn_grid, online);
- }
- } else {
- gtk_stack_set_visible_child_name(GTK_STACK(g_devices.right_pane_stack), "pair");
- set_markup(g_devices.lbl_unpaired_name,
- ("<b>" + escape_markup(g_devices.selected_device_name) + "</b>"));
- set_text(g_devices.lbl_unpaired_ip,
- ("Found at " + g_devices.selected_device_ip + ":" +
- std::to_string(g_devices.selected_device_port)));
- }
- }
-
- void on_device_selected(GtkListBox*, GtkListBoxRow* row, gpointer) {
- if (!row)
- return;
- const char* fp = (const char*)g_object_get_data(G_OBJECT(row), "fp");
- const char* name = (const char*)g_object_get_data(G_OBJECT(row), "name");
- const char* ip = (const char*)g_object_get_data(G_OBJECT(row), "ip");
- g_devices.selected_device_fp = fp ? fp : "";
- g_devices.selected_device_name = name ? name : "";
- g_devices.selected_device_ip = ip ? ip : "";
- g_devices.selected_device_port = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(row), "port"));
- update_right_pane();
- }
-
- void on_pair_click(GtkWidget*, gpointer) {
- if (g_devices.selected_device_ip.empty())
- return;
- set_text(g_devices.lbl_unpaired_ip, "Sending pair request...");
- nlohmann::json j;
- j["command"] = "pair_request";
- j["host"] = g_devices.selected_device_ip;
- j["port"] = g_devices.selected_device_port;
- daemon_send(j);
- set_status_main("Pair request sent. Approve on remote device!");
- }
-
- void on_accept_click(GtkWidget*, gpointer) {
- if (g_devices.selected_device_fp.empty())
- return;
- nlohmann::json j;
- j["command"] = "accept_device";
- j["fingerprint"] = g_devices.selected_device_fp;
- daemon_send(j);
- }
-
- void send_file_async(const std::filesystem::path& path) {
- if (!daemon_connected()) {
- set_status_action("Daemon unavailable.");
- return;
- }
- set_status_action("Sending " + path.filename().string() + "…");
- nlohmann::json j;
- j["command"] = "send_file";
- j["path"] = path.string();
- daemon_send(j);
- }
-
- void on_choose_file(GtkWidget*, gpointer) {
- GtkWidget* dialog = gtk_file_chooser_dialog_new("Send File",
- GTK_WINDOW(main_window()),
- GTK_FILE_CHOOSER_ACTION_OPEN,
- "_Cancel",
- GTK_RESPONSE_CANCEL,
- "_Send",
- GTK_RESPONSE_ACCEPT,
- nullptr);
- if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
- char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
- if (filename) {
- send_file_async(filename);
- g_free(filename);
- }
- }
- gtk_widget_destroy(dialog);
- }
-
- void apply_state_snapshot(const nlohmann::json& j) {
- g_devices.connected_fps.clear();
- if (j.contains("connected_clients") && j["connected_clients"].is_array()) {
- for (auto& c : j["connected_clients"]) {
- if (c.value("paired", false)) {
- g_devices.connected_fps.push_back(c.value("fingerprint", ""));
- } else {
- tether::DiscoveredDevice dev;
- dev.fingerprint = c.value("fingerprint", "");
- dev.name = c.value("device_name", "Unknown Device");
- dev.addresses.push_back({c.value("address", ""), 5134});
- g_devices.discovered_devices.push_back(dev);
- }
- }
- }
- g_devices.pending_pairing_requests.clear();
- if (j.contains("pending_pairs") && j["pending_pairs"].is_array()) {
- for (auto& p : j["pending_pairs"]) {
- tether::DiscoveredDevice req;
- req.fingerprint = p.value("fingerprint", "");
- req.name = p.value("device_name", "Unknown Device");
- g_devices.pending_pairing_requests.push_back(req);
- }
- }
- devices_view_refresh();
- }
-
- } // namespace
-
- void devices_view_trigger_discovery() {
- set_status_main("Scanning for nearby devices...");
- nlohmann::json j;
- j["command"] = "discover";
- daemon_send(j);
- }
-
- // Refresh the device list based on Discovered (unpaired), Paired (offline), Paired (online)
- void devices_view_refresh() {
- clear_list_box(g_devices.list_devices);
-
- tether::Crypto::instance().init();
- try {
- nlohmann::json known = nlohmann::json::parse(tether::Crypto::instance().get_known_hosts_dump());
- g_devices.paired_devices.clear();
- if (!known.empty()) {
- for (auto& [fingerprint, name_value] : known.items()) {
- g_devices.paired_devices.push_back(
- {fingerprint, name_value.is_string() ? name_value.get<std::string>() : "Unknown Device"});
- }
- }
- } catch (...) {
- }
-
- // We build a unified list of devices.
- // 1. All Paired Devices
- // 2. Any Discovered Devices not in the Paired list
-
- auto create_row = [](const std::string& name,
- const std::string& fp,
- const std::string& ip,
- uint16_t port,
- bool paired,
- bool online) {
- GtkWidget* row = gtk_list_box_row_new();
- g_object_set_data_full(G_OBJECT(row), "fp", g_strdup(fp.c_str()), g_free);
- g_object_set_data_full(G_OBJECT(row), "name", g_strdup(name.c_str()), g_free);
- g_object_set_data_full(G_OBJECT(row), "ip", g_strdup(ip.c_str()), g_free);
- g_object_set_data(G_OBJECT(row), "port", GINT_TO_POINTER(port));
- g_object_set_data(G_OBJECT(row), "paired", GINT_TO_POINTER(paired ? 1 : 0));
-
- GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 12);
- gtk_container_set_border_width(GTK_CONTAINER(box), 12);
-
- const char* icon_name =
- paired ? (online ? "network-cellular-connected-symbolic" : "network-cellular-offline-symbolic")
- : "dialog-information-symbolic";
- GtkWidget* icon = gtk_image_new_from_icon_name(icon_name, GTK_ICON_SIZE_LARGE_TOOLBAR);
- gtk_box_pack_start(GTK_BOX(box), icon, FALSE, FALSE, 0);
-
- GtkWidget* labels = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
- GtkWidget* title = gtk_label_new(nullptr);
- gtk_label_set_markup(GTK_LABEL(title), ("<b>" + escape_markup(name) + "</b>").c_str());
- gtk_label_set_xalign(GTK_LABEL(title), 0.0);
- gtk_box_pack_start(GTK_BOX(labels), title, FALSE, FALSE, 0);
-
- GtkWidget* subtitle = gtk_label_new(paired ? (online ? "Connected" : "Offline") : "Nearby (Tap to Pair)");
- gtk_label_set_xalign(GTK_LABEL(subtitle), 0.0);
- gtk_style_context_add_class(gtk_widget_get_style_context(subtitle), "muted");
- gtk_box_pack_start(GTK_BOX(labels), subtitle, FALSE, FALSE, 0);
-
- gtk_box_pack_start(GTK_BOX(box), labels, TRUE, TRUE, 0);
- gtk_container_add(GTK_CONTAINER(row), box);
- return row;
- };
-
- auto create_header_row = [](const std::string& title_text) {
- GtkWidget* row = gtk_list_box_row_new();
- gtk_list_box_row_set_selectable(GTK_LIST_BOX_ROW(row), FALSE);
- GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
- gtk_container_set_border_width(GTK_CONTAINER(box), 8);
- GtkWidget* lbl = gtk_label_new(nullptr);
- gtk_label_set_markup(
- GTK_LABEL(lbl),
- ("<b><span size='small' color='gray'>" + escape_markup(title_text) + "</span></b>").c_str());
- gtk_label_set_xalign(GTK_LABEL(lbl), 0.0);
- gtk_box_pack_start(GTK_BOX(box), lbl, TRUE, TRUE, 0);
- gtk_container_add(GTK_CONTAINER(row), box);
- return row;
- };
-
- std::string my_fp = tether::Crypto::instance().get_my_fingerprint();
-
- std::vector<GtkWidget*> connected_rows;
- std::vector<GtkWidget*> remembered_rows;
- std::vector<GtkWidget*> discovered_rows;
-
- for (const auto& paired : g_devices.paired_devices) {
- bool online = std::find(g_devices.connected_fps.begin(), g_devices.connected_fps.end(), paired.first) !=
- g_devices.connected_fps.end();
- GtkWidget* r = create_row(paired.second, paired.first, "", 5134, true, online);
- if (online) {
- connected_rows.push_back(r);
- } else {
- remembered_rows.push_back(r);
- }
- }
-
- for (const auto& disc : g_devices.discovered_devices) {
- if (disc.fingerprint == my_fp)
- continue;
- bool is_paired = false;
- for (const auto& p : g_devices.paired_devices) {
- if (p.first == disc.fingerprint) {
- is_paired = true;
- break;
- }
- }
- if (is_paired)
- continue; // already added above
- std::string ip = disc.addresses.empty() ? "" : disc.addresses[0].address;
- uint16_t port = disc.addresses.empty() ? 5134 : disc.addresses[0].port;
- GtkWidget* r = create_row(disc.name, disc.fingerprint, ip, port, false, false);
- discovered_rows.push_back(r);
- }
-
- // Render Pending Pair Requests
- for (const auto& req : g_devices.pending_pairing_requests) {
- bool is_paired = false;
- for (const auto& p : g_devices.paired_devices) {
- if (p.first == req.fingerprint) {
- is_paired = true;
- break;
- }
- }
- if (is_paired)
- continue; // ignore if they successfully paired
-
- bool already_shown = false;
- for (const auto& disc : g_devices.discovered_devices) {
- if (disc.fingerprint == req.fingerprint) {
- already_shown = true;
- break;
- }
- }
- if (already_shown)
- continue; // ignore if mDNS already populated it
-
- std::string ip = req.addresses.empty() ? "" : req.addresses[0].address;
- uint16_t port = req.addresses.empty() ? 5134 : req.addresses[0].port;
- GtkWidget* r = create_row(req.name, req.fingerprint, ip, port, false, false);
- discovered_rows.push_back(r);
- }
-
- if (!connected_rows.empty()) {
- gtk_list_box_insert(GTK_LIST_BOX(g_devices.list_devices), create_header_row("CONNECTED"), -1);
- for (auto* r : connected_rows)
- gtk_list_box_insert(GTK_LIST_BOX(g_devices.list_devices), r, -1);
- }
-
- if (!remembered_rows.empty()) {
- gtk_list_box_insert(GTK_LIST_BOX(g_devices.list_devices), create_header_row("REMEMBERED"), -1);
- for (auto* r : remembered_rows)
- gtk_list_box_insert(GTK_LIST_BOX(g_devices.list_devices), r, -1);
- }
-
- if (!discovered_rows.empty()) {
- gtk_list_box_insert(GTK_LIST_BOX(g_devices.list_devices), create_header_row("DISCOVERED"), -1);
- for (auto* r : discovered_rows)
- gtk_list_box_insert(GTK_LIST_BOX(g_devices.list_devices), r, -1);
- }
-
- gtk_widget_show_all(g_devices.list_devices);
- }
-
- bool devices_view_handle_event(const nlohmann::json& event) {
- const std::string command = event.value("command", "");
- if (command == "state_snapshot") {
- apply_state_snapshot(event);
- return true;
- }
- if (command == "client_connected") {
- std::string fp = event.value("fingerprint", "");
- if (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);
- }
- devices_view_refresh();
- update_right_pane();
- return true;
- }
- if (command == "client_disconnected") {
- std::string fp = event.value("fingerprint", "");
- g_devices.connected_fps.erase(
- std::remove(g_devices.connected_fps.begin(), g_devices.connected_fps.end(), fp),
- g_devices.connected_fps.end());
- devices_view_refresh();
- update_right_pane();
- return true;
- }
- if (command == "pair_request_received" || command == "untrusted_client_connected") {
- tether::DiscoveredDevice req;
- req.fingerprint = event.value("fingerprint", "");
-
- std::string resolved_name = event.value("device_name", "Unknown Device");
- if (resolved_name == "Unknown Device") {
- for (const auto& d : g_devices.discovered_devices) {
- if (d.fingerprint == req.fingerprint && !d.name.empty()) {
- resolved_name = d.name;
- break;
- }
- }
- }
- req.name = resolved_name;
- req.addresses.push_back({event.value("address", ""), 5134});
- bool exists = false;
- for (const auto& dev : g_devices.pending_pairing_requests) {
- if (dev.fingerprint == req.fingerprint) {
- exists = true;
- break;
- }
- }
- if (!exists) {
- g_devices.pending_pairing_requests.push_back(req);
- devices_view_refresh();
- }
- return true;
- }
- if (command == "pair_accepted") {
- std::string fp = event.value("fingerprint", "");
- std::string name = event.value("device_name", "");
- if (!fp.empty()) {
- 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});
-
- g_devices.pending_pairing_requests.erase(
- std::remove_if(g_devices.pending_pairing_requests.begin(),
- g_devices.pending_pairing_requests.end(),
- [&](const tether::DiscoveredDevice& d) { return d.fingerprint == fp; }),
- g_devices.pending_pairing_requests.end());
- devices_view_refresh();
- update_right_pane();
- }
- return true;
- }
- if (command == "discovery_result") {
- g_devices.discovered_devices.clear();
- if (event.contains("devices") && event["devices"].is_array()) {
- for (const auto& d : event["devices"]) {
- tether::DiscoveredDevice dev;
- dev.name = d.value("name", "");
- dev.fingerprint = d.value("fingerprint", "");
- if (d.contains("addresses") && d["addresses"].is_array()) {
- for (const auto& a : d["addresses"]) {
- dev.addresses.push_back({a.value("address", ""), a.value<uint16_t>("port", 5134)});
- }
- }
- g_devices.discovered_devices.push_back(dev);
- }
- }
- devices_view_refresh();
- set_status_main("Ready");
- return true;
- }
- if (command == "file_send_complete") {
- set_status_action(event.value("message", ""));
- return true;
- }
- if (command == "clipboard_content") {
- set_status_action("Desktop Clipboard Sync triggered.");
- return true;
- }
- return false;
- }
-
- GtkWidget* devices_view_new() {
- GtkWidget* paned = gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
-
- // Left Pane (List)
- GtkWidget* left_scroll = gtk_scrolled_window_new(nullptr, nullptr);
- gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(left_scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
- gtk_widget_set_size_request(left_scroll, 220, -1);
-
- g_devices.list_devices = gtk_list_box_new();
- g_signal_connect(g_devices.list_devices, "row-selected", G_CALLBACK(on_device_selected), nullptr);
- gtk_container_add(GTK_CONTAINER(left_scroll), g_devices.list_devices);
- gtk_paned_pack1(GTK_PANED(paned), left_scroll, FALSE, FALSE);
-
- // Right Pane
- g_devices.right_pane_stack = gtk_stack_new();
- gtk_stack_set_transition_type(GTK_STACK(g_devices.right_pane_stack), GTK_STACK_TRANSITION_TYPE_CROSSFADE);
-
- // Placeholder
- GtkWidget* placeholder = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
- gtk_widget_set_valign(placeholder, GTK_ALIGN_CENTER);
- gtk_widget_set_halign(placeholder, GTK_ALIGN_CENTER);
- GtkWidget* p_icon = gtk_image_new_from_icon_name("computer-symbolic", GTK_ICON_SIZE_DIALOG);
- gtk_box_pack_start(GTK_BOX(placeholder), p_icon, FALSE, FALSE, 0);
- GtkWidget* p_lbl = gtk_label_new("Select a device to start");
- gtk_style_context_add_class(gtk_widget_get_style_context(p_lbl), "muted");
- gtk_box_pack_start(GTK_BOX(placeholder), p_lbl, FALSE, FALSE, 0);
- gtk_stack_add_named(GTK_STACK(g_devices.right_pane_stack), placeholder, "placeholder");
-
- // Pair
- GtkWidget* pair_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 16);
- gtk_widget_set_valign(pair_box, GTK_ALIGN_CENTER);
- gtk_widget_set_halign(pair_box, GTK_ALIGN_CENTER);
- g_devices.lbl_unpaired_name = gtk_label_new(nullptr);
- gtk_box_pack_start(GTK_BOX(pair_box), g_devices.lbl_unpaired_name, FALSE, FALSE, 0);
- g_devices.lbl_unpaired_ip = gtk_label_new(nullptr);
- gtk_style_context_add_class(gtk_widget_get_style_context(g_devices.lbl_unpaired_ip), "muted");
- gtk_box_pack_start(GTK_BOX(pair_box), g_devices.lbl_unpaired_ip, FALSE, FALSE, 0);
-
- GtkWidget* pair_btn = gtk_button_new_with_label("Pair Device");
- gtk_style_context_add_class(gtk_widget_get_style_context(pair_btn), "suggested-action");
- g_signal_connect(pair_btn, "clicked", G_CALLBACK(on_pair_click), nullptr);
- gtk_box_pack_start(GTK_BOX(pair_box), pair_btn, FALSE, FALSE, 0);
-
- // optional accept override button
- GtkWidget* accept_btn = gtk_button_new_with_label("Force Trust (Accept Pending)");
- g_signal_connect(accept_btn, "clicked", G_CALLBACK(on_accept_click), nullptr);
- gtk_box_pack_start(GTK_BOX(pair_box), accept_btn, FALSE, FALSE, 0);
-
- gtk_stack_add_named(GTK_STACK(g_devices.right_pane_stack), pair_box, "pair");
-
- // Action
- GtkWidget* action_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 24);
- gtk_container_set_border_width(GTK_CONTAINER(action_box), 32);
- gtk_widget_set_valign(action_box, GTK_ALIGN_CENTER);
-
- g_devices.lbl_action_name = gtk_label_new(nullptr);
- gtk_widget_set_halign(g_devices.lbl_action_name, GTK_ALIGN_CENTER);
- gtk_box_pack_start(GTK_BOX(action_box), g_devices.lbl_action_name, FALSE, FALSE, 0);
-
- GtkWidget* btn_grid = gtk_box_new(GTK_ORIENTATION_VERTICAL, 12);
- gtk_widget_set_halign(btn_grid, GTK_ALIGN_CENTER);
- g_devices.btn_grid = btn_grid;
-
- GtkWidget* btn_send_file = gtk_button_new_with_label("Send File");
- gtk_style_context_add_class(gtk_widget_get_style_context(btn_send_file), "suggested-action");
- g_signal_connect(btn_send_file, "clicked", G_CALLBACK(on_choose_file), nullptr);
- gtk_box_pack_start(GTK_BOX(btn_grid), btn_send_file, FALSE, FALSE, 0);
-
- GtkWidget* btn_send_clip = gtk_button_new_with_label("Send Clipboard");
- g_signal_connect(btn_send_clip,
- "clicked",
- G_CALLBACK(+[](GtkWidget*, gpointer) {
- nlohmann::json j;
- j["command"] = "clipboard_set"; // triggers clipboard send
- daemon_send(j);
- set_status_action("Clipboard sync requested...");
- }),
- nullptr);
- gtk_box_pack_start(GTK_BOX(btn_grid), btn_send_clip, FALSE, FALSE, 0);
-
- gtk_box_pack_start(GTK_BOX(action_box), btn_grid, FALSE, FALSE, 0);
-
- g_devices.lbl_action_status = gtk_label_new("Ready");
- gtk_widget_set_halign(g_devices.lbl_action_status, GTK_ALIGN_CENTER);
- gtk_style_context_add_class(gtk_widget_get_style_context(g_devices.lbl_action_status), "muted");
- gtk_box_pack_start(GTK_BOX(action_box), g_devices.lbl_action_status, FALSE, FALSE, 0);
-
- gtk_stack_add_named(GTK_STACK(g_devices.right_pane_stack), action_box, "action");
-
- gtk_paned_pack2(GTK_PANED(paned), g_devices.right_pane_stack, TRUE, FALSE);
- gtk_stack_set_visible_child_name(GTK_STACK(g_devices.right_pane_stack), "placeholder");
-
- return paned;
- }
-
-} // namespace tether::ui
diff --git a/src/gtk/devices_view.hpp b/src/gtk/devices_view.hpp
deleted file mode 100644
index b4dfd3e..0000000
--- a/src/gtk/devices_view.hpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#pragma once
-
-#include <gtk/gtk.h>
-#include <nlohmann/json.hpp>
-
-namespace tether::ui {
-
- // The device manager: discovered, remembered and connected devices beside a
- // pane for acting on the selected one.
- GtkWidget* devices_view_new();
-
- // Returns true when the event belonged to this view.
- bool devices_view_handle_event(const nlohmann::json& event);
-
- void devices_view_refresh();
- void devices_view_trigger_discovery();
-
-} // namespace tether::ui
diff --git a/src/gtk/main.cpp b/src/gtk/main.cpp
index da02e2e..251fa1b 100644
--- a/src/gtk/main.cpp
+++ b/src/gtk/main.cpp
@@ -1,95 +1,794 @@
-#include "daemon_client.hpp"
-#include "devices_view.hpp"
-#include "messages_view.hpp"
-#include "notifications_view.hpp"
-#include "ui_util.hpp"
-
+#include <gio/gio.h>
#include <gtk/gtk.h>
+
+#include <nlohmann/json.hpp>
+
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <ctime>
+#include <filesystem>
+#include <string>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <tether/core.hpp>
#include <tether/crypto.hpp>
+#include <tether/discovery.hpp>
+#include <tether/log.hpp>
+#include <tether/net.hpp>
+#include <unistd.h>
+#include <vector>
namespace {
- using namespace tether::ui;
+ struct AppState {
+ std::vector<tether::DiscoveredDevice> discovered_devices;
+ std::vector<tether::DiscoveredDevice> pending_pairing_requests;
+ std::vector<std::pair<std::string, std::string>> paired_devices; // fp, name
+ std::vector<std::string> connected_fps; // active connections
+
+ int event_fd = -1;
+ GIOChannel* event_channel = nullptr;
+ guint event_watch_id = 0;
+ guint event_retry_id = 0;
+
+ GtkApplication* app = nullptr;
+ GtkWidget* window = nullptr;
+
+ GtkWidget* header_bar = nullptr;
+ GtkWidget* list_devices = nullptr;
+ GtkWidget* right_pane_stack = nullptr;
+
+ std::string selected_device_fp;
+ std::string selected_device_name;
+ std::string selected_device_ip;
+ uint16_t selected_device_port = 5134;
+
+ GtkWidget* lbl_action_name = nullptr;
+ GtkWidget* lbl_action_status = nullptr;
+ GtkWidget* btn_grid = nullptr;
+
+ GtkWidget* lbl_unpaired_name = nullptr;
+ GtkWidget* lbl_unpaired_ip = nullptr;
+ };
+
+ AppState g_app;
+
+ std::string format_fingerprint(const std::string& fingerprint) {
+ std::string formatted;
+ for (size_t i = 0; i < fingerprint.size(); ++i) {
+ if (i > 0 && i % 2 == 0)
+ formatted += ":";
+ formatted += fingerprint[i];
+ }
+ return formatted;
+ }
+
+ std::string escape_markup(const std::string& text) {
+ gchar* escaped = g_markup_escape_text(text.c_str(), -1);
+ std::string result = escaped ? escaped : "";
+ g_free(escaped);
+ return result;
+ }
+
+ void set_markup(GtkWidget* label, const std::string& text) {
+ if (label) {
+ gtk_label_set_markup(GTK_LABEL(label), text.c_str());
+ }
+ }
+
+ void set_status(GtkWidget* label, const std::string& text) {
+ if (label) {
+ gtk_label_set_text(GTK_LABEL(label), text.c_str());
+ }
+ }
+
+ void set_status_main(const std::string& text) {
+ if (g_app.header_bar) {
+ gtk_header_bar_set_subtitle(GTK_HEADER_BAR(g_app.header_bar), text.c_str());
+ }
+ }
+
+ void set_status_action(const std::string& text) { set_status(g_app.lbl_action_status, text); }
+
+ void send_async_daemon_message(const nlohmann::json& j) {
+ if (g_app.event_fd >= 0) {
+ std::string payload = j.dump() + "\n";
+ if (::write(g_app.event_fd, payload.c_str(), payload.size()) < 0) {
+ debug::log(ERR, "daemon write error\n");
+ }
+ }
+ }
+
+ void trigger_discovery() {
+ set_status_main("Scanning for nearby devices...");
+ nlohmann::json j;
+ j["command"] = "discover";
+ send_async_daemon_message(j);
+ }
+
+ void clear_list_box(GtkWidget* list_box) {
+ GList* children = gtk_container_get_children(GTK_CONTAINER(list_box));
+ for (GList* iter = children; iter; iter = g_list_next(iter)) {
+ gtk_widget_destroy(GTK_WIDGET(iter->data));
+ }
+ g_list_free(children);
+ }
+
+ // Refresh the device list based on Discovered (unpaired), Paired (offline), Paired (online)
+ void refresh_device_list() {
+ clear_list_box(g_app.list_devices);
+
+ tether::Crypto::instance().init();
+ try {
+ nlohmann::json known = nlohmann::json::parse(tether::Crypto::instance().get_known_hosts_dump());
+ g_app.paired_devices.clear();
+ if (!known.empty()) {
+ for (auto& [fingerprint, name_value] : known.items()) {
+ g_app.paired_devices.push_back(
+ {fingerprint, name_value.is_string() ? name_value.get<std::string>() : "Unknown Device"});
+ }
+ }
+ } catch (...) {
+ }
+
+ // We build a unified list of devices.
+ // 1. All Paired Devices
+ // 2. Any Discovered Devices not in the Paired list
+
+ auto create_row = [](const std::string& name,
+ const std::string& fp,
+ const std::string& ip,
+ uint16_t port,
+ bool paired,
+ bool online) {
+ GtkWidget* row = gtk_list_box_row_new();
+ g_object_set_data_full(G_OBJECT(row), "fp", g_strdup(fp.c_str()), g_free);
+ g_object_set_data_full(G_OBJECT(row), "name", g_strdup(name.c_str()), g_free);
+ g_object_set_data_full(G_OBJECT(row), "ip", g_strdup(ip.c_str()), g_free);
+ g_object_set_data(G_OBJECT(row), "port", GINT_TO_POINTER(port));
+ g_object_set_data(G_OBJECT(row), "paired", GINT_TO_POINTER(paired ? 1 : 0));
+
+ GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 12);
+ gtk_container_set_border_width(GTK_CONTAINER(box), 12);
+
+ const char* icon_name =
+ paired ? (online ? "network-cellular-connected-symbolic" : "network-cellular-offline-symbolic")
+ : "dialog-information-symbolic";
+ GtkWidget* icon = gtk_image_new_from_icon_name(icon_name, GTK_ICON_SIZE_LARGE_TOOLBAR);
+ gtk_box_pack_start(GTK_BOX(box), icon, FALSE, FALSE, 0);
+
+ GtkWidget* labels = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
+ GtkWidget* title = gtk_label_new(nullptr);
+ gtk_label_set_markup(GTK_LABEL(title), ("<b>" + escape_markup(name) + "</b>").c_str());
+ gtk_label_set_xalign(GTK_LABEL(title), 0.0);
+ gtk_box_pack_start(GTK_BOX(labels), title, FALSE, FALSE, 0);
+
+ GtkWidget* subtitle = gtk_label_new(paired ? (online ? "Connected" : "Offline") : "Nearby (Tap to Pair)");
+ gtk_label_set_xalign(GTK_LABEL(subtitle), 0.0);
+ gtk_style_context_add_class(gtk_widget_get_style_context(subtitle), "muted");
+ gtk_box_pack_start(GTK_BOX(labels), subtitle, FALSE, FALSE, 0);
+
+ gtk_box_pack_start(GTK_BOX(box), labels, TRUE, TRUE, 0);
+ gtk_container_add(GTK_CONTAINER(row), box);
+ return row;
+ };
+
+ auto create_header_row = [](const std::string& title_text) {
+ GtkWidget* row = gtk_list_box_row_new();
+ gtk_list_box_row_set_selectable(GTK_LIST_BOX_ROW(row), FALSE);
+ GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
+ gtk_container_set_border_width(GTK_CONTAINER(box), 8);
+ GtkWidget* lbl = gtk_label_new(nullptr);
+ gtk_label_set_markup(
+ GTK_LABEL(lbl),
+ ("<b><span size='small' color='gray'>" + escape_markup(title_text) + "</span></b>").c_str());
+ gtk_label_set_xalign(GTK_LABEL(lbl), 0.0);
+ gtk_box_pack_start(GTK_BOX(box), lbl, TRUE, TRUE, 0);
+ gtk_container_add(GTK_CONTAINER(row), box);
+ return row;
+ };
+
+ std::string my_fp = tether::Crypto::instance().get_my_fingerprint();
+
+ std::vector<GtkWidget*> connected_rows;
+ std::vector<GtkWidget*> remembered_rows;
+ std::vector<GtkWidget*> discovered_rows;
+
+ for (const auto& paired : g_app.paired_devices) {
+ bool online = std::find(g_app.connected_fps.begin(), g_app.connected_fps.end(), paired.first) !=
+ g_app.connected_fps.end();
+ GtkWidget* r = create_row(paired.second, paired.first, "", 5134, true, online);
+ if (online) {
+ connected_rows.push_back(r);
+ } else {
+ remembered_rows.push_back(r);
+ }
+ }
+
+ for (const auto& disc : g_app.discovered_devices) {
+ if (disc.fingerprint == my_fp)
+ continue;
+ bool is_paired = false;
+ for (const auto& p : g_app.paired_devices) {
+ if (p.first == disc.fingerprint) {
+ is_paired = true;
+ break;
+ }
+ }
+ if (is_paired)
+ continue; // already added above
+ std::string ip = disc.addresses.empty() ? "" : disc.addresses[0].address;
+ uint16_t port = disc.addresses.empty() ? 5134 : disc.addresses[0].port;
+ GtkWidget* r = create_row(disc.name, disc.fingerprint, ip, port, false, false);
+ discovered_rows.push_back(r);
+ }
+
+ // Render Pending Pair Requests
+ for (const auto& req : g_app.pending_pairing_requests) {
+ bool is_paired = false;
+ for (const auto& p : g_app.paired_devices) {
+ if (p.first == req.fingerprint) {
+ is_paired = true;
+ break;
+ }
+ }
+ if (is_paired)
+ continue; // ignore if they successfully paired
+
+ bool already_shown = false;
+ for (const auto& disc : g_app.discovered_devices) {
+ if (disc.fingerprint == req.fingerprint) {
+ already_shown = true;
+ break;
+ }
+ }
+ if (already_shown)
+ continue; // ignore if mDNS already populated it
+
+ std::string ip = req.addresses.empty() ? "" : req.addresses[0].address;
+ uint16_t port = req.addresses.empty() ? 5134 : req.addresses[0].port;
+ GtkWidget* r = create_row(req.name, req.fingerprint, ip, port, false, false);
+ discovered_rows.push_back(r);
+ }
+
+ if (!connected_rows.empty()) {
+ gtk_list_box_insert(GTK_LIST_BOX(g_app.list_devices), create_header_row("CONNECTED"), -1);
+ for (auto* r : connected_rows)
+ gtk_list_box_insert(GTK_LIST_BOX(g_app.list_devices), r, -1);
+ }
+
+ if (!remembered_rows.empty()) {
+ gtk_list_box_insert(GTK_LIST_BOX(g_app.list_devices), create_header_row("REMEMBERED"), -1);
+ for (auto* r : remembered_rows)
+ gtk_list_box_insert(GTK_LIST_BOX(g_app.list_devices), r, -1);
+ }
+
+ if (!discovered_rows.empty()) {
+ gtk_list_box_insert(GTK_LIST_BOX(g_app.list_devices), create_header_row("DISCOVERED"), -1);
+ for (auto* r : discovered_rows)
+ gtk_list_box_insert(GTK_LIST_BOX(g_app.list_devices), r, -1);
+ }
+
+ gtk_widget_show_all(g_app.list_devices);
+ }
+
+ void update_right_pane() {
+ if (g_app.selected_device_fp.empty()) {
+ gtk_stack_set_visible_child_name(GTK_STACK(g_app.right_pane_stack), "placeholder");
+ return;
+ }
- GtkWidget* g_refresh_button = nullptr;
+ bool is_paired = false;
+ for (const auto& p : g_app.paired_devices) {
+ if (p.first == g_app.selected_device_fp)
+ is_paired = true;
+ }
- void on_visible_view_changed(GObject* stack, GParamSpec*, gpointer) {
- const gchar* name = gtk_stack_get_visible_child_name(GTK_STACK(stack));
- const std::string view = name ? name : "";
+ if (is_paired) {
+ gtk_stack_set_visible_child_name(GTK_STACK(g_app.right_pane_stack), "action");
+ set_markup(g_app.lbl_action_name, ("<b>" + escape_markup(g_app.selected_device_name) + "</b>"));
+ bool online = std::find(g_app.connected_fps.begin(), g_app.connected_fps.end(), g_app.selected_device_fp) !=
+ g_app.connected_fps.end();
+ set_status_action(online ? "Connected and ready." : "Device is offline. Pair again or wait for network.");
+ if (g_app.btn_grid) {
+ gtk_widget_set_visible(g_app.btn_grid, online);
+ }
+ } else {
+ gtk_stack_set_visible_child_name(GTK_STACK(g_app.right_pane_stack), "pair");
+ set_markup(g_app.lbl_unpaired_name, ("<b>" + escape_markup(g_app.selected_device_name) + "</b>"));
+ set_status(g_app.lbl_unpaired_ip,
+ ("Found at " + g_app.selected_device_ip + ":" + std::to_string(g_app.selected_device_port)));
+ }
+ }
- // Refresh means "scan for devices", which is meaningless on the other
- // views, so it only appears where it does something.
- if (g_refresh_button)
- gtk_widget_set_visible(g_refresh_button, view == "devices");
+ void on_device_selected(GtkListBox*, GtkListBoxRow* row, gpointer) {
+ if (!row)
+ return;
+ const char* fp = (const char*)g_object_get_data(G_OBJECT(row), "fp");
+ const char* name = (const char*)g_object_get_data(G_OBJECT(row), "name");
+ const char* ip = (const char*)g_object_get_data(G_OBJECT(row), "ip");
+ g_app.selected_device_fp = fp ? fp : "";
+ g_app.selected_device_name = name ? name : "";
+ g_app.selected_device_ip = ip ? ip : "";
+ g_app.selected_device_port = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(row), "port"));
+ update_right_pane();
+ }
- messages_view_set_visible(view == "messages");
- notifications_view_set_visible(view == "notifications");
+ void on_pair_click(GtkWidget*, gpointer) {
+ if (g_app.selected_device_ip.empty())
+ return;
+ set_status(g_app.lbl_unpaired_ip, "Sending pair request...");
+ nlohmann::json j;
+ j["command"] = "pair_request";
+ j["host"] = g_app.selected_device_ip;
+ j["port"] = g_app.selected_device_port;
+ send_async_daemon_message(j);
+ set_status_main("Pair request sent. Approve on remote device!");
+ }
+
+ void on_accept_click(GtkWidget*, gpointer) {
+ if (g_app.selected_device_fp.empty())
+ return;
+ nlohmann::json j;
+ j["command"] = "accept_device";
+ j["fingerprint"] = g_app.selected_device_fp;
+ send_async_daemon_message(j);
+ }
+
+ void send_file_async(const std::filesystem::path& path) {
+ if (g_app.event_fd < 0) {
+ set_status_action("Daemon unavailable.");
+ return;
+ }
+ set_status_action("Sending " + path.filename().string() + "…");
+ nlohmann::json j;
+ j["command"] = "send_file";
+ j["path"] = path.string();
+ send_async_daemon_message(j);
+ }
+
+ void on_choose_file(GtkWidget*, gpointer) {
+ GtkWidget* dialog = gtk_file_chooser_dialog_new("Send File",
+ GTK_WINDOW(g_app.window),
+ GTK_FILE_CHOOSER_ACTION_OPEN,
+ "_Cancel",
+ GTK_RESPONSE_CANCEL,
+ "_Send",
+ GTK_RESPONSE_ACCEPT,
+ nullptr);
+ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
+ char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
+ if (filename) {
+ send_file_async(filename);
+ g_free(filename);
+ }
+ }
+ gtk_widget_destroy(dialog);
+ }
+
+ void on_pull_clipboard(GtkWidget*, gpointer) {
+ nlohmann::json j;
+ j["command"] = "clipboard_get";
+ send_async_daemon_message(j);
+ set_status_action("Requested desktop clipboard...");
+ }
+
+ void on_push_clipboard(GtkWidget*, gpointer) {
+ // Wait, KDE Connect puts local clipboard to remote automatically, or via button.
+ // We can just use the Push Clipboard button which pushes current wayland clipboard.
+ // But the daemon does this transparently! We just need `clipboard_set` if the user typed text,
+ // but here we just push whatever is on Wayland to the remote right now, wait...
+ // Actually, if the user hits "Push", we read local Wayland, then send it via daemon? No, the Daemon already
+ // pushes wayland changes! Actually, let's keep the button for explicit "Sync Now" if they disabled auto-sync.
+ }
+
+ void apply_state_snapshot(const nlohmann::json& j) {
+ g_app.connected_fps.clear();
+ if (j.contains("connected_clients") && j["connected_clients"].is_array()) {
+ for (auto& c : j["connected_clients"]) {
+ if (c.value("paired", false)) {
+ g_app.connected_fps.push_back(c.value("fingerprint", ""));
+ } else {
+ tether::DiscoveredDevice dev;
+ dev.fingerprint = c.value("fingerprint", "");
+ dev.name = c.value("device_name", "Unknown Device");
+ dev.addresses.push_back({c.value("address", ""), 5134});
+ g_app.discovered_devices.push_back(dev);
+ }
+ }
+ }
+ g_app.pending_pairing_requests.clear();
+ if (j.contains("pending_pairs") && j["pending_pairs"].is_array()) {
+ for (auto& p : j["pending_pairs"]) {
+ tether::DiscoveredDevice req;
+ req.fingerprint = p.value("fingerprint", "");
+ req.name = p.value("device_name", "Unknown Device");
+ g_app.pending_pairing_requests.push_back(req);
+ }
+ }
+ refresh_device_list();
+ }
+
+ void handle_daemon_event(const nlohmann::json& event) {
+ const std::string command = event.value("command", "");
+ if (command == "state_snapshot") {
+ apply_state_snapshot(event);
+ return;
+ }
+ if (command == "client_connected") {
+ std::string fp = event.value("fingerprint", "");
+ if (std::find(g_app.connected_fps.begin(), g_app.connected_fps.end(), fp) == g_app.connected_fps.end()) {
+ g_app.connected_fps.push_back(fp);
+ }
+ refresh_device_list();
+ update_right_pane();
+ return;
+ }
+ if (command == "client_disconnected") {
+ std::string fp = event.value("fingerprint", "");
+ g_app.connected_fps.erase(std::remove(g_app.connected_fps.begin(), g_app.connected_fps.end(), fp),
+ g_app.connected_fps.end());
+ refresh_device_list();
+ update_right_pane();
+ return;
+ }
+ if (command == "pair_request_received" || command == "untrusted_client_connected") {
+ tether::DiscoveredDevice req;
+ req.fingerprint = event.value("fingerprint", "");
+
+ std::string resolved_name = event.value("device_name", "Unknown Device");
+ if (resolved_name == "Unknown Device") {
+ for (const auto& d : g_app.discovered_devices) {
+ if (d.fingerprint == req.fingerprint && !d.name.empty()) {
+ resolved_name = d.name;
+ break;
+ }
+ }
+ }
+ req.name = resolved_name;
+ req.addresses.push_back({event.value("address", ""), 5134});
+ bool exists = false;
+ for (const auto& dev : g_app.pending_pairing_requests) {
+ if (dev.fingerprint == req.fingerprint) {
+ exists = true;
+ break;
+ }
+ }
+ if (!exists) {
+ g_app.pending_pairing_requests.push_back(req);
+ refresh_device_list();
+ }
+ return;
+ }
+ if (command == "pair_accepted") {
+ std::string fp = event.value("fingerprint", "");
+ std::string name = event.value("device_name", "");
+ if (!fp.empty()) {
+ g_app.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_app.paired_devices) {
+ if (p.first == fp) {
+ already_paired = true;
+ break;
+ }
+ }
+ if (!already_paired)
+ g_app.paired_devices.push_back({fp, name});
+
+ g_app.pending_pairing_requests.erase(
+ std::remove_if(g_app.pending_pairing_requests.begin(),
+ g_app.pending_pairing_requests.end(),
+ [&](const tether::DiscoveredDevice& d) { return d.fingerprint == fp; }),
+ g_app.pending_pairing_requests.end());
+ refresh_device_list();
+ update_right_pane();
+ }
+ return;
+ }
+ if (command == "discovery_result") {
+ g_app.discovered_devices.clear();
+ if (event.contains("devices") && event["devices"].is_array()) {
+ for (const auto& d : event["devices"]) {
+ tether::DiscoveredDevice dev;
+ dev.name = d.value("name", "");
+ dev.fingerprint = d.value("fingerprint", "");
+ if (d.contains("addresses") && d["addresses"].is_array()) {
+ for (const auto& a : d["addresses"]) {
+ dev.addresses.push_back({a.value("address", ""), a.value<uint16_t>("port", 5134)});
+ }
+ }
+ g_app.discovered_devices.push_back(dev);
+ }
+ }
+ refresh_device_list();
+ set_status_main("Ready");
+ return;
+ }
+ if (command == "file_send_complete") {
+ bool ok = event.value("success", false);
+ set_status_action(event.value("message", ""));
+ return;
+ }
+ if (command == "clipboard_content") {
+ set_status_action("Desktop Clipboard Sync triggered.");
+ return;
+ }
+ if (command == "pair_accepted") {
+ // Remove from pending pairing requests
+ std::string fp = event.value("fingerprint", "");
+ g_app.pending_pairing_requests.erase(
+ std::remove_if(g_app.pending_pairing_requests.begin(),
+ g_app.pending_pairing_requests.end(),
+ [&](const tether::DiscoveredDevice& d) { return d.fingerprint == fp; }),
+ g_app.pending_pairing_requests.end());
+
+ refresh_device_list();
+ update_right_pane();
+ return;
+ }
+ }
+
+ // ----------- EVENT LOOP -----------
+ void stop_event_subscription() {
+ if (g_app.event_watch_id != 0) {
+ g_source_remove(g_app.event_watch_id);
+ g_app.event_watch_id = 0;
+ }
+ if (g_app.event_channel) {
+ g_io_channel_shutdown(g_app.event_channel, TRUE, nullptr);
+ g_io_channel_unref(g_app.event_channel);
+ g_app.event_channel = nullptr;
+ } else if (g_app.event_fd >= 0) {
+ close(g_app.event_fd);
+ }
+ g_app.event_fd = -1;
+ }
+
+ gboolean start_event_subscription(gpointer);
+ void schedule_event_retry() {
+ if (g_app.event_retry_id == 0)
+ g_app.event_retry_id = g_timeout_add_seconds(2, start_event_subscription, nullptr);
+ }
+
+ gboolean on_event_channel(GIOChannel* source, GIOCondition condition, gpointer) {
+ if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
+ stop_event_subscription();
+ schedule_event_retry();
+ set_status_main("Daemon Offline");
+ return FALSE;
+ }
+ if (condition & G_IO_IN) {
+ gchar* line = nullptr;
+ gsize length = 0;
+ GError* error = nullptr;
+ while (true) {
+ GIOStatus status = g_io_channel_read_line(source, &line, &length, nullptr, &error);
+ if (status == G_IO_STATUS_AGAIN) {
+ if (line)
+ g_free(line);
+ break;
+ }
+ if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR) {
+ if (error) {
+ debug::log(ERR, "Stream err: {}", error->message);
+ g_error_free(error);
+ }
+ if (line)
+ g_free(line);
+ stop_event_subscription();
+ schedule_event_retry();
+ set_status_main("Daemon Offline");
+ return FALSE;
+ }
+ if (line && length > 0) {
+ try {
+ handle_daemon_event(nlohmann::json::parse(std::string(line, length)));
+ } catch (...) {
+ }
+ }
+ if (line)
+ g_free(line);
+ }
+ }
+ return TRUE;
+ }
+
+ gboolean start_event_subscription(gpointer) {
+ if (g_app.event_retry_id != 0) {
+ g_source_remove(g_app.event_retry_id);
+ g_app.event_retry_id = 0;
+ }
+ stop_event_subscription();
+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd < 0) {
+ schedule_event_retry();
+ return G_SOURCE_REMOVE;
+ }
+
+ sockaddr_un addr{};
+ addr.sun_family = AF_UNIX;
+ std::string path = tether::get_runtime_dir() + "/tetherd.sock";
+ std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
+
+ if (::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
+ close(fd);
+ static bool autostart_attempted = false;
+ if (!autostart_attempted) {
+ autostart_attempted = true;
+ pid_t pid = fork();
+ if (pid == 0) {
+ std::filesystem::path self_path = std::filesystem::read_symlink("/proc/self/exe");
+ std::string daemon_path = (self_path.parent_path() / "tetherd").string();
+ if (fork() == 0) {
+ if (freopen("/dev/null", "w", stdout) == nullptr) {
+ }
+ if (freopen("/dev/null", "w", stderr) == nullptr) {
+ }
+ if (freopen("/dev/null", "r", stdin) == nullptr) {
+ }
+ execl(daemon_path.c_str(), "tetherd", nullptr);
+ execlp("tetherd", "tetherd", nullptr);
+ exit(1);
+ }
+ exit(0);
+ } else if (pid > 0) {
+ int status;
+ waitpid(pid, &status, 0);
+ }
+ }
+ schedule_event_retry();
+ set_status_main("Daemon Offline");
+ return G_SOURCE_REMOVE;
+ }
+
+ g_app.event_fd = fd;
+ g_app.event_channel = g_io_channel_unix_new(fd);
+ g_io_channel_set_encoding(g_app.event_channel, nullptr, nullptr);
+ g_io_channel_set_buffered(g_app.event_channel, TRUE);
+ g_io_channel_set_flags(g_app.event_channel, G_IO_FLAG_NONBLOCK, nullptr);
+ g_app.event_watch_id = g_io_add_watch(g_app.event_channel,
+ static_cast<GIOCondition>(G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL),
+ on_event_channel,
+ nullptr);
+ static const char kSubscribe[] = "{\"command\":\"subscribe\"}\n";
+ if (write(fd, kSubscribe, sizeof(kSubscribe) - 1) < 0) {
+ debug::log(ERR, "subscribe write error\n");
+ }
+ set_status_main("Daemon Online");
+ return G_SOURCE_REMOVE;
}
void activate(GtkApplication* app, gpointer) {
+ g_app.app = app;
tether::Crypto::instance().init();
- GtkWidget* window = gtk_application_window_new(app);
- gtk_window_set_title(GTK_WINDOW(window), "Tether");
- gtk_window_set_default_size(GTK_WINDOW(window), 820, 560);
- set_main_window(window);
+ g_app.window = gtk_application_window_new(app);
+ gtk_window_set_title(GTK_WINDOW(g_app.window), "Tether");
+ gtk_window_set_default_size(GTK_WINDOW(g_app.window), 600, 500);
+
+ // HeaderBar
+ g_app.header_bar = gtk_header_bar_new();
+ gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(g_app.header_bar), TRUE);
+ gtk_header_bar_set_title(GTK_HEADER_BAR(g_app.header_bar), "Tether");
+ gtk_window_set_titlebar(GTK_WINDOW(g_app.window), g_app.header_bar);
+
+ GtkWidget* refresh_btn = gtk_button_new_from_icon_name("view-refresh-symbolic", GTK_ICON_SIZE_BUTTON);
+ g_signal_connect(
+ refresh_btn, "clicked", G_CALLBACK(+[](GtkWidget*, gpointer) { trigger_discovery(); }), nullptr);
+ gtk_header_bar_pack_start(GTK_HEADER_BAR(g_app.header_bar), refresh_btn);
+
+ // Paned Layout
+ GtkWidget* paned = gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
+ gtk_container_add(GTK_CONTAINER(g_app.window), paned);
+
+ // Left Pane (List)
+ GtkWidget* left_scroll = gtk_scrolled_window_new(nullptr, nullptr);
+ gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(left_scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
+ gtk_widget_set_size_request(left_scroll, 220, -1);
- GtkWidget* header_bar = gtk_header_bar_new();
- gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(header_bar), TRUE);
- gtk_header_bar_set_title(GTK_HEADER_BAR(header_bar), "Tether");
- gtk_window_set_titlebar(GTK_WINDOW(window), header_bar);
- set_header_bar(header_bar);
+ g_app.list_devices = gtk_list_box_new();
+ g_signal_connect(g_app.list_devices, "row-selected", G_CALLBACK(on_device_selected), nullptr);
+ gtk_container_add(GTK_CONTAINER(left_scroll), g_app.list_devices);
+ gtk_paned_pack1(GTK_PANED(paned), left_scroll, FALSE, FALSE);
- g_refresh_button = gtk_button_new_from_icon_name("view-refresh-symbolic", GTK_ICON_SIZE_BUTTON);
- g_signal_connect(g_refresh_button,
+ // Right Pane
+ g_app.right_pane_stack = gtk_stack_new();
+ gtk_stack_set_transition_type(GTK_STACK(g_app.right_pane_stack), GTK_STACK_TRANSITION_TYPE_CROSSFADE);
+
+ // --- State: Placeholder ---
+ GtkWidget* placeholder = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
+ gtk_widget_set_valign(placeholder, GTK_ALIGN_CENTER);
+ gtk_widget_set_halign(placeholder, GTK_ALIGN_CENTER);
+ GtkWidget* p_icon = gtk_image_new_from_icon_name("computer-symbolic", GTK_ICON_SIZE_DIALOG);
+ gtk_box_pack_start(GTK_BOX(placeholder), p_icon, FALSE, FALSE, 0);
+ GtkWidget* p_lbl = gtk_label_new("Select a device to start");
+ gtk_style_context_add_class(gtk_widget_get_style_context(p_lbl), "muted");
+ gtk_box_pack_start(GTK_BOX(placeholder), p_lbl, FALSE, FALSE, 0);
+ gtk_stack_add_named(GTK_STACK(g_app.right_pane_stack), placeholder, "placeholder");
+
+ // --- State: Pair ---
+ GtkWidget* pair_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 16);
+ gtk_widget_set_valign(pair_box, GTK_ALIGN_CENTER);
+ gtk_widget_set_halign(pair_box, GTK_ALIGN_CENTER);
+ g_app.lbl_unpaired_name = gtk_label_new(nullptr);
+ gtk_box_pack_start(GTK_BOX(pair_box), g_app.lbl_unpaired_name, FALSE, FALSE, 0);
+ g_app.lbl_unpaired_ip = gtk_label_new(nullptr);
+ gtk_style_context_add_class(gtk_widget_get_style_context(g_app.lbl_unpaired_ip), "muted");
+ gtk_box_pack_start(GTK_BOX(pair_box), g_app.lbl_unpaired_ip, FALSE, FALSE, 0);
+
+ GtkWidget* pair_btn = gtk_button_new_with_label("Pair Device");
+ gtk_style_context_add_class(gtk_widget_get_style_context(pair_btn), "suggested-action");
+ g_signal_connect(pair_btn, "clicked", G_CALLBACK(on_pair_click), nullptr);
+ gtk_box_pack_start(GTK_BOX(pair_box), pair_btn, FALSE, FALSE, 0);
+
+ // optional accept override button
+ GtkWidget* accept_btn = gtk_button_new_with_label("Force Trust (Accept Pending)");
+ g_signal_connect(accept_btn, "clicked", G_CALLBACK(on_accept_click), nullptr);
+ gtk_box_pack_start(GTK_BOX(pair_box), accept_btn, FALSE, FALSE, 0);
+
+ gtk_stack_add_named(GTK_STACK(g_app.right_pane_stack), pair_box, "pair");
+
+ // --- State: Action ---
+ GtkWidget* action_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 24);
+ gtk_container_set_border_width(GTK_CONTAINER(action_box), 32);
+ gtk_widget_set_valign(action_box, GTK_ALIGN_CENTER);
+
+ g_app.lbl_action_name = gtk_label_new(nullptr);
+ gtk_widget_set_halign(g_app.lbl_action_name, GTK_ALIGN_CENTER);
+ gtk_box_pack_start(GTK_BOX(action_box), g_app.lbl_action_name, FALSE, FALSE, 0);
+
+ GtkWidget* btn_grid = gtk_box_new(GTK_ORIENTATION_VERTICAL, 12);
+ gtk_widget_set_halign(btn_grid, GTK_ALIGN_CENTER);
+ g_app.btn_grid = btn_grid;
+
+ GtkWidget* btn_send_file = gtk_button_new_with_label("Send File");
+ gtk_style_context_add_class(gtk_widget_get_style_context(btn_send_file), "suggested-action");
+ g_signal_connect(btn_send_file, "clicked", G_CALLBACK(on_choose_file), nullptr);
+ gtk_box_pack_start(GTK_BOX(btn_grid), btn_send_file, FALSE, FALSE, 0);
+
+ GtkWidget* btn_send_clip = gtk_button_new_with_label("Send Clipboard");
+ g_signal_connect(btn_send_clip,
"clicked",
- G_CALLBACK(+[](GtkWidget*, gpointer) { devices_view_trigger_discovery(); }),
+ G_CALLBACK(+[](GtkWidget*, gpointer) {
+ nlohmann::json j;
+ j["command"] = "clipboard_set"; // triggers clipboard send
+ send_async_daemon_message(j);
+ set_status_action("Clipboard sync requested...");
+ }),
nullptr);
- gtk_header_bar_pack_start(GTK_HEADER_BAR(header_bar), g_refresh_button);
-
- GtkWidget* stack = gtk_stack_new();
- gtk_stack_set_transition_type(GTK_STACK(stack), GTK_STACK_TRANSITION_TYPE_CROSSFADE);
- gtk_stack_add_titled(GTK_STACK(stack), devices_view_new(), "devices", "Devices");
- gtk_stack_add_titled(GTK_STACK(stack), messages_view_new(), "messages", "Messages");
- gtk_stack_add_titled(GTK_STACK(stack), notifications_view_new(), "notifications", "Notifications");
+ gtk_box_pack_start(GTK_BOX(btn_grid), btn_send_clip, FALSE, FALSE, 0);
- GtkWidget* switcher = gtk_stack_switcher_new();
- gtk_stack_switcher_set_stack(GTK_STACK_SWITCHER(switcher), GTK_STACK(stack));
- gtk_header_bar_set_custom_title(GTK_HEADER_BAR(header_bar), switcher);
+ gtk_box_pack_start(GTK_BOX(action_box), btn_grid, FALSE, FALSE, 0);
- g_signal_connect(stack, "notify::visible-child-name", G_CALLBACK(on_visible_view_changed), nullptr);
- gtk_container_add(GTK_CONTAINER(window), stack);
+ g_app.lbl_action_status = gtk_label_new("Ready");
+ gtk_widget_set_halign(g_app.lbl_action_status, GTK_ALIGN_CENTER);
+ gtk_style_context_add_class(gtk_widget_get_style_context(g_app.lbl_action_status), "muted");
+ gtk_box_pack_start(GTK_BOX(action_box), g_app.lbl_action_status, FALSE, FALSE, 0);
- // One feed, dispatched to whichever view owns the event; the views never
- // hold the socket themselves.
- daemon_client_start([](const nlohmann::json& event) {
- if (devices_view_handle_event(event))
- return;
- if (messages_view_handle_event(event))
- return;
- notifications_view_handle_event(event);
- });
+ gtk_stack_add_named(GTK_STACK(g_app.right_pane_stack), action_box, "action");
- devices_view_trigger_discovery();
- devices_view_refresh();
+ gtk_paned_pack2(GTK_PANED(paned), g_app.right_pane_stack, TRUE, FALSE);
+ gtk_stack_set_visible_child_name(GTK_STACK(g_app.right_pane_stack), "placeholder");
- // Ask once at startup so the messages banner reflects reality before the
- // user ever opens that view.
- nlohmann::json connection;
- connection["command"] = "bt_connection";
- daemon_send(connection);
+ start_event_subscription(nullptr);
+ trigger_discovery();
+ refresh_device_list();
- gtk_widget_show_all(window);
- gtk_stack_set_visible_child_name(GTK_STACK(stack), "devices");
+ gtk_widget_show_all(g_app.window);
}
-
} // namespace
int main(int argc, char** argv) {
GtkApplication* app = gtk_application_new("com.tether.desktop", G_APPLICATION_DEFAULT_FLAGS);
g_signal_connect(app, "activate", G_CALLBACK(activate), nullptr);
int status = g_application_run(G_APPLICATION(app), argc, argv);
- tether::ui::daemon_client_stop();
+ stop_event_subscription();
+ if (g_app.event_retry_id != 0)
+ g_source_remove(g_app.event_retry_id);
g_object_unref(app);
return status;
}
diff --git a/src/gtk/messages_view.cpp b/src/gtk/messages_view.cpp
deleted file mode 100644
index 6abf803..0000000
--- a/src/gtk/messages_view.cpp
+++ /dev/null
@@ -1,450 +0,0 @@
-#include "messages_view.hpp"
-#include "daemon_client.hpp"
-#include "ui_util.hpp"
-
-#include <ctime>
-#include <string>
-
-namespace tether::ui {
-
- namespace {
-
- struct MessagesState {
- GtkWidget* banner = nullptr;
- GtkWidget* banner_label = nullptr;
- GtkWidget* thread_list = nullptr;
- GtkWidget* conversation = nullptr;
- GtkWidget* conversation_scroll = nullptr;
- GtkWidget* composer = nullptr;
- GtkWidget* send_button = nullptr;
- GtkWidget* placeholder_stack = nullptr;
-
- std::string selected_thread;
- std::string selected_name;
- bool visible = false;
- bool map_open = false;
- bool sending = false;
- // Whether the daemon says the selected thread can be replied to, and
- // why not when it cannot.
- bool selected_repliable = false;
- std::string selected_block_reason;
- };
-
- MessagesState g_messages;
-
- void update_composer_sensitivity();
-
- std::string format_timestamp(int64_t epoch) {
- if (epoch <= 0)
- return "";
- std::time_t t = static_cast<std::time_t>(epoch);
- std::tm tm{};
- localtime_r(&t, &tm);
-
- std::time_t now = std::time(nullptr);
- std::tm now_tm{};
- localtime_r(&now, &now_tm);
-
- char buffer[64];
- // Same day gets a time, anything older gets a date: a wall of
- // identical timestamps is harder to scan than a mixed list.
- const char* format =
- (tm.tm_year == now_tm.tm_year && tm.tm_yday == now_tm.tm_yday) ? "%H:%M" : "%b %-d, %H:%M";
- std::strftime(buffer, sizeof(buffer), format, &tm);
- return buffer;
- }
-
- void request_threads() {
- nlohmann::json j;
- j["command"] = "bt_list_threads";
- daemon_send(j);
- }
-
- void request_messages(const std::string& thread_key) {
- if (thread_key.empty())
- return;
- nlohmann::json j;
- j["command"] = "bt_list_messages";
- j["thread"] = thread_key;
- daemon_send(j);
- }
-
- GtkWidget* build_thread_row(const nlohmann::json& thread) {
- const std::string key = thread.value("thread", "");
- const std::string address = thread.value("address", "");
- const std::string name = thread.value("name", address);
- const std::string preview = thread.value("preview", "");
- const int unread = thread.value("unread", 0);
-
- GtkWidget* row = gtk_list_box_row_new();
- g_object_set_data_full(G_OBJECT(row), "thread", g_strdup(key.c_str()), g_free);
- g_object_set_data_full(G_OBJECT(row), "name", g_strdup(name.c_str()), g_free);
- // The daemon owns the decision about whether a group can be replied
- // to; the UI must not re-derive it from the key shape.
- g_object_set_data(G_OBJECT(row), "repliable", GINT_TO_POINTER(thread.value("repliable", true) ? 1 : 0));
- g_object_set_data_full(
- G_OBJECT(row), "reply_reason", g_strdup(thread.value("reply_reason", "").c_str()), g_free);
- g_object_set_data(G_OBJECT(row), "group", GINT_TO_POINTER(thread.value("group", false) ? 1 : 0));
-
- GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);
- gtk_container_set_border_width(GTK_CONTAINER(box), 10);
-
- GtkWidget* labels = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
-
- GtkWidget* title = gtk_label_new(nullptr);
- gtk_label_set_markup(GTK_LABEL(title), ("<b>" + escape_markup(name) + "</b>").c_str());
- gtk_label_set_xalign(GTK_LABEL(title), 0.0);
- gtk_label_set_ellipsize(GTK_LABEL(title), PANGO_ELLIPSIZE_END);
- gtk_box_pack_start(GTK_BOX(labels), title, FALSE, FALSE, 0);
-
- GtkWidget* subtitle = gtk_label_new(preview.c_str());
- gtk_label_set_xalign(GTK_LABEL(subtitle), 0.0);
- gtk_label_set_ellipsize(GTK_LABEL(subtitle), PANGO_ELLIPSIZE_END);
- gtk_label_set_single_line_mode(GTK_LABEL(subtitle), TRUE);
- gtk_style_context_add_class(gtk_widget_get_style_context(subtitle), "muted");
- gtk_box_pack_start(GTK_BOX(labels), subtitle, FALSE, FALSE, 0);
-
- gtk_box_pack_start(GTK_BOX(box), labels, TRUE, TRUE, 0);
-
- if (unread > 0) {
- GtkWidget* badge = gtk_label_new(nullptr);
- gtk_label_set_markup(GTK_LABEL(badge), ("<b>" + std::to_string(unread) + "</b>").c_str());
- gtk_widget_set_valign(badge, GTK_ALIGN_CENTER);
- gtk_box_pack_start(GTK_BOX(box), badge, FALSE, FALSE, 0);
- }
-
- gtk_container_add(GTK_CONTAINER(row), box);
- return row;
- }
-
- GtkWidget* build_message_row(const nlohmann::json& message) {
- const bool outgoing = message.value("outgoing", false);
- const std::string body = message.value("body", "");
- const std::string stamp = format_timestamp(message.value("timestamp", static_cast<int64_t>(0)));
-
- GtkWidget* row = gtk_list_box_row_new();
- gtk_list_box_row_set_selectable(GTK_LIST_BOX_ROW(row), FALSE);
- gtk_list_box_row_set_activatable(GTK_LIST_BOX_ROW(row), FALSE);
-
- GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
- gtk_container_set_border_width(GTK_CONTAINER(box), 8);
- gtk_widget_set_halign(box, outgoing ? GTK_ALIGN_END : GTK_ALIGN_START);
-
- GtkWidget* bubble = gtk_label_new(body.c_str());
- gtk_label_set_line_wrap(GTK_LABEL(bubble), TRUE);
- gtk_label_set_line_wrap_mode(GTK_LABEL(bubble), PANGO_WRAP_WORD_CHAR);
- gtk_label_set_max_width_chars(GTK_LABEL(bubble), 48);
- gtk_label_set_xalign(GTK_LABEL(bubble), outgoing ? 1.0 : 0.0);
- gtk_label_set_selectable(GTK_LABEL(bubble), TRUE);
- gtk_box_pack_start(GTK_BOX(box), bubble, FALSE, FALSE, 0);
-
- if (!stamp.empty()) {
- GtkWidget* time_label = gtk_label_new(stamp.c_str());
- gtk_label_set_xalign(GTK_LABEL(time_label), outgoing ? 1.0 : 0.0);
- gtk_style_context_add_class(gtk_widget_get_style_context(time_label), "muted");
- gtk_box_pack_start(GTK_BOX(box), time_label, FALSE, FALSE, 0);
- }
-
- gtk_container_add(GTK_CONTAINER(row), box);
- return row;
- }
-
- void scroll_conversation_to_end() {
- if (!g_messages.conversation_scroll)
- return;
- GtkAdjustment* adjustment =
- gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(g_messages.conversation_scroll));
- if (adjustment)
- gtk_adjustment_set_value(adjustment, gtk_adjustment_get_upper(adjustment));
- }
-
- void show_threads(const nlohmann::json& event) {
- clear_list_box(g_messages.thread_list);
- if (!event.contains("threads") || !event["threads"].is_array())
- return;
-
- GtkWidget* reselect = nullptr;
- for (const auto& thread : event["threads"]) {
- GtkWidget* row = build_thread_row(thread);
- gtk_list_box_insert(GTK_LIST_BOX(g_messages.thread_list), row, -1);
- if (thread.value("thread", "") == g_messages.selected_thread)
- reselect = row;
- }
- gtk_widget_show_all(g_messages.thread_list);
-
- // Rebuilding the list drops the selection; restoring it keeps the
- // open conversation from closing every time a message arrives.
- if (reselect)
- gtk_list_box_select_row(GTK_LIST_BOX(g_messages.thread_list), GTK_LIST_BOX_ROW(reselect));
- }
-
- void show_messages(const nlohmann::json& event) {
- if (event.value("thread", "") != g_messages.selected_thread)
- return;
-
- clear_list_box(g_messages.conversation);
- if (event.contains("messages") && event["messages"].is_array()) {
- for (const auto& message : event["messages"])
- gtk_list_box_insert(GTK_LIST_BOX(g_messages.conversation), build_message_row(message), -1);
- }
- gtk_widget_show_all(g_messages.conversation);
- scroll_conversation_to_end();
-
- // Opening a conversation marks it read here and on the phone, which
- // is what makes the unread badge agree with what the user has seen.
- if (event.contains("messages") && event["messages"].is_array()) {
- for (const auto& message : event["messages"]) {
- if (message.value("read", true) || message.value("outgoing", false))
- continue;
- nlohmann::json j;
- j["command"] = "bt_mark_read";
- j["handle"] = message.value("handle", "");
- j["read"] = true;
- daemon_send(j);
- }
- }
- }
-
- void set_banner(const std::string& text) {
- if (!g_messages.banner)
- return;
- if (text.empty()) {
- gtk_widget_hide(g_messages.banner);
- return;
- }
- set_text(g_messages.banner_label, text);
- gtk_widget_show_all(g_messages.banner);
- }
-
- void update_connection(const nlohmann::json& event) {
- const bool map_open = event.value("map_open", false);
- g_messages.map_open = map_open;
- update_composer_sensitivity();
- if (map_open) {
- set_banner("");
- if (g_messages.visible)
- request_threads();
- return;
- }
- // The daemon's reason strings name the actual next step, including
- // which toggle to flip on the phone, so they are shown verbatim
- // rather than replaced with something vaguer.
- std::string reason = event.value("profile_reason", "");
- if (reason.empty())
- reason = event.value("link_reason", "");
- if (reason.empty())
- reason = "Messages are not connected.";
- set_banner(reason);
- }
-
- // Replying needs an open conversation and a live MAP session. A group
- // thread has no reply routing yet, and the daemon refuses one anyway, so
- // the composer stays shut rather than accepting text that will bounce.
- void update_composer_sensitivity() {
- const bool can_send =
- g_messages.map_open && !g_messages.selected_thread.empty() && g_messages.selected_repliable;
- if (!g_messages.composer)
- return;
-
- gtk_widget_set_sensitive(g_messages.composer, can_send && !g_messages.sending);
- gtk_widget_set_sensitive(g_messages.send_button, can_send && !g_messages.sending);
-
- const char* reason = nullptr;
- if (g_messages.sending)
- reason = "Sending…";
- else if (!g_messages.map_open)
- reason = "Messages are not connected.";
- else if (g_messages.selected_thread.empty())
- reason = "Select a conversation first.";
- else if (!g_messages.selected_block_reason.empty())
- reason = g_messages.selected_block_reason.c_str();
- else if (!can_send)
- reason = "Replying to this conversation is not available.";
- gtk_widget_set_tooltip_text(g_messages.send_button, reason);
- }
-
- std::string composer_text() {
- GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(g_messages.composer));
- GtkTextIter start, end;
- gtk_text_buffer_get_bounds(buffer, &start, &end);
- gchar* text = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
- std::string out = text ? text : "";
- g_free(text);
- return out;
- }
-
- void on_send_clicked(GtkWidget*, gpointer) {
- const std::string body = composer_text();
- if (body.empty() || g_messages.selected_thread.empty())
- return;
-
- nlohmann::json j;
- j["command"] = "bt_send_message";
- j["thread"] = g_messages.selected_thread;
- j["body"] = body;
- daemon_send(j);
-
- // The composer stays locked until the phone answers. Sending is a
- // real OBEX transfer and takes a moment; an unlocked box invites a
- // second copy of the same message.
- g_messages.sending = true;
- update_composer_sensitivity();
- set_status_main("Sending…");
- }
-
- void on_send_result(const nlohmann::json& event) {
- g_messages.sending = false;
- update_composer_sensitivity();
-
- if (event.value("success", false)) {
- // Only cleared once the phone accepted it, so a failed send
- // leaves the text where the user can retry or copy it out.
- GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(g_messages.composer));
- gtk_text_buffer_set_text(buffer, "", -1);
- set_status_main("Sent");
- return;
- }
- set_status_main(event.value("message", "The message was not sent."));
- }
-
- void on_thread_selected(GtkListBox*, GtkListBoxRow* row, gpointer) {
- if (!row) {
- g_messages.selected_thread.clear();
- g_messages.selected_repliable = false;
- g_messages.selected_block_reason.clear();
- update_composer_sensitivity();
- return;
- }
- const char* thread = (const char*)g_object_get_data(G_OBJECT(row), "thread");
- const char* name = (const char*)g_object_get_data(G_OBJECT(row), "name");
- const char* block_reason = (const char*)g_object_get_data(G_OBJECT(row), "reply_reason");
- g_messages.selected_thread = thread ? thread : "";
- g_messages.selected_name = name ? name : "";
- g_messages.selected_repliable = g_object_get_data(G_OBJECT(row), "repliable") != nullptr;
- g_messages.selected_block_reason = block_reason ? block_reason : "";
- update_composer_sensitivity();
- gtk_stack_set_visible_child_name(GTK_STACK(g_messages.placeholder_stack), "conversation");
- request_messages(g_messages.selected_thread);
- }
-
- } // namespace
-
- void messages_view_set_visible(bool visible) {
- g_messages.visible = visible;
- if (visible)
- request_threads();
- }
-
- bool messages_view_handle_event(const nlohmann::json& event) {
- const std::string command = event.value("command", "");
- if (command == "bt_threads") {
- show_threads(event);
- return true;
- }
- if (command == "bt_messages") {
- show_messages(event);
- return true;
- }
- if (command == "bt_connection_changed") {
- update_connection(event);
- return true;
- }
- if (command == "bt_message") {
- // A new message changes both the thread list and, when it lands in
- // the open conversation, the conversation itself. Refreshing while
- // the view is hidden would just be traffic nobody sees; switching
- // back re-reads everything anyway.
- if (!g_messages.visible)
- return true;
- request_threads();
- if (event.value("thread", "") == g_messages.selected_thread)
- request_messages(g_messages.selected_thread);
- return true;
- }
- if (command == "bt_send_result") {
- on_send_result(event);
- return true;
- }
- if (command == "bt_message_read") {
- if (g_messages.visible)
- request_threads();
- return true;
- }
- return false;
- }
-
- GtkWidget* messages_view_new() {
- GtkWidget* root = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
-
- g_messages.banner = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);
- gtk_container_set_border_width(GTK_CONTAINER(g_messages.banner), 8);
- GtkWidget* banner_icon = gtk_image_new_from_icon_name("dialog-information-symbolic", GTK_ICON_SIZE_BUTTON);
- gtk_box_pack_start(GTK_BOX(g_messages.banner), banner_icon, FALSE, FALSE, 0);
- g_messages.banner_label = gtk_label_new(nullptr);
- gtk_label_set_xalign(GTK_LABEL(g_messages.banner_label), 0.0);
- gtk_label_set_line_wrap(GTK_LABEL(g_messages.banner_label), TRUE);
- gtk_box_pack_start(GTK_BOX(g_messages.banner), g_messages.banner_label, TRUE, TRUE, 0);
- gtk_box_pack_start(GTK_BOX(root), g_messages.banner, FALSE, FALSE, 0);
-
- GtkWidget* paned = gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
- gtk_box_pack_start(GTK_BOX(root), paned, TRUE, TRUE, 0);
-
- GtkWidget* thread_scroll = gtk_scrolled_window_new(nullptr, nullptr);
- gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(thread_scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
- gtk_widget_set_size_request(thread_scroll, 240, -1);
- g_messages.thread_list = gtk_list_box_new();
- g_signal_connect(g_messages.thread_list, "row-selected", G_CALLBACK(on_thread_selected), nullptr);
- gtk_container_add(GTK_CONTAINER(thread_scroll), g_messages.thread_list);
- gtk_paned_pack1(GTK_PANED(paned), thread_scroll, FALSE, FALSE);
-
- g_messages.placeholder_stack = gtk_stack_new();
-
- GtkWidget* placeholder = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
- gtk_widget_set_valign(placeholder, GTK_ALIGN_CENTER);
- gtk_widget_set_halign(placeholder, GTK_ALIGN_CENTER);
- GtkWidget* placeholder_icon = gtk_image_new_from_icon_name("mail-unread-symbolic", GTK_ICON_SIZE_DIALOG);
- gtk_box_pack_start(GTK_BOX(placeholder), placeholder_icon, FALSE, FALSE, 0);
- GtkWidget* placeholder_label = gtk_label_new("Select a conversation");
- gtk_style_context_add_class(gtk_widget_get_style_context(placeholder_label), "muted");
- gtk_box_pack_start(GTK_BOX(placeholder), placeholder_label, FALSE, FALSE, 0);
- gtk_stack_add_named(GTK_STACK(g_messages.placeholder_stack), placeholder, "placeholder");
-
- GtkWidget* conversation_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
-
- g_messages.conversation_scroll = gtk_scrolled_window_new(nullptr, nullptr);
- gtk_scrolled_window_set_policy(
- GTK_SCROLLED_WINDOW(g_messages.conversation_scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
- g_messages.conversation = gtk_list_box_new();
- gtk_list_box_set_selection_mode(GTK_LIST_BOX(g_messages.conversation), GTK_SELECTION_NONE);
- gtk_container_add(GTK_CONTAINER(g_messages.conversation_scroll), g_messages.conversation);
- gtk_box_pack_start(GTK_BOX(conversation_box), g_messages.conversation_scroll, TRUE, TRUE, 0);
-
- GtkWidget* composer_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);
- gtk_container_set_border_width(GTK_CONTAINER(composer_box), 8);
- g_messages.composer = gtk_text_view_new();
- gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(g_messages.composer), GTK_WRAP_WORD_CHAR);
- gtk_widget_set_size_request(g_messages.composer, -1, 48);
- GtkWidget* composer_frame = gtk_scrolled_window_new(nullptr, nullptr);
- gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(composer_frame), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
- gtk_container_add(GTK_CONTAINER(composer_frame), g_messages.composer);
- gtk_box_pack_start(GTK_BOX(composer_box), composer_frame, TRUE, TRUE, 0);
-
- g_messages.send_button = gtk_button_new_with_label("Send");
- gtk_widget_set_valign(g_messages.send_button, GTK_ALIGN_END);
- gtk_box_pack_start(GTK_BOX(composer_box), g_messages.send_button, FALSE, FALSE, 0);
-
- g_signal_connect(g_messages.send_button, "clicked", G_CALLBACK(on_send_clicked), nullptr);
- // Enabled only once MAP is up and a conversation is open.
- update_composer_sensitivity();
-
- gtk_box_pack_start(GTK_BOX(conversation_box), composer_box, FALSE, FALSE, 0);
- gtk_stack_add_named(GTK_STACK(g_messages.placeholder_stack), conversation_box, "conversation");
-
- gtk_paned_pack2(GTK_PANED(paned), g_messages.placeholder_stack, TRUE, FALSE);
- gtk_stack_set_visible_child_name(GTK_STACK(g_messages.placeholder_stack), "placeholder");
-
- gtk_widget_set_no_show_all(g_messages.banner, TRUE);
- return root;
- }
-
-} // namespace tether::ui
diff --git a/src/gtk/messages_view.hpp b/src/gtk/messages_view.hpp
deleted file mode 100644
index 40b3563..0000000
--- a/src/gtk/messages_view.hpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#pragma once
-
-#include <gtk/gtk.h>
-#include <nlohmann/json.hpp>
-
-namespace tether::ui {
-
- // Conversations from the iPhone over MAP: a thread list beside the selected
- // conversation, with a composer that stays disabled until sending exists.
- GtkWidget* messages_view_new();
-
- // Returns true when the event belonged to this view.
- bool messages_view_handle_event(const nlohmann::json& event);
-
- // Threads are only pulled while someone is looking at them, so the view has
- // to be told when it comes and goes.
- void messages_view_set_visible(bool visible);
-
-} // namespace tether::ui
diff --git a/src/gtk/notifications_view.cpp b/src/gtk/notifications_view.cpp
deleted file mode 100644
index d2344e6..0000000
--- a/src/gtk/notifications_view.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-#include "notifications_view.hpp"
-#include "daemon_client.hpp"
-#include "ui_util.hpp"
-
-#include <ctime>
-#include <string>
-
-namespace tether::ui {
-
- namespace {
-
- struct NotificationsState {
- GtkWidget* status_label = nullptr;
- GtkWidget* list = nullptr;
- GtkWidget* stack = nullptr;
- bool visible = false;
- bool ready = false;
- };
-
- NotificationsState g_notifications;
-
- std::string format_timestamp(int64_t epoch) {
- if (epoch <= 0)
- return "";
- std::time_t t = static_cast<std::time_t>(epoch);
- std::tm tm{};
- localtime_r(&t, &tm);
- char buffer[32];
- std::strftime(buffer, sizeof(buffer), "%H:%M", &tm);
- return buffer;
- }
-
- void request_notifications() {
- nlohmann::json j;
- j["command"] = "bt_list_notifications";
- daemon_send(j);
- }
-
- GtkWidget* build_row(const nlohmann::json& notification) {
- const std::string app = notification.value("app_name", notification.value("app_id", ""));
- const std::string title = notification.value("title", "");
- const std::string body = notification.value("body", "");
- const std::string stamp = format_timestamp(notification.value("timestamp", static_cast<int64_t>(0)));
-
- GtkWidget* row = gtk_list_box_row_new();
- gtk_list_box_row_set_selectable(GTK_LIST_BOX_ROW(row), FALSE);
-
- GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
- gtk_container_set_border_width(GTK_CONTAINER(box), 10);
-
- GtkWidget* header = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);
- GtkWidget* app_label = gtk_label_new(nullptr);
- gtk_label_set_markup(GTK_LABEL(app_label), ("<b>" + escape_markup(app) + "</b>").c_str());
- gtk_label_set_xalign(GTK_LABEL(app_label), 0.0);
- gtk_box_pack_start(GTK_BOX(header), app_label, TRUE, TRUE, 0);
-
- if (!stamp.empty()) {
- GtkWidget* time_label = gtk_label_new(stamp.c_str());
- gtk_style_context_add_class(gtk_widget_get_style_context(time_label), "muted");
- gtk_box_pack_start(GTK_BOX(header), time_label, FALSE, FALSE, 0);
- }
- gtk_box_pack_start(GTK_BOX(box), header, FALSE, FALSE, 0);
-
- // With content mirroring off, only the app is known — which is the
- // point of that default, so the row says so rather than looking broken.
- const std::string detail = !title.empty() ? title : (!body.empty() ? body : "New notification");
- GtkWidget* detail_label = gtk_label_new(detail.c_str());
- gtk_label_set_xalign(GTK_LABEL(detail_label), 0.0);
- gtk_label_set_line_wrap(GTK_LABEL(detail_label), TRUE);
- gtk_box_pack_start(GTK_BOX(box), detail_label, FALSE, FALSE, 0);
-
- if (!title.empty() && !body.empty()) {
- GtkWidget* body_label = gtk_label_new(body.c_str());
- gtk_label_set_xalign(GTK_LABEL(body_label), 0.0);
- gtk_label_set_line_wrap(GTK_LABEL(body_label), TRUE);
- gtk_style_context_add_class(gtk_widget_get_style_context(body_label), "muted");
- gtk_box_pack_start(GTK_BOX(box), body_label, FALSE, FALSE, 0);
- }
-
- gtk_container_add(GTK_CONTAINER(row), box);
- return row;
- }
-
- void show_notifications(const nlohmann::json& event) {
- clear_list_box(g_notifications.list);
- const bool empty = !event.contains("notifications") || event["notifications"].empty();
- if (!empty) {
- for (const auto& notification : event["notifications"])
- gtk_list_box_insert(GTK_LIST_BOX(g_notifications.list), build_row(notification), -1);
- }
- gtk_widget_show_all(g_notifications.list);
- gtk_stack_set_visible_child_name(GTK_STACK(g_notifications.stack), empty ? "status" : "list");
- }
-
- } // namespace
-
- void notifications_view_set_visible(bool visible) {
- g_notifications.visible = visible;
- if (visible)
- request_notifications();
- }
-
- bool notifications_view_handle_event(const nlohmann::json& event) {
- const std::string command = event.value("command", "");
-
- if (command == "bt_notifications") {
- show_notifications(event);
- return true;
- }
- if (command == "bt_notification" || command == "bt_notification_removed") {
- if (g_notifications.visible)
- request_notifications();
- return true;
- }
- if (command == "bt_connection_changed") {
- g_notifications.ready = event.value("ancs_ready", false);
- // The daemon's reason names the actual next step, including the
- // toggle to enable on the phone, so it is shown verbatim.
- const std::string reason = event.value("ancs_reason", "");
- set_text(g_notifications.status_label,
- g_notifications.ready ? "No notifications yet."
- : (reason.empty() ? "Notification mirroring is unavailable." : reason));
- return false;
- }
- return false;
- }
-
- GtkWidget* notifications_view_new() {
- g_notifications.stack = gtk_stack_new();
-
- GtkWidget* status_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
- gtk_widget_set_valign(status_box, GTK_ALIGN_CENTER);
- gtk_widget_set_halign(status_box, GTK_ALIGN_CENTER);
- GtkWidget* icon =
- gtk_image_new_from_icon_name("preferences-system-notifications-symbolic", GTK_ICON_SIZE_DIALOG);
- gtk_box_pack_start(GTK_BOX(status_box), icon, FALSE, FALSE, 0);
- g_notifications.status_label = gtk_label_new("Waiting for the iPhone.");
- gtk_label_set_line_wrap(GTK_LABEL(g_notifications.status_label), TRUE);
- gtk_label_set_justify(GTK_LABEL(g_notifications.status_label), GTK_JUSTIFY_CENTER);
- gtk_style_context_add_class(gtk_widget_get_style_context(g_notifications.status_label), "muted");
- gtk_box_pack_start(GTK_BOX(status_box), g_notifications.status_label, FALSE, FALSE, 0);
- gtk_stack_add_named(GTK_STACK(g_notifications.stack), status_box, "status");
-
- GtkWidget* scroll = gtk_scrolled_window_new(nullptr, nullptr);
- gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
- g_notifications.list = gtk_list_box_new();
- gtk_list_box_set_selection_mode(GTK_LIST_BOX(g_notifications.list), GTK_SELECTION_NONE);
- gtk_container_add(GTK_CONTAINER(scroll), g_notifications.list);
- gtk_stack_add_named(GTK_STACK(g_notifications.stack), scroll, "list");
-
- gtk_stack_set_visible_child_name(GTK_STACK(g_notifications.stack), "status");
- return g_notifications.stack;
- }
-
-} // namespace tether::ui
diff --git a/src/gtk/notifications_view.hpp b/src/gtk/notifications_view.hpp
deleted file mode 100644
index 4275b64..0000000
--- a/src/gtk/notifications_view.hpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#pragma once
-
-#include <gtk/gtk.h>
-#include <nlohmann/json.hpp>
-
-namespace tether::ui {
-
- // Mirrored iPhone notifications, delivered over ANCS.
- GtkWidget* notifications_view_new();
-
- bool notifications_view_handle_event(const nlohmann::json& event);
-
- // Notifications are only re-read while the view is on screen.
- void notifications_view_set_visible(bool visible);
-
-} // namespace tether::ui
diff --git a/src/gtk/ui_util.cpp b/src/gtk/ui_util.cpp
deleted file mode 100644
index 7dffe2a..0000000
--- a/src/gtk/ui_util.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-#include "ui_util.hpp"
-
-namespace tether::ui {
-
- namespace {
- GtkWidget* g_window = nullptr;
- GtkWidget* g_header_bar = nullptr;
- } // namespace
-
- std::string escape_markup(const std::string& text) {
- gchar* escaped = g_markup_escape_text(text.c_str(), -1);
- std::string result = escaped ? escaped : "";
- g_free(escaped);
- return result;
- }
-
- void set_markup(GtkWidget* label, const std::string& text) {
- if (label) {
- gtk_label_set_markup(GTK_LABEL(label), text.c_str());
- }
- }
-
- void set_text(GtkWidget* label, const std::string& text) {
- if (label) {
- gtk_label_set_text(GTK_LABEL(label), text.c_str());
- }
- }
-
- void clear_list_box(GtkWidget* list_box) {
- GList* children = gtk_container_get_children(GTK_CONTAINER(list_box));
- for (GList* iter = children; iter; iter = g_list_next(iter)) {
- gtk_widget_destroy(GTK_WIDGET(iter->data));
- }
- g_list_free(children);
- }
-
- void set_main_window(GtkWidget* window) { g_window = window; }
-
- GtkWidget* main_window() { return g_window; }
-
- void set_header_bar(GtkWidget* bar) { g_header_bar = bar; }
-
- void set_status_main(const std::string& text) {
- if (g_header_bar) {
- gtk_header_bar_set_subtitle(GTK_HEADER_BAR(g_header_bar), text.c_str());
- }
- }
-
-} // namespace tether::ui
diff --git a/src/gtk/ui_util.hpp b/src/gtk/ui_util.hpp
deleted file mode 100644
index a298715..0000000
--- a/src/gtk/ui_util.hpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#pragma once
-
-#include <gtk/gtk.h>
-#include <string>
-
-namespace tether::ui {
-
- std::string escape_markup(const std::string& text);
- void set_markup(GtkWidget* label, const std::string& text);
- void set_text(GtkWidget* label, const std::string& text);
- void clear_list_box(GtkWidget* list_box);
-
- // Registered once at startup so views can reach the window and the header
- // bar without every one of them holding the whole application struct.
- void set_main_window(GtkWidget* window);
- GtkWidget* main_window();
- void set_header_bar(GtkWidget* bar);
- void set_status_main(const std::string& text);
-
-} // namespace tether::ui
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 75ca1ac..72f34d2 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -1,16 +1,5 @@
add_executable(tether_test
test_base64.cpp
- test_bluetooth_objects.cpp
- test_bluetooth_pairing.cpp
- test_bluetooth_supervisor.cpp
- test_bmessage.cpp
- test_bmessage_build.cpp
- test_ancs_parser.cpp
- test_ancs_sequencer.cpp
- test_groups.cpp
- test_bt_diagnostics.cpp
- test_vcard.cpp
- test_journal.cpp
test_crypto.cpp
test_discovery.cpp
test_file_transfer.cpp
diff --git a/test/test_ancs_parser.cpp b/test/test_ancs_parser.cpp
deleted file mode 100644
index 8069b6c..0000000
--- a/test/test_ancs_parser.cpp
+++ /dev/null
@@ -1,260 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/ancs/parser.hpp>
-
-using namespace tether::bluetooth::ancs;
-
-namespace {
-
- std::vector<uint8_t> source_packet(uint8_t event, uint8_t flags, uint8_t category, uint8_t count, uint32_t uid) {
- return {event,
- flags,
- category,
- count,
- static_cast<uint8_t>(uid & 0xff),
- static_cast<uint8_t>((uid >> 8) & 0xff),
- static_cast<uint8_t>((uid >> 16) & 0xff),
- static_cast<uint8_t>((uid >> 24) & 0xff)};
- }
-
- void append_attribute(std::vector<uint8_t>& out, uint8_t id, const std::string& value) {
- out.push_back(id);
- out.push_back(static_cast<uint8_t>(value.size() & 0xff));
- out.push_back(static_cast<uint8_t>((value.size() >> 8) & 0xff));
- out.insert(out.end(), value.begin(), value.end());
- }
-
- std::vector<uint8_t> notification_response(uint32_t uid) {
- std::vector<uint8_t> out{0x00,
- static_cast<uint8_t>(uid & 0xff),
- static_cast<uint8_t>((uid >> 8) & 0xff),
- static_cast<uint8_t>((uid >> 16) & 0xff),
- static_cast<uint8_t>((uid >> 24) & 0xff)};
- append_attribute(out, 0, "com.example.app");
- append_attribute(out, 1, "Title here");
- return out;
- }
-
- DataSourceAssembler::Result feed(DataSourceAssembler& assembler,
- const std::vector<uint8_t>& bytes,
- Response& out,
- std::string& err) {
- return assembler.append(bytes.data(), bytes.size(), out, err);
- }
-
-} // namespace
-
-// --- Notification Source -------------------------------------------------
-
-TEST(AncsParser, ParsesASourceEvent) {
- SourceEvent event;
- auto packet = source_packet(0, FlagImportant | FlagPositiveAction, 4, 2, 0xDEADBEEF);
-
- ASSERT_TRUE(parse_source_event(packet.data(), packet.size(), event));
- EXPECT_EQ(event.event, EventId::Added);
- EXPECT_EQ(event.category, CategoryId::Social);
- EXPECT_EQ(event.category_count, 2);
- EXPECT_EQ(event.uid, 0xDEADBEEFu);
- EXPECT_TRUE(event.has_positive_action());
- EXPECT_FALSE(event.pre_existing());
-}
-
-// A truncated packet would leave fields to be invented, and the UID is what
-// every later request is keyed on — so anything but eight bytes is refused.
-TEST(AncsParser, RejectsSourcePacketsOfTheWrongLength) {
- SourceEvent event;
- auto packet = source_packet(0, 0, 0, 0, 1);
-
- EXPECT_FALSE(parse_source_event(packet.data(), 7, event));
- EXPECT_FALSE(parse_source_event(packet.data(), 9, event));
- EXPECT_FALSE(parse_source_event(packet.data(), 0, event));
- EXPECT_FALSE(parse_source_event(nullptr, 8, event));
-}
-
-TEST(AncsParser, RejectsUnknownEventIds) {
- SourceEvent event;
- auto packet = source_packet(9, 0, 0, 0, 1);
- EXPECT_FALSE(parse_source_event(packet.data(), packet.size(), event));
-}
-
-// --- Data Source reassembly ----------------------------------------------
-
-TEST(AncsParser, ReassemblesACompleteResponse) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- Response response;
- std::string err;
- ASSERT_EQ(feed(assembler, notification_response(42), response, err), DataSourceAssembler::Result::Complete) << err;
- EXPECT_EQ(response.uid, 42u);
- EXPECT_EQ(response.attribute(0), "com.example.app");
- EXPECT_EQ(response.attribute(1), "Title here");
- EXPECT_FALSE(assembler.expecting());
-}
-
-// Responses have no total length and arrive split across GATT notifications, so
-// completion can only be recognized from the requested attribute sequence.
-TEST(AncsParser, ReassemblesAcrossArbitraryFragmentBoundaries) {
- const auto full = notification_response(7);
-
- for (size_t split = 1; split < full.size(); ++split) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- Response response;
- std::string err;
- std::vector<uint8_t> first(full.begin(), full.begin() + static_cast<long>(split));
- std::vector<uint8_t> second(full.begin() + static_cast<long>(split), full.end());
-
- ASSERT_EQ(feed(assembler, first, response, err), DataSourceAssembler::Result::NeedMore)
- << "split at " << split << ": " << err;
- ASSERT_EQ(feed(assembler, second, response, err), DataSourceAssembler::Result::Complete)
- << "split at " << split << ": " << err;
- EXPECT_EQ(response.attribute(1), "Title here");
- }
-}
-
-TEST(AncsParser, ReassemblesOneByteAtATime) {
- const auto full = notification_response(9);
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- Response response;
- std::string err;
- for (size_t i = 0; i + 1 < full.size(); ++i)
- ASSERT_EQ(assembler.append(&full[i], 1, response, err), DataSourceAssembler::Result::NeedMore) << i;
- EXPECT_EQ(assembler.append(&full.back(), 1, response, err), DataSourceAssembler::Result::Complete) << err;
-}
-
-TEST(AncsParser, ParsesAppAttributeResponses) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetAppAttributes, {0});
-
- std::vector<uint8_t> bytes{0x01};
- const std::string app = "com.apple.MobileSMS";
- bytes.insert(bytes.end(), app.begin(), app.end());
- bytes.push_back(0);
- append_attribute(bytes, 0, "Messages");
-
- Response response;
- std::string err;
- ASSERT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Complete) << err;
- EXPECT_EQ(response.app_id, "com.apple.MobileSMS");
- EXPECT_EQ(response.attribute(0), "Messages");
-}
-
-TEST(AncsParser, WaitsForAnUnterminatedAppIdentifier) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetAppAttributes, {0});
-
- std::vector<uint8_t> bytes{0x01, 'c', 'o', 'm'};
- Response response;
- std::string err;
- EXPECT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::NeedMore);
-}
-
-// --- Hostile input -------------------------------------------------------
-
-TEST(AncsParser, RejectsAResponseThatDoesNotEchoTheCommand) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0});
-
- std::vector<uint8_t> bytes{0x07, 0, 0, 0, 0};
- Response response;
- std::string err;
- EXPECT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Error);
- EXPECT_FALSE(err.empty());
-}
-
-TEST(AncsParser, RejectsAttributesReturnedOutOfOrder) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- std::vector<uint8_t> bytes{0x00, 1, 0, 0, 0};
- append_attribute(bytes, 3, "wrong attribute");
-
- Response response;
- std::string err;
- EXPECT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Error);
-}
-
-// A length field is two bytes and can claim far more than we ever ask for.
-// Believing it would let a peer make us buffer for as long as it likes.
-TEST(AncsParser, RejectsAnImplausibleAttributeLength) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0});
-
- std::vector<uint8_t> bytes{0x00, 1, 0, 0, 0, 0, 0xff, 0xff};
- Response response;
- std::string err;
- EXPECT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Error);
-}
-
-TEST(AncsParser, RejectsTrailingBytesAfterACompleteResponse) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- auto bytes = notification_response(3);
- bytes.push_back(0xAA);
- bytes.push_back(0xBB);
-
- Response response;
- std::string err;
- EXPECT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Error);
-}
-
-TEST(AncsParser, RejectsAResponseThatGrowsWithoutEnding) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1, 2, 3});
-
- Response response;
- std::string err;
- std::vector<uint8_t> flood(1024, 0);
- flood[0] = 0x00;
-
- DataSourceAssembler::Result result = DataSourceAssembler::Result::NeedMore;
- for (int i = 0; i < 16 && result == DataSourceAssembler::Result::NeedMore; ++i)
- result = feed(assembler, flood, response, err);
-
- EXPECT_EQ(result, DataSourceAssembler::Result::Error) << "an endless response must be cut off";
-}
-
-TEST(AncsParser, RefusesFragmentsWithNoRequestInFlight) {
- DataSourceAssembler assembler;
- Response response;
- std::string err;
-
- auto bytes = notification_response(1);
- EXPECT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Error);
-}
-
-// A rejected response must not leave half-parsed state behind for the next one
-// to inherit.
-TEST(AncsParser, RecoversAfterAnError) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- Response response;
- std::string err;
- std::vector<uint8_t> garbage{0x09, 0x09};
- ASSERT_EQ(feed(assembler, garbage, response, err), DataSourceAssembler::Result::Error);
- EXPECT_FALSE(assembler.expecting());
-
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
- EXPECT_EQ(feed(assembler, notification_response(5), response, err), DataSourceAssembler::Result::Complete) << err;
- EXPECT_EQ(response.uid, 5u);
-}
-
-TEST(AncsParser, HandlesEmptyAttributeValues) {
- DataSourceAssembler assembler;
- assembler.expect(CommandId::GetNotificationAttributes, {0, 1});
-
- std::vector<uint8_t> bytes{0x00, 4, 0, 0, 0};
- append_attribute(bytes, 0, "com.example.app");
- append_attribute(bytes, 1, "");
-
- Response response;
- std::string err;
- ASSERT_EQ(feed(assembler, bytes, response, err), DataSourceAssembler::Result::Complete) << err;
- EXPECT_EQ(response.attribute(1), "") << "an absent attribute is still a tuple";
- EXPECT_EQ(response.attributes.size(), 2u);
-}
diff --git a/test/test_ancs_sequencer.cpp b/test/test_ancs_sequencer.cpp
deleted file mode 100644
index 741dd03..0000000
--- a/test/test_ancs_sequencer.cpp
+++ /dev/null
@@ -1,305 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/ancs/notifications.hpp>
-#include <tether/bluetooth/ancs/sequencer.hpp>
-
-using namespace tether::bluetooth::ancs;
-
-namespace {
-
- struct Harness {
- std::vector<std::vector<uint8_t>> writes;
- std::vector<std::pair<Request, Response>> completions;
- std::vector<std::pair<Request, std::string>> failures;
- bool write_succeeds = true;
-
- ControlPointSequencer make() {
- return ControlPointSequencer([this](const std::vector<uint8_t>& payload) {
- writes.push_back(payload);
- return write_succeeds;
- },
- [this](const Request& request, const Response& response) {
- completions.emplace_back(request, response);
- },
- [this](const Request& request, const std::string& reason) {
- failures.emplace_back(request, reason);
- });
- }
- };
-
- std::vector<uint8_t> notification_response(uint32_t uid, const std::string& app) {
- std::vector<uint8_t> out{0x00,
- static_cast<uint8_t>(uid & 0xff),
- static_cast<uint8_t>((uid >> 8) & 0xff),
- static_cast<uint8_t>((uid >> 16) & 0xff),
- static_cast<uint8_t>((uid >> 24) & 0xff)};
- out.push_back(0);
- out.push_back(static_cast<uint8_t>(app.size() & 0xff));
- out.push_back(static_cast<uint8_t>((app.size() >> 8) & 0xff));
- out.insert(out.end(), app.begin(), app.end());
- return out;
- }
-
- SourceEvent event_for(uint32_t uid, EventId event = EventId::Added, uint8_t flags = 0) {
- SourceEvent e;
- e.uid = uid;
- e.event = event;
- e.flags = flags;
- return e;
- }
-
-} // namespace
-
-// --- Request encoding ----------------------------------------------------
-
-TEST(AncsSequencer, EncodesANotificationRequest) {
- Request request = build_notification_request(0x01020304, {NotificationAttributeId::AppIdentifier,
- NotificationAttributeId::Message});
-
- ASSERT_GE(request.payload.size(), 8u);
- EXPECT_EQ(request.payload[0], 0x00);
- EXPECT_EQ(request.payload[1], 0x04) << "the UID is little-endian";
- EXPECT_EQ(request.payload[4], 0x01);
- EXPECT_EQ(request.payload[5], 0x00) << "AppIdentifier takes no length";
- EXPECT_EQ(request.payload[6], 0x03) << "Message follows immediately";
- // Message is length-capped, and the cap is what Phase 9 correlates against.
- EXPECT_EQ(request.payload[7] | (request.payload[8] << 8), MAX_BODY_LENGTH);
- EXPECT_EQ(request.attribute_ids, (std::vector<uint8_t>{0, 3}));
-}
-
-TEST(AncsSequencer, EncodesAnAppRequest) {
- Request request = build_app_request("com.apple.MobileSMS");
-
- EXPECT_EQ(request.payload[0], 0x01);
- EXPECT_EQ(request.payload[request.payload.size() - 2], 0x00) << "the identifier is NUL-terminated";
- EXPECT_EQ(request.payload.back(), 0x00) << "DisplayName is the requested attribute";
-}
-
-TEST(AncsSequencer, EncodesAnActionRequest) {
- Request request = build_action_request(0x11223344, ActionId::Negative);
-
- EXPECT_EQ(request.payload[0], 0x02);
- EXPECT_EQ(request.payload.back(), 0x01);
- EXPECT_TRUE(request.attribute_ids.empty()) << "an action expects no response";
-}
-
-// --- Serialization -------------------------------------------------------
-
-// Responses carry no request identifier, so two in flight cannot be told apart
-// and one notification's attributes would be attached to another.
-TEST(AncsSequencer, KeepsExactlyOneRequestInFlight) {
- Harness harness;
- auto sequencer = harness.make();
-
- sequencer.submit(build_notification_request(1, {NotificationAttributeId::AppIdentifier}));
- sequencer.submit(build_notification_request(2, {NotificationAttributeId::AppIdentifier}));
- sequencer.submit(build_notification_request(3, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
-
- EXPECT_EQ(harness.writes.size(), 1u);
- EXPECT_EQ(sequencer.queued(), 2u);
- EXPECT_TRUE(sequencer.in_flight());
-
- auto bytes = notification_response(1, "com.example.one");
- sequencer.on_data_source(bytes.data(), bytes.size(), 1);
-
- EXPECT_EQ(harness.completions.size(), 1u);
- EXPECT_EQ(harness.completions[0].first.uid, 1u);
- EXPECT_EQ(harness.writes.size(), 2u) << "the next request starts as soon as the first completes";
-}
-
-TEST(AncsSequencer, MatchesEachResponseToItsOwnRequest) {
- Harness harness;
- auto sequencer = harness.make();
-
- sequencer.submit(build_notification_request(11, {NotificationAttributeId::AppIdentifier}));
- sequencer.submit(build_notification_request(22, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
-
- auto first = notification_response(11, "com.example.first");
- sequencer.on_data_source(first.data(), first.size(), 1);
- auto second = notification_response(22, "com.example.second");
- sequencer.on_data_source(second.data(), second.size(), 2);
-
- ASSERT_EQ(harness.completions.size(), 2u);
- EXPECT_EQ(harness.completions[0].first.uid, 11u);
- EXPECT_EQ(harness.completions[0].second.attribute(0), "com.example.first");
- EXPECT_EQ(harness.completions[1].first.uid, 22u);
- EXPECT_EQ(harness.completions[1].second.attribute(0), "com.example.second");
-}
-
-// An action gets no Data Source response at all, so waiting for one would stall
-// every queued request behind it for the full timeout.
-TEST(AncsSequencer, DoesNotWaitForAResponseToAnAction) {
- Harness harness;
- auto sequencer = harness.make();
-
- sequencer.submit(build_action_request(5, ActionId::Positive));
- sequencer.submit(build_notification_request(6, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
-
- EXPECT_EQ(harness.writes.size(), 2u);
- EXPECT_EQ(harness.completions.size(), 1u);
- EXPECT_TRUE(sequencer.in_flight()) << "the notification request is the one now waiting";
-}
-
-TEST(AncsSequencer, TimesOutARequestThatIsNeverAnswered) {
- Harness harness;
- auto sequencer = harness.make();
-
- sequencer.submit(build_notification_request(1, {NotificationAttributeId::AppIdentifier}));
- sequencer.submit(build_notification_request(2, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
- ASSERT_EQ(harness.writes.size(), 1u);
-
- sequencer.tick(REQUEST_TIMEOUT_SECONDS - 1);
- EXPECT_TRUE(harness.failures.empty()) << "not yet due";
-
- sequencer.tick(REQUEST_TIMEOUT_SECONDS);
- ASSERT_EQ(harness.failures.size(), 1u);
- EXPECT_EQ(harness.failures[0].first.uid, 1u);
- EXPECT_EQ(harness.writes.size(), 2u) << "the queue must not stay wedged behind a lost response";
-}
-
-TEST(AncsSequencer, FailsARequestWhoseWriteIsRefused) {
- Harness harness;
- harness.write_succeeds = false;
- auto sequencer = harness.make();
-
- sequencer.submit(build_notification_request(1, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
-
- EXPECT_EQ(harness.failures.size(), 1u);
- EXPECT_FALSE(sequencer.in_flight());
-}
-
-TEST(AncsSequencer, FailsTheRequestWhenItsResponseIsMalformed) {
- Harness harness;
- auto sequencer = harness.make();
-
- sequencer.submit(build_notification_request(1, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
-
- std::vector<uint8_t> garbage{0x09, 0x09, 0x09};
- sequencer.on_data_source(garbage.data(), garbage.size(), 1);
-
- EXPECT_EQ(harness.failures.size(), 1u);
- EXPECT_TRUE(harness.completions.empty());
-}
-
-TEST(AncsSequencer, DropsEverythingOnReset) {
- Harness harness;
- auto sequencer = harness.make();
-
- sequencer.submit(build_notification_request(1, {NotificationAttributeId::AppIdentifier}));
- sequencer.submit(build_notification_request(2, {NotificationAttributeId::AppIdentifier}));
- sequencer.tick(0);
- sequencer.reset();
-
- EXPECT_FALSE(sequencer.in_flight());
- EXPECT_EQ(sequencer.queued(), 0u);
-
- // A response from the dead session must not be applied to anything.
- auto bytes = notification_response(1, "com.example.one");
- sequencer.on_data_source(bytes.data(), bytes.size(), 1);
- EXPECT_TRUE(harness.completions.empty());
-}
-
-TEST(AncsSequencer, BoundsTheQueue) {
- Harness harness;
- auto sequencer = harness.make();
-
- size_t accepted = 0;
- for (size_t i = 0; i < MAX_QUEUED_REQUESTS + 10; ++i) {
- if (sequencer.submit(build_notification_request(static_cast<uint32_t>(i),
- {NotificationAttributeId::AppIdentifier})))
- ++accepted;
- }
- EXPECT_EQ(accepted, MAX_QUEUED_REQUESTS) << "a notification burst must not grow the daemon without bound";
-}
-
-// --- Delivery rules ------------------------------------------------------
-
-// iOS replays its whole backlog whenever the subscription comes up. Delivering
-// it would turn every reconnect into a burst of desktop popups.
-TEST(AncsNotifications, SkipsPreExistingOnFirstSubscribe) {
- NotificationRegistry registry;
- auto pre_existing = event_for(1, EventId::Added, FlagPreExisting);
-
- EXPECT_EQ(registry.classify(pre_existing, true), Decision::Ignore);
- EXPECT_EQ(registry.classify(pre_existing, false), Decision::Fetch)
- << "after the initial sync a pre-existing flag is not a reason to hide it";
-}
-
-TEST(AncsNotifications, DedupesRepeatedAddedEvents) {
- NotificationRegistry registry;
- auto added = event_for(7);
-
- EXPECT_EQ(registry.classify(added, false), Decision::Fetch);
- registry.remember(added);
- EXPECT_EQ(registry.classify(added, false), Decision::Ignore) << "a replay of the same UID is not news";
-}
-
-// A modification is a genuine update — a call that became a missed call, a
-// message that was edited — so dedupe must not swallow it.
-TEST(AncsNotifications, NeverSuppressesAModification) {
- NotificationRegistry registry;
- auto added = event_for(7);
- registry.remember(added);
-
- EXPECT_EQ(registry.classify(event_for(7, EventId::Modified), false), Decision::Fetch);
-}
-
-TEST(AncsNotifications, WithdrawsRemovedNotifications) {
- NotificationRegistry registry;
- auto added = event_for(7);
- registry.remember(added);
-
- EXPECT_EQ(registry.classify(event_for(7, EventId::Removed), false), Decision::Withdraw);
-
- registry.forget(7);
- EXPECT_EQ(registry.classify(added, false), Decision::Fetch) << "the UID is free to be seen again";
-}
-
-// MAP already delivers these with read state that stays in sync, so an ANCS
-// popup would be the second copy of the same message.
-TEST(AncsNotifications, SuppressesDesktopPopupsForMessages) {
- Notification messages;
- messages.app_id = "com.apple.MobileSMS";
- EXPECT_FALSE(should_show_desktop_popup(messages));
-
- Notification other;
- other.app_id = "com.example.chat";
- EXPECT_TRUE(should_show_desktop_popup(other));
-
- Notification silent;
- silent.app_id = "com.example.chat";
- silent.silent = true;
- EXPECT_FALSE(should_show_desktop_popup(silent)) << "the phone was told to stay quiet about this one";
-}
-
-TEST(AncsNotifications, KeepsRecentNotificationsNewestFirst) {
- NotificationRegistry registry;
- for (uint32_t i = 1; i <= 3; ++i) {
- Notification n;
- n.uid = i;
- n.app_id = "com.example.app";
- registry.store(n);
- }
-
- auto recent = registry.recent();
- ASSERT_EQ(recent.size(), 3u);
- EXPECT_EQ(recent[0].uid, 3u);
- EXPECT_EQ(recent[2].uid, 1u);
-}
-
-TEST(AncsNotifications, ClearingForgetsEverything) {
- NotificationRegistry registry;
- Notification n;
- n.uid = 1;
- registry.store(n);
- registry.remember(event_for(1));
-
- registry.clear();
- EXPECT_EQ(registry.size(), 0u);
- EXPECT_EQ(registry.classify(event_for(1), false), Decision::Fetch);
-}
diff --git a/test/test_bluetooth_objects.cpp b/test/test_bluetooth_objects.cpp
deleted file mode 100644
index ef6fe40..0000000
--- a/test/test_bluetooth_objects.cpp
+++ /dev/null
@@ -1,304 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/objects.hpp>
-
-using namespace tether::bluetooth;
-
-namespace {
-
- // Builds an ObjectManager payload from GVariant text format, the same shape
- // BlueZ returns from GetManagedObjects. Keeps the tests free of a real bus.
- struct Payload {
- GVariant* v = nullptr;
-
- explicit Payload(const char* text) {
- GError* error = nullptr;
- v = g_variant_parse(G_VARIANT_TYPE("a{oa{sa{sv}}}"), text, nullptr, nullptr, &error);
- if (!v) {
- ADD_FAILURE() << "bad fixture: " << (error ? error->message : "unknown");
- g_clear_error(&error);
- }
- }
- ~Payload() {
- if (v)
- g_variant_unref(v);
- }
- Payload(const Payload&) = delete;
- Payload& operator=(const Payload&) = delete;
- };
-
- // A capable adapter: powered, both LE roles, advertising, A/V Hands-Free class.
- constexpr const char* ADAPTER_FULL = R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': {
- 'Address': <'AC:F2:3C:AF:52:9C'>,
- 'Alias': <'btw'>,
- 'Class': <uint32 8127496>,
- 'Powered': <true>,
- 'Roles': <['central', 'peripheral']>
- },
- 'org.bluez.LEAdvertisingManager1': {
- 'SupportedInstances': <byte 15>
- }
- }
- })";
-
- // An iPhone bonded on both transports, exposing MAP, PBAP and ANCS.
- constexpr const char* IPHONE_BONDED = R"({
- '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {
- 'org.bluez.Device1': {
- 'Address': <'60:57:C8:30:6A:F7'>,
- 'Alias': <'Zack 15 Pro'>,
- 'Adapter': <objectpath '/org/bluez/hci0'>,
- 'Paired': <true>,
- 'Bonded': <true>,
- 'Trusted': <true>,
- 'Connected': <true>,
- 'UUIDs': <['00001132-0000-1000-8000-00805f9b34fb',
- '00001133-0000-1000-8000-00805f9b34fb',
- '0000112f-0000-1000-8000-00805f9b34fb',
- '7905f431-b5ce-4e99-a40f-4b1e122d00d0']>
- },
- 'org.bluez.Bearer.LE1': {
- 'Paired': <true>, 'Bonded': <true>, 'Connected': <true>
- }
- }
- })";
-
- std::string join(const char* a, const char* b) {
- std::string left(a), right(b);
- // Splice two single-entry dictionaries into one.
- left.erase(left.find_last_of('}'));
- right = right.substr(right.find('{') + 1);
- return left + "," + right;
- }
-
-} // namespace
-
-TEST(BluetoothObjects, ParsesAdapterProperties) {
- Payload p(ADAPTER_FULL);
- auto objects = parse_managed_objects(p.v);
-
- ASSERT_EQ(objects.adapters.size(), 1u);
- const auto& a = objects.adapters[0];
- EXPECT_EQ(a.path, "/org/bluez/hci0");
- EXPECT_EQ(a.address, "AC:F2:3C:AF:52:9C");
- EXPECT_EQ(a.name, "btw");
- EXPECT_TRUE(a.powered);
- EXPECT_TRUE(a.has_role("central"));
- EXPECT_TRUE(a.has_role("peripheral"));
- EXPECT_FALSE(a.has_role("broadcaster"));
- EXPECT_EQ(a.advertising_instances, 15);
- // 8127496 == 0x7c0408: service bits set above an A/V Hands-Free base class.
- EXPECT_TRUE(a.class_is_handsfree());
-}
-
-TEST(BluetoothObjects, ParsesDeviceAndBearer) {
- Payload p(IPHONE_BONDED);
- auto objects = parse_managed_objects(p.v);
-
- ASSERT_EQ(objects.devices.size(), 1u);
- const auto& d = objects.devices[0];
- EXPECT_EQ(d.address, "60:57:C8:30:6A:F7");
- EXPECT_EQ(d.name, "Zack 15 Pro");
- EXPECT_EQ(d.adapter_path, "/org/bluez/hci0");
- EXPECT_TRUE(d.bonded);
- EXPECT_TRUE(d.connected);
- EXPECT_TRUE(d.has_le_bearer);
- EXPECT_TRUE(d.le_connected);
- EXPECT_TRUE(d.supports_map());
- EXPECT_TRUE(d.supports_pbap());
- EXPECT_TRUE(d.supports_ancs());
- EXPECT_TRUE(d.looks_like_iphone());
-}
-
-TEST(BluetoothObjects, UuidMatchIsCaseInsensitive) {
- Payload p(R"({
- '/org/bluez/hci0/dev_AA': {
- 'org.bluez.Device1': {
- 'UUIDs': <['7905F431-B5CE-4E99-A40F-4B1E122D00D0']>
- }
- }
- })");
- auto objects = parse_managed_objects(p.v);
- ASSERT_EQ(objects.devices.size(), 1u);
- EXPECT_TRUE(objects.devices[0].supports_ancs());
-}
-
-TEST(BluetoothObjects, DerivesAdapterPathWhenPropertyMissing) {
- Payload p(R"({
- '/org/bluez/hci1/dev_AA_BB': {
- 'org.bluez.Device1': { 'Address': <'AA:BB:CC:DD:EE:FF'> }
- }
- })");
- auto objects = parse_managed_objects(p.v);
- ASSERT_EQ(objects.devices.size(), 1u);
- EXPECT_EQ(objects.devices[0].adapter_path, "/org/bluez/hci1");
-}
-
-// Older BlueZ has no Bonded property; a paired device must still read as bonded
-// or capability resolution would treat the bearer API as merely unconfirmed.
-TEST(BluetoothObjects, BondedFallsBackToPaired) {
- Payload p(R"({
- '/org/bluez/hci0/dev_AA': {
- 'org.bluez.Device1': { 'Paired': <true> }
- }
- })");
- auto objects = parse_managed_objects(p.v);
- ASSERT_EQ(objects.devices.size(), 1u);
- EXPECT_TRUE(objects.devices[0].bonded);
-}
-
-TEST(BluetoothObjects, IgnoresUnexpectedPropertyTypes) {
- // A string where a boolean belongs must not throw or corrupt the record.
- Payload p(R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': { 'Powered': <'yes'>, 'Class': <'nope'>, 'Address': <uint32 7> }
- }
- })");
- auto objects = parse_managed_objects(p.v);
- ASSERT_EQ(objects.adapters.size(), 1u);
- EXPECT_FALSE(objects.adapters[0].powered);
- EXPECT_EQ(objects.adapters[0].device_class, 0u);
- EXPECT_TRUE(objects.adapters[0].address.empty());
-}
-
-TEST(BluetoothObjects, RejectsNullAndWrongShape) {
- EXPECT_TRUE(parse_managed_objects(nullptr).adapters.empty());
-
- GVariant* wrong = g_variant_new_string("not an object tree");
- g_variant_ref_sink(wrong);
- auto objects = parse_managed_objects(wrong);
- EXPECT_TRUE(objects.adapters.empty());
- EXPECT_TRUE(objects.devices.empty());
- g_variant_unref(wrong);
-}
-
-TEST(Capability, FullModeWhenBearerConfirmed) {
- Payload p(join(ADAPTER_FULL, IPHONE_BONDED).c_str());
- auto cap = resolve_capability(parse_managed_objects(p.v));
-
- EXPECT_EQ(cap.mode, DeliveryMode::Full);
- EXPECT_EQ(cap.bearer_api, BearerApi::Confirmed);
- EXPECT_TRUE(cap.le_central);
- EXPECT_TRUE(cap.le_peripheral);
- EXPECT_TRUE(cap.advertising);
- EXPECT_TRUE(cap.class_ok);
- EXPECT_TRUE(cap.reasons.empty());
-}
-
-// Without --experimental the bearer interface can never appear, so its absence
-// is conclusive.
-TEST(Capability, CompatibilityWhenExperimentalIsOff) {
- Payload p(join(ADAPTER_FULL, R"({
- '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {
- 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true> }
- }
- })")
- .c_str());
- auto objects = parse_managed_objects(p.v);
- objects.experimental_api = false;
- auto cap = resolve_capability(objects);
-
- EXPECT_EQ(cap.mode, DeliveryMode::Compatibility);
- EXPECT_EQ(cap.bearer_api, BearerApi::Absent);
- EXPECT_FALSE(cap.reasons.empty());
-}
-
-// Headsets and game controllers are bonded but never expose a bearer under any
-// build, so treating any bond as proof of absence gives a false negative and
-// silently disables ANCS on a machine that supports it.
-TEST(Capability, ClassicOnlyBondDoesNotDisproveBearerApi) {
- Payload p(join(ADAPTER_FULL, R"({
- '/org/bluez/hci0/dev_F8_D3_F0_3C_84_4A': {
- 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true> }
- }
- })")
- .c_str());
- auto objects = parse_managed_objects(p.v);
- objects.experimental_api = true;
- auto cap = resolve_capability(objects);
-
- EXPECT_EQ(cap.bearer_api, BearerApi::Unknown);
- EXPECT_EQ(cap.mode, DeliveryMode::Full);
-}
-
-TEST(Capability, BearerUnknownWithoutAnyBondStaysFull) {
- Payload p(ADAPTER_FULL);
- auto objects = parse_managed_objects(p.v);
- objects.experimental_api = true;
- auto cap = resolve_capability(objects);
-
- EXPECT_EQ(cap.mode, DeliveryMode::Full);
- EXPECT_EQ(cap.bearer_api, BearerApi::Unknown);
- // Tentative, so it must say why rather than claiming a verified result.
- EXPECT_FALSE(cap.reasons.empty());
-}
-
-TEST(Capability, BlockedWhenAdapterMissingOrOff) {
- EXPECT_EQ(resolve_capability({}).mode, DeliveryMode::Blocked);
-
- Payload off(R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': { 'Powered': <false>, 'Roles': <['central', 'peripheral']> }
- }
- })");
- auto cap = resolve_capability(parse_managed_objects(off.v));
- EXPECT_EQ(cap.mode, DeliveryMode::Blocked);
- EXPECT_TRUE(cap.adapter_present);
-}
-
-TEST(Capability, BlockedWithoutCentralRole) {
- Payload p(R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': { 'Powered': <true>, 'Roles': <['peripheral']> }
- }
- })");
- EXPECT_EQ(resolve_capability(parse_managed_objects(p.v)).mode, DeliveryMode::Blocked);
-}
-
-TEST(Capability, CompatibilityWithoutAdvertising) {
- Payload p(R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': {
- 'Powered': <true>, 'Roles': <['central', 'peripheral']>, 'Class': <uint32 8127496>
- }
- }
- })");
- auto cap = resolve_capability(parse_managed_objects(p.v));
- EXPECT_EQ(cap.mode, DeliveryMode::Compatibility);
- EXPECT_FALSE(cap.advertising);
-}
-
-// Wrong Class of Device blocks the iPhone's permission toggles for MAP and PBAP
-// too, so it is reported as a setup problem rather than an ANCS downgrade.
-TEST(Capability, WrongClassIsReportedButDoesNotDowngradeMode) {
- Payload p(join(R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': {
- 'Powered': <true>, 'Roles': <['central', 'peripheral']>, 'Class': <uint32 8126732>
- },
- 'org.bluez.LEAdvertisingManager1': { 'SupportedInstances': <byte 15> }
- }
- })",
- IPHONE_BONDED)
- .c_str());
- auto cap = resolve_capability(parse_managed_objects(p.v));
-
- EXPECT_EQ(cap.mode, DeliveryMode::Full);
- EXPECT_FALSE(cap.class_ok);
- EXPECT_FALSE(cap.reasons.empty());
-}
-
-TEST(Capability, PrefersAPoweredAdapter) {
- Payload p(R"({
- '/org/bluez/hci0': {
- 'org.bluez.Adapter1': { 'Powered': <false>, 'Roles': <['central']> }
- },
- '/org/bluez/hci1': {
- 'org.bluez.Adapter1': { 'Powered': <true>, 'Roles': <['central', 'peripheral']> }
- }
- })");
- auto cap = resolve_capability(parse_managed_objects(p.v));
- EXPECT_TRUE(cap.powered);
- EXPECT_TRUE(cap.le_peripheral);
-}
diff --git a/test/test_bluetooth_pairing.cpp b/test/test_bluetooth_pairing.cpp
deleted file mode 100644
index 4fade67..0000000
--- a/test/test_bluetooth_pairing.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/agent.hpp>
-#include <tether/bluetooth/config.hpp>
-
-using namespace tether::bluetooth;
-
-// The agent authorizes services during pairing. Anything outside this set would
-// grant the phone a profile Tether has no reason to consume.
-TEST(AgentPolicy, AuthorizesOnlyMapAndPbap) {
- EXPECT_TRUE(is_authorized_service("0000112e-0000-1000-8000-00805f9b34fb")); // PBAP client
- EXPECT_TRUE(is_authorized_service("0000112f-0000-1000-8000-00805f9b34fb")); // PBAP server
- EXPECT_TRUE(is_authorized_service("00001132-0000-1000-8000-00805f9b34fb")); // MAP server
- EXPECT_TRUE(is_authorized_service("00001133-0000-1000-8000-00805f9b34fb")); // MAP notification
- EXPECT_TRUE(is_authorized_service("00001134-0000-1000-8000-00805f9b34fb")); // MAP client
-}
-
-TEST(AgentPolicy, RefusesEverythingElse) {
- // Hands-free / headset: the phone offers these, Tether must not accept them.
- EXPECT_FALSE(is_authorized_service("0000111e-0000-1000-8000-00805f9b34fb"));
- EXPECT_FALSE(is_authorized_service("0000110a-0000-1000-8000-00805f9b34fb"));
- // ANCS is reached over GATT after bonding, never authorized as a profile.
- EXPECT_FALSE(is_authorized_service("7905f431-b5ce-4e99-a40f-4b1e122d00d0"));
- EXPECT_FALSE(is_authorized_service(""));
- EXPECT_FALSE(is_authorized_service("garbage"));
- // A prefix match would be a real hole; require the whole UUID.
- EXPECT_FALSE(is_authorized_service("00001132-0000-1000-8000-00805f9b34f"));
- EXPECT_FALSE(is_authorized_service("00001132-0000-1000-8000-00805f9b34fbb"));
-}
-
-TEST(AgentPolicy, ServiceMatchIsCaseInsensitive) {
- EXPECT_TRUE(is_authorized_service("0000112F-0000-1000-8000-00805F9B34FB"));
-}
-
-// iOS renders the comparison with leading zeros. Dropping them shows the user a
-// code that does not match their phone, which reads as a failed pairing.
-TEST(Passkey, FormatsSixDigitsWithLeadingZeros) {
- EXPECT_EQ(format_passkey(123456), "123456");
- EXPECT_EQ(format_passkey(1234), "001234");
- EXPECT_EQ(format_passkey(0), "000000");
- EXPECT_EQ(format_passkey(7), "000007");
- EXPECT_EQ(format_passkey(999999), "999999");
-}
-
-TEST(BluetoothConfig, RoundTrips) {
- Config config;
- config.device_address = "60:57:C8:30:6A:F7";
- config.auth_strategy = AuthStrategy::ExplicitPair;
- config.ancs_enabled = false;
-
- EXPECT_EQ(deserialize_config(serialize_config(config)), config);
-}
-
-TEST(BluetoothConfig, DefaultsToConnectFirstAndAncsEnabled) {
- Config config = deserialize_config("{}");
- EXPECT_EQ(config.auth_strategy, AuthStrategy::ConnectFirst);
- EXPECT_TRUE(config.ancs_enabled);
- EXPECT_TRUE(config.device_address.empty());
-}
-
-// Connect-first is the default for a reason: a Linux-initiated Pair() can yield
-// a BR/EDR-only bond that can never carry ANCS. An unknown value must not
-// silently select the workaround.
-TEST(BluetoothConfig, UnknownStrategyFallsBackToConnectFirst) {
- EXPECT_EQ(auth_strategy_from_string("nonsense"), AuthStrategy::ConnectFirst);
- EXPECT_EQ(auth_strategy_from_string(""), AuthStrategy::ConnectFirst);
- EXPECT_EQ(auth_strategy_from_string("explicit-pair"), AuthStrategy::ExplicitPair);
-}
-
-TEST(BluetoothConfig, SurvivesCorruptFile) {
- Config config = deserialize_config("{not json at all");
- EXPECT_EQ(config, Config{});
-
- // A valid JSON document of the wrong shape must also yield defaults.
- EXPECT_EQ(deserialize_config("[1,2,3]"), Config{});
- EXPECT_EQ(deserialize_config("\"string\""), Config{});
-}
diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cpp
deleted file mode 100644
index 612803e..0000000
--- a/test/test_bluetooth_supervisor.cpp
+++ /dev/null
@@ -1,470 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/bearer_supervisor.hpp>
-#include <tether/bluetooth/profile_supervisor.hpp>
-
-#include <string>
-#include <vector>
-
-using namespace tether::bluetooth;
-
-namespace {
-
- class FakeBearer : public BearerOps {
- public:
- bool present = true;
- bool paired = true;
- bool classic = false;
- bool le_available = true;
- bool le = false;
- bool classic_succeeds = true;
- bool le_succeeds = true;
-
- int classic_attempts = 0;
- int le_attempts = 0;
- std::vector<std::string> preferred;
-
- bool device_present() const override { return present; }
- bool device_paired() const override { return paired; }
- bool classic_connected() const override { return classic; }
- bool le_bearer_available() const override { return le_available; }
- bool le_connected() const override { return le; }
-
- void set_preferred_bearer(const std::string& bearer) override { preferred.push_back(bearer); }
-
- std::string classic_error = "br/edr refused";
- std::string le_error = "le refused";
-
- bool connect_classic(std::string& err) override {
- ++classic_attempts;
- if (!classic_succeeds) {
- err = classic_error;
- return false;
- }
- classic = true;
- return true;
- }
-
- bool connect_le(std::string& err) override {
- ++le_attempts;
- if (!le_succeeds) {
- err = le_error;
- return false;
- }
- le = true;
- return true;
- }
- };
-
- class FakeProfiles : public ProfileOps {
- public:
- std::string map_error;
- std::string pbap_error;
- int map_attempts = 0;
- int pbap_attempts = 0;
- std::vector<std::string> removed;
- int session_counter = 0;
-
- std::string create_session(const std::string& target, std::string& err) override {
- const bool is_map = target == "map";
- (is_map ? map_attempts : pbap_attempts)++;
- const std::string& failure = is_map ? map_error : pbap_error;
- if (!failure.empty()) {
- err = failure;
- return {};
- }
- return "/session" + std::to_string(++session_counter);
- }
-
- void remove_session(const std::string& path) override { removed.push_back(path); }
- };
-
-} // namespace
-
-// BR/EDR must come up first; LE must wait out the settle window. Connecting LE
-// too early leaves the bond half-connected and flapping.
-TEST(BearerSupervisor, ConnectsClassicThenLeAfterSettling) {
- FakeBearer ops;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- EXPECT_EQ(ops.classic_attempts, 1);
- EXPECT_EQ(ops.le_attempts, 0) << "LE must not be attempted before Classic is up";
-
- // Classic is up at t=1, but the settle window has not elapsed.
- sup.tick(1);
- EXPECT_EQ(ops.le_attempts, 0);
- sup.tick(1 + BEARER_SETTLE_SECONDS - 1);
- EXPECT_EQ(ops.le_attempts, 0) << "LE attempted before the settle window elapsed";
-
- sup.tick(1 + BEARER_SETTLE_SECONDS);
- EXPECT_EQ(ops.le_attempts, 1);
- EXPECT_TRUE(sup.status().le_connected);
-}
-
-// PreferredBearer is an instruction for the next connection, not a durable
-// setting. Leaving LE preferred while idle changes later reconnect behavior.
-TEST(BearerSupervisor, NeverLeavesLePreferredWhileIdle) {
- FakeBearer ops;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(1);
- sup.tick(1 + BEARER_SETTLE_SECONDS);
-
- ASSERT_FALSE(ops.preferred.empty());
- EXPECT_EQ(ops.preferred.back(), "bredr");
-
- // Every "le" selection must be immediately followed by a return to "bredr".
- for (size_t i = 0; i < ops.preferred.size(); ++i) {
- if (ops.preferred[i] == "le") {
- ASSERT_LT(i + 1, ops.preferred.size()) << "left LE preferred at the end";
- EXPECT_EQ(ops.preferred[i + 1], "bredr");
- }
- }
-}
-
-TEST(BearerSupervisor, ClassicBackoffGrowsAndCaps) {
- FakeBearer ops;
- ops.classic_succeeds = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- EXPECT_EQ(ops.classic_attempts, 1);
- EXPECT_EQ(sup.status().classic_backoff, BEARER_BACKOFF_MIN_SECONDS);
-
- // Ticking inside the backoff window must not retry.
- sup.tick(BEARER_BACKOFF_MIN_SECONDS - 1);
- EXPECT_EQ(ops.classic_attempts, 1) << "retried before the backoff expired";
-
- sup.tick(BEARER_BACKOFF_MIN_SECONDS);
- EXPECT_EQ(ops.classic_attempts, 2);
- EXPECT_EQ(sup.status().classic_backoff, BEARER_BACKOFF_MIN_SECONDS * 2);
-
- // Drive many failures and confirm the cap holds.
- int64_t now = BEARER_BACKOFF_MIN_SECONDS;
- for (int i = 0; i < 20; ++i) {
- now += sup.status().classic_backoff;
- sup.tick(now);
- }
- EXPECT_EQ(sup.status().classic_backoff, BEARER_BACKOFF_MAX_SECONDS);
-}
-
-// InProgress means BlueZ is still finishing an operation of its own, which
-// clears without help. Treating it like a refusal pushed the retry out to
-// minutes and left LE — and so ANCS — down long after the cause was gone.
-TEST(BearerSupervisor, InProgressDoesNotGrowTheClassicBackoff) {
- FakeBearer ops;
- ops.classic_succeeds = false;
- ops.classic_error = "GDBus.Error:org.bluez.Error.InProgress: In Progress";
- BearerSupervisor sup(ops, true);
-
- int64_t now = 0;
- for (int i = 0; i < 10; ++i) {
- sup.tick(now);
- EXPECT_EQ(sup.status().classic_backoff, BEARER_BACKOFF_MIN_SECONDS);
- now += BEARER_BACKOFF_MIN_SECONDS;
- }
- EXPECT_EQ(ops.classic_attempts, 10);
-}
-
-TEST(BearerSupervisor, InProgressDoesNotGrowTheLeBackoff) {
- FakeBearer ops;
- ops.le_succeeds = false;
- ops.le_error = "GDBus.Error:org.bluez.Error.InProgress: In Progress";
- BearerSupervisor sup(ops, true);
-
- // Classic is observed connected on the tick after it is dialed, and the
- // settle window runs from there.
- sup.tick(0);
- sup.tick(1);
- int64_t now = 1 + BEARER_SETTLE_SECONDS;
- for (int i = 0; i < 10; ++i) {
- sup.tick(now);
- EXPECT_EQ(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS);
- now += BEARER_BACKOFF_MIN_SECONDS;
- }
- EXPECT_EQ(ops.le_attempts, 10);
-}
-
-// A refusal is different: the phone said no, and hammering it was observed to
-// hold the bond in a half-connected flapping state.
-TEST(BearerSupervisor, RefusalStillGrowsTheLeBackoff) {
- FakeBearer ops;
- ops.le_succeeds = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(1);
- sup.tick(1 + BEARER_SETTLE_SECONDS);
- EXPECT_EQ(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS);
-
- sup.tick(1 + BEARER_SETTLE_SECONDS + BEARER_BACKOFF_MIN_SECONDS);
- EXPECT_EQ(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS * 2);
-}
-
-TEST(BearerSupervisor, LeBackoffDoesNotBlockClassic) {
- FakeBearer ops;
- ops.le_succeeds = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(1);
- sup.tick(1 + BEARER_SETTLE_SECONDS);
- EXPECT_EQ(ops.le_attempts, 1);
- EXPECT_GT(sup.status().le_backoff, 0);
- EXPECT_TRUE(sup.status().classic_connected) << "an LE failure must not tear down Classic";
-}
-
-TEST(BearerSupervisor, RecoversAfterDisconnect) {
- FakeBearer ops;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(1);
- sup.tick(1 + BEARER_SETTLE_SECONDS);
- ASSERT_TRUE(sup.status().le_connected);
-
- // The phone walks out of range.
- ops.classic = false;
- ops.le = false;
- sup.tick(100);
- EXPECT_FALSE(sup.status().classic_connected);
- EXPECT_FALSE(sup.status().le_connected) << "LE cannot be up while Classic is down";
- EXPECT_EQ(ops.classic_attempts, 2);
-
- // ...and comes back.
- sup.tick(101);
- sup.tick(101 + BEARER_SETTLE_SECONDS);
- EXPECT_TRUE(sup.status().classic_connected);
- EXPECT_TRUE(sup.status().le_connected);
-}
-
-// reset() models a resume: recovery should start at once, not after waiting out
-// a backoff accumulated before the machine slept.
-TEST(BearerSupervisor, ResetClearsBackoffForImmediateRetry) {
- FakeBearer ops;
- ops.classic_succeeds = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(BEARER_BACKOFF_MIN_SECONDS);
- ASSERT_EQ(ops.classic_attempts, 2);
-
- sup.reset();
- ops.classic_succeeds = true;
- sup.tick(BEARER_BACKOFF_MIN_SECONDS + 1);
- EXPECT_EQ(ops.classic_attempts, 3) << "reset must allow an immediate retry";
-}
-
-TEST(BearerSupervisor, SkipsLeWhenAncsDisabled) {
- FakeBearer ops;
- BearerSupervisor sup(ops, false);
-
- sup.tick(0);
- sup.tick(1);
- sup.tick(1 + BEARER_SETTLE_SECONDS + 10);
- EXPECT_EQ(ops.le_attempts, 0);
- EXPECT_TRUE(sup.status().classic_connected);
-}
-
-TEST(BearerSupervisor, SkipsLeWhenBearerUnavailable) {
- FakeBearer ops;
- ops.le_available = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(1);
- sup.tick(1 + BEARER_SETTLE_SECONDS + 10);
- EXPECT_EQ(ops.le_attempts, 0);
- EXPECT_FALSE(sup.status().le_available);
-}
-
-TEST(BearerSupervisor, ReportsMissingDevice) {
- FakeBearer ops;
- ops.present = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- EXPECT_FALSE(sup.status().device_present);
- EXPECT_EQ(ops.classic_attempts, 0) << "must not dial a device BlueZ does not know";
-}
-
-// A known-but-unpaired device happens after an unpair or after the phone forgets
-// this computer. Dialing it collides with the pairing transaction, and BlueZ
-// answers both attempts with br-connection-busy.
-TEST(BearerSupervisor, StandsDownWhenDeviceIsUnpaired) {
- FakeBearer ops;
- ops.paired = false;
- BearerSupervisor sup(ops, true);
-
- sup.tick(0);
- sup.tick(BEARER_POLL_SECONDS * 20);
- EXPECT_TRUE(sup.status().device_present);
- EXPECT_FALSE(sup.status().device_paired);
- EXPECT_EQ(ops.classic_attempts, 0) << "must not dial an unpaired device";
- EXPECT_EQ(ops.le_attempts, 0);
- EXPECT_TRUE(ops.preferred.empty()) << "must not touch PreferredBearer before a bond exists";
-}
-
-// Forbidden and Busy look similar but call for opposite advice. Reporting a
-// permissions problem as a busy session sends the user off re-pairing for
-// nothing, and vice versa.
-TEST(ObexErrors, DistinguishesForbiddenFromBusy) {
- EXPECT_EQ(classify_obex_error("Forbidden"), ObexError::Forbidden);
- EXPECT_EQ(classify_obex_error("org.bluez.obex.Error.Forbidden: Forbidden"), ObexError::Forbidden);
- EXPECT_EQ(classify_obex_error("OBEX response 0x43"), ObexError::Forbidden);
-
- EXPECT_EQ(classify_obex_error("Connection refused (111)"), ObexError::Busy);
- EXPECT_EQ(classify_obex_error("connection refused"), ObexError::Busy);
-}
-
-// Observed on real hardware with the iPhone bonded, connected, and all three
-// permission toggles verified on. Classifying it as Forbidden would send the
-// user to settings that are already correct.
-TEST(ObexErrors, ServiceRecordMissingIsNotAPermissionProblem) {
- const std::string real = "GDBus.Error:org.bluez.obex.Error.Failed: Unable to find service record";
- EXPECT_EQ(classify_obex_error(real), ObexError::NoRecord);
- EXPECT_NE(classify_obex_error(real), ObexError::Forbidden);
-
- // obexd reports a missing record whenever its SDP fetch is refused, so the
- // advice must name both plausible causes and must not send the user
- // re-pairing, which fixes neither.
- const std::string advice = obex_error_advice(ObexError::NoRecord, "map");
- EXPECT_NE(advice.find("another computer"), std::string::npos);
- EXPECT_NE(advice.find("Show Message Notifications"), std::string::npos);
- EXPECT_NE(advice.find("re-pairing is not the fix"), std::string::npos);
-}
-
-TEST(ObexErrors, ClassifiesUnavailableAndOther) {
- EXPECT_EQ(classify_obex_error("Host is down"), ObexError::Unavailable);
- EXPECT_EQ(classify_obex_error("Page Timeout"), ObexError::Unavailable);
- EXPECT_EQ(classify_obex_error(""), ObexError::None);
- EXPECT_EQ(classify_obex_error("something entirely new"), ObexError::Other);
-}
-
-TEST(ObexErrors, AdviceNamesThePermissionToggle) {
- const std::string map_advice = obex_error_advice(ObexError::Forbidden, "map");
- EXPECT_NE(map_advice.find("Show Message Notifications"), std::string::npos);
- // Must not send the user re-pairing over a permission.
- EXPECT_EQ(map_advice.find("re-pair"), std::string::npos);
-
- EXPECT_NE(obex_error_advice(ObexError::Forbidden, "pbap").find("Sync Contacts"), std::string::npos);
- EXPECT_NE(obex_error_advice(ObexError::Busy, "map").find("another computer"), std::string::npos);
-}
-
-TEST(ProfileSupervisor, OpensBothSessionsWhenLinkReady) {
- FakeProfiles ops;
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- EXPECT_TRUE(sup.status().map_open);
- EXPECT_TRUE(sup.status().pbap_open);
- EXPECT_FALSE(sup.map_session().empty());
- EXPECT_FALSE(sup.pbap_session().empty());
-}
-
-TEST(ProfileSupervisor, DoesNothingUntilLinkIsReady) {
- FakeProfiles ops;
- ProfileSupervisor sup(ops);
-
- sup.tick(0, false);
- EXPECT_EQ(ops.map_attempts, 0);
- EXPECT_EQ(ops.pbap_attempts, 0);
-}
-
-// A Forbidden may be a stale obexd session from a previous run, so exactly one
-// retry is allowed. It must never escalate to restarting obexd.
-TEST(ProfileSupervisor, RetriesOnceAfterForbidden) {
- FakeProfiles ops;
- ops.map_error = "Forbidden";
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- EXPECT_EQ(ops.map_attempts, 2) << "expected exactly one retry after Forbidden";
- EXPECT_FALSE(sup.status().map_open);
- EXPECT_EQ(sup.status().map_error, ObexError::Forbidden);
-
- // PBAP opened, so the supervisor is on the steady cadence even though MAP is
- // still failing. The extra Forbidden retry is spent, so this poll makes
- // exactly one attempt — a persistent permission problem must not turn into a
- // retry burst against obexd.
- sup.tick(PROFILE_STEADY_POLL_SECONDS, true);
- EXPECT_EQ(ops.map_attempts, 3);
-}
-
-// While nothing has opened yet, the fast cadence applies so a user flipping the
-// permission toggles is picked up promptly.
-TEST(ProfileSupervisor, UsesFastCadenceUntilSomethingOpens) {
- FakeProfiles ops;
- ops.map_error = "Forbidden";
- ops.pbap_error = "Forbidden";
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- const int attempts = ops.map_attempts;
-
- sup.tick(PROFILE_INITIAL_POLL_SECONDS - 1, true);
- EXPECT_EQ(ops.map_attempts, attempts);
-
- sup.tick(PROFILE_INITIAL_POLL_SECONDS, true);
- EXPECT_GT(ops.map_attempts, attempts);
-}
-
-TEST(ProfileSupervisor, PartialSuccessKeepsRetryingTheOtherProfile) {
- FakeProfiles ops;
- ops.pbap_error = "Forbidden";
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- EXPECT_TRUE(sup.status().map_open);
- EXPECT_FALSE(sup.status().pbap_open);
-
- const int map_attempts_after_open = ops.map_attempts;
- ops.pbap_error.clear();
- sup.tick(PROFILE_STEADY_POLL_SECONDS, true);
- EXPECT_TRUE(sup.status().pbap_open);
- EXPECT_EQ(ops.map_attempts, map_attempts_after_open) << "must not reopen an already-open session";
-}
-
-TEST(ProfileSupervisor, RespectsPollInterval) {
- FakeProfiles ops;
- ops.map_error = "Connection refused (111)";
- ops.pbap_error = "Connection refused (111)";
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- const int attempts = ops.map_attempts;
- sup.tick(1, true);
- EXPECT_EQ(ops.map_attempts, attempts) << "retried before the poll interval elapsed";
-
- sup.tick(PROFILE_INITIAL_POLL_SECONDS, true);
- EXPECT_GT(ops.map_attempts, attempts);
-}
-
-TEST(ProfileSupervisor, ResetRemovesSessions) {
- FakeProfiles ops;
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- ASSERT_TRUE(sup.status().map_open);
-
- sup.reset();
- EXPECT_EQ(ops.removed.size(), 2u);
- EXPECT_FALSE(sup.status().map_open);
- EXPECT_TRUE(sup.map_session().empty());
-
- // And reopens on the next tick.
- sup.tick(100, true);
- EXPECT_TRUE(sup.status().map_open);
-}
-
-TEST(ProfileSupervisor, BusySessionKeepsPollingWithoutRetryBurst) {
- FakeProfiles ops;
- ops.map_error = "Connection refused (111)";
- ProfileSupervisor sup(ops);
-
- sup.tick(0, true);
- // Busy is not Forbidden, so it gets no extra immediate retry.
- EXPECT_EQ(ops.map_attempts, 1);
- EXPECT_EQ(sup.status().map_error, ObexError::Busy);
-}
diff --git a/test/test_bmessage.cpp b/test/test_bmessage.cpp
deleted file mode 100644
index 34a811b..0000000
--- a/test/test_bmessage.cpp
+++ /dev/null
@@ -1,386 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/bmessage.hpp>
-#include <tether/bluetooth/map_session.hpp>
-#include <tether/bluetooth/messages.hpp>
-
-using namespace tether::bluetooth;
-
-namespace {
-
- // Shape observed from the iPhone: originator vCard outside BENV, recipient
- // inside it, UTF-8 body in BBODY/MSG, TYPE always SMS_GSM.
- constexpr const char* INCOMING_TEL =
- "BEGIN:BMSG\r\n"
- "VERSION:1.0\r\n"
- "STATUS:UNREAD\r\n"
- "TYPE:SMS_GSM\r\n"
- "FOLDER:telecom/msg/inbox\r\n"
- "BEGIN:VCARD\r\n"
- "VERSION:2.1\r\n"
- "N:Doe;Jane\r\n"
- "TEL:+1 (555) 123-4567\r\n"
- "END:VCARD\r\n"
- "BEGIN:BENV\r\n"
- "BEGIN:VCARD\r\n"
- "VERSION:2.1\r\n"
- "TEL:+15559998888\r\n"
- "END:VCARD\r\n"
- "BEGIN:BBODY\r\n"
- "CHARSET:UTF-8\r\n"
- "LENGTH:42\r\n"
- "BEGIN:MSG\r\n"
- "Running late\r\n"
- "END:MSG\r\n"
- "END:BBODY\r\n"
- "END:BENV\r\n"
- "END:BMSG\r\n";
-
- // Apple-ID destination: no TEL at all, only EMAIL.
- constexpr const char* INCOMING_EMAIL =
- "BEGIN:BMSG\n"
- "VERSION:1.0\n"
- "STATUS:READ\n"
- "TYPE:SMS_GSM\n"
- "FOLDER:telecom/msg/inbox\n"
- "BEGIN:VCARD\n"
- "FN:Sam Smith\n"
- "EMAIL:[email protected]\n"
- "END:VCARD\n"
- "BEGIN:BENV\n"
- "BEGIN:BBODY\n"
- "BEGIN:MSG\n"
- "sent from an apple id\n"
- "END:MSG\n"
- "END:BBODY\n"
- "END:BENV\n"
- "END:BMSG\n";
-
-} // namespace
-
-TEST(BMessageParse, ParsesTelephoneOriginator) {
- BMessage m = parse_bmessage(INCOMING_TEL);
- ASSERT_TRUE(m.valid);
- EXPECT_FALSE(m.read);
- EXPECT_EQ(m.type, "SMS_GSM");
- EXPECT_EQ(m.folder, "telecom/msg/inbox");
- EXPECT_EQ(m.originator.tel, "+1 (555) 123-4567");
- EXPECT_EQ(m.originator.name, "Jane Doe");
- EXPECT_EQ(m.body, "Running late");
- ASSERT_EQ(m.recipients.size(), 1u);
- EXPECT_EQ(m.recipients[0].tel, "+15559998888");
-}
-
-TEST(BMessageParse, ParsesAppleIdOriginator) {
- BMessage m = parse_bmessage(INCOMING_EMAIL);
- ASSERT_TRUE(m.valid);
- EXPECT_TRUE(m.read);
- EXPECT_TRUE(m.originator.tel.empty());
- EXPECT_EQ(m.originator.email, "[email protected]");
- EXPECT_EQ(m.originator.name, "Sam Smith");
- EXPECT_EQ(m.body, "sent from an apple id");
-}
-
-TEST(BMessageParse, KeepsMultilineAndUtf8Bodies) {
- const std::string text = "BEGIN:BMSG\r\nSTATUS:UNREAD\r\n"
- "BEGIN:VCARD\r\nTEL:+15551112222\r\nEND:VCARD\r\n"
- "BEGIN:BENV\r\nBEGIN:BBODY\r\nBEGIN:MSG\r\n"
- "line one\r\nline two\r\n\xC3\xA9\xC3\xA0 \xE2\x9C\x93 \xF0\x9F\x8E\x89\r\n"
- "END:MSG\r\nEND:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n";
- BMessage m = parse_bmessage(text);
- ASSERT_TRUE(m.valid);
- EXPECT_EQ(m.body, "line one\nline two\n\xC3\xA9\xC3\xA0 \xE2\x9C\x93 \xF0\x9F\x8E\x89");
-}
-
-// A body line that looks like a structural token is byte-stuffed by the sender.
-// Failing to unstuff would corrupt the message; failing to stop at the real
-// END:MSG would swallow the rest of the container.
-TEST(BMessageParse, UnstuffsBodyLinesThatLookStructural) {
- const std::string text = "BEGIN:BMSG\r\nSTATUS:UNREAD\r\n"
- "BEGIN:VCARD\r\nTEL:+15551112222\r\nEND:VCARD\r\n"
- "BEGIN:BENV\r\nBEGIN:BBODY\r\nBEGIN:MSG\r\n"
- " END:MSG\r\n"
- " BEGIN:VCARD\r\n"
- "real text\r\n"
- "END:MSG\r\nEND:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n";
- BMessage m = parse_bmessage(text);
- ASSERT_TRUE(m.valid);
- EXPECT_EQ(m.body, "END:MSG\nBEGIN:VCARD\nreal text");
- // The stuffed vCard line must not have been read as a real party.
- EXPECT_TRUE(m.recipients.empty());
-}
-
-TEST(BMessageParse, AcceptsLfOnlyAndIgnoresUnknownProperties) {
- const std::string text = "BEGIN:BMSG\nX-WEIRD:whatever\nSTATUS:READ\n"
- "BEGIN:VCARD\nTEL;TYPE=CELL:+15551112222\nX-OTHER:x\nEND:VCARD\n"
- "BEGIN:BENV\nBEGIN:BBODY\nBEGIN:MSG\nhi\nEND:MSG\nEND:BBODY\nEND:BENV\nEND:BMSG";
- BMessage m = parse_bmessage(text);
- ASSERT_TRUE(m.valid);
- EXPECT_EQ(m.originator.tel, "+15551112222") << "vCard parameters must not break property parsing";
- EXPECT_EQ(m.body, "hi");
-}
-
-TEST(BMessageParse, RejectsMalformedInputWithoutThrowing) {
- EXPECT_FALSE(parse_bmessage("").valid);
- EXPECT_FALSE(parse_bmessage("not a bmessage at all").valid);
- EXPECT_FALSE(parse_bmessage("STATUS:READ\nBEGIN:MSG\nbody\n").valid);
-
- // Truncated mid-container: must parse what it can and not crash.
- BMessage truncated = parse_bmessage("BEGIN:BMSG\nSTATUS:UNREAD\nBEGIN:VCARD\nTEL:+1555");
- EXPECT_TRUE(truncated.valid);
- EXPECT_TRUE(truncated.body.empty());
-}
-
-// --- Identity ----------------------------------------------------------
-
-TEST(AddressIdentity, NormalizesPhoneFormatting) {
- EXPECT_EQ(normalize_phone("+1 (555) 123-4567"), "+15551234567");
- EXPECT_EQ(normalize_phone("+1-555-123-4567"), "+15551234567");
- EXPECT_EQ(normalize_phone("555.123.4567"), "5551234567");
- EXPECT_EQ(normalize_phone(""), "");
-}
-
-// Guessing a country code could route a reply to a different person, so a
-// national number must not silently become an international one.
-TEST(AddressIdentity, DoesNotInventCountryCodes) {
- EXPECT_NE(normalize_phone("5551234567"), normalize_phone("+15551234567"));
-}
-
-TEST(AddressIdentity, EmailIsCaseInsensitive) {
- EXPECT_EQ(normalize_email(" [email protected] "), "[email protected]");
-}
-
-TEST(AddressIdentity, ThreadKeyPrefersTelAndNamespacesTypes) {
- VCardParty both;
- both.tel = "+1 555 123 4567";
- both.email = "[email protected]";
- EXPECT_EQ(thread_key_for(both), "tel:+15551234567");
-
- VCardParty email_only;
- email_only.email = "[email protected]";
- EXPECT_EQ(thread_key_for(email_only), "email:[email protected]");
-
- // A phone number and an email must never collide.
- EXPECT_NE(thread_key_for(both), thread_key_for(email_only));
-
- EXPECT_TRUE(thread_key_for(VCardParty{}).empty());
-}
-
-// The display name is not identity; two contacts sharing a name must stay apart.
-TEST(AddressIdentity, NameDoesNotAffectThreadKey) {
- VCardParty a;
- a.name = "Sam";
- a.tel = "+15551110000";
- VCardParty b;
- b.name = "Sam";
- b.tel = "+15552220000";
- EXPECT_NE(thread_key_for(a), thread_key_for(b));
-}
-
-TEST(Timestamps, ParsesMapBasicIso) {
- EXPECT_GT(parse_map_timestamp("20260816T024500"), 0);
- EXPECT_EQ(parse_map_timestamp("20260816T024500Z"), 1786848300); // 2026-08-16T02:45:00Z
- EXPECT_EQ(parse_map_timestamp(""), 0);
- EXPECT_EQ(parse_map_timestamp("garbage"), 0);
- EXPECT_EQ(parse_map_timestamp("20261399T999999"), 0);
-}
-
-// --- Store -------------------------------------------------------------
-
-namespace {
-
- Message make(const std::string& handle, const std::string& thread, int64_t ts, bool read = false,
- bool outgoing = false) {
- Message m;
- m.handle = handle;
- m.thread_key = thread;
- m.peer_address = thread;
- m.body = "body " + handle;
- m.timestamp = ts;
- m.read = read;
- m.outgoing = outgoing;
- return m;
- }
-
-} // namespace
-
-// MNS events and ListMessages polling both deliver the same message, and the
-// phone replays messages after a reconnect.
-TEST(MessageStore, DedupesByHandle) {
- MessageStore store;
- EXPECT_TRUE(store.add(make("h1", "tel:+1555", 100)));
- EXPECT_FALSE(store.add(make("h1", "tel:+1555", 100)));
- EXPECT_EQ(store.size(), 1u);
-}
-
-TEST(MessageStore, RejectsMessagesWithoutHandle) {
- MessageStore store;
- EXPECT_FALSE(store.add(make("", "tel:+1555", 100)));
- EXPECT_EQ(store.size(), 0u);
-}
-
-TEST(MessageStore, GroupsThreadsNewestFirst) {
- MessageStore store;
- store.add(make("a", "tel:+1111", 100));
- store.add(make("b", "tel:+2222", 300));
- store.add(make("c", "tel:+1111", 200));
-
- auto threads = store.threads();
- ASSERT_EQ(threads.size(), 2u);
- EXPECT_EQ(threads[0].key, "tel:+2222");
- EXPECT_EQ(threads[1].key, "tel:+1111");
- EXPECT_EQ(threads[1].count, 2);
- EXPECT_EQ(threads[1].last_body, "body c") << "preview must come from the newest message";
-}
-
-TEST(MessageStore, CountsUnreadIncomingOnly) {
- MessageStore store;
- store.add(make("a", "tel:+1111", 100, /*read=*/false));
- store.add(make("b", "tel:+1111", 200, /*read=*/true));
- store.add(make("c", "tel:+1111", 300, /*read=*/false, /*outgoing=*/true));
-
- auto threads = store.threads();
- ASSERT_EQ(threads.size(), 1u);
- EXPECT_EQ(threads[0].unread, 1) << "an unread outgoing message is not unread mail";
-}
-
-TEST(MessageStore, MarkReadIsIdempotentAndReportsChange) {
- MessageStore store;
- store.add(make("a", "tel:+1111", 100, /*read=*/false));
-
- EXPECT_TRUE(store.set_read("a", true));
- EXPECT_FALSE(store.set_read("a", true)) << "an echo of our own change must not loop";
- EXPECT_TRUE(store.set_read("a", false));
- EXPECT_FALSE(store.set_read("unknown", true));
-}
-
-TEST(MessageStore, MessagesAreOldestFirstAndLimited) {
- MessageStore store;
- for (int i = 0; i < 10; ++i)
- store.add(make("h" + std::to_string(i), "tel:+1111", 100 + i));
-
- auto all = store.messages("tel:+1111");
- ASSERT_EQ(all.size(), 10u);
- EXPECT_EQ(all.front().handle, "h0");
- EXPECT_EQ(all.back().handle, "h9");
-
- auto recent = store.messages("tel:+1111", 3);
- ASSERT_EQ(recent.size(), 3u);
- EXPECT_EQ(recent.front().handle, "h7") << "limit must keep the newest, in oldest-first order";
- EXPECT_EQ(recent.back().handle, "h9");
-}
-
-TEST(MessageStore, EvictsOldestBeyondCap) {
- MessageStore store(3);
- for (int i = 0; i < 5; ++i)
- store.add(make("h" + std::to_string(i), "tel:+1111", 100 + i));
-
- EXPECT_EQ(store.size(), 3u);
- EXPECT_EQ(store.find("h0"), nullptr);
- EXPECT_NE(store.find("h4"), nullptr);
-}
-
-TEST(MessageStore, BuildsMessageFromIncomingBMessage) {
- Message m = message_from_bmessage(parse_bmessage(INCOMING_TEL), "0x0001", 12345);
- EXPECT_EQ(m.handle, "0x0001");
- EXPECT_EQ(m.thread_key, "tel:+15551234567") << "keyed on the originator for incoming mail";
- EXPECT_EQ(m.peer_name, "Jane Doe");
- EXPECT_FALSE(m.outgoing);
- EXPECT_FALSE(m.read);
- EXPECT_EQ(m.timestamp, 12345);
-}
-
-// For a message we sent, the conversation is the recipient, not ourselves.
-TEST(MessageStore, OutgoingMessageIsKeyedOnRecipient) {
- const std::string sent = "BEGIN:BMSG\nSTATUS:READ\nFOLDER:telecom/msg/sent\n"
- "BEGIN:VCARD\nEND:VCARD\n"
- "BEGIN:BENV\nBEGIN:VCARD\nTEL:+15557778888\nEND:VCARD\n"
- "BEGIN:BBODY\nBEGIN:MSG\nyo\nEND:MSG\nEND:BBODY\nEND:BENV\nEND:BMSG\n";
- Message m = message_from_bmessage(parse_bmessage(sent), "0x0002", 999);
- EXPECT_TRUE(m.outgoing);
- EXPECT_EQ(m.thread_key, "tel:+15557778888");
-}
-
-// --- MAP listings ------------------------------------------------------
-//
-// ListMessages alone carries enough to display a conversation, so the listing
-// path must produce the same identity as a parsed bMessage would.
-
-TEST(MapListing, BuildsMessageWithoutBMessageFetch) {
- MapListing listing;
- listing.handle = "/org/bluez/obex/client/session1/message0";
- listing.subject = "see you there";
- listing.sender_address = "+1 (555) 123-4567";
- listing.sender_name = "Jane Doe";
- listing.timestamp = "20260816T024500Z";
- listing.type = "sms-gsm";
- listing.folder = "inbox";
- listing.read = false;
-
- Message m = message_from_listing(listing);
- // The handle is the stable id, not the session-scoped object path.
- EXPECT_EQ(m.handle, "0");
- EXPECT_EQ(m.object_path, listing.handle);
- EXPECT_EQ(m.body, "see you there");
- EXPECT_EQ(m.thread_key, "tel:+15551234567");
- EXPECT_EQ(m.peer_address, "+15551234567");
- EXPECT_EQ(m.peer_name, "Jane Doe");
- EXPECT_EQ(m.timestamp, 1786848300);
- EXPECT_FALSE(m.read);
- EXPECT_FALSE(m.outgoing);
-}
-
-// An Apple-ID sender arrives in the same field as a phone number, with '@' the
-// only discriminator available.
-TEST(MapListing, RoutesAppleIdSenderToEmailIdentity) {
- MapListing listing;
- listing.handle = "h";
- listing.sender_address = "[email protected]";
- Message m = message_from_listing(listing);
- EXPECT_EQ(m.thread_key, "email:[email protected]");
-}
-
-// A listing and a full bMessage for the same conversation must land in one
-// thread, or history would split depending on how it was fetched.
-TEST(MapListing, AgreesWithBMessageThreadKey) {
- MapListing listing;
- listing.handle = "h";
- listing.sender_address = "+15551234567";
- const Message from_listing = message_from_listing(listing);
- const Message from_bmessage = message_from_bmessage(parse_bmessage(INCOMING_TEL), "h2", 1);
- EXPECT_EQ(from_listing.thread_key, from_bmessage.thread_key);
-}
-
-TEST(MapListing, SentFlagMarksOutgoing) {
- MapListing listing;
- listing.handle = "h";
- listing.sender_address = "+15551234567";
- listing.sent = true;
- EXPECT_TRUE(message_from_listing(listing).outgoing);
-}
-
-// obexd's object path embeds the OBEX session number, which changes on every
-// reconnect. Keying a message on the whole path makes the same message look new
-// after each one, duplicating history without bound.
-TEST(MapHandle, StripsTheSessionScopedPrefix) {
- EXPECT_EQ(map_handle_from_path("/org/bluez/obex/client/session5/message1086086778701665313"),
- "1086086778701665313");
- EXPECT_EQ(map_handle_from_path("/org/bluez/obex/client/session11/message1086086778701665313"),
- "1086086778701665313")
- << "a different session must yield the same handle";
-}
-
-TEST(MapHandle, PassesThroughUnexpectedShapes) {
- EXPECT_EQ(map_handle_from_path("12345"), "12345");
- EXPECT_EQ(map_handle_from_path(""), "");
-}
-
-TEST(MapListingConversion, KeepsTheObjectPathForActingOnTheMessage) {
- MapListing listing;
- listing.handle = "/org/bluez/obex/client/session5/message42";
- listing.sender_address = "+15551234567";
- listing.subject = "hi";
-
- Message message = message_from_listing(listing);
- EXPECT_EQ(message.handle, "42");
- EXPECT_EQ(message.object_path, "/org/bluez/obex/client/session5/message42");
-}
diff --git a/test/test_bmessage_build.cpp b/test/test_bmessage_build.cpp
deleted file mode 100644
index 4e7e623..0000000
--- a/test/test_bmessage_build.cpp
+++ /dev/null
@@ -1,207 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/bmessage.hpp>
-
-using namespace tether::bluetooth;
-
-namespace {
-
- Recipient tel(const std::string& address) { return {RecipientKind::Tel, address}; }
- Recipient email(const std::string& address) { return {RecipientKind::Email, address}; }
-
- size_t count_occurrences(const std::string& haystack, const std::string& needle) {
- size_t count = 0;
- for (size_t at = haystack.find(needle); at != std::string::npos; at = haystack.find(needle, at + 1))
- ++count;
- return count;
- }
-
-} // namespace
-
-TEST(BMessageBuild, ProducesTheShapeThePhoneAccepts) {
- const std::string out = build_bmessage({tel("+15551234567")}, "on my way");
-
- EXPECT_NE(out.find("BEGIN:BMSG"), std::string::npos);
- EXPECT_NE(out.find("TYPE:SMS_GSM"), std::string::npos);
- EXPECT_NE(out.find("FOLDER:telecom/msg/outbox"), std::string::npos);
- EXPECT_NE(out.find("CHARSET:UTF-8"), std::string::npos);
- EXPECT_NE(out.find("TEL:+15551234567"), std::string::npos);
- EXPECT_NE(out.find("on my way"), std::string::npos);
-
- // The originator vCard is empty and sits before the envelope; the recipient
- // vCard sits inside it.
- const size_t originator = out.find("BEGIN:VCARD");
- const size_t envelope = out.find("BEGIN:BENV");
- const size_t recipient = out.find("TEL:+15551234567");
- ASSERT_NE(envelope, std::string::npos);
- EXPECT_LT(originator, envelope) << "originator must be outside the envelope";
- EXPECT_LT(envelope, recipient) << "recipient must be inside the envelope";
-}
-
-// iOS chooses iMessage on its own; the type never changes, and nothing here can
-// force or observe that choice.
-TEST(BMessageBuild, AlwaysUsesSmsGsmEvenForAppleIdRecipients) {
- const std::string out = build_bmessage({email("[email protected]")}, "hi");
-
- EXPECT_NE(out.find("TYPE:SMS_GSM"), std::string::npos);
- EXPECT_NE(out.find("EMAIL:[email protected]"), std::string::npos);
- EXPECT_EQ(out.find("TEL:"), std::string::npos);
-}
-
-TEST(BMessageBuild, LengthCountsTheWholeMessageBlock) {
- const std::string out = build_bmessage({tel("+15551234567")}, "hello");
-
- const size_t length_at = out.find("LENGTH:");
- ASSERT_NE(length_at, std::string::npos);
- const size_t declared = std::stoul(out.substr(length_at + 7));
-
- const size_t begin = out.find("BEGIN:MSG");
- const size_t end = out.find("END:MSG");
- ASSERT_NE(begin, std::string::npos);
- ASSERT_NE(end, std::string::npos);
- const size_t actual = (end + std::string("END:MSG\r\n").size()) - begin;
- EXPECT_EQ(declared, actual);
-}
-
-// --- The trust boundary --------------------------------------------------
-//
-// Every case below is an address that, interpolated verbatim, would add a
-// recipient the user never chose.
-
-TEST(BMessageBuild, RejectsNewlineInjectedRecipient) {
- std::string err;
- EXPECT_FALSE(validate_recipient(tel("+15551234567\r\nTEL:+15559999999"), err));
- EXPECT_FALSE(err.empty());
-
- EXPECT_FALSE(validate_recipient(tel("+15551234567\nTEL:+15559999999"), err));
- EXPECT_FALSE(validate_recipient(email("[email protected]\r\nEMAIL:[email protected]"), err));
-}
-
-TEST(BMessageBuild, RejectsVCardDelimiters) {
- std::string err;
- EXPECT_FALSE(validate_recipient(email("[email protected];TYPE=WORK"), err));
- EXPECT_FALSE(validate_recipient(email("[email protected]:x"), err));
- EXPECT_FALSE(validate_recipient(email("[email protected],[email protected]"), err));
- EXPECT_FALSE(validate_recipient(email("a\\@b.com"), err));
-}
-
-TEST(BMessageBuild, RejectsControlCharacters) {
- std::string err;
- EXPECT_FALSE(validate_recipient(tel(std::string("+1555\x01"
- "234")),
- err));
- EXPECT_FALSE(validate_recipient(email(std::string("a@b\x7f.com")), err));
- EXPECT_FALSE(validate_recipient(tel("+1555\t234"), err));
-}
-
-// The builder refuses outright rather than escaping: a message that reaches
-// the wrong person cannot be taken back, so there is no partial success here.
-TEST(BMessageBuild, BuildRefusesAnInvalidRecipientEntirely) {
- EXPECT_EQ(build_bmessage({tel("+15551234567\r\nTEL:+15559999999")}, "hi"), "");
- EXPECT_EQ(build_bmessage({}, "hi"), "");
-
- // One bad recipient poisons the whole message, including the valid one.
- EXPECT_EQ(build_bmessage({tel("+15551234567"), email("[email protected]\r\nEMAIL:[email protected]")}, "hi"), "");
-}
-
-// The end-to-end proof: whatever an attacker puts in the address, the built
-// message must never contain more recipients than were asked for.
-TEST(BMessageBuild, InjectedRecipientNeverSurvivesIntoAParsedMessage) {
- const std::string out = build_bmessage({tel("+15551234567")}, "hi");
- ASSERT_FALSE(out.empty());
-
- BMessage parsed = parse_bmessage(out);
- ASSERT_TRUE(parsed.valid);
- ASSERT_EQ(parsed.recipients.size(), 1u);
- EXPECT_EQ(parsed.recipients[0].tel, "+15551234567");
-}
-
-TEST(BMessageBuild, AcceptsAddressesPeopleActuallyWrite) {
- std::string err;
- EXPECT_TRUE(validate_recipient(tel("+1 (555) 123-4567"), err)) << err;
- EXPECT_TRUE(validate_recipient(tel("5551234567"), err)) << err;
- EXPECT_TRUE(validate_recipient(email("[email protected]"), err)) << err;
-}
-
-TEST(BMessageBuild, RejectsAddressesThatAreNotAddresses) {
- std::string err;
- EXPECT_FALSE(validate_recipient(tel(""), err));
- EXPECT_FALSE(validate_recipient(tel("no-digits-here"), err));
- EXPECT_FALSE(validate_recipient(email("missing-at-sign"), err));
- EXPECT_FALSE(validate_recipient(email("two@[email protected]"), err));
- EXPECT_FALSE(validate_recipient(email("@nolocal.com"), err));
- EXPECT_FALSE(validate_recipient(email("nodomain@"), err));
- EXPECT_FALSE(validate_recipient(tel(std::string(300, '5')), err)) << "absurd length must not reach the phone";
-}
-
-// --- Byte stuffing -------------------------------------------------------
-
-TEST(BMessageBuild, StuffsBodyLinesThatLookStructural) {
- const std::string out = build_bmessage({tel("+15551234567")}, "END:MSG");
-
- // Exactly one real terminator: the body's copy is stuffed and does not end
- // the message early.
- EXPECT_EQ(count_occurrences(out, "\r\nEND:MSG\r\n"), 1u);
- EXPECT_NE(out.find(" END:MSG"), std::string::npos);
-}
-
-TEST(BMessageBuild, StuffedBodySurvivesARoundTrip) {
- for (const std::string& body : {std::string("END:MSG"),
- std::string("BEGIN:VCARD"),
- std::string("line one\nEND:BMSG\nline three"),
- std::string(" BEGIN:MSG"),
- std::string("begin:msg")}) {
- const std::string out = build_bmessage({tel("+15551234567")}, body);
- ASSERT_FALSE(out.empty()) << body;
-
- BMessage parsed = parse_bmessage(out);
- EXPECT_TRUE(parsed.valid) << body;
- EXPECT_EQ(parsed.body, body) << "body must survive stuffing and unstuffing unchanged";
- EXPECT_EQ(parsed.recipients.size(), 1u) << "a body that looks like a vCard must not become a recipient";
- }
-}
-
-TEST(BMessageBuild, PreservesUtf8Bodies) {
- const std::string body = "emoji \xF0\x9F\x92\xA9 and accents \xC3\xA9\xC3\xA8";
- BMessage parsed = parse_bmessage(build_bmessage({tel("+15551234567")}, body));
-
- EXPECT_TRUE(parsed.valid);
- EXPECT_EQ(parsed.body, body);
-}
-
-TEST(BMessageBuild, HandlesMultiLineAndEmptyBodies) {
- BMessage multi = parse_bmessage(build_bmessage({tel("+15551234567")}, "one\ntwo\nthree"));
- EXPECT_EQ(multi.body, "one\ntwo\nthree");
-
- BMessage empty = parse_bmessage(build_bmessage({tel("+15551234567")}, ""));
- EXPECT_TRUE(empty.valid);
- EXPECT_EQ(empty.body, "");
-}
-
-// --- Thread keys ---------------------------------------------------------
-
-TEST(BMessageBuild, ParsesRecipientsFromThreadKeys) {
- Recipient out;
- std::string err;
-
- ASSERT_TRUE(recipient_from_thread_key("tel:+15551234567", out, err)) << err;
- EXPECT_EQ(out.kind, RecipientKind::Tel);
- EXPECT_EQ(out.address, "+15551234567");
-
- ASSERT_TRUE(recipient_from_thread_key("email:[email protected]", out, err)) << err;
- EXPECT_EQ(out.kind, RecipientKind::Email);
- EXPECT_EQ(out.address, "[email protected]");
-}
-
-// Group threads need their own routing rules, so replying to one must fail
-// closed rather than guessing a recipient set.
-TEST(BMessageBuild, RefusesThreadKeysItDoesNotUnderstand) {
- Recipient out;
- std::string err;
-
- EXPECT_FALSE(recipient_from_thread_key("group:weekend-trip", out, err));
- EXPECT_FALSE(err.empty());
- EXPECT_FALSE(recipient_from_thread_key("+15551234567", out, err));
- EXPECT_FALSE(recipient_from_thread_key("", out, err));
- EXPECT_FALSE(recipient_from_thread_key("tel:+1555\r\nTEL:+1999", out, err))
- << "an injected key must not pass just because its prefix is known";
-}
diff --git a/test/test_bt_diagnostics.cpp b/test/test_bt_diagnostics.cpp
deleted file mode 100644
index 087c079..0000000
--- a/test/test_bt_diagnostics.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-#include "tether/bluetooth/diagnostics.hpp"
-
-#include <cstdlib>
-#include <gtest/gtest.h>
-
-using namespace tether::bluetooth;
-
-TEST(BtDiagnostics, RedactsBareAddress) {
- Redactor r;
- EXPECT_EQ(r.text("connecting to 60:57:C8:30:6A:F7"), "connecting to <address-1>");
-}
-
-TEST(BtDiagnostics, RedactsDeviceNodeInObjectPath) {
- Redactor r;
- EXPECT_EQ(r.text("/org/bluez/hci0/dev_60_57_C8_30_6A_F7"), "/org/bluez/hci0/dev_<address-1>");
-}
-
-TEST(BtDiagnostics, SameDeviceGetsSamePlaceholderAcrossSpellings) {
- Redactor r;
- const std::string out = r.text("dev_60_57_C8_30_6A_F7 is 60:57:c8:30:6a:f7");
- EXPECT_EQ(out, "dev_<address-1> is <address-1>");
-}
-
-TEST(BtDiagnostics, DistinctDevicesGetDistinctPlaceholders) {
- Redactor r;
- const std::string out = r.text("AA:BB:CC:DD:EE:FF and 11:22:33:44:55:66");
- EXPECT_EQ(out, "<address-1> and <address-2>");
-}
-
-TEST(BtDiagnostics, RedactsEmailAndPhoneNumber) {
- Redactor r;
- EXPECT_EQ(r.text("sent to tel:+15035550101"), "sent to tel:<number-1>");
- EXPECT_EQ(r.text("sent to [email protected]"), "sent to <email-1>");
-}
-
-TEST(BtDiagnostics, LeavesTimestampsAndErrorCodesAlone) {
- Redactor r;
- const std::string out = r.text("2026-08-16T10:11:12 failed with 0x43 after 30000 ms");
- EXPECT_EQ(out, "2026-08-16T10:11:12 failed with 0x43 after 30000 ms");
-}
-
-TEST(BtDiagnostics, RedactsHomeAndRuntimeDirectories) {
- setenv("HOME", "/home/someone", 1);
- setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1);
- Redactor r;
- EXPECT_EQ(r.text("staged /run/user/1000/tether/out.bmsg"), "staged <runtime>/tether/out.bmsg");
- EXPECT_EQ(r.text("wrote /home/someone/.config/tether/bluetooth.json"),
- "wrote <home>/.config/tether/bluetooth.json");
-}
-
-TEST(BtDiagnostics, RedactsRuntimeDirectoryWithoutTheEnvironmentVariable) {
- unsetenv("XDG_RUNTIME_DIR");
- Redactor r;
- EXPECT_EQ(r.text("/run/user/4242/tether/tetherd.sock"), "<runtime>/tether/tetherd.sock");
-}
-
-TEST(BtDiagnostics, DropsContentKeysRatherThanRedactingThem) {
- Redactor r;
- const nlohmann::json in = {
- {"command", "bt_message"},
- {"body", "meet me at the usual place"},
- {"sender", "Jane"},
- {"name", "Jane's iPhone"},
- {"address", "60:57:C8:30:6A:F7"},
- };
-
- const nlohmann::json out = r.value(in);
- EXPECT_FALSE(out.contains("body"));
- EXPECT_FALSE(out.contains("sender"));
- EXPECT_FALSE(out.contains("name"));
- EXPECT_EQ(out["address"], "<address-1>");
-}
-
-TEST(BtDiagnostics, RedactsNestedStructures) {
- Redactor r;
- const nlohmann::json in = {{"adapters", {{{"path", "/org/bluez/hci0"}, {"address", "AA:BB:CC:DD:EE:FF"}}}}};
- const nlohmann::json out = r.value(in);
- EXPECT_EQ(out["adapters"][0]["address"], "<address-1>");
- EXPECT_EQ(out["adapters"][0]["path"], "/org/bluez/hci0");
-}
-
-TEST(BtDiagnostics, TimelineKeepsOnlyStateEvents) {
- clear_diagnostic_timeline();
- record_diagnostic_event({{"command", "bt_pair_progress"}, {"step", "connect"}});
- record_diagnostic_event({{"command", "bt_message"}, {"body", "hello"}});
- record_diagnostic_event({{"command", "clipboard_updated"}, {"content", "hello"}});
-
- const auto timeline = diagnostic_timeline();
- ASSERT_EQ(timeline.size(), 1u);
- EXPECT_EQ(timeline[0]["command"], "bt_pair_progress");
-}
-
-TEST(BtDiagnostics, TimelineStripsContentAtRecordTime) {
- clear_diagnostic_timeline();
- record_diagnostic_event({{"command", "bt_send_result"}, {"success", true}, {"body", "secret"}});
-
- const auto timeline = diagnostic_timeline();
- ASSERT_EQ(timeline.size(), 1u);
- EXPECT_FALSE(timeline[0].contains("body"));
- EXPECT_TRUE(timeline[0]["success"]);
-}
-
-TEST(BtDiagnostics, TimelineIsOrderedAndMonotonic) {
- clear_diagnostic_timeline();
- record_diagnostic_event({{"command", "bt_pair_progress"}, {"step", "first"}});
- record_diagnostic_event({{"command", "bt_pair_progress"}, {"step", "second"}});
-
- const auto timeline = diagnostic_timeline();
- ASSERT_EQ(timeline.size(), 2u);
- EXPECT_EQ(timeline[0]["step"], "first");
- EXPECT_EQ(timeline[1]["step"], "second");
- EXPECT_LE(timeline[0]["at_ms"].get<int64_t>(), timeline[1]["at_ms"].get<int64_t>());
-}
-
-TEST(BtDiagnostics, TimelineIsBounded) {
- clear_diagnostic_timeline();
- for (int i = 0; i < 500; ++i)
- record_diagnostic_event({{"command", "bt_pair_progress"}, {"step", std::to_string(i)}});
-
- const auto timeline = diagnostic_timeline();
- EXPECT_EQ(timeline.size(), 200u);
- // The oldest entries are the ones dropped.
- EXPECT_EQ(timeline.back()["step"], "499");
-}
-
-TEST(BtDiagnostics, ReportCarriesNoAddressOrContent) {
- clear_diagnostic_timeline();
- record_diagnostic_event({{"command", "bt_connection_changed"},
- {"link_reason", "Connecting to 60:57:C8:30:6A:F7"},
- {"map_open", false}});
-
- const nlohmann::json status = {{"adapters", {{{"address", "AA:BB:CC:DD:EE:FF"}, {"name", "someone-laptop"}}}}};
- const nlohmann::json connection = {{"link_reason", "no route to 60:57:C8:30:6A:F7"}};
-
- const std::string dumped = build_diagnostics(status, connection).dump();
- EXPECT_EQ(dumped.find("60:57:C8:30:6A:F7"), std::string::npos);
- EXPECT_EQ(dumped.find("AA:BB:CC:DD:EE:FF"), std::string::npos);
- EXPECT_EQ(dumped.find("someone-laptop"), std::string::npos);
-}
diff --git a/test/test_groups.cpp b/test/test_groups.cpp
deleted file mode 100644
index d73720a..0000000
--- a/test/test_groups.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/groups.hpp>
-
-using namespace tether::bluetooth;
-
-namespace {
-
- ContactStore contacts_with(const std::string& vcards) {
- ContactStore store;
- store.set(parse_vcards(vcards));
- return store;
- }
-
- MessageNotification notification(const std::string& sender,
- const std::string& subtitle,
- const std::string& body,
- int64_t received) {
- return MessageNotification{sender, subtitle, body, received};
- }
-
-} // namespace
-
-// --- Parsing the side channel -------------------------------------------
-
-TEST(Groups, ParsesAnUnnamedGroupSubtitle) {
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "To you & Bob", info));
-
- EXPECT_TRUE(info.is_group);
- EXPECT_FALSE(info.named);
- EXPECT_EQ(info.sender, "Alice");
- ASSERT_EQ(info.participants.size(), 1u);
- EXPECT_EQ(info.participants[0], "Bob") << "the user is a member but never a reply recipient";
-}
-
-TEST(Groups, ParsesLongerParticipantLists) {
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "To you, Bob & Carol", info));
- ASSERT_EQ(info.participants.size(), 2u);
- EXPECT_EQ(info.participants[0], "Bob");
- EXPECT_EQ(info.participants[1], "Carol");
-
- ASSERT_TRUE(parse_group_notification("Alice", "To Bob, Carol & you", info));
- ASSERT_EQ(info.participants.size(), 2u);
-}
-
-TEST(Groups, ParsesANamedGroup) {
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "Weekend Trip", info));
-
- EXPECT_TRUE(info.named);
- EXPECT_EQ(info.name, "Weekend Trip");
- EXPECT_TRUE(info.participants.empty()) << "a group name carries no member list";
-}
-
-TEST(Groups, TreatsAOneToOneNotificationAsNotAGroup) {
- GroupInfo info;
- EXPECT_FALSE(parse_group_notification("Alice", "", info));
- EXPECT_FALSE(parse_group_notification("Alice", "To you", info)) << "only the user means no other members";
-}
-
-// iOS supplies a name but no conversation identifier, so two groups sharing a
-// name collapse into one local thread. That is a documented limitation, and the
-// key has to make it visible rather than pretend otherwise.
-TEST(Groups, NamedGroupsWithTheSameNameShareAKey) {
- GroupInfo first;
- GroupInfo second;
- ASSERT_TRUE(parse_group_notification("Alice", "Weekend Trip", first));
- ASSERT_TRUE(parse_group_notification("Bob", "weekend trip", second));
-
- EXPECT_EQ(group_thread_key(first), group_thread_key(second));
-}
-
-TEST(Groups, UnnamedGroupKeyDoesNotDependOnMemberOrder) {
- GroupInfo first;
- GroupInfo second;
- ASSERT_TRUE(parse_group_notification("Alice", "To you, Bob & Carol", first));
- ASSERT_TRUE(parse_group_notification("Carol", "To Bob, you & Alice", second));
-
- EXPECT_NE(group_thread_key(first), group_thread_key(second))
- << "different member sets are different conversations";
-
- GroupInfo reordered;
- ASSERT_TRUE(parse_group_notification("Alice", "To Carol, you & Bob", reordered));
- EXPECT_EQ(group_thread_key(first), group_thread_key(reordered));
-}
-
-// --- Correlation ---------------------------------------------------------
-
-TEST(Groups, CorrelatesAMessageToItsNotification) {
- GroupCorrelator correlator;
- correlator.observe(notification("Alice", "To you & Bob", "dinner at seven", 100));
-
- GroupInfo info;
- EXPECT_EQ(correlator.correlate("dinner at seven", 105, info), Correlation::Matched);
- EXPECT_EQ(info.sender, "Alice");
-}
-
-// ANCS bodies are capped at what was requested, so a longer MAP body matches
-// the notification as a prefix.
-TEST(Groups, MatchesALongerBodyByItsPrefix) {
- GroupCorrelator correlator;
- correlator.observe(notification("Alice", "To you & Bob", "the first part of a long", 100));
-
- GroupInfo info;
- EXPECT_EQ(correlator.correlate("the first part of a long message that kept going", 101, info),
- Correlation::Matched);
-}
-
-TEST(Groups, IgnoresNotificationsOutsideTheWindow) {
- GroupCorrelator correlator;
- correlator.observe(notification("Alice", "To you & Bob", "hello", 100));
-
- GroupInfo info;
- EXPECT_EQ(correlator.correlate("hello", 100 + GROUP_CORRELATION_WINDOW_SECONDS + 1, info), Correlation::NoMatch);
-}
-
-// Two notifications carrying the same text cannot be told apart, and guessing
-// would aim a reply at the wrong people.
-TEST(Groups, RefusesAmbiguousRepeatedBodies) {
- GroupCorrelator correlator;
- correlator.observe(notification("Alice", "To you & Bob", "ok", 100));
- correlator.observe(notification("Carol", "Weekend Trip", "ok", 101));
-
- GroupInfo info;
- EXPECT_EQ(correlator.correlate("ok", 102, info), Correlation::Ambiguous);
-}
-
-TEST(Groups, ReportsNoMatchForAnUnrelatedMessage) {
- GroupCorrelator correlator;
- correlator.observe(notification("Alice", "To you & Bob", "hello", 100));
-
- GroupInfo info;
- EXPECT_EQ(correlator.correlate("something else entirely", 101, info), Correlation::NoMatch);
-}
-
-TEST(Groups, ExpiryDropsStaleNotifications) {
- GroupCorrelator correlator;
- correlator.observe(notification("Alice", "To you & Bob", "hello", 100));
- correlator.expire(100 + GROUP_CORRELATION_WINDOW_SECONDS + 1);
- EXPECT_EQ(correlator.size(), 0u);
-}
-
-// --- Reply routing -------------------------------------------------------
-
-TEST(Groups, ResolvesAnUnnamedGroupWhenEveryNameIsUnambiguous) {
- auto contacts = contacts_with(
- "BEGIN:VCARD\nFN:Bob\nTEL:+15550000002\nEND:VCARD\n"
- "BEGIN:VCARD\nFN:Carol\nTEL:+15550000003\nEND:VCARD\n");
-
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "To you, Bob & Carol", info));
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(info, group_thread_key(info), contacts, GroupRoster{}, true, recipients, reason),
- ReplyEligibility::Allowed)
- << reason;
- EXPECT_EQ(recipients.size(), 2u);
-}
-
-// A name matching two contacts must never be resolved by picking one: the
-// message would go to a stranger.
-TEST(Groups, RefusesAnAmbiguousParticipantName) {
- auto contacts = contacts_with(
- "BEGIN:VCARD\nFN:Bob\nTEL:+15550000002\nEND:VCARD\n"
- "BEGIN:VCARD\nFN:Bob\nTEL:+15559999999\nEND:VCARD\n");
-
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "To you & Bob", info));
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(info, group_thread_key(info), contacts, GroupRoster{}, true, recipients, reason),
- ReplyEligibility::Unresolved);
- EXPECT_TRUE(recipients.empty()) << "a refused resolution must leave no partial recipient set";
-}
-
-TEST(Groups, RefusesAnUnknownParticipantName) {
- auto contacts = contacts_with("BEGIN:VCARD\nFN:Bob\nTEL:+15550000002\nEND:VCARD\n");
-
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "To you, Bob & Dave", info));
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(info, group_thread_key(info), contacts, GroupRoster{}, true, recipients, reason),
- ReplyEligibility::Unresolved);
- EXPECT_TRUE(recipients.empty());
-}
-
-// A named group identifies the conversation but gives no roster, so it stays
-// read-only until the user provides one.
-TEST(Groups, NamedGroupsAreReadOnlyWithoutARoster) {
- auto contacts = contacts_with("BEGIN:VCARD\nFN:Bob\nTEL:+15550000002\nEND:VCARD\n");
-
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "Weekend Trip", info));
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(info, group_thread_key(info), contacts, GroupRoster{}, true, recipients, reason),
- ReplyEligibility::NeedsRoster);
- EXPECT_TRUE(recipients.empty());
-}
-
-TEST(Groups, ARosterMakesANamedGroupRepliable) {
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "Weekend Trip", info));
- const std::string key = group_thread_key(info);
-
- GroupRoster roster;
- roster.set(key, {"tel:+15550000002", "email:[email protected]"});
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(info, key, ContactStore{}, roster, true, recipients, reason),
- ReplyEligibility::Allowed)
- << reason;
- ASSERT_EQ(recipients.size(), 2u);
- EXPECT_EQ(recipients[0].kind, RecipientKind::Tel);
- EXPECT_EQ(recipients[1].kind, RecipientKind::Email);
-}
-
-// The roster is user-supplied text, and it lands in a bMessage as structure.
-TEST(Groups, RefusesARosterEntryThatCouldInjectARecipient) {
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "Weekend Trip", info));
- const std::string key = group_thread_key(info);
-
- GroupRoster roster;
- roster.set(key, {"tel:+1555\r\nTEL:+15559999999"});
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(info, key, ContactStore{}, roster, true, recipients, reason),
- ReplyEligibility::Unresolved);
- EXPECT_TRUE(recipients.empty());
-}
-
-// Group membership lives only in memory, so after a restart a group thread has
-// no known members until the phone sends another message. Replying then would
-// be routing to nobody, and must not silently succeed.
-TEST(Groups, AnUnidentifiedThreadCannotBeRepliedTo) {
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(resolve_group_recipients(
- GroupInfo{}, "group:name:weekend-trip", ContactStore{}, GroupRoster{}, true, recipients, reason),
- ReplyEligibility::NeedsRoster);
- EXPECT_TRUE(recipients.empty());
- EXPECT_FALSE(reason.empty());
-}
-
-TEST(Groups, RepliesAreOffUntilEnabled) {
- GroupInfo info;
- ASSERT_TRUE(parse_group_notification("Alice", "To you & Bob", info));
-
- std::vector<Recipient> recipients;
- std::string reason;
- EXPECT_EQ(
- resolve_group_recipients(info, group_thread_key(info), ContactStore{}, GroupRoster{}, false, recipients, reason),
- ReplyEligibility::Disabled);
-}
-
-// iOS reports nothing when a member is silently added, so an unfamiliar sender
-// is the only evidence that a roster has gone stale.
-TEST(Groups, AnUnknownSenderInvalidatesTheRoute) {
- std::vector<Recipient> recipients{{RecipientKind::Tel, "+15550000002"},
- {RecipientKind::Tel, "+15550000003"}};
-
- EXPECT_FALSE(sender_invalidates_route("tel:+15550000002", recipients));
- EXPECT_TRUE(sender_invalidates_route("tel:+15557654321", recipients));
- EXPECT_TRUE(sender_invalidates_route("email:[email protected]", recipients));
-}
-
-TEST(Groups, RosterSurvivesARoundTrip) {
- GroupRoster roster;
- roster.set("group:name:weekend-trip", {"tel:+15550000002"});
-
- GroupRoster restored = GroupRoster::deserialize(roster.serialize());
- const auto* addresses = restored.find("group:name:weekend-trip");
- ASSERT_NE(addresses, nullptr);
- ASSERT_EQ(addresses->size(), 1u);
- EXPECT_EQ((*addresses)[0], "tel:+15550000002");
-}
-
-// A corrupt roster must leave groups read-only rather than routing a reply to
-// whatever happened to survive parsing.
-TEST(Groups, CorruptRosterResolvesToNothing) {
- EXPECT_TRUE(GroupRoster::deserialize("{not json").empty());
- EXPECT_TRUE(GroupRoster::deserialize("[]").empty());
- EXPECT_TRUE(GroupRoster::deserialize("").empty());
-}
diff --git a/test/test_journal.cpp b/test/test_journal.cpp
deleted file mode 100644
index 47feec6..0000000
--- a/test/test_journal.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/journal.hpp>
-
-using namespace tether::bluetooth;
-
-namespace {
-
- Message make(const std::string& handle, int64_t timestamp, const std::string& body = "hi") {
- Message m;
- m.handle = handle;
- m.thread_key = "tel:+15551234567";
- m.peer_address = "+15551234567";
- m.body = body;
- m.timestamp = timestamp;
- m.folder = "inbox";
- return m;
- }
-
- constexpr int64_t NOW = 1786848300;
- constexpr int64_t DAY = 24 * 3600;
-
-} // namespace
-
-TEST(Journal, RoundTripsAMessage) {
- Message original = make("/msg/1", NOW, "hello \xF0\x9F\x92\xA9");
- original.read = true;
- original.outgoing = true;
-
- Message restored;
- ASSERT_TRUE(deserialize_message_line(serialize_message_line(original), restored));
- EXPECT_EQ(restored, original);
-}
-
-TEST(Journal, SerializesToASingleLine) {
- const std::string line = serialize_message_line(make("/msg/1", NOW, "two\nlines"));
- EXPECT_EQ(line.find('\n'), std::string::npos) << "an embedded newline would split one record into two";
-}
-
-// One bad write must not cost the whole history, so unreadable lines are
-// skipped rather than aborting the load.
-TEST(Journal, RejectsMalformedLines) {
- Message out;
- EXPECT_FALSE(deserialize_message_line("", out));
- EXPECT_FALSE(deserialize_message_line("{not json", out));
- EXPECT_FALSE(deserialize_message_line("[]", out));
- EXPECT_FALSE(deserialize_message_line("{\"body\":\"orphan\"}", out)) << "no handle means it can never dedupe";
- EXPECT_FALSE(deserialize_message_line("{\"handle\":\"/m/1\"}", out)) << "no thread key means it belongs nowhere";
-}
-
-TEST(Journal, RetentionDropsMessagesPastTheAgeLimit) {
- std::vector<Message> messages{
- make("/msg/old", NOW - 120 * DAY),
- make("/msg/recent", NOW - DAY),
- };
-
- auto kept = apply_retention(messages, NOW);
- ASSERT_EQ(kept.size(), 1u);
- EXPECT_EQ(kept[0].handle, "/msg/recent");
-}
-
-TEST(Journal, RetentionKeepsTheNewestWhenOverCount) {
- std::vector<Message> messages;
- for (int i = 0; i < 10; ++i)
- messages.push_back(make("/msg/" + std::to_string(i), NOW - (10 - i)));
-
- auto kept = apply_retention(messages, NOW, 3);
- ASSERT_EQ(kept.size(), 3u);
- EXPECT_EQ(kept[0].handle, "/msg/7");
- EXPECT_EQ(kept[2].handle, "/msg/9");
-}
-
-// MAP sometimes supplies no usable timestamp. Treating zero as 1970 would evict
-// those messages instantly, which is worse than keeping them.
-TEST(Journal, RetentionKeepsUndatedMessages) {
- std::vector<Message> messages{make("/msg/undated", 0)};
-
- auto kept = apply_retention(messages, NOW);
- ASSERT_EQ(kept.size(), 1u);
- EXPECT_EQ(kept[0].handle, "/msg/undated");
-}
-
-TEST(Journal, RetentionIsANoOpUnderBothLimits) {
- std::vector<Message> messages{make("/msg/1", NOW - DAY), make("/msg/2", NOW)};
- EXPECT_EQ(apply_retention(messages, NOW).size(), 2u);
-}
-
-// The journal is append-only and a reconnect re-lists everything, so the same
-// message is written more than once. Without collapsing, history doubles on
-// every reconnect.
-TEST(Journal, RetentionCollapsesRepeatedHandles) {
- Message first = make("/msg/1", NOW);
- Message again = make("/msg/1", NOW);
- again.read = true;
-
- auto kept = apply_retention({first, again}, NOW);
- ASSERT_EQ(kept.size(), 1u);
- EXPECT_TRUE(kept[0].read) << "the newest copy carries the current read state";
-}
diff --git a/test/test_vcard.cpp b/test/test_vcard.cpp
deleted file mode 100644
index 8170f5e..0000000
--- a/test/test_vcard.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-#include <gtest/gtest.h>
-#include <tether/bluetooth/contacts.hpp>
-#include <tether/bluetooth/messages.hpp>
-#include <tether/bluetooth/vcard.hpp>
-
-using namespace tether::bluetooth;
-
-TEST(VCard, ParsesNameTelAndEmail) {
- auto cards = parse_vcards(
- "BEGIN:VCARD\r\n"
- "VERSION:3.0\r\n"
- "FN:Ada Lovelace\r\n"
- "TEL;TYPE=CELL:+15551234567\r\n"
- "EMAIL;TYPE=INTERNET:[email protected]\r\n"
- "END:VCARD\r\n");
-
- ASSERT_EQ(cards.size(), 1u);
- EXPECT_EQ(cards[0].name, "Ada Lovelace");
- ASSERT_EQ(cards[0].tels.size(), 1u);
- EXPECT_EQ(cards[0].tels[0], "+15551234567");
- ASSERT_EQ(cards[0].emails.size(), 1u);
- EXPECT_EQ(cards[0].emails[0], "[email protected]");
-}
-
-// A contact reachable at several numbers is the normal case, not an edge case:
-// keeping only the first would silently lose the address a thread is keyed on.
-TEST(VCard, KeepsEveryTelAndEmail) {
- auto cards = parse_vcards(
- "BEGIN:VCARD\n"
- "FN:Grace Hopper\n"
- "TEL;TYPE=CELL:+15550000001\n"
- "TEL;TYPE=HOME:+15550000002\n"
- "EMAIL:[email protected]\n"
- "EMAIL:[email protected]\n"
- "END:VCARD\n");
-
- ASSERT_EQ(cards.size(), 1u);
- EXPECT_EQ(cards[0].tels.size(), 2u);
- EXPECT_EQ(cards[0].emails.size(), 2u);
-}
-
-TEST(VCard, ParsesMultipleCards) {
- auto cards = parse_vcards(
- "BEGIN:VCARD\nFN:One\nTEL:+1555000001\nEND:VCARD\n"
- "BEGIN:VCARD\nFN:Two\nTEL:+1555000002\nEND:VCARD\n");
-
- ASSERT_EQ(cards.size(), 2u);
- EXPECT_EQ(cards[0].name, "One");
- EXPECT_EQ(cards[1].name, "Two");
-}
-
-// RFC 2425 folding splits long values across lines; without unfolding, a long
-// name or address is silently truncated at the fold.
-TEST(VCard, UnfoldsContinuationLines) {
- auto cards = parse_vcards(
- "BEGIN:VCARD\r\n"
- "FN:A Very Long Contact\r\n"
- " Name Indeed\r\n"
- "TEL:+1555\r\n"
- " 0000001\r\n"
- "END:VCARD\r\n");
-
- ASSERT_EQ(cards.size(), 1u);
- EXPECT_EQ(cards[0].name, "A Very Long Contact Name Indeed");
- ASSERT_EQ(cards[0].tels.size(), 1u);
- EXPECT_EQ(cards[0].tels[0], "+15550000001");
-}
-
-TEST(VCard, FallsBackToStructuredName) {
- auto cards = parse_vcards("BEGIN:VCARD\nN:Lovelace;Ada;;;\nTEL:+1555\nEND:VCARD\n");
-
- ASSERT_EQ(cards.size(), 1u);
- EXPECT_EQ(cards[0].name, "Ada Lovelace");
-}
-
-TEST(VCard, PrefersFormattedNameOverStructured) {
- auto cards = parse_vcards("BEGIN:VCARD\nN:Lovelace;Ada;;;\nFN:Countess Ada\nTEL:+1555\nEND:VCARD\n");
-
- ASSERT_EQ(cards.size(), 1u);
- EXPECT_EQ(cards[0].name, "Countess Ada");
-}
-
-TEST(VCard, UnescapesValues) {
- auto cards = parse_vcards("BEGIN:VCARD\nFN:Smith\\, Alice\nTEL:+1555\nEND:VCARD\n");
-
- ASSERT_EQ(cards.size(), 1u);
- EXPECT_EQ(cards[0].name, "Smith, Alice");
-}
-
-TEST(VCard, IgnoresMalformedInput) {
- EXPECT_TRUE(parse_vcards("").empty());
- EXPECT_TRUE(parse_vcards("not a vcard at all").empty());
- EXPECT_TRUE(parse_vcards("BEGIN:VCARD\nEND:VCARD\n").empty()) << "an empty card carries nothing to store";
-}
-
-// A card cut off mid-transfer should still yield what it had rather than
-// swallowing the card that follows it.
-TEST(VCard, RecoversFromUnterminatedCard) {
- auto cards = parse_vcards(
- "BEGIN:VCARD\nFN:First\nTEL:+1555000001\n"
- "BEGIN:VCARD\nFN:Second\nTEL:+1555000002\nEND:VCARD\n");
-
- ASSERT_EQ(cards.size(), 2u);
- EXPECT_EQ(cards[0].name, "First");
- EXPECT_EQ(cards[1].name, "Second");
-}
-
-TEST(ContactStore, ResolvesNamesByTelAndEmail) {
- ContactStore store;
- store.set(parse_vcards("BEGIN:VCARD\nFN:Ada\nTEL:+1 (555) 123-4567\nEMAIL:[email protected]\nEND:VCARD\n"));
-
- EXPECT_EQ(store.name_for("tel:+15551234567"), "Ada");
- EXPECT_EQ(store.name_for("email:[email protected]"), "Ada");
- EXPECT_EQ(store.name_for("tel:+15559999999"), "");
-}
-
-// Tether never invents a country code, so the two forms stay distinct keys. A
-// contact stored one way must not silently label the other.
-TEST(ContactStore, DoesNotEquateNationalAndE164Forms) {
- ContactStore store;
- store.set(parse_vcards("BEGIN:VCARD\nFN:Ada\nTEL:+15551234567\nEND:VCARD\n"));
-
- EXPECT_EQ(store.name_for("tel:+15551234567"), "Ada");
- EXPECT_EQ(store.name_for("tel:5551234567"), "");
-}
-
-TEST(ContactStore, SurvivesJsonRoundTrip) {
- ContactStore store;
- store.set(parse_vcards("BEGIN:VCARD\nFN:Ada\nTEL:+15551234567\nEMAIL:[email protected]\nEND:VCARD\n"));
-
- ContactStore restored = deserialize_contacts(serialize_contacts(store));
- EXPECT_EQ(restored.size(), store.size());
- EXPECT_EQ(restored.name_for("tel:+15551234567"), "Ada");
- EXPECT_EQ(restored.name_for("email:[email protected]"), "Ada");
-}
-
-TEST(ContactStore, CorruptCacheYieldsEmptyStore) {
- EXPECT_EQ(deserialize_contacts("{not json").size(), 0u);
- EXPECT_EQ(deserialize_contacts("").size(), 0u);
-}
-
-// A contact with no name still contributes nothing to display, but must not
-// index an empty label over a valid one.
-TEST(ContactStore, SkipsUnnamedContacts) {
- ContactStore store;
- store.set(parse_vcards("BEGIN:VCARD\nTEL:+15551234567\nEND:VCARD\n"));
-
- EXPECT_EQ(store.name_for("tel:+15551234567"), "");
-}
-
-// A re-listing after reconnect carries the same message under a new object path.
-// The store must adopt the new path, or acting on the message uses a dead one.
-TEST(MessageStore, RefreshesObjectPathOnRelist) {
- MessageStore store;
- Message first;
- first.handle = "42";
- first.thread_key = "tel:+15551234567";
- first.object_path = "/org/bluez/obex/client/session5/message42";
- EXPECT_TRUE(store.add(first));
-
- Message again = first;
- again.object_path = "/org/bluez/obex/client/session11/message42";
- EXPECT_FALSE(store.add(again)) << "same handle is still a duplicate";
-
- ASSERT_NE(store.find("42"), nullptr);
- EXPECT_EQ(store.find("42")->object_path, "/org/bluez/obex/client/session11/message42");
-}