From 53c0e776824fefcd7c100dff114fea387cba1095 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 20:32:23 +0000 Subject: [PATCH 01/19] security: pin CI actions to commit SHAs, stop leaking fds to root children Supply-chain re-scan (docs/SECURITY-AUDIT.md, 2026-11-07 addendum): - Pin every GitHub Action to a full commit SHA (same majors, latest patch) instead of a mutable tag; the packaging jobs hold the Developer ID certificate and notary key. Dependabot proposes updates. - actions/checkout: persist-credentials: false everywhere; no job pushes with git. - process_runner: spawn ipconfig/route with POSIX_SPAWN_CLOEXEC_DEFAULT and /dev/null stdin, so they no longer inherit the daemon's BPF, socket and libusb descriptors. - libusb: 1.0.30 is still the latest release; the pinned tarball hash was re-verified against the GitHub release asset. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015mjUJdY1Lr5qCEHAzbbHPK --- .github/dependabot.yml | 12 ++++ .github/workflows/ci.yml | 32 +++++++---- .github/workflows/release.yml | 4 +- docs/SECURITY-AUDIT.md | 68 +++++++++++++++++++++++ include/tetherkitnext/common/messages.def | 2 + src/capi/process_runner.cc | 21 ++++++- 6 files changed, 126 insertions(+), 13 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..76e3121 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# Keeps the SHA-pinned GitHub Actions in .github/workflows current. +# Actions are pinned to full commit SHAs (a moved tag cannot swap the code +# that runs with our signing secrets); Dependabot proposes the bumps as PRs. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions: + patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34d43a0..f59614f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,14 +44,16 @@ jobs: matrix: os: [macos-15, macos-26, macos-15-intel] steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Toolchain run: | sw_vers; uname -m; cmake --version; c++ --version - name: Cache libusb - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: build/libusb-universal key: libusb-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-libusb.sh') }} @@ -86,7 +88,9 @@ jobs: runs-on: macos-26 timeout-minutes: 45 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Select the newest Xcode run: | @@ -126,7 +130,7 @@ jobs: fi plutil -p "$app/Contents/Library/LaunchDaemons/com.tetherkitnext.helperd.plist" - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: TetherKitNext-dmg path: | @@ -143,7 +147,7 @@ jobs: runs-on: macos-15-intel timeout-minutes: 45 steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: TetherKitNext-dmg - name: Mount, copy to /Applications, run @@ -180,7 +184,7 @@ jobs: timeout-minutes: 15 continue-on-error: true steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: TetherKitNext-dmg path: built @@ -212,7 +216,7 @@ jobs: for dmg in built/*.dmg; do shoot "$dmg" "ci-build"; done for dmg in released/*.dmg; do [ -f "$dmg" ] && shoot "$dmg" "published-release"; done ls -l shots - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: dmg-window-${{ matrix.os }} path: shots/*.png @@ -226,7 +230,9 @@ jobs: runs-on: macos-26 timeout-minutes: 45 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Build libusb run: ./scripts/build-libusb.sh "$PWD/build-tsan/libusb-universal" - name: Configure & build @@ -252,7 +258,9 @@ jobs: matrix: os: [macos-15, macos-26, macos-15-intel] steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Build run: | ./scripts/build-libusb.sh "$PWD/build/libusb-universal" @@ -294,7 +302,9 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Validate tag env: @@ -306,7 +316,7 @@ jobs: [ "${BASH_REMATCH[1]}" = "$version" ] \ || { echo "::error::tag ${TAG} does not match CMakeLists VERSION ${version}"; exit 1; } - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: TetherKitNext-dmg path: artifact diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dd9440f..3d6fb94 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -42,7 +42,9 @@ jobs: runs-on: macos-26 timeout-minutes: 90 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Check if release already exists id: existing diff --git a/docs/SECURITY-AUDIT.md b/docs/SECURITY-AUDIT.md index cb459a9..3e1ef2b 100644 --- a/docs/SECURITY-AUDIT.md +++ b/docs/SECURITY-AUDIT.md @@ -153,3 +153,71 @@ a string that disappeared when log messages were localized. It now pins of people who can act is unchanged. The residual risk moves to the app: a bug that skips `UserPresence.confirm` before a privileged call would skip the prompt. Keep every privileged call behind `AppModel.authorized`. + +--- + +## Addendum: 2026-11-07 re-scan + +Re-scan prompted by the recent run of supply-chain attacks (hijacked +GitHub Action tags, poisoned release tarballs). Base: `2e92841` (1.2.0). + +### Dependencies + +| Component | Pinned | Latest upstream | Verdict | +|---|---|---|---| +| libusb | 1.0.30 (`scripts/build-libusb.sh`) | **1.0.30** (2026-05-17); no newer release or release candidate | Up to date. The pinned SHA-256 was re-checked against the GitHub release asset: `fea36f34…dbaf`, match. | +| doctest | 2.4.12 (vendored, test-only) | n/a | Not shipped. | + +libusb `master` has darwin fixes since 1.0.30 (interface claim/re-claim +bookkeeping after a failed state restore, run-loop reference handling, +parent-session refresh on re-enumeration) and a memory-safety fix in +`libusb_get_port_numbers` (`1110f3a`, a write before the caller's array +when a re-enumerated device's parent chain grows between two passes). +TetherKitNext calls none of `libusb_get_port_numbers`, +`libusb_set_configuration` or `libusb_reset_device`, so none of these is +reachable from our code. **Decision: stay on the signed 1.0.30 release** and +take 1.0.31 when it is tagged, rather than shipping an untagged snapshot. + +### CI supply chain (fixed) + +**S1. GitHub Actions were referenced by mutable tags** (`actions/checkout@v5`, +…). A moved tag runs new code in jobs that hold the Developer ID certificate +and notary key. All `uses:` are now pinned to full commit SHAs (same major +versions, latest patch: checkout v5.1.0, cache v4.3.0, upload-artifact v4.6.2, +download-artifact v4.3.0), with `.github/dependabot.yml` proposing updates. + +**S2. `actions/checkout` persisted the job token in `.git/config`.** No job +pushes with git (the prerelease job uses `GH_TOKEN` via `gh`), so every +checkout now sets `persist-credentials: false`; a compromised build step can +no longer read the token from disk. + +Reviewed and fine: workflow-level `permissions: contents: read` with +`contents: write` only on the release/prerelease jobs; no +`pull_request_target`; secrets only reach non-PR events, so fork PRs build +ad-hoc signed; the libusb tarball is hash-verified before use. + +### Code (fixed) + +**L3. Root child processes inherited every open descriptor.** +`posix_spawn` without `POSIX_SPAWN_CLOEXEC_DEFAULT` passes the daemon's +descriptors that lack `FD_CLOEXEC` (BPF device, routing / `feth` sockets, +libusb's internal pipes) to `ipconfig` and `route`. Those are +Apple binaries, so this was not exploitable on its own, but a root process +should hand a child exactly stdin/stdout/stderr. `process_runner.cc` now sets +`POSIX_SPAWN_CLOEXEC_DEFAULT` and gives the child `/dev/null` as stdin. + +### Re-reviewed with no new issue + +* RNDIS decoding of device data (`packet_codec.h`, `messages.cc`): 64-bit + bounds arithmetic, `MessageLength ≥ 44` guarantees forward progress, + alignment factor and transfer size clamps intact. +* XPC: Team-ID requirement on every connection for signed builds; privileged + calls re-verify an authorization or the presence path (`admin` group); + unauthenticated calls are read-only (`queryNetwork` validates the interface + name in the C ABI). +* CLI symlink: `lstat`/`readlink`/`symlink` never follow links; foreign + entries are reported, not replaced. +* New in this change: the Advanced → Interfaces page reads `getifaddrs` and + the `NET_RT_IFLIST2` sysctl in the unprivileged app. It parses kernel data + with bounds checks (`ifm_msglen` validated against the buffer before each + step) and sends nothing to the daemon or the network. diff --git a/include/tetherkitnext/common/messages.def b/include/tetherkitnext/common/messages.def index dab6cab..327bad1 100644 --- a/include/tetherkitnext/common/messages.def +++ b/include/tetherkitnext/common/messages.def @@ -639,6 +639,8 @@ TETHERKITNEXT_MESSAGE(kCoreLinkUnrecoverable, "链路不可恢复", "the link is TETHERKITNEXT_MESSAGE(kCapiPipeFailed, "创建管道失败", "failed to create a pipe") TETHERKITNEXT_MESSAGE(kCapiSpawnFileActionsFailed, "posix_spawn_file_actions_init 失败", "posix_spawn_file_actions_init failed") +TETHERKITNEXT_MESSAGE(kCapiSpawnAttributesFailed, "posix_spawnattr_init 失败", + "posix_spawnattr_init failed") TETHERKITNEXT_MESSAGE(kCapiExecFailed, "无法执行 {}", "cannot execute {}") TETHERKITNEXT_MESSAGE(kCapiWaitFailed, "等待 {} 结束失败", "failed to wait for {} to finish") diff --git a/src/capi/process_runner.cc b/src/capi/process_runner.cc index 80df01d..138a404 100644 --- a/src/capi/process_runner.cc +++ b/src/capi/process_runner.cc @@ -1,6 +1,7 @@ #include "tetherkitnext/common/i18n.h" #include "process_runner.h" +#include #include #include #include @@ -60,6 +61,8 @@ Result Spawn(std::string_view executable, return std::unexpected(Error::FromErrno(rc, Tr(Msg::kCapiSpawnFileActionsFailed))); } // Child process: close the read end, connect the write end to stdout and stderr, then close the original write end. + // stdin comes from /dev/null rather than whatever the daemon inherited. + ::posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0); ::posix_spawn_file_actions_addclose(&actions, pipe_fds[0]); ::posix_spawn_file_actions_adddup2(&actions, pipe_fds[1], STDOUT_FILENO); ::posix_spawn_file_actions_adddup2(&actions, pipe_fds[1], STDERR_FILENO); @@ -74,9 +77,25 @@ Result Spawn(std::string_view executable, static char kLangVar[] = "LANG=C"; std::array clean_environment{kPathVar, kLangVar, nullptr}; + // POSIX_SPAWN_CLOEXEC_DEFAULT (Darwin): the child inherits only the + // descriptors the file actions above set up (stdin/stdout/stderr). Without + // it every descriptor this root process holds that lacks FD_CLOEXEC -- the + // BPF device, feth control sockets, libusb's pipes, the XPC listener's + // descriptors -- would leak into ipconfig / route. + ::posix_spawnattr_t attributes{}; + if (const int rc = ::posix_spawnattr_init(&attributes); rc != 0) { + ::posix_spawn_file_actions_destroy(&actions); + ::close(pipe_fds[0]); + ::close(pipe_fds[1]); + return std::unexpected(Error::FromErrno(rc, Tr(Msg::kCapiSpawnAttributesFailed))); + } + // NOLINTNEXTLINE(google-runtime-int): posix_spawnattr_setflags takes a short. + ::posix_spawnattr_setflags(&attributes, static_cast(POSIX_SPAWN_CLOEXEC_DEFAULT)); + ::pid_t child = -1; - const int spawn_rc = ::posix_spawn(&child, executable_path.c_str(), &actions, nullptr, + const int spawn_rc = ::posix_spawn(&child, executable_path.c_str(), &actions, &attributes, argv.data(), clean_environment.data()); + ::posix_spawnattr_destroy(&attributes); ::posix_spawn_file_actions_destroy(&actions); // The parent process must close the write end immediately, otherwise ReadAll will never see EOF -- it is itself still holding a // write end, so the pipe never closes. This is the classic pipe deadlock. From 6d161ab8ea864edc9030acee447d85e6717734c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 20:32:23 +0000 Subject: [PATCH 02/19] ci: run builds, the feth ABI gate and a GUI launch test on macOS 27 GitHub's xcode-27 image runs macOS 27 Golden Gate. Add it to the native C++ and root feth ABI matrices, plus a job that builds the app with Xcode 27, runs the Swift tests and checks that the bundled app launches and stays up. docs/MACOS-27.md reviews the macOS 27, 27.2 and 27.3 release notes against what TetherKitNext uses. Nothing documented breaks us; the launchd quarantined-plist change needs a check with a downloaded, notarized DMG on real hardware. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015mjUJdY1Lr5qCEHAzbbHPK --- .github/workflows/ci.yml | 53 ++++++++++++++++++++++++++++++++++++-- docs/MACOS-27.md | 55 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 docs/MACOS-27.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f59614f..129d078 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,7 +42,8 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-15, macos-26, macos-15-intel] + # xcode-27 is GitHub's macOS 27 (Golden Gate) image: Apple silicon only. + os: [macos-15, macos-26, macos-15-intel, xcode-27] steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: @@ -222,6 +223,53 @@ jobs: path: shots/*.png if-no-files-found: warn + # ---------------------------------------------------------------------------- + # macOS 27 (Golden Gate) with the Xcode 27 toolchain: the GUI builds with the + # macOS 27 SDK (Swift 6 strict concurrency, the @State macro), its unit tests + # pass, and the bundled app launches and stays up. Together with the + # native + feth ABI jobs on xcode-27 this is the automated part of the + # Golden Gate support statement (docs/MACOS-27.md lists what still needs a + # real device). + # ---------------------------------------------------------------------------- + gui-macos-27: + name: GUI · macOS 27 (Xcode 27) + runs-on: xcode-27 + timeout-minutes: 45 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + - name: Toolchain + run: | + sw_vers; uname -m + latest="$(ls -d /Applications/Xcode_*.app | sort -V | tail -1)" + sudo xcode-select -s "${latest}" + xcodebuild -version; swift --version + - name: Build C++ (native arch) + run: | + ./scripts/build-libusb.sh "$PWD/build/libusb-universal" + cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DLibUSB_ROOT="$PWD/build/libusb-universal" -DTETHERKITNEXT_BUILD_BENCHMARKS=OFF \ + -DTETHERKITNEXT_WARNINGS_AS_ERRORS=ON + cmake --build build -j"$(sysctl -n hw.ncpu)" + - name: Build app bundle (ad-hoc signed) + run: ./gui/Scripts/build-gui.sh + - name: Swift unit tests + run: TETHERKITNEXT_LIB_DIR="$PWD/build/lib" swift test --package-path gui + - name: Launch smoke test + run: | + app=dist/TetherKitNext.app + otool -l "$app/Contents/MacOS/TetherKitNext" | grep -A4 LC_BUILD_VERSION + "$app/Contents/MacOS/TetherKitNext" > launch.log 2>&1 & + pid=$! + sleep 15 + if ! kill -0 "$pid" 2>/dev/null; then + echo "::error::TetherKitNext exited within 15 s of launch on macOS 27" + cat launch.log; exit 1 + fi + kill "$pid"; wait "$pid" 2>/dev/null || true + echo "✓ app launched and stayed up on $(sw_vers -productVersion)" + # ---------------------------------------------------------------------------- # ThreadSanitizer: the lock-free rings and the park/wake handshake. # ---------------------------------------------------------------------------- @@ -256,7 +304,8 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-15, macos-26, macos-15-intel] + # xcode-27 is GitHub's macOS 27 (Golden Gate) image: Apple silicon only. + os: [macos-15, macos-26, macos-15-intel, xcode-27] steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: diff --git a/docs/MACOS-27.md b/docs/MACOS-27.md new file mode 100644 index 0000000..45c1f31 --- /dev/null +++ b/docs/MACOS-27.md @@ -0,0 +1,55 @@ +# macOS 27 Golden Gate compatibility review + +Date: 2026-11-07 · Sources: Apple's [macOS 27](https://developer.apple.com/documentation/macos-release-notes/macos-27-release-notes), +[27.2](https://developer.apple.com/documentation/macos-release-notes/macos-27_2-release-notes) and +[27.3 beta](https://developer.apple.com/documentation/macos-release-notes/macos-27_3-release-notes) release notes. + +Every release-note item that touches something TetherKitNext uses was checked +against the code. **None of the documented changes breaks TetherKitNext.** +One item (launchd and quarantined property lists) needs a check on a real +machine before release, because the notes don't say whether it covers +`SMAppService` daemons inside a notarized app. + +## How support is verified + +| Layer | How | Status | +|---|---|---| +| C++ driver builds with `-Werror`, all CTest suites pass | CI `native` job on the `xcode-27` runner (macOS 27, Apple silicon) | Automated | +| Private kernel ABI (`if_fake` peer pairing, BPF private ioctls) | CI `abi-check` job on `xcode-27`: creates, pairs and destroys a real `feth` pair as root | Automated | +| GUI builds against the macOS 27 SDK (Swift 6, Xcode 27's `@State` macro) and its unit tests pass | CI `gui-macos-27` job | Automated | +| The bundled app launches and stays up | CI `gui-macos-27` launch smoke test | Automated | +| Real RNDIS session (Android phone) on macOS 27 | Manual, on hardware | **Open** | +| Downloaded, notarized DMG installs and the background component registers | Manual, on hardware | **Open** (see launchd item) | + +Say "runs on macOS 27 Golden Gate" once all CI jobs above are green **and** +the two manual items are ticked. + +## Release-note items reviewed + +| Area (release note) | What changed | Impact on TetherKitNext | +|---|---|---| +| **Launch Daemons and Agents** (166415497) | `launchd` no longer loads property lists that carry the quarantine extended attribute. | **Verify on hardware.** Our daemon plist ships inside the app (`Contents/Library/LaunchDaemons/`) and is registered with `SMAppService`; a DMG download marks the bundle's files quarantined. The notes don't say whether `SMAppService` bundle plists of notarized apps are exempt. Test: download the notarized DMG in Safari, install, open, enable the background component, connect. If it fails, `xattr -dr com.apple.quarantine /Applications/TetherKitNext.app` confirms the cause; the fix would be in the installer flow, not the driver. | +| **Accessory Access** (new framework) | Consent-based USB accessory access for `IOUSBHost` clients, mainly sandboxed apps and virtualization. | None documented. It is opt-in for apps that adopt it; nothing in the notes restricts IOKit user-client access for unsandboxed processes, which is what libusb uses. Covered by the hardware session test. | +| **Rosetta / Deprecation Information** | macOS 27 is the last release that runs Intel apps (Intel apps show a notice in Get Info); Rosetta is not restored after upgrading. | None. The app is universal, so Apple silicon runs the arm64 slice natively and no notice is shown. The x86_64 slice stays for Intel Macs on earlier macOS. | +| **AppKit / SwiftUI menus** (170477566, 170480710, 179374305) | Apps linked against the macOS 26 SDK or later hide symbol images in menu items by default. | None. Our app and context menus are text-only; the menu bar extra uses a window-style panel, not a menu. This now applies to us because the app is stamped with the macOS 26+ SDK (see below). | +| **SwiftUI `@State` macro** (105893279, Xcode 27) | `@State` becomes a macro. A value set both at the declaration and in an initializer no longer compiles, and neither does the synthesized private memberwise init. | None found: every `@State` has an initial value and no initializer assigns it. The `gui-macos-27` CI job compiles the GUI with Xcode 27. | +| **System Integrity Protection / TCC** | Other teams' app containers are denied by default; the TCC database can't be read directly. | None. We touch neither. | +| **Network Security** (176055825) | Stricter TLS requirements for system MDM / install / update processes. | None. Only system processes are affected. Our one outbound call (the optional GitHub release check) is TLS 1.3. | +| **DriverKit / SCSIControllerDriverKit** (27.3) | API additions and deprecations. | None. We ship no driver extension. | +| **NEURLFilter** (27.3) | Info.plist requirements for URL filter providers. | None. We ship no network extension. | + +## Related change: SDK stamp and window chrome + +macOS 26 and later choose the window chrome (traffic-light size and spacing, +title bar metrics, Liquid Glass) from the `sdk` field of the executable's +`LC_BUILD_VERSION`, not from what the code was compiled against. A SwiftPM +link can stamp the deployment target (14.0) there, which gives the whole app +the compatibility look. `gui/Scripts/build-gui.sh` now reads the stamp after +linking. If it is older than the SDK in use, the script rewrites only `sdk` +with `vtool`, using the SDK version actually in use (nothing hard-coded); +`minos` stays 14.0. The script then fails the build if the shipped binary +isn't stamped with SDK 26 or later. Check it on any build: + +```bash +otool -l dist/TetherKitNext.app/Contents/MacOS/TetherKitNext | grep -A4 LC_BUILD_VERSION +``` From ebd60353db5bd43a6189c8d59504972ba3ebf984 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 20:32:24 +0000 Subject: [PATCH 03/19] build(gui): stamp the app with the SDK it was built with macOS 26+ picks a window's chrome from the sdk field of the binary's LC_BUILD_VERSION, and a SwiftPM link can record the deployment target there, which gives the whole app the legacy look. After linking, read minos/sdk with otool; if sdk is older than `xcrun --show-sdk-version`, rewrite only sdk with vtool (minos stays 14.0). The verify step fails the build if the signed app is still stamped below 26. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015mjUJdY1Lr5qCEHAzbbHPK --- gui/Scripts/build-gui.sh | 55 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/gui/Scripts/build-gui.sh b/gui/Scripts/build-gui.sh index 4d9d841..6b9e2e8 100755 --- a/gui/Scripts/build-gui.sh +++ b/gui/Scripts/build-gui.sh @@ -80,13 +80,54 @@ swift_build() { ${SWIFT_BUILD_FLAGS[@]+"${SWIFT_BUILD_FLAGS[@]}"} "${@:2}" } +# ------------------------------------------------------------------------------ +# SDK stamp (LC_BUILD_VERSION). +# +# macOS 26+ picks a window's chrome (traffic lights, title bar metrics, glass) +# from the `sdk` field of the executable's LC_BUILD_VERSION, independently of +# what was actually compiled against: an app stamped with an older SDK gets the +# compatibility ("legacy") appearance. Xcode stamps the SDK in use; a SwiftPM +# link can end up stamping the deployment target instead. The deployment +# target (`minos`) is what decides where the app runs and is left untouched. +# +# Read both fields, and if the stamp is older than the SDK we just built with, +# rewrite only `sdk` (vtool, Xcode command line tools). The bundle is signed +# afterwards, so invalidating the linker's ad-hoc signature here is harmless. +# ------------------------------------------------------------------------------ +SDK_VERSION="$(xcrun --sdk macosx --show-sdk-version)" +SDK_MAJOR="${SDK_VERSION%%.*}" + +build_version_field() { # + otool -l "$1" | awk -v field="$2" ' + $1 == "cmd" && $2 == "LC_BUILD_VERSION" { inside = 1; next } + $1 == "cmd" { inside = 0 } + inside && $1 == field { print $2; exit }' +} + +stamp_sdk() { # + local minos sdk + minos="$(build_version_field "$1" minos)" + sdk="$(build_version_field "$1" sdk)" + [[ -n "${minos}" && -n "${sdk}" ]] || die "no LC_BUILD_VERSION in $1" + if [[ "${sdk%%.*}" -lt "${SDK_MAJOR}" ]]; then + echo " sdk stamp ${sdk} -> ${SDK_VERSION} (minos ${minos} unchanged): $(basename "$1")" + vtool -set-build-version macos "${minos}" "${SDK_VERSION}" -replace -output "$2" "$1" + else + cp "$1" "$2" + fi +} + +STAMP_DIR="$(mktemp -d)" +trap 'rm -rf "${STAMP_DIR}"' EXIT + APP_SLICES=() HELPER_SLICES=() for arch in "${ARCHS[@]}"; do log "Compiling Swift targets for ${arch}" swift_build "${arch}" bin_path="$(swift_build "${arch}" --show-bin-path)" - APP_SLICES+=("${bin_path}/TetherKitNextApp") + stamp_sdk "${bin_path}/TetherKitNextApp" "${STAMP_DIR}/TetherKitNextApp-${arch}" + APP_SLICES+=("${STAMP_DIR}/TetherKitNextApp-${arch}") HELPER_SLICES+=("${bin_path}/tetherkitnext-helper") done @@ -234,6 +275,18 @@ ln -s "${CONTENTS}/MacOS/tetherkitnext-cli" "${probe_dir}/tetherkitnext-cli" rm -rf "${probe_dir}" echo " ✓ CLI runs through a symlink" +# The SDK stamp decides the window chrome on macOS 26+ (see "SDK stamp" above). +# Checked on the final, signed binary so a later step cannot silently undo it. +for arch in "${ARCHS[@]}"; do + thin="${STAMP_DIR}/verify-${arch}" + lipo -thin "${arch}" "${CONTENTS}/MacOS/TetherKitNext" -output "${thin}" 2>/dev/null \ + || cp "${CONTENTS}/MacOS/TetherKitNext" "${thin}" + stamped="$(build_version_field "${thin}" sdk)" + [[ "${stamped%%.*}" -ge 26 ]] \ + || die "TetherKitNext (${arch}) is stamped sdk ${stamped:-none}; macOS 26+ would draw legacy window chrome" +done +echo " ✓ app is stamped with the macOS ${SDK_VERSION} SDK (modern window chrome on macOS 26+)" + cat < Date: Sat, 7 Nov 2026 20:32:36 +0000 Subject: [PATCH 04/19] =?UTF-8?q?feat(gui):=20AppKit-owned=20main=20window?= =?UTF-8?q?,=20testable=20page=20model,=20opt-in=20Advanced=20=E2=86=92=20?= =?UTF-8?q?Interfaces?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main window - MainWindowController owns an NSWindow with an NSHostingController (toolbar/title bridging, sizingOptions = [.minSize]) instead of a SwiftUI Window scene. With a MenuBarExtra, SwiftUI resurrected a closed Window scene whenever the app was activated; the 3-second isWindowPresentationExpected() workaround is gone. - The window opens from applicationDidFinishLaunching (bare `swift run` binaries too); applicationShouldHandleReopen now reaches us, so a Finder double-click reopens it in menu-bar-only mode. - Explicit File ▸ Close (⌘W); without a window scene SwiftUI adds none. It also closes a minimized main window. - Sidebar selection moves from @SceneStorage to @AppStorage (there is no scene to store into). TetherKitNextUIModel (new library target + tests) - Pane: sidebar sections, opt-in advanced pages, stale-selection fallback. Unit-tested. - InterfaceSampler / InterfaceRateTracker: getifaddrs plus 64-bit NET_RT_IFLIST2 counters (getifaddrs' if_data counters are 32-bit and wrap at 4 GiB); handles interfaces recreated with fresh counters. Advanced tools - Settings ▸ General ▸ "Show advanced tools" (off by default) adds an Advanced sidebar section. Its first page, Interfaces, lists every interface with MAC, addresses and live rates. Read-only, unprivileged, no daemon or network traffic. - New strings in all six languages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015mjUJdY1Lr5qCEHAzbbHPK --- gui/Package.swift | 12 +- gui/Sources/TetherKitNextApp/AppModel.swift | 24 +- .../MainWindowController.swift | 145 +++++++++++ .../TetherKitNextApp/TetherKitNextApp.swift | 89 +++---- .../TetherKitNextApp/Views/ContentView.swift | 63 ++--- .../Views/InterfacesPage.swift | 123 +++++++++ .../TetherKitNextApp/Views/MenuBarPanel.swift | 3 +- .../TetherKitNextApp/Views/SettingsPage.swift | 12 + .../TetherKitNextIPC/LocalizedStrings.swift | 84 +++++++ .../InterfaceTraffic.swift | 236 ++++++++++++++++++ gui/Sources/TetherKitNextUIModel/Pane.swift | 75 ++++++ .../InterfaceTrafficTests.swift | 82 ++++++ .../TetherKitNextUIModelTests/PaneTests.swift | 52 ++++ 13 files changed, 883 insertions(+), 117 deletions(-) create mode 100644 gui/Sources/TetherKitNextApp/MainWindowController.swift create mode 100644 gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift create mode 100644 gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift create mode 100644 gui/Sources/TetherKitNextUIModel/Pane.swift create mode 100644 gui/Tests/TetherKitNextUIModelTests/InterfaceTrafficTests.swift create mode 100644 gui/Tests/TetherKitNextUIModelTests/PaneTests.swift diff --git a/gui/Package.swift b/gui/Package.swift index 6b063e6..9ec19f0 100644 --- a/gui/Package.swift +++ b/gui/Package.swift @@ -103,9 +103,17 @@ let package = Package( // The SwiftUI App that users see (running as an ordinary user). .executableTarget(name: "TetherKitNextApp", - dependencies: ["TetherKitNextCore", "TetherKitNextIPC"]), + dependencies: ["TetherKitNextCore", "TetherKitNextIPC", + "TetherKitNextUIModel"]), + + // UI logic that deserves unit tests: sidebar composition and + // persisted-selection rules, interface traffic sampling. A library of + // its own because an executable target cannot be @testable-imported. + // No libtetherkitnext dependency, so its tests run without the C++ build. + .target(name: "TetherKitNextUIModel", dependencies: ["TetherKitNextIPC"]), - // Tests only TetherKitNextIPC: it is the only "pure logic, touches no hardware and needs no root" layer. + // Tests cover the pure-logic layers (TetherKitNextIPC, TetherKitNextUIModel): no hardware, no root. // Tests of sessions and NIC configuration are on the C++ side (tests/test_capi.cc), and are not repeated here. .testTarget(name: "TetherKitNextIPCTests", dependencies: ["TetherKitNextIPC"]), + .testTarget(name: "TetherKitNextUIModelTests", dependencies: ["TetherKitNextUIModel"]), ]) diff --git a/gui/Sources/TetherKitNextApp/AppModel.swift b/gui/Sources/TetherKitNextApp/AppModel.swift index 9b5bb87..09745cb 100644 --- a/gui/Sources/TetherKitNextApp/AppModel.swift +++ b/gui/Sources/TetherKitNextApp/AppModel.swift @@ -187,13 +187,10 @@ final class AppModel { /// The moment of the last device enumeration. A monotonic clock is used, avoiding negative intervals when the system time is adjusted. private var lastDeviceRefresh: ContinuousClock.Instant? - /// Whether the main window is currently visible. It only affects the polling pace; the Dock icon policy is handled at the view layer. + /// Whether the main window is currently visible. It only affects the polling pace; the Dock icon + /// policy is derived from AppKit window notifications in AppDelegate. private var isWindowVisible = true - /// The moment of the most recent "explicitly asked to show the main window". The initial value = now, because the App's launch itself - /// is a legitimate window presentation. - private var windowPresentationRequestedAt = ContinuousClock.now - /// The cached authorization token. nil means the next privileged operation needs to pop up a dialog. /// /// It does not keep its own expiry time: the system's timeout is controlled by the authorization database (and may be changed by an administrator), @@ -294,23 +291,6 @@ final class AppModel { isWindowVisible = false } - /// Registers that "this upcoming main window presentation is one we asked for ourselves". - /// - /// Registered once at App launch (initializing defaults) and once by the "open main window" button. - func expectWindowPresentation() { - windowPresentationRequestedAt = ContinuousClock.now - } - - /// Whether this window appearance was requested by ourselves. - /// - /// SwiftUI will on its own recreate the Window scene when "an App without windows is activated" (clicking the menu bar icon triggers it), - /// and such a revival must be closed on the spot. A time window rather than a one-shot flag is used to decide: - /// "registered within the last 3 seconds" counts -- a one-shot flag would linger on paths like - /// "click open again while the window is already open", while a time window heals itself naturally. - func isWindowPresentationExpected() -> Bool { - ContinuousClock.now - windowPresentationRequestedAt < .seconds(3) - } - /// The polling interval that should be used right now. /// /// Three cases use the fast pace: a session is running (the menu bar shows real-time rates), starting/stopping diff --git a/gui/Sources/TetherKitNextApp/MainWindowController.swift b/gui/Sources/TetherKitNextApp/MainWindowController.swift new file mode 100644 index 0000000..b0199aa --- /dev/null +++ b/gui/Sources/TetherKitNextApp/MainWindowController.swift @@ -0,0 +1,145 @@ +import AppKit +import SwiftUI +import TetherKitNextIPC + +/// Owns the main window as a plain AppKit `NSWindow`. +/// +/// ★ Why not a SwiftUI `Window` scene ★ +/// +/// * With a `MenuBarExtra` alongside, SwiftUI recreates a closed `Window` +/// scene whenever the windowless app is activated, which clicking the menu +/// bar item does. The old workaround (`AppModel.isWindowPresentationExpected`, +/// a 3-second "did we ask for this?" window) dismissed the resurrected +/// window after the fact, so it could still flash. With no window scene, +/// SwiftUI has nothing to resurrect. +/// * Presentation becomes deterministic: the window exists from +/// `applicationDidFinishLaunching`, also for bare `swift run` binaries, and +/// `applicationShouldHandleReopen` (Dock / Finder double-click while in +/// menu-bar-only mode) reaches us, so reopening brings it back. +/// +/// SwiftUI still renders everything inside it: an `NSHostingController` +/// with toolbar and title bridging, so `.toolbar` / `.navigationTitle` in +/// ContentView keep working. +/// +/// ★ Closing ★ +/// +/// `isReleasedWhenClosed = false`: the red button, File ▸ Close (⌘W) and +/// `close()` only order the window out. The SwiftUI view tree stays alive +/// (cheap, and reopening is instant); AppDelegate's window notifications +/// drop the app to the `.accessory` policy (menu-bar-only mode). +/// +/// ★ Size stability ★ +/// +/// `sizingOptions = [.minSize]`: the hosting controller pushes only the +/// content's minimum size into the window. Its default also publishes the +/// preferred (intrinsic) size, and pages have different intrinsic heights, +/// so switching pages would resize the window, which macOS 26 animates in +/// step with the content change. Set before the controller becomes the +/// window's content, so the first layout already uses it. +@MainActor +final class MainWindowController: NSObject, NSWindowDelegate { + /// Set once at launch by AppDelegate; nil only before that. + private(set) static var shared: MainWindowController? + + private let model: AppModel + private let window: NSWindow + + /// Frame autosave name: the window reopens where the user left it. + private static let autosaveName = "TetherKitNextMainWindow" + + static func install(model: AppModel) -> MainWindowController { + if let shared { return shared } + let controller = MainWindowController(model: model) + shared = controller + return controller + } + + private init(model: AppModel) { + self.model = model + + let hosting = NSHostingController(rootView: MainWindowRoot(model: model)) + hosting.sizingOptions = [.minSize] + hosting.sceneBridgingOptions = [.toolbars, .title] + + window = NSWindow( + contentRect: NSRect(x: 0, y: 0, + width: Design.Window.defaultWidth, + height: Design.Window.defaultHeight), + styleMask: [.titled, .closable, .miniaturizable, .resizable, + .fullSizeContentView], + backing: .buffered, + defer: false) + window.title = "TetherKitNext" + window.toolbarStyle = .unified + window.isReleasedWhenClosed = false + window.contentMinSize = NSSize(width: Design.Window.minWidth, + height: Design.Window.minHeight) + window.contentViewController = hosting + // contentViewController adopts the controller's view size; put the + // design size back before restoring any saved frame. + window.setContentSize(NSSize(width: Design.Window.defaultWidth, + height: Design.Window.defaultHeight)) + window.center() + window.setFrameAutosaveName(Self.autosaveName) + + super.init() + window.delegate = self + } + + var isVisible: Bool { window.isVisible || window.isMiniaturized } + + /// Shows the window and brings the app forward. Idempotent: safe from + /// launch, the menu bar panel, and Dock / Finder reopen alike. + func present() { + if NSApp.activationPolicy() != .regular { + NSApp.setActivationPolicy(.regular) + } + if window.isMiniaturized { + window.deminiaturize(nil) + } + window.makeKeyAndOrderFront(nil) + NSApp.activate() + } + + /// File ▸ Close (⌘W). A minimized main window is never key, so + /// `NSApp.keyWindow?.performClose` alone would do nothing for it; fall + /// back to closing the main window when nothing else is key. + func closeFrontWindow() { + if let key = NSApp.keyWindow { + key.performClose(nil) + } else if window.isMiniaturized { + window.close() + } + } + + // MARK: NSWindowDelegate + + func windowDidBecomeKey(_ notification: Notification) { + model.windowDidAppear() + } + + func windowWillClose(_ notification: Notification) { + model.windowDidDisappear() + } + + func windowDidMiniaturize(_ notification: Notification) { + model.windowDidDisappear() + } + + func windowDidDeminiaturize(_ notification: Notification) { + model.windowDidAppear() + } +} + +/// The SwiftUI content of the main window. +private struct MainWindowRoot: View { + var model: AppModel + + var body: some View { + ContentView(model: model) + .frame(minWidth: Design.Window.minWidth, minHeight: Design.Window.minHeight) + // Rebuild on a language switch (SwiftUI cannot see the global + // string table change; docs/GUI-ARCHITECTURE.md). + .id(model.languageRevision) + } +} diff --git a/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift b/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift index 94c546c..2d65138 100644 --- a/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift +++ b/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift @@ -19,36 +19,28 @@ import TetherKitNextIPC @main struct TetherKitNextApplication: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate - @State private var model = AppModel() var body: some Scene { - // Window, not WindowGroup: one connection panel. Several windows would - // just poll the same daemon several times. - Window("TetherKitNext", id: WindowID.main) { - MainWindowRoot(model: model) - } - .defaultSize(width: Design.Window.defaultWidth, height: Design.Window.defaultHeight) - .windowResizability(.contentMinSize) - .windowToolbarStyle(.unified) - .commands { - CommandGroup(replacing: .newItem) {} - CommandGroup(replacing: .appInfo) { AboutMenuItem(model: model) } - CommandGroup(after: .appInfo) { AppMenuItems(model: model) } - } - + // No Window scene: the main window is an AppKit NSWindow owned by + // MainWindowController (see there for why). The menu bar extra is the + // only SwiftUI scene; app-wide commands attach to it. MenuBarExtra { - MenuBarPanel(model: model) + MenuBarPanel(model: appDelegate.model) } label: { - MenuBarLabel(model: model) + MenuBarLabel(model: appDelegate.model) } .menuBarExtraStyle(.window) + .commands { + CommandGroup(replacing: .newItem) {} + // Without a Window scene SwiftUI provides no File ▸ Close; ⌘W + // hides the window like the red button (menu-bar-only mode). + CommandGroup(after: .newItem) { CloseWindowMenuItem(model: appDelegate.model) } + CommandGroup(replacing: .appInfo) { AboutMenuItem(model: appDelegate.model) } + CommandGroup(after: .appInfo) { AppMenuItems(model: appDelegate.model) } + } } } -enum WindowID { - static let main = "main" -} - /// Keeps the Dock icon in sync with the main window. /// /// The previous implementation flipped the activation policy from SwiftUI's @@ -58,9 +50,16 @@ enum WindowID { /// visible, non-panel window → `.regular`; none → `.accessory`. @MainActor final class AppDelegate: NSObject, NSApplicationDelegate { + /// The single app model, shared by the main window and the menu bar + /// extra. Owned here (not by the App struct) because the AppKit-owned + /// main window is created from `applicationDidFinishLaunching`. + let model = AppModel() private var observers: [NSObjectProtocol] = [] func applicationDidFinishLaunching(_ notification: Notification) { + model.start() + MainWindowController.install(model: model).present() + let center = NotificationCenter.default for name in [NSWindow.willCloseNotification, NSWindow.didBecomeKeyNotification, NSWindow.didMiniaturizeNotification, NSWindow.didDeminiaturizeNotification] { @@ -80,6 +79,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { false } + /// Dock icon click or Finder double-click while the app is running. + /// Reaches us now that SwiftUI owns no window scene; reopen the main + /// window instead of doing nothing (menu-bar-only mode has no Dock icon, + /// but a Finder double-click still lands here). + func applicationShouldHandleReopen(_ sender: NSApplication, + hasVisibleWindows flag: Bool) -> Bool { + if !(MainWindowController.shared?.isVisible ?? true) { + MainWindowController.shared?.present() + } + return true + } + static func updateActivationPolicy(excluding closing: NSWindow? = nil) { let hasAppWindow = NSApp.windows.contains { window in window !== closing && isAppWindow(window) @@ -155,39 +166,13 @@ struct LanguagePicker: View { } } -private struct MainWindowRoot: View { +/// File ▸ Close (⌘W). +private struct CloseWindowMenuItem: View { var model: AppModel - @Environment(\.dismissWindow) private var dismissWindow var body: some View { - ContentView(model: model) - .frame(minWidth: Design.Window.minWidth, minHeight: Design.Window.minHeight) - .id(model.languageRevision) - .task { - model.start() - } - .onAppear { - // SwiftUI resurrects the Window scene when a windowless app is - // activated (clicking the menu bar item does that). Only keep - // windows we asked for. - guard model.isWindowPresentationExpected() else { - dismissWindow(id: WindowID.main) - return - } - model.windowDidAppear() - AppDelegate.updateActivationPolicy() - } - .onDisappear { - model.windowDidDisappear() - } + let _ = model.languageRevision + Button(L(.closeWindow)) { MainWindowController.shared?.closeFrontWindow() } + .keyboardShortcut("w") } } - -/// Opens (or brings forward) the main window from the menu bar. -@MainActor -func presentMainWindow(_ model: AppModel, _ openWindow: OpenWindowAction) { - model.expectWindowPresentation() - NSApp.setActivationPolicy(.regular) - openWindow(id: WindowID.main) - NSApp.activate() -} diff --git a/gui/Sources/TetherKitNextApp/Views/ContentView.swift b/gui/Sources/TetherKitNextApp/Views/ContentView.swift index d7e0b2d..ababb43 100644 --- a/gui/Sources/TetherKitNextApp/Views/ContentView.swift +++ b/gui/Sources/TetherKitNextApp/Views/ContentView.swift @@ -1,46 +1,25 @@ import AppKit import SwiftUI import TetherKitNextIPC - -/// Sidebar destinations. -/// -/// The old single dashboard crammed five cards into one screen under a hard -/// "fits in 700 pt" budget. Splitting by task — look at the connection, pick a -/// device, set up addressing, read logs, manage the app — gives each page room -/// and makes the window resizable without layout gymnastics. -enum Pane: String, CaseIterable, Identifiable, Hashable { - case overview, device, network, activity, settings - - var id: Self { self } - - var title: String { - switch self { - case .overview: return L(.paneOverview) - case .device: return L(.paneDevice) - case .network: return L(.paneNetwork) - case .activity: return L(.paneActivity) - case .settings: return L(.paneSettings) - } - } - - var symbol: String { - switch self { - case .overview: return "gauge.with.dots.needle.67percent" - case .device: return "cable.connector" - case .network: return "network" - case .activity: return "list.bullet.rectangle" - case .settings: return "gearshape" - } - } -} +import TetherKitNextUIModel struct ContentView: View { @Bindable var model: AppModel - @SceneStorage("selectedPane") private var pane: Pane = .overview + // @AppStorage rather than @SceneStorage: the window is an AppKit-owned + // NSWindow (MainWindowController), which has no SwiftUI scene to store in. + @AppStorage(PreferenceKey.selectedPane) private var storedPane = Pane.overview.rawValue + @AppStorage(PreferenceKey.advancedToolsEnabled) private var advancedToolsEnabled = false @State private var confirmingHelperUninstall = false @State private var confirmingHelperUpdate = false + /// The selected page. Resolution drops stale values (renamed pages, an + /// advanced page after advanced tools were turned off) to the overview. + private var pane: Pane { + get { Pane.resolveStored(storedPane, advancedToolsEnabled: advancedToolsEnabled) } + nonmutating set { storedPane = newValue.rawValue } + } + var body: some View { Group { if model.helperAvailability.isAvailable { @@ -92,14 +71,18 @@ struct ContentView: View { private var mainSplit: some View { NavigationSplitView { List(selection: Binding(get: { pane }, set: { pane = $0 ?? .overview })) { - Section { - ForEach([Pane.overview, .device, .network, .activity]) { item in - sidebarRow(item) + ForEach(Pane.sidebarSections(advancedToolsEnabled: advancedToolsEnabled), + id: \.self) { section in + if section.contains(where: \.isAdvanced) { + Section(L(.sidebarAdvancedSection)) { + ForEach(section) { item in sidebarRow(item) } + } + } else { + Section { + ForEach(section) { item in sidebarRow(item) } + } } } - Section { - sidebarRow(.settings) - } } .navigationSplitViewColumnWidth(min: 190, ideal: 210, max: 260) .safeAreaInset(edge: .bottom) { @@ -156,6 +139,8 @@ struct ContentView: View { LogCard(model: model) .padding(Design.Spacing.medium) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + case .interfaces: + InterfacesPage() case .settings: SettingsPage(model: model, requestHelperUpdate: requestHelperUpdate, diff --git a/gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift b/gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift new file mode 100644 index 0000000..862773d --- /dev/null +++ b/gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift @@ -0,0 +1,123 @@ +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// Advanced → Interfaces: every network interface on the Mac with its +/// addresses and live traffic. +/// +/// Read-only and unprivileged (getifaddrs + the routing socket's counters), +/// so it talks to neither the daemon nor the network. It is the first of the +/// opt-in advanced tools (docs/ADVANCED-TOOLS.md) and the base the planned +/// per-interface speed test builds on. +struct InterfacesPage: View { + @State private var monitor = InterfaceMonitor() + @AppStorage(PreferenceKey.interfacesShowInactive) private var showInactive = false + + var body: some View { + Page { + Card(title: L(.interfacesTitle), systemImage: "point.3.connected.trianglepath.dotted", + accessory: AnyView(Toggle(L(.interfacesShowInactive), isOn: $showInactive) + .toggleStyle(.checkbox) + .controlSize(.small))) { + Text(L(.interfacesSubtitle)) + .font(.callout) + .foregroundStyle(.secondary) + + let shown = monitor.interfaces.filter { showInactive || $0.isActive } + if shown.isEmpty { + Text(L(.interfacesEmpty)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .center) + .padding(.vertical, Design.Spacing.medium) + } else { + VStack(spacing: 0) { + ForEach(Array(shown.enumerated()), id: \.element.id) { index, interface in + if index > 0 { Divider() } + InterfaceRow(interface: interface, + rates: monitor.rates[interface.name] ?? .zero) + } + } + } + } + } + // Samples only while the page is on screen; .task cancels on leave. + .task { await monitor.run() } + } +} + +private struct InterfaceRow: View { + let interface: InterfaceSnapshot + let rates: InterfaceRates + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: Design.Spacing.medium) { + Circle() + .fill(interface.isActive ? Color.green : Color.secondary.opacity(0.4)) + .frame(width: 8, height: 8) + .accessibilityLabel(L(interface.isActive ? .interfaceActive : .interfaceInactive)) + + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: interface.name) + .font(.body.monospaced().weight(.medium)) + if let link = interface.linkAddress { + Text(verbatim: link) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + } + } + .frame(width: 150, alignment: .leading) + + VStack(alignment: .leading, spacing: 2) { + ForEach(interface.ipv4Addresses + interface.ipv6Addresses, id: \.self) { address in + Text(verbatim: address) + .font(.callout.monospaced()) + .textSelection(.enabled) + .lineLimit(1) + .truncationMode(.middle) + } + if interface.ipv4Addresses.isEmpty && interface.ipv6Addresses.isEmpty { + Text(L(.interfaceNoAddress)) + .font(.callout) + .foregroundStyle(.secondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + + VStack(alignment: .trailing, spacing: 2) { + Text(verbatim: "↓ \(Format.bitrate(rates.receiveBitsPerSecond))") + Text(verbatim: "↑ \(Format.bitrate(rates.transmitBitsPerSecond))") + } + .font(.callout.monospacedDigit()) + .foregroundStyle(.secondary) + .frame(width: 120, alignment: .trailing) + } + .padding(.vertical, Design.Spacing.small) + } +} + +/// Samples the interface list once a second. +@Observable +@MainActor +final class InterfaceMonitor { + private(set) var interfaces: [InterfaceSnapshot] = [] + private(set) var rates: [String: InterfaceRates] = [:] + + @ObservationIgnored private var tracker = InterfaceRateTracker() + @ObservationIgnored private let origin = ContinuousClock.now + + func run() async { + while !Task.isCancelled { + sample() + try? await Task.sleep(for: .seconds(1)) + } + } + + private func sample() { + let snapshots = InterfaceSampler.snapshot() + let elapsed = origin.duration(to: .now) + let seconds = Double(elapsed.components.seconds) + + Double(elapsed.components.attoseconds) / 1e18 + rates = tracker.update(with: snapshots, at: seconds) + interfaces = snapshots + } +} diff --git a/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift b/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift index e598bfc..9007c77 100644 --- a/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift +++ b/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift @@ -34,7 +34,6 @@ struct MenuBarLabel: View { /// (open the main window, quit). Configuration, charts and logs all stay in the main window -- the panel is not a second UI. struct MenuBarPanel: View { var model: AppModel - @Environment(\.openWindow) private var openWindow @Environment(\.dismiss) private var dismiss private var status: SessionStatus { model.status } @@ -120,7 +119,7 @@ struct MenuBarPanel: View { HStack { Button(L(.openMainWindow)) { dismiss() - presentMainWindow(model, openWindow) + MainWindowController.shared?.present() } .secondaryActionButtonStyle() .controlSize(.small) diff --git a/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift b/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift index 803cc89..69528ea 100644 --- a/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift +++ b/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift @@ -10,6 +10,13 @@ enum PreferenceKey { static let menuBarShowsSpeed = "menuBarShowsSpeed" /// Existing key: `defaults write com.tetherkitnext.app updateCheckDisabled -bool YES`. static let updateCheckDisabled = "updateCheckDisabled" + /// Opt-in "Advanced" sidebar section (network diagnostics). Off by default + /// so everyday users only ever see the tethering flow. + static let advancedToolsEnabled = "advancedToolsEnabled" + /// Interfaces page: also list interfaces that are down or have no address. + static let interfacesShowInactive = "interfacesShowInactive" + /// Last selected sidebar page (`Pane.rawValue`). + static let selectedPane = "selectedPane" } /// Everything about the app itself, gathered in one place instead of @@ -22,6 +29,7 @@ struct SettingsPage: View { @AppStorage(PreferenceKey.menuBarShowsSpeed) private var menuBarShowsSpeed = true @AppStorage(PreferenceKey.updateCheckDisabled) private var updateCheckDisabled = false @AppStorage(AppModel.autoConfigureNetworkKey) private var autoConfigureNetwork = true + @AppStorage(PreferenceKey.advancedToolsEnabled) private var advancedToolsEnabled = false @State private var launchAtLogin = SMAppService.mainApp.status == .enabled @State private var showingLicenses = false @State private var copiedPayPal = false @@ -135,6 +143,10 @@ struct SettingsPage: View { .onChange(of: launchAtLogin) { _, enabled in setLaunchAtLogin(enabled) } + Toggle(isOn: $advancedToolsEnabled) { + Text(L(.settingsAdvancedTools)) + Text(L(.settingsAdvancedToolsHelp)) + } } } diff --git a/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift b/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift index ad096d1..4878526 100644 --- a/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift +++ b/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift @@ -124,6 +124,18 @@ public enum L10nKey: String, CaseIterable, Sendable { case paneNetwork case paneActivity case paneSettings + case paneInterfaces + case sidebarAdvancedSection + case settingsAdvancedTools + case settingsAdvancedToolsHelp + case interfacesTitle + case interfacesSubtitle + case interfacesShowInactive + case interfacesEmpty + case interfaceNoAddress + case interfaceActive + case interfaceInactive + case closeWindow case configureNetwork case setupTitle case setupSubtitle @@ -382,6 +394,18 @@ extension L10nKey { case .paneNetwork: return "Network" case .paneActivity: return "Activity" case .paneSettings: return "Settings" + case .paneInterfaces: return "Interfaces" + case .sidebarAdvancedSection: return "Advanced" + case .settingsAdvancedTools: return "Show advanced tools" + case .settingsAdvancedToolsHelp: return "Adds an Advanced section to the sidebar with network diagnostics. Read-only; tethering works the same either way." + case .interfacesTitle: return "Network interfaces" + case .interfacesSubtitle: return "Every interface on this Mac with its addresses and live traffic, read from the system's counters." + case .interfacesShowInactive: return "Show inactive" + case .interfacesEmpty: return "No active interfaces" + case .interfaceNoAddress: return "No address" + case .interfaceActive: return "Active" + case .interfaceInactive: return "Inactive" + case .closeWindow: return "Close Window" case .configureNetwork: return "Configure…" case .setupTitle: return "Welcome to TetherKitNext" case .setupSubtitle: return "A few steps turn your Android phone's USB tethering into a network interface on your Mac." @@ -627,6 +651,18 @@ extension L10nKey { case .paneNetwork: return "Red" case .paneActivity: return "Actividad" case .paneSettings: return "Ajustes" + case .paneInterfaces: return "Interfaces" + case .sidebarAdvancedSection: return "Avanzado" + case .settingsAdvancedTools: return "Mostrar herramientas avanzadas" + case .settingsAdvancedToolsHelp: return "Añade una sección Avanzado a la barra lateral con diagnósticos de red. Solo lectura; el anclaje funciona igual en ambos casos." + case .interfacesTitle: return "Interfaces de red" + case .interfacesSubtitle: return "Todas las interfaces de este Mac con sus direcciones y tráfico en vivo, leídos de los contadores del sistema." + case .interfacesShowInactive: return "Mostrar inactivas" + case .interfacesEmpty: return "No hay interfaces activas" + case .interfaceNoAddress: return "Sin dirección" + case .interfaceActive: return "Activa" + case .interfaceInactive: return "Inactiva" + case .closeWindow: return "Cerrar ventana" case .configureNetwork: return "Configurar…" case .setupTitle: return "Bienvenido a TetherKitNext" case .setupSubtitle: return "Unos sencillos pasos transforman la conexión compartida por USB de tu Android en una interfaz de red en tu Mac." @@ -872,6 +908,18 @@ extension L10nKey { case .paneNetwork: return "网络" case .paneActivity: return "日志" case .paneSettings: return "设置" + case .paneInterfaces: return "网络接口" + case .sidebarAdvancedSection: return "高级" + case .settingsAdvancedTools: return "显示高级工具" + case .settingsAdvancedToolsHelp: return "在侧栏添加“高级”分区,提供网络诊断工具。只读,不影响共享网络的使用。" + case .interfacesTitle: return "网络接口" + case .interfacesSubtitle: return "本机所有网络接口的地址与实时流量,数据来自系统计数器。" + case .interfacesShowInactive: return "显示未活动的接口" + case .interfacesEmpty: return "没有活动的接口" + case .interfaceNoAddress: return "无地址" + case .interfaceActive: return "活动" + case .interfaceInactive: return "未活动" + case .closeWindow: return "关闭窗口" case .configureNetwork: return "配置…" case .setupTitle: return "欢迎使用 TetherKitNext" case .setupSubtitle: return "只需几步,就能把 Android 手机的 USB 网络共享变成 Mac 上的一张网卡。" @@ -1117,6 +1165,18 @@ extension L10nKey { case .paneNetwork: return "ネットワーク" case .paneActivity: return "アクティビティ" case .paneSettings: return "設定" + case .paneInterfaces: return "インターフェイス" + case .sidebarAdvancedSection: return "詳細" + case .settingsAdvancedTools: return "詳細ツールを表示" + case .settingsAdvancedToolsHelp: return "サイドバーにネットワーク診断用の「詳細」セクションを追加します。読み取り専用で、テザリングの動作は変わりません。" + case .interfacesTitle: return "ネットワークインターフェイス" + case .interfacesSubtitle: return "この Mac のすべてのインターフェイスのアドレスとリアルタイムの通信量(システムのカウンタから取得)。" + case .interfacesShowInactive: return "非アクティブも表示" + case .interfacesEmpty: return "アクティブなインターフェイスはありません" + case .interfaceNoAddress: return "アドレスなし" + case .interfaceActive: return "アクティブ" + case .interfaceInactive: return "非アクティブ" + case .closeWindow: return "ウインドウを閉じる" case .configureNetwork: return "設定…" case .setupTitle: return "TetherKitNext へようこそ" case .setupSubtitle: return "いくつかのステップで、Android スマホの USB テザリングを Mac のネットワークインターフェースに変換できます。" @@ -1362,6 +1422,18 @@ extension L10nKey { case .paneNetwork: return "Netzwerk" case .paneActivity: return "Aktivität" case .paneSettings: return "Einstellungen" + case .paneInterfaces: return "Schnittstellen" + case .sidebarAdvancedSection: return "Erweitert" + case .settingsAdvancedTools: return "Erweiterte Werkzeuge anzeigen" + case .settingsAdvancedToolsHelp: return "Fügt der Seitenleiste einen Bereich „Erweitert“ mit Netzwerkdiagnose hinzu. Nur lesend; das Tethering funktioniert in beiden Fällen gleich." + case .interfacesTitle: return "Netzwerkschnittstellen" + case .interfacesSubtitle: return "Alle Schnittstellen dieses Macs mit Adressen und Live-Datenverkehr, gelesen aus den Systemzählern." + case .interfacesShowInactive: return "Inaktive anzeigen" + case .interfacesEmpty: return "Keine aktiven Schnittstellen" + case .interfaceNoAddress: return "Keine Adresse" + case .interfaceActive: return "Aktiv" + case .interfaceInactive: return "Inaktiv" + case .closeWindow: return "Fenster schließen" case .configureNetwork: return "Konfigurieren…" case .setupTitle: return "Willkommen bei TetherKitNext" case .setupSubtitle: return "Mit wenigen Schritten wird das USB-Tethering Ihres Android-Telefons zu einer Netzwerkschnittstelle auf Ihrem Mac." @@ -1607,6 +1679,18 @@ extension L10nKey { case .paneNetwork: return "네트워크" case .paneActivity: return "활동" case .paneSettings: return "설정" + case .paneInterfaces: return "인터페이스" + case .sidebarAdvancedSection: return "고급" + case .settingsAdvancedTools: return "고급 도구 표시" + case .settingsAdvancedToolsHelp: return "사이드바에 네트워크 진단 도구가 있는 고급 섹션을 추가합니다. 읽기 전용이며 테더링 동작에는 영향이 없습니다." + case .interfacesTitle: return "네트워크 인터페이스" + case .interfacesSubtitle: return "이 Mac의 모든 인터페이스와 주소, 실시간 트래픽을 시스템 카운터에서 읽어 표시합니다." + case .interfacesShowInactive: return "비활성 표시" + case .interfacesEmpty: return "활성 인터페이스 없음" + case .interfaceNoAddress: return "주소 없음" + case .interfaceActive: return "활성" + case .interfaceInactive: return "비활성" + case .closeWindow: return "윈도우 닫기" case .configureNetwork: return "구성…" case .setupTitle: return "TetherKitNext에 오신 것을 환영합니다" case .setupSubtitle: return "몇 가지 단계만으로 Android 스마트폰의 USB 테더링을 Mac의 네트워크 인터페이스로 변환할 수 있습니다." diff --git a/gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift b/gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift new file mode 100644 index 0000000..c19fef6 --- /dev/null +++ b/gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift @@ -0,0 +1,236 @@ +import Darwin +import Foundation + +/// One network interface as `getifaddrs(3)` reports it, at one instant. +/// +/// Read without privileges: every user can enumerate interfaces and read +/// their byte counters, which is what the Advanced → Interfaces page shows. +public struct InterfaceSnapshot: Sendable, Equatable, Identifiable { + public var name: String + /// `IFF_UP`: administratively enabled. + public var isUp: Bool + /// `IFF_RUNNING`: resources allocated / link present. + public var isRunning: Bool + public var isLoopback: Bool + /// Hardware address (`aa:bb:cc:dd:ee:ff`), when the link layer has one. + public var linkAddress: String? + public var mtu: UInt32 + /// Cumulative byte counters (`struct if_data64` via `NET_RT_IFLIST2`). + /// + /// 64-bit on purpose: the `struct if_data` that `getifaddrs` hands out + /// has 32-bit counters that wrap every 4 GiB, and a wrap is then + /// indistinguishable from an interface being recreated with fresh + /// counters. With 64 bits a decrease can only mean a reset. + public var receivedBytes: UInt64 + public var sentBytes: UInt64 + public var ipv4Addresses: [String] + public var ipv6Addresses: [String] + + public var id: String { name } + + /// Up, running, and carrying at least one address: the interfaces worth + /// showing by default. + public var isActive: Bool { + isUp && isRunning && !(ipv4Addresses.isEmpty && ipv6Addresses.isEmpty) + } + + public init(name: String, isUp: Bool, isRunning: Bool, isLoopback: Bool, + linkAddress: String?, mtu: UInt32, receivedBytes: UInt64, sentBytes: UInt64, + ipv4Addresses: [String], ipv6Addresses: [String]) { + self.name = name + self.isUp = isUp + self.isRunning = isRunning + self.isLoopback = isLoopback + self.linkAddress = linkAddress + self.mtu = mtu + self.receivedBytes = receivedBytes + self.sentBytes = sentBytes + self.ipv4Addresses = ipv4Addresses + self.ipv6Addresses = ipv6Addresses + } +} + +/// Live receive / transmit rate of one interface. +public struct InterfaceRates: Sendable, Equatable { + public var receiveBitsPerSecond: Double + public var transmitBitsPerSecond: Double + + public static let zero = InterfaceRates(receiveBitsPerSecond: 0, transmitBitsPerSecond: 0) + + public init(receiveBitsPerSecond: Double, transmitBitsPerSecond: Double) { + self.receiveBitsPerSecond = receiveBitsPerSecond + self.transmitBitsPerSecond = transmitBitsPerSecond + } +} + +/// Turns successive counter snapshots into rates. +/// +/// Pure value logic so the edge cases are unit-tested: +/// * The first sample of an interface has nothing to compare with: 0. +/// * A counter that went down means the interface was destroyed and +/// recreated under the same name (feth pairs between sessions do exactly +/// this): that direction reports 0 for one round instead of a bogus spike. +/// * Interfaces absent from a round are forgotten, so a later reappearance +/// starts fresh. +public struct InterfaceRateTracker: Sendable { + private struct Sample: Sendable { + var received: UInt64 + var sent: UInt64 + var time: Double + } + + private var previous: [String: Sample] = [:] + + public init() {} + + /// Feeds one round of snapshots taken at `time` (seconds, monotonic) and + /// returns the rate of every interface in it. + public mutating func update(with snapshots: [InterfaceSnapshot], + at time: Double) -> [String: InterfaceRates] { + var rates: [String: InterfaceRates] = [:] + var next: [String: Sample] = [:] + for snapshot in snapshots { + let sample = Sample(received: snapshot.receivedBytes, sent: snapshot.sentBytes, + time: time) + next[snapshot.name] = sample + guard let old = previous[snapshot.name], time > old.time else { + rates[snapshot.name] = .zero + continue + } + let elapsed = time - old.time + rates[snapshot.name] = InterfaceRates( + receiveBitsPerSecond: Self.rate(sample.received, old.received, elapsed), + transmitBitsPerSecond: Self.rate(sample.sent, old.sent, elapsed)) + } + previous = next + return rates + } + + static func rate(_ current: UInt64, _ old: UInt64, _ elapsed: Double) -> Double { + guard current >= old else { return 0 } + return Double(current - old) * 8 / elapsed + } +} + +/// Reads the interface list with `getifaddrs(3)`. +public enum InterfaceSampler { + /// All interfaces, in the order the kernel lists them. + public static func snapshot() -> [InterfaceSnapshot] { + var head: UnsafeMutablePointer? + guard getifaddrs(&head) == 0, let first = head else { return [] } + defer { freeifaddrs(head) } + + var order: [String] = [] + var byName: [String: InterfaceSnapshot] = [:] + + for entry in sequence(first: first, next: { $0.pointee.ifa_next }) { + let item = entry.pointee + guard let address = item.ifa_addr else { continue } + let name = String(cString: item.ifa_name) + let flags = Int32(bitPattern: item.ifa_flags) + + if byName[name] == nil { + order.append(name) + byName[name] = InterfaceSnapshot( + name: name, + isUp: flags & IFF_UP != 0, + isRunning: flags & IFF_RUNNING != 0, + isLoopback: flags & IFF_LOOPBACK != 0, + linkAddress: nil, mtu: 0, receivedBytes: 0, sentBytes: 0, + ipv4Addresses: [], ipv6Addresses: []) + } + + switch Int32(address.pointee.sa_family) { + case AF_LINK: + // For AF_LINK entries ifa_data points at the interface's + // struct if_data; only the MTU is taken from it (its byte + // counters are 32-bit, see `receivedBytes`). + if let data = item.ifa_data?.assumingMemoryBound(to: if_data.self) { + byName[name]?.mtu = data.pointee.ifi_mtu + } + byName[name]?.linkAddress = linkAddress(address) + case AF_INET: + if let text = numericHost(address) { byName[name]?.ipv4Addresses.append(text) } + case AF_INET6: + if let text = numericHost(address) { byName[name]?.ipv6Addresses.append(text) } + default: + break + } + } + let counters = counters64() + return order.compactMap { name in + guard var snapshot = byName[name] else { return nil } + if let pair = counters[name] { + snapshot.receivedBytes = pair.received + snapshot.sentBytes = pair.sent + } + return snapshot + } + } + + /// 64-bit byte counters per interface name, from the routing socket's + /// `NET_RT_IFLIST2` dump (`RTM_IFINFO2` records carry `struct if_data64`). + /// The same source `netstat -b` uses; no privileges required. + static func counters64() -> [String: (received: UInt64, sent: UInt64)] { + var mib: [Int32] = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0] + var length = 0 + guard sysctl(&mib, UInt32(mib.count), nil, &length, nil, 0) == 0, length > 0 else { + return [:] + } + // Interfaces can appear between the two calls; leave some headroom. + length += length / 8 + var buffer = [UInt8](repeating: 0, count: length) + guard sysctl(&mib, UInt32(mib.count), &buffer, &length, nil, 0) == 0 else { return [:] } + + var result: [String: (received: UInt64, sent: UInt64)] = [:] + buffer.withUnsafeBytes { raw in + guard let base = raw.baseAddress else { return } + var offset = 0 + let headerSize = MemoryLayout.size + while offset + headerSize <= length { + let message = base.advanced(by: offset) + // ifm_msglen leads every routing message; stop on garbage. + let messageLength = Int(message.loadUnaligned(as: UInt16.self)) + guard messageLength > 0, offset + messageLength <= length else { break } + let type = Int32(message.loadUnaligned(fromByteOffset: 3, as: UInt8.self)) + if type == RTM_IFINFO2, + messageLength >= MemoryLayout.size { + let header = message.loadUnaligned(as: if_msghdr2.self) + var nameBuffer = [CChar](repeating: 0, count: Int(IF_NAMESIZE) + 1) + if if_indextoname(UInt32(header.ifm_index), &nameBuffer) != nil { + let name = String( + decoding: nameBuffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, + as: UTF8.self) + result[name] = (header.ifm_data.ifi_ibytes, header.ifm_data.ifi_obytes) + } + } + offset += messageLength + } + } + return result + } + + private static func numericHost(_ address: UnsafeMutablePointer) -> String? { + var host = [CChar](repeating: 0, count: Int(NI_MAXHOST)) + let status = getnameinfo(address, socklen_t(address.pointee.sa_len), + &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) + guard status == 0 else { return nil } + return String(decoding: host.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, + as: UTF8.self) + } + + /// `sockaddr_dl` → "aa:bb:cc:dd:ee:ff". The address follows the interface + /// name inside `sdl_data` (LLADDR() in ). + private static func linkAddress(_ address: UnsafeMutablePointer) -> String? { + address.withMemoryRebound(to: sockaddr_dl.self, capacity: 1) { link -> String? in + let length = Int(link.pointee.sdl_alen) + guard length == 6 else { return nil } + let dataOffset = MemoryLayout.offset(of: \sockaddr_dl.sdl_data) ?? 8 + let start = UnsafeRawPointer(link) + .advanced(by: dataOffset + Int(link.pointee.sdl_nlen)) + let bytes = (0..