Skip to content

Linux + iPhone Continuity / iMessage / SMS

Add headless OCI container runtime support

Nick Pisanid408ee87f58c
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..16dcff7
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,13 @@
+.git
+.direnv
+.scratch
+build
+build-*
+result
+result-*
+**/node_modules
+**/.DS_Store
+**/*.swp
+**/*.swo
+.env
+packaging/container/.env
diff --git a/.github/workflows/container.yml b/.github/workflows/container.yml
new file mode 100644
index 0000000..dcb27aa
--- /dev/null
+++ b/.github/workflows/container.yml
@@ -0,0 +1,54 @@
+name: container
+
+on:
+ pull_request:
+ push:
+ branches: [main, develop]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ container:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: ubuntu-24.04
+ platform: linux/amd64
+ arch: amd64
+ - runner: ubuntu-24.04-arm
+ platform: linux/arm64
+ arch: arm64
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+ - name: Build and test (non-root, native architecture)
+ shell: bash
+ run: |
+ docker build --progress=plain --platform '${{ matrix.platform }}' \
+ --build-arg TETHER_VERSION="$(git describe --tags --always)" \
+ --target test -f packaging/container/Dockerfile -t tether-tests:ci . \
+ 2>&1 | tee "$RUNNER_TEMP/tether-tests.log"
+ - name: Build runtime
+ shell: bash
+ run: |
+ docker build --progress=plain --platform '${{ matrix.platform }}' \
+ --build-arg TETHER_VERSION="$(git describe --tags --always)" \
+ --target runtime -f packaging/container/Dockerfile -t tether-runtime:ci . \
+ 2>&1 | tee "$RUNNER_TEMP/tether-runtime.log"
+ - name: Smoke test without host hardware or services
+ shell: bash
+ run: |
+ bash -n packaging/container/entrypoint.sh packaging/container/healthcheck.sh scripts/test-container.sh
+ scripts/test-container.sh tether-runtime:ci tether-tests:ci \
+ 2>&1 | tee "$RUNNER_TEMP/tether-smoke.log"
+ - name: Failure evidence (synthetic test data only)
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: container-${{ matrix.arch }}-logs
+ path: ${{ runner.temp }}/tether-*.log
+ retention-days: 7
diff --git a/.gitignore b/.gitignore
index 16812ed..4674a37 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@ _CPack_Packages
*.rpm
*.tar.gz
.idea
+packaging/container/.env
diff --git a/README.md b/README.md
index a3e274a..1f094ce 100644
--- a/README.md
+++ b/README.md
@@ -197,6 +197,17 @@ does not start a daemon. Firewall opening is opt-in. Bluetooth experimental
mode and adapter class changes are also opt-in. If your system uses another
adapter or multiple adapters, change `bluetooth.adapters` accordingly.
+### Container (local build)
+
+A headless Linux Docker deployment is available for amd64 and arm64. It runs
+`tetherd` and its session services as non-root, using the host's BlueZ/Avahi and
+persistent state/download mounts. Pair and send messages/files through the CLI;
+there is no web UI yet. Bluetooth messaging still needs the iPhone near the host.
+
+See [docs/CONTAINER.md](docs/CONTAINER.md) for prerequisites, Compose setup,
+security considerations and the real-iPhone acceptance checklist. No registry
+image is published by this setup.
+
### Build from Source
On Debian/Ubuntu:
@@ -292,7 +303,8 @@ tether accept 9a4f21...
tether status # devices, links, and recent transfers
```
-See [docs/HEADLESS.md](docs/HEADLESS.md).
+See [docs/HEADLESS.md](docs/HEADLESS.md), or [the container guide](docs/CONTAINER.md)
+for Docker deployment.
diff --git a/docs/CONTAINER.md b/docs/CONTAINER.md
new file mode 100644
index 0000000..76a27ef
--- /dev/null
+++ b/docs/CONTAINER.md
@@ -0,0 +1,284 @@
+# Tether in a container
+
+The container runs `tetherd`, a private session D-Bus, and `obexd`. Drive it with
+`docker compose exec tether tether ...`; there is **no web UI in this image**.
+
+This is a local-build option, not a published registry image. Automated tests
+cover the image and headless behavior; a real iPhone/Bluetooth validation is
+still required for a particular host. See the acceptance checklist below.
+
+## What runs where
+
+| Host Linux machine | Container |
+|---|---|
+| Bluetooth adapter and BlueZ (`bluetoothd`), including Bluetooth bonds | Non-root `tetherd` and CLI |
+| Avahi/mDNS, firewall, system D-Bus | Private session D-Bus and foreground OBEX daemon |
+| Persistent directories owned by your chosen user | Keys/config/history in `/data`, received files in `/downloads` |
+
+Wi-Fi pairing and file transfer use the Tether iPhone app. **SMS/iMessage needs
+the iPhone within Bluetooth range of this Linux machine.** A remote browser or
+container cannot turn Bluetooth messaging into an internet transport.
+
+The first supported deployment shape is ordinary Linux Docker with host
+networking on amd64 or arm64. Rootless/user-namespace-remapped Docker,
+Kubernetes, Docker Desktop Bluetooth passthrough, calls/audio, AirPods and
+notification mirroring are not validated by this deployment. Clipboard sync
+needs a Wayland session and is not available here.
+
+## Host prerequisites
+
+1. Configure BlueZ and the adapter using [the Bluetooth instructions](BLUETOOTH.md)
+ and [README prerequisites](../README.md#bluetooth-for-messages-and-notifications).
+ In particular, configure the experimental bearer API and adapter class **on
+ the host before pairing**, then enable the iPhone's Messages/Contacts permissions.
+ Upstream currently recommends BlueZ 5.86+ on the host; the Ubuntu 24.04 image
+ has its own packaged OBEX client (currently 5.72). Record both versions when testing.
+2. Run Avahi and the system bus on the host. Open inbound 5134/tcp and mDNS
+ 5353/udp on the trusted local network; see the README's firewall instructions.
+3. Choose a real non-root host UID/GID authorized to use the host system bus and
+ Bluetooth services. Do not run another `tetherd` on that host port/adapter.
+
+The example mounts `/run/dbus` read-only at `/host/run/dbus`. **This is privileged
+access to host services: a read-only mount does not make D-Bus calls read-only.**
+Host D-Bus policy checks the configured identity. Some distributions require a
+supplemental host group: add only that numeric GID to Compose's `group_add` if
+needed. Do not use `privileged: true`, wildcard D-Bus policy grants, host PID
+sharing or broad device mounts to work around an unexplained permission error.
+
+Bluetooth bonds remain in the host's BlueZ storage, not the Tether data volume.
+The container never installs host service files, changes the firewall, kills a
+host daemon, or automatically confirms pairing requests.
+
+## Build and start
+
+From the repository root, as the non-root user that will own the data:
+
+```sh
+# Choose paths outside the repository/build context.
+mkdir -p "$HOME/.local/share/tether-container" "$HOME/tether-inbox"
+chmod 700 "$HOME/.local/share/tether-container"
+
+cp packaging/container/.env.example packaging/container/.env
+id -u
+id -g
+```
+
+Edit `packaging/container/.env`:
+
+- Set `TETHER_UID`/`TETHER_GID` to the values above (not root).
+- Set `TETHER_DATA_DIR`/`TETHER_DOWNLOADS_DIR` to the **absolute**, pre-created host
+ paths. Replace the example `/home/your-user` values; do not use literal `$HOME`.
+- Optionally choose `TETHER_HOSTNAME`, a DNS-style host label such as `tether-pi`.
+ It is the advertised display name; the persisted certificate is the identity.
+
+The entrypoint refuses wrong ownership or a non-private data directory rather
+than recursively changing your files. Existing directories must already be
+owned by the selected UID. Missing source directories are not auto-created.
+
+```sh
+docker compose --env-file packaging/container/.env \
+ -f packaging/container/compose.yaml config
+
+docker compose --env-file packaging/container/.env \
+ -f packaging/container/compose.yaml up -d --build
+```
+
+For the remaining examples, work in `packaging/container` so Compose finds both
+`compose.yaml` and `.env`:
+
+```sh
+cd packaging/container
+docker compose logs -f --tail 100
+docker compose exec tether tether status
+```
+
+The image is `tether:local`, built for your machine's architecture. Build a
+specific architecture with Docker's `--platform linux/amd64` or
+`--platform linux/arm64`; executing cross-architecture images requires emulation.
+No build or workflow pushes an image to a registry.
+
+The reference deployment uses host networking, so Docker port mappings do not
+apply: `tetherd` listens on host port 5134. Limit access with the host firewall.
+Only the existing mTLS phone/peer endpoint listens on TCP; the local control
+socket is **not** exposed on the network.
+
+## Pair and use the CLI
+
+### Wi-Fi
+
+Open the Tether iPhone app on the same discoverable network, select this host,
+and compare the fingerprint before approving:
+
+```sh
+docker compose exec tether tether pending
+docker compose exec tether tether accept <fingerprint>
+docker compose exec tether tether status
+```
+
+Without Wayland, no desktop approval window is launched. A missing/broken GUI
+helper is not a rejection: the request waits for explicit approval through the
+CLI. Neither the container nor its health probe accepts devices automatically.
+
+### Bluetooth messages
+
+```sh
+docker compose exec tether tether bt devices
+docker compose exec tether tether bt pair AA:BB:CC:DD:EE:FF
+docker compose exec tether tether bt connection
+docker compose exec tether tether bt threads
+docker compose exec tether tether bt messages 'tel:+15555550100'
+# Sends a real message. Choose your own recipient and content.
+docker compose exec tether tether bt send 'tel:+15555550100' 'test message'
+```
+
+Keep the interactive terminal for pairing and confirm the matching passkey on
+both ends. Enable **Show Message Notifications** and **Sync Contacts** in the
+iPhone's Bluetooth settings for this computer. Some permission toggles take time
+to appear. These operations use the host's adapter; don't delete existing bonds
+unless you intend to re-pair that phone.
+
+If a send times out/disconnects, check the phone before retrying. The container
+does not queue or replay messages, and a lost response does not prove the phone
+failed to send.
+
+### Files
+
+Send a file from the iPhone share sheet/app; it lands in your configured inbox:
+
+```sh
+docker compose exec tether tether status
+# Place a file into your host inbox first; the daemon sees the container path.
+docker compose exec tether tether send /downloads/report.pdf
+```
+
+Files remain after a container restart. The recent-received list in `status` is
+memory-only and resets on restart; it is not a durable file catalog. Successful
+receives are recorded even without a desktop notification service. Incomplete
+transfers are not reported as successful; no resumable-transfer guarantee is added.
+
+## Persistence and secrets
+
+| Container path | Contents |
+|---|---|
+| `/data/.config/tether` | TLS certificate/private key, trusted peers, Bluetooth configuration, headless history key |
+| `/data/.local/share/tether` | Message journal and contact cache |
+| `/data/.local/state/tether` | Application state (normal container logs go to stderr instead) |
+| `/downloads` | Received files |
+| `/run/tether-runtime` | Private tmpfs: session bus, `tether/tetherd.sock`, caches and OBEX staging |
+
+XDG roots equal their HOME-based defaults, avoiding accidental migration to a
+second config tree. The image declares these variables so `docker exec` and the
+supervised daemon agree. Configure mounts instead of overriding these paths.
+
+Encrypted history remains the default. With no desktop secret service, Tether
+keeps its history key in a mode-0600 `store.key` under the config directory.
+**The key and encrypted data are on the same volume.** Encryption does not
+protect against theft of that entire volume or backup. Keep `/data` and its
+backups private and restore the key and journal together; don't downgrade to
+plaintext to work around missing keys.
+
+To take a consistent backup, stop the container and copy both persistent host
+directories, preserving ownership/permissions. Do not back up or share the
+runtime tmpfs or a desktop user's session bus. Recreating the container with the
+same volumes preserves Wi-Fi identity/trust. Deleting `/data` creates a new
+identity and requires pairing again. Migrating to another Bluetooth host also
+requires handling that host's bonds separately.
+
+## Lifecycle, health and diagnostics
+
+- All application processes run as the selected UID with capabilities dropped
+ and a read-only root filesystem. The image uses `tini` and a supervisor script,
+ not systemd.
+- The supervisor checks the host bus, starts its session bus and OBEX with bounded
+ readiness waits, then starts `tetherd`. If any managed child exits, its siblings
+ are terminated and the container exits nonzero.
+- SIGTERM stops the children within the 15-second Compose grace period. Docker
+ manages restart/backoff (`unless-stopped`); permanent setup errors remain
+ visible in logs rather than gaining permissions automatically.
+- Health checks ask the existing daemon for status and check session-bus/OBEX
+ presence. They never spawn `tetherd`, activate OBEX, send messages or pair a
+ device. A missing phone, powered-off adapter or missing mDNS does not by itself
+ fail liveness. A hung daemon/bus causes the probe to fail within five seconds.
+- Docker does **not** restart a still-running container just because it is
+ unhealthy. Inspect logs and restart deliberately if needed.
+
+The two new opt-in environment switches are also usable outside Docker:
+
+| Variable | Exact value `1` does this | Otherwise |
+|---|---|---|
+| `TETHER_LOG_STDERR` | Keep daemon stderr attached to its supervisor | Preserve normal nonterminal log-file behavior |
+| `TETHER_NO_AUTOSTART` | Prevent CLI/client helpers from spawning `tetherd` | Preserve normal spawning/systemd ownership behavior |
+
+`XDG_DOWNLOAD_DIR` now takes precedence when nonempty and absolute; invalid or
+empty overrides fall back to the existing GLib/HOME lookup.
+
+Troubleshooting:
+
+- **`wrong-owner` / `invalid-layout`:** correct the host directory ownership,
+ private `/data` permissions, UID/GID or required environment. Do not run as root.
+- **`host-bus-missing` / `host-bus-denied`:** check `/run/dbus`, the host identity
+ and host D-Bus policy. Capture the exact failure before considering any access change.
+- **OBEX cannot start/connect:** record the image/host BlueZ versions and bus
+ errors. Non-root Bluetooth/OBEX operation is a hardware acceptance gate, not a
+ reason to enable privileged mode silently.
+- **Phone not discoverable:** confirm Avahi, host firewall and local multicast
+ connectivity. This container cannot make mDNS cross an isolated network/VPN.
+- **Misleading `tether bt setup` advice:** some diagnostics inspect `/proc` for
+ `bluetoothd` or use `btmgmt`. The host process is hidden by the container's PID
+ namespace, and raw probes may lack permission. Apply the documented setup on
+ the host; don't share host PID space just to improve a diagnostic.
+- **Host service repaired/restarted:** Tether may need a container restart if
+ BlueZ was unavailable during startup. This packaging does not promise new
+ D-Bus reconnection behavior.
+- **Port already in use:** stop the competing Tether instance intentionally.
+ The container will not kill or replace it.
+
+Compose rotates Docker logs (10 MB × 3 files). Existing Tether logs can contain
+device identifiers, recipient addresses and file paths: treat them as sensitive,
+not as an automatically redacted support bundle.
+
+## Automated tests
+
+From the repository root:
+
+```sh
+docker build --target test -f packaging/container/Dockerfile -t tether-test:local .
+docker build --target runtime -f packaging/container/Dockerfile -t tether:local .
+scripts/test-container.sh tether:local tether-test:local
+```
+
+The test stage runs GTest/CTest as non-root. The smoke script creates disposable
+volumes and a private stand-in system bus, never mounts host services or touches
+a real adapter. It tests supervised child failures, bounded health, restart
+persistence including a nonempty encrypted journal, volume ownership and
+permission constraints. Its root initialization command only prepares its own
+throwaway volumes; the tested runtime remains non-root. Traps clean up test
+containers and volumes on exit.
+
+`.github/workflows/container.yml` runs this on native amd64 and arm64 Linux
+runners, without registry credentials or publishing. Discovery tests that need
+Avahi may explicitly skip when that service is absent. A passing build or
+synthetic socket/bus test is not proof of Bluetooth/iPhone compatibility.
+
+## Real-iPhone acceptance checklist
+
+Before calling a host deployment functional:
+
+- [ ] Record architecture, distro/kernel, Docker/image identity, BlueZ/OBEX,
+ adapter and iOS/Tether app versions. Redact personal identifiers when sharing.
+- [ ] With fresh private state and no desktop, discover/pair over Wi-Fi, compare
+ fingerprints and explicitly accept; both ends report paired.
+- [ ] Pair Bluetooth through the CLI, confirm both passkeys and iPhone permissions.
+- [ ] Read a one-to-one thread, send an operator-approved test message to a
+ consenting recipient, verify it on the phone/recipient and receive a reply.
+- [ ] Transfer a benign file in each direction; compare bytes/checksum and see the
+ receive status without a desktop notification service.
+- [ ] Recreate the container with the same volumes: retain fingerprint/trust,
+ nonempty message history and downloaded files; reconnect without fresh pairing.
+- [ ] Take the phone out of range and restore it: daemon stays alive and existing
+ transport reconnection works; no competing daemon is spawned.
+- [ ] Stop/restart cleanly without orphaned processes or host-service takeover.
+
+Run this on at least one Bluetooth-equipped Linux architecture after automated
+checks pass on both. Explicitly label any other architecture as hardware-unverified.
+The web gateway/UI remains a separate follow-up to issue #147.
diff --git a/docs/HEADLESS.md b/docs/HEADLESS.md
index cdde0fb..2432a88 100644
--- a/docs/HEADLESS.md
+++ b/docs/HEADLESS.md
@@ -15,6 +15,13 @@ What you get, and what you do not:
| Messages, notifications, calls | ✅ with a Bluetooth adapter the machine can see |
| Clipboard sync | ❌ needs a Wayland session with `wlr-data-control` |
+## Container deployment
+
+For a non-root Docker image, Compose example and persistent mounts, see
+[CONTAINER.md](CONTAINER.md). It reuses host BlueZ/Avahi and runs its own session
+bus and OBEX daemon. It is CLI-driven, not a web UI, and Bluetooth messaging
+still requires a nearby phone.
+
## Run the daemon under systemd
The distro packages install a `tetherd.service` user unit into
@@ -107,6 +114,19 @@ systemctl --user edit tetherd.service
# Environment=XDG_DOWNLOAD_DIR=%h/inbox
```
+## With a process supervisor
+
+Set `TETHER_NO_AUTOSTART=1` for clients when your supervisor owns `tetherd`, so a
+status check or CLI command cannot spawn another daemon during an outage.
+Set `TETHER_LOG_STDERR=1` for the daemon to keep logs on stderr instead of
+redirecting nonterminal output into its state-directory log. Only the exact value
+`1` enables either option; defaults for desktop/package installations are unchanged.
+
+An absolute, nonempty `XDG_DOWNLOAD_DIR` overrides the normal GLib/HOME download
+lookup. Received files are recorded for status/subscribers independently of desktop
+notifications. With no Wayland display, pairing waits for CLI approval; failure to
+launch a desktop dialog does not by itself reject or accept the request.
+
## Clipboard sync
`tether status` says `Clipboard: off, no Wayland session on this machine` and
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index ae80431..93b33c8 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -162,6 +162,11 @@ Every node is a peer. A PC, iPhone or iPad all listen and all dial, and one cert
A node must never pin a peer on local assertion alone — a UI must not report a device paired or connected until `pair_accepted` has crossed the wire and the trust record exists.
+Without a Wayland display, the receiver leaves the request pending for explicit local
+CLI approval rather than launching a desktop dialog. A helper that cannot run is not
+a rejection or acceptance. An explicit dialog rejection/timeout still rejects; a
+stale dialog result cannot undo acceptance already supplied through the CLI.
+
### Reconnecting
A node dials a peer it already trusts on its own, whenever mDNS resolves one whose `fp=` is in `known_hosts.json`.
diff --git a/packaging/container/.env.example b/packaging/container/.env.example
new file mode 100644
index 0000000..790ffcc
--- /dev/null
+++ b/packaging/container/.env.example
@@ -0,0 +1,10 @@
+# Copy to .env in this directory, then replace with your actual host identity/paths.
+# Run id -u and id -g as the non-root user that should own Tether's state.
+TETHER_UID=1000
+TETHER_GID=1000
+# Pre-create these outside the repository; /data must be private (mode 0700).
+TETHER_DATA_DIR=/home/your-user/.local/share/tether-container
+TETHER_DOWNLOADS_DIR=/home/your-user/tether-inbox
+TETHER_HOSTNAME=tether
+# Optional local build label. No image is published by this configuration.
+TETHER_VERSION=0.2.32-container-dev
diff --git a/packaging/container/Dockerfile b/packaging/container/Dockerfile
new file mode 100644
index 0000000..926709f
--- /dev/null
+++ b/packaging/container/Dockerfile
@@ -0,0 +1,64 @@
+# syntax=docker/dockerfile:1
+FROM ubuntu:24.04 AS build
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ g++ cmake ninja-build git pkg-config ca-certificates \
+ libwayland-dev libavahi-client-dev libssl-dev libglib2.0-dev libsecret-1-dev \
+ libgtk-3-dev libgtk-layer-shell-dev libnotify-dev gettext dbus-daemon \
+ && rm -rf /var/lib/apt/lists/*
+WORKDIR /src
+COPY . .
+ARG TETHER_VERSION=0.2.32-container-dev
+ARG BUILD_JOBS=4
+RUN cmake -S . -B /build -G Ninja -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_INSTALL_PREFIX=/usr/local -DTETHER_VERSION="${TETHER_VERSION}" \
+ -DTETHER_BUILD_EXTENSIONS=OFF \
+ && cmake --build /build --target tetherd tether_cli translations -j "${BUILD_JOBS}" \
+ && mkdir -p /payload/bin /payload/share/locale \
+ && install -m 755 /build/tether /build/tetherd /payload/bin/ \
+ && cp -a /build/locale/. /payload/share/locale/
+
+FROM build AS test
+RUN cmake --build /build --target tether_test tether_headless_test tether_container_store_fixture -j "${BUILD_JOBS}"
+WORKDIR /build
+# Run tests as non-root too; permission failures must not be hidden by root.
+RUN chmod -R a+rX /src /build && mkdir -p /test-home /build/Testing \
+ && chown -R 1000:1000 /test-home /build/Testing
+ENV HOME=/test-home
+USER 1000:1000
+RUN ctest --output-on-failure -j 4
+
+FROM ubuntu:24.04 AS runtime
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash coreutils tini dbus-daemon dbus-bin libglib2.0-bin bluez-obexd \
+ libwayland-client0 libavahi-client3 libssl3t64 libglib2.0-0t64 libsecret-1-0 libnotify4 \
+ && rm -rf /var/lib/apt/lists/* \
+ && mkdir -p /usr/local/libexec /data /downloads /run/tether-runtime \
+ && obexd="$(dpkg -L bluez-obexd | grep '/obexd$')" \
+ && test -x "$obexd" && "$obexd" --help | grep -q -- '--nodetach' \
+ && ln -s "$obexd" /usr/local/libexec/tether-obexd \
+ # OBEX is explicitly supervised, never silently respawned by D-Bus activation.
+ && rm /usr/share/dbus-1/services/org.bluez.obex.service \
+ && chown 1000:1000 /data /downloads /run/tether-runtime \
+ && chmod 700 /data /downloads /run/tether-runtime
+COPY --from=build /payload/ /usr/local/
+COPY --chmod=755 packaging/container/entrypoint.sh /usr/local/libexec/tether-container-entrypoint
+COPY --chmod=755 packaging/container/healthcheck.sh /usr/local/libexec/tether-container-healthcheck
+RUN ldd /usr/local/bin/tether /usr/local/bin/tetherd > /tmp/linked-libraries \
+ && ! grep -q 'not found' /tmp/linked-libraries && rm /tmp/linked-libraries
+ENV HOME=/data \
+ XDG_CONFIG_HOME=/data/.config \
+ XDG_DATA_HOME=/data/.local/share \
+ XDG_STATE_HOME=/data/.local/state \
+ XDG_DOWNLOAD_DIR=/downloads \
+ XDG_RUNTIME_DIR=/run/tether-runtime \
+ XDG_CACHE_HOME=/run/tether-runtime/cache \
+ DBUS_SYSTEM_BUS_ADDRESS=unix:path=/host/run/dbus/system_bus_socket \
+ DBUS_SESSION_BUS_ADDRESS=unix:path=/run/tether-runtime/bus \
+ TETHER_LOG_STDERR=1 \
+ TETHER_NO_AUTOSTART=1
+USER 1000:1000
+STOPSIGNAL SIGTERM
+HEALTHCHECK --interval=30s --timeout=6s --start-period=30s --retries=3 \
+ CMD ["/usr/local/libexec/tether-container-healthcheck"]
+ENTRYPOINT ["/usr/bin/tini", "-g", "--", "/usr/local/libexec/tether-container-entrypoint"]
+CMD ["tetherd"]
diff --git a/packaging/container/compose.yaml b/packaging/container/compose.yaml
new file mode 100644
index 0000000..795e309
--- /dev/null
+++ b/packaging/container/compose.yaml
@@ -0,0 +1,43 @@
+services:
+ tether:
+ image: tether:local
+ build:
+ context: ../..
+ dockerfile: packaging/container/Dockerfile
+ target: runtime
+ args:
+ TETHER_VERSION: ${TETHER_VERSION:-0.2.32-container-dev}
+ hostname: ${TETHER_HOSTNAME:-tether}
+ user: "${TETHER_UID:?Set your non-root host UID}:${TETHER_GID:?Set your host GID}"
+ network_mode: host
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ restart: unless-stopped
+ stop_grace_period: 15s
+ volumes:
+ - type: bind
+ source: ${TETHER_DATA_DIR:?Set an absolute private host data directory}
+ target: /data
+ bind:
+ create_host_path: false
+ - type: bind
+ source: ${TETHER_DOWNLOADS_DIR:?Set an absolute host downloads directory}
+ target: /downloads
+ bind:
+ create_host_path: false
+ # Read-only filesystem access does NOT make system D-Bus calls read-only.
+ - type: bind
+ source: /run/dbus
+ target: /host/run/dbus
+ read_only: true
+ bind:
+ create_host_path: false
+ tmpfs:
+ - /run/tether-runtime:uid=${TETHER_UID},gid=${TETHER_GID},mode=0700
+ - /tmp:mode=1777
+ logging:
+ driver: json-file
+ options:
+ max-size: "10m"
+ max-file: "3"
diff --git a/packaging/container/entrypoint.sh b/packaging/container/entrypoint.sh
new file mode 100755
index 0000000..c59a71d
--- /dev/null
+++ b/packaging/container/entrypoint.sh
@@ -0,0 +1,107 @@
+#!/usr/bin/env bash
+# A single lifecycle owner for the private session bus, OBEX and Tether.
+set -euo pipefail
+umask 077
+children=()
+
+fail() { printf 'tether-container: %s\n' "$*" >&2; exit 1; }
+# Invoked by the EXIT trap, including exits from a signal/readiness failure.
+# shellcheck disable=SC2329
+cleanup() {
+ local status=$? pid deadline alive
+ trap - EXIT
+ # Do not interrupt reaping if Docker/user sends another shutdown signal.
+ trap '' TERM INT
+ for pid in "${children[@]}"; do kill -TERM "$pid" 2>/dev/null || true; done
+ deadline=$((SECONDS + 10))
+ while (( SECONDS < deadline )); do
+ alive=false
+ for pid in "${children[@]}"; do
+ if kill -0 "$pid" 2>/dev/null; then alive=true; fi
+ done
+ $alive || break
+ sleep 0.1
+ done
+ for pid in "${children[@]}"; do
+ if kill -0 "$pid" 2>/dev/null; then kill -KILL "$pid" 2>/dev/null || true; fi
+ wait "$pid" 2>/dev/null || true
+ done
+ exit "$status"
+}
+trap cleanup EXIT
+trap 'exit 0' TERM INT
+
+[[ $# == 1 && $1 == tetherd ]] || fail 'unsupported-command: use docker exec for CLI commands'
+uid=$(id -u)
+[[ $uid != 0 ]] || fail 'root-user: configure a non-root host UID/GID'
+hostname=$(uname -n)
+[[ $hostname =~ ^[[:alnum:]]([[:alnum:]-]{0,61}[[:alnum:]])?$ ]] || fail 'invalid-layout: choose a DNS-style hostname'
+
+require_env() {
+ [[ ${!1-} == "$2" ]] || fail "invalid-layout: $1 must be $2 (configure mounts instead)"
+}
+require_env HOME /data
+require_env XDG_CONFIG_HOME /data/.config
+require_env XDG_DATA_HOME /data/.local/share
+require_env XDG_STATE_HOME /data/.local/state
+require_env XDG_DOWNLOAD_DIR /downloads
+require_env XDG_RUNTIME_DIR /run/tether-runtime
+require_env XDG_CACHE_HOME /run/tether-runtime/cache
+require_env DBUS_SYSTEM_BUS_ADDRESS unix:path=/host/run/dbus/system_bus_socket
+require_env DBUS_SESSION_BUS_ADDRESS unix:path=/run/tether-runtime/bus
+require_env TETHER_LOG_STDERR 1
+require_env TETHER_NO_AUTOSTART 1
+# Never accidentally attach to a desktop inherited through operator environment overrides.
+unset DISPLAY WAYLAND_DISPLAY
+
+for dir in /data /downloads /run/tether-runtime; do
+ [[ -d $dir && ! -L $dir ]] || fail "invalid-layout: $dir must be a directory mount"
+ [[ $(stat -c %u "$dir") == "$uid" ]] || fail "wrong-owner: prepare $dir for UID $uid on the host"
+ [[ -w $dir && -x $dir ]] || fail "unwritable-volume: $dir must be writable by UID $uid"
+done
+for dir in /data /run/tether-runtime; do
+ mode=$(stat -c %a "$dir")
+ (( (8#$mode & 077) == 0 )) || fail "invalid-layout: $dir must not grant group/other access (use mode 0700)"
+done
+mkdir -p "$XDG_CONFIG_HOME/tether" "$XDG_DATA_HOME/tether" "$XDG_STATE_HOME/tether" "$XDG_CACHE_HOME"
+[[ -S /host/run/dbus/system_bus_socket ]] || fail 'host-bus-missing: mount the host /run/dbus directory at /host/run/dbus'
+if ! timeout -k 0.5s 3s gdbus call --system --timeout 2 --dest org.freedesktop.DBus \
+ --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.ListNames >/dev/null 2>&1; then
+ fail 'host-bus-denied: verify host UID and D-Bus policy; do not use privileged mode'
+fi
+for name in org.bluez org.freedesktop.Avahi; do
+ if [[ $(timeout -k 0.5s 3s gdbus call --system --timeout 2 --dest org.freedesktop.DBus \
+ --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.NameHasOwner "$name" 2>/dev/null) != '(true,)' ]]; then
+ printf 'tether-container: %s unavailable; repair the host service and restart if needed\n' "$name" >&2
+ fi
+done
+
+bus_ready() {
+ timeout -k 0.2s 1s gdbus call --session --timeout 1 --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus \
+ --method org.freedesktop.DBus.NameHasOwner "$1" 2>/dev/null | grep -qx '(true,)'
+}
+wait_ready() {
+ local name=$1 label=$2 deadline=$((SECONDS + 10)) pid
+ while (( SECONDS < deadline )); do
+ for pid in "${children[@]}"; do
+ kill -0 "$pid" 2>/dev/null || fail "child-exited: $label did not become ready"
+ done
+ if bus_ready "$name"; then return; fi
+ sleep 0.1
+ done
+ fail "$label-timeout: private $label did not become ready"
+}
+# The runtime directory is ephemeral. Do not mount a host session bus here.
+dbus-daemon --session --nofork --nopidfile --address="$DBUS_SESSION_BUS_ADDRESS" &
+children+=("$!")
+wait_ready org.freedesktop.DBus session-bus
+# Ubuntu's foreground switch is --nodetach, verified in the image build.
+/usr/local/libexec/tether-obexd --nodetach &
+children+=("$!")
+wait_ready org.bluez.obex obex
+printf 'tether-container: session bus and OBEX ready; starting tetherd\n' >&2
+tetherd &
+children+=("$!")
+status=0
+wait -n "${children[@]}" || status=$?
+fail "child-exited: a supervised process exited ($status); stopping its siblings"
diff --git a/packaging/container/healthcheck.sh b/packaging/container/healthcheck.sh
new file mode 100755
index 0000000..5b78bd2
--- /dev/null
+++ b/packaging/container/healthcheck.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+# Bound the entire probe, not each read independently. Never activate a service.
+# Variables must expand in the bounded child shell, not the outer wrapper.
+# shellcheck disable=SC2016
+exec timeout --kill-after=0.5s 4s /bin/bash -ec '
+ [[ ${DBUS_SESSION_BUS_ADDRESS:-} == unix:path=/run/tether-runtime/bus ]]
+ [[ $(gdbus call --session --timeout 1 --dest org.freedesktop.DBus \
+ --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.NameHasOwner org.bluez.obex 2>/dev/null) == "(true,)" ]]
+ TETHER_NO_AUTOSTART=1 /usr/local/bin/tether status >/dev/null 2>&1
+'
diff --git a/scripts/test-container.sh b/scripts/test-container.sh
new file mode 100755
index 0000000..99fcd41
--- /dev/null
+++ b/scripts/test-container.sh
@@ -0,0 +1,186 @@
+#!/usr/bin/env bash
+# Only disposable Docker volumes and a private bus: never use the host's BlueZ/Avahi.
+set -euo pipefail
+image=${1:?Usage: test-container.sh RUNTIME_IMAGE TEST_IMAGE}
+test_image=${2:?Supply the Dockerfile test-stage image for the encrypted-store fixture}
+prefix="tether-smoke-$$-${RANDOM}"
+app="$prefix-app"
+bus="$prefix-bus"
+volumes=("$prefix-data" "$prefix-downloads" "$prefix-bus" "$prefix-fault")
+cleanup() {
+ local status=$?
+ if (( status != 0 )); then
+ docker logs --tail 100 "$app" >&2 || true
+ docker logs --tail 30 "$bus" >&2 || true
+ fi
+ docker rm -f "$app" "$bus" "$prefix-init" >/dev/null 2>&1 || true
+ for volume in "${volumes[@]}"; do docker volume rm "$volume" >/dev/null 2>&1 || true; done
+}
+trap cleanup EXIT
+for volume in "${volumes[@]}"; do docker volume create "$volume" >/dev/null; done
+
+# Root is used only to initialize these disposable test volumes, never to run Tether.
+docker run --rm --name "$prefix-init" --network none --user 0:0 \
+ -v "$prefix-data:/data" -v "$prefix-downloads:/downloads" -v "$prefix-bus:/bus" \
+ --entrypoint /bin/sh "$image" -ec 'chown 1000:1000 /data /downloads /bus; chmod 700 /data /downloads /bus'
+# An external OBEX executable that never claims its bus name exercises readiness timeout.
+# This override exists only in a disposable test volume, never in the runtime image.
+docker run --rm --network none --user 0:0 -v "$prefix-fault:/fault" \
+ --entrypoint /bin/sh "$image" -ec '
+ cp -L /usr/local/libexec/tether-* /fault/
+ printf "#!/bin/sh\nexec sleep 30\n" > /fault/tether-obexd
+ chmod 755 /fault/tether-obexd
+ '
+docker run -d --name "$bus" --network none --user 1000:1000 --read-only \
+ --cap-drop ALL --security-opt no-new-privileges:true -e XDG_RUNTIME_DIR=/bus -v "$prefix-bus:/bus" \
+ --entrypoint /usr/bin/dbus-daemon "$image" \
+ --session --nofork --nopidfile --address=unix:path=/bus/system_bus_socket >/dev/null
+
+start() {
+ docker rm -f "$app" >/dev/null 2>&1 || true
+ docker run -d --name "$app" --network none --read-only --user 1000:1000 \
+ --cap-drop ALL --security-opt no-new-privileges:true \
+ --tmpfs /run/tether-runtime:uid=1000,gid=1000,mode=0700 \
+ --tmpfs /tmp:mode=1777 \
+ -v "$prefix-data:/data" -v "$prefix-downloads:/downloads" \
+ -v "$prefix-bus:/host/run/dbus:ro" "$@" "$image" >/dev/null
+}
+ready() {
+ local i
+ for ((i=0; i<100; i++)); do
+ [[ $(docker inspect -f '{{.State.Running}}' "$app") == true ]] || return 1
+ if docker exec "$app" /usr/local/libexec/tether-container-healthcheck; then return 0; fi
+ sleep 0.2
+ done
+ echo 'runtime never became healthy' >&2
+ return 1
+}
+exited() {
+ local i
+ for ((i=0; i<80; i++)); do
+ [[ $(docker inspect -f '{{.State.Running}}' "$app") == false ]] && return 0
+ sleep 0.2
+ done
+ echo 'runtime did not terminate within its shutdown budget' >&2
+ return 1
+}
+signal_child() {
+ docker exec "$app" bash -ec '
+ for comm in /proc/[0-9]*/comm; do
+ read -r name 2>/dev/null < "$comm" || continue
+ if [[ $name == "$1" ]]; then
+ pid=${comm#/proc/}; pid=${pid%/comm}
+ kill -"$2" "$pid"
+ exit 0
+ fi
+ done
+ exit 1
+ ' _ "$1" "$2"
+}
+store_fixture() {
+ docker run --rm --network none --read-only --user 1000:1000 \
+ -e HOME=/data -e XDG_CONFIG_HOME=/data/.config -e XDG_DATA_HOME=/data/.local/share \
+ -e DBUS_SESSION_BUS_ADDRESS=unix:path=/no-session-bus \
+ -v "$prefix-data:/data" --entrypoint /build/test/tether_container_store_fixture "$test_image" "$1"
+}
+
+# Give the fixture bus a bounded startup window, without touching any host bus.
+for ((i=0; i<50; i++)); do
+ docker exec "$bus" test -S /bus/system_bus_socket && break
+ sleep 0.1
+done
+start
+ready
+printf 'PASS: non-root runtime is healthy without a phone, BlueZ or Avahi\n'
+docker exec "$app" bash -ec '
+ [[ $(id -u) == 1000 ]]
+ [[ $TETHER_NO_AUTOSTART == 1 && $TETHER_LOG_STDERR == 1 ]]
+ test ! -e /usr/local/bin/tether-gtk
+ test ! -e /usr/local/bin/tether-dialog
+ test ! -e /usr/share/dbus-1/services/org.bluez.obex.service
+ test -f /usr/local/share/locale/fr/LC_MESSAGES/tether.mo
+ ! command -v g++
+ ! command -v npm
+ ! ldd /usr/local/bin/tether /usr/local/bin/tetherd | grep "not found"
+ test ! -e /data/.local/state/tether/tetherd.log
+ [[ $(stat -c %a /data) == 700 ]]
+ [[ $(stat -c %a /run/tether-runtime) == 700 ]]
+'
+docker logs "$app" 2>&1 | grep 'tetherd version' >/dev/null
+# No connected remote peer; this only creates synthetic local trust in this disposable home.
+docker exec "$app" tether accept container-smoke-fingerprint >/dev/null
+identity=$(docker exec "$app" sha256sum /data/.config/tether/cert.pem /data/.config/tether/key.pem /data/.config/tether/known_hosts.json)
+docker exec "$app" sh -c 'umask 077; printf "persistent file\n" > /downloads/smoke.txt; touch /run/tether-runtime/staging-sentinel'
+# Populate the journal while the daemon is stopped; never race a live journal writer.
+docker stop -t 15 "$app" >/dev/null
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") == 0 ]]
+store_fixture seed
+start
+ready
+[[ $(docker exec "$app" sha256sum /data/.config/tether/cert.pem /data/.config/tether/key.pem /data/.config/tether/known_hosts.json) == "$identity" ]]
+docker exec "$app" sh -ec 'test ! -e /run/tether-runtime/staging-sentinel; test "$(cat /downloads/smoke.txt)" = "persistent file"; test "$(stat -c %a /data/.config/tether/store.key)" = 600'
+docker stop -t 15 "$app" >/dev/null
+store_fixture check
+printf 'PASS: identity, trust, nonempty encrypted history and files survive recreation\n'
+
+# A stuck process fails passive health within budget, without spawning replacements.
+start
+ready
+for name in tetherd dbus-daemon; do
+ signal_child "$name" STOP
+ before=$SECONDS
+ if docker exec "$app" /usr/local/libexec/tether-container-healthcheck; then
+ echo "health unexpectedly passed with $name stopped" >&2; exit 1
+ fi
+ (( SECONDS - before <= 6 ))
+ [[ $(docker inspect -f '{{.State.Running}}' "$app") == true ]]
+ signal_child "$name" CONT
+ ready
+done
+printf 'PASS: stuck daemon/bus fail bounded health without restarting the runtime\n'
+
+# Each critical child is owned by this test container. Killing it must stop its siblings.
+for name in tetherd tether-obexd dbus-daemon; do
+ start
+ ready
+ signal_child "$name" KILL
+ exited
+ [[ $(docker inspect -f '{{.State.ExitCode}}' "$app") != 0 ]]
+ printf 'PASS: %s failure terminates the runtime\n' "$name"
+done
+
+start
+ready
+docker kill --signal INT "$app" >/dev/null
+exited
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") == 0 ]]
+# A child that stays alive without becoming ready must not keep the runtime starting forever.
+before=$SECONDS
+start -v "$prefix-fault:/usr/local/libexec:ro"
+exited
+(( SECONDS - before <= 15 ))
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") != 0 ]]
+docker logs "$app" 2>&1 | grep 'obex-timeout' >/dev/null
+printf 'PASS: SIGINT shuts down cleanly; OBEX startup timeout stops the runtime\n'
+
+start --user 0:0
+exited
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") != 0 ]]
+docker logs "$app" 2>&1 | grep 'root-user' >/dev/null
+start -e DBUS_SYSTEM_BUS_ADDRESS=unix:path=/wrong-bus
+exited
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") != 0 ]]
+docker logs "$app" 2>&1 | grep 'invalid-layout' >/dev/null
+# An unavailable host bus is an actionable startup failure, not a privileged fallback.
+docker stop "$bus" >/dev/null
+start
+exited
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") != 0 ]]
+docker logs "$app" 2>&1 | grep -E 'host-bus-(missing|denied)' >/dev/null
+# Misowned persistent data is refused before bus checks, not recursively chowned.
+docker run --rm --network none --user 0:0 -v "$prefix-data:/data" --entrypoint /bin/sh "$image" -c 'chown 0:0 /data'
+start
+exited
+[[ $(docker inspect -f '{{.State.ExitCode}}' "$app") != 0 ]]
+docker logs "$app" 2>&1 | grep 'wrong-owner' >/dev/null
+printf 'PASS: unsafe users, layout overrides and misowned volumes are refused\n'
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index 60e2e1f..c41cc7f 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -1109,7 +1109,28 @@ static nlohmann::json parse_first_line(const std::string& response) {
}
static nlohmann::json state_snapshot(tether::Client& client) {
- return parse_first_line(client.send_and_wait("{\"command\":\"state_snapshot\"}\n"));
+ if (!client.send("{\"command\":\"state_snapshot\"}\n"))
+ throw std::runtime_error("Could not request state_snapshot");
+ // Unix sockets are streams: a healthy daemon's reply can span several reads.
+ // Keep the existing first-line handling, but bound an unframed/malformed reply
+ // in both size and time, so a daemon that stalls mid-reply fails fast instead
+ // of hanging the CLI forever.
+ constexpr size_t max_reply_bytes = 1024 * 1024;
+ constexpr int read_timeout_ms = 5000;
+ std::string response;
+ char buffer[4096];
+ while (response.find('\n') == std::string::npos) {
+ if (!client.wait_readable(read_timeout_ms))
+ throw std::runtime_error("Timed out waiting for state_snapshot");
+ const ssize_t n = client.read(buffer, sizeof(buffer));
+ if (n <= 0 || response.size() + static_cast<size_t>(n) > max_reply_bytes)
+ throw std::runtime_error("Incomplete or oversized state_snapshot");
+ response.append(buffer, static_cast<size_t>(n));
+ }
+ auto snapshot = parse_first_line(response);
+ if (!snapshot.is_object() || snapshot.value("command", "") != "state_snapshot")
+ throw std::runtime_error("Expected a state_snapshot reply");
+ return snapshot;
}
static int print_status(tether::Client& client) {
diff --git a/src/core/include/tether/client.hpp b/src/core/include/tether/client.hpp
index f472392..56118cf 100644
--- a/src/core/include/tether/client.hpp
+++ b/src/core/include/tether/client.hpp
@@ -5,7 +5,7 @@
namespace tether {
- // Starts tetherd detached, and returns once it has been launched
+ // Starts tetherd detached unless supervised (TETHER_NO_AUTOSTART=1 or enabled systemd unit).
void spawn_daemon();
class Client {
@@ -13,7 +13,7 @@ namespace tether {
Client();
~Client();
- // host="" uses the local UNIX socket, auto-launching the daemon if needed.
+ // host="" uses the local UNIX socket, auto-launching if needed unless supervised.
// host!="" opens a TCP+TLS connection to a remote daemon.
bool connect(const std::string& host = "", int port = 5134);
void disconnect();
@@ -26,6 +26,8 @@ namespace tether {
std::string get_peer_fingerprint() const;
ssize_t read(char* buf, size_t count);
+ // Blocks up to timeout_ms for read() to return data without blocking; false means timed out.
+ bool wait_readable(int timeout_ms) const;
// High Level Features
std::string get_clipboard(std::string& err_out);
diff --git a/src/core/src/client.cpp b/src/core/src/client.cpp
index da1d640..6f1ed86 100644
--- a/src/core/src/client.cpp
+++ b/src/core/src/client.cpp
@@ -12,9 +12,11 @@
#include <fstream>
#include <netdb.h>
#include <nlohmann/json.hpp>
+#include <poll.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
+#include <string_view>
#include <tether/log.hpp>
#include <unistd.h>
@@ -77,6 +79,9 @@ namespace tether {
}
void spawn_daemon() {
+ // A container/process supervisor owns the daemon, including while it is down.
+ if (const char* value = std::getenv("TETHER_NO_AUTOSTART"); value && std::string_view(value) == "1")
+ return;
// Let systemd start it, and stay out of the way when it already does.
if (systemd_owns_tetherd())
return;
@@ -259,6 +264,14 @@ namespace tether {
}
}
+ bool Client::wait_readable(int timeout_ms) const {
+ // TLS can already hold a full record in userspace that poll() on the raw fd won't see.
+ if (ssl_ && SSL_pending(ssl_) > 0)
+ return true;
+ pollfd pfd{sock_, POLLIN, 0};
+ return poll(&pfd, 1, timeout_ms) > 0;
+ }
+
std::string Client::get_clipboard(std::string& err_out) {
nlohmann::json j;
j["command"] = "clipboard_get";
diff --git a/src/core/src/file_transfer.cpp b/src/core/src/file_transfer.cpp
index 4cf04a6..9f18401 100644
--- a/src/core/src/file_transfer.cpp
+++ b/src/core/src/file_transfer.cpp
@@ -1,5 +1,6 @@
#include "tether/file_transfer.hpp"
#include "tether/base64.hpp"
+#include <cstdlib>
#include <glib.h>
#include <tether/log.hpp>
@@ -18,6 +19,10 @@ namespace tether {
}
std::string FileReceiveManager::get_downloads_dir() {
+ if (const char* override_dir = std::getenv("XDG_DOWNLOAD_DIR");
+ override_dir && *override_dir && std::filesystem::path(override_dir).is_absolute()) {
+ return override_dir;
+ }
if (const char* downloads = g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD)) {
return downloads;
}
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index f2ac29c..22cb26e 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -2227,6 +2227,14 @@ namespace tether {
SSL* ssl,
const std::string& fingerprint,
const std::string& device_name) {
+ // A headless client approves through the command socket. No GUI is not a rejection.
+ // WAYLAND_DISPLAY alone would also skip a working X11 session: tether-dialog
+ // falls back to an ordinary window when gtk-layer-shell isn't available.
+ const char* wayland_display = std::getenv("WAYLAND_DISPLAY");
+ const char* x11_display = std::getenv("DISPLAY");
+ if ((!wayland_display || !*wayland_display) && (!x11_display || !*x11_display))
+ return;
+
// Translated before the fork: gettext takes a lock, and calling it in the
// child of a threaded process can deadlock if another thread held it.
std::string short_fp = fingerprint;
@@ -2334,15 +2342,13 @@ namespace tether {
accept_device(info.fingerprint, info.device_name);
} else if (info.superseded) {
debug::log(INFO, "Pairing dialog dismissed after {} was accepted elsewhere", info.device_name);
+ } else if (!bluetooth::dialog_answered(status)) {
+ debug::log(WARN,
+ "[Pairing Pending] {}: dialog unavailable (exit code {}); explicit approval still required",
+ info.device_name,
+ exit_code);
} else {
-
- if (!bluetooth::dialog_answered(status))
- debug::log(ERR,
- "[Pairing Denied] {}: the confirmation dialog could not run (exit code {})",
- info.device_name,
- exit_code);
- else
- debug::log(INFO, "[Pairing Rejected] {} (exit code {})", info.device_name, exit_code);
+ debug::log(INFO, "[Pairing Rejected] {} (exit code {})", info.device_name, exit_code);
auto remote_it = connected_remote_clients.find(info.client_fd);
auto ssl_it = active_ssl_.find(info.client_fd);
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 74b3021..b089861 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -1,6 +1,8 @@
#include "notification.hpp"
#include <csignal>
#include <cstdio>
+#include <cstdlib>
+#include <string_view>
#include <ctime>
#include <mutex>
#include <nlohmann/json.hpp>
@@ -38,6 +40,8 @@ void signal_handler(int) {
// Append stderr/stdout to the state-dir log unless attached to a terminal.
static void redirect_output_to_log() {
+ if (const char* value = std::getenv("TETHER_LOG_STDERR"); value && std::string_view(value) == "1")
+ return;
if (isatty(STDERR_FILENO))
return;
try {
@@ -165,12 +169,12 @@ int main(int argc, char** argv) {
const bool notifier_ready = notifier.init();
if (!notifier_ready) {
debug::log(ERR, "Warning: desktop notifications unavailable");
- } else {
- file_mgr.set_on_complete([&notifier](const std::filesystem::path& path, size_t bytes_written) {
- notifier.notify_file_arrived(path);
- tether::record_received_file(path, bytes_written);
- });
}
+ file_mgr.set_on_complete([&notifier, notifier_ready](const std::filesystem::path& path, size_t bytes_written) {
+ tether::record_received_file(path, bytes_written);
+ if (notifier_ready)
+ notifier.notify_file_arrived(path);
+ });
tether::g_file_manager = &file_mgr;
notifier.set_copy_handler([&loop](const std::string& code) {
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index e5686bd..1e16ecd 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -47,6 +47,20 @@ target_link_libraries(tether_test PRIVATE
include(GoogleTest)
gtest_discover_tests(tether_test)
+# These exercise the actual daemon/CLI in isolated homes, on the daemon's fixed port.
+add_executable(tether_container_store_fixture fixtures/container_store.cpp)
+target_link_libraries(tether_container_store_fixture PRIVATE tether)
+add_library(tether_notify_unavailable SHARED fixtures/notify_unavailable.cpp)
+add_executable(tether_headless_test test_headless_runtime.cpp)
+target_link_libraries(tether_headless_test PRIVATE tether GTest::gtest_main)
+target_compile_definitions(tether_headless_test PRIVATE
+ TETHERD_TEST_PATH="$<TARGET_FILE:tetherd>"
+ TETHER_CLI_TEST_PATH="$<TARGET_FILE:tether_cli>"
+ TETHER_NOTIFY_FIXTURE="$<TARGET_FILE:tether_notify_unavailable>"
+)
+add_dependencies(tether_headless_test tetherd tether_cli tether_notify_unavailable)
+gtest_discover_tests(tether_headless_test PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
+
# The same gates the i18n workflow runs, so a missing translation fails here first.
find_program(MSGFMT_EXECUTABLE msgfmt)
if(MSGFMT_EXECUTABLE)
diff --git a/test/fixtures/container_store.cpp b/test/fixtures/container_store.cpp
new file mode 100644
index 0000000..28cb5ce
--- /dev/null
+++ b/test/fixtures/container_store.cpp
@@ -0,0 +1,33 @@
+// Seeds and reads a nonempty encrypted journal across container recreation.
+// Test-image only: no synthetic phone data or test binaries ship in the runtime.
+#include <ctime>
+#include <string_view>
+#include <sys/stat.h>
+#include <tether/bluetooth/journal.hpp>
+
+int main(int argc, char** argv) {
+ if (argc != 2)
+ return 2;
+ umask(0077);
+ tether::secret::set_retention(tether::Retention::Encrypted);
+ tether::bluetooth::MessageJournal journal;
+ if (!journal.open())
+ return 1;
+ if (std::string_view(argv[1]) == "seed") {
+ tether::bluetooth::Message message;
+ message.handle = "container-fixture";
+ message.thread_key = "tel:+15555550100";
+ message.body = "synthetic retained message";
+ message.timestamp = std::time(nullptr);
+ journal.append(message);
+ journal.close();
+ return 0;
+ }
+ if (std::string_view(argv[1]) != "check")
+ return 2;
+ const auto messages = journal.load(std::time(nullptr));
+ return messages.size() == 1 && messages[0].handle == "container-fixture" &&
+ messages[0].body == "synthetic retained message"
+ ? 0
+ : 1;
+}
diff --git a/test/fixtures/notify_unavailable.cpp b/test/fixtures/notify_unavailable.cpp
new file mode 100644
index 0000000..ccd8003
--- /dev/null
+++ b/test/fixtures/notify_unavailable.cpp
@@ -0,0 +1,3 @@
+// Test-only dynamic-library seam: absence of a notification service alone does
+// not make libnotify initialization fail. Never ship this in the runtime image.
+extern "C" int notify_init(const char*) { return 0; }
diff --git a/test/test_file_transfer.cpp b/test/test_file_transfer.cpp
index 3fd607c..1787561 100644
--- a/test/test_file_transfer.cpp
+++ b/test/test_file_transfer.cpp
@@ -1,3 +1,4 @@
+#include "scoped_env.hpp"
#include <gtest/gtest.h>
#include <tether/file_transfer.hpp>
#include <tether/base64.hpp>
@@ -22,6 +23,27 @@ protected:
std::filesystem::temp_directory_path() / ("tether-tests-" + std::to_string(getpid()));
};
+TEST_F(FileTransferTest, AbsoluteDownloadOverrideWins) {
+ tether::testing::ScopedEnv downloads("XDG_DOWNLOAD_DIR", home_ / "inbox");
+ tether::FileReceiveManager mgr;
+ ASSERT_TRUE(mgr.handle_start("override", "hello.txt", 3));
+ ASSERT_TRUE(mgr.handle_chunk("override", 0, tether::base64_encode((const unsigned char*)"abc", 3)));
+ ASSERT_TRUE(mgr.handle_end("override"));
+ EXPECT_TRUE(std::filesystem::exists(home_ / "inbox/hello.txt"));
+ EXPECT_FALSE(std::filesystem::exists(home_ / "Downloads/hello.txt"));
+}
+
+TEST_F(FileTransferTest, InvalidDownloadOverrideFallsBack) {
+ for (const std::string value : {"", "relative/inbox"}) {
+ tether::testing::ScopedEnv downloads("XDG_DOWNLOAD_DIR", value);
+ tether::FileReceiveManager mgr;
+ ASSERT_TRUE(mgr.handle_start("fallback", "fallback.txt", 0));
+ ASSERT_TRUE(mgr.handle_end("fallback"));
+ EXPECT_TRUE(std::filesystem::exists(home_ / "Downloads/fallback.txt"));
+ std::filesystem::remove(home_ / "Downloads/fallback.txt");
+ }
+}
+
TEST_F(FileTransferTest, SingleChunkTransfer) {
tether::FileReceiveManager mgr;
diff --git a/test/test_headless_runtime.cpp b/test/test_headless_runtime.cpp
new file mode 100644
index 0000000..fcfcc3b
--- /dev/null
+++ b/test/test_headless_runtime.cpp
@@ -0,0 +1,404 @@
+#include "scoped_env.hpp"
+#include <gtest/gtest.h>
+#include <nlohmann/json.hpp>
+#include <tether/base64.hpp>
+#include <tether/crypto.hpp>
+
+#include <algorithm>
+#include <arpa/inet.h>
+#include <chrono>
+#include <csignal>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <filesystem>
+#include <fstream>
+#include <map>
+#include <poll.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <thread>
+#include <unistd.h>
+
+using json = nlohmann::json;
+using namespace std::chrono_literals;
+namespace fs = std::filesystem;
+
+namespace {
+
+ // Real Unix/TLS framing: retain broadcasts that arrive in the same read as a reply.
+ class Peer {
+ public:
+ Peer() = default;
+ Peer(const Peer&) = delete;
+ Peer& operator=(const Peer&) = delete;
+ int fd = -1;
+ SSL* ssl = nullptr;
+ ~Peer() {
+ if (ssl)
+ SSL_free(ssl);
+ if (fd >= 0)
+ close(fd);
+ }
+ void send(const json& value) {
+ const auto bytes = value.dump() + "\n";
+ size_t at = 0;
+ while (at < bytes.size()) {
+ const int n = ssl ? SSL_write(ssl, bytes.data() + at, bytes.size() - at)
+ : ::send(fd, bytes.data() + at, bytes.size() - at, MSG_NOSIGNAL);
+ if (n <= 0)
+ throw std::runtime_error("peer write failed");
+ at += n;
+ }
+ }
+ json next(std::chrono::milliseconds timeout = 3s) {
+ const auto deadline = std::chrono::steady_clock::now() + timeout;
+ for (;;) {
+ const auto newline = buffer.find('\n');
+ if (newline != std::string::npos) {
+ auto line = buffer.substr(0, newline);
+ buffer.erase(0, newline + 1);
+ if (line == "OK" || line.empty())
+ continue;
+ return json::parse(line);
+ }
+ const auto left =
+ std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
+ if (left <= 0ms)
+ return {};
+ pollfd pfd{fd, POLLIN, 0};
+ if (!(ssl && SSL_pending(ssl)) && poll(&pfd, 1, left.count()) <= 0)
+ return {};
+ char bytes[8192];
+ const int n = ssl ? SSL_read(ssl, bytes, sizeof(bytes)) : read(fd, bytes, sizeof(bytes));
+ if (n <= 0)
+ return {};
+ buffer.append(bytes, n);
+ }
+ }
+ json until(const std::string& command) {
+ const auto deadline = std::chrono::steady_clock::now() + 3s;
+ while (std::chrono::steady_clock::now() < deadline) {
+ auto value = next(
+ std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()));
+ if (value.is_null() || value.value("command", "") == command)
+ return value;
+ }
+ return {};
+ }
+
+ private:
+ std::string buffer;
+ };
+
+ std::string contents(const fs::path& path) {
+ std::ifstream in(path);
+ return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
+ }
+
+ class HeadlessRuntime : public ::testing::Test {
+ protected:
+ fs::path root;
+ std::map<std::string, std::string> env;
+ std::vector<pid_t> children;
+
+ void SetUp() override {
+ char dir[] = "/tmp/tether-h-XXXXXX";
+ ASSERT_NE(mkdtemp(dir), nullptr);
+ root = dir;
+ for (const auto* name : {"bin", "home", "runtime", "downloads"})
+ fs::create_directory(root / name);
+ fs::copy_file(TETHERD_TEST_PATH, root / "bin/tetherd");
+ fs::copy_file(TETHER_CLI_TEST_PATH, root / "bin/tether");
+ env = {{"HOME", (root / "home").string()},
+ {"XDG_CONFIG_HOME", (root / "home/.config").string()},
+ {"XDG_DATA_HOME", (root / "home/.local/share").string()},
+ {"XDG_STATE_HOME", (root / "home/.local/state").string()},
+ {"XDG_RUNTIME_DIR", (root / "runtime").string()},
+ {"XDG_DOWNLOAD_DIR", (root / "downloads").string()},
+ {"DBUS_SESSION_BUS_ADDRESS", "unix:path=" + (root / "bus").string()},
+ {"DBUS_SYSTEM_BUS_ADDRESS", "unix:path=" + (root / "no-system-bus").string()},
+ {"WAYLAND_DISPLAY", ""},
+ {"DISPLAY", ""},
+ {"PATH", "/usr/bin:/bin"},
+ {"TETHER_LOG_STDERR", "1"},
+ {"TETHER_NO_AUTOSTART", "1"}};
+ }
+ void TearDown() override {
+ for (auto it = children.rbegin(); it != children.rend(); ++it) {
+ // Each test child owns its process group, including any dialog helpers.
+ kill(-*it, SIGKILL);
+ int status;
+ waitpid(*it, &status, 0);
+ }
+ fs::remove_all(root);
+ }
+ pid_t spawn(const std::vector<std::string>& args, const std::string& log = "daemon.log") {
+ std::vector<char*> argv;
+ for (const auto& arg : args)
+ argv.push_back(const_cast<char*>(arg.c_str()));
+ argv.push_back(nullptr);
+ const auto output = (root / log).string();
+ const pid_t pid = fork();
+ if (pid == 0) {
+ if (setpgid(0, 0) != 0)
+ _exit(126);
+ umask(0077);
+ for (const auto& [key, value] : env) {
+ if (value.empty())
+ unsetenv(key.c_str());
+ else
+ setenv(key.c_str(), value.c_str(), 1);
+ }
+ const int fd = open(output.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
+ if (fd < 0)
+ _exit(126);
+ dup2(fd, STDOUT_FILENO);
+ dup2(fd, STDERR_FILENO);
+ close(fd);
+ execv(argv[0], argv.data());
+ _exit(127);
+ }
+ if (pid < 0)
+ throw std::runtime_error("fork failed");
+ children.push_back(pid);
+ return pid;
+ }
+ int finish(pid_t pid) {
+ int status = 0;
+ const auto deadline = std::chrono::steady_clock::now() + 5s;
+ while (std::chrono::steady_clock::now() < deadline) {
+ if (waitpid(pid, &status, WNOHANG) == pid) {
+ children.erase(std::find(children.begin(), children.end(), pid));
+ return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
+ }
+ std::this_thread::sleep_for(10ms);
+ }
+ throw std::runtime_error("child timed out");
+ }
+ void start(Peer& local) {
+ spawn({"/usr/bin/dbus-daemon",
+ "--session",
+ "--nofork",
+ "--nopidfile",
+ "--address=" + env["DBUS_SESSION_BUS_ADDRESS"]},
+ "bus.log");
+ for (int i = 0; i < 100 && !fs::exists(root / "bus"); ++i)
+ std::this_thread::sleep_for(10ms);
+ spawn({(root / "bin/tetherd").string()});
+ const auto path = (root / "runtime/tether/tetherd.sock").string();
+ for (int i = 0; i < 300; ++i) {
+ local.fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ strcpy(address.sun_path, path.c_str());
+ if (connect(local.fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0) {
+ // Unix bind precedes TCP startup. Wait for our daemon's event
+ // loop so a port conflict cannot send a test to another daemon.
+ local.send({{"command", "state_snapshot"}});
+ if (local.until("state_snapshot").value("command", "") != "state_snapshot")
+ throw std::runtime_error("daemon did not become ready: " + contents(root / "daemon.log"));
+ return;
+ }
+ close(local.fd);
+ local.fd = -1;
+ std::this_thread::sleep_for(10ms);
+ }
+ throw std::runtime_error("daemon did not start: " + contents(root / "daemon.log"));
+ }
+ void connect_phone(Peer& phone) {
+ // The peer has its own identity; never reuse the daemon's certificate.
+ const auto peer_home = (root / "peer").string();
+ tether::testing::ScopedEnv home("HOME", peer_home);
+ tether::testing::ScopedEnv config("XDG_CONFIG_HOME", peer_home + "/.config");
+ tether::Crypto::instance().reset_for_tests();
+ ASSERT_TRUE(tether::Crypto::instance().init());
+ phone.fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ sockaddr_in address{};
+ address.sin_family = AF_INET;
+ address.sin_port = htons(5134);
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ ASSERT_EQ(connect(phone.fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)), 0);
+ timeval timeout{3, 0};
+ setsockopt(phone.fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
+ setsockopt(phone.fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
+ phone.ssl = SSL_new(tether::Crypto::instance().get_client_context());
+ SSL_set_fd(phone.ssl, phone.fd);
+ ASSERT_EQ(SSL_connect(phone.ssl), 1);
+ }
+ void check_pending_pair() {
+ Peer local, phone;
+ start(local);
+ connect_phone(phone);
+ phone.send({{"command", "pair_request"}, {"device_name", "test phone"}});
+ ASSERT_EQ(phone.until("pair_pending").value("command", ""), "pair_pending");
+ EXPECT_TRUE(phone.next(400ms).is_null()) << "a missing GUI must not reject or accept the request";
+ phone.send({{"command", "clipboard_set"}, {"content", "not authorized"}});
+ EXPECT_EQ(phone.until("error").value("message", ""), "unauthorized");
+ local.send({{"command", "state_snapshot"}});
+ EXPECT_EQ(local.until("state_snapshot")["pending_pairs"].size(), 1u);
+ const auto fp = tether::Crypto::instance().get_my_fingerprint();
+ local.send({{"command", "accept_device"}, {"fingerprint", fp}});
+ EXPECT_TRUE(local.until("accept_device_result").value("connected", false));
+ EXPECT_EQ(phone.until("pair_accepted").value("command", ""), "pair_accepted");
+ EXPECT_EQ(json::parse(contents(root / "home/.config/tether/known_hosts.json"))[fp], "test phone");
+ }
+ };
+
+ TEST_F(HeadlessRuntime, NoWaylandLeavesPairingPendingForExplicitApproval) {
+ std::ofstream(root / "bin/tether-dialog")
+ << "#!/bin/sh\nprintf invoked > '" << (root / "dialog-invoked").string() << "'\nexit 0\n";
+ fs::permissions(root / "bin/tether-dialog", fs::perms::owner_all);
+ check_pending_pair();
+ EXPECT_FALSE(fs::exists(root / "dialog-invoked"));
+ }
+
+ TEST_F(HeadlessRuntime, MissingDialogLeavesPairingPendingForExplicitApproval) {
+ env["WAYLAND_DISPLAY"] = "missing-wayland";
+ check_pending_pair();
+ }
+
+ class DialogRejection : public HeadlessRuntime, public ::testing::WithParamInterface<int> {};
+ TEST_P(DialogRejection, ExplicitRejectionAndTimeoutAreNotTreatedAsMissingGui) {
+ env["WAYLAND_DISPLAY"] = "test-display";
+ std::ofstream(root / "bin/tether-dialog") << "#!/bin/sh\nexit " << GetParam() << "\n";
+ fs::permissions(root / "bin/tether-dialog", fs::perms::owner_all);
+ Peer local, phone;
+ start(local);
+ connect_phone(phone);
+ phone.send({{"command", "pair_request"}, {"device_name", "test phone"}});
+ EXPECT_EQ(phone.until("pair_rejected").value("command", ""), "pair_rejected");
+ local.send({{"command", "state_snapshot"}});
+ EXPECT_TRUE(local.until("state_snapshot")["paired_devices"].empty());
+ }
+ INSTANTIATE_TEST_SUITE_P(DialogExit, DialogRejection, ::testing::Values(1, 2));
+
+ TEST_F(HeadlessRuntime, CliApprovalSupersedesAnOutstandingDialog) {
+ env["WAYLAND_DISPLAY"] = "test-display";
+ std::ofstream(root / "bin/tether-dialog") << "#!/bin/sh\nexec sleep 5\n";
+ fs::permissions(root / "bin/tether-dialog", fs::perms::owner_all);
+ Peer local, phone;
+ start(local);
+ connect_phone(phone);
+ phone.send({{"command", "pair_request"}, {"device_name", "test phone"}});
+ ASSERT_EQ(phone.until("pair_pending").value("command", ""), "pair_pending");
+ local.send({{"command", "accept_device"}, {"fingerprint", tether::Crypto::instance().get_my_fingerprint()}});
+ ASSERT_TRUE(local.until("accept_device_result").value("connected", false));
+ EXPECT_EQ(phone.until("pair_accepted").value("command", ""), "pair_accepted");
+ EXPECT_TRUE(phone.next(400ms).is_null()) << "the superseded dialog must not reject the accepted peer";
+ }
+
+ TEST_F(HeadlessRuntime, ExplicitStderrLoggingDoesNotCreateALogFile) {
+ env["XDG_RUNTIME_DIR"] = "/dev/null"; // deterministic startup error, before networking
+ EXPECT_NE(finish(spawn({(root / "bin/tetherd").string()})), 0);
+ EXPECT_NE(contents(root / "daemon.log").find("Initialization error"), std::string::npos);
+ EXPECT_FALSE(fs::exists(root / "home/.local/state/tether/tetherd.log"));
+ }
+
+ TEST_F(HeadlessRuntime, DefaultLoggingStillUsesTheStateDirectory) {
+ env["XDG_RUNTIME_DIR"] = "/dev/null";
+ for (const auto* value : {"", "0", "true"}) {
+ env["TETHER_LOG_STDERR"] = value;
+ EXPECT_NE(finish(spawn({(root / "bin/tetherd").string()})), 0);
+ EXPECT_TRUE(contents(root / "daemon.log").empty());
+ EXPECT_NE(contents(root / "home/.local/state/tether/tetherd.log").find("Initialization error"),
+ std::string::npos);
+ fs::remove(root / "home/.local/state/tether/tetherd.log");
+ }
+ }
+
+ TEST_F(HeadlessRuntime, CliAutostartCanBeDisabledWithoutChangingTheDefault) {
+ fs::remove(root / "bin/tetherd");
+ std::ofstream(root / "bin/tetherd") << "#!/bin/sh\nprintf invoked > '" << (root / "spawned").string() << "'\n";
+ fs::permissions(root / "bin/tetherd", fs::perms::owner_all);
+ for (const auto* value : {"1", "", "0", "true"}) {
+ env["TETHER_NO_AUTOSTART"] = value;
+ EXPECT_NE(finish(spawn({(root / "bin/tether").string(), "status"}, "cli.log")), 0);
+ EXPECT_EQ(fs::exists(root / "spawned"), std::string(value) != "1") << value;
+ fs::remove(root / "spawned");
+ }
+ }
+
+ TEST_F(HeadlessRuntime, StatusRejectsWrongRepliesAndAcceptsFirstLineSnapshots) {
+ fs::create_directory(root / "runtime/tether");
+ const auto path = (root / "runtime/tether/tetherd.sock").string();
+ for (const auto& [reply, expected] : std::vector<std::pair<std::string, int>>{
+ {"{\"command\":\"unrelated\"}\n", 1},
+ {"not json\n", 1},
+ {"{\"command\":\"state_snapshot\"}\n{\"command\":\"unrelated\"}\n", 0}}) {
+ unlink(path.c_str());
+ Peer listener;
+ listener.fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ strcpy(address.sun_path, path.c_str());
+ ASSERT_EQ(bind(listener.fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)), 0);
+ ASSERT_EQ(listen(listener.fd, 1), 0);
+ auto pid = spawn({(root / "bin/tether").string(), "status"}, "cli.log");
+ pollfd ready{listener.fd, POLLIN, 0};
+ ASSERT_GT(poll(&ready, 1, 3000), 0);
+ Peer client;
+ client.fd = accept4(listener.fd, nullptr, nullptr, SOCK_CLOEXEC);
+ ASSERT_GE(client.fd, 0);
+ EXPECT_EQ(client.next().value("command", ""), "state_snapshot");
+ ASSERT_EQ(::send(client.fd, reply.data(), reply.size(), MSG_NOSIGNAL), static_cast<ssize_t>(reply.size()));
+ EXPECT_EQ(finish(pid), expected) << reply;
+ }
+ }
+
+ TEST_F(HeadlessRuntime, StatusReassemblesAFragmentedSnapshot) {
+ fs::create_directory(root / "runtime/tether");
+ Peer listener;
+ listener.fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ strcpy(address.sun_path, (root / "runtime/tether/tetherd.sock").c_str());
+ ASSERT_EQ(bind(listener.fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)), 0);
+ ASSERT_EQ(listen(listener.fd, 1), 0);
+ const auto pid = spawn({(root / "bin/tether").string(), "status"}, "cli.log");
+ pollfd ready{listener.fd, POLLIN, 0};
+ ASSERT_GT(poll(&ready, 1, 3000), 0);
+ Peer client;
+ client.fd = accept4(listener.fd, nullptr, nullptr, SOCK_CLOEXEC);
+ ASSERT_GE(client.fd, 0);
+ EXPECT_EQ(client.next().value("command", ""), "state_snapshot");
+ const std::string first = "{\"command\":\"state_";
+ const std::string last = "snapshot\"}\n";
+ ASSERT_EQ(::send(client.fd, first.data(), first.size(), MSG_NOSIGNAL), static_cast<ssize_t>(first.size()));
+ std::this_thread::sleep_for(100ms);
+ // A broken client may already have closed; finish(pid) is the behavior assertion.
+ ::send(client.fd, last.data(), last.size(), MSG_NOSIGNAL);
+ EXPECT_EQ(finish(pid), 0);
+ }
+
+ TEST_F(HeadlessRuntime, ReceiveEventsDoNotDependOnNotifierInitialization) {
+ env["LD_PRELOAD"] = TETHER_NOTIFY_FIXTURE;
+ Peer local, phone;
+ start(local);
+ connect_phone(phone);
+ phone.send({{"command", "pair_request"}, {"device_name", "test phone"}});
+ ASSERT_EQ(phone.until("pair_pending").value("command", ""), "pair_pending");
+ local.send({{"command", "accept_device"}, {"fingerprint", tether::Crypto::instance().get_my_fingerprint()}});
+ ASSERT_TRUE(local.until("accept_device_result").value("connected", false));
+ ASSERT_EQ(phone.until("pair_accepted").value("command", ""), "pair_accepted");
+ local.send({{"command", "subscribe"}});
+ ASSERT_EQ(local.until("bt_connection_changed").value("command", ""), "bt_connection_changed");
+ phone.send({{"command", "file_start"}, {"filename", "hello.txt"}, {"size", 5}, {"transfer_id", "complete"}});
+ phone.send({{"command", "file_chunk"}, {"transfer_id", "complete"}, {"chunk_index", 0}, {"data", "aGVsbG8="}});
+ phone.send({{"command", "file_end"}, {"transfer_id", "complete"}});
+ const auto received = local.until("file_received");
+ ASSERT_FALSE(received.is_null());
+ EXPECT_EQ(received["filename"], "hello.txt");
+ EXPECT_EQ(received["bytes_written"], 5);
+ EXPECT_EQ(contents(root / "downloads/hello.txt"), "hello");
+ local.send({{"command", "state_snapshot"}});
+ EXPECT_EQ(local.until("state_snapshot")["recent_received_files"].size(), 1u);
+ phone.send({{"command", "file_start"}, {"filename", "partial.txt"}, {"size", 5}, {"transfer_id", "partial"}});
+ phone.send({{"command", "file_end"}, {"transfer_id", "partial"}});
+ EXPECT_TRUE(local.next(200ms).is_null());
+ EXPECT_FALSE(fs::exists(root / "downloads/partial.txt"));
+ }
+
+} // namespace