diff --git a/.clang-format b/.clang-format index a0a2b89..a077dc3 100644 --- a/.clang-format +++ b/.clang-format @@ -55,3 +55,7 @@ MaxEmptyLinesToKeep: 1 SeparateDefinitionBlocks: Always SpacesBeforeTrailingComments: 2 QualifierAlignment: Left + +# doctest's TEST_SUITE("name") { ... } groups test cases like a namespace; format it as one +# (contents unindented, as everywhere in tests/) instead of as a block that indents its body. +NamespaceMacros: [TEST_SUITE] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..37ab354 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,59 @@ +name: Bug report +description: Something doesn't work as expected +labels: [bug] +body: + - type: markdown + attributes: + value: | + Thanks for reporting. For a **security** problem, please use the repository's + **Security › Report a vulnerability** instead (see SECURITY.md). + - type: textarea + id: what + attributes: + label: What happened? + description: What did you expect, and what happened instead? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Plug in the phone and turn on USB tethering + 2. Click Connect + 3. … + validations: + required: true + - type: input + id: app-version + attributes: + label: TetherKitNext version + description: Settings › Updates shows it. + placeholder: "1.3.0" + validations: + required: true + - type: input + id: macos + attributes: + label: macOS version and Mac + placeholder: "macOS 26.1, MacBook Air M3" + validations: + required: true + - type: input + id: device + attributes: + label: Phone or device + placeholder: "Pixel 8, Android 16 (USB tethering)" + validations: + required: true + - type: dropdown + id: layout + attributes: + label: Layout + options: [Simple, Detailed, "Not sure / setup screen"] + - type: textarea + id: log + attributes: + label: Log + description: Detailed layout › Activity › copy the log (remove anything private). + render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..8c36aae --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/AA-EION/TetherKitNext/security/advisories/new + about: Please report security problems privately, not as a public issue. + - name: Download the latest release + url: https://github.com/AA-EION/TetherKitNext/releases/latest + about: Most problems are already fixed in the newest version. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..20a9b81 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,27 @@ +name: Feature request +description: Suggest an idea or an improvement +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: What problem would this solve? + description: Describe the situation, not only the solution. + validations: + required: true + - type: textarea + id: idea + attributes: + label: What would you like to happen? + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives you considered + - type: checkboxes + id: contribute + attributes: + label: Contributing + options: + - label: I'd like to work on this (please read CONTRIBUTING.md first) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..6cb88a8 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,24 @@ + + +## What and why + + + +## How it was tested + + + +## Checklist + +- [ ] Builds and tests pass locally (`ctest`, `swift test`); changed C/C++ lines are clang-formatted +- [ ] New logic has unit tests; no test needs a USB device or root unless opt-in +- [ ] User-facing text is localized (C++: English + Chinese; app: all six languages) +- [ ] README / docs / AGENTS.md updated where behavior changed (new pitfalls in AGENTS.md section 7) +- [ ] Pushes were batched, and this PR stayed a draft while iterating +- [ ] No new macOS CI jobs or matrix entries (or: the reason is explained below) + +## AI assistance + + 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..c633ef3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,14 +4,32 @@ # GitHub's hosted macOS runners are Apple Silicon VMs, plus an Intel image # (macos-15-intel) that we use to prove the universal binary really runs on # x86_64 hardware, not just under Rosetta. +# +# Shared-runner policy (AGENTS.md section 10, CONTRIBUTING.md) +# +# macOS runners are a shared, scarce resource (a handful of concurrent jobs per account, long +# queues at peak). The `plan` job (Linux, seconds) picks: +# skip docs-only change → no macOS job at all +# fast draft pull request → 2 macOS jobs: macOS 26 build + unit + +# root feth tests, universal app + DMG +# full ready PR, main, weekly, → every OS, Intel install test, macOS 27 +# manual run GUI, ThreadSanitizer (+ DMG Finder +# check when the DMG scripts change) +# Nothing is merged or released without the full set. `CI result` is the single check to require +# in branch protection: it always reports. name: CI on: push: - branches: ["**"] + branches: [main] tags-ignore: ["v*"] # release.yml handles tags pull_request: + # ready_for_review: leaving draft triggers the full set. + types: [opened, synchronize, reopened, ready_for_review] + schedule: + # Weekly full run: catches runner-image and macOS updates between changes. + - cron: "41 4 * * 2" workflow_dispatch: inputs: prerelease_tag: @@ -23,7 +41,8 @@ on: type: string concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + # Keyed on the PR number, so a new push cancels the previous run of that PR. + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true permissions: @@ -31,30 +50,111 @@ permissions: jobs: # ---------------------------------------------------------------------------- - # Native build + unit tests on each supported runner architecture/OS. - # None of the tests need root or a USB device; feth/BPF cases skip themselves - # without TETHERKITNEXT_ROOT_TESTS (the abi-check job runs them as root). + # Decide what this run needs (see the header). Linux, no macOS minutes. + # ---------------------------------------------------------------------------- + plan: + name: Plan + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + code: ${{ steps.plan.outputs.code }} + full: ${{ steps.plan.outputs.full }} + dmg: ${{ steps.plan.outputs.dmg }} + oses: ${{ steps.plan.outputs.oses }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + fetch-depth: 0 + - name: Plan + id: plan + env: + EVENT: ${{ github.event_name }} + DRAFT: ${{ github.event.pull_request.draft }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + BEFORE: ${{ github.event.before }} + run: | + base="" + if [ "$EVENT" = pull_request ]; then + base="$(git merge-base "$PR_BASE" HEAD)" + elif [ "$EVENT" = push ] && [ -n "$BEFORE" ] \ + && [ "$BEFORE" != 0000000000000000000000000000000000000000 ] \ + && git cat-file -e "$BEFORE^{commit}" 2>/dev/null; then + base="$BEFORE" + fi + if [ -n "$base" ]; then + changed="$(git diff --name-only "$base" HEAD)" + else + changed="(scheduled or manual run: everything)" + fi + printf 'Changed files:\n%s\n' "$changed" + + # Docs-only: Markdown anywhere, docs/, licence and community files. + code=true + if [ -n "$base" ] && [ -n "$changed" ] && ! printf '%s\n' "$changed" \ + | grep -vqE '(\.md$|^docs/|^LICENSE$|^\.github/ISSUE_TEMPLATE/|^\.github/FUNDING\.ya?ml$)'; then + code=false + fi + full=true + if [ "$EVENT" = pull_request ] && [ "$DRAFT" = true ]; then full=false; fi + dmg=false + if [ "$full" = true ] && { [ -z "$base" ] || printf '%s\n' "$changed" \ + | grep -qE '^(scripts/make-dmg\.sh|scripts/dmg/|\.github/workflows/ci\.yml)'; }; then + dmg=true + fi + if [ "$full" = true ]; then + oses='["macos-15","macos-26","macos-15-intel","xcode-27"]' + else + oses='["macos-26"]' + fi + { + echo "code=$code"; echo "full=$full"; echo "dmg=$dmg"; echo "oses=$oses" + } >> "$GITHUB_OUTPUT" + { + echo "### CI plan" + if [ "$code" = false ]; then echo "Docs-only change: no macOS jobs." + elif [ "$full" = true ]; then echo "Full set on: $oses (DMG Finder check: $dmg)" + else echo "Draft PR: fast set (macOS 26 build + tests, universal app). Mark the PR ready for review for the full set." + fi + } >> "$GITHUB_STEP_SUMMARY" + + # ---------------------------------------------------------------------------- + # Native build + unit tests, then the feth/BPF cases as root (the private-ABI + # gate), on each supported runner OS/architecture. One VM per OS: building + # once and running both test sets saves a whole macOS job per OS. + # + # The biggest long-term risk is xnu changing struct if_fake_request. The root + # step is a gate, not a signal: skipped root tests must fail it. # ---------------------------------------------------------------------------- native: - name: C++ · ${{ matrix.os }} + name: C++ + feth ABI · ${{ matrix.os }} + needs: plan + if: needs.plan.outputs.code == 'true' runs-on: ${{ matrix.os }} timeout-minutes: 45 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: ${{ fromJSON(needs.plan.outputs.oses) }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Toolchain + id: toolchain run: | sw_vers; uname -m; cmake --version; c++ --version + # Part of the libusb cache key: runners of the same OS/arch (macos-15, + # macos-26, xcode-27) must not share a libusb built with another SDK. + echo "sdk=$(xcrun --sdk macosx --show-sdk-version)-$(sw_vers -productVersion)" >> "$GITHUB_OUTPUT" - 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') }} + key: libusb-${{ runner.os }}-${{ runner.arch }}-sdk${{ steps.toolchain.outputs.sdk }}-${{ hashFiles('scripts/build-libusb.sh') }} - name: Build libusb (universal, pinned + hash-verified) run: ./scripts/build-libusb.sh "$PWD/build/libusb-universal" @@ -74,6 +174,25 @@ jobs: ./build/bin/tetherkitnext-cli --version ./build/bin/tetherkitnext-cli --list + - name: Disable feth hardware checksum offload + run: sudo sysctl -w net.link.fake.hwcsum=0 + - name: feth ABI gate (feth/BPF cases as root) + # bash (not the default `bash -e`) adds -o pipefail, so a failing ctest is not + # masked by `| tee`; without it the gate below could pass with red root tests. + shell: bash + run: | + # Pin the log language: the gate greps for a message text. + sudo env TETHERKITNEXT_ROOT_TESTS=1 TETHERKITNEXT_LANG=en \ + ctest --test-dir build -V -R 'net\.' 2>&1 | tee abi.log + # Skip notice is hard-coded in tests/test_net_link.cc. + if grep -q "needs root and TETHERKITNEXT_ROOT_TESTS=1" abi.log; then + echo "::error::feth cases were skipped; the ABI check did not run"; exit 1 + fi + if ! grep -q "created virtual interface feth" abi.log; then + echo "::error::no feth creation in the log; cannot confirm the private ABI"; exit 1 + fi + echo "✓ $(grep -m1 'created virtual interface feth' abi.log)" + # ---------------------------------------------------------------------------- # The shipping build: universal C++ + Swift, app bundle, DMG. # @@ -83,14 +202,26 @@ jobs: # ---------------------------------------------------------------------------- package: name: Universal app + DMG + needs: plan + if: needs.plan.outputs.code == 'true' 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 + # Newest Xcode *26*, not 27: a libusb built with the macOS + # 27 SDK segfaults during device enumeration on macOS 15 and 26 (seen in + # CI, see AGENTS.md pitfall 33). Shipping builds stay on the 26 SDK until + # that is understood; the xcode-27 jobs cover building on macOS 27. + - name: Select the newest Xcode 26 run: | - latest="$(ls -d /Applications/Xcode_*.app | sort -V | tail -1)" + # Release bundles only (Xcode_26.x.app), never betas/RCs; `|| true` so a missing + # Xcode 26 reaches the explicit error below instead of aborting silently. + latest="$(ls -d /Applications/Xcode_26*.app 2>/dev/null \ + | grep -E '/Xcode_26(\.[0-9]+)*\.app$' | sort -V | tail -1 || true)" + [ -n "${latest}" ] || { echo "::error::no Xcode 26 on this runner"; ls -d /Applications/Xcode_*.app; exit 1; } sudo xcode-select -s "${latest}" xcodebuild -version; swift --version @@ -117,16 +248,17 @@ jobs: app=dist/TetherKitNext.app codesign --display --verbose=2 "$app" 2>&1 | sed -n '1,12p' for f in "$app/Contents/MacOS/"* "$app/Contents/Frameworks/"*; do + # Frameworks: report the binary inside (Sparkle.framework/Sparkle). + [ -d "$f" ] && f="$f/$(basename "$f" .framework)" printf '%-60s %s\n' "${f#dist/}" "$(lipo -archs "$f")" done - # The daemon refuses to run outside launchd (and the legacy - # --install setuid mode is gone): it must exit non-zero, promptly. + # The daemon refuses to run outside launchd: it must exit non-zero, promptly. if perl -e 'alarm 10; exec @ARGV' "$app/Contents/MacOS/tetherkitnext-helper" --install; then echo "::error::tetherkitnext-helper ran outside launchd"; exit 1 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: | @@ -135,20 +267,28 @@ jobs: if-no-files-found: error # ---------------------------------------------------------------------------- - # Install the DMG on a real Intel Mac and run the CLI from it. + # Install the shipped DMG on the oldest macOS CI offers and run it: the CLI + # from the bundle, then the GUI for a few seconds. Covers backward + # compatibility of the app built on macOS 26 with the newest SDK (both + # architectures; the x86_64 slice only runs on the Intel image). # ---------------------------------------------------------------------------- intel-smoke: - name: DMG on Intel - needs: package - runs-on: macos-15-intel + name: DMG on ${{ matrix.os }} + needs: [plan, package] + if: needs.plan.outputs.full == 'true' && needs.plan.outputs.code == 'true' + strategy: + fail-fast: false + matrix: + os: [macos-15-intel, macos-15] + runs-on: ${{ matrix.os }} 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 run: | - uname -m + sw_vers; uname -m dmg="$(ls TetherKitNext-*.dmg)" mnt="$(hdiutil attach -nobrowse -readonly "$dmg" | awk -F'\t' '/\/Volumes\// {print $NF}')" ditto "$mnt/TetherKitNext.app" /Applications/TetherKitNext.app @@ -157,21 +297,24 @@ jobs: codesign --verify --deep --strict "$app" "$app/Contents/MacOS/tetherkitnext-cli" --version "$app/Contents/MacOS/tetherkitnext-cli" --list - # Launch the GUI briefly: proves the x86_64 Swift slice + dylibs load. - "$app/Contents/MacOS/TetherKitNext" & pid=$! + # Launch the GUI briefly: proves this architecture's Swift slice and + # dylibs load, and that nothing at launch needs a newer macOS. + "$app/Contents/MacOS/TetherKitNext" > gui.log 2>&1 & pid=$! sleep 8 - kill -0 "$pid" || { echo "::error::GUI exited early on Intel"; exit 1; } + kill -0 "$pid" || { echo "::error::GUI exited early on $(sw_vers -productVersion) $(uname -m)"; cat gui.log; exit 1; } kill "$pid" # ---------------------------------------------------------------------------- # What people see when they open the DMG: mount it in Finder and take a # screenshot (the install layout lives in .DS_Store, which nothing else # checks). Also shoots the latest published release for comparison. - # Diagnostic only: never fails the build. + # Diagnostic only: never fails the build. Runs only when the DMG layout can + # have changed (scripts/make-dmg.sh, scripts/dmg/) or on scheduled/manual runs. # ---------------------------------------------------------------------------- dmg-look: name: DMG window · ${{ matrix.os }} - needs: package + needs: [plan, package] + if: needs.plan.outputs.dmg == 'true' && needs.plan.outputs.code == 'true' strategy: fail-fast: false matrix: @@ -180,7 +323,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,21 +355,75 @@ 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 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) + needs: plan + if: needs.plan.outputs.full == 'true' && needs.plan.outputs.code == 'true' + 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 + # This job is the macOS 27 / Xcode 27 check: newest Xcode. + 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. # ---------------------------------------------------------------------------- tsan: name: ThreadSanitizer + needs: plan + if: needs.plan.outputs.full == 'true' && needs.plan.outputs.code == 'true' 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 @@ -238,45 +435,39 @@ jobs: run: ctest --test-dir build-tsan --output-on-failure # ---------------------------------------------------------------------------- - # Private ABI drift gate: create/destroy a real feth pair as root. - # - # The biggest long-term risk is xnu changing struct if_fake_request. This job - # is a gate, not a signal: skipped root tests must fail it. + # The one check to require in branch protection. Always reports: skipped jobs + # (docs-only change, draft PR) count as passed; anything else that is not a + # success (failed, cancelled, abandoned for lack of a runner) fails it. + # A draft PR therefore passes on the fast set; the full set runs when it is + # marked ready for review, and that run is what a merge must wait for. # ---------------------------------------------------------------------------- - abi-check: - name: feth ABI · ${{ matrix.os }} - runs-on: ${{ matrix.os }} - timeout-minutes: 45 - strategy: - fail-fast: false - matrix: - os: [macos-15, macos-26, macos-15-intel] + result: + name: CI result + if: always() + needs: [plan, native, package, intel-smoke, gui-macos-27, tsan] + runs-on: ubuntu-latest + timeout-minutes: 5 steps: - - uses: actions/checkout@v5 - - name: Build - 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 - cmake --build build -j"$(sysctl -n hw.ncpu)" - - name: Disable feth hardware checksum offload - run: sudo sysctl -w net.link.fake.hwcsum=0 - - name: Run feth/BPF cases as root + - name: Summarize + env: + RESULTS: ${{ toJSON(needs) }} + FULL: ${{ needs.plan.outputs.full }} run: | - # Pin the log language: the gate greps for a message text. - sudo env TETHERKITNEXT_ROOT_TESTS=1 TETHERKITNEXT_LANG=en \ - ctest --test-dir build -V -R 'net\.' 2>&1 | tee abi.log - # Skip notice is hard-coded in tests/test_net_link.cc. - if grep -q "需要 root 且需设置" abi.log; then - echo "::error::feth cases were skipped; the ABI check did not run"; exit 1 - fi - # kNetCreated. (The previous gate grepped for "创建了 feth", a string - # that stopped existing when log messages were localized — it could - # never pass.) - if ! grep -q "created virtual interface feth" abi.log; then - echo "::error::no feth creation in the log; cannot confirm the private ABI"; exit 1 - fi - echo "✓ $(grep -m1 'created virtual interface feth' abi.log)" + echo "$RESULTS" | python3 -c " + import json, os, sys + needs = json.load(sys.stdin) + # Allowlist: anything but success/skipped fails, including results such as + # 'abandoned' (no runner ever picked the job up), so a job that never ran + # can never let a merge through. + bad = {k: v['result'] for k, v in needs.items() if v['result'] not in ('success', 'skipped')} + for k, v in needs.items(): + print(f'{k:14} {v[\"result\"]}') + if bad: + print('::error::failed: ' + ', '.join(f'{k} ({v})' for k, v in bad.items())) + sys.exit(1) + if os.environ.get('FULL') != 'true': + print('::notice::fast set only (draft PR); the full set runs when the PR is ready for review') + " # ---------------------------------------------------------------------------- # Optional: publish the tested DMG as a prerelease (manual runs only). @@ -294,7 +485,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 +499,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/codeql.yml b/.github/workflows/codeql.yml index 41b8a5b..16deca4 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,105 +1,113 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. +# CodeQL (advanced setup): static security analysis of the C++ driver/C ABI, +# the Swift app and root daemon, the Python build scripts, and these GitHub +# Actions workflows. Replaces GitHub's generated template, which used +# unpinned actions and an autobuild that cannot build this project. Results appear under +# Security › Code scanning. # -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. +# Toolchain: macOS 26 + Xcode 26. CodeQL cannot trace builds on +# macOS 27 / Xcode 27 or analyze Swift 6.4 (GitHub changelog 2026-10-19, +# "CodeQL changes for macOS 27, Xcode 27 and Swift 6.4"); Xcode 26 ships +# Swift 6.3, which CodeQL supports. # -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. +# libusb is built *before* `init`, so CodeQL traces only our own code. # -name: "CodeQL Advanced" +# Shared-runner policy (AGENTS.md section 10): draft PRs analyze only the +# Linux languages (Actions, Python); the macOS ones (C/C++, Swift) run when the +# PR is ready for review, on main, weekly and on manual runs. Docs-only changes +# skip it entirely. + +name: CodeQL on: push: - branches: [ "main" ] + branches: [main] + paths-ignore: ["**/*.md", "docs/**"] pull_request: - branches: [ "main" ] + types: [opened, synchronize, reopened, ready_for_review] + paths-ignore: ["**/*.md", "docs/**"] schedule: - - cron: '30 15 * * 1' + - cron: "27 3 * * 1" # weekly, so new queries also run on unchanged code + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read jobs: analyze: - name: Analyze (${{ matrix.language }}) - # Runner size impacts CodeQL analysis time. To learn more, please see: - # - https://gh.io/recommended-hardware-resources-for-running-codeql - # - https://gh.io/supported-runners-and-hardware-resources - # - https://gh.io/using-larger-runners (GitHub.com only) - # Consider using larger runners or machines with greater resources for possible analysis time improvements. - runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + name: CodeQL · ${{ matrix.language }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 permissions: - # required for all workflows - security-events: write - - # required to fetch internal or private CodeQL packs - packages: read - - # only required for workflows in private repositories - actions: read contents: read - + actions: read + security-events: write strategy: fail-fast: false matrix: - include: - - language: actions - build-mode: none - - language: c-cpp - build-mode: none - - language: python - build-mode: none - - language: swift - build-mode: autobuild - # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift' - # Use `c-cpp` to analyze code written in C, C++ or both - # Use 'java-kotlin' to analyze code written in Java, Kotlin or both - # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both - # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, - # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. - # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how - # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages + # Draft PRs: Linux languages only (no macOS runner). + include: >- + ${{ fromJSON(github.event.pull_request.draft + && '[{"language":"actions","runner":"ubuntu-latest","build-mode":"none"}, + {"language":"python","runner":"ubuntu-latest","build-mode":"none"}]' + || '[{"language":"c-cpp","runner":"macos-26","build-mode":"manual"}, + {"language":"swift","runner":"macos-26","build-mode":"manual"}, + {"language":"actions","runner":"ubuntu-latest","build-mode":"none"}, + {"language":"python","runner":"ubuntu-latest","build-mode":"none"}]') }} steps: - - name: Checkout repository - uses: actions/checkout@v7 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + + - name: Select Xcode 26 + if: runner.os == 'macOS' + run: | + latest="$(ls -d /Applications/Xcode_26*.app 2>/dev/null \ + | grep -E '/Xcode_26(\.[0-9]+)*\.app$' | sort -V | tail -1 || true)" + [ -n "${latest}" ] || { echo "::error::no Xcode 26 on this runner"; ls -d /Applications/Xcode_*.app; exit 1; } + sudo xcode-select -s "${latest}" + xcodebuild -version; swift --version + + - name: Build libusb (not analyzed) + if: runner.os == 'macOS' + run: ./scripts/build-libusb.sh "$PWD/build/libusb-universal" - # Add any setup steps before running the `github/codeql-action/init` action. - # This includes steps like installing compilers or runtimes (`actions/setup-node` - # or others). This is typically only required for manual builds. - # - name: Setup runtime (example) - # uses: actions/setup-example@v1 + # The Swift package links libtetherkitnext, so build the C++ side first, + # outside the trace (the c-cpp job analyzes it). + # Universal: under CodeQL's tracer the Swift package also builds an x86_64 + # slice, which an arm64-only libtetherkitnext cannot link. + - name: Build the C++ library for the Swift package (not analyzed) + if: matrix.language == 'swift' + run: | + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" \ + -DLibUSB_ROOT="$PWD/build/libusb-universal" \ + -DTETHERKITNEXT_BUILD_TESTS=OFF -DTETHERKITNEXT_BUILD_BENCHMARKS=OFF + cmake --build build -j"$(sysctl -n hw.ncpu)" - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v4 - with: - languages: ${{ matrix.language }} - build-mode: ${{ matrix.build-mode }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. + - name: Initialize CodeQL + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + queries: security-extended - # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs - # queries: security-extended,security-and-quality + - name: Build C++ (traced) + if: matrix.language == 'c-cpp' + run: | + cmake -S . -B build-codeql -DCMAKE_BUILD_TYPE=Debug \ + -DLibUSB_ROOT="$PWD/build/libusb-universal" \ + -DTETHERKITNEXT_BUILD_TESTS=OFF -DTETHERKITNEXT_BUILD_BENCHMARKS=OFF + cmake --build build-codeql -j"$(sysctl -n hw.ncpu)" - # If the analyze step fails for one of the languages you are analyzing with - # "We were unable to automatically build your code", modify the matrix above - # to set the build mode to "manual" for that language. Then modify this step - # to build your code. - # ℹ️ Command-line programs to run using the OS shell. - # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - - name: Run manual build steps - if: matrix.build-mode == 'manual' - shell: bash - run: | - echo 'If you are using a "manual" build mode for one or more of the' \ - 'languages you are analyzing, replace this with the commands to build' \ - 'your code, for example:' - echo ' make bootstrap' - echo ' make release' - exit 1 + - name: Build Swift (traced) + if: matrix.language == 'swift' + run: TETHERKITNEXT_LIB_DIR="$PWD/build/lib" swift build --package-path gui - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4 - with: - category: "/language:${{matrix.language}}" + - name: Analyze + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..bd02b5b --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,146 @@ +# Lint: formatting and static checks for C/C++. +# +# clang-format (blocking) checks only the lines a change touches: most files +# predate .clang-format and reformatting them all at once would bury real +# history. The repo-wide count is reported as an advisory summary. +# +# clang-tidy (advisory) runs on the changed C++ sources and reports findings as +# annotations without failing the run, until the existing backlog is cleared. +# It needs a macOS runner, so it runs only on PRs that are ready for review and +# only when C++ sources changed (shared-runner policy, AGENTS.md section 10). +# +# clang-format 18 from Ubuntu 24.04 is pinned so CI and local runs agree: +# git clang-format --binary clang-format-18 --extensions c,h,cc,cpp,hpp --diff origin/main + +name: Lint + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + EXTENSIONS: c,h,cc,cpp,hpp + +jobs: + clang-format: + name: clang-format (changed lines) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Install clang-format 18 + run: | + sudo apt-get update -q + sudo apt-get install -y -q clang-format-18 + clang-format-18 --version + + - name: Determine the diff base + id: base + env: + EVENT: ${{ github.event_name }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + BEFORE: ${{ github.event.before }} + run: | + if [ "$EVENT" = pull_request ]; then + base="$(git merge-base "$PR_BASE" HEAD)" + elif [ -n "$BEFORE" ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ] \ + && git cat-file -e "$BEFORE^{commit}" 2>/dev/null; then + base="$BEFORE" + else + base="$(git rev-parse HEAD~1)" + fi + echo "sha=$base" >> "$GITHUB_OUTPUT" + echo "Diff base: $base" + + - name: Check the formatting of changed lines + env: + BASE: ${{ steps.base.outputs.sha }} + run: | + diff="$(git clang-format-18 --binary clang-format-18 --extensions "$EXTENSIONS" \ + --diff "$BASE" 2>&1 || true)" + if printf '%s\n' "$diff" | grep -q '^@@'; then + echo "::error::Changed lines are not clang-formatted. Fix with:" + echo "::error::git clang-format --binary clang-format-18 --extensions $EXTENSIONS $BASE" + printf '%s\n' "$diff" + exit 1 + fi + echo "✓ changed lines are formatted" + + - name: Repo-wide backlog (advisory) + if: always() + run: | + total=0; unformatted=0 + while IFS= read -r file; do + total=$((total + 1)) + clang-format-18 --dry-run -Werror "$file" >/dev/null 2>&1 || unformatted=$((unformatted + 1)) + done < <(git ls-files '*.c' '*.h' '*.cc' '*.cpp' '*.hpp' | grep -v '^third_party/') + echo "### clang-format backlog: ${unformatted} of ${total} files not fully formatted" >> "$GITHUB_STEP_SUMMARY" + + # Which C++ sources changed: decided on Linux, so the macOS job below only + # starts when there is something to check (docs-only or Swift-only PRs start + # no macOS runner; AGENTS.md section 10). + tidy-files: + name: clang-tidy file list + if: github.event_name == 'pull_request' && !github.event.pull_request.draft + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + list: ${{ steps.files.outputs.list }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + fetch-depth: 0 + - name: Changed C++ sources + id: files + env: + PR_BASE: ${{ github.event.pull_request.base.sha }} + run: | + base="$(git merge-base "$PR_BASE" HEAD)" + files="$(git diff --name-only --diff-filter=AM "$base" HEAD -- 'src/*.cc' | tr '\n' ' ')" + echo "list=$files" >> "$GITHUB_OUTPUT" + echo "Changed: ${files:-none}" + + clang-tidy: + name: clang-tidy (changed files, advisory) + needs: tidy-files + if: needs.tidy-files.outputs.list != '' + runs-on: macos-26 + timeout-minutes: 30 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + + - name: Configure (compile_commands.json) + run: | + brew install --quiet llvm libusb + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug \ + -DTETHERKITNEXT_BUILD_TESTS=OFF -DTETHERKITNEXT_BUILD_BENCHMARKS=OFF + + - name: clang-tidy + env: + FILES: ${{ needs.tidy-files.outputs.list }} + run: | + tidy="$(brew --prefix llvm)/bin/clang-tidy" + "$tidy" --version + # Advisory: findings become annotations; the step never fails the run. + for file in $FILES; do + "$tidy" -p build --quiet "$file" 2>/dev/null \ + | sed -nE 's#^(/[^:]+):([0-9]+):([0-9]+): (warning|error): (.*)$#::warning file=\1,line=\2,col=\3::\5#p' \ + || true + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dd9440f..e42e548 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,8 @@ # Release: push a v* tag to publish a DMG. # # Stable: git tag -a v1.1.0 -m "TetherKitNext 1.1.0" && git push origin v1.1.0 -# Prerelease: git tag -a v1.1.0-beta.1 -m "TetherKitNext 1.1.0 beta 1" && git push origin v1.1.0-beta.1 +# Prerelease: git tag -a v1.1.0-beta.1 -m "TetherKitNext 1.1.0 beta 1" && git push origin +# v1.1.0-beta.1 # # A tag with a suffix after the version (v1.1.0-beta.1, v1.1.0-rc.1) publishes a # GitHub *prerelease*. Prereleases may be built without signing secrets: the @@ -14,6 +15,13 @@ # NOTARY_KEY_P8 base64 of an App Store Connect API key (.p8) # NOTARY_KEY_ID that key's ID # NOTARY_ISSUER_ID App Store Connect issuer ID +# +# Self-update (Sparkle). Optional; without them the app stays check-only: +# SPARKLE_ED_PRIVATE_KEY secret: EdDSA private key (`generate_keys -x `) +# SPARKLE_ED_PUBLIC_KEY repository *variable*: the matching public key +# With both, the build embeds the public key and stable releases also publish +# appcast.xml (releases/latest/download/appcast.xml is the app's feed). The job +# verifies the signature with the key inside the built app before publishing. name: Release @@ -42,7 +50,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 @@ -78,8 +88,15 @@ jobs: env: HAS_CERT: ${{ secrets.MACOS_CERTIFICATE_P12 != '' }} HAS_NOTARY: ${{ secrets.NOTARY_KEY_P8 != '' && secrets.NOTARY_KEY_ID != '' && secrets.NOTARY_ISSUER_ID != '' }} + HAS_SPARKLE: ${{ secrets.SPARKLE_ED_PRIVATE_KEY != '' && vars.SPARKLE_ED_PUBLIC_KEY != '' }} PRERELEASE: ${{ steps.tag.outputs.prerelease }} run: | + if [ "$HAS_SPARKLE" = true ]; then + echo "sparkle=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::No SPARKLE_ED_PRIVATE_KEY secret / SPARKLE_ED_PUBLIC_KEY variable: this build will not update itself" + echo "sparkle=false" >> "$GITHUB_OUTPUT" + fi if [ "$HAS_CERT" = true ] && [ "$HAS_NOTARY" = true ]; then echo "signed=true" >> "$GITHUB_OUTPUT" elif [ "$PRERELEASE" = true ]; then @@ -90,10 +107,18 @@ jobs: exit 1 fi - - name: Select the newest Xcode + # Newest Xcode *26*, not 27: a libusb built with the macOS + # 27 SDK segfaults during device enumeration on macOS 15 and 26 (seen in + # CI, see AGENTS.md pitfall 33). Shipping builds stay on the 26 SDK until + # that is understood; the xcode-27 jobs cover building on macOS 27. + - name: Select the newest Xcode 26 if: steps.existing.outputs.exists != 'true' run: | - latest="$(ls -d /Applications/Xcode_*.app | sort -V | tail -1)" + # Release bundles only (Xcode_26.x.app), never betas/RCs; `|| true` so a missing + # Xcode 26 reaches the explicit error below instead of aborting silently. + latest="$(ls -d /Applications/Xcode_26*.app 2>/dev/null \ + | grep -E '/Xcode_26(\.[0-9]+)*\.app$' | sort -V | tail -1 || true)" + [ -n "${latest}" ] || { echo "::error::no Xcode 26 on this runner"; ls -d /Applications/Xcode_*.app; exit 1; } sudo xcode-select -s "${latest}" xcodebuild -version @@ -109,6 +134,7 @@ jobs: if: steps.existing.outputs.exists != 'true' env: TETHERKITNEXT_BUILD_NUMBER: ${{ github.run_number }} + TETHERKITNEXT_SPARKLE_PUBLIC_KEY: ${{ steps.signing.outputs.sparkle == 'true' && vars.SPARKLE_ED_PUBLIC_KEY || '' }} NOTARY_KEY_ID: ${{ steps.signing.outputs.signed == 'true' && secrets.NOTARY_KEY_ID || '' }} NOTARY_ISSUER_ID: ${{ steps.signing.outputs.signed == 'true' && secrets.NOTARY_ISSUER_ID || '' }} run: ./scripts/build-release.sh @@ -144,6 +170,39 @@ jobs: } > notes.md cat notes.md + # Stable only: the feed lives at releases/latest/download/appcast.xml, + # and prereleases are never "latest". + - name: Sparkle appcast + if: >- + steps.existing.outputs.exists != 'true' && steps.tag.outputs.prerelease != 'true' + && steps.signing.outputs.sparkle == 'true' + env: + SPARKLE_ED_PRIVATE_KEY: ${{ secrets.SPARKLE_ED_PRIVATE_KEY }} + REPOSITORY: ${{ github.repository }} + GH_TOKEN: ${{ github.token }} + run: | + app=dist/TetherKitNext.app + dmg="$(ls dist/TetherKitNext-*.dmg)" + sign_update="$(find gui/.build/artifacts -type f -path '*/bin/sign_update' | head -1)" + [ -x "$sign_update" ] || { echo "::error::sign_update not found in the Sparkle package"; exit 1; } + # The key goes through stdin, never the command line or a file. + signature="$(printf '%s' "$SPARKLE_ED_PRIVATE_KEY" | "$sign_update" --ed-key-file - -p "$dmg")" + [ -n "$signature" ] || { echo "::error::sign_update produced no signature"; exit 1; } + swift scripts/verify-sparkle-signature.swift "$app" "$dmg" "$signature" + # The update dialog shows what changed (GitHub's generated notes), not + # the install steps of notes.md; the full page is one click away. + if ! gh api -X POST "repos/${REPOSITORY}/releases/generate-notes" \ + -f tag_name="$RELEASE_TAG" -f target_commitish="$GITHUB_SHA" \ + --jq .body > update-notes.md 2>/dev/null || [ ! -s update-notes.md ]; then + echo "See the release notes for what changed in ${RELEASE_TAG}." > update-notes.md + fi + python3 scripts/make-appcast.py \ + --app "$app" --dmg "$dmg" --signature "$signature" --notes update-notes.md \ + --download-url "https://github.com/${REPOSITORY}/releases/download/${RELEASE_TAG}/$(basename "$dmg")" \ + --release-url "https://github.com/${REPOSITORY}/releases/tag/${RELEASE_TAG}" \ + > dist/appcast.xml + cat dist/appcast.xml + - name: Create release if: steps.existing.outputs.exists != 'true' env: @@ -154,6 +213,14 @@ jobs: flags=() if [ "$PRERELEASE" = true ]; then flags+=(--prerelease) + else + # A fixed-name copy for the README's download button: + # releases/latest/download/TetherKitNext.dmg only resolves when every stable + # release has an asset with exactly this name (prereleases are never "latest"). + cp "${assets[0]}" dist/TetherKitNext.dmg + assets+=(dist/TetherKitNext.dmg) + # The self-update feed (see "Sparkle appcast"), when this build has one. + if [ -f dist/appcast.xml ]; then assets+=(dist/appcast.xml); fi fi if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then # Creates the tag on the commit that was just built and tested. diff --git a/.github/workflows/ui-snapshots.yml b/.github/workflows/ui-snapshots.yml new file mode 100644 index 0000000..bf0650c --- /dev/null +++ b/.github/workflows/ui-snapshots.yml @@ -0,0 +1,93 @@ +# UI snapshots: every screen of both layouts (setup → layout choice → simple or +# detailed), in light and dark mode, rendered from sample data by the debug +# app (`TetherKitNextApp --render-ui-snapshots `, UISnapshotRenderer.swift). +# No device, root or background daemon is involved. +# +# macOS 26 shows the Liquid Glass design; macOS 15 shows the fallback materials +# the app uses on older systems. Images and manifest.json are uploaded as +# artifacts (ui-snapshots-). +# +# On demand only (shared-runner policy, AGENTS.md section 10): run it by hand +# (Actions › UI snapshots › Run workflow), or add the `ui-snapshots` label to a +# PR that changes the GUI. It also runs once when such a PR leaves draft. +# Never re-run it to check a cosmetic tweak: batch UI changes first. + +name: UI snapshots + +on: + workflow_dispatch: + pull_request: + types: [labeled, ready_for_review] + paths: + - "gui/**" + - ".github/workflows/ui-snapshots.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + snapshots: + name: Snapshots · ${{ matrix.runner }} + if: >- + github.event_name == 'workflow_dispatch' + || github.event.action == 'ready_for_review' + || (github.event.action == 'labeled' && github.event.label.name == 'ui-snapshots') + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + runner: [macos-26, macos-15] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + + - name: Select Xcode 26 + run: | + latest="$(ls -d /Applications/Xcode_26*.app 2>/dev/null \ + | grep -E '/Xcode_26(\.[0-9]+)*\.app$' | sort -V | tail -1 || true)" + [ -n "${latest}" ] || { echo "::error::no Xcode 26 on this runner"; ls -d /Applications/Xcode_*.app; exit 1; } + sudo xcode-select -s "${latest}" + sw_vers; xcodebuild -version + + - name: Build C++ (native arch) + run: | + ./scripts/build-libusb.sh "$PWD/build/libusb-universal" + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug \ + -DLibUSB_ROOT="$PWD/build/libusb-universal" \ + -DTETHERKITNEXT_BUILD_TESTS=OFF -DTETHERKITNEXT_BUILD_BENCHMARKS=OFF + cmake --build build -j"$(sysctl -n hw.ncpu)" + + - name: Build the app (debug) + run: TETHERKITNEXT_LIB_DIR="$PWD/build/lib" swift build --package-path gui --product TetherKitNextApp + + - name: Render + env: + TETHERKITNEXT_LANG: en + run: | + bin="$(TETHERKITNEXT_LIB_DIR="$PWD/build/lib" swift build --package-path gui --show-bin-path)" + out="$PWD/ui-snapshots" + # -AppleLanguages: English UI regardless of the runner's locale. + perl -e 'alarm 900; exec @ARGV' "$bin/TetherKitNextApp" -AppleLanguages '(en)' \ + --render-ui-snapshots "$out" + ls -la "$out" + python3 -c " + import json, sys + m = json.load(open('$out/manifest.json')) + methods = {s['capture'] for s in m['scenes']} + print('macOS', m['macOS'], '| scenes', len(m['scenes']), '| capture', methods) + sys.exit(1 if 'failed' in methods or not m['scenes'] else 0) + " + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + if: always() + with: + name: ui-snapshots-${{ matrix.runner }} + path: ui-snapshots/ + if-no-files-found: error + retention-days: 30 diff --git a/.gitignore b/.gitignore index 71e306e..06d4b40 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,29 @@ build-tsan/ build-asan/ build-rel/ build2/ + +# ---- Signing material and secrets (never commit) ---- +*.p12 +*.p8 +*.pem +*.cer +*.key +*.pfx +*.mobileprovision +.env +.env.* +.netrc +sparkle_private_key* + +# ---- Release output ---- +*.dmg +*.dmg.sparkle_guid +/appcast.xml + +# ---- Xcode ---- +DerivedData/ +xcuserdata/ +*.xcuserstate + +# ---- Local agent settings ---- +.claude/settings.local.json diff --git a/AGENTS.md b/AGENTS.md index 31692ed..34b6b85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,6 +3,10 @@ > This file serves as the **working memory** for AI agents and human maintainers. > Update the corresponding sections after completing a commit. Read this file before starting any work to avoid repeating known pitfalls. > +> **Shared-runner policy is mandatory**: before pushing anything, read [Section 10](#10-ci--shared-macos-runner-policy-mandatory-always). Every push can start macOS jobs on runners that other projects share. +> +> **Writing and hygiene rules are mandatory**: comments, docs, secrets and leftover files follow [Section 11](#11-comments-documentation-and-repository-hygiene-mandatory-always). +> > **Naming**: Starting in 1.0, this project was renamed **TetherKitNext** (maintained by Issen Software Group, forked from `XiaoMiku01/TetherKit`). Identifiers in the historical entries prior to row 42 of Section 5 were batch-renamed alongside the codebase and describe behavior at the time they were written (originally named `TetherKit` / `tetherkit-cli` / `com.tetherkit.*`). --- @@ -30,7 +34,7 @@ Verified on: macOS 26.5.1 (Darwin 25.5.0), Apple Silicon `arm64`, Apple Clang 21 | CPU | 10 logical cores, including **4 Performance cores** (`hw.perflevel0.logicalcpu = 4`). Data-path threads request P-cores via QoS | `sysctl hw.ncpu hw.perflevel0.logicalcpu` | | `-mcpu=apple-m1` / `-mcpu=native` | Supported, but **off by default** (see trade-offs in `cmake/Optimizations.cmake`) | Compile test | | `ninja` | **Not assumed installed**; use default Unix Makefiles generator | `which ninja` | -| CMake | 4.3.3+ | `cmake --version` | +| CMake | 4.3.3 on the dev machine; minimum 3.24 (`cmake_minimum_required` in `CMakeLists.txt`) | `cmake --version` | ### 2.2 `libusb` @@ -96,8 +100,12 @@ Verified on: macOS 26.5.1 (Darwin 25.5.0), Apple Silicon `arm64`, Apple Clang 21 ``` TetherKitNext/ -├── AGENTS.md Agent and maintainer working memory +├── AGENTS.md Agent and maintainer working memory (section 10: CI policy) ├── README.md User-facing documentation (English) +├── CONTRIBUTING.md How to contribute, incl. the shared-runner CI rules +├── CODE_OF_CONDUCT.md Contributor Covenant 2.1 +├── SECURITY.md Private vulnerability reporting, supported versions +├── LICENSE, NOTICE.md MIT license; upstream attribution and third-party notices ├── CMakeLists.txt Top-level CMake build configuration ├── .clang-format Code formatting rules (Google style base, 100 columns) ├── .clang-tidy Static analysis and naming rules @@ -105,12 +113,15 @@ TetherKitNext/ │ ├── FindLibUSB.cmake libusb-1.0 discovery (pkg-config + Homebrew fallback) │ ├── CompilerWarnings.cmake Warning flags INTERFACE target │ ├── Sanitizers.cmake ASan/UBSan/TSan options -│ └── Optimizations.cmake Data-path optimization flags and trade-offs +│ ├── Optimizations.cmake Data-path optimization flags and trade-offs +│ └── tetherkitnext_exports.txt Exported-symbol allowlist for libtetherkitnext (`_tk_*`) ├── include/tetherkitnext/ Public headers (organized by module) -│ ├── common/messages.def All user-facing localized strings (X-macro, Chinese & English) +│ ├── common/ Errors, logging, i18n (messages.def: all C++ user-facing strings, zh + en), rings, stats +│ ├── rndis/ usb/ net/ core/ Protocol codec + state machine, libusb transport, feth/BPF, bridge + runtime │ └── capi/ C ABI — sole extern "C" boundary in the project -├── src/ C++ implementation +├── src/ C++ implementation (same modules as include/) │ ├── version.cc.in CMake version template +│ ├── common/ rndis/ usb/ net/ core/ │ ├── capi/ C ABI implementation (sessions, network config, logs, orphan cleanup) │ └── app/ CLI entry point ├── gui/ SwiftUI application (SwiftPM package; see docs/GUI-ARCHITECTURE.md) @@ -118,12 +129,16 @@ TetherKitNext/ │ ├── Sources/TetherKitNextIPC/ Shared between App and helper: XPC protocol, models, auth, i18n │ ├── Sources/TetherKitNextCore/ Swift wrapper around the C ABI │ ├── Sources/TetherKitNextHelper/ Privileged helper daemon (root, launched via SMAppService / launchd) +│ ├── Sources/TetherKitNextUIModel/ Testable UI logic (sidebar panes, interface traffic); no libtetherkitnext dependency │ ├── Sources/TetherKitNextApp/ SwiftUI user interface -│ ├── Resources/ App-Info.plist, LaunchDaemon plist, AppIcon +│ ├── Tests/ TetherKitNextIPCTests, TetherKitNextUIModelTests (XCTest) +│ ├── Resources/ App-Info.plist, LaunchDaemon plist, AppIcon, third-party license texts (Sparkle) │ └── Scripts/ Build and helper uninstall scripts +├── scripts/ libusb build, release build, CI certificate import, DMG packaging (dmg/ assets), Sparkle appcast + signature check, comment-only change check +├── .github/ CI + release workflows (SHA-pinned actions), Dependabot, release notes template, PR template, issue forms ├── tests/ doctest unit test suite ├── benchmarks/ Lightweight benchmark harness and microbenchmarks -├── third_party/doctest/ Vendored doctest 2.4.12 single-header library +├── third_party/ Vendored doctest 2.4.12 (tests only) and its CMakeLists.txt └── docs/ Design documentation, protocol reference, benchmarks, security audit ``` @@ -238,19 +253,14 @@ Legend: `✅ Completed` `🚧 In Progress` `⬜ Not Started` | 43 | `feat(gui): Touch ID confirmation for privileged actions (1.1.0)` | ✅ | `LAContext` + Team ID XPC pinning + `admin` group check; XPC rev 5 | | 44 | `fix(gui): make background component restart reliable on first click (1.1.1)` | ✅ | `HelperInstaller.reregister()` waits for `launchd` state transition and retries | | 45 | `feat(gui): add Spanish/Japanese/German/Korean i18n, donations, licenses sheet, and graceful disconnect (1.2.0)` | ✅ | Full 6-language L10n tables; non-blocking deadSession teardown in helper; LicensesSheet fallback; GUI supports 6 languages but the C++ library only en/zh (`Language.cValue` falls back to English); failed sessions stay visible (no forced reset to idle) | +| 46 | `security` + `feat(gui)`: local-link devices, Sparkle self-update, Simple/Detailed layouts, hardening, macOS 27 and shared-runner CI | 🚧 | Draft PR #8. (1) Local-link devices (drones, controllers, goggles, gadget boards), Sparkle self-update, Simple/Detailed layouts with opt-in auto-connect. (2) Hardening: SHA-pinned actions, spawn fd hygiene, review-driven fixes (pitfalls 37-44, 47). (3) Infrastructure: macOS 27 CI, UI snapshots, shared-runner CI policy (section 10). See docs/MACOS-27.md, docs/ADVANCED-TOOLS.md, docs/LOCAL-DEVICES.md and the SECURITY-AUDIT addendum | -### Current Status (TetherKitNext, 2026-10-06) +### Current Status -- **Distribution**: Signed and notarized universal DMG (`scripts/build-release.sh`, shared across CI and releases). Security audit documented in [docs/SECURITY-AUDIT.md](docs/SECURITY-AUDIT.md). +- **Distribution**: Signed and notarized universal DMG (`scripts/build-release.sh`, shared across CI and releases). In-app updates through **Sparkle 2.10.1** (user-confirmed; EdDSA feed at `releases/latest/download/appcast.xml`, stable releases only) when the release has the `SPARKLE_ED_PRIVATE_KEY` secret and the `SPARKLE_ED_PUBLIC_KEY` variable; otherwise check-only. Security audit documented in [docs/SECURITY-AUDIT.md](docs/SECURITY-AUDIT.md). - **Privileged Daemon**: `SMAppService` with label `com.tetherkitnext.helperd`, executed in-place from the `.app` bundle; automatically cleans up legacy `com.tetherkit.helper` installs on first run. XPC protocol revision 5. -- **CI**: Native builds and tests on `macos-15`, `macos-26`, and `macos-15-intel`, universal `.app` + DMG packaging, Intel hardware DMG installation smoke test, ThreadSanitizer, and `feth` ABI gate. - -### Historical Upstream Status (Recorded at v0.1.5) - -- **Tests**: 23 CTest suites passing (including `common.i18n` placeholder verification); 17 SwiftPM unit tests passing (`LocalizationTests`, `HelperConstantsTests`, `AuthorizationTests`). -- **Build**: Zero warnings under `-Werror` across CLI, shared library (`libtetherkitnext`), and SwiftUI GUI. -- **Runtime**: `--version`, `--help`, and `--list` work without root; bilingual Chinese/English switching updates GUI views, app menus, C++ library logs, and helper messages immediately at runtime. -- **End-to-End Hardware Benchmarks**: **RX 324–327 Mbps / TX 239–302 Mbps** over USB 2.0 High-Speed (426 Mbps theoretical limit); zero TX drops after `WaitForSendCapacity` fix. +- **Tests**: 24 CTest suites (incl. `core.peer_address`); SwiftPM suites (`TetherKitNextIPCTests`: localization, helper constants, authorization, code signing, rate formatting; `TetherKitNextUIModelTests`: panes, interface traffic, link assessment, auto-connect policy, interface style, session failure). Test names and messages are English; only test data that checks multibyte handling or the zh table itself is Chinese. +- **CI** (tiered by the shared-runner policy, section 10): Native builds and tests on `macos-15`, `macos-26`, `macos-15-intel` and `xcode-27` (macOS 27 Golden Gate), universal `.app` + DMG packaging, Intel hardware DMG installation smoke test, ThreadSanitizer, `feth` ABI gate (also on macOS 27), and a macOS 27 GUI build + launch smoke test. All third-party actions are pinned to commit SHAs (Dependabot updates them). **CodeQL** (`codeql.yml`: c-cpp, swift, actions, python; security-extended; weekly + PRs; pinned to macOS 26 / Xcode 26) and **Lint** (`lint.yml`: clang-format 18 on changed lines, blocking; clang-tidy on changed sources, advisory). **UI snapshots** (`ui-snapshots.yml`) run only on the triggers in section 10. The `CI result` job in `ci.yml` is the single required check. Section 10 says what runs when. ### GUI & Architecture Notes @@ -306,6 +316,7 @@ Open items for future investigation: - [ ] Bimodal TCP TX throughput (~240 vs. ~300 Mbps stable modes, both with 0 retransmissions). - [ ] Bidirectional RTT inflation (0.4 ms idle → 16.6 ms under full RX load). - [ ] Static IPv4 DNS adoption across macOS network transitions (DHCP path is verified). +- [ ] Survey of RNDIS parameters across Android OEM kernels (sampled so far: vivo with 10 packets / 15800 bytes, mainline Linux gadget with 1 packet / 1580 bytes). ### 6.4 Verified: Real-Device End-to-End (Android USB Tethering) @@ -319,9 +330,9 @@ RNDIS negotiation complete: version 1.0, MTU 1500, device aggregation limit 1580 ### 6.5 Fixed: High-Load TX Frame Drops -**Root cause**: `Bridge::RunTransmitExtractor` immediately discarded remaining frames in a batch when the 4-slot USB bulk OUT pool was full instead of waiting a few hundred microseconds for a transfer completion. +**Root cause**: `Bridge::RunTransmitExtractor` discarded the rest of a batch when the 4-slot USB bulk OUT pool was full, instead of waiting for a transfer completion. -**Fix**: `SendFrames` returns `SendOutcome{consumed, sent_frames, sent_bytes, skipped}` and the bridge calls `WaitForSendCapacity(50ms)` when `consumed == 0`, delegating burst absorption to the 4 MiB kernel BPF buffer. +**Fix**: `SendFrames` returns `SendOutcome{consumed, sent_frames, sent_bytes, skipped}`; when `consumed == 0` the bridge calls `WaitForSendCapacity(50ms)`, and the 4 MiB kernel BPF buffer absorbs bursts. The full analysis is in [docs/BENCHMARKS.md](docs/BENCHMARKS.md). | Metric | Before Fix | After Fix | |---|---:|---:| @@ -367,6 +378,30 @@ RNDIS negotiation complete: version 1.0, MTU 1500, device aggregation limit 1580 25. **Preserve legacy identifiers (`com.tetherkit.helper`, `libtetherkit*`, `"TetherKit"` service prefix) in cleanup code** during renames so upgrades clean up prior installations. 26. **`dmgbuild` background images fail to render in Finder on macOS 15/26**; `scripts/make-dmg.sh` applies the DMG window layout using Finder via AppleScript on a temporary read-write image. 27. **`SMAppService.unregister()` returning does not mean `launchd` has finished removing the job**; always use `HelperInstaller.reregister()` (which waits for state transitions and retries) to restart the daemon. +28. **macOS 26+ draws window chrome by the `LC_BUILD_VERSION` `sdk` stamp, not by what the code was compiled against.** A SwiftPM link can stamp the deployment target (14.0), so the app gets legacy chrome. `build-gui.sh` rewrites `sdk` with `vtool` (keeping `minos`) and fails if the signed app is below 26. Any other packaging path (e.g. a Homebrew formula) must do the same. +29. **Don't reintroduce a SwiftUI `Window` scene for the main window.** With a `MenuBarExtra`, SwiftUI resurrects it when the app is activated. `MainWindowController` owns an `NSWindow`; reopen via `MainWindowController.shared?.present()`. Without a window scene there is no default File ▸ Close, so keep the explicit ⌘W `CommandGroup`, and use `@AppStorage` (no `@SceneStorage`, there is no scene). +30. **`getifaddrs` byte counters (`struct if_data`) are 32-bit and wrap at 4 GiB.** Read 64-bit counters from the `NET_RT_IFLIST2` sysctl (`if_msghdr2.ifm_data`, `if_data64`); a decrease then always means the interface was recreated (`feth` pairs are, every session). +31. **Root child processes must be spawned with `POSIX_SPAWN_CLOEXEC_DEFAULT`** (`process_runner.cc`), or they inherit the daemon's BPF / socket / libusb descriptors. +32. **Pin GitHub Actions to full commit SHAs** (the signing jobs hold the Developer ID certificate and notary key) and keep `persist-credentials: false` on checkouts. Bump them via Dependabot, not by retagging. +33. **⚠️ A libusb built on macOS 27 / with the macOS 27 SDK segfaults in device enumeration on macOS 15 and 26** (`capi.basics` → `tk_list_devices`), even with `MIN_MACOS=13.3`. Found when CI's xcode-27 job shared the libusb cache with macos-15/26; root cause not yet known. Shipping builds therefore select **Xcode 26** explicitly (`Xcode_26*`, not "newest"), and the libusb cache key includes the SDK + OS version. The `macos-15` DMG smoke job (`tetherkitnext-cli --list`) catches a regression. +34. **Never persist a device's "kind" (internet vs local link).** A phone that is slow to hand out a lease or whose upstream is down would be remembered as a local device. `LinkAssessment` is recomputed from live facts every poll; addresses applied for local devices are session-only (`AppModel.sessionOnlyAddress`) and must never be written to `networkConfiguration`. Never probe internet reachability to decide it (docs/LOCAL-DEVICES.md). +35. **"Route all traffic" must follow the router, not the request.** `ConfigureManagedDhcpService(make_primary: true)` reorders services before the lease exists; `ApplyDhcp` demotes the service again when no stable router appears (`DemoteManagedNetworkService`). Keep that pairing in any new DHCP path. +36. **Learn the peer address only from on-link-only frames** (ARP sender; IPv4 to 255.255.255.255 or 224.0.0.0/24). A phone forwards internet traffic, so ordinary unicast sources are remote hosts. +37. **`tx_free_slots_` is strictly SPSC: only the libusb completion callback pushes.** The send thread must never push a slot back (two producers lose slots and the 4-slot pool drains for good); an unused slot goes to `held_tx_slot_` and is reused first. +38. **Control replies are matched by RequestId, not just type** (`StateMachine::awaited_request_id_`). A late reply to a timed-out QUERY would otherwise answer the next QUERY of the same type. RESET_CMPLT is the only completion without an id. +39. **A failed `Bridge::Start` must shut the data channel down itself**: `running_` stays false, so `Stop()` won't, and in-flight bulk IN callbacks would write into the destroyed `rx_ring_`. +40. **Each `DirectionCounters` has one writer.** RX drops seen by the injector thread go to `rx_inject_counters_` and are merged in `Bridge::Snapshot()`. +41. **The orphan registry is rewritten atomically** (temp file with `O_EXCL|O_NOFOLLOW`, then `rename`), and re-creating a known interface name takes the new owner PID; a stale dead PID would make the next startup destroy a live interface. +42. **XPC calls time out after `HelperConstants.requestTimeout`** (`HelperClient.invoke`), so a daemon that never replies cannot wedge `isBusy` and polling. Only clear the cached connection from *its own* invalidation handler. +43. **After clearing a configuration or destroying the interface, reconcile the kernel default route with configd** (`ReconcileSystemDefaultRoute`, called from `ApplyNone` and the interface-destroyed callback). Manual-mode "route all traffic" changes the kernel route behind configd's back, so configd never reinstalls the primary service's route on its own. Read `State:/Network/Global/IPv4` for the target; never cache the previous gateway (stale after a network change or helper restart), and never touch a default route through another interface (VPNs). +44. **Before talking to a device, re-enumerate and pass VID/PID with the bus address** (`AppModel.startSession`). Android re-enumerates when tethering is toggled; the C filter ANDs every given field, so a stale address can never select another device. +45. **Format changed C/C++ lines with clang-format 18 before pushing**: `git clang-format --binary clang-format-18 --extensions c,h,cc,cpp,hpp --diff origin/main` must print no hunks (the Lint workflow blocks otherwise). Don't reformat untouched code. `.clang-format` declares `NamespaceMacros: [TEST_SUITE]` so doctest suites keep their unindented bodies. +46. **CodeQL must stay on macOS 26 / Xcode 26** until CodeQL supports traced builds on macOS 27 and Swift 6.4; libusb (and, for the Swift job, the C++ library) are built before `init` so only our code is analyzed. +47. **The daemon reports `.failed` exactly once, then drops the dead session** (the next `sessionStatus` is `.idle`). Every reader of `sessionStatus` in the app must hand a failed status to `AppModel.apply(status:)`, which keeps it as `lastFailure` until the user dismisses it or starts a new session. Classify failures only by the libusb error *name* (`SessionFailureCause`), never by localized wording. +48. **Sparkle self-update invariants.** (a) `CFBundleVersion` is the Release workflow's run number and Sparkle compares it, so releases must only come from `release.yml` (another workflow's run numbers are unrelated and could go backwards). (b) The public key (`SPARKLE_ED_PUBLIC_KEY` variable) and private key (`SPARKLE_ED_PRIVATE_KEY` secret) must be a pair; the release job proves it with `scripts/verify-sparkle-signature.swift` before publishing. Never skip that step. (c) Copy `Sparkle.framework` with `ditto` and re-sign it inside-out before the app (Downloader.xpc keeps its entitlements). (d) Keep `SUAllowsAutomaticUpdates` off: updates are always user-confirmed. (e) Replacing the app does not restart the daemon; `restartHelperAfterUpdateIfNeeded()` does, only with no session running. +49. **Layouts and auto-connect.** (a) `InterfaceStylePreference.migrateIfNeeded` must run first in `AppModel.start()`: "existing install" is measured as "the preferences domain was non-empty before this launch wrote anything", and the decision is stored once (`interfaceStyleDecided`), so a new user who quit mid-setup is not later treated as existing. (b) The layout chooser comes **after** the setup assistant (the daemon must work first). (c) Auto-connect never starts a session while the Mac has Wi-Fi/Ethernet (NWPathMonitor; our `feth*` excluded; unknown = online), fires once per plug-in, treats a running/stopped session as "handled", and needs a stable 10 s offline period before failover. All of it is in `AutoConnectPolicy` (unit-tested); keep the rules there, not in views. (d) The simple window is fixed-size (`SimpleView.windowSize`); `MainWindowController.applyLayout` remembers the detailed frame across launches. +50. **Never waste shared macOS runners** (section 10). One push used to start ~35 macOS jobs (push + pull_request duplicates, a matrix per workflow, about ten pushes in a day), and a single snapshot job then queued for over half an hour. Keep PRs draft while iterating, batch pushes, test locally, don't re-run macOS jobs for cosmetic changes, and justify any new macOS job. +51. **Comments state the current why; docs describe the present; nothing secret, personal or generated is committed** (section 11). A comment or doc cleanup is proven comment-only with `scripts/check-comment-only.py` before it is pushed. --- @@ -400,3 +435,137 @@ TETHERKITNEXT_LIB_DIR=$PWD/build/lib swift test --package-path gui ./build/bin/tetherkitnext-cli --lang zh --list ctest --test-dir build -R common.i18n --output-on-failure ``` + +--- + +## 9. Release Signing & Self-Update Setup (Maintainer's Mac) — **Open To-Do** + +> **Status: not done yet.** The code for self-update (Sparkle) is in place, but no signing key exists yet, so no build updates itself. An agent running **on the maintainer's Mac** (with Xcode 26, the maintainer's Keychain and an authenticated `gh` CLI) should carry out the steps below when asked to "build, sign and publish". A cloud/Linux agent cannot do this: it needs the Keychain and `codesign`/`notarytool`. + +### 9.1 What the Release workflow needs + +| Name | Kind | Required for | Content | +|---|---|---|---| +| `MACOS_CERTIFICATE_P12` | secret | stable releases | base64 of the "Developer ID Application" certificate + private key exported as .p12 | +| `MACOS_CERTIFICATE_PASSWORD` | secret | stable releases | the .p12 export password | +| `NOTARY_KEY_P8` | secret | stable releases | base64 of an App Store Connect API key (.p8) | +| `NOTARY_KEY_ID` | secret | stable releases | that key's ID | +| `NOTARY_ISSUER_ID` | secret | stable releases | App Store Connect issuer ID | +| `SPARKLE_ED_PRIVATE_KEY` | secret | self-update | Sparkle EdDSA private key (export of `generate_keys -x`) | +| `SPARKLE_ED_PUBLIC_KEY` | **variable** (not secret) | self-update | the matching public key, base64 | + +Check what already exists before creating anything: `gh secret list` and `gh variable list`. **Never overwrite an existing `SPARKLE_ED_*` value** without the maintainer's explicit approval: replacing the key pair strands every installed copy (they would reject all future updates and need a manual download). + +### 9.2 One-time Sparkle key setup + +1. Get Sparkle's tools from the exact version the app uses (2.10.1, `gui/Package.swift`). Either build the GUI once (`swift build --package-path gui`) and use `gui/.build/artifacts/sparkle/Sparkle/bin/`, or download `Sparkle-2.10.1.tar.xz` from the Sparkle GitHub release. +2. Create the key pair (stored in the login Keychain; prints the public key): + ```bash + gui/.build/artifacts/sparkle/Sparkle/bin/generate_keys + ``` + If a key already exists in the Keychain, it prints that one instead: reuse it, do not create another. +3. Store both in GitHub **without the private key ever appearing in a chat, log, command line or commit**: + ```bash + umask 077 + gui/.build/artifacts/sparkle/Sparkle/bin/generate_keys -x "$TMPDIR/sparkle_private_key" + gh secret set SPARKLE_ED_PRIVATE_KEY --repo AA-EION/TetherKitNext < "$TMPDIR/sparkle_private_key" + rm -P "$TMPDIR/sparkle_private_key" + gh variable set SPARKLE_ED_PUBLIC_KEY --repo AA-EION/TetherKitNext --body "" + ``` +4. Remind the maintainer to back up the Keychain item ("Private key for signing Sparkle updates"). Losing it means installed apps can never auto-update again. + +### 9.3 Publishing a release + +1. Bump `VERSION` in `CMakeLists.txt` (the tag must match it) and commit on `main`. +2. Tag and push: `git tag -a vX.Y.Z -m "TetherKitNext X.Y.Z" && git push origin vX.Y.Z` (a `-beta.N`/`-rc.N` suffix makes a prerelease, which gets no appcast). +3. The Release workflow builds, signs, notarizes, and for stable tags with the Sparkle key: signs the DMG, verifies it against the key inside the built app (`scripts/verify-sparkle-signature.swift`), and uploads `appcast.xml`, `TetherKitNext-X.Y.Z.dmg` and `TetherKitNext.dmg`. +4. Verify after publishing: + ```bash + curl -fsSL https://github.com/AA-EION/TetherKitNext/releases/latest/download/appcast.xml | head -30 + ``` + The `` must be greater than the previous release's, and the enclosure URL must download. +5. **Releases come only from `release.yml`** (pitfall 48): `CFBundleVersion` is its run number. + +### 9.4 Local signed build (optional, for testing on the Mac) + +```bash +export TETHERKITNEXT_SIGN_IDENTITY="Developer ID Application: ()" +export TETHERKITNEXT_SPARKLE_PUBLIC_KEY="" # omit to build a check-only app +./scripts/build-release.sh +``` + +To test an update end to end, install an older signed build, publish a newer one (or serve a local appcast through `TETHERKITNEXT_SPARKLE_FEED_URL` at build time; it must be https), and use **Check for Updates…**. + +--- + +## 10. CI & Shared macOS Runner Policy (**Mandatory, Always**) + +GitHub-hosted macOS runners are shared and scarce. GitHub's documented limit is **5 concurrent macOS jobs** on Free/Pro/Team plans (50 on Enterprise), and "during periods of high demand, jobs that run on macOS runners may take longer to start." AI-driven development multiplies branches, pushes and runs. This project must stay a good neighbour **without weakening what is checked before a merge or a release**. Every agent and maintainer follows these rules; changing them needs the maintainer's explicit approval. + +### 10.1 What runs when (implemented in the workflows; keep it this way) + +| Trigger | macOS jobs | +|---|---| +| Docs-only change (`*.md`, `docs/`, licence, issue templates) | **None** (`ci.yml` `plan` job; CodeQL `paths-ignore`) | +| Push to a **draft** PR | **Fast set, 2 jobs**: `C++ + feth ABI · macos-26`, `Universal app + DMG`. CodeQL runs its Linux languages only; clang-tidy is skipped | +| PR **ready for review** (and pushes to it), push to `main`, weekly schedule, manual run | **Full set**: C++ + feth ABI on macos-15/26/15-intel/xcode-27, universal app, Intel/old-macOS DMG install test, macOS 27 GUI, ThreadSanitizer, CodeQL C/C++ + Swift, clang-tidy (when C++ sources changed) | +| DMG layout scripts changed (`scripts/make-dmg.sh`, `scripts/dmg/`) on a full run | + Finder DMG window check | +| `ui-snapshots` label, PR leaving draft with GUI changes, or manual run | UI snapshots (macOS 26 + 15) | +| `v*` tag | Release build (one job) | + +- `push` triggers only on `main`; branches are covered by their PR. **Never** add `push: branches: ["**"]` back: it doubled every run. +- Concurrency groups use `github.event.pull_request.number || github.ref`, so a new push cancels the previous run of the same PR. +- `CI result` (`ci.yml` `result` job) is the single required check: it always reports, so skipped jobs never block a merge. It is an **allowlist**: only `success` and `skipped` pass. Anything else fails it, including `abandoned` (a job no runner ever picked up, seen on 2026-12-01 when the macOS queue was saturated). Never turn it back into a denylist of `failure`/`cancelled`. +- One VM per OS: build once, run unit tests and the root `feth` gate in the same job. Don't split jobs that run on the same OS without a reason. + +### 10.2 Rules for agents and contributors + +1. **Open PRs as draft and iterate there.** Mark ready for review only when the work is complete; that triggers the full set once. +2. **Batch pushes.** Commit freely, push related commits together. Don't push to "see if it compiles" what you can compile or test locally; on a Mac, run `ctest` and `swift test` first. +3. **Run local checks first**: clang-format on changed lines (pitfall 45), unit tests, script syntax, `actionlint` for workflow edits, and `scripts/check-comment-only.py` for comment-only changes. +4. **Docs-only or workflow-only commits that need no run**: add `[skip ci]` to the commit message (works for `push` and `pull_request`; it must be the PR's HEAD commit). +5. **Never re-run macOS jobs for cosmetic checks**, never "Re-run all jobs" for one failure (re-run the failed job only), and never re-trigger a run to "refresh" results. Don't push while a needed macOS run is still queued: it cancels that run and puts a new one at the back of the queue. +6. **UI screenshots on purpose**: request them once per batch of UI changes (label or manual run), never per push. +7. **No new macOS jobs, matrix entries, schedules or longer timeouts without a written reason** in the PR. Move anything that doesn't need macOS to Linux. +8. **Report queue time honestly.** If a macOS job is queued, say so and wait (or work on something else); don't retrigger it. + +--- + +## 11. Comments, Documentation and Repository Hygiene (**Mandatory, Always**) + +Much of this codebase was written or translated with AI agents. A repository-wide audit (December 2026) found ~60 stale or history-narrating comments, 14 "this machine" translation slips, 1,409 over-long comment lines, contradictory docs, and an unreferenced screenshot. These rules keep that from coming back. They apply to people and agents alike. + +### 11.1 Code comments + +1. **Explain why, not what or when.** A comment states a constraint, an invariant or a reason the code cannot show (a Darwin quirk, an ABI fact, a threading or security rule). Don't restate the next line. +2. **No change narration.** No "used to", "previously", "the old implementation", "now that", "we fixed", "back then", "regression for the bug where", dates of changes, or references to sessions, agents or reviews. State the current rule and its reason. History belongs in commit messages and PR descriptions. +3. **No issue or PR numbers as the explanation.** Write the reason ("fixed width so the menu bar item does not jitter"), not "upstream issue #1". External references that document a platform quirk are fine (e.g. libusb issue #1288). +4. **Say what is true everywhere.** Never "this machine", "on my Mac" or a single measurement stated as a universal fact. Cite the measured value with its source ("2048 on macOS 26, see section 2.4") or say "this Mac" / "the host" when that is what is meant. +5. **Plain style.** No "★ … ★" or `* Title *` banners (use a plain first line or `// MARK: -`), no "deliberately"/"on purpose" filler (pitfall 16), at most one or two **bold** words per comment, no `--` as a dash in prose (use a comma, colon, semicolon or parentheses). +6. **Line length.** C/C++ comments ≤ 100 columns (`.clang-format`); Swift comments ≤ 120; shell/YAML/Python comments ≤ 100. Wrap when you touch a comment. +7. **One home per explanation.** When the same quirk matters in several files, explain it fully once (or in a pitfall here) and point to it elsewhere ("see AGENTS.md pitfall 12"). +8. **No commented-out code and no finished TODOs.** Delete them; git keeps history. +9. **Comment-only changes must be proven comment-only.** After any comment or wording cleanup, run `scripts/check-comment-only.py` (against `HEAD` for uncommitted work, or `origin/main` for a branch). It strips comments from both versions and fails on any other difference. Then run clang-format on the changed C/C++ lines (pitfall 45). + +### 11.2 Documentation + +1. **Docs describe the present.** No dated "Current Status (date)" headings, no "this change", no "(new)", no struck-through rows. Dated content is only for audits and reviews (e.g. SECURITY-AUDIT addenda, MACOS-27 review date). +2. **One source of truth.** Facts live in one place and other docs link to it: coding conventions (section 4), pitfalls (section 7), open verification items (section 6.3), CI policy (section 10). Don't copy them into other files. +3. **Verify against the code before writing.** Job names, file paths, versions, counts, minimums (CMake 3.24, macOS 14 to run / 15 + Xcode 26 to build), language lists (GUI: six; C++ library and CLI: English and Chinese) must match the code. When you change behaviour, update every doc that describes it in the same change. +4. **Remove, don't annotate.** When a feature or file is removed, delete its docs (or move still-true facts to a reference note) instead of adding "removed" remarks. Spike and history documents are trimmed to what is still true. +5. **No instructions that destroy content** (e.g. "regenerate by redirecting into this hand-written file"). +6. **Links must resolve.** Check relative links and anchors after renaming or deleting a doc, including citations in code comments. + +### 11.3 Secrets, personal data and environment values + +1. **Never commit secrets**: keys, tokens, certificates (.p12, .p8, .pem, .cer, .key, .mobileprovision), Sparkle private keys, passwords, `.env` files. `.gitignore` blocks the usual files; don't override it. Workflows read secrets only from `secrets.*`, never echo them, never put them on a command line, never enable `set -x` near them; pass keys through stdin or a `RUNNER_TEMP` file that is deleted afterwards. +2. **No personal or machine-specific values in tracked files**: no `/Users/`, `/home/`, `/private/var/folders`, agent scratch paths (`/tmp/claude`, scratchpads), real names in signing identities, personal emails or hostnames. Use placeholders (`Developer ID Application: ()`). The public donation address is a maintainer decision, not something agents add or spread. +3. **If a secret is ever committed**: stop, tell the maintainer, rotate the secret, and only then discuss rewriting history. Removing it from the tip is not enough. +4. **Scan before large pushes** of new files: a secret scanner (e.g. `detect-secrets scan --all-files`) or at least a grep for key prefixes and personal paths, over the tree and the branch's history. + +### 11.4 Leftover files + +1. **Nothing generated or temporary is committed**: build output, logs, screenshots, reports, plans, `.orig`/`.rej`/`.bak` files, agent notes or summaries. Agent scratch work stays outside the repository. +2. **Every committed asset is referenced** (by the README, a doc, a script or the build). Delete unreferenced images and scripts. +3. **Reports to the user go in the chat or PR, not in new Markdown files**, unless the maintainer asks for a document. + diff --git a/CMakeLists.txt b/CMakeLists.txt index 57363e1..364b3b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,50 +2,54 @@ cmake_minimum_required(VERSION 3.24) project( TetherKitNext - VERSION 1.2.0 - DESCRIPTION "macOS 用户态 RNDIS 驱动:libusb + feth + BPF" + VERSION 1.3.0 + DESCRIPTION "User-space RNDIS driver for macOS: libusb + feth + BPF" LANGUAGES CXX) # ------------------------------------------------------------------------------ # Platform prerequisite check # -# This project depends on macOS-private feth (if_fake) virtual NICs and Darwin BPF, so it cannot be cross-platform. +# This project depends on macOS-private feth (if_fake) virtual NICs and Darwin BPF, so it cannot be +# cross-platform. # ------------------------------------------------------------------------------ if(NOT APPLE) - message(FATAL_ERROR "TetherKitNext 仅支持 macOS:依赖 feth(if_fake) 与 Darwin BPF。") + message(FATAL_ERROR "TetherKitNext supports macOS only: it depends on feth (if_fake) and Darwin BPF.") endif() # ------------------------------------------------------------------------------ # Global language standard # # Why C++23 (verified on Apple clang 21 / macOS 26.5): -# * std::expected -- the main vehicle for error propagation on the initialization path, avoiding a mix of exceptions and error codes. -# * std::byteswap -- the RNDIS wire format is little-endian, so explicit conversion is needed on other endiannesses. +# * std::expected: the main vehicle for error propagation on the initialization path, avoiding a +# mix of exceptions and error codes. +# * std::byteswap: the RNDIS wire format is little-endian, so explicit conversion is needed on +# other endiannesses. # ------------------------------------------------------------------------------ set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) # Deployment target: -# * Not set explicitly; let CMake take the host macOS version -- otherwise it would produce the linker warning "building for -# macOS-13.3, but linking with dylib which was built for newer version" against Homebrew's libusb -# (built for the host version). -# * But the lower bound of 13.3 must be validated: libc++'s std::to_chars (the underlying implementation of -# std::format floating-point formatting) carries an availability annotation, and a lower deployment target fails to compile. +# * Not set explicitly; let CMake take the host macOS version; otherwise it would produce the +# linker warning "building for macOS-13.3, but linking with dylib which was built for newer +# version" against Homebrew's libusb (built for the host version). +# * But the lower bound of 13.3 must be validated: libc++'s std::to_chars (the underlying +# implementation of std::format floating-point formatting) carries an availability annotation, +# and a lower deployment target fails to compile. set(TETHERKITNEXT_MIN_MACOS_VERSION "13.3") if(CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS TETHERKITNEXT_MIN_MACOS_VERSION) message( FATAL_ERROR - "CMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} 过低," - "至少需要 ${TETHERKITNEXT_MIN_MACOS_VERSION}(libc++ 的 std::to_chars 带 availability 标注)。") + "CMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} is too low; " + "at least ${TETHERKITNEXT_MIN_MACOS_VERSION} is required (libc++'s std::to_chars has an availability annotation).") endif() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "RelWithDebInfo" - CACHE STRING "构建类型" FORCE) + CACHE STRING "Build type" FORCE) endif() # Always export compile_commands.json for clangd / clang-tidy. @@ -53,12 +57,14 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # Enable position-independent code globally. # -# Each feature module is a static library, but they are ultimately linked into the shared library libtetherkitnext -- non-PIC object -# files cannot be linked into a dylib. PIC is already the default on macOS/clang; it is written out explicitly here so that -# "why PIC is required" is documented in the build script. +# Each feature module is a static library, but they are ultimately linked into the shared library +# libtetherkitnext; non-PIC object files cannot be linked into a dylib. PIC is already the default +# on macOS/clang; it is written out explicitly here so that "why PIC is required" is documented in +# the build script. set(CMAKE_POSITION_INDEPENDENT_CODE ON) -# Executables and libraries are all output to build/bin and build/lib, which is convenient for scripts to reference. +# Executables and libraries are all output to build/bin and build/lib, which is convenient for +# scripts to reference. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") @@ -68,15 +74,15 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") # ------------------------------------------------------------------------------ # Build options # ------------------------------------------------------------------------------ -option(TETHERKITNEXT_BUILD_TESTS "构建单元测试" ON) -option(TETHERKITNEXT_BUILD_BENCHMARKS "构建性能基准" ON) -option(TETHERKITNEXT_BUILD_SHARED_LIB "构建共享库 libtetherkitnext(GUI 与其它语言绑定需要)" ON) -option(TETHERKITNEXT_WARNINGS_AS_ERRORS "把编译警告当作错误" OFF) -option(TETHERKITNEXT_NATIVE_ARCH "为本机 CPU 微架构优化(-mcpu=native,产物不可移植)" OFF) -option(TETHERKITNEXT_ENABLE_LTO "启用链接时优化(Release 类构建)" OFF) -option(TETHERKITNEXT_ENABLE_ASAN "启用 AddressSanitizer" OFF) -option(TETHERKITNEXT_ENABLE_UBSAN "启用 UndefinedBehaviorSanitizer" OFF) -option(TETHERKITNEXT_ENABLE_TSAN "启用 ThreadSanitizer(验证无锁队列与线程模型)" OFF) +option(TETHERKITNEXT_BUILD_TESTS "Build unit tests" ON) +option(TETHERKITNEXT_BUILD_BENCHMARKS "Build benchmarks" ON) +option(TETHERKITNEXT_BUILD_SHARED_LIB "Build the shared library libtetherkitnext (needed by the GUI and other language bindings)" ON) +option(TETHERKITNEXT_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF) +option(TETHERKITNEXT_NATIVE_ARCH "Optimize for this CPU's microarchitecture (-mcpu=native; output is not portable)" OFF) +option(TETHERKITNEXT_ENABLE_LTO "Enable link-time optimization (Release-type builds)" OFF) +option(TETHERKITNEXT_ENABLE_ASAN "Enable AddressSanitizer" OFF) +option(TETHERKITNEXT_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer" OFF) +option(TETHERKITNEXT_ENABLE_TSAN "Enable ThreadSanitizer (validates the lock-free queues and threading model)" OFF) include(CompilerWarnings) include(Sanitizers) @@ -107,17 +113,18 @@ endif() # ------------------------------------------------------------------------------ # Graphical interface # -# The Swift part is built by SwiftPM (see gui/Package.swift for why CMake's Swift support is not used); here we only -# provide a convenient entry point that chains "build C++ first, then Swift": +# The Swift part is built by SwiftPM (see gui/Package.swift for why CMake's Swift support is not +# used); here we only provide a convenient entry point that chains "build C++ first, then Swift": # # cmake --build build --target gui # -# Deliberately made a **manually triggered** target (the effect of EXCLUDE_FROM_ALL): the GUI needs the Xcode toolchain, -# and people who only want the command line should not be forced to install it. +# A **manually triggered** target (the effect of EXCLUDE_FROM_ALL): the GUI needs the Xcode +# toolchain, and people who only want the command line should not be forced to install it. # ------------------------------------------------------------------------------ if(TETHERKITNEXT_BUILD_SHARED_LIB AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gui/Package.swift") - # Explicitly pass the current build directory to the script (it defaults to /build), so libtetherkitnext is also - # found correctly in non-default directories such as build-rel / build-tsan. + # Explicitly pass the current build directory to the script (it defaults to /build), so + # libtetherkitnext is also found correctly in non-default directories such as build-rel / + # build-tsan. add_custom_target( gui COMMAND "${CMAKE_COMMAND}" -E env "TETHERKITNEXT_BUILD_DIR=${CMAKE_BINARY_DIR}" @@ -125,7 +132,7 @@ if(TETHERKITNEXT_BUILD_SHARED_LIB AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gui/Pa "${CMAKE_CURRENT_SOURCE_DIR}/gui/Scripts/build-gui.sh" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" DEPENDS tetherkitnext_shared tetherkitnext - COMMENT "构建 TetherKitNext.app 与 tetherkitnext-helper" + COMMENT "Building TetherKitNext.app and tetherkitnext-helper" USES_TERMINAL VERBATIM) set_property(TARGET gui APPEND PROPERTY @@ -136,20 +143,20 @@ endif() # Build configuration summary # ------------------------------------------------------------------------------ message(STATUS "") -message(STATUS "==== TetherKitNext ${PROJECT_VERSION} 构建配置 ====") -message(STATUS " 构建类型 : ${CMAKE_BUILD_TYPE}") -message(STATUS " C++ 标准 : C++${CMAKE_CXX_STANDARD}") +message(STATUS "==== TetherKitNext ${PROJECT_VERSION} build configuration ====") +message(STATUS " Build type : ${CMAKE_BUILD_TYPE}") +message(STATUS " C++ standard : C++${CMAKE_CXX_STANDARD}") if(CMAKE_OSX_DEPLOYMENT_TARGET) set(_tk_deploy "macOS ${CMAKE_OSX_DEPLOYMENT_TARGET}") else() - set(_tk_deploy "宿主默认") + set(_tk_deploy "host default") endif() -message(STATUS " 部署目标 : ${_tk_deploy}(下限 ${TETHERKITNEXT_MIN_MACOS_VERSION})") -message(STATUS " 编译器 : ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}") +message(STATUS " Deployment target : ${_tk_deploy} (minimum ${TETHERKITNEXT_MIN_MACOS_VERSION})") +message(STATUS " Compiler : ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}") message(STATUS " libusb : ${LibUSB_VERSION} (${LibUSB_LIBRARY})") -message(STATUS " 单元测试 : ${TETHERKITNEXT_BUILD_TESTS}") -message(STATUS " 性能基准 : ${TETHERKITNEXT_BUILD_BENCHMARKS}") -message(STATUS " 本机微架构优化 : ${TETHERKITNEXT_NATIVE_ARCH}") +message(STATUS " Unit tests : ${TETHERKITNEXT_BUILD_TESTS}") +message(STATUS " Benchmarks : ${TETHERKITNEXT_BUILD_BENCHMARKS}") +message(STATUS " Native -mcpu : ${TETHERKITNEXT_NATIVE_ARCH}") message(STATUS " LTO : ${TETHERKITNEXT_ENABLE_LTO}") message(STATUS " ASan/UBSan/TSan : ${TETHERKITNEXT_ENABLE_ASAN}/${TETHERKITNEXT_ENABLE_UBSAN}/${TETHERKITNEXT_ENABLE_TSAN}") message(STATUS "=========================================") diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..9349d14 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,134 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement, the maintainers +at Issen Software Group, through the contact details at +. You can also use GitHub's **Report content** +option on the comment, issue or pull request concerned. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..745b2fd --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,123 @@ +# Contributing to TetherKitNext + +Thanks for helping. TetherKitNext is a macOS app plus a user-space RNDIS +driver, maintained by Issen Software Group. This guide covers how to build it, +what a good change looks like, and how we keep CI fast and fair to everyone +else who shares GitHub's macOS runners. + +By taking part you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). +Security problems go through [SECURITY.md](SECURITY.md), never a public issue. + +## Before you start + +* **Bugs**: open an issue with the bug form (macOS version, app version, phone + or device, and the log from the app's **Activity** page). +* **Features**: open an issue first for anything larger than a small fix, so we + can agree on the approach before you spend time on it. +* **Read [AGENTS.md](AGENTS.md)** before changing code. Despite the name it is + the project's working memory for humans and AI agents alike: verified facts + about macOS (BPF, `feth`, libusb), coding conventions, and a list of pitfalls + that were each expensive to find. + +## Building and testing + +Requirements: a Mac with macOS 15 or later and Xcode 26 to build (the app runs on macOS 14+), CMake 3.24+, and libusb +(`brew install libusb`, or `scripts/build-libusb.sh` for the pinned universal +build). No phone and no root are needed for the default tests. + +```bash +cmake -S . -B build -DTETHERKITNEXT_WARNINGS_AS_ERRORS=ON && cmake --build build -j +ctest --test-dir build --output-on-failure +TETHERKITNEXT_LIB_DIR=$PWD/build/lib swift test --package-path gui +./gui/Scripts/build-gui.sh # dist/TetherKitNext.app (ad-hoc signed) +``` + +Root-only cases (creating a real `feth` pair) are opt-in: + +```bash +sudo TETHERKITNEXT_ROOT_TESTS=1 build/bin/tetherkitnext_tests --test-suite=net.feth +``` + +More commands, including ThreadSanitizer and benchmarks, are in AGENTS.md +section 8. + +## What a good change looks like + +* **Small and focused.** One topic per pull request. Refactors go in their own PR. +* **Tested.** New logic gets a unit test (doctest for C++, XCTest for the + Swift `TetherKitNextIPC` / `TetherKitNextUIModel` layers). Tests must not + need a USB device or root unless they are opt-in like the `feth` cases. +* **Formatted.** Changed C/C++ lines must be clean under clang-format 18 + (the Lint workflow blocks otherwise): + `git clang-format --binary clang-format-18 --extensions c,h,cc,cpp,hpp --diff origin/main` +* **Localized.** No user-facing string literals in code. C++ strings go in + `include/tetherkitnext/common/messages.def` (English and Chinese); app + strings go in `gui/Sources/TetherKitNextIPC/LocalizedStrings.swift` in all + six languages. Placeholders must match in every language. +* **Hot path rules.** No allocation, exceptions or `std::expected` on the data + path (AGENTS.md section 4). +* **Documented.** Update README, docs/ or AGENTS.md when behavior changes. A + new non-obvious trap goes into AGENTS.md section 7 as a pitfall. +* **Clean comments and docs.** Comments explain why, not what or when: no change + history, issue numbers as explanations, banners or "this machine". Docs describe + the present and keep each fact in one place. Never commit secrets, personal paths + or generated files. The full rules are in AGENTS.md section 11; check + comment-only cleanups with `scripts/check-comment-only.py`. +* **Commit messages** follow Conventional Commits (`feat(gui): …`, + `fix(core): …`, `ci: …`, `docs: …`). + +## CI and shared macOS runners + +GitHub's macOS runners are shared and scarce: an account can run only a few +macOS jobs at once, and at busy times jobs queue for a long time. Every +unnecessary macOS job delays other projects too. Our CI is built so that +**nothing is checked less before a merge or a release**, but nothing runs that +does not need to: + +| When | What runs on macOS | +|---|---| +| Docs-only change (Markdown, `docs/`) | Nothing | +| Push to a **draft** pull request | Fast set: macOS 26 build, unit tests and `feth` ABI tests, plus the universal app and DMG (2 jobs) | +| PR marked **ready for review**, pushes to it, `main`, weekly, manual runs | Full set: macOS 15, 26, 15-Intel and 27, Intel install test, macOS 27 GUI, ThreadSanitizer, CodeQL, clang-tidy (when C++ sources changed) | +| DMG layout scripts changed | Plus the Finder DMG check | +| `ui-snapshots` label or manual run | UI screenshots of both layouts | + +What we ask of everyone, people and AI agents alike: + +1. **Open pull requests as drafts** and keep them draft while you iterate. + Mark them **ready for review** only when you want the full set and a review. +2. **Batch your pushes.** Commit as often as you like, but push a set of + related commits together, not every small step. Each push to a ready PR + runs about a dozen macOS jobs. +3. **Run the checks locally first** (build, `ctest`, `swift test`, + clang-format). CI confirms; it is not the place to find typos. +4. **Docs-only commits**: CI already skips the macOS jobs, and you can add + `[skip ci]` to the commit message to skip CI entirely. +5. **Don't re-run macOS jobs** to check a cosmetic change, and don't use + "Re-run all jobs" when one job failed: re-run only the failed job. +6. **Ask for UI screenshots on purpose**: add the `ui-snapshots` label once + your UI changes are done, not on every push. +7. **New macOS jobs or matrix entries need a reason** in the pull request + description. Prefer Linux for anything that doesn't need macOS + (formatting, Actions and Python analysis, scripts). + +The **CI result** check sums up each run and is the one to wait for. On a draft +PR it passes on the fast set; the full set runs when the PR is marked ready. + +## AI-assisted contributions + +AI coding assistants are welcome. The contributor who opens the pull request is +responsible for every line in it, as with any other code: + +* Make sure the assistant reads and follows [AGENTS.md](AGENTS.md), including + the CI policy above (section 10 there). +* Review and run the change yourself before you mark it ready. +* Say in the pull request description that an assistant was used and for what. +* No bulk or automated pull requests (mass refactors, drive-by "fixes" + across many files) without an agreed issue first. + +## Licence + +TetherKitNext is MIT-licensed (see [LICENSE](LICENSE) and +[NOTICE.md](NOTICE.md)). By contributing you agree that your contribution is +licensed under the same terms. diff --git a/NOTICE.md b/NOTICE.md index 5987910..07fee4f 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -23,4 +23,5 @@ endorse TetherKitNext. | Component | License | Where | |---|---|---| | [libusb](https://libusb.info) 1.0.30 | LGPL-2.1-or-later | Ships as a separate, replaceable dynamic library (`Contents/Frameworks/libusb-1.0.0.dylib`). The license text is in `Contents/Resources/Licenses/`. Built from the unmodified release tarball by `scripts/build-libusb.sh`. | +| [Sparkle](https://sparkle-project.org) 2.10.1 | MIT (with bundled notices for bsdiff, sais-lite and others) | In-app updates. Ships unmodified as `Contents/Frameworks/Sparkle.framework`; its license text is in `Contents/Resources/Licenses/Sparkle-LICENSE.txt`. | | [doctest](https://github.com/doctest/doctest) 2.4.12 | MIT | Tests only (`third_party/doctest`); not shipped in the app. | diff --git a/README.md b/README.md index 593f55b..fb37e68 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,17 @@ No kernel extensions, no security settings to lower, nothing to disable.

+

+ + Download TetherKitNext for macOS + +
+ + Latest version + +  · macOS 14 or later · Apple silicon and Intel · all releases +

+

By Issen Software Group · based on TetherKit by XiaoMiku01

@@ -34,6 +45,10 @@ connection, so your Mac gets online through your phone's mobile data or Wi-Fi. - **One click to connect.** Plug in, click **Connect**, and you're online. - **Lives in the menu bar**, with an optional live speed readout. - **Command-line tool included** for scripts and power users. +- **Not just phones.** Drones and their remote controllers, FPV goggles, boards like the + Raspberry Pi in USB gadget mode, cameras and other devices that use the same USB networking + (RNDIS) work too. TetherKitNext recognizes when a device is a private link rather than an + internet connection and says so ([details](#devices-that-arent-phones)). - **Interface in 6 languages** (English, Spanish, Chinese, Japanese, German, and Korean). Tested with real phones at about **325 Mbps download / 240–300 Mbps upload** over USB 2.0, @@ -50,8 +65,9 @@ close to what the cable can carry. ## Install -1. Download the latest **TetherKitNext .dmg** from the - [Releases page](https://github.com/AA-EION/TetherKitNext/releases). +1. **[Download TetherKitNext.dmg](https://github.com/AA-EION/TetherKitNext/releases/latest/download/TetherKitNext.dmg)** + (always the latest version; older versions and test builds are on the + [Releases page](https://github.com/AA-EION/TetherKitNext/releases)). 2. Open it and drag **TetherKitNext** into **Applications**. 3. Open TetherKitNext from your Applications folder. 4. Click **Enable Background Component**. macOS will ask you to allow it once, in @@ -69,8 +85,15 @@ or install. ### Updating -Download the new .dmg and replace the app in Applications. If the background component is -still running the old version, **Settings** shows a button to restart it. +TetherKitNext updates itself. When a new version is out, it shows what changed and asks +before doing anything: **Install and Relaunch**, **Remind Me Later** or **Skip This Version**. +The download is checked against the project's signing key and Developer ID before it +replaces the app, and the background component restarts with it (if a connection is active, +it waits until you disconnect). You can also use **Check for Updates…** in the app menu. + +Coming from 1.2.0 or earlier, update once by hand: download the new .dmg and replace the app +in Applications. If the background component is still running the old version, +**Settings** shows a button to restart it. ### Uninstalling @@ -113,9 +136,27 @@ You can also delete it yourself (select it, then **⋯ › Delete Service**). 3. In TetherKitNext, click **Connect**. TetherKitNext sets up the connection and gets an address automatically (DHCP), so internet works -right away. The window shows connection status, live speed and your IP address. +right away. + +### Two layouts: Simple and Detailed + +After the first-time setup, you choose how the window looks (you can change it any time in +Settings, with the gear in the simple view, or with **View › Use Simple/Detailed View**, ⇧⌘L): + +- **Simple** (preselected for new installs): one round button to connect, the device and its + status at a glance, live speed, and a gear for the few settings you need. If you have several + devices, the device name becomes a menu to pick one. Devices that need an address get a + one-click fix right there. +- **Detailed**: everything, organized in a sidebar (below). Installs updated from an earlier + version keep this layout, and are shown the simple one once. -The sidebar has five pages: +**Connect automatically** (off by default; Settings or the gear): connects when you plug in a +device, **but only if your Mac has no Wi-Fi or Ethernet connection**, so plugging in your phone +to charge never takes over a Mac that's already online. If Wi-Fi drops while the phone is plugged +in, it connects after the Mac has been offline for about 10 seconds. It tries once per plug-in: +after you disconnect, it stays disconnected until you plug the device in again. + +The detailed layout's sidebar has five pages: | Page | What's there | |---|---| @@ -123,7 +164,13 @@ The sidebar has five pages: | **Device** | Choose which phone to use (if you have several), plus a couple of advanced options | | **Network** | Automatic (DHCP) or a manual/static IP, DNS servers, and whether to send *all* traffic through the phone | | **Activity** | A live log, useful when something goes wrong | -| **Settings** | Background component, command-line tool, language, menu bar, start at login, updates | +| **Settings** | Background component, command-line tool, language, menu bar, start at login, advanced tools, updates | + +**Advanced tools (optional).** Turn on *Settings › Show advanced tools* to add an **Advanced** +section to the sidebar. Its first page, **Interfaces**, lists every network interface on your Mac +with its addresses and live speed. It only reads your Mac's own counters and changes nothing. +More network tools are planned there ([roadmap](docs/ADVANCED-TOOLS.md)). Leave it off and the +app looks exactly as before. **Closing the window doesn't disconnect you.** TetherKitNext moves to the menu bar (the Dock icon disappears) and keeps the connection up. Click the menu bar icon to see speeds, connect or @@ -135,9 +182,37 @@ network service, so VPN apps such as FortiClient can use it. **Language**: switch between System, English, Spanish, Chinese, Japanese, German, and Korean at any time from the TetherKitNext menu, the menu bar panel, or Settings. -**Updates**: TetherKitNext checks this project's GitHub releases once a day and tells you when -there's a new version. You can turn this off in Settings. It never downloads or installs -anything by itself. +### Devices that aren't phones + +Many gadgets use the same USB networking as Android phones but are a **private link to the +device**, not a way onto the internet: drones and their remote controllers (for desktop +companion apps that update firmware, calibrate or download logs), FPV goggles, single-board +computers in USB gadget mode, cameras, and more. On a Mac those used to need HoRNDIS, a +kernel driver that no longer loads on current macOS and never ran on Apple Silicon. + +Connect them the same way. TetherKitNext checks what the device actually offers and +adjusts: + +| What the device does | What you see | +|---|---| +| Hands out an address **with** a router (a phone) | The normal connection. Nothing changes. | +| Hands out an address **without** a router | **Connected · local device.** The Mac keeps using Wi-Fi or Ethernet for the internet; apps that work with the device can reach it. | +| Has no DHCP server at all | After a short wait, TetherKitNext shows the device's own address if it saw it on the wire and suggests one for your Mac in the same network. One click applies it **for this connection only**. | + +- **Your internet is never taken over by a device that can't provide it.** "Route all traffic + through this interface" is only honored when the device offers a router. +- **Nothing is remembered about the device.** The check runs live every time and keeps + running while you're connected. A phone that is simply slow to hand out an address shows + "Waiting for an address" and switches to the normal connection on its own once it does. + An address you set for a local device is used for that connection only and never replaces + your saved network settings. +- Whether a device's own desktop software accepts the connection depends on that + software; TetherKitNext provides the network link it expects. + +**Updates**: TetherKitNext checks this project's GitHub releases once a day. When there's a +new version it asks you first, then downloads, verifies and installs it (see +[Updating](#updating)). It never installs anything without your confirmation, and you can +turn the check off in Settings. --- @@ -181,7 +256,8 @@ Tip: `sudo` doesn't always pass your language setting through, so use `--lang en |---|---| | **"No device detected"** | Try another cable (many only charge). Make sure USB tethering is turned **on** on the phone. Unlock the phone and accept any "trust this computer" / USB prompt. | | **Stuck on "Allow TetherKitNext in System Settings"** | Open **System Settings › General › Login Items & Extensions** and turn TetherKitNext on. Make sure the app is in your **Applications** folder, not running from the downloaded disk image. | -| **Connected, but no internet** | On the phone, check that mobile data or Wi-Fi actually works. On the **Network** page, turn on "route all traffic through this interface" if your Mac is also connected to another network. | +| **Connected, but no internet** | On the phone, check that mobile data or Wi-Fi actually works. On the **Network** page, turn on "route all traffic through this interface" if your Mac is also connected to another network. If the status says **local device**, the device doesn't offer internet at all (a drone, a board); that's expected. | +| **"No address from the device"** | A phone: check that USB tethering is on; the page updates by itself when an address arrives. A device with a fixed address: use the suggested address, or type one in the device's network. | | **Error about another program using the device** | Something else is holding the phone's USB connection, often an old HoRNDIS install. Remove it and restart. | | **Slow speeds** | Use a USB 3 port and a short, good cable. Close other tethering apps. See [docs/PERFORMANCE.md](docs/PERFORMANCE.md) for tuning. | | **Anything else** | The **Activity** page shows exactly what happened. Include it when you open an [issue](https://github.com/AA-EION/TetherKitNext/issues). | @@ -203,8 +279,10 @@ requires rebooting into Recovery and lowering your security settings. TetherKitN job without any of that. **Which devices work?** -Most Android phones with USB tethering. Also some Linux boards (Raspberry Pi Zero, -BeagleBone) and older Windows phones. Run `tetherkitnext-cli --list` to check yours. +Most Android phones with USB tethering, and other devices that use USB networking (RNDIS): +drones and remote controllers, FPV goggles, Linux boards (Raspberry Pi Zero, BeagleBone), +cameras and older Windows phones. Run `tetherkitnext-cli --list` to check yours. Devices that +aren't phones are handled as local links; see [Devices that aren't phones](#devices-that-arent-phones). **Do I need this for an iPhone?** No. macOS supports iPhone USB tethering on its own. @@ -241,7 +319,7 @@ More detail: [docs/DESIGN.md](docs/DESIGN.md) · ### Building -You need macOS 14 or later, **Xcode 26** and CMake 3.24 or newer. +The app runs on macOS 14 or later. Building it needs macOS 15 or later with **Xcode 26**, and CMake 3.24 or newer. ```bash # The whole thing: universal app + disk image, with all tests @@ -268,6 +346,12 @@ export TETHERKITNEXT_SIGN_IDENTITY="Developer ID Application: Your Name (TEAMID) --- +## Contributing + +Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) (building, tests, and +how we keep CI light on GitHub's shared macOS runners) and the [Code of Conduct](CODE_OF_CONDUCT.md). +Report security problems privately as described in [SECURITY.md](SECURITY.md). + ## Support & Donations TetherKitNext is free and open-source software. If it has been helpful to you, consider supporting its ongoing development: diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f805ab3 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,43 @@ +# Security Policy + +TetherKitNext runs a privileged background component (root) and handles USB +and network traffic, so security reports are taken seriously. + +## Supported versions + +Only the latest release receives security fixes. The app updates itself +(Settings › Updates), so staying current is one click. + +| Version | Supported | +|---|---| +| Latest release | ✅ | +| Older releases | ❌ (update first) | + +## Reporting a vulnerability + +**Please do not open a public issue for a security problem.** + +Report it privately through GitHub: on this repository, open the **Security** +tab and click **Report a vulnerability** (GitHub private vulnerability +reporting). Include: + +* what an attacker can do and under which conditions (local user, another app, + a malicious USB device, the network); +* the affected version and macOS version; +* steps or a proof of concept, if you have one. + +You will get an acknowledgement within a few days. We will agree on a +disclosure date with you, fix the issue, publish an advisory, and credit you +unless you prefer otherwise. + +## Scope + +In scope: the app, the privileged daemon and its XPC interface, the +command-line tool, the C/C++ driver, the self-update path (Sparkle feed and +signature checks), and the build and release workflows. + +Out of scope: vulnerabilities in macOS itself or in a phone's tethering +implementation (report those to Apple or the vendor), and issues that need an +attacker who already has root on the Mac. + +The project's own security review is in [docs/SECURITY-AUDIT.md](docs/SECURITY-AUDIT.md). diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 69a949d..98321fa 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -1,8 +1,9 @@ -# benchmarks -- performance benchmarks +# benchmarks: performance benchmarks # -# google/benchmark is not pulled in: this project only needs three kinds of metrics -- "nanoseconds per frame / pps / Gbps" -- -# and the bundled lightweight harness (see benchmarks/harness.h) is sufficient, and it can directly emit a Markdown -# summary table to be written into docs/BENCHMARKS.md, saving a parsing step. +# google/benchmark is not pulled in: this project only needs three kinds of metrics; "nanoseconds +# per frame / pps / Gbps", and the bundled lightweight harness (see benchmarks/harness.h) is +# sufficient, and it can directly emit a Markdown summary table to be written into +# docs/BENCHMARKS.md, saving a parsing step. add_executable( tetherkitnext_bench @@ -12,6 +13,7 @@ add_executable( bench_rndis.cc harness.cc) -# tk_core links all the other modules PUBLICly (the benchmarks use rndis codecs and the net loopback). +# tk_core links all the other modules PUBLICly (the benchmarks use rndis codecs and the net +# loopback). target_link_libraries(tetherkitnext_bench PRIVATE tetherkitnext_base tk_version tk_core) target_include_directories(tetherkitnext_bench PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/benchmarks/bench_common.cc b/benchmarks/bench_common.cc index 4b5041e..02fc8a2 100644 --- a/benchmarks/bench_common.cc +++ b/benchmarks/bench_common.cc @@ -1,9 +1,10 @@ // Microbenchmarks of the infrastructure layer. // // These numbers are the baseline for later judging "where the real bottleneck is". In particular: -// * memcpy of one frame vs one SPSC enqueue+dequeue -- used to verify the claim in the FrameRing comments that -// "the copy is not the bottleneck"; -// * Cross-thread throughput of the lock-free queue -- determines the theoretical ceiling of the data path. +// * memcpy of one frame vs one SPSC enqueue+dequeue; used to verify the claim in the FrameRing +// comments that "the copy is not the bottleneck"; +// * Cross-thread throughput of the lock-free queue: determines the theoretical ceiling of the +// data path. #include "bench_common.h" #include @@ -24,7 +25,8 @@ namespace tetherkitnext::bench { namespace { -/// The two most common frame lengths on Ethernet: an MTU-sized full frame and a small TCP ACK frame. +/// The two most common frame lengths on Ethernet: an MTU-sized full frame and a small TCP ACK +/// frame. constexpr std::uint32_t kFullFrameBytes = 1514; constexpr std::uint32_t kSmallFrameBytes = 64; @@ -42,9 +44,10 @@ std::vector MakeFrame(std::uint32_t length) { /// Plain memcpy: the lower bound of FrameRing's single-copy cost. /// -/// Note these are numbers under a **fully hot cache**: both source and destination stay resident in L1. The source on the real RX path is a buffer written by USB -/// DMA, which is cold to the CPU cache, so the actual cost will be higher. What is measured here is the lower bound, -/// used to subtract from FrameRing's round-trip cost to estimate the queue's own overhead. +/// Note these are numbers under a **fully hot cache**: both source and destination stay resident in +/// L1. The source on the real RX path is a buffer written by USB DMA, which is cold to the CPU +/// cache, so the actual cost will be higher. What is measured here is the lower bound, used to +/// subtract from FrameRing's round-trip cost to estimate the queue's own overhead. std::uint64_t BenchMemcpy(std::uint64_t iterations, std::uint32_t frame_bytes) { const std::vector source = MakeFrame(frame_bytes); std::vector destination(frame_bytes); @@ -61,8 +64,8 @@ std::uint64_t BenchMemcpy(std::uint64_t iterations, std::uint32_t frame_bytes) { /// The 11 LoadLe32 calls needed to parse an RNDIS_PACKET_MSG header. std::uint64_t BenchParsePacketHeader(std::uint64_t iterations) { - // A 44-byte REMOTE_NDIS_PACKET_MSG header, deliberately placed at an odd offset, - // to also verify the cost of unaligned reads (should be zero). + // A 44-byte REMOTE_NDIS_PACKET_MSG header, placed at an odd offset, to also verify the cost of + // unaligned reads (should be zero). std::vector buffer(64); for (std::size_t i = 0; i < buffer.size(); ++i) { buffer[i] = std::byte{static_cast(i)}; @@ -83,7 +86,8 @@ std::uint64_t BenchParsePacketHeader(std::uint64_t iterations) { // SPSC queue // --------------------------------------------------------------------------- -/// One single-thread enqueue+dequeue round: measures pure index arithmetic and memory-ordering overhead (no cross-core cache round trip). +/// One single-thread enqueue+dequeue round: measures pure index arithmetic and memory-ordering +/// overhead (no cross-core cache round trip). std::uint64_t BenchSpscRoundTripSameThread(std::uint64_t iterations) { SpscRing ring(1024); std::uint64_t sink = 0; @@ -99,7 +103,8 @@ std::uint64_t BenchSpscRoundTripSameThread(std::uint64_t iterations) { return iterations; } -/// Cross-thread movement: this is the situation the data path really encounters, including a cache coherence round trip. +/// Cross-thread movement: this is the situation the data path really encounters, including a cache +/// coherence round trip. std::uint64_t BenchSpscCrossThread(std::uint64_t iterations) { SpscRing ring(4096); std::atomic start{false}; @@ -156,11 +161,13 @@ std::uint64_t BenchFrameRingRoundTrip(std::uint64_t iterations, std::uint32_t fr return iterations; } -/// Cross-thread frame movement: the real model of the RX path (libusb callback thread -> BPF write thread). +/// Cross-thread frame movement: the real model of the RX path (libusb callback thread -> BPF write +/// thread). /// -/// `batch_size` = 1 is equivalent to per-frame publishing (one release store per frame, and the cache line holding the write position -/// bounces across cores once per frame); > 1 uses BatchWrite / BatchRead to amortize the publishing. -/// This comparison is direct evidence for the single highest-payoff optimization in the entire data-path design. +/// `batch_size` = 1 is equivalent to per-frame publishing (one release store per frame, and the +/// cache line holding the write position bounces across cores once per frame); > 1 uses BatchWrite +/// / BatchRead to amortize the publishing. This comparison is direct evidence for the single +/// highest-payoff optimization in the entire data-path design. std::uint64_t BenchFrameRingCrossThread(std::uint64_t iterations, std::uint32_t frame_bytes, std::uint32_t batch_size) { FrameRing ring(4096, kMaxEthernetFrameBytes); @@ -196,7 +203,8 @@ std::uint64_t BenchFrameRingCrossThread(std::uint64_t iterations, std::uint32_t if (view.Empty()) { break; } - // Simulate that the consumer really reads the frame content (BPF write reads the whole frame). + // Simulate that the consumer really reads the frame content (BPF write reads the whole + // frame). DoNotOptimize(view.data[0]); ++received; } @@ -212,10 +220,11 @@ std::uint64_t BenchFrameRingCrossThread(std::uint64_t iterations, std::uint32_t /// The counter update executed for every frame: it must be cheap enough to ignore. /// -/// ClobberMemory() must be put in the loop body: consecutive relaxed atomic read-modify-writes are **allowed** to be -/// merged by the compiler (N increments of +1 folded into one +N), and without the barrier the measurement would be 0 ns/op -- that is not the counter's -/// true per-call cost. On the real data path a system call sits between every two counts, so there is no opportunity -/// to merge, and adding a compiler barrier (no runtime instruction) is the correct model. +/// ClobberMemory() must be put in the loop body: consecutive relaxed atomic read-modify-writes are +/// **allowed** to be merged by the compiler (N increments of +1 folded into one +N), and without +/// the barrier the measurement would be 0 ns/op; that is not the counter's true per-call cost. On +/// the real data path a system call sits between every two counts, so there is no opportunity to +/// merge, and adding a compiler barrier (no runtime instruction) is the correct model. std::uint64_t BenchCounterUpdate(std::uint64_t iterations) { DirectionCounters counters; for (std::uint64_t i = 0; i < iterations; ++i) { @@ -226,7 +235,8 @@ std::uint64_t BenchCounterUpdate(std::uint64_t iterations) { return iterations; } -/// Comparison: how much more expensive it would be to use fetch_add (a true atomic read-modify-write, which on arm64 is LSE's ldadd). +/// Comparison: how much more expensive it would be to use fetch_add (a true atomic +/// read-modify-write, which on arm64 is LSE's ldadd). std::uint64_t BenchCounterUpdateFetchAdd(std::uint64_t iterations) { std::atomic frames{0}; std::atomic bytes{0}; @@ -245,48 +255,51 @@ void RegisterCommonBenchmarks(Runner& runner) { constexpr std::uint64_t kMicroOps = 2'000'000; constexpr std::uint64_t kFrameOps = 500'000; - runner.Add("memcpy 基线", "1514 字节帧", + runner.Add("memcpy baseline", "1514-byte frame", Config{.ops_per_round = kFrameOps, .bytes_per_op = kFullFrameBytes}, [](std::uint64_t n) { return BenchMemcpy(n, kFullFrameBytes); }); - runner.Add("memcpy 基线", "64 字节帧", + runner.Add("memcpy baseline", "64-byte frame", Config{.ops_per_round = kFrameOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchMemcpy(n, kSmallFrameBytes); }); - runner.Add("字节序", "解析 44 字节 RNDIS 包头(未对齐)", Config{.ops_per_round = kMicroOps}, + runner.Add("Byte order", "Parse a 44-byte RNDIS header (unaligned)", + Config{.ops_per_round = kMicroOps}, [](std::uint64_t n) { return BenchParsePacketHeader(n); }); - runner.Add("SPSC 队列", "单线程 push+pop", Config{.ops_per_round = kMicroOps}, + runner.Add("SPSC queue", "Single-thread push+pop", Config{.ops_per_round = kMicroOps}, [](std::uint64_t n) { return BenchSpscRoundTripSameThread(n); }); - runner.Add("SPSC 队列", "跨线程搬运", Config{.measure_rounds = 5, .ops_per_round = kFrameOps}, + runner.Add("SPSC queue", "Cross-thread transfer", + Config{.measure_rounds = 5, .ops_per_round = kFrameOps}, [](std::uint64_t n) { return BenchSpscCrossThread(n); }); - runner.Add("FrameRing", "单线程往返(1514 字节)", + runner.Add("FrameRing", "Single-thread round trip (1514 bytes)", Config{.ops_per_round = kFrameOps, .bytes_per_op = kFullFrameBytes}, [](std::uint64_t n) { return BenchFrameRingRoundTrip(n, kFullFrameBytes); }); - runner.Add("FrameRing", "单线程往返(64 字节)", + runner.Add("FrameRing", "Single-thread round trip (64 bytes)", Config{.ops_per_round = kFrameOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchFrameRingRoundTrip(n, kSmallFrameBytes); }); - // Comparison of the effect of batch publishing. This is the most important group of numbers for the whole data path: the same queue, - // the same amount moved, changing only "how many frames each release store publishes". + // Comparison of the effect of batch publishing. This is the most important group of numbers for + // the whole data path: the same queue, the same amount moved, changing only "how many frames each + // release store publishes". for (const std::uint32_t batch : {1U, 4U, 8U, 32U, 64U}) { runner.Add( - "FrameRing 批量发布", - std::format("跨线程 1514 字节 × batch={}", batch), + "FrameRing batch publish", std::format("Cross-thread 1514 bytes × batch={}", batch), Config{.measure_rounds = 5, .ops_per_round = kFrameOps, .bytes_per_op = kFullFrameBytes}, [batch](std::uint64_t n) { return BenchFrameRingCrossThread(n, kFullFrameBytes, batch); }); } runner.Add( - "FrameRing 批量发布", "跨线程 64 字节 × batch=1", + "FrameRing batch publish", "Cross-thread 64 bytes × batch=1", Config{.measure_rounds = 5, .ops_per_round = kFrameOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchFrameRingCrossThread(n, kSmallFrameBytes, 1); }); runner.Add( - "FrameRing 批量发布", "跨线程 64 字节 × batch=32", + "FrameRing batch publish", "Cross-thread 64 bytes × batch=32", Config{.measure_rounds = 5, .ops_per_round = kFrameOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchFrameRingCrossThread(n, kSmallFrameBytes, 32); }); - runner.Add("统计计数器", "relaxed load+store(本项目做法)", Config{.ops_per_round = kMicroOps}, + runner.Add("Stats counter", "relaxed load+store (this project)", + Config{.ops_per_round = kMicroOps}, [](std::uint64_t n) { return BenchCounterUpdate(n); }); - runner.Add("统计计数器", "fetch_add 对比", Config{.ops_per_round = kMicroOps}, + runner.Add("Stats counter", "fetch_add, for comparison", Config{.ops_per_round = kMicroOps}, [](std::uint64_t n) { return BenchCounterUpdateFetchAdd(n); }); } diff --git a/benchmarks/bench_main.cc b/benchmarks/bench_main.cc index 4bc8bb3..ed1944d 100644 --- a/benchmarks/bench_main.cc +++ b/benchmarks/bench_main.cc @@ -1,7 +1,7 @@ // Performance benchmark entry point. // -// The output is a complete Markdown document (on standard output), which can be redirected directly into -// docs/BENCHMARKS.md: +// The output is a complete Markdown document (on standard output), which can be redirected directly +// into docs/BENCHMARKS.md: // // ./build-rel/bin/tetherkitnext_bench > docs/BENCHMARKS.md // @@ -18,47 +18,51 @@ #include "tetherkitnext/version.h" int main() { - // The benchmark thread itself also runs with the data path's QoS, otherwise it might be scheduled onto efficiency cores, - // and the measured numbers would be worse than at actual runtime. + // The benchmark thread itself also runs with the data path's QoS, otherwise it might be scheduled + // onto efficiency cores, and the measured numbers would be worse than at actual runtime. tetherkitnext::ConfigureCurrentThread("bench", tetherkitnext::ThreadRole::kDataPath); const std::string version{tetherkitnext::GetVersionString()}; - std::printf("# TetherKitNext 性能基准\n\n"); - std::printf("由 `tetherkitnext_bench` 自动生成 —— %s\n\n", version.c_str()); - std::printf("> 重新生成:`./build-rel/bin/tetherkitnext_bench > docs/BENCHMARKS.md`\n"); - std::printf("> 必须使用 **未启用消毒器的 Release 构建**,否则数字无参考价值。\n\n"); + std::printf("# TetherKitNext Benchmarks\n\n"); + std::printf("Generated by `tetherkitnext_bench`: %s\n\n", version.c_str()); + std::printf("> Regenerate: `./build-rel/bin/tetherkitnext_bench > docs/BENCHMARKS.md`\n"); + std::printf( + "> Use a **Release build without sanitizers**; other builds produce meaningless " + "numbers.\n\n"); tetherkitnext::bench::PrintEnvironment(); - std::fprintf(stderr, "开始测量……\n"); + std::fprintf(stderr, "Measuring...\n"); { tetherkitnext::bench::Runner runner; tetherkitnext::bench::RegisterCommonBenchmarks(runner); - tetherkitnext::bench::PrintMarkdownReport(runner.RunAll(), "基础设施层(tk_common)"); + tetherkitnext::bench::PrintMarkdownReport(runner.RunAll(), "Infrastructure (tk_common)"); } { tetherkitnext::bench::Runner runner; tetherkitnext::bench::RegisterRndisBenchmarks(runner); - tetherkitnext::bench::PrintMarkdownReport(runner.RunAll(), "RNDIS 编解码(tk_rndis)"); + tetherkitnext::bench::PrintMarkdownReport(runner.RunAll(), "RNDIS codec (tk_rndis)"); } { - // The link layer needs root. When skipped, a trace must also be left in the report -- otherwise the reader cannot tell whether this report - // means "tested and fine" or "not tested at all". + // The link layer needs root. When skipped, a trace must also be left in the report; otherwise + // the reader cannot tell whether this report means "tested and fine" or "not tested at all". tetherkitnext::bench::Runner runner; std::string skip_reason; if (tetherkitnext::bench::RegisterNetBenchmarks(runner, skip_reason)) { - tetherkitnext::bench::PrintMarkdownReport(runner.RunAll(), "feth / BPF 链路层(tk_net,需 root)"); - // It must be torn down here and cannot be left to static destruction -- see bench_net.h for the reason. + tetherkitnext::bench::PrintMarkdownReport(runner.RunAll(), + "feth / BPF link layer (tk_net, needs root)"); + // It must be torn down here and cannot be left to static destruction; see bench_net.h for the + // reason. tetherkitnext::bench::ShutdownNetBenchmarks(); } else { - std::printf("## feth / BPF 链路层(tk_net,需 root)\n\n"); - std::printf("**本次未测量** —— %s。\n\n", skip_reason.c_str()); - std::printf("补测方法:`sudo ./build/bin/tetherkitnext_bench > docs/BENCHMARKS.md`\n\n"); - std::fprintf(stderr, " 跳过链路层基准:%s\n", skip_reason.c_str()); + std::printf("## feth / BPF link layer (tk_net, needs root)\n\n"); + std::printf("**Not measured in this run**: %s.\n\n", skip_reason.c_str()); + std::printf("To measure: `sudo ./build/bin/tetherkitnext_bench > docs/BENCHMARKS.md`\n\n"); + std::fprintf(stderr, " Skipping link-layer benchmarks: %s\n", skip_reason.c_str()); } } - std::fprintf(stderr, "测量完成。\n"); + std::fprintf(stderr, "Done.\n"); return 0; } diff --git a/benchmarks/bench_net.cc b/benchmarks/bench_net.cc index 8161515..1e82a40 100644 --- a/benchmarks/bench_net.cc +++ b/benchmarks/bench_net.cc @@ -1,18 +1,21 @@ -// Benchmarks of the feth / BPF link layer -- **needs root**. +// Benchmarks of the feth / BPF link layer; **needs root**. // -// This group fills in the items that had been long left hanging in the last section of docs/BENCHMARKS.md: the real cost of a BPF write, -// the speedup factor of BIOCSBATCHWRITE relative to per-frame writes, the per-frame cost of batch reads, and the -// round-trip latency of the feth data path. Before this, these numbers all came from research estimates (that ~700 ns write cost came from -// `write(/dev/null)`, **not** a measurement on a real BPF descriptor). +// This group fills in the items that had been long left hanging in the last section of +// docs/BENCHMARKS.md: the real cost of a BPF write, the speedup factor of BIOCSBATCHWRITE relative +// to per-frame writes, the per-frame cost of batch reads, and the round-trip latency of the feth +// data path. Before this, these numbers all came from research estimates (that ~700 ns write cost +// came from `write(/dev/null)`, **not** a measurement on a real BPF descriptor). // // How the fixture is set up: // feth0 (system side, configured with 10.99.99.1) <-> feth1 (driver side) -// * driver_perframe / driver_batched: two BPF descriptors both attached to feth1, -// with BIOCSBATCHWRITE turned off and on respectively, for the A/B of per-frame writes vs batch writes; +// * driver_perframe / driver_batched: two BPF descriptors both attached to feth1, with +// BIOCSBATCHWRITE turned off and on respectively, for the A/B of per-frame writes vs batch +// writes; // * system_link: attached to feth0, used to pour traffic toward feth1 to measure read cost. // -// WARNING: The write cost naturally includes the overhead of "the peer's IP stack receiving the frame and discarding it" -- which is exactly the price the real RX path -// pays for every frame, so measuring this way is correct, and it should not be deliberately bypassed. +// WARNING: The write cost naturally includes the overhead of "the peer's IP stack receiving the +// frame and discarding it", which is exactly the price the real RX path pays for every frame, so +// measuring this way is correct, and it should not be bypassed. #include "bench_net.h" #include @@ -54,8 +57,9 @@ constexpr std::size_t kArpFrameBytes = 42; std::vector MakeFrame(std::uint32_t length) { std::vector frame(length, std::byte{0}); - // Broadcast destination MAC + locally administered source MAC, with EtherType 0x0800. The content itself is unimportant; - // what matters is that it is a structurally legal Ethernet frame that the peer will actually accept and then discard. + // Broadcast destination MAC + locally administered source MAC, with EtherType 0x0800. The content + // itself is unimportant; what matters is that it is a structurally legal Ethernet frame that the + // peer will actually accept and then discard. for (int i = 0; i < 6; ++i) { frame[static_cast(i)] = std::byte{0xFF}; } @@ -130,7 +134,7 @@ std::vector MakeArpRequest() { }; if (!fill(request.ifra_addr, address) || !fill(request.ifra_mask, "255.255.255.0")) { ::close(fd); - return "inet_pton 失败"; + return "inet_pton failed"; } const int result = ::ioctl(fd, SIOCAIFADDR, &request); const int saved_errno = errno; @@ -143,7 +147,8 @@ struct Fixture { std::unique_ptr pair; std::unique_ptr driver_perframe; ///< feth1, batch writes turned off std::unique_ptr driver_batched; ///< feth1, batch writes turned on - std::unique_ptr system_link; ///< feth0, used to pour in traffic in that direction + /// feth0, used to pour in traffic in that direction + std::unique_ptr system_link; bool batch_write_available = false; }; @@ -151,7 +156,8 @@ Fixture* g_fixture = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-globa /// Write benchmark: hands `frames_per_write` frames as one batch to WriteFrames. /// -/// The unit of measurement is the **frame**, so numbers of per-frame writes and batch writes can be compared directly side by side. +/// The unit of measurement is the **frame**, so numbers of per-frame writes and batch writes can be +/// compared directly side by side. std::uint64_t BenchWrite(net::BpfLink& link, std::uint64_t frame_iterations, std::uint32_t frame_bytes, std::uint32_t frames_per_write) { const std::vector frame = MakeFrame(frame_bytes); @@ -164,7 +170,9 @@ std::uint64_t BenchWrite(net::BpfLink& link, std::uint64_t frame_iterations, while (written < frame_iterations) { const auto result = link.WriteFrames(batch); if (!result) { - break; // peer queue saturated and similar cases: honestly count by the number of frames actually written. + // peer queue saturated and similar cases: honestly count by the number of frames actually + // written. + break; } written += result->frames_written; DoNotOptimize(result->bytes_written); @@ -174,8 +182,9 @@ std::uint64_t BenchWrite(net::BpfLink& link, std::uint64_t frame_iterations, /// Read benchmark: pours `burst` frames in from feth0, then reads them back from feth1. /// -/// WARNING: This item measures the combined cost of **write + read**, not pure reading -- the harness can only time the whole -/// closure. To get the pure read cost, subtract the write benchmark value at the same batch size. +/// WARNING: This item measures the combined cost of **write + read**, not pure reading; the harness +/// can only time the whole closure. To get the pure read cost, subtract the write benchmark value +/// at the same batch size. std::uint64_t BenchWriteThenRead(std::uint64_t frame_iterations, std::uint32_t frame_bytes, std::uint32_t burst) { Fixture& fixture = *g_fixture; @@ -192,7 +201,8 @@ std::uint64_t BenchWriteThenRead(std::uint64_t frame_iterations, std::uint32_t f break; } std::uint32_t drained = 0; - // Give up after a bounded number of spins: feth drops frames under queue pressure, so it is normal not to get them all back. + // Give up after a bounded number of spins: feth drops frames under queue pressure, so it is + // normal not to get them all back. for (int attempt = 0; attempt < 4 && drained < written->frames_written; ++attempt) { const auto received = fixture.driver_batched->ReadFrames(); if (!received) { @@ -206,9 +216,11 @@ std::uint64_t BenchWriteThenRead(std::uint64_t frame_iterations, std::uint32_t f return completed; } -/// feth data-path round-trip latency: write an ARP request from the driver side, and wait for the system-side IP stack's reply to be read back. +/// feth data-path round-trip latency: write an ARP request from the driver side, and wait for the +/// system-side IP stack's reply to be read back. /// -/// This is the only true **latency** metric -- the previous items are all amortized costs in the throughput sense. +/// This is the only true **latency** metric; the previous items are all amortized costs in the +/// throughput sense. std::uint64_t BenchArpRoundTrip(std::uint64_t iterations) { Fixture& fixture = *g_fixture; const std::vector request = MakeArpRequest(); @@ -234,7 +246,9 @@ std::uint64_t BenchArpRoundTrip(std::uint64_t iterations) { } } if (!answered) { - break; // when the neighbor table already has a cache the system side no longer answers; stop here rather than over-report. + // when the neighbor table already has a cache the system side no longer answers; stop here + // rather than over-report. + break; } ++completed; } @@ -245,7 +259,7 @@ std::uint64_t BenchArpRoundTrip(std::uint64_t iterations) { bool RegisterNetBenchmarks(Runner& runner, std::string& skip_reason) { if (!net::IsRunningAsRoot()) { - skip_reason = "需要 root(要建 feth 网卡对并打开 /dev/bpf*)"; + skip_reason = "needs root (creates a feth pair and opens /dev/bpf*)"; return false; } @@ -253,14 +267,14 @@ bool RegisterNetBenchmarks(Runner& runner, std::string& skip_reason) { auto pair = net::FethPair::Create(1500); if (!pair) { - skip_reason = std::format("创建 feth 网卡对失败:{}", pair.error().ToString()); + skip_reason = std::format("creating the feth pair failed: {}", pair.error().ToString()); return false; } fixture.pair = std::make_unique(std::move(*pair)); const std::string assign_error = AssignIpv4(fixture.pair->SystemSide().Name(), kSystemIp); if (!assign_error.empty()) { - skip_reason = std::format("给系统侧配地址失败:{}", assign_error); + skip_reason = std::format("assigning the system-side address failed: {}", assign_error); return false; } @@ -277,23 +291,24 @@ bool RegisterNetBenchmarks(Runner& runner, std::string& skip_reason) { fixture.system_link = open(fixture.pair->SystemSide().Name(), true); if (fixture.driver_perframe == nullptr || fixture.driver_batched == nullptr || fixture.system_link == nullptr) { - skip_reason = "打开 BPF 描述符失败"; + skip_reason = "opening a BPF descriptor failed"; return false; } fixture.batch_write_available = fixture.driver_batched->SupportsBatchWrite(); g_fixture = &fixture; - // Frames per round: writing is system-call-level overhead (hundreds of nanoseconds to microseconds), and tens of thousands of frames are stable enough, - // and more would only make the whole round run longer. + // Frames per round: writing is system-call-level overhead (hundreds of nanoseconds to + // microseconds), and tens of thousands of frames are stable enough, and more would only make the + // whole round run longer. constexpr std::uint64_t kWriteOps = 20000; constexpr std::uint64_t kReadOps = 20000; - runner.Add("BPF 写入(逐帧 write)", "1514 字节", + runner.Add("BPF write (per-frame write)", "1514 bytes", Config{.ops_per_round = kWriteOps, .bytes_per_op = kFullFrameBytes}, [](std::uint64_t n) { return BenchWrite(*g_fixture->driver_perframe, n, kFullFrameBytes, 1); }); - runner.Add("BPF 写入(逐帧 write)", "64 字节", + runner.Add("BPF write (per-frame write)", "64 bytes", Config{.ops_per_round = kWriteOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchWrite(*g_fixture->driver_perframe, n, kSmallFrameBytes, 1); @@ -301,27 +316,29 @@ bool RegisterNetBenchmarks(Runner& runner, std::string& skip_reason) { if (fixture.batch_write_available) { for (const std::uint32_t per_write : {8U, 32U, 64U, 128U}) { - runner.Add("BPF 写入(BIOCSBATCHWRITE)", std::format("1514 字节 × 每次 {} 帧", per_write), + runner.Add("BPF write (BIOCSBATCHWRITE)", + std::format("1514 bytes × {} frames per write", per_write), Config{.ops_per_round = kWriteOps, .bytes_per_op = kFullFrameBytes}, [per_write](std::uint64_t n) { return BenchWrite(*g_fixture->driver_batched, n, kFullFrameBytes, per_write); }); } - runner.Add("BPF 写入(BIOCSBATCHWRITE)", "64 字节 × 每次 64 帧", + runner.Add("BPF write (BIOCSBATCHWRITE)", "64 bytes × 64 frames per write", Config{.ops_per_round = kWriteOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchWrite(*g_fixture->driver_batched, n, kSmallFrameBytes, 64); }); } - runner.Add("feth 往返(写+读合计)", "1514 字节 × 每批 64 帧", + runner.Add("feth round trip (write + read)", "1514 bytes × 64 frames per batch", Config{.ops_per_round = kReadOps, .bytes_per_op = kFullFrameBytes}, [](std::uint64_t n) { return BenchWriteThenRead(n, kFullFrameBytes, 64); }); - // The round-trip latency is only run a few hundred times: each one has to wait for the peer IP stack to really answer, and is an operation under a millisecond yet far slower than - // the previous items; running too many gives no extra information. - runner.Add("feth 往返延迟", "ARP 请求 → 系统侧 IP 栈应答", Config{.ops_per_round = 200}, - [](std::uint64_t n) { return BenchArpRoundTrip(n); }); + // The round-trip latency is only run a few hundred times: each one has to wait for the peer IP + // stack to really answer, and is an operation under a millisecond yet far slower than the + // previous items; running too many gives no extra information. + runner.Add("feth round-trip latency", "ARP request → system-side IP stack reply", + Config{.ops_per_round = 200}, [](std::uint64_t n) { return BenchArpRoundTrip(n); }); return true; } @@ -330,8 +347,8 @@ void ShutdownNetBenchmarks() noexcept { if (g_fixture == nullptr) { return; } - // The order matters: close the BPF descriptor first, then destroy the feth pair. In the reverse order - // the interface it is attached to is already gone when BpfLink is destroyed. + // The order matters: close the BPF descriptor first, then destroy the feth pair. In the reverse + // order the interface it is attached to is already gone when BpfLink is destroyed. g_fixture->system_link.reset(); g_fixture->driver_batched.reset(); g_fixture->driver_perframe.reset(); diff --git a/benchmarks/bench_net.h b/benchmarks/bench_net.h index d64a38b..cbb6ab7 100644 --- a/benchmarks/bench_net.h +++ b/benchmarks/bench_net.h @@ -1,8 +1,8 @@ // Registration entry point of the feth / BPF link-layer benchmarks. // -// Unlike the other benchmarks, this group **needs root** (it must create a feth pair and open /dev/bpf*). -// Without root nothing is registered, and the reason is stated through skip_reason -- the report must make visible -// that "this group did not run", rather than letting it vanish silently. +// Unlike the other benchmarks, this group **needs root** (it must create a feth pair and open +// /dev/bpf*). Without root nothing is registered, and the reason is stated through skip_reason; the +// report must make visible that "this group did not run", rather than letting it vanish silently. #pragma once #include @@ -14,16 +14,18 @@ class Runner; /// Builds the feth + BPF fixture and registers the link-layer benchmarks. /// /// @param skip_reason The skip reason written when false is returned. -/// @return Whether registration succeeded. The fixture's lifetime is held by this module's static object, +/// @return Whether registration succeeded. The fixture's lifetime is held by this module's static +/// object, /// and it lives until process exit. bool RegisterNetBenchmarks(Runner& runner, std::string& skip_reason); /// Tears down the fixture (closes the BPF descriptor, destroys the feth pair). /// -/// **Must be called explicitly before main returns.** Letting the fixture live into the static destruction phase crashes: -/// FethDevice's destructor writes logs, and by then the logging module's static mutex may already have been -/// destroyed first, so it throws `std::system_error: mutex lock failed` and the process exits with 134 -- -/// the benchmarks had clearly all finished, yet the exit code is a failure. +/// **Must be called explicitly before main returns.** Letting the fixture live into the static +/// destruction phase crashes: FethDevice's destructor writes logs, and by then the logging module's +/// static mutex may already have been destroyed first, so it throws `std::system_error: mutex lock +/// failed` and the process exits with 134; the benchmarks had clearly all finished, yet the exit +/// code is a failure. void ShutdownNetBenchmarks() noexcept; } // namespace tetherkitnext::bench diff --git a/benchmarks/bench_rndis.cc b/benchmarks/bench_rndis.cc index 2cf4973..96ed54a 100644 --- a/benchmarks/bench_rndis.cc +++ b/benchmarks/bench_rndis.cc @@ -1,8 +1,10 @@ // Microbenchmarks of RNDIS encoding/decoding. // -// These two paths are walked once per frame, and are the only CPU cost billed per frame besides system calls: -// TX: PacketMessageWriter wraps Ethernet frames into RNDIS_PACKET_MSG (including multi-packet aggregation and alignment) -// RX: PacketMessageReader unpacks frame by frame from one bulk IN transfer +// These two paths are walked once per frame, and are the only CPU cost billed per frame besides +// system calls: +// TX: PacketMessageWriter wraps Ethernet frames into RNDIS_PACKET_MSG (including multi-packet +// aggregation and alignment) RX: PacketMessageReader unpacks frame by frame from one bulk IN +// transfer #include "bench_rndis.h" #include @@ -31,7 +33,8 @@ std::vector MakeFrame(std::uint32_t length) { /// TX encoding: aggregates `frames_per_transfer` frames into one transfer. /// -/// The unit of measurement is the **frame** rather than the transfer, so numbers at different aggregation levels can be compared directly side by side. +/// The unit of measurement is the **frame** rather than the transfer, so numbers at different +/// aggregation levels can be compared directly side by side. std::uint64_t BenchEncode(std::uint64_t frame_iterations, std::uint32_t frame_bytes, std::uint32_t frames_per_transfer, std::uint32_t alignment_bytes) { // The transfer buffer must hold frames_per_transfer full frames. @@ -59,10 +62,11 @@ std::uint64_t BenchEncode(std::uint64_t frame_iterations, std::uint32_t frame_by } const std::uint32_t produced = writer.Finish(); DoNotOptimize(produced); - // * The **contents of the target buffer** must also be forcibly observed. If only DoNotOptimize(the return value of Finish()), - // the compiler sees that nobody reads this buffer afterwards and eliminates the memcpy inside TryAppend - // entirely -- so the measurement comes out at 14.5 ns/frame, faster than a bare 1514-byte memcpy (25 ns), - // which is obviously wrong at a glance. Adding ClobberMemory gives the true cost. + // * The **contents of the target buffer** must also be forcibly observed. If only + // DoNotOptimize(the return value of Finish()), the compiler sees that nobody reads this + // buffer afterwards and eliminates the memcpy inside TryAppend entirely, so the measurement + // comes out at 14.5 ns/frame, faster than a bare 1514-byte memcpy (25 ns), which is obviously + // wrong at a glance. Adding ClobberMemory gives the true cost. DoNotOptimize(transfer.data()[0]); ClobberMemory(); } @@ -114,7 +118,8 @@ std::uint64_t BenchDecode(std::uint64_t frame_iterations, std::uint32_t frame_by return decoded; } -/// Encode + decode round trip, simulating the full CPU cost of "the host sends out, the device sends it back unchanged". +/// Encode + decode round trip, simulating the full CPU cost of "the host sends out, the device +/// sends it back unchanged". std::uint64_t BenchRoundTrip(std::uint64_t frame_iterations, std::uint32_t frame_bytes, std::uint32_t frames_per_transfer) { const std::size_t capacity = @@ -146,7 +151,9 @@ std::uint64_t BenchRoundTrip(std::uint64_t frame_iterations, std::uint32_t frame if (packed == 0) { break; } - ClobberMemory(); // see the explanation in BenchEncode: prevents the memcpy from being eliminated across iterations + // see the explanation in BenchEncode: prevents the memcpy from being eliminated across + // iterations + ClobberMemory(); rndis::PacketMessageReader reader(std::span{transfer.data(), transfer_bytes}, rndis::kDefaultMtu + rndis::kEthernetHeaderBytes); @@ -164,42 +171,44 @@ std::uint64_t BenchRoundTrip(std::uint64_t frame_iterations, std::uint32_t frame void RegisterRndisBenchmarks(Runner& runner) { constexpr std::uint64_t kFrameOps = 1'000'000; - // The effect of aggregation level on per-frame cost -- this is the basis of the --max-transfer-kb tuning knob. + // The effect of aggregation level on per-frame cost; this is the basis of the --max-transfer-kb + // tuning knob. for (const std::uint32_t per_transfer : {1U, 4U, 10U}) { - runner.Add("RNDIS 编码", - std::format("1514 字节 × 每传输 {} 帧", per_transfer), + runner.Add("RNDIS encode", std::format("1514 bytes × {} frames per transfer", per_transfer), Config{.ops_per_round = kFrameOps, .bytes_per_op = kFullFrameBytes}, [per_transfer](std::uint64_t n) { return BenchEncode(n, kFullFrameBytes, per_transfer, 1); }); } - runner.Add("RNDIS 编码", "64 字节 × 每传输 10 帧", + runner.Add("RNDIS encode", "64 bytes × 10 frames per transfer", Config{.ops_per_round = kFrameOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchEncode(n, kSmallFrameBytes, 10, 1); }); - // The alignment requirement (PacketAlignmentFactor) introduces extra memset and MessageLength backfilling. - runner.Add("RNDIS 编码", "1514 字节 × 每传输 10 帧 × 对齐 128", + // The alignment requirement (PacketAlignmentFactor) introduces extra memset and MessageLength + // backfilling. + runner.Add("RNDIS encode", "1514 bytes × 10 frames per transfer × 128-byte alignment", Config{.ops_per_round = kFrameOps, .bytes_per_op = kFullFrameBytes}, [](std::uint64_t n) { return BenchEncode(n, kFullFrameBytes, 10, 128); }); - // Decoding deliberately **does not fill bytes_per_op** (so the throughput column shows "-"): the decoder is **zero-copy**, - // it only parses headers and returns views pointing into the transfer buffer, moving not a single byte. Computing "Gbps" for it - // would give absurd numbers in the tens of thousands, not comparable with the encoding's throughput -- on the encoding side memcpy really happens. + // Decoding **does not fill bytes_per_op** (so the throughput column shows "-"): the decoder is + // **zero-copy**, it only parses headers and returns views pointing into the transfer buffer, + // moving not a single byte. Computing "Gbps" for it would give absurd numbers in the tens of + // thousands, not comparable with the encoding's throughput; on the encoding side memcpy really + // happens. for (const std::uint32_t per_transfer : {1U, 4U, 10U}) { - runner.Add("RNDIS 解码(零拷贝)", - std::format("1514 字节 × 每传输 {} 帧", per_transfer), - Config{.ops_per_round = kFrameOps}, - [per_transfer](std::uint64_t n) { + runner.Add("RNDIS decode (zero-copy)", + std::format("1514 bytes × {} frames per transfer", per_transfer), + Config{.ops_per_round = kFrameOps}, [per_transfer](std::uint64_t n) { return BenchDecode(n, kFullFrameBytes, per_transfer); }); } - runner.Add("RNDIS 解码(零拷贝)", "64 字节 × 每传输 10 帧", + runner.Add("RNDIS decode (zero-copy)", "64 bytes × 10 frames per transfer", Config{.ops_per_round = kFrameOps}, [](std::uint64_t n) { return BenchDecode(n, kSmallFrameBytes, 10); }); - runner.Add("RNDIS 编解码往返", "1514 字节 × 每传输 10 帧", + runner.Add("RNDIS encode/decode round trip", "1514 bytes × 10 frames per transfer", Config{.ops_per_round = kFrameOps, .bytes_per_op = kFullFrameBytes}, [](std::uint64_t n) { return BenchRoundTrip(n, kFullFrameBytes, 10); }); - runner.Add("RNDIS 编解码往返", "64 字节 × 每传输 10 帧", + runner.Add("RNDIS encode/decode round trip", "64 bytes × 10 frames per transfer", Config{.ops_per_round = kFrameOps, .bytes_per_op = kSmallFrameBytes}, [](std::uint64_t n) { return BenchRoundTrip(n, kSmallFrameBytes, 10); }); } diff --git a/benchmarks/harness.cc b/benchmarks/harness.cc index 4421821..e2b64ee 100644 --- a/benchmarks/harness.cc +++ b/benchmarks/harness.cc @@ -65,7 +65,8 @@ std::string FormatThroughput(const Result& result) { return buffer.data(); } -/// Adds an exclamation mark when dispersion exceeds 30%, hinting to the reader that this measurement was disturbed by the environment. +/// Adds an exclamation mark when dispersion exceeds 30%, hinting to the reader that this +/// measurement was disturbed by the environment. std::string FormatSpread(const Result& result) { std::array buffer{}; const double spread = result.Spread(); @@ -82,26 +83,28 @@ void PrintEnvironment() { const std::int64_t efficiency = SysctlInt("hw.perflevel1.logicalcpu"); const std::int64_t cacheline = SysctlInt("hw.cachelinesize"); - std::printf("## 测量环境\n\n"); - std::printf("| 项目 | 值 |\n|---|---|\n"); + std::printf("## Environment\n\n"); + std::printf("| Item | Value |\n|---|---|\n"); std::printf("| CPU | %s |\n", SysctlString("machdep.cpu.brand_string").c_str()); - std::printf("| 逻辑核 | %lld(性能核 %lld / 效率核 %lld) |\n", logical, performance, efficiency); - std::printf("| 缓存行 | %lld 字节(kCacheLineSize = %zu) |\n", cacheline, kCacheLineSize); - std::printf("| 系统 | macOS %s (%s) |\n", SysctlString("kern.osproductversion").c_str(), + std::printf("| Logical cores | %lld (%lld performance / %lld efficiency) |\n", logical, + performance, efficiency); + std::printf("| Cache line | %lld bytes (kCacheLineSize = %zu) |\n", cacheline, kCacheLineSize); + std::printf("| OS | macOS %s (%s) |\n", SysctlString("kern.osproductversion").c_str(), SysctlString("kern.osversion").c_str()); const std::string build{GetBuildDescription()}; - std::printf("| 构建 | %s |\n", build.c_str()); + std::printf("| Build | %s |\n", build.c_str()); std::printf("\n"); } void PrintMarkdownReport(const std::vector& results, std::string_view title) { std::printf("## %.*s\n\n", static_cast(title.size()), title.data()); - std::printf("| 分组 | 基准 | 中位数 ns/op | 最好 ns/op | 速率 | 吞吐 | 离散度 |\n"); + std::printf("| Group | Benchmark | Median ns/op | Best ns/op | Rate | Throughput | Spread |\n"); std::printf("|---|---|---:|---:|---:|---:|---:|\n"); std::string current_group; for (const Result& result : results) { - // Within the same group, show the group name only in the first row, which makes the table easier to read. + // Within the same group, show the group name only in the first row, which makes the table + // easier to read. const std::string group_cell = result.group == current_group ? "" : result.group; if (!group_cell.empty()) { current_group = result.group; @@ -112,8 +115,12 @@ void PrintMarkdownReport(const std::vector& results, std::string_view ti FormatSpread(result).c_str()); } std::printf("\n"); - std::printf("> 离散度 =(最差轮 − 最好轮)/ 中位数。超过 30%% 会标 ⚠,说明测量期间存在\n"); - std::printf("> 后台干扰或被调度到了效率核,此时的绝对数值仅供参考。\n\n"); + std::printf( + "> Spread = (worst round − best round) / median. Above 30%% it is flagged ⚠: something ran " + "in\n"); + std::printf( + "> the background or the run landed on an efficiency core, so treat the absolute numbers as " + "rough.\n\n"); } } // namespace tetherkitnext::bench diff --git a/benchmarks/harness.h b/benchmarks/harness.h index 6663a45..35edcc7 100644 --- a/benchmarks/harness.h +++ b/benchmarks/harness.h @@ -1,17 +1,20 @@ // Lightweight performance benchmark harness. // // Why not google/benchmark: -// This project cares about only three kinds of metrics -- nanoseconds per operation, frames per second (pps), and bits per second -// (Gbps). google/benchmark's automatic iteration-count inference, statistical model and JSON output are all things -// we do not need, and it would introduce FetchContent's network dependency and noticeably slow down the build. -// This harness is only 200 lines, yet can directly emit a Markdown table that can be pasted into docs/BENCHMARKS.md, -// saving a parsing step. +// This project cares about only three kinds of metrics; nanoseconds per operation, frames per +// second (pps), and bits per second (Gbps). google/benchmark's automatic iteration-count +// inference, statistical model and JSON output are all things we do not need, and it would +// introduce FetchContent's network dependency and noticeably slow down the build. This harness is +// only 200 lines, yet can directly emit a Markdown table that can be pasted into +// docs/BENCHMARKS.md, saving a parsing step. // // Measurement method (for each benchmark): -// 1. Run several warmup rounds, letting the branch predictor, caches and CPU frequency reach steady state; +// 1. Run several warmup rounds, letting the branch predictor, caches and CPU frequency reach +// steady state; // 2. Then run N formal rounds, with a fixed number of loop iterations inside each round; -// 3. Take the **median** across rounds rather than the mean -- on macOS background processes and big.LITTLE scheduling cause -// occasional long tails, and the median is more robust against them; the best value and relative dispersion are also reported, making it easy to judge +// 3. Take the **median** across rounds rather than the mean; on macOS background processes and +// big.LITTLE scheduling cause occasional long tails, and the median is more robust against +// them; the best value and relative dispersion are also reported, making it easy to judge // whether this measurement is trustworthy. #pragma once @@ -31,14 +34,16 @@ namespace tetherkitnext::bench { /// Prevents the compiler from optimizing away the code under test. /// -/// The inline assembly declares the value as "read, and memory possibly modified", so the compiler cannot eliminate the -/// computation that produces it. This is an equivalent implementation of google/benchmark's DoNotOptimize. +/// The inline assembly declares the value as "read, and memory possibly modified", so the compiler +/// cannot eliminate the computation that produces it. This is an equivalent implementation of +/// google/benchmark's DoNotOptimize. template inline void DoNotOptimize(T const& value) { asm volatile("" : : "r,m"(value) : "memory"); } -/// Makes the compiler assume all memory may be read or written, used to separate two pieces of code that must not be merged. +/// Makes the compiler assume all memory may be read or written, used to separate two pieces of code +/// that must not be merged. inline void ClobberMemory() { asm volatile("" : : : "memory"); } @@ -55,7 +60,8 @@ struct Result { double best_nanos_per_op = 0.0; double worst_nanos_per_op = 0.0; - /// Relative dispersion = (worst - best) / median. Above 0.3 means the measurement environment was noisy. + /// Relative dispersion = (worst - best) / median. Above 0.3 means the measurement environment was + /// noisy. [[nodiscard]] double Spread() const { return median_nanos_per_op > 0.0 ? (worst_nanos_per_op - best_nanos_per_op) / median_nanos_per_op : 0.0; @@ -76,7 +82,8 @@ struct Result { /// Configuration of one benchmark run. struct Config { std::uint32_t warmup_rounds = 3; ///< Number of warmup rounds; results are not counted. - std::uint32_t measure_rounds = 9; ///< Number of formal rounds; the median is taken (an odd number makes taking the middle easy). + /// Number of formal rounds; the median is taken (an odd number makes taking the middle easy). + std::uint32_t measure_rounds = 9; std::uint64_t ops_per_round = 0; ///< Operations per round; decided by each benchmark itself. std::uint64_t bytes_per_op = 0; ///< Bytes per operation, used to convert to Gbps. }; @@ -84,9 +91,11 @@ struct Config { /// The benchmark registry and executor. class Runner { public: - /// Signature of the function under test: given the number of operations to execute this round, returns the number actually executed. + /// Signature of the function under test: given the number of operations to execute this round, + /// returns the number actually executed. /// - /// Returning a value rather than always using the argument lets benchmarks like "stop when the queue is full" also report honestly. + /// Returning a value rather than always using the argument lets benchmarks like "stop when the + /// queue is full" also report honestly. using Body = std::function; /// Registers one benchmark. `group` is used for grouping in the summary table. @@ -99,7 +108,7 @@ class Runner { std::vector results; results.reserve(entries_.size()); for (const Entry& entry : entries_) { - std::fprintf(stderr, " 正在测量 %s / %s ...\n", entry.group.c_str(), entry.name.c_str()); + std::fprintf(stderr, " Measuring %s / %s ...\n", entry.group.c_str(), entry.name.c_str()); results.push_back(RunOne(entry)); } return results; @@ -158,7 +167,8 @@ class Runner { /// Renders the result set as a Markdown table that can be pasted directly into docs/BENCHMARKS.md. void PrintMarkdownReport(const std::vector& results, std::string_view title); -/// Prints the local environment information (CPU, core count, cache line, build configuration); benchmark results only mean something with context. +/// Prints the local environment information (CPU, core count, cache line, build configuration); +/// benchmark results only mean something with context. void PrintEnvironment(); } // namespace tetherkitnext::bench diff --git a/cmake/CompilerWarnings.cmake b/cmake/CompilerWarnings.cmake index b5a1bd4..40bc743 100644 --- a/cmake/CompilerWarnings.cmake +++ b/cmake/CompilerWarnings.cmake @@ -1,7 +1,7 @@ -# CompilerWarnings.cmake -- centralized management of warning options +# CompilerWarnings.cmake: centralized management of warning options # -# Provides the INTERFACE target tetherkitnext_warnings, which all of this project's own targets link; -# third-party code (third_party/) does not link it, to avoid noise. +# Provides the INTERFACE target tetherkitnext_warnings, which all of this project's own targets +# link; third-party code (third_party/) does not link it, to avoid noise. add_library(tetherkitnext_warnings INTERFACE) @@ -22,10 +22,12 @@ set(_tk_warnings -Wdouble-promotion -Wformat=2 -Wimplicit-fallthrough - # Implicit heap allocation on the data path is a performance killer; let the compiler watch for VLAs. + # Implicit heap allocation on the data path is a performance killer; let the compiler watch for + # VLAs. -Wvla - # Struct padding affects our hand-written wire-format structs and needs a static_assert backstop, - # but -Wpadded is too noisy, so it is not enabled; static_assert(sizeof(...)) checks are used instead. + # Struct padding affects our hand-written wire-format structs and needs a static_assert + # backstop, but -Wpadded is too noisy, so it is not enabled; static_assert(sizeof(...)) checks + # are used instead. ) target_compile_options(tetherkitnext_warnings INTERFACE ${_tk_warnings}) diff --git a/cmake/FindLibUSB.cmake b/cmake/FindLibUSB.cmake index abbacf4..9e3d5b6 100644 --- a/cmake/FindLibUSB.cmake +++ b/cmake/FindLibUSB.cmake @@ -1,14 +1,15 @@ -# FindLibUSB.cmake -- locate libusb-1.0 +# FindLibUSB.cmake: locate libusb-1.0 # -# Prefer pkg-config (the libusb installed by Homebrew ships a .pc file, which correctly reports -# the unconventional header directory `include/libusb-1.0`); on failure, fall back to a manual search of common prefixes. +# Prefer pkg-config (the libusb installed by Homebrew ships a .pc file, which correctly reports the +# unconventional header directory `include/libusb-1.0`); on failure, fall back to a manual search of +# common prefixes. # # Outputs: -# LibUSB_FOUND -- whether it was found -# LibUSB_VERSION -- version string -# LibUSB_INCLUDE_DIR -- directory containing libusb.h -# LibUSB_LIBRARY -- path to the library file -# LibUSB::LibUSB -- IMPORTED target that can be linked directly +# LibUSB_FOUND: whether it was found +# LibUSB_VERSION: version string +# LibUSB_INCLUDE_DIR: directory containing libusb.h +# LibUSB_LIBRARY: path to the library file +# LibUSB::LibUSB: IMPORTED target that can be linked directly # LibUSB_ROOT (see scripts/build-libusb.sh) pins a specific build — the # universal, @rpath-named libusb that release builds embed in TetherKitNext.app. @@ -56,7 +57,8 @@ find_library( PATHS /opt/homebrew/opt/libusb/lib /usr/local/opt/libusb/lib /opt/local/lib /usr/local/lib /usr/lib) -# Version: pkg-config is the most reliable; otherwise infer a lower bound from LIBUSB_API_VERSION in the header. +# Version: pkg-config is the most reliable; otherwise infer a lower bound from LIBUSB_API_VERSION in +# the header. if(PC_LIBUSB_VERSION) set(LibUSB_VERSION "${PC_LIBUSB_VERSION}") elseif(LibUSB_INCLUDE_DIR AND EXISTS "${LibUSB_INCLUDE_DIR}/libusb.h") @@ -82,7 +84,8 @@ if(LibUSB_FOUND AND NOT TARGET LibUSB::LibUSB) LibUSB::LibUSB PROPERTIES IMPORTED_LOCATION "${LibUSB_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${LibUSB_INCLUDE_DIR}") - # libusb's darwin backend needs IOKit and CoreFoundation, plus Security (IOUSBHost permission checks). + # libusb's darwin backend needs IOKit and CoreFoundation, plus Security (IOUSBHost permission + # checks). find_library(IOKIT_FRAMEWORK IOKit REQUIRED) find_library(COREFOUNDATION_FRAMEWORK CoreFoundation REQUIRED) find_library(SECURITY_FRAMEWORK Security REQUIRED) diff --git a/cmake/Optimizations.cmake b/cmake/Optimizations.cmake index 99e9f9e..98de678 100644 --- a/cmake/Optimizations.cmake +++ b/cmake/Optimizations.cmake @@ -1,14 +1,15 @@ -# Optimizations.cmake -- data-path optimization options +# Optimizations.cmake: data-path optimization options # # Provides the INTERFACE target tetherkitnext_optimizations. # # Design trade-offs: -# * -march/-mcpu are not added by default: the Apple Silicon baseline (armv8.4-a for M1) already contains -# everything we need (LSE atomics, NEON); an additional -mcpu=native gains little but ties the artifact -# to a specific chip generation. Turn it on when needed with -DTETHERKITNEXT_NATIVE_ARCH=ON. -# * -O3 is not used: this project's hot path is dominated by memcpy and system calls, for which -O3's aggressive loop unrolling and -# vectorization bring almost no benefit while increasing code size and worsening I-cache hit rate. -O2 (the RelWithDebInfo default) -# is the better choice. +# * -march/-mcpu are not added by default: the Apple Silicon baseline (armv8.4-a for M1) already +# contains everything we need (LSE atomics, NEON); an additional -mcpu=native gains little but +# ties the artifact to a specific chip generation. Turn it on when needed with +# -DTETHERKITNEXT_NATIVE_ARCH=ON. +# * -O3 is not used: this project's hot path is dominated by memcpy and system calls, for which +# -O3's aggressive loop unrolling and vectorization bring almost no benefit while increasing code +# size and worsening I-cache hit rate. -O2 (the RelWithDebInfo default) is the better choice. # * -fno-plt / -fvisibility=hidden reduce indirect jumps and symbol table size. add_library(tetherkitnext_optimizations INTERFACE) @@ -16,11 +17,13 @@ add_library(tetherkitnext_optimizations INTERFACE) target_compile_options( tetherkitnext_optimizations INTERFACE - # Internal symbols are hidden by default: this project does not export a stable ABI, which lets the optimizer inline more freely. + # Internal symbols are hidden by default: this project does not export a stable ABI, which lets + # the optimizer inline more freely. -fvisibility=hidden -fvisibility-inlines-hidden - # Strict aliasing is dangerous for our hand-written wire-format parsing (lots of reinterpret_cast), so it is turned off. - # The cost is small: the real bottleneck on the hot path is system calls, not alias analysis. + # Strict aliasing is dangerous for our hand-written wire-format parsing (lots of + # reinterpret_cast), so it is turned off. The cost is small: the real bottleneck on the hot path + # is system calls, not alias analysis. -fno-strict-aliasing) if(TETHERKITNEXT_NATIVE_ARCH) @@ -29,7 +32,7 @@ if(TETHERKITNEXT_NATIVE_ARCH) if(TK_HAS_MCPU_NATIVE) target_compile_options(tetherkitnext_optimizations INTERFACE -mcpu=native) else() - message(WARNING "编译器不支持 -mcpu=native,已跳过本机微架构优化。") + message(WARNING "The compiler does not support -mcpu=native; skipping native tuning.") endif() endif() @@ -40,6 +43,6 @@ if(TETHERKITNEXT_ENABLE_LTO) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON PARENT_SCOPE) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO ON PARENT_SCOPE) else() - message(WARNING "不支持 LTO,已跳过:${TK_IPO_MSG}") + message(WARNING "LTO is not supported, skipping: ${TK_IPO_MSG}") endif() endif() diff --git a/cmake/Sanitizers.cmake b/cmake/Sanitizers.cmake index 9b5f9fe..cd9addf 100644 --- a/cmake/Sanitizers.cmake +++ b/cmake/Sanitizers.cmake @@ -1,18 +1,20 @@ -# Sanitizers.cmake -- sanitizer switches +# Sanitizers.cmake: sanitizer switches # # Provides the INTERFACE target tetherkitnext_sanitizers. # # Notes: # * ASan and TSan are mutually exclusive and cannot be enabled together. -# * TSan is this project's most important sanitizer -- the memory-ordering correctness among the lock-free SPSC rings, the libusb event thread and -# the BPF read/write threads can only be verified with it. It is recommended to run at least once: -# cmake -B build-tsan -DTETHERKITNEXT_ENABLE_TSAN=ON && ctest --test-dir build-tsan -# * Sanitizers significantly reduce throughput; benchmarks must be run on a Release build without sanitizers. +# * TSan is this project's most important sanitizer; the memory-ordering correctness among the +# lock-free SPSC rings, the libusb event thread and the BPF read/write threads can only be +# verified with it. It is recommended to run at least once: cmake -B build-tsan +# -DTETHERKITNEXT_ENABLE_TSAN=ON && ctest --test-dir build-tsan +# * Sanitizers significantly reduce throughput; benchmarks must be run on a Release build without +# sanitizers. add_library(tetherkitnext_sanitizers INTERFACE) if(TETHERKITNEXT_ENABLE_ASAN AND TETHERKITNEXT_ENABLE_TSAN) - message(FATAL_ERROR "AddressSanitizer 与 ThreadSanitizer 不能同时启用。") + message(FATAL_ERROR "AddressSanitizer and ThreadSanitizer cannot be enabled together.") endif() set(_tk_san_list "") @@ -27,8 +29,8 @@ endif() if(TETHERKITNEXT_ENABLE_UBSAN) list(APPEND _tk_san_list undefined) - # Would hand-written wire-format structs cause unaligned accesses? No -- we read everything byte by byte, - # so the alignment check stays on, to catch real bugs. + # Would hand-written wire-format structs cause unaligned accesses? No; we read everything byte by + # byte, so the alignment check stays on, to catch real bugs. endif() if(_tk_san_list) @@ -37,7 +39,7 @@ if(_tk_san_list) target_compile_options(tetherkitnext_sanitizers INTERFACE -fsanitize=${_tk_san_flags} -fno-omit-frame-pointer -g) target_link_options(tetherkitnext_sanitizers INTERFACE -fsanitize=${_tk_san_flags}) - message(STATUS "已启用消毒器: ${_tk_san_flags}") + message(STATUS "Sanitizers enabled: ${_tk_san_flags}") else() set(TETHERKITNEXT_SANITIZER_SUMMARY "none") endif() diff --git a/cmake/tetherkitnext_exports.txt b/cmake/tetherkitnext_exports.txt index 45ad191..f830587 100644 --- a/cmake/tetherkitnext_exports.txt +++ b/cmake/tetherkitnext_exports.txt @@ -1,10 +1,11 @@ # Export symbol allowlist for libtetherkitnext.dylib (-exported_symbols_list). # -# Only the C ABI is exported. C++ symbols (mangled names of tetherkitnext::*, the static copy of libusb) are all -# hidden, for two reasons: -# 1. The host process may already have another libusb loaded, and exporting identically named symbols would let the two pollute each other; -# 2. C++ symbols carry an ABI fingerprint; once leaked they amount to a promise of stability, and we only want to -# promise the tetherkitnext_c.h layer. +# Only the C ABI is exported. C++ symbols (mangled names of tetherkitnext::*, the static copy of +# libusb) are all hidden, for two reasons: +# 1. The host process may already have another libusb loaded, and exporting identically named +# symbols would let the two pollute each other; +# 2. C++ symbols carry an ABI fingerprint; once leaked they amount to a promise of stability, and +# we only want to promise the tetherkitnext_c.h layer. # # The leading underscore is Mach-O's C symbol naming convention (C's tk_version -> _tk_version). _tk_* diff --git a/docs/ADVANCED-TOOLS.md b/docs/ADVANCED-TOOLS.md new file mode 100644 index 0000000..0f7effb --- /dev/null +++ b/docs/ADVANCED-TOOLS.md @@ -0,0 +1,105 @@ +# Advanced tools: roadmap + +Goal: make TetherKitNext the one place for networking work on a Mac, without +changing what everyday users see. Everything here lives in the opt-in +**Advanced** sidebar section (Settings › General › *Show advanced tools*, +off by default). + +## Ground rules + +1. **Opt-in and out of the way.** Advanced pages are only listed when the + toggle is on (`Pane.isAdvanced`, `Pane.sidebarSections`). The tethering + flow (Overview, Device, Network, Activity) never changes because of them. +2. **Unprivileged first.** A tool that can run as the user runs in the app, + not in the root daemon. The daemon's XPC surface grows only for things that + truly need root, behind the same Team-ID pinning and authorization or + Touch ID check as connecting. +3. **No surprise traffic.** Tools that send packets to other hosts (speed + tests, scans) start only on an explicit click, show what they will contact, + and default to the local network or Apple's own endpoints. +4. **Local Network privacy.** From macOS 15, talking to devices on the LAN + (Bonjour, unicast or broadcast to local addresses) triggers the + Local Network permission. The app needs an `NSLocalNetworkUsageDescription` + in `App-Info.plist` *before* the first such tool ships; without it access is + denied silently and the app never appears in System Settings + ([TN3179](https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy)). +5. **Same localization rules** as the rest of the app: every string goes + through `L10nKey` in all six languages. + +## Shipped + +| Tool | What it does | How | +|---|---|---| +| **Interfaces** (this change) | Every interface with state, MAC, IPv4/IPv6 addresses and live ↓/↑ rate, updated every second. Inactive interfaces are hidden unless you ask for them. | `getifaddrs(3)` for flags and addresses. 64-bit byte counters come from the `NET_RT_IFLIST2` sysctl (`if_data64`; `getifaddrs`' own counters are 32-bit and wrap at 4 GiB). The rate logic (`InterfaceRateTracker`) is unit-tested, including the reset when a `feth` pair is recreated. | + +## Next, in recommended order + +### 1. Speed test per interface +macOS has a built-in tester: `/usr/bin/networkQuality` (macOS 12+). `-I ` +binds the test to one interface and `-c` prints JSON (download/upload +throughput, responsiveness in RPM, `interface_name`). Run it unprivileged from +the app on a chosen row of the Interfaces page, so you can compare the phone +tether against Wi-Fi or Ethernet. It needs no third-party server and no +bundled dependency. Show it as one row of results per interface with a +history of past runs. + +### 2. Combined throughput, and what "merging interfaces" can honestly mean +- **Combined view (cheap):** the Interfaces page already has every rate; add + a total and a stacked chart of interfaces carrying traffic. +- **Aggregate capacity test:** run the speed test on two interfaces at the + same time to show what the links can carry together. +- **Real bonding of one connection across two uplinks isn't possible on the + Mac alone.** macOS routes each flow out of one interface; Network Service + Order only picks a primary and fails over. Products that do bond (Speedify, + for example) tunnel every packet to their own server and reassemble it + there. The options, in increasing cost: + 1. per-connection load spreading (new connections alternate between + interfaces using scoped routes / `IP_BOUND_IF`); helps parallel + downloads, not a single stream; + 2. Multipath TCP via Network framework (`multipathServiceType`), only + where the server supports MPTCP; + 3. `ifconfig bond` (802.3ad), Ethernet only, needs an LACP switch; + 4. a bonding tunnel, which means running a server: a separate product. + + Recommendation: ship the combined view and the aggregate test, and offer a + "prefer this interface" control (we already reorder `ServiceOrder` for + "route all traffic"). Don't advertise bonding. + +### 3. LAN device discovery ("IP discovery") +- Neighbour table (ARP / NDP) from the routing sysctl: who has talked to this + Mac recently, with MAC addresses and an offline OUI → vendor table. +- Bonjour browsing (`NWBrowser`) for named devices and services. +- Optional active sweep of the local subnet (ICMP / TCP probes), rate-limited + and only after a click. +- Needs the Local Network permission (rule 4). + +### 4. Port check / port scan +- TCP connect checks (`NWConnection`) to one host and a port list (common + services or a range), with concurrency and timeout limits. Unprivileged. + A SYN scan would need root and raw BPF; not planned. +- Defaults to private addresses. Scanning other networks asks for + confirmation, with a note on acceptable use. + +### 5. Everyday diagnostics +Ping, traceroute and DNS lookup with an interface picker (`IP_BOUND_IF`), plus +the route table and the current primary service / DNS resolvers. These answer +"which link is my traffic using?" next to the tether controls. + +### 6. Packet capture of the tether link (privileged) +The daemon already owns a BPF descriptor on the `feth` pair. Exporting a +time-limited `.pcapng` of the tether link would be a privileged XPC call +behind the existing authorization. Useful for debugging phones, but it is the +first tool that grows the root surface, so it comes last and gets its own +security review. + +### Considered, not planned +- **Public IP / egress check per interface:** needs a third-party echo + service. Possible later as an opt-in with the provider named. +- **Wi-Fi scanning (CoreWLAN):** SSIDs and BSSIDs need the Location permission + since macOS 14. It's a different domain from tethering and well covered by + Apple's Wireless Diagnostics. + +## Sources +- [`networkQuality` usage (`-I`, `-c`)](https://www.den.dev/blog/speed-test-macos-networkquality/), [NetBeez overview](https://netbeez.net/blog/measure-network-quality-on-macos/) +- [Local network privacy on Sequoia/Tahoe (Apple forums)](https://developer.apple.com/forums/thread/814226), [TN3179](https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy) +- [Speedify: why macOS can't combine connections natively](https://speedify.com/blog/how-to/combine-connections-on-macos/) diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index ee03e97..ffbf48b 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -1,8 +1,8 @@ # TetherKitNext Performance Benchmarks -Generated by `tetherkitnext_bench` — TetherKitNext 0.1.2 (C++23, macOS 13.3+) +The tables were produced by `tetherkitnext_bench` at version 0.1.2 on an Apple M5 under macOS 26.5.1. The rest of the file is hand-written analysis. -> To regenerate: `./build-rel/bin/tetherkitnext_bench > docs/BENCHMARKS.md` +> To refresh the tables, run `./build-rel/bin/tetherkitnext_bench` and paste its tables into this file. > Always run on a **Release build without sanitizers**, otherwise the numbers have no reference value. ## Measurement Environment @@ -261,40 +261,17 @@ Every frame is counted as both received and errored while all replies succeed no - **Microbenchmark numbers represent hot L1-cache upper bounds.** Real RX buffers written by USB DMA are cold in CPU cache; streaming `memcpy` of 1514 bytes takes 67–71 ns vs. ~33 ns in L1. Treat CPU microbenchmark figures in these tables as **lower bounds** on latency. The link-layer benchmarks (`BPF` / `feth`) are unaffected because they measure real kernel system calls. - **The historical anomaly where "RNDIS encoding was faster than bare `memcpy`" is gone.** An earlier hardware run recorded ~14 ns/frame for 1514B encoding vs. ~25 ns for `memcpy`. Re-measured on Apple M5, encoding takes 35.1 ns vs. 32.9 ns for `memcpy` — slightly slower than `memcpy`, matching expectations (`memcpy` plus a 44-byte header). - **High-spread benchmarks** (`SPSC cross-thread`, `FrameRing single-thread 64B`, `feth round-trip latency`) should be evaluated by their **Best ns/op** column because spinning threads can be scheduled across different combinations of Performance and Efficiency cores (4 P + 6 E), and macOS does not support strict core pinning (`thread_affinity_policy` is advisory/ignored on Apple Silicon). -- **Link-layer benchmarks require root.** Running without root skips the group with an explicit note rather than silently omitting it. Re-run with `sudo ./build/bin/tetherkitnext_bench > docs/BENCHMARKS.md`. Note that the fixture must be torn down explicitly before `main` returns (`ShutdownNetBenchmarks`) — leaving teardown to static destructors triggers an abort (exit code 134) because the logging mutex has already been destroyed. +- **Link-layer benchmarks require root.** Running without root skips the group with an explicit note rather than silently omitting it. Re-run with `sudo ./build/bin/tetherkitnext_bench` and paste its tables. Note that the fixture must be torn down explicitly before `main` returns (`ShutdownNetBenchmarks`) — leaving teardown to static destructors triggers an abort (exit code 134) because the logging mutex has already been destroyed. - **Compiler barrier lesson (`ClobberMemory`)**: the statistics counter benchmark initially reported **0.00 ns/op** because back-to-back `memory_order_relaxed` read-modify-writes can be coalesced by the compiler (`N` increments of `+1` folded into a single `+N`). Adding `ClobberMemory` revealed the true 0.34 ns/op cost. --- ## Completed and Remaining Benchmark Items -The items originally tracked here have been **completed** (see sections above): - -- [x] BPF write cost (requires root) — 2181 ns single-frame / 805 ns batched (see Findings #2 and #3); -- [x] BPF batched read per-frame cost — reported as combined `feth` write+read round-trip at 1309 ns/frame (subtract batched write cost at the same batch size for pure read cost); -- [x] `feth` data-path round-trip latency — 24.5 µs (see Finding #4); -- [x] End-to-end real-device throughput — RX 324–327 Mbps / TX 234–302 Mbps (see End-to-End Real-Device Measurements); -- [x] Root cause and fix of TX frame drops — TetherKitNext TX frame drops reduced from 1889 to 0 (see Root Cause and Fix of TX Frame Drops); -- [x] Graceful shutdown after adding TX backpressure waiting (`WaitForSendCapacity`) — verified in a real interactive terminal (`sudo build/bin/tetherkitnext-cli` followed by `Ctrl-C` logs clean shutdown and leaves zero residual `feth` interfaces). - -Open items for future investigation: - -- [ ] **Bimodal TCP TX throughput** (~240 Mbps vs. ~300 Mbps stable states, both with zero retransmissions) — likely tied to USB microframe scheduling or device-side aggregation timing. -- [ ] **Bidirectional RTT inflation** (0.4 ms idle → 16.6 ms under full RX load) — no longer collapses throughput after fixing TX drops, but impacts latency-sensitive workloads. -- [ ] **Survey of RNDIS parameters across Android OEM kernels** — currently sampled on vivo (`10 packets / 15800 bytes`) and mainline Linux gadget (`1 packet / 1580 bytes`). +The completed and open verification items are tracked in [AGENTS.md section 6.3](../AGENTS.md#63-completed--open-verification-items). --- -## ⚠️ Benchmark Environment Pitfall: Privilege Escalation Swallows SIGTERM - -The `osascript ... with administrator privileges` privilege-escalation chain **swallows inter-process `SIGTERM` delivery**: `kill -TERM $pid` returns 0, the target process's `blocked` and `pending` signal masks remain 0, and `sigaction` shows the handler installed, yet the signal never arrives and the process can only be terminated with `kill -9`. - -Verified with a standalone 15-line C reproduction independent of TetherKitNext: - -| Execution Environment | Receives `SIGTERM`? | -|---|---| -| Standard interactive shell | ✅ | -| Standard `osascript do shell script` | ✅ | -| `osascript ... with administrator privileges` | ❌ | +## Benchmark Environment Pitfall: SIGTERM -**Consequence: never use `osascript ... with administrator privileges` to test graceful shutdown.** It produces a false "shutdown hang" (`Killed: 9`) unrelated to the application code. Always verify graceful shutdown in a real interactive terminal via `sudo build/bin/tetherkitnext-cli` followed by `Ctrl-C`. +`osascript ... with administrator privileges` swallows `SIGTERM`, so test graceful shutdown in a real interactive terminal. See AGENTS.md [pitfall 15](../AGENTS.md#7-known-pitfalls-and-safeguards-do-not-repeat). diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 92f220b..0351354 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -83,6 +83,9 @@ tk_usb ← common, rndis libusb wrapper (rndis used only for protocol con tk_core ← all of above Data-path bridge + runtime orchestration ↑ tetherkitnext ← core CLI executable +tk_capi ← core C ABI, packaged as the shared library libtetherkitnext + ↑ +gui/ (Swift) ← libtetherkitnext App and privileged helper (only `_tk_*` symbols are exported) ``` **Keeping `tk_rndis` free of I/O is a deliberate architectural constraint**: it allows the entire RNDIS implementation (including the state machine) to be thoroughly unit-tested on a machine with neither a USB device nor root privileges. For this reason, the `ControlChannel` interface lives in the `rndis` layer (describing RNDIS protocol semantics rather than USB specifics) and is implemented by `tk_usb`. @@ -277,17 +280,4 @@ In short: **functional ABIs have remained stable for 15+ years and are guarded b ## 11. Coding Conventions -| Category | Convention | Example | -|---|---|---| -| Namespace | `lower_case` | `tetherkitnext::rndis` | -| Types | `CamelCase` | `PacketMessageWriter` | -| Functions & Methods (including accessors) | `CamelCase` | `MaxFrameBytes()` | -| Local variables & parameters | `lower_case` | `frame_length` | -| Private member variables | `lower_case_` | `bulk_in_endpoint_` | -| Constants / Enumerator values | `k` + `CamelCase` | `kPacketMsgHeaderBytes` | -| Files | `snake_case`, `.h` / `.cc` | `packet_codec.h` | -| Message IDs | `k` + module prefix + `CamelCase` | `kNetBpfBindFailed`, `kCliUnknownOption` | - -Accessors also use `CamelCase` (rather than STL-style `lower_case`) so that `readability-identifier-naming` can enforce naming mechanically without manual exceptions. - -`.clang-tidy` disables specific checks unsuitable for low-level systems code, with documented rationale for each. In particular, `performance-enum-size` is disabled because protocol enum underlying types **must** match exact wire field widths (LE32 in RNDIS). +See [AGENTS.md section 4](../AGENTS.md#4-coding-conventions-enforced-by-clang-tidy). diff --git a/docs/GUI-ARCHITECTURE.md b/docs/GUI-ARCHITECTURE.md index 6601894..7c1d8b1 100644 --- a/docs/GUI-ARCHITECTURE.md +++ b/docs/GUI-ARCHITECTURE.md @@ -2,25 +2,23 @@ This document records **what the TetherKitNext GUI implements, why it is structured that way, and which invariants must not be broken**. -Companion reading: [GUI-SPIKE.md](GUI-SPIKE.md) documents the initial feasibility spike (especially the three approaches that were ruled out); this document describes the production architecture and its constraints. **Read both before modifying GUI or helper code.** +Companion reading: [MACOS-NETWORKING-NOTES.md](MACOS-NETWORKING-NOTES.md) explains why `feth` needs `IPConfiguration` and a persistent `SCNetworkService` (no IOKit node, SCDynamicStore injection ignored) and records the commands that verify it. **Read both before modifying GUI, helper or network configuration code.** -## 0. TetherKitNext Changes (Read First — Supersedes Legacy Install/Trust Sections Below) +## 0. Changes from the Upstream Design (Read First) -Sections 1–6 below preserve the historical design record from upstream. The following parts have changed in TetherKitNext: +This section lists changes from the upstream design; the other sections describe the current app unless this section says otherwise. | Area | Upstream | Now | |---|---|---| | Daemon install | `AuthorizationExecuteWithPrivileges` (via `dlsym`) runs the helper with `--install`, which calls `setuid(0)` and runs `install-helper.sh` to copy files into `/Library/PrivilegedHelperTools` + `/Library/LaunchDaemons` | `SMAppService.daemon(plistName: "com.tetherkitnext.helperd.plist")`. `launchd` runs `Contents/MacOS/tetherkitnext-helper` **in place** from the signed bundle; the user approves it once in Login Items. No files are copied; `InstallerMode.swift` and `install-helper.sh` are gone | -| Label / Mach service | `com.tetherkitnext.helper` | `com.tetherkitnext.helperd` (distinct label so it never collides with a still-loaded legacy job). The new daemon boots out and deletes the legacy install on first start (`LegacyHelper`) | +| Label / Mach service | `com.tetherkit.helper` | `com.tetherkitnext.helperd` (distinct label so it never collides with a still-loaded legacy job). The new daemon boots out and deletes the legacy install on first start (`LegacyHelper`) | | Who may connect | Anyone; security relies only on per-call admin authorization | Team-signed builds: `setCodeSigningRequirement` on both ends (`CodeSigning.swift`, Team ID read from the running binary). Per-call authorization is kept as a second layer. Ad-hoc builds fall back to the authorization-only model | | Protocol revision | 3 | 5 (`SMAppService` daemon + `setCommandLineToolInstalled` + Touch ID empty-authorization support) | | Bundle layout | `Contents/Library/HelperTools/` payload | `MacOS/{TetherKitNext,tetherkitnext-cli,tetherkitnext-helper}`, `Frameworks/{libtetherkitnext.0,libusb-1.0.0}.dylib`, `Library/LaunchDaemons/com.tetherkitnext.helperd.plist`, `Resources/Licenses/` | -| CLI on PATH | Homebrew formula | Daemon-managed symlink `/usr/local/bin/tetherkitnext-cli` → the CLI inside its own bundle (`CommandLineToolLink`) | +| CLI on PATH | Installed separately | Daemon-managed symlink `/usr/local/bin/tetherkitnext-cli` → the CLI inside its own bundle (`CommandLineToolLink`) | | Architectures | arm64, Homebrew libusb | Universal (`arm64` + `x86_64`); libusb 1.0.30 built from a hash-pinned tarball (`scripts/build-libusb.sh`) | -| Swift | tools 5.9, Swift 5 mode | tools 6.2, Swift 6 language mode | | Layout | Single dashboard under a 700 pt height budget | `NavigationSplitView`: Overview / Device / Network / Activity / Settings; Connect button in toolbar | | Dock icon | Activation policy set in SwiftUI `onDisappear` (not reliably called when a `Window` scene closes) | `AppDelegate` derives it from `NSWindow` notifications | -| Finder alias | Created on launch (for Homebrew Cellar installs) | Removed | Constraints that still hold: UTF-8 boundary truncation in the C ABI, enum-order `static_assert`s, `.id(model.languageRevision)` for live language switching, and never blocking an XPC queue. @@ -73,8 +71,10 @@ gui/ │ ├── TetherKitNextIPC/ Shared between App & helper: XPC protocol, models, auth, i18n │ ├── TetherKitNextCore/ Swift wrapper over the C ABI │ ├── TetherKitNextHelper/ Privileged helper daemon -│ └── TetherKitNextApp/ SwiftUI application -├── Tests/TetherKitNextIPCTests/ Auth token lifetime, code signing, and i18n placeholder tests +│ ├── TetherKitNextUIModel/ Testable UI logic: sidebar panes, interface traffic sampling +│ └── TetherKitNextApp/ SwiftUI application (main window owned by MainWindowController) +├── Tests/TetherKitNextIPCTests/ Localization, helper constants, authorization, code signing, rate formatting +├── Tests/TetherKitNextUIModelTests/ Panes, interface traffic, link assessment, auto-connect policy, interface style, session failure ├── Resources/ App-Info.plist, LaunchDaemon plist, AppIcon └── Scripts/ GUI packaging and helper uninstallation scripts ``` @@ -159,6 +159,10 @@ Therefore, the App caches `AuthorizationToken` across operations for up to 5 min - **Throughput calculations divide byte deltas by the library's monotonic timestamp delta**, not the nominal UI timer interval. - **Fixed-size C `char` arrays import into Swift as tuples**; always decode them via `CInterop.swift` by scanning up to the first `NUL` or the buffer bound rather than `String(cString:)`. - **Adaptive polling**: 500 ms when a session is active/starting/stopping or the main window is visible; 2 seconds when idle in the background. +- **The main window is an AppKit `NSWindow` (`MainWindowController`), not a SwiftUI `Window` scene.** With a `MenuBarExtra` present, SwiftUI recreated a closed `Window` scene whenever the windowless app was activated (clicking the menu bar item), so the old code had to dismiss "unexpected" windows after the fact. The only SwiftUI scene is now the `MenuBarExtra`, and app-wide `.commands` attach to it. Rules: create and present the window from `AppDelegate.applicationDidFinishLaunching`; reopen through `MainWindowController.shared?.present()` (menu bar panel, `applicationShouldHandleReopen`); closing only orders the window out (`isReleasedWhenClosed = false`); File ▸ Close (⌘W) is our own `CommandGroup` item, since SwiftUI provides none without a window scene; the `NSHostingController` uses `sceneBridgingOptions = [.toolbars, .title]` so `.toolbar` / `.navigationTitle` keep working, and `sizingOptions = [.minSize]` so pages with different intrinsic heights never resize the window. +- **Persist UI state with `@AppStorage`, not `@SceneStorage`.** The main window has no SwiftUI scene to store into. The sidebar selection is stored as `Pane.rawValue` and read back through `Pane.resolveStored`, which drops values for hidden advanced pages. +- **Local-link devices** (drones, controllers, goggles, gadget-mode boards): the overview's `LinkKindCard` renders `AppModel.linkAssessment`, which is recomputed every poll and never stored; addresses offered for such devices are session-only. Auto-configuration after Connect no longer raises alerts for DHCP timeouts. See [LOCAL-DEVICES.md](LOCAL-DEVICES.md). +- **Advanced tools are opt-in** (`PreferenceKey.advancedToolsEnabled`, default off). Pages with `Pane.isAdvanced` appear in a separate "Advanced" sidebar section; see [ADVANCED-TOOLS.md](ADVANCED-TOOLS.md). ### 4.7b Interface Localization @@ -176,21 +180,31 @@ Switching languages in `AppModel.applyLanguage` updates three places atomically: - **Always copy dylibs with `cp -a` rather than `install`** to preserve versioned symlinks (`libtetherkitnext.dylib` → `libtetherkitnext.0.dylib`). - **Always re-sign binaries after modifying Mach-O headers with `install_name_tool`**, otherwise macOS on Apple Silicon terminates the process with `Killed: 9` (`SIGKILL` due to invalid code signature). +- **The app binary must be stamped with SDK ≥ 26 (`LC_BUILD_VERSION` `sdk`).** macOS 26+ picks the window chrome from that field, and a SwiftPM link can stamp the deployment target instead. `build-gui.sh` rewrites only `sdk` with `vtool` (using `xcrun --show-sdk-version`; `minos` stays 14.0) before `lipo`, and fails the build if the signed binary is still below 26. `swift run` binaries skip this and may show legacy chrome; that is expected. See [MACOS-27.md](MACOS-27.md). - **Bundle `libusb-1.0.0.dylib` inside `Contents/Frameworks/`** and sign it with the same identity so Hardened Runtime library validation succeeds. - **Strip build-directory `@rpath` entries** from release binaries so dyld always loads the bundled Frameworks rather than development paths on the build machine. -### 4.9 In-App Privileged Helper Installation (`SMAppService` / Historical AEWP) +### 4.9 In-App Privileged Helper Installation (`SMAppService`) -> **Current (TetherKitNext 1.0+)**: `HelperInstaller.swift` manages the helper daemon via `SMAppService.daemon(plistName: "com.tetherkitnext.helperd.plist")` (see Section 0). Historical details below describe the earlier AEWP-based installer for reference. +`HelperInstaller.swift` registers, restarts and removes the daemon with `SMAppService.daemon(plistName: "com.tetherkitnext.helperd.plist")` (see Section 0). Restart through `HelperInstaller.reregister()`, which waits for `launchd` to finish the transition (AGENTS.md pitfall 27). The installer based on `AuthorizationExecuteWithPrivileges` and a setuid trampoline was removed in 1.0. -In the pre-1.0 AEWP design: -- `AuthorizationExecuteWithPrivileges` (`dlsym`-resolved from `Security.framework`) executed a tiny C trampoline (`install-trampoline.c`) that promoted `euid=0` to real `uid/gid=0` via `setuid(0)` / `setgid(0)`, redirected `stderr` into `stdout` (`dup2`), and `exec`'d `install-helper.sh`. -- Success was verified not via process exit code (which AEWP does not expose), but by reading `stdout` to `EOF` and then performing an XPC round-trip to confirm a matching helper version was reachable. -- Uninstallation ran `--uninstall` → `uninstall-helper.sh` and confirmed XPC could no longer connect. +### 4.9b Layouts and auto-connect (`SimpleView.swift`, `LayoutViews.swift`, `AutoConnectPolicy.swift`) -### 4.10 Update Checker (`UpdateChecker.swift`) +- `AppModel.interfaceStyle` (`InterfaceStylePreference`, UIModel) selects the window content: setup assistant → (new installs) `LayoutChooserView` with Simple preselected → `SimpleView` or the sidebar layout. Updated installs are migrated to `.full` and get `LayoutAnnouncementSheet` once. +- `LayoutPreview` draws both layouts with shapes (follows dark mode and accent color, no per-language screenshots). +- `MainWindowController.applyLayout(compact:animate:)` makes the simple window fixed-size and restores the detailed frame (persisted as `MainWindowFullFrame`). +- Auto-connect: `NetworkPathWatcher` (NWPathMonitor, Wi-Fi/Ethernet only, `feth*` excluded) feeds `AutoConnectPolicy`, evaluated after every poll. See AGENTS.md pitfall 49. -`UpdateChecker.swift` queries GitHub's `releases/latest` API and performs semantic version comparison against `CFBundleShortVersionString` in `Info.plist` (single-sourced from `CMakeLists.txt`). It is **intentionally check-only** (it opens the release page rather than self-replacing the `.app` bundle in place): +### 4.10 Updates (`SoftwareUpdater.swift`, `UpdateChecker.swift`) + +**Self-update (Sparkle 2.10.1).** `SoftwareUpdater` wraps `SPUStandardUpdaterController` and is active only when Info.plist has `SUFeedURL` and `SUPublicEDKey`. `build-gui.sh` adds both when `TETHERKITNEXT_SPARKLE_PUBLIC_KEY` is set (the release workflow, from the `SPARKLE_ED_PUBLIC_KEY` repository variable). The feed is `releases/latest/download/appcast.xml`, written by `scripts/make-appcast.py` for stable releases only. +- Always user-confirmed: `SUAllowsAutomaticUpdates` / `SUAutomaticallyUpdate` are off; scheduled checks show Sparkle's dialog. The Settings toggle drives `automaticallyChecksForUpdates`. +- Trust: EdDSA signature checked before extraction (`SUVerifyUpdateBeforeExtraction`), plus Sparkle's same-Team-ID code-signing check. The release job runs `scripts/verify-sparkle-signature.swift` with the key embedded in the built app, so a secret/variable mismatch fails the release instead of every user's update. +- `CFBundleVersion` is the release workflow's run number (Sparkle compares it). Never build a release from another workflow, whose run numbers are unrelated. +- The daemon: `updaterWillRelaunchApplication` sets `restartHelperAfterUpdate`; after relaunch `AppModel.restartHelperAfterUpdateIfNeeded()` restarts it once its build differs and no session is running. +- Packaging: `Sparkle.framework` is copied with `ditto` from `gui/.build/artifacts` and re-signed inside-out (Installer.xpc, Downloader.xpc with `--preserve-metadata=entitlements`, Autoupdate, Updater.app, the framework) before the app. + +**Check-only fallback.** Builds without the key (local, ad-hoc, CI) use `UpdateChecker.swift`, which queries GitHub's `releases/latest` API and performs semantic version comparison against `CFBundleShortVersionString` in `Info.plist` (single-sourced from `CMakeLists.txt`), opening the release page rather than replacing the app: - **Two entry points**: manual "Check for Updates…" in the application menu (presents a result dialog with the release page link), and an automatic background check at most once per 24 hours that quietly surfaces a non-intrusive badge when a newer release is available. - **Privacy**: only queries the public GitHub Releases API (`https://api.github.com/repos/AA-EION/TetherKitNext/releases/latest`) and fails silently when offline. Can be disabled completely via: @@ -217,11 +231,10 @@ In the pre-1.0 AEWP design: | Orphan `feth` interface cleanup | `tk_cleanup_orphan_interfaces` | | Privileged helper daemon (`SMAppService`) + Team ID & authorization checks | `gui/Sources/TetherKitNextHelper` | | In-app helper registration / update / uninstallation | `gui/Sources/TetherKitNextApp/HelperInstaller.swift` | -| Update checker (check-only, daily auto-check + manual menu item) | `gui/Sources/TetherKitNextApp/UpdateChecker.swift` | -| Finder alias / `/Applications` placement check | `gui/Sources/TetherKitNextApp` | +| Self-update (Sparkle) with a check-only fallback (daily auto-check + manual menu item) | `gui/Sources/TetherKitNextApp/UpdateChecker.swift` | | SwiftUI dashboard (Status, Devices, Network, Throughput, Activity log, Settings) | `gui/Sources/TetherKitNextApp` | | Live menu bar throughput indicator + background (menu-bar-only) mode | `gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift` | -| Bilingual UI (Chinese / English, runtime-switchable across UI, C++ library, and helper) | `gui/Sources/TetherKitNextIPC/Localization.swift`, `tk_set_language` | +| GUI in six languages (en, es, zh, ja, de, ko), C++ library and CLI in English and Chinese; runtime-switchable across UI, library and helper | `gui/Sources/TetherKitNextIPC/Localization.swift`, `tk_set_language` | ### Known Limitations @@ -233,8 +246,8 @@ In the pre-1.0 AEWP design: | **Hotplug** | `Context::SupportsHotplug()` is available in the USB layer, while the GUI currently refreshes device enumeration every 2 seconds. | | **IPv6** | Network configuration in the GUI currently manages IPv4 (`DHCP` / static IPv4); IPv6 link-local works automatically via separate MAC addresses on `feth0` and `feth1`. | | **Single active session** | The helper daemon manages one active RNDIS session at a time. | -| **App icon history** | Originally used the system default icon during initial spike; full `.icns` asset set added in commit #24 and updated for TetherKitNext 1.0 in commit #42. | -| **Supported UI languages** | Chinese (`zh-Hans`) and English (`en`) are compiled into the binary tables (`Localization.swift` and `messages.def`). Adding a third language requires extending the `Language` enum and exhaustive `switch` / X-macro tables. | +| **App icon** | Full `.icns` set (`gui/Resources/AppIcon.icns`). | +| **Supported UI languages** | The GUI has six languages (`en`, `es`, `zh`, `ja`, `de`, `ko`), compiled into `LocalizedStrings.swift` with an exhaustive `switch`; `Localization.swift` defines the `Language` enum. The C++ library and CLI (`messages.def`) have only English and Chinese, and the other four fall back to English in the library (`Language.cValue`). Adding a language means extending the `Language` enum and every exhaustive table. | --- @@ -258,7 +271,7 @@ During development, you can also build and run the SwiftPM package directly: ```bash export TETHERKITNEXT_LIB_DIR="$PWD/build/lib" swift build --package-path gui -swift test --package-path gui # Runs TetherKitNextIPC unit tests +swift test --package-path gui # Runs the TetherKitNextIPC and TetherKitNextUIModel tests ``` To uninstall the helper daemon and clean up state from the terminal: @@ -271,15 +284,14 @@ Troubleshooting quick reference: | Symptom | Where to Check First | |---|---| -| UI stays on "Enable Background Component" | Check `launchctl print system/com.tetherkitnext.helperd` (or legacy `system/com.tetherkitnext.helper`) and ensure the app is in `/Applications` and enabled in *System Settings › General › Login Items & Extensions*. | +| UI stays on "Enable Background Component" | Check `launchctl print system/com.tetherkitnext.helperd` (or legacy `system/com.tetherkit.helper`) and ensure the app is in `/Applications` and enabled in *System Settings › General › Login Items & Extensions*. | | Helper fails to start | Check `/var/log/tetherkitnext-helper.log` (or unified logging for `com.tetherkitnext.helperd`). | | Connection fails | Check the **Activity** log panel in the app (supports one-click copy). | | App still links against Homebrew `libusb` | Inspect `otool -L dist/TetherKitNext.app/Contents/Frameworks/libtetherkitnext.0.*.dylib`. | | Clicking "Connect" reports `errAuthorizationExternalizeNotAllowed (-60005)` | The App released `AuthorizationRef` prematurely before the helper finished `CreateFromExternalForm`; see Section 4.4 rule 4. | | UI shows "Background Component Needs Update" | The app and running helper have mismatched `protocolRevision` or `buildId`; click **Update Background Component** in the app. | -| Clicking "Install Helper" reports missing payload | Running a bare `swift run` executable instead of the `.app` bundle assembled by `build-gui.sh`. | | Authorization prompt asks for password instead of Touch ID | `AuthorizationCopyRights` only supports password entry on ad-hoc builds; signed builds (1.1.0+) use `LAContext` for Touch ID (see Section 4.5). | | Re-plugging device and clicking "Connect" says session is already running | Running an older helper daemon that did not clear `failed`/`stopped` sessions; update/restart the background component. | -| Double-clicking Finder icon does nothing in Menu Bar Only mode | Known trade-off when activation policy is `.accessory` (see `MainWindowRoot`); open the main window from the menu bar panel (`Open TetherKitNext`). | +| Window chrome looks like an old app on macOS 26+ (small traffic lights) | The binary's `LC_BUILD_VERSION` `sdk` stamp is below 26. `build-gui.sh` rewrites and then checks it; verify with `otool -l …/MacOS/TetherKitNext \| grep -A4 LC_BUILD_VERSION`. | diff --git a/docs/GUI-SPIKE.md b/docs/GUI-SPIKE.md deleted file mode 100644 index 29f3eb2..0000000 --- a/docs/GUI-SPIKE.md +++ /dev/null @@ -1,285 +0,0 @@ -# GUI and Privilege Escalation Feasibility Spike - -This document records the findings of the initial exploratory spike: **can we build a native Swift GUI on top of TetherKitNext and acquire root privileges for network configuration cleanly on macOS?** - -The answer is yes, after ruling out several approaches that initially appeared standard. **Documenting the rejected paths and why they failed is even more valuable than the final design itself**, so future maintainers do not repeat the same dead ends. - -> Note: Section 3.3 and Section 4 reflect the initial upstream spike when distribution targeted unsigned source builds via Homebrew. For how TetherKitNext 1.0+ evolved to signed universal DMGs and `SMAppService.daemon`, see Section 0 of [GUI-ARCHITECTURE.md](GUI-ARCHITECTURE.md). - ---- - -## 1. Summary of Findings - -| Capability | Verdict | Evidence | -|---|---|---| -| Existing C API (at spike time) | **Did not exist** | Only C++23 headers + CLI existed; led to creating `include/tetherkitnext/capi/tetherkitnext_c.h` | -| Calling C++23 directly from Swift | **Unviable** | Swift C++ interop cannot import `std::expected`, `std::span`, or pure virtual base classes | -| USB device enumeration | **No root needed** | Verified via `libusb` as normal user (`uid 501`) | -| Creating `feth` interfaces | **Requires root** | Verified (`SIOCIFCREATE2` returns `EPERM` without root) | -| Assigning IPv4 via `SIOCAIFADDR` | **Works** | Kernel retains address without `configd` interference | -| Subnet / specific routes | **Works** | Automatically generated when IPv4 address is assigned | -| System DHCP client (`IPConfiguration`) | **Works** | Acquires lease (`State: BOUND`) on `feth0` | -| Scoped DNS & default route | **Automatically configured** | Configured by `IPConfiguration` / `SCNetworkService` | -| Overriding global default route | **Requires explicit step** | Needed only when a higher-priority interface is already online | - ---- - -## 2. Core Fact: `feth` Has No IOKit Node - -This single fact is the **common root cause** behind most macOS networking quirks with `feth`. - -`if_fake` (`feth`) interfaces are created via `SIOCIFCREATE` → `ifnet_attach` and **do not register an IOKit `IONetworkInterface` provider**. - -Empirical comparison on macOS: - -``` -IOKit IONetworkInterface: en0–en7, anpi0/1/3, vmenet0/1 ← no feth -NetworkInterfaces.plist: 0 occurrences of feth -ipconfig getiflist: en4 en5 en6 bridge0 en0 en7 ← no feth (until a service is attached) -SCDynamicStore: State:/Network/Interface/feth0/Link ← present! -``` - -`configd`'s **dynamic store** sees `feth` link state (fed by routing sockets / kernel events), whereas `SCNetworkInterfaceCopyAll()` does **not** enumerate `feth` because it walks the IOKit registry. - ---- - -## 3. Investigated Approaches - -### 3.1 Persistent `SCPreferences` + `SCNetworkService` ✅ (Initially Thought Impossible, Later Proven Working) - -Initial assumption: because `SCNetworkInterfaceCopyAll()` only enumerates IOKit nodes and omits `feth`, we initially assumed `SCNetworkService` could not be created for `feth`. - -**That initial assumption was disproved.** Not being enumerated by `SCNetworkInterfaceCopyAll()` does not prevent constructing an `SCNetworkInterfaceRef`. `SystemConfiguration` provides a long-standing SPI (present in open-source `configd`'s `SCNetworkInterface.c` since macOS 10.5+) that constructs an interface object by BSD name using `SIOCGIFFLAGS` without touching IOKit: - -```c -SCNetworkInterfaceRef -_SCNetworkInterfaceCreateWithBSDName(CFAllocatorRef allocator, - CFStringRef bsdName, - UInt32 flags); -``` - -Once the `SCNetworkInterfaceRef` is constructed, public APIs (`SCNetworkServiceCreate`, `SCNetworkSetAddService`, `SCPreferencesCommitChanges`) register `feth` as a first-class service visible in **System Settings › Network** and `networksetup -listallnetworkservices`. - -**Why this matters**: `ipconfig set feth0 DHCP` creates a transient `State:`-only service without a `Setup:` entry. While normal socket traffic works, **NetworkExtension VPN packet-tunnel providers (such as FortiClient) refuse to use an underlying interface unless it has a registered `Setup:` service**, failing with `"No network route to host"`. Registering a persistent `SCNetworkService` fixes VPN compatibility completely (`src/capi/managed_network_service.cc`). - -### 3.2 Directly Injecting Service Keys into `SCDynamicStore` ❌ - -Idea: bypass `SCPreferences` and write `State:/Network/Service//IPv4` and `/DNS` directly into `SCDynamicStore`. - -Result: `IPMonitor` ignores manually fabricated `State:` service entries unless they correspond to a service instantiated from `Setup:` or registered by `IPConfiguration` itself (`scutil --dns` never adopts the injected resolvers). - -### 3.3 `SMAppService` vs. `AuthorizationRef` - -- For **unsigned / source builds** (such as Homebrew formulas), `SMAppService` cannot be used because `SMPrivilegedExecutables` / `SMAuthorizedClients` require matching code-signing Designated Requirements (`cdhash` changes on every local build). -- For **signed Developer ID DMG distributions** (TetherKitNext 1.0+), `SMAppService.daemon` **is** used, combined with bidirectional Team ID code-signing checks (`CodeSigning.swift`) and `AuthorizationRef` / `LocalAuthentication` verification. - ---- - -## 4. Privilege and Authorization Architecture - -``` -TetherKitNext.app (uid 501, unprivileged) - │ ① Calls C ABI directly for non-root tasks: environment preflight, USB device list - │ ② Confirms user authorization (Touch ID via LAContext on team-signed builds, - │ or AuthorizationCopyRights → 32-byte external form token) - │ - ├── XPC (com.tetherkitnext.helperd, .privileged) ──► tetherkitnext-helper (uid 0) - │ │ ③ Verifies peer Team ID signature - │ │ ④ Verifies admin group / AuthorizationRef - │ │ (WITHOUT interactionAllowed) - │ │ ⑤ Executes privileged session/network op - └────────────────────── Result ◄─────────────────────┘ -``` - -### Why Authorization Verification Was Chosen alongside Code Signing - -| Approach | Local / Ad-Hoc Source Builds | Signed Developer ID Builds | -|---|---|---| -| `SMJobBless` Designated Requirement alone | ❌ Fails (`cdhash` changes on every build) | ✅ Works | -| `AuthorizationCopyRights` external token + Team ID check | ✅ Works (verifies `admin` credential in helper) | ✅ Works (Team ID pin + Touch ID / `AuthorizationRef`) | - -### Three Critical Authorization Rules - -1. **Never pass `interactionAllowed` when verifying in the daemon.** The daemon has no UI session; allowing interaction would let any local caller trigger system password dialogs. -2. **Never pass `destroyRights` to `AuthorizationFree` in the daemon.** The token belongs to the App and is cached for 5 minutes; destroying rights in the daemon would invalidate the App's cache. -3. **Do not require authorization for read-only status/probe methods.** This lets the UI distinguish between "daemon not enabled" and "user cancelled authorization". - -### Historical Addendum: In-App Helper Installation via AEWP (Before 1.0 `SMAppService` Migration) - -Prior to the 1.0 `SMAppService` migration, the app installed `/Library/PrivilegedHelperTools/com.tetherkitnext.helper` using `AuthorizationExecuteWithPrivileges` resolved via `dlsym`: - -- **Why a binary trampoline (`--install`) was required instead of a shell script**: `/usr/libexec/security_authtrampoline` launches the child with `euid=0` and `ruid=caller`. Standard shells (`bash`, `zsh`, `dash`) drop `euid` back to `ruid` when `euid != ruid` unless `-p` is passed. Invoking the helper binary with `--install` called `setgid(0)` + `setuid(0)` first before `exec`-ing `install-helper.sh`. -- **No exit code or PID from AEWP**: AEWP returns only a stdout pipe (`stderr` was merged via `dup2`), so completion was verified by establishing a live XPC connection and checking `protocolRevision` and `buildId`. -- **Resolved via `dlsym`**: avoided hard symbol binding to a deprecated symbol. - ---- - -## 5. Key Clarification: Authorization ≠ Root - -Calling `AuthorizationCopyRights` in the App **does not change the process's `uid` or `euid`**. It returns an `AuthorizationRef` credential proving the user consented to a right. Calling `tk_feth_create()` in the App immediately after `AuthorizationCopyRights` still fails with `EPERM`; the privileged work must be performed by the root daemon (`tetherkitnext-helper`) after verifying the credential. - ---- - -## 6. Network Configuration Capabilities - -### 6.1 Kernel-Level Configuration (`SIOCAIFADDR`) - -- Assigning IPv4 addresses and netmasks via `SIOCAIFADDR` works and persists without `configd` removing them. -- Subnet routes and interface-scoped default routes (`RTF_IFSCOPE`) work as expected. - -### 6.2 DHCP via System `IPConfiguration` Client - -macOS's built-in `IPConfiguration` agent supports `feth` interfaces directly: - -```bash -sudo ipconfig set feth9 DHCP # exit=0 -ipconfig getiflist # → ... feth9 ← appears immediately -ipconfig getsummary feth9 # → ConfigMethod: DHCP, ServiceID: DHCP-feth9 -``` - -⚠️ **Diagnostic pitfall**: `ipconfig getiflist` only lists interfaces that **currently have an active IPConfiguration service attached**, not all configurable interfaces (even a physical Thunderbolt Ethernet card `en1` is absent from `getiflist` until configured). - -### 6.3 What One Command Provides - -When `feth0` is paired with `feth1` and connected to a phone's DHCP server: - -```bash -sudo ipconfig set feth0 DHCP -``` - -`IPConfiguration` automatically completes all four steps: - -| Outcome | Verification | -|---|---| -| Acquires IPv4 lease | `ipconfig getifaddr feth0` → `192.168.35.128` (`State: BOUND`) | -| Configures scoped DNS | `scutil --dns` shows `nameserver 192.168.35.7 / if_index (feth0) / Scoped` | -| Installs scoped default route | `netstat -rn` shows `default 192.168.35.7 UGScIg feth0` | -| Publishes service to `SCDynamicStore` | `State:/Network/Service/.../{DHCP,DNS,IPv4}` (`IsPublished: TRUE`) | - -### 6.4 Taking Over the Global Default Route - -If the Mac already has another active primary network interface (such as Wi-Fi), `feth0` receives a **scoped** default route, while unbound traffic continues using the primary interface. When the user enables "Route all traffic through this interface", the helper updates the default route (and promotes the managed service in `ServiceOrder`): - -```bash -sudo route -n change default $(ipconfig getoption feth0 router) -``` - -### 6.5 Impact on Implementation - -Because `IPConfiguration` and `SCNetworkService` handle DHCP leases, DNS publishing, and route installation natively, TetherKitNext does not need a custom user-space DHCP state machine. Teardown simply clears the `SCNetworkService` or runs `sudo ipconfig set feth0 NONE`. - ---- - -## 7. Packaging Lessons Learned - -### Hardened Runtime and `libusb` - -Under Hardened Runtime, macOS refuses to load dynamic libraries signed with a different Team ID (or ad-hoc Homebrew binaries): - -``` -Library not loaded: /opt/homebrew/opt/libusb/lib/libusb-1.0.0.dylib -Reason: ... have different Team IDs -``` - -Therefore, `TetherKitNext.app` bundles its own universal `libusb-1.0.0.dylib` inside `Contents/Frameworks/` and signs all Mach-O binaries with the same identity. - -### Re-Signing After `install_name_tool` - -On Apple Silicon, modifying load commands or rpaths with `install_name_tool` invalidates the binary's code signature, causing the kernel to immediately `SIGKILL` (`Killed: 9`) the process on launch. Always re-sign inside-out after running `install_name_tool`. - -### Preserve Symlinks When Copying Dylibs (`cp -a`, Not `install`) - -`libtetherkitnext.dylib` and `libtetherkitnext.0.dylib` are symlinks to the versioned library. Using `install` dereferences symlinks into separate duplicate files, causing `install_name_tool` to patch only one copy while `@rpath` loads the unpatched copy. Always use `cp -a`. - -### Inspect Dependencies on the Right Binary - -`libusb` is a link dependency of `libtetherkitnext.dylib`, not of the helper executable directly. Running `otool -L` against the helper executable returns no `libusb` entry, silently skipping dependency fixups if checked on the wrong target. - -### Always Brace Shell Variables (`${VAR}`) Before Non-ASCII Punctuation - -```bash -echo "cleaned ($IFACE)" # Unbraced $VAR adjacent to multibyte punctuation fails under UTF-8 locale -``` - -Under a UTF-8 locale, `bash` treats the leading byte (`0xEF`) of full-width punctuation as a valid identifier character (`isalnum()` returns true), absorbing the punctuation into `$VAR` and failing with `unbound variable`. Always write `${VAR}`. - -### Set Explicit `CMAKE_OSX_DEPLOYMENT_TARGET` - -Without an explicit `CMAKE_OSX_DEPLOYMENT_TARGET`, CMake defaults to the host macOS version, and Homebrew's `libusb` is also built for the host OS version. Release builds must build `libusb` and `libtetherkitnext` with an explicit deployment target (`13.3` for CLI/core, `14.0` for GUI). - ---- - -## 8. Homebrew Distribution Considerations - -### Two Empirically Verified Constraints - -- **`brew services` DSL has no `MachServices` support** (confirmed in `Library/Homebrew/service.rb`), so it cannot register an XPC LaunchDaemon. -- **`brew install` never runs as root**, so a formula cannot write to `/Library/LaunchDaemons`. - -### Location of `.app` in Homebrew Cellar - -A Homebrew formula can install a `.app` inside the Cellar, but it will not automatically appear in `/Applications`, Launchpad, or Spotlight without user action or a Cask / DMG drag-to-`/Applications` workflow. - -### Signing Requirements by Distribution Channel - -| Channel | Certificate Required? | -|---|---| -| Formula (built from source locally) | **No** — locally compiled binaries have no quarantine attribute, so Gatekeeper does not block execution | -| Prebuilt DMG / Cask (downloaded `.app`) | **Requires Developer ID + Apple Notarization** — downloaded archives carry `com.apple.quarantine` (adopted in TetherKitNext 1.0+) | - ---- - -## 9. C API Gaps Identified During Spike (Subsequently Implemented in Commits #12–#16) - -To support a non-blocking GUI and helper daemon, the following capabilities were added to `libtetherkitnext`: - -- **Read-only status accessors**: bridge statistics, RNDIS state, link up/down status, negotiated parameters, driver-side interface name, and fatal error messages. -- **Self-hosted control thread (`Runtime::Start`)**: non-blocking startup instead of blocking `RunUntilStopped()`. -- **Pollable event queue and log ring (`tk_poll_event`, `tk_drain_logs`)**: avoids cross-thread Swift callbacks and re-entrancy deadlocks on `Stop()`. - -| Identified Gap | Resolution in `tk_capi` | -|---|---| -| Log sink | Added lock-free ring buffer (`tk_drain_logs`) so the GUI can display live logs without reading `stderr` | -| USB string descriptors | Added vendor, product, and serial number fields (`tk_list_devices`) with `ReconcileDeviceStrings` caching | -| Hotplug | `Context::SupportsHotplug()` verified; GUI polls `tk_list_devices` every 2 seconds | -| Orphan `feth` cleanup | Added `/var/run/tetherkitnext-interfaces.state` and `tk_cleanup_orphan_interfaces` in case of `SIGKILL` | -| Helper signal handling | Added `DispatchSource.makeSignalSource` for `SIGTERM` / `SIGINT` in `tetherkitnext-helper` | - ---- - -## 10. Useful Verification Commands - -```bash -# Check whether feth appears in IOKit (expected: absent) -ioreg -c IONetworkInterface -r -d1 | grep '"BSD Name"' | sort -u - -# Verify IPConfiguration accepts feth (expected: exit=0 and appears in getiflist) -sudo ifconfig feth9 create -sudo ipconfig set feth9 DHCP && ipconfig getiflist -sudo ipconfig set feth9 NONE && sudo ifconfig feth9 destroy - -# ⚠️ Note: `ipconfig getiflist` lists interfaces that currently have an active -# IPConfiguration service, NOT all interfaces capable of being configured. -# Interfaces that have never run a service (even physical NICs) do not appear. - -# End-to-end verification on a live RNDIS session -sudo ipconfig set feth0 DHCP -ipconfig getifaddr feth0 # Lease IP -scutil --dns | grep -A3 feth0 # Scoped DNS (in lower section; do not truncate with head) -netstat -rn -f inet | grep -E "^default" # Scoped default route -ipconfig getsummary feth0 | grep -E "State|IsPublished|Router" -sudo ipconfig set feth0 NONE # Teardown - -# Verify kernel SIOCAIFADDR address assignment on feth (expected: succeeds) -sudo ifconfig feth9 create -sudo ifconfig feth9 inet 10.99.99.1 netmask 255.255.255.0 up -netstat -rn -f inet | grep 10.99.99 -sudo ifconfig feth9 destroy - -# Check whether Homebrew service DSL supports MachServices (expected: no matches) -grep -i machservice /opt/homebrew/Library/Homebrew/service.rb -``` - -Note: The trailing `!` on interface routes in `netstat -rn` output indicates a scoped route (`RTF_IFSCOPE`), **not an error** — standard `en0` and `bridge` routes carry it as well. - - diff --git a/docs/LOCAL-DEVICES.md b/docs/LOCAL-DEVICES.md new file mode 100644 index 0000000..699a835 --- /dev/null +++ b/docs/LOCAL-DEVICES.md @@ -0,0 +1,79 @@ +# Local-link devices (not phones) + +Many devices use the same USB networking (RNDIS) as Android tethering but are +a **private link to the device**, not an internet connection: +- drones and their remote controllers, whose desktop companion apps update + firmware, calibrate and download logs over this link; +- FPV goggles; +- single-board computers in USB gadget mode (Raspberry Pi Zero, BeagleBone); +- cameras and other appliances. + +On macOS they used to need HoRNDIS, a kernel extension that is unmaintained +and doesn't load on current macOS without disabling SIP. Some vendors' install +guides tell users to do exactly that. TetherKitNext's user-space driver already +speaks RNDIS to any device that matches the standard interface signatures +(no vendor table), so the work here is about **behaving correctly once +connected**. + +## Why this matters + +Treating such a device like a phone shows a "DHCP got no lease within 10 s" alert for fixed-address devices, and with *Route all traffic* on a device that offers DHCP but no router could outrank the Mac's real internet in the service order. + +## Design + +1. **Live link assessment** (`TetherKitNextUIModel/LinkAssessment.swift`, + unit-tested). From current facts only (run state, time since connect, + DHCP lease, router, the device's own address) it yields: *waiting for an + address*, *internet* (lease with a router), *local link* (address, no + router; includes macOS's 169.254 fallback) or *no address* (after a grace + period). Phones with internet see exactly the UI they saw before. +2. **Passive peer discovery** (`core/peer_address.h`). The bridge reads the + device's own IPv4 address from frames only it can have sent: ARP sender + addresses, plus IPv4 sent to the limited broadcast or 224.0.0.0/24 (mDNS, + DHCP replies). Ordinary unicast is ignored, because phones forward internet + traffic whose source is a remote server. This costs a few byte loads per + frame and one atomic store when the address changes, and sends nothing. + It is exposed as `tk_session_status_t.peer_ipv4` and `SessionStatus.peerAddress` + (optional, so older daemons' JSON still decodes). +3. **Route safety.** If *Route all traffic* was requested but no router + appears, `ApplyDhcp` moves our service back to the end of the service order + (`DemoteManagedNetworkService`). A device that can't reach the internet + never outranks Wi-Fi or Ethernet. The UI says the option wasn't applied. +4. **Quiet auto-configuration.** DHCP timeouts after Connect are no longer + alerts; the card explains the state instead. An explicit *Apply* on the + Network page still reports errors. +5. **Session-only address.** For devices without DHCP, the card suggests an + address in the device's /24 (`.10`, `.20`, `.100` or `.200`, never the + device's own) or takes one typed in. It is applied as a manual + configuration for this connection only. It is never written to the saved + settings and is cleared when the session ends. macOS's IPConfiguration + checks for address conflicts with ARP when it applies the address. + +## Why the device kind is never saved + +A remembered label misfires: a phone that is slow to start its DHCP server, +or whose upstream (Wi-Fi bridging, mobile data) is slow or down, would be +saved as "local device", and the next connection would be handled wrongly. +Alternatives considered: + +| Option | Verdict | +|---|---| +| Remember kind per device (VID:PID + serial) | **Rejected.** A slow phone gets stuck with the wrong label, and Android randomizes the RNDIS MAC every session. | +| Vendor table (e.g. "this vendor ID is a drone") | **Rejected for behavior.** Same vendor IDs cover phones and accessories, and it ages badly. It could at most be a UI hint, and isn't needed. | +| Probe the internet (HTTP / DNS check through the interface) | **Rejected.** It sends traffic the user didn't ask for, and it fails on a phone whose upstream is momentarily down, which is exactly the slow-phone misfire. | +| **Evidence-based, recomputed every poll** | **Chosen.** Only facts the link itself reports count (lease, router, the device's address). A late lease flips the result to *internet* with no user action. Nothing is stored. | +| Grace period before saying "no address" | **Chosen** (20 s): covers the daemon's 10 s DHCP wait, Android's transitional 464XLAT lease and slow devices. | +| Manual per-session override ("treat as phone / local") | Not needed: the only behavior that depends on the kind is *Route all traffic*, and that follows the factual presence of a router. "Try automatic again" re-applies the saved settings at any time. | +| Session-only address instead of editing saved settings | **Chosen.** Configuring a drone must never leave a fixed address behind for the next phone. | + +## Testing + +- C++: `core.peer_address` (frame rules, observer) and `capi.basics` + (`peer_ipv4` empty when idle). These run in CI on every macOS runner. +- Swift: `LinkAssessmentTests` (grace period, late lease, 169.254 fallback, + suggestions). +- **Not yet tested on hardware**: a drone or controller with its vendor + software, and a Raspberry Pi Zero in gadget mode with a static address. + A gadget-mode Pi is the easiest stand-in: + `modprobe g_ether` (RNDIS enabled), `ip addr add 192.168.7.2/24 dev usb0`, + and no DHCP server. diff --git a/docs/MACOS-27.md b/docs/MACOS-27.md new file mode 100644 index 0000000..9eb6bdb --- /dev/null +++ b/docs/MACOS-27.md @@ -0,0 +1,93 @@ +# 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 `native` job on `xcode-27`, step "feth ABI gate": 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. + +## Known issue: building with the macOS 27 SDK + +A libusb built on the macOS 27 runner (Xcode 27, macOS 27 SDK, +`MIN_MACOS=13.3`) **segfaults during USB device enumeration on macOS 15 and +26**; the same library built with Xcode 26 works on all of them, and the +Xcode 27 build works on macOS 27. CI hit this when the jobs shared a libusb +cache. Until the cause is found: + +* Release and packaging builds select **Xcode 26** explicitly + (`ci.yml` `package`, `release.yml`). +* The libusb cache key includes the SDK and OS version. +* The DMG smoke test on `macos-15` runs `tetherkitnext-cli --list`, which + enumerates USB devices, so a release built with the wrong toolchain fails CI. + +This affects only how we *build*; running the Xcode 26 build on macOS 27 is +what the `xcode-27` CI jobs test. + +## 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. Mitigation in place: `HelperInstaller.register()` removes `com.apple.quarantine` from the bundled plist before every registration (extended attributes are not part of the code signature). Still confirm on hardware. | +| **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 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 outbound calls (the optional GitHub release check, and Sparkle's appcast and update download) are 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 +``` + +## Deployment targets and older systems + +The app needs macOS 14.0 (`LSMinimumSystemVersion`, `platforms: [.macOS(.v14)]`); the CLI and `libtetherkitnext` need 13.3. Building the app needs macOS 15 or later with Xcode 26. The main-window code uses `NSHostingController.sceneBridgingOptions` and `NSApplication.activate()`, both macOS 14.0. + +* **SDK stamp.** Rewriting `sdk` to 26.x matches what an Xcode-built app + carries. On macOS 14/15 it only turns on behaviors those releases gate on + "linked on 14/15 or later", which the code (compiled with the 26 SDK) + already expects. `minos` stays 14.0, so the launch floor is unchanged. +* **Persisted state.** UI state is stored with `@AppStorage` (there is no + scene to hold `@SceneStorage`), and the window frame has its own autosave + name. +* **CLI.** The process spawn flag and stdin handling are covered by + `capi.process` tests (no inherited descriptor; stdin is EOF), which run in + CI on macOS 15 (arm64 and Intel), 26 and 27. + +Runtime coverage in CI: the shipped universal DMG is installed and its GUI +launched on `macos-15` (arm64) and `macos-15-intel`, and built and launched +on macOS 27. GitHub has no macOS 13 or 14 runners, so **macOS 14 needs a +manual launch check** (window opens, sidebar and toolbar render, ⌘W, reopen +from the menu bar), and so does the CLI on macOS 13.3. diff --git a/docs/MACOS-NETWORKING-NOTES.md b/docs/MACOS-NETWORKING-NOTES.md new file mode 100644 index 0000000..e98bb15 --- /dev/null +++ b/docs/MACOS-NETWORKING-NOTES.md @@ -0,0 +1,132 @@ +# macOS Networking Notes for `feth` + +Reference notes on how macOS network services treat `feth` interfaces, with the commands used to verify each fact. They explain why the C ABI configures addresses through `IPConfiguration` and `SCNetworkService` instead of raw socket ioctls. The GUI and helper design is in [GUI-ARCHITECTURE.md](GUI-ARCHITECTURE.md). + +--- + +## 1. Summary + +| Capability | Verdict | Evidence | +|---|---|---| +| USB device enumeration | **No root needed** | `libusb` as a normal user (`uid 501`) | +| Creating `feth` interfaces | **Requires root** | `SIOCIFCREATE2` returns `EPERM` without root | +| Assigning IPv4 via `SIOCAIFADDR` | **Works** | The kernel keeps the address, but `configd` ignores it (no service, no scoped DNS, no default route) | +| Subnet / specific routes | **Works** | Generated automatically when an IPv4 address is assigned | +| System DHCP client (`IPConfiguration`) | **Works** | Acquires a lease (`State: BOUND`) on `feth0` | +| Scoped DNS and default route | **Configured automatically** | By `IPConfiguration` / `SCNetworkService` | +| Overriding the global default route | **Needs an explicit step** | Only when a higher-priority interface is already online | + +--- + +## 2. `feth` Has No IOKit Node + +This is the common root cause of most macOS networking quirks with `feth`. + +`if_fake` (`feth`) interfaces are created via `SIOCIFCREATE` and `ifnet_attach`. They do not register an IOKit `IONetworkInterface` provider. + +``` +IOKit IONetworkInterface: en0-en7, anpi0/1/3, vmenet0/1 (no feth) +NetworkInterfaces.plist: 0 occurrences of feth +ipconfig getiflist: en4 en5 en6 bridge0 en0 en7 (no feth until a service is attached) +SCDynamicStore: State:/Network/Interface/feth0/Link is present +``` + +`configd`'s dynamic store sees `feth` link state (fed by routing sockets and kernel events). `SCNetworkInterfaceCopyAll()` does not enumerate `feth`, because it walks the IOKit registry. + +--- + +## 3. Service Registration + +### 3.1 Persistent `SCPreferences` + `SCNetworkService` (used) + +`SCNetworkInterfaceCopyAll()` omitting `feth` does not prevent constructing an `SCNetworkInterfaceRef`. `SystemConfiguration` has a long-standing SPI that builds an interface object from a BSD name using `SIOCGIFFLAGS`, without touching IOKit: + +```c +SCNetworkInterfaceRef +_SCNetworkInterfaceCreateWithBSDName(CFAllocatorRef allocator, + CFStringRef bsdName, + UInt32 flags); +``` + +With that reference, the public APIs (`SCNetworkServiceCreate`, `SCNetworkSetAddService`, `SCPreferencesCommitChanges`) register `feth` as a service visible in System Settings > Network and in `networksetup -listallnetworkservices`. The SPI is resolved through `dlsym` with a fallback (AGENTS.md pitfall 22). + +Why a persistent service matters: `ipconfig set feth0 DHCP` alone creates a transient `State:`-only service without a `Setup:` entry. Ordinary socket traffic works, but NetworkExtension VPN packet-tunnel providers (FortiClient, for example) refuse to use an underlying interface that has no registered `Setup:` service and fail with "No network route to host". Registering a persistent `SCNetworkService` fixes this (`src/capi/managed_network_service.cc`). + +### 3.2 Injecting service keys into `SCDynamicStore` (does not work) + +Writing `State:/Network/Service//IPv4` and `/DNS` directly into `SCDynamicStore` is ignored. `IPMonitor` only honors `State:` service entries that belong to a service instantiated from `Setup:` or registered by `IPConfiguration` itself; `scutil --dns` never adopts the injected resolvers. + +--- + +## 4. Network Configuration Capabilities + +### 4.1 Kernel-level configuration (`SIOCAIFADDR`) + +- Assigning IPv4 addresses and netmasks via `SIOCAIFADDR` works and persists without `configd` removing them. +- Subnet routes and interface-scoped default routes (`RTF_IFSCOPE`) work as expected. +- `configd` ignores these addresses, so they are not enough on their own. + +### 4.2 DHCP via the system `IPConfiguration` client + +macOS's built-in `IPConfiguration` agent supports `feth` interfaces directly: + +```bash +sudo ipconfig set feth9 DHCP # exit=0 +ipconfig getiflist # ... feth9 appears immediately +ipconfig getsummary feth9 # ConfigMethod: DHCP, ServiceID: DHCP-feth9 +``` + +`ipconfig getiflist` lists only interfaces that currently have an active IPConfiguration service attached, not all configurable interfaces. A physical Thunderbolt Ethernet card is absent until configured as well. + +### 4.3 What one command provides + +When `feth0` is paired with `feth1` and connected to a phone's DHCP server, `sudo ipconfig set feth0 DHCP` completes four steps: + +| Outcome | Verification | +|---|---| +| Acquires an IPv4 lease | `ipconfig getifaddr feth0` returns an address (`State: BOUND`) | +| Configures scoped DNS | `scutil --dns` shows `nameserver ... if_index (feth0) ... Scoped` | +| Installs a scoped default route | `netstat -rn` shows `default UGScIg feth0` | +| Publishes the service to `SCDynamicStore` | `State:/Network/Service/.../{DHCP,DNS,IPv4}` (`IsPublished: TRUE`) | + +### 4.4 Taking over the global default route + +If the Mac already has another primary interface (such as Wi-Fi), `feth0` receives a scoped default route and unbound traffic keeps using the primary interface. With "Route all traffic through this interface", the helper updates the default route and promotes the managed service in `ServiceOrder`: + +```bash +sudo route -n change default $(ipconfig getoption feth0 router) +``` + +### 4.5 Consequences for the implementation + +Because `IPConfiguration` and `SCNetworkService` handle leases, DNS publishing and route installation, TetherKitNext has no user-space DHCP state machine. Teardown clears the `SCNetworkService` or runs `sudo ipconfig set feth0 NONE`. Interface names that must be destroyed after a crash are recorded in `/var/run/tetherkitnext-interfaces` (`src/capi/orphan_cleanup.cc`). + +--- + +## 5. Verification Commands + +```bash +# Check whether feth appears in IOKit (expected: absent) +ioreg -c IONetworkInterface -r -d1 | grep '"BSD Name"' | sort -u + +# Verify IPConfiguration accepts feth (expected: exit=0 and appears in getiflist) +sudo ifconfig feth9 create +sudo ipconfig set feth9 DHCP && ipconfig getiflist +sudo ipconfig set feth9 NONE && sudo ifconfig feth9 destroy + +# End-to-end check on a live RNDIS session +sudo ipconfig set feth0 DHCP +ipconfig getifaddr feth0 # lease IP +scutil --dns | grep -A3 feth0 # scoped DNS (lower section; do not truncate with head) +netstat -rn -f inet | grep -E "^default" # scoped default route +ipconfig getsummary feth0 | grep -E "State|IsPublished|Router" +sudo ipconfig set feth0 NONE # teardown + +# Verify SIOCAIFADDR address assignment on feth (expected: succeeds) +sudo ifconfig feth9 create +sudo ifconfig feth9 inet 10.99.99.1 netmask 255.255.255.0 up +netstat -rn -f inet | grep 10.99.99 +sudo ifconfig feth9 destroy +``` + +A trailing `!` on interface routes in `netstat -rn` output marks a scoped route (`RTF_IFSCOPE`), not an error. Standard `en0` and `bridge` routes carry it as well. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 478972c..d48aeb3 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -113,29 +113,25 @@ Data path started: RX ring 2048 frames (4352 KiB), RX write batch 64 frames, TX | libusb **control transfers** are ~10× slower on Apple Silicon | Keepalive and OID queries take milliseconds | No. Keepalive intervals should not be shortened, and control operations must never enter the data hot path | | `BIOCSBATCHWRITE` is macOS 14+ only | One syscall per RX frame on macOS 13 and earlier | No; automatically falls back to per-frame writes | | Community reports of kernel mbuf exhaustion panic on `feth` at **> 5–8 Gbps** | Very low risk for this project | RNDIS over USB 2.0 measures ~325 Mbps RX / ~235 Mbps TX, and even USB 3 rarely exceeds 1–2 Gbps—well below that threshold | -| ~~TX backpressure frame drops under heavy load~~ | ~~Dropped 1889 frames in 6 seconds~~ | **Fixed**: the bridge now waits for a free transfer slot instead of dropping immediately, reducing TX drops to 0. See "Root Cause and Fix of TX Frame Drops" in [BENCHMARKS.md](BENCHMARKS.md) | -| RTT inflates from 0.4 ms to 16.6 ms under bidirectional load | No longer causes throughput collapse after fixing TX drops (bidirectional TX improved from 4.8 → 87 Mbps), but latency-sensitive traffic is still affected | Partially. Reducing RX queue depth can mitigate bufferbloat at the cost of peak RX throughput; exact trade-off not yet measured | -| Bimodal TCP TX throughput (~240 Mbps vs. ~300 Mbps stable states) | Throughput fluctuates between two stable modes, though both have zero retransmissions (not packet loss) | Root cause not yet identified | +| RTT inflation under bidirectional load; bimodal TCP TX throughput | Latency-sensitive traffic is affected; TX throughput alternates between two stable modes with zero retransmissions | Not yet. Both are open items in [AGENTS.md section 6.3](../AGENTS.md#63-completed--open-verification-items) | --- -## Measured Conclusions (Completed 2026-07-28) +## Measured Conclusions -All four items previously listed as "unmeasured estimates" now have real hardware measurements. Full data and methodology are in [BENCHMARKS.md](BENCHMARKS.md); below is the summary: +Full data and methodology are in [BENCHMARKS.md](BENCHMARKS.md); summary: -| Original Estimate | Measured Value | Difference | +| Item | Measured Value | Note | |---|---|---| -| BPF `write()` ~700 ns (extrapolated from `write(/dev/null)`) | **2181 ns** | **~3× more expensive** | -| `BIOCSBATCHWRITE` speedup factor unknown | 805 ns/frame (batch ≥ 32) | **~2.7× speedup** | -| Whether end-to-end throughput can approach 426 Mbps | RX **324–327 Mbps** (77% of theoretical limit) | Close, though bounded by USB/gadget overhead | -| `feth` round-trip latency unknown | **24.5 µs** | Accounts for only ~5% of end-to-end RTT | +| BPF `write()` | **2181 ns** | About 3x the ~700 ns extrapolated from `write(/dev/null)` | +| `BIOCSBATCHWRITE` | 805 ns/frame (batch >= 32) | About 2.7x faster than single writes | +| End-to-end RX throughput | **324-327 Mbps** | 77% of the 426 Mbps theoretical limit | +| `feth` round-trip latency | **24.5 µs** | About 5% of end-to-end RTT | -Three key takeaways: +Takeaways: 1. **BPF writing is not the bottleneck.** Although single writes are 3× more expensive than estimated, batch writes still achieve 1.24 million frames/sec (~15 Gbps at 1514 bytes), whereas USB 2.0 high-speed requires only ~27k frames/sec — a 45× safety margin. Earlier concerns that BPF writes would cap theoretical RX throughput can be put to rest. 2. **This overhead is nearly independent of frame length** (1934 ns for 64 bytes vs. 2181 ns for 1514 bytes, a 13% difference). Almost all of the cost is per-call fixed overhead, which is why batch writing is critical rather than shrinking frames. -3. **The TX path was previously the weak side; its root cause has been identified and fixed.** Drops were occurring in our own TX path because the bridge **immediately discarded** remaining frames in a batch whenever the bulk OUT transfer pool was full, even though a slot would become free within a few hundred microseconds. Switching to bounded waiting reduced TX drops from 1889 → **0**, TCP TX retransmissions from 3829 → **0**, and boosted bidirectional concurrent TX from **4.8 → 87 Mbps**. This also invalidated an earlier tuning recommendation: after the fix, setting `--tx-transfers` to 4, 8, or 16 shows no discernible difference, so the default remains 4. See [BENCHMARKS.md](BENCHMARKS.md) for details. +3. **TX frame drops came from our own TX path.** The bridge **immediately discarded** remaining frames in a batch whenever the bulk OUT transfer pool was full, even though a slot would become free within a few hundred microseconds. Switching to bounded waiting reduced TX drops from 1889 → **0**, TCP TX retransmissions from 3829 → **0**, and boosted bidirectional concurrent TX from **4.8 → 87 Mbps**. After the fix, setting `--tx-transfers` to 4, 8, or 16 shows no discernible difference, so the default remains 4. See [BENCHMARKS.md](BENCHMARKS.md) for details. -**Lesson learned**: The original drop logic had a convincing comment claiming that waiting would cause invisible kernel buffer drops. Both premises were false: `bs_drop` is read back on every batch and displayed in the stats line, and the 4 MiB kernel buffer is specifically meant to absorb bursts. **When writing a justification for a deliberate design choice, always check the orders of magnitude**: a pool depth of 4 slots vs. ~26 slots needed for a burst immediately reveals the mismatch. - -Still open: the bimodal TCP TX behavior and RTT inflation under bidirectional load. See the final section of [BENCHMARKS.md](BENCHMARKS.md). +Open items (bimodal TCP TX throughput, RTT inflation under bidirectional load) are listed in [AGENTS.md section 6.3](../AGENTS.md#63-completed--open-verification-items). diff --git a/docs/SECURITY-AUDIT.md b/docs/SECURITY-AUDIT.md index cb459a9..4a0b71e 100644 --- a/docs/SECURITY-AUDIT.md +++ b/docs/SECURITY-AUDIT.md @@ -2,6 +2,8 @@ Date: 2026-09-25 · Base: upstream `XiaoMiku01/TetherKit` v0.1.5 (`1ded051`) +The body of this document is the original audit; dated addenda at the end cover later changes. + Scope: every source file in this repository — the C++ driver (`src/`, `include/`), the C ABI, the Swift app, the root daemon, the build scripts and the CI workflows — reviewed for backdoors, memory safety, privilege @@ -14,7 +16,7 @@ Developer ID signing and notarization. | Check | Result | |---|---| -| Outbound network connections | One: the optional, read-only GitHub release check (`UpdateChecker.swift`). It downloads nothing and runs nothing. | +| Outbound network connections | Two optional ones. The read-only GitHub release check (`UpdateChecker.swift`) downloads nothing and runs nothing. Sparkle fetches the appcast and, after the user confirms, the update download; the EdDSA signature and Team ID are verified (see the 2026-12-01 addendum). | | Process execution | `/usr/sbin/ipconfig` and `/sbin/route` with absolute paths through `posix_spawn` and an argv array (no shell). Arguments are validated interface names (`feth`) and IPv4 literals. The legacy installer's `execv("/bin/bash")` has been removed. | | Dynamic code loading | Upstream: `dlsym("AuthorizationExecuteWithPrivileges")` (removed). Now only `dlsym("_SCNetworkInterfaceCreateWithBSDName")`, a documented, optional lookup of an Apple SPI. | | Obfuscation, encoded payloads, hidden persistence | None. The only persistence is the LaunchDaemon, which the user approves and can see in System Settings › Login Items. | @@ -96,7 +98,7 @@ response could open `file://` or custom-scheme URLs. **L1. Root child processes inherited the full environment.** `ipconfig` and `route` now run with a fixed `PATH` and `LANG=C`. -**L2. The CI ABI gate could never pass.** It searched the log for a legacy Chinese message ("Created feth"), +**L2. The CI `feth ABI gate` step could never pass.** It searched the log for a legacy Chinese message ("Created feth"), a string that disappeared when log messages were localized. It now pins `TETHERKITNEXT_LANG=en` and matches the current message. @@ -135,13 +137,13 @@ a string that disappeared when log messages were localized. It now pins | No deprecated privilege APIs | AEWP removed; SMAppService (macOS 13+) is used | | Library validation | All bundled dylibs are signed by the same team | | Notarization + stapling | App (zip) → staple → DMG → notarize → staple (`make-dmg.sh`) | -| Private API use | `feth`'s `if_fake` ioctl ABI (the core of the product, gated by the CI ABI check) and one optional SystemConfiguration SPI (resolved at runtime). Both are fine for Developer ID distribution; neither would be allowed on the Mac App Store. | +| Private API use | `feth`'s `if_fake` ioctl ABI (the core of the product, gated by the `feth ABI gate` step of the CI `native` job) and one optional SystemConfiguration SPI (resolved at runtime). Both are fine for Developer ID distribution; neither would be allowed on the Mac App Store. | | Third-party licenses | libusb (LGPL-2.1) is shipped as a separate, replaceable dylib, with its license text in `Contents/Resources/Licenses` | ## Residual risks and recommendations * **Kernel private ABI.** `if_fake_request` and the `BIOC*` private ioctls can - change in any macOS release. The CI ABI gate runs on each runner image; keep + change in any macOS release. The `feth ABI gate` step of the CI `native` job runs on each runner image; keep it required. * **Ad-hoc development builds** have no Team ID to pin, so they fall back to the authorization-only XPC model. Only distribute builds signed with a @@ -153,3 +155,102 @@ 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. + +## Addendum: 2026-12-01 self-update (Sparkle) + +The app gained in-app updates through Sparkle 2.10.1, which replaces the +`.app` with a downloaded one, so it adds a code-delivery path that needs its +own trust argument: + +* **Integrity and origin.** Each update DMG carries an EdDSA (Ed25519) + signature in the appcast. The installed app verifies it with the public key + in its own Info.plist **before unpacking** (`SUVerifyUpdateBeforeExtraction`). + Sparkle additionally requires the new app to be signed by the same Developer + ID Team as the running one. The download is also notarized and stapled. +* **Key handling.** The private key exists only in the `SPARKLE_ED_PRIVATE_KEY` + secret and in the maintainer's keychain. The release job passes it to + `sign_update` on stdin (`--ed-key-file -`), never as an argument or a file. + Before publishing, `scripts/verify-sparkle-signature.swift` checks the + signature with the key embedded in the built app, so a mismatched + secret/variable pair cannot ship. +* **No silent installs.** Automatic installation is disabled; every update + needs the user's confirmation in Sparkle's dialog. +* **Feed.** Served over HTTPS from this repository's latest release. Anyone + able to publish releases could already ship a signed DMG; the EdDSA key adds + a second, independent secret on top of the Developer ID certificate. +* **Dependency.** Pinned with `exact: "2.10.1"`; SwiftPM verifies the binary + against the checksum in Sparkle's manifest + (`4c2e48a3e50ebcc2c88a58a4c7264a1a99c3c31857ce754357afb9cdb323022a`, + re-checked by downloading the archive). The framework is re-signed with our + Developer ID inside-out and covered by hardened runtime and notarization. +* **Residual risk.** Compromise of both the GitHub release permission and the + EdDSA private key would allow a malicious update; rotating the key requires + an app release that carries the new public key. diff --git a/docs/assets/screenshot-main-en.jpg b/docs/assets/screenshot-main-en.jpg deleted file mode 100644 index ed9be2f..0000000 Binary files a/docs/assets/screenshot-main-en.jpg and /dev/null differ diff --git a/gui/Package.swift b/gui/Package.swift index 6b063e6..0f951d2 100644 --- a/gui/Package.swift +++ b/gui/Package.swift @@ -1,39 +1,35 @@ // swift-tools-version: 6.2 // -// Swift 6 language mode (the default for tools 6.x): strict data-race checking -// is on for every target. Building needs Xcode 26 / Swift 6.2, which is also -// what provides the macOS 26 SDK the Liquid Glass UI is compiled against; the -// app still deploys back to macOS 14. +// Swift 6 language mode (the default for tools 6.x): strict data-race checking is on for every target. +// Building needs Xcode 26 / Swift 6.2, which also provides the macOS 26 SDK the Liquid Glass UI is compiled +// against; the app still deploys back to macOS 14. // // TetherKitNext's graphical interface. // -// * Why SwiftPM rather than CMake or an Xcode project * +// Why SwiftPM rather than CMake or an Xcode project: +// - CMake's Swift support exists only under the Ninja / Xcode generators, while this repository uses Unix +// Makefiles, and switching generators would disturb the C++ build flow. +// - An Xcode project file is hand-written XML that is unreadable in review and invites merge conflicts. +// - SwiftPM needs only a Package.swift and `swift build`, which is also consistent with building from source. // -// * CMake's Swift support is only available under the Ninja / Xcode generators, while this repository uses -// Unix Makefiles, and forcibly switching generators would disturb the existing C++ build flow; -// * An Xcode project file is unreadable, unreliably hand-written XML, and checking it in would only bring merge conflicts; -// * SwiftPM needs only a Package.swift and `swift build` suffices, which is also consistent with the source-distribution -// (Homebrew formula) route. +// SwiftPM produces only the executables. The .app bundle is assembled by Scripts/build-gui.sh, which puts +// together the Info.plist, icon and embedded dylib. // -// The .app bundle is assembled by Scripts/build-gui.sh -- SwiftPM produces only the executable, -// and the Info.plist, icon and embedded dylib are all put together in the script. +// Finding libtetherkitnext: build the C++ side first; its products are in /build/lib. The path is passed +// through an environment variable: // -// * How to find libtetherkitnext * +// export TETHERKITNEXT_LIB_DIR=$PWD/build/lib +// swift build --package-path gui // -// The C++ side is built first, with its products in /build/lib. The path is passed in via an environment variable: -// -// export TETHERKITNEXT_LIB_DIR=$PWD/build/lib -// swift build --package-path gui -// -// Scripts/build-gui.sh sets it up for you. When not set it falls back to the repository default build/lib, -// so a direct `swift build` inside the repository also works. +// Scripts/build-gui.sh sets it up. When unset it falls back to the repository default build/lib, so a direct +// `swift build` inside the repository also works. import Foundation import PackageDescription /// The directory where libtetherkitnext lives. /// -/// An absolute path is used: SwiftPM's working directory varies with how it is invoked, and a relative path would give different results between -/// `swift build --package-path gui` and `cd gui && swift build`. +/// An absolute path is used: SwiftPM's working directory varies with how it is invoked, and a relative path +/// would give different results between `swift build --package-path gui` and `cd gui && swift build`. let libraryDirectory: String = { if let fromEnvironment = ProcessInfo.processInfo.environment["TETHERKITNEXT_LIB_DIR"], !fromEnvironment.isEmpty { @@ -49,24 +45,23 @@ let libraryDirectory: String = { /// All the flags needed to link libtetherkitnext. /// -/// unsafeFlags must be used here -- SwiftPM has no safe interface for "add a library search path". -/// This package is the root package and will not be depended on by others, so the restriction of unsafeFlags does not apply. +/// unsafeFlags is needed because SwiftPM has no safe interface for "add a library search path". This package +/// is the root package and is not depended on by others, so the restriction on unsafeFlags does not apply. let tetherkitnextLinkerSettings: [LinkerSetting] = [ .unsafeFlags([ "-L\(libraryDirectory)", - // rpath must be passed to the linker segment by segment with -Xlinker. - // Writing it in gcc style "-Wl,-rpath,..." would be taken by swiftc as its own argument, - // reporting "unknown argument" -- this is not a link error but a rejection at the driver level. + // rpath must be passed to the linker one segment at a time with -Xlinker. The gcc style "-Wl,-rpath,..." + // would be taken by swiftc as its own argument and rejected with "unknown argument" at the driver level. // - // The three rpaths each have a purpose, and **the order matters** (dyld tries them one by one in declaration order): - // 1. ../Frameworks -- where the dylib is after being installed into the .app; - // 2. Next to the executable -- the helper is a bare executable, and the dylib is right beside it; - // 3. The build product directory -- so that `swift run` works directly during development. + // The three rpaths each have a purpose, and the order matters (dyld tries them in declaration order): + // 1. ../Frameworks: where the dylib is after being embedded in the .app; + // 2. next to the executable: the helper is a bare executable with the dylib right beside it; + // 3. the build product directory: so that `swift run` works directly during development. // - // The build directory must be placed **last**: it is an absolute path and certainly exists on the development machine. - // If placed earlier, the packaged .app on this machine would still load the copy in the build directory, - // and the embedded copy would never be verified -- only exposed on another machine, by which time it is too late. - // (Scripts/build-gui.sh also removes this rpath completely from release products.) + // The build directory must come last: it is an absolute path that exists on the build machine. Earlier, the + // packaged .app on that machine would still load the copy in the build directory, and the embedded copy + // would never be verified; the problem would only show on another machine. (Scripts/build-gui.sh also + // removes this rpath completely from release products.) "-Xlinker", "-rpath", "-Xlinker", "@executable_path/../Frameworks", "-Xlinker", "-rpath", "-Xlinker", "@executable_path", "-Xlinker", "-rpath", "-Xlinker", libraryDirectory, @@ -76,20 +71,26 @@ let tetherkitnextLinkerSettings: [LinkerSetting] = [ let package = Package( name: "TetherKitNextGUI", - // macOS 14: @Observable and ContentUnavailableView need it. The command-line part still - // supports 13.3; the two are independent products and need not be aligned. + // macOS 14: @Observable and ContentUnavailableView need it. The command-line part still supports 13.3; the + // two are independent products and need not be aligned. platforms: [.macOS(.v14)], products: [ .executable(name: "TetherKitNextApp", targets: ["TetherKitNextApp"]), .executable(name: "tetherkitnext-helper", targets: ["TetherKitNextHelper"]), ], + dependencies: [ + // Self-update (Sparkle 2): EdDSA-signed appcast, user-confirmed install and relaunch. + // Pinned exactly; SwiftPM checks the binary's checksum from Sparkle's own manifest. + // build-gui.sh embeds and re-signs Sparkle.framework; see SoftwareUpdater.swift. + .package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.1"), + ], targets: [ - // The C ABI's module map. The header is a symbolic link to include/tetherkitnext/capi/tetherkitnext_c.h, - // and therefore is always in sync with the C++ side, needing no generation step. + // The C ABI's module map. The header is a symbolic link to include/tetherkitnext/capi/tetherkitnext_c.h, so it + // is always in sync with the C++ side and needs no generation step. .target(name: "CTetherKitNext"), - // The XPC protocol and data models shared by the App and the helper. - // The two sides stay consistent through the same source code, rather than each copying its own. + // The XPC protocol and data models shared by the app and the helper. Both sides stay consistent through the + // same source code instead of each copying its own. .target(name: "TetherKitNextIPC"), // The C ABI's Swift wrapper: translates tk_* into Swift types and errors. @@ -101,11 +102,19 @@ let package = Package( .executableTarget(name: "TetherKitNextHelper", dependencies: ["TetherKitNextCore", "TetherKitNextIPC"]), - // The SwiftUI App that users see (running as an ordinary user). + // The SwiftUI app that users see (running as an ordinary user). .executableTarget(name: "TetherKitNextApp", - dependencies: ["TetherKitNextCore", "TetherKitNextIPC"]), + dependencies: ["TetherKitNextCore", "TetherKitNextIPC", + "TetherKitNextUIModel", + .product(name: "Sparkle", package: "Sparkle")]), + + // 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. It has 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 of sessions and NIC configuration are on the C++ side (tests/test_capi.cc), and are not repeated here. + // Tests cover the pure-logic layers (TetherKitNextIPC, TetherKitNextUIModel): no hardware, no root. + // Tests of sessions and interface configuration are on the C++ side (tests/test_capi.cc) and not repeated here. .testTarget(name: "TetherKitNextIPCTests", dependencies: ["TetherKitNextIPC"]), + .testTarget(name: "TetherKitNextUIModelTests", dependencies: ["TetherKitNextUIModel"]), ]) diff --git a/gui/Resources/App-Info.plist b/gui/Resources/App-Info.plist index 55ed1bf..3a26a46 100644 --- a/gui/Resources/App-Info.plist +++ b/gui/Resources/App-Info.plist @@ -3,7 +3,7 @@ Info.plist template for TetherKitNext.app. Scripts/build-gui.sh replaces __TETHERKITNEXT_VERSION__ with the real version number and copies it into - TetherKitNext.app/Contents/。 + TetherKitNext.app/Contents/. No entitlements are needed (hardened runtime, Developer ID): the app runs as the user and never touches USB or network interfaces itself; privileged work @@ -49,12 +49,27 @@ zh-Hans - TetherKitNextUpdateRepository AA-EION/TetherKitNext + + SUEnableAutomaticChecks + + SUScheduledCheckInterval + 86400 + SUAllowsAutomaticUpdates + + SUAutomaticallyUpdate + + + SUVerifyUpdateBeforeExtraction + + + LSMinimumSystemVersion 14.0 diff --git a/gui/Resources/Licenses/Sparkle-LICENSE.txt b/gui/Resources/Licenses/Sparkle-LICENSE.txt new file mode 100644 index 0000000..abe6e04 --- /dev/null +++ b/gui/Resources/Licenses/Sparkle-LICENSE.txt @@ -0,0 +1,134 @@ +Copyright (c) 2006-2013 Andy Matuschak. +Copyright (c) 2009-2013 Elgato Systems GmbH. +Copyright (c) 2011-2014 Kornel Lesiński. +Copyright (c) 2015-2017 Mayur Pawashe. +Copyright (c) 2014 C.W. Betts. +Copyright (c) 2014 Petroules Corporation. +Copyright (c) 2014 Big Nerd Ranch. +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================= +EXTERNAL LICENSES +================= + +bspatch.c and bsdiff.c, from bsdiff 4.3 : + +Copyright 2003-2005 Colin Percival +All rights reserved + +Redistribution and use in source and binary forms, with or without +modification, are permitted providing that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +-- + +sais.c and sais.h, from sais-lite (2010/08/07) : + +The sais-lite copyright is as follows: + +Copyright (c) 2008-2010 Yuta Mori All Rights Reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +-- + +Portable C implementation of Ed25519, from https://github.com/orlp/ed25519 + +Copyright (c) 2015 Orson Peters + +This software is provided 'as-is', without any express or implied warranty. In no event will the +authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial +applications, and to alter it and redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not claim that you wrote the + original software. If you use this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be misrepresented as + being the original software. + +3. This notice may not be removed or altered from any source distribution. + +-- + +SUSignatureVerifier.m: + +Copyright (c) 2011 Mark Hamlin. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted providing that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/gui/Scripts/build-gui.sh b/gui/Scripts/build-gui.sh index 4d9d841..f547f4d 100755 --- a/gui/Scripts/build-gui.sh +++ b/gui/Scripts/build-gui.sh @@ -9,11 +9,16 @@ # ./gui/Scripts/build-gui.sh --debug # debug Swift build # # Signing (environment): +# TETHERKITNEXT_SPARKLE_PUBLIC_KEY +# Sparkle EdDSA public key (base64). Set → the app updates itself from +# SUFeedURL; unset → check-only. +# TETHERKITNEXT_SPARKLE_FEED_URL +# appcast URL (default: this repository's latest release asset +# appcast.xml). # TETHERKITNEXT_SIGN_IDENTITY codesign identity, e.g. -# "Developer ID Application: Jane Doe (ABCDE12345)". -# Unset → ad-hoc signature (local development only: -# no hardened runtime, XPC falls back to the -# authorization-only check, SMAppService may refuse). +# "Developer ID Application: Jane Doe (ABCDE12345)". Unset → ad-hoc +# signature (local development only: no hardened runtime, XPC falls back +# to the authorization-only check, SMAppService may refuse). # # Architectures: the Swift targets are built for every architecture that # libtetherkitnext.dylib contains and merged with lipo, so a C++ build configured @@ -25,7 +30,7 @@ # Contents/MacOS/tetherkitnext-cli command-line tool (linked into # /usr/local/bin from the app on request) # Contents/MacOS/tetherkitnext-helper root daemon (SMAppService BundleProgram) -# Contents/Frameworks/ libtetherkitnext + libusb (@rpath) +# Contents/Frameworks/ libtetherkitnext + libusb (@rpath), Sparkle.framework # Contents/Library/LaunchDaemons/ com.tetherkitnext.helperd.plist # Contents/Resources/Licenses/ TetherKitNext (MIT) and libusb (LGPL-2.1) set -euo pipefail @@ -80,16 +85,63 @@ 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 +# Sparkle.framework (universal, prebuilt by the Sparkle project; SwiftPM +# verified its checksum when resolving the package). +SPARKLE_FRAMEWORK="$(find "${GUI_DIR}/.build/artifacts" -type d \ + -path '*Sparkle.xcframework/macos-*/Sparkle.framework' -prune 2>/dev/null | head -1)" +[[ -d "${SPARKLE_FRAMEWORK}" ]] || die "Sparkle.framework not found under gui/.build/artifacts" + # ------------------------------------------------------------------------------ # Bundle layout # ------------------------------------------------------------------------------ @@ -107,12 +159,27 @@ cp "${BIN_DIR}/tetherkitnext-cli" "${CONTENTS}/MacOS/tetherkitnext-cli" sed -e "s/__TETHERKITNEXT_VERSION__/${VERSION}/g" -e "s/__TETHERKITNEXT_BUILD__/${BUILD_NUMBER}/g" \ "${GUI_DIR}/Resources/App-Info.plist" > "${CONTENTS}/Info.plist" +# Self-update is configured only when a Sparkle public key is supplied (the +# release workflow does that when it holds the matching private key). +if [[ -n "${TETHERKITNEXT_SPARKLE_PUBLIC_KEY:-}" ]]; then + feed_url="${TETHERKITNEXT_SPARKLE_FEED_URL:-https://github.com/AA-EION/TetherKitNext/releases/latest/download/appcast.xml}" + plutil -insert SUFeedURL -string "${feed_url}" "${CONTENTS}/Info.plist" + plutil -insert SUPublicEDKey -string "${TETHERKITNEXT_SPARKLE_PUBLIC_KEY}" "${CONTENTS}/Info.plist" + echo " self-update: ${feed_url}" +else + echo " self-update: off (no TETHERKITNEXT_SPARKLE_PUBLIC_KEY; check-only)" +fi plutil -lint "${CONTENTS}/Info.plist" >/dev/null cp "${GUI_DIR}/Resources/AppIcon.icns" "${CONTENTS}/Resources/" cp "${GUI_DIR}/Resources/com.tetherkitnext.helperd.plist" "${CONTENTS}/Library/LaunchDaemons/" plutil -lint "${CONTENTS}/Library/LaunchDaemons/com.tetherkitnext.helperd.plist" >/dev/null cp "${REPO_ROOT}/LICENSE" "${CONTENTS}/Resources/Licenses/TetherKitNext-LICENSE.txt" cp "${REPO_ROOT}/NOTICE.md" "${CONTENTS}/Resources/Licenses/NOTICE.md" +cp "${GUI_DIR}/Resources/Licenses/Sparkle-LICENSE.txt" "${CONTENTS}/Resources/Licenses/" + +# ditto keeps the framework's Versions/Current symlinks (codesign rejects a +# flattened copy). +ditto "${SPARKLE_FRAMEWORK}" "${CONTENTS}/Frameworks/Sparkle.framework" # libtetherkitnext: a single real file named after its install name # (@rpath/libtetherkitnext..dylib). Copying the versioned symlinks too @@ -192,6 +259,14 @@ else fi sign() { codesign "${SIGN_FLAGS[@]}" "$@" >/dev/null; } +# Sparkle, innermost first, as its documentation prescribes for re-signing; +# the Downloader service keeps its entitlements. +SPARKLE_B="${CONTENTS}/Frameworks/Sparkle.framework/Versions/B" +sign "${SPARKLE_B}/XPCServices/Installer.xpc" +sign --preserve-metadata=entitlements "${SPARKLE_B}/XPCServices/Downloader.xpc" +sign "${SPARKLE_B}/Autoupdate" +sign "${SPARKLE_B}/Updater.app" +sign "${CONTENTS}/Frameworks/Sparkle.framework" sign "${CONTENTS}/Frameworks/${libusb_name}" sign "${CONTENTS}/Frameworks/${tetherkitnext_dylib}" sign --identifier com.tetherkitnext.cli "${CONTENTS}/MacOS/tetherkitnext-cli" @@ -211,6 +286,9 @@ while IFS= read -r -d '' file; do for arch in "${ARCHS[@]}"; do [[ " ${archs} " == *" ${arch} "* ]] || die "${file#"${APP_DIR}/"} lacks ${arch} (has: ${archs})" done + # Sparkle's own executables are upstream's build and resolve their links + # inside the framework; only their architectures are checked here. + [[ "${file}" == "${CONTENTS}/Frameworks/Sparkle.framework/"* ]] && continue # Dependency lines are tab-indented; header lines ("file (architecture x):") # are not. while read -r dependency; do @@ -234,6 +312,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 <\033[0m %s\n' "$1"; } diff --git a/gui/Sources/TetherKitNextApp/AppModel.swift b/gui/Sources/TetherKitNextApp/AppModel.swift index 9b5bb87..fd9986a 100644 --- a/gui/Sources/TetherKitNextApp/AppModel.swift +++ b/gui/Sources/TetherKitNextApp/AppModel.swift @@ -3,9 +3,10 @@ import Observation import SwiftUI import TetherKitNextCore import TetherKitNextIPC +import TetherKitNextUIModel /// The instantaneous rate obtained from one sample. -struct ThroughputSample: Identifiable { +struct ThroughputSample: Identifiable, Equatable { let id = UUID() let timestamp: Date let receiveBitsPerSecond: Double @@ -20,9 +21,9 @@ struct ThroughputSample: Identifiable { /// Consecutive repeated logs are folded into one. /// -/// Periodic paths (such as device enumeration once every 2 seconds) flood the same sentence into a whole column, drowning the lines that really -/// carry information; folding into "one line x N" carries the same information. The id is taken from the first entry -- repeats only update the -/// count and timestamp, and the row's identity stays unchanged, so the list need not rebuild whole rows. +/// Periodic paths (such as device enumeration every 2 seconds) would otherwise fill the whole column with +/// the same sentence and drown the informative lines. The id comes from the first entry; repeats only update +/// the count and timestamp, so the row keeps its identity and the list need not rebuild it. struct CollapsedLogEntry: Identifiable { let first: LogEntry private(set) var latest: LogEntry @@ -35,7 +36,8 @@ struct CollapsedLogEntry: Identifiable { var id: UUID { first.id } - /// Only entries identical apart from the timestamp count as repeats -- messages carrying changing values (addresses, counts) should stay on separate lines. + /// Only entries identical apart from the timestamp count as repeats: messages that carry changing values + /// (addresses, counts) stay on separate lines. func matches(_ entry: LogEntry) -> Bool { entry.level == first.level && entry.thread == first.thread && entry.message == first.message @@ -47,15 +49,15 @@ struct CollapsedLogEntry: Identifiable { } } -/// The reachability of the helper. The UI uses it to decide between "show install guidance" and "work normally". +/// The reachability of the helper. The UI uses it to choose between the setup steps and normal operation. enum HelperAvailability: Equatable { case unknown case available(version: String) case missing(reason: String) - /// The installed helper is older (or newer) than the current App, and the XPC interface does not match. + /// The installed helper speaks a different XPC protocol revision than this app. /// - /// A separate state rather than merged into missing: the remedies for the two cases differ, - /// one being "go install" and the other "go reinstall", and the hint text must be able to tell them apart. + /// A separate state rather than part of `missing`: the setup page must tell "not registered" apart from + /// "registered but incompatible". case outdated(installed: Int, expected: Int) var isAvailable: Bool { @@ -64,22 +66,16 @@ enum HelperAvailability: Equatable { } } -/// The installed privileged component is not the same version as the one the App bundles. +/// The running background component differs in version or build from the one this app bundles. /// -/// * Division of labor with `HelperAvailability.outdated` * -/// That one is about a **protocol mismatch**: the method signatures are no longer consistent, and calling further would either hang or crash, -/// so it must be stopped at the install guidance page. This one is about **the protocol still being compatible but the version differing** -- -/// the component works as usual, but it still contains the pre-upgrade libtetherkitnext, and the problems fixed in the new version have not been fixed -/// at all on the side that really does the work (`brew upgrade` only replaces the .app and cannot touch -/// /Library/PrivilegedHelperTools). -/// -/// So it does not block the way, and only lights up an "Update privileged component" in the management row. For versions where the protocol number is unchanged -/// (like 0.1.4 -> 0.1.5) there used to be no hint at all, and the only sign the user could notice was -/// "the bug the release notes say was fixed is still there". +/// After the app is replaced the daemon keeps running the old binary until it is restarted. The protocol is +/// still compatible, so the app keeps working and offers "Restart background component". This differs from +/// `HelperAvailability.outdated`, where the protocol itself does not match and further calls would hang or +/// crash, so the UI stops at the setup page. struct HelperVersionMismatch: Equatable { - /// The installed one, taking only the version number (such as `"0.1.3"`). + /// The running component's version, e.g. `"0.1.3"`. let installed: String - /// The one the App bundles -- the version that will be installed after the button is clicked. + /// The version this app bundles, which the restart brings in. let expected: String } @@ -88,50 +84,51 @@ enum UpdateCheckResult: Equatable { case upToDate(current: String) case updateAvailable(UpdateChecker.Release) case failed(String) - /// A development build (the bare executable from `swift run`) has no version number and cannot be compared. + /// A development build (the bare executable from `swift run`) has no version number to compare. case unavailable } /// All of the UI's state and actions. /// -/// * Why everything goes through the helper rather than the App calling the library itself * -/// The App runs as an ordinary user, and creating feth and opening BPF both need root, so a session can only run inside -/// the helper. Device enumeration and the environment preflight, although they need no root, also go uniformly through the helper -- once a session is running -/// the device is held exclusively by the helper, and the App reading it again would only get inconsistent results. +/// Everything goes through the helper rather than calling the library directly. The app runs as an ordinary +/// user, and creating feth and opening BPF need root, so a session can only run inside the helper. Device +/// enumeration and the environment preflight need no root but also go through it: while a session runs the +/// helper holds the device exclusively, so reading it from the app would give inconsistent results. @Observable @MainActor final class AppModel { // MARK: - State exposed to the UI private(set) var helperAvailability: HelperAvailability = .unknown - /// The two version numbers when the installed component and the App version do not match; nil when consistent (or not yet probed). + /// The two version numbers when the running component differs from this app; nil when they match or are unknown. private(set) var helperVersionMismatch: HelperVersionMismatch? private(set) var environment: EnvironmentReport? private(set) var devices: [DeviceDescriptor] = [] private(set) var status: SessionStatus = .idle + /// Why the last session failed, kept after the daemon reports `.idle` again (see `SessionFailure`). + /// Cleared by `dismissFailure()` or a new session. + private(set) var lastFailure: SessionFailure? private(set) var networkState: NetworkState = .empty private(set) var throughput: ThroughputSample = .zero private(set) var throughputHistory: [ThroughputSample] = [] private(set) var logs: [LogEntry] = [] private(set) var droppedLogCount: UInt64 = 0 - /// The daemon is registered but the user has not approved it in System - /// Settings › Login Items yet. + /// The daemon is registered but the user has not approved it in System Settings › Login Items yet. private(set) var helperNeedsApproval = false - /// `installHelper()` is restarting the daemon; it is briefly unreachable. + /// `installHelper()` is restarting the daemon, which is briefly unreachable. private var isRestartingHelper = false /// State of the `/usr/local/bin/tetherkitnext-cli` link. private(set) var commandLineToolState: CommandLineToolState = .current - /// The one the user selected in the device list. nil means "use the first one found". + /// The device selected in the list; nil means the first one found. var selectedDeviceID: String? /// The user-adjustable part of the session configuration. var requestedMTU: UInt32 = 1500 var adoptDeviceMAC: Bool = true /// The network configuration form. /// - /// Persisted, so a choice like "route all traffic through this interface" - /// sticks across launches and the automatic configuration on Connect - /// applies it every time. + /// Persisted, so a choice like "route all traffic through this interface" sticks across launches and + /// applies on every Connect. var networkConfiguration: NetworkConfiguration = .dhcp { didSet { guard networkConfiguration != oldValue, @@ -149,12 +146,12 @@ final class AppModel { networkConfiguration = stored } - /// The UI language preference. Changing it does **three** things at once: switches the Swift-side message table, pushes the language to - /// libtetherkitnext (otherwise another language would get mixed into the log card), and then pushes it to the helper (which runs as root - /// under launchd and cannot see the user's language preference). + /// The UI language preference. Changing it updates three places: the Swift message table, libtetherkitnext + /// (otherwise the log card mixes languages) and the helper (root under launchd, so it cannot see the user's + /// preference). /// - /// `didSet` also increments `languageRevision` -- messages are looked up from a global table, - /// and SwiftUI has no way to know they changed, so this value is used to rebuild the whole view tree once. + /// `didSet` also increments `languageRevision`: messages come from a global table that SwiftUI cannot + /// observe, so the revision forces one rebuild of the view tree. var languagePreference: LanguagePreference = .system { didSet { guard languagePreference != oldValue else { return } @@ -162,17 +159,29 @@ final class AppModel { } } - /// How many times the language has changed. `.id(model.languageRevision)` is attached at the view root, and it triggers the rebuild. + /// How many times the language has changed. `.id(model.languageRevision)` on the view root triggers the rebuild. private(set) var languageRevision = 0 - /// Waiting for some privileged operation to complete -- the UI uses it to disable buttons and show progress. + /// A privileged operation is in progress; the UI disables buttons and shows progress. private(set) var isBusy: Bool = false - /// An error that needs to be popped up to the user. - var alertMessage: String? + /// A start request is in flight (authorization, enumeration, the daemon call) before the session itself + /// reports `.starting`. Distinct from `isBusy`, which other actions (restarting the background component) + /// also set. + private(set) var isStartingSession = false + /// An error to show to the user. + var alertMessage: String? { + didSet { + // The alert is attached to the main window. In menu-bar-only mode (window ordered out) a failure from the + // menu bar panel's Connect would stay invisible until the window is next opened, so bring the window up. + if alertMessage != nil, MainWindowController.shared?.isVisible == false { + MainWindowController.shared?.present() + } + } + } - /// The known new version. Drives the "new version available" hint in the management row; nil = none or never checked. + /// The known new version. Drives the "new version available" hint in Settings; nil = none or never checked. private(set) var availableUpdate: UpdateChecker.Release? - /// The popup of the manual "check for updates" result. Set back to nil when the view dismisses the popup. + /// The result of the manual "check for updates" popup; set back to nil when the view dismisses it. var updateCheckResult: UpdateCheckResult? var logLevelFilter: LogLevel = .info @@ -181,27 +190,25 @@ final class AppModel { private let client = HelperClient() private var pollingTask: Task? - /// The previous state snapshot, used to compute rates by differencing. + /// The previous status snapshot, used to compute rates by differencing. private var previousStatus: SessionStatus? private var sessionStartedAt: Date? - /// The moment of the last device enumeration. A monotonic clock is used, avoiding negative intervals when the system time is adjusted. + /// The moment of the last device enumeration. A monotonic clock avoids negative intervals when the system time + /// changes. 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 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. + /// The cached authorization token. nil means the next privileged operation shows the 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), - /// and computing our own copy would only disagree with the system. Going by the helper's verification result is more reliable. + /// There is no expiry time of our own: the system timeout comes from the authorization database (an + /// administrator can change it), so a local copy could only disagree. The helper's verification result decides. private var cachedAuthorization: AuthorizationToken? - /// The daemon refused a Touch ID-confirmed request (the user is not an - /// administrator). Use the administrator dialog for the rest of this run. + /// The daemon refused a Touch ID-confirmed request (the user is not an administrator). The administrator + /// dialog is used for the rest of this run. private var presenceRejected = false @@ -209,33 +216,32 @@ final class AppModel { /// Polling period. /// - /// 500 ms is the balance point between "looks real-time" and "do not turn XPC round trips into a burden": faster makes no difference - /// to the human eye, and slower makes the rate curve look choppy. + /// 500 ms balances "looks real-time" against XPC round-trip load: faster is invisible to the eye, slower + /// makes the rate curve choppy. private static let pollInterval: Duration = .milliseconds(500) - /// The polling interval in pure background standby (window closed, no session running). + /// The polling interval in background standby (window closed, no session running). private static let backgroundPollInterval: Duration = .seconds(2) /// The minimum interval of device enumeration. /// - /// Much slower than state polling, because enumeration needs libusb_open to read string descriptors. A 2-second plug/unplug - /// response delay is basically imperceptible to the user, while the overhead drops to a quarter of the original. + /// Enumeration needs libusb_open to read string descriptors, so it runs much slower than status polling. + /// A 2-second plug/unplug delay is imperceptible and cuts the overhead to a quarter. private static let deviceRefreshInterval: Duration = .seconds(2) - /// The number of sample points the throughput curve retains. 120 points x 500 ms = the most recent 60 seconds. + /// The number of throughput samples kept. 120 points x 500 ms = the last 60 seconds. private static let historyCapacity = 120 - /// The number of lines the log panel retains. + /// The number of log lines kept. /// - /// 2000 lines are enough to look back over a whole startup sequence plus several minutes of running; more than that and SwiftUI's list starts to lag. + /// 2000 lines cover a whole startup sequence plus several minutes of running; more makes SwiftUI's list lag. private static let logCapacity = 2000 // MARK: - Lifecycle - /// Applies a language preference: this process -> libtetherkitnext -> helper, not one place may be missed. + /// Applies a language preference to this process, libtetherkitnext and the helper; all three must be updated. /// - /// UserDefaults is written only here, and read in `restoreLanguagePreference()` -- - /// both sides use the same key-name constant, so a rename cannot miss half. + /// UserDefaults is written only here and read in `restoreLanguagePreference()`, which share one key constant. func applyLanguage(_ preference: LanguagePreference) { let resolved = L10n.apply(preference) TetherKitNextLibrary.setLanguage(resolved) @@ -244,12 +250,12 @@ final class AppModel { Task { await client.setLanguage(resolved) } } - /// Restores the language chosen last time at startup. If never saved it is `.system`. + /// Restores the language chosen last time; `.system` if none was saved. private func restoreLanguagePreference() { let stored = UserDefaults.standard.string(forKey: Self.languageDefaultsKey) let preference = stored.flatMap(LanguagePreference.init(rawValue:)) ?? .system - // Writing the stored property directly would trigger didSet to save to disk once more, so bypass it: this is a "restore", - // not "the user changed it". + // Setting the stored property would run didSet and save again, so apply directly when unchanged: + // this is a restore, not a user change. if preference != languagePreference { languagePreference = preference } else { @@ -261,61 +267,52 @@ final class AppModel { func start() { guard pollingTask == nil else { return } + // First: whether this install existed before layouts must be measured before anything below writes a + // preference (language, window frame, updater state). + decideInterfaceStyle() + networkWatcher.start() restoreLanguagePreference() restoreNetworkConfiguration() pollingTask = Task { [weak self] in while !Task.isCancelled { guard let self else { return } await self.refresh() - // The interval is dynamic: keep it smooth while a session is running or the window is open, and slow down in pure background standby. + // The interval is dynamic: smooth while a session runs or the window is open, slower in background + // standby. try? await Task.sleep(for: self.pollDelay) } } restoreKnownUpdate() + // Starts Sparkle (when this build is configured for it) with the user's setting. + SoftwareUpdater.shared.setAutomaticallyChecks( + !UserDefaults.standard.bool(forKey: Self.updateCheckDisabledKey)) Task { await checkForUpdatesQuietly() } } - func stopPolling() { - pollingTask?.cancel() - pollingTask = nil - } - /// The main window appears (including reopening from the menu bar). /// - /// Refresh once immediately rather than waiting for the next period: background polling may be sleeping in a 2-second long interval, - /// and the first glance the user gets when opening the window should not be stale data. + /// Refreshes at once: background polling may be sleeping in its 2-second interval, and the first glance at + /// the opened window should not show stale data. func windowDidAppear() { + // Called on every key-window change (sheets, alerts, app switches). Refresh only when the window was really + // hidden: an extra refresh() interleaves with the polling loop's own at every await and can apply replies + // out of order. + guard !isWindowVisible else { return } isWindowVisible = true Task { await refresh() } } - /// The main window closes. The App moves into background mode; polling continues (the menu bar relies on it for data) but slows down. + /// The main window closes. The app moves to background mode; polling continues (the menu bar needs the data) but + /// slows down. func windowDidDisappear() { 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. + /// The polling interval to use right now. /// - /// 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 - /// (the user is waiting for a result), and the window is open (the user is looking). Only "pure background standby" slows down -- - /// then the only output of polling is helper liveness probing and device scanning, and nobody needs them every half second. + /// The fast pace applies while a session runs (the menu bar shows live rates), while it starts or stops + /// (the user is waiting), and while the window is open. Only background standby slows down: polling then + /// only probes the helper and scans devices, which nobody needs every half second. private var pollDelay: Duration { let sessionActive = status.runState == .running || status.runState.isTransitional return sessionActive || isWindowVisible ? Self.pollInterval : Self.backgroundPollInterval @@ -330,25 +327,33 @@ final class AppModel { guard revision == HelperConstants.protocolRevision else { helperAvailability = .outdated(installed: revision, expected: HelperConstants.protocolRevision) - // When the protocol does not match, do not additionally report a version mismatch: that card is meant to make the user update the component anyway, - // and saying the same thing twice would only make people suspect there are two problems. + // With a protocol mismatch, do not also report a version mismatch: both prompt the same component + // update, and two messages would suggest two problems. helperVersionMismatch = nil - // If the interface does not match, do not keep sending requests -- the shapes of both parameters and replies may be inconsistent. + // With a mismatched interface, stop sending requests: parameter and reply shapes may differ. return } helperAvailability = .available(version: version) helperVersionMismatch = Self.versionMismatch(installed: version, build: build) + // A daemon that just appeared (registered, approved, restarted or updated) starts in its default language; + // the push in applyLanguage only happens on a change. + let daemonIdentity = "\(version)|\(String(describing: build))" + if languageSyncedDaemon != daemonIdentity { + languageSyncedDaemon = daemonIdentity + let language = L10n.language + Task { await client.setLanguage(language) } + } helperNeedsApproval = false commandLineToolState = .current } catch { - // While the daemon restarts it is briefly unreachable. Keep what we - // had instead of flashing the setup steps as if it were not installed. + // While the daemon restarts it is briefly unreachable. Keep what we had instead of flashing the setup + // steps as if it were not registered. if isRestartingHelper { return } + languageSyncedDaemon = nil helperAvailability = .missing(reason: error.localizedDescription) helperVersionMismatch = nil helperNeedsApproval = HelperInstaller.needsApproval - // If it cannot connect, do not send subsequent requests -- each would repeat the same failure, - // and only flood the log. + // If it cannot connect, stop here: every further request would repeat the same failure and flood the log. return } @@ -364,21 +369,21 @@ final class AppModel { apply(feed: feed) } - // The device list is refreshed only when not running: while running the device is held exclusively and the list should not change. + // The device list is refreshed only when no session runs: a running session holds the device exclusively. // - // And **refreshed more slowly than state**. One enumeration has to read USB string descriptors, which needs - // libusb_open to really open the device once -- doing this at the 500 ms state-polling pace - // amounts to opening and closing the user's device twice a second, both wasteful and possibly disruptive to it. A 2-second slower plug/unplug response - // does not affect the perceived experience at all. + // It is also refreshed more slowly than status. Enumeration reads USB string descriptors, which needs + // libusb_open to really open the device; at the 500 ms status pace that would open and close the user's + // device twice a second, which is wasteful and may disturb it. // - // The exception: when an active session just ended (e.g. device unplugged), refresh immediately so the list is not stale. + // Exception: when an active session just ended (e.g. the device was unplugged), refresh at once so the + // list is not stale. let sessionJustEnded = wasActive && (status.runState != .running && status.runState != .starting) if status.runState != .running, (sessionJustEnded || shouldRefreshDevices()) { if let fresh = try? await client.listDevices() { devices = fresh - // After the device the user selected is unplugged, the selection must be invalidated with it, otherwise "Start" would look for a device by a - // nonexistent bus address. + // If the selected device was unplugged, drop the selection; otherwise "Start" would look for a device + // at a nonexistent bus address. if let selected = selectedDeviceID, !devices.contains(where: { $0.id == selected }) { selectedDeviceID = nil @@ -392,6 +397,30 @@ final class AppModel { } else { networkState = .empty } + + restartHelperAfterUpdateIfNeeded() + evaluateAutoConnect() + } + + /// After Sparkle replaced the app, the daemon still runs the old binary (launchd does not notice). Restart + /// it once its build differs, but never under a running session: restarting the daemon ends the session, so + /// the flag then waits for the session to end (the "restart the background component" prompt stays visible). + private func restartHelperAfterUpdateIfNeeded() { + let defaults = UserDefaults.standard + let key = SoftwareUpdater.restartHelperAfterUpdateKey + guard defaults.bool(forKey: key), helperAvailability.isAvailable else { return } + guard helperVersionMismatch != nil else { + defaults.removeObject(forKey: key) // the daemon already matches + return + } + switch status.runState { + case .idle, .stopped, .failed: + guard !isBusy else { return } + defaults.removeObject(forKey: key) + Task { await installHelper() } + case .starting, .running, .stopping: + return + } } @@ -401,24 +430,34 @@ final class AppModel { status = fresh } - // Record/clear the connection moment, used to display the connected duration. + if fresh.runState == .failed, !fresh.fatalMessage.isEmpty { + lastFailure = SessionFailure(message: fresh.fatalMessage) + } else if fresh.runState == .running { + lastFailure = nil + } + if fresh.runState == .running, sessionStartedAt == nil { sessionStartedAt = Date() } else if fresh.runState != .running, fresh.runState != .stopping { sessionStartedAt = nil + sessionOnlyAddress = nil + autoConfigureNote = nil } + // Both snapshots must come from the same running session: after a failed session a new one starts with + // counters back near zero, and the wrapping deltas below would plot a rate of ~10^19 bit/s. guard let previous = previousStatus, - fresh.runState == .running, - fresh.monotonicNanos > previous.monotonicNanos else { + fresh.runState == .running, previous.runState == .running, + fresh.monotonicNanos > previous.monotonicNanos, + fresh.rxBytes >= previous.rxBytes, fresh.txBytes >= previous.txBytes else { if fresh.runState != .running { throughput = .zero } return } - // The denominator uses the difference of the library's monotonic clock rather than our polling period -- the real - // interval between two pulls gets stretched by scheduling, and using a fixed period as the denominator would overestimate the rate. + // The denominator is the library's monotonic clock difference, not our polling period: scheduling stretches + // the real interval between pulls, and a fixed period would overestimate the rate. let seconds = Double(fresh.monotonicNanos - previous.monotonicNanos) / 1_000_000_000 guard seconds > 0 else { return } @@ -453,6 +492,75 @@ final class AppModel { sessionStartedAt.map { Date().timeIntervalSince($0) } } + /// What kind of link the device is: internet-capable or a local device. + /// + /// Re-judged from evidence on every poll and never stored per device, so a phone that is merely slow is not + /// remembered as "local" (LinkAssessment). + var linkAssessment: LinkAssessment { + LinkAssessment.assess(isRunning: status.runState == .running, + connectedFor: connectedDuration ?? 0, + mode: networkConfiguration.mode, + network: networkState, + peerAddress: status.peerAddress) + } + + /// The status line shown in the window and the menu bar. A running link to a local device reads + /// "Connected · local device" rather than suggesting internet. + var statusLabel: String { + if status.runState == .running, status.linkUp, linkAssessment.isLocalOnly { + return L(.statusConnectedLocal) + } + return Design.statusLabel(for: status) + } + + /// An address applied for the current session only (local devices without DHCP). Never written to + /// `networkConfiguration`: the next phone must not inherit a fixed address meant for a drone. Cleared when + /// the session ends. + private(set) var sessionOnlyAddress: String? + + /// The daemon (version + build) the UI language was last pushed to; nil when unreachable. + @ObservationIgnored private var languageSyncedDaemon: String? + + /// Why automatic configuration after Connect did not finish (no lease, no router). Shown as a quiet detail + /// next to the link assessment instead of an alert, since for a local device this is expected. Cleared per + /// session. + private(set) var autoConfigureNote: String? + + /// Applies `address` (/24, no router, no DNS) to the interface for this session only, for devices with a + /// fixed address and no DHCP server. + func useSessionOnlyAddress(_ address: String) async { + guard !isBusy else { return } + let interface = status.systemInterface + guard !interface.isEmpty else { + alertMessage = L(.interfaceNotReadyYet) + return + } + let configuration = NetworkConfiguration(mode: .manual, address: address, + netmask: "255.255.255.0") + if let message = NetworkValidator.validationMessage(for: configuration) { + alertMessage = message + return + } + isBusy = true + defer { isBusy = false } + let applied = await authorized { [self] authorization in + try await client.applyNetwork(authorization: authorization, interface: interface, + configuration: configuration) + networkState = (try? await client.queryNetwork(interface: interface)) ?? .empty + } + if applied { + sessionOnlyAddress = address + autoConfigureNote = nil + } + } + + /// Drops a session-only address and re-applies the saved settings (normally DHCP), e.g. when a slow device + /// finally starts its DHCP server. The apply itself clears the session-only address and the auto-configure + /// note, and only if it succeeds. + func retrySavedNetworkConfiguration() async { + await applyNetworkConfiguration() + } + var selectedDevice: DeviceDescriptor? { if let selectedDeviceID { return devices.first { $0.id == selectedDeviceID } @@ -460,11 +568,11 @@ final class AppModel { return devices.first } - /// The log after filtering + consecutive deduplication. + /// The log after filtering and consecutive deduplication. /// - /// Folding is placed **after** filtering: two identical INFO entries in the raw stream may have a trace between them, - /// so folding in raw order would fail, while the adjacent repeats the user sees at some level are what should be merged. - /// Recomputed in O(n), n <= 2000, imperceptible at a 500 ms refresh pace. + /// Folding comes after filtering: two identical INFO entries in the raw stream may have a trace entry + /// between them, while the adjacent repeats the user sees at the chosen level should merge. + /// Recomputed in O(n) with n <= 2000, which is cheap at a 500 ms refresh. var filteredLogs: [CollapsedLogEntry] { var collapsed: [CollapsedLogEntry] = [] for entry in logs where entry.level >= logLevelFilter { @@ -481,13 +589,26 @@ final class AppModel { func startSession() async { guard !isBusy else { return } isBusy = true - defer { isBusy = false } + isStartingSession = true + defer { + isBusy = false + isStartingSession = false + } + + lastFailure = nil + + // Enumerate again first: turning USB tethering on makes Android re-enumerate with a new bus address, and + // the list may be up to one refresh period old. + await refreshDevices() var configuration = SessionConfiguration(mtu: requestedMTU, adoptDeviceMAC: adoptDeviceMAC) - // Specify bus + address rather than VID/PID: two devices of the same model have exactly the same VID/PID, - // and only the bus address can tell them apart. + // Bus + address tell apart two devices of the same model; VID/PID are passed too. The C filter requires + // every given field to match, so if the address went stale and now belongs to another device, the start + // fails instead of claiming the wrong one. if let device = selectedDevice { + configuration.vendorID = device.vendorID + configuration.productID = device.productID configuration.busNumber = device.busNumber configuration.deviceAddress = device.deviceAddress } @@ -506,25 +627,27 @@ final class AppModel { /// Defaults key for "configure the network automatically on connect". static let autoConfigureNetworkKey = "autoConfigureNetworkOnConnect" - /// One-click internet: once the virtual interface exists, apply the - /// addressing mode chosen on the Network page — DHCP unless the user set - /// up something else — so Connect alone brings the tethered link up. + /// One-click internet: once the virtual interface exists, apply the addressing mode chosen on the Network + /// page (DHCP unless the user set up something else), so Connect alone brings the tethered link up. /// - /// Runs inside startSession's busy window and reuses the authorization - /// token Connect just obtained, so there is no second password prompt. - /// Skipped when the mode is "don't configure", when a static form is - /// incomplete, or when the interface already has an address (e.g. a - /// persistent network service picked it up by itself). + /// Runs inside startSession's busy window and reuses the authorization token Connect just obtained, so + /// there is no second prompt. Skipped when the mode is "don't configure", when a static form is incomplete, + /// or when the interface already has an address (e.g. a persistent network service picked it up). private func configureNetworkAfterConnect() async { guard networkConfiguration.mode != .none, NetworkValidator.validationMessage(for: networkConfiguration) == nil else { return } - // The session reaches running (and names its interface) only after the - // RNDIS handshake and feth creation; poll for that, bounded. + // The session reaches running (and names its interface) only after the RNDIS handshake and feth creation; + // poll for that, bounded. var interface = "" for _ in 0..<60 { guard let fresh = try? await client.sessionStatus() else { return } - if fresh.runState == .failed || fresh.runState == .stopped { return } + if fresh.runState == .failed || fresh.runState == .stopped { + // The daemon reports a failure once and then drops the session, so this read may be the only one that + // carries the reason. + apply(status: fresh) + return + } if fresh.runState == .running, !fresh.systemInterface.isEmpty { interface = fresh.systemInterface break @@ -541,12 +664,92 @@ final class AppModel { let configuration = networkConfiguration await authorized { [self] authorization in - try await client.applyNetwork(authorization: authorization, interface: interface, - configuration: configuration) + do { + try await client.applyNetwork(authorization: authorization, interface: interface, + configuration: configuration) + } catch let failure as HelperClient.Failure where failure.isAuthorizationProblem { + throw failure // let `authorized` re-prompt + } catch { + // No alert: a device without a DHCP server or router is a normal local link, not a failure. The live + // link assessment explains it and offers what to do next. + autoConfigureNote = error.localizedDescription + } networkState = (try? await client.queryNetwork(interface: interface)) ?? .empty } } + // MARK: - Layout + + /// The main window's layout; nil until a new user has chosen (the chooser appears right after the setup assistant). + private(set) var interfaceStyle: InterfaceStyle? + /// The one-time "new: simple view" announcement for updated installs. + private(set) var interfaceStyleAnnouncementPending = false + @ObservationIgnored private let interfaceStylePreference = InterfaceStylePreference() + + private func decideInterfaceStyle() { + let hadPreferences = Bundle.main.bundleIdentifier + .flatMap { UserDefaults.standard.persistentDomain(forName: $0) } + .map { !$0.isEmpty } ?? false + interfaceStylePreference.migrateIfNeeded(hadPreferencesBefore: hadPreferences) + interfaceStyle = interfaceStylePreference.style + interfaceStyleAnnouncementPending = interfaceStylePreference.announcementPending + } + + func setInterfaceStyle(_ style: InterfaceStyle) { + interfaceStylePreference.style = style + interfaceStyle = style + dismissInterfaceStyleAnnouncement() + } + + func dismissInterfaceStyleAnnouncement() { + interfaceStylePreference.announcementPending = false + interfaceStyleAnnouncementPending = false + } + + // MARK: - Auto-connect + + static let autoConnectKey = "autoConnectEnabled" + + /// "Connect automatically when a device is plugged in". Off by default; the rules (never with Wi-Fi/Ethernet, + /// once per plug-in) are in AutoConnectPolicy. + var autoConnectEnabled = UserDefaults.standard.bool(forKey: AppModel.autoConnectKey) { + didSet { UserDefaults.standard.set(autoConnectEnabled, forKey: Self.autoConnectKey) } + } + /// A device is plugged in but auto-connect holds back because the Mac is online. + private(set) var autoConnectWaiting = false + @ObservationIgnored private var autoConnectPolicy = AutoConnectPolicy() + @ObservationIgnored private let networkWatcher = NetworkPathWatcher() + + /// Runs after every poll. + private func evaluateAutoConnect() { + let state = status.runState + let idle = helperAvailability.isAvailable && !isBusy && !isRestartingHelper + && (state == .idle || state == .stopped || state == .failed) + let decision = autoConnectPolicy.evaluate(.init( + enabled: autoConnectEnabled, + deviceIDs: devices.map(\.id), + preferredDeviceID: selectedDeviceID, + idle: idle, + hasOtherNetwork: networkWatcher.hasOtherNetwork, + now: ProcessInfo.processInfo.systemUptime)) + // A session (started by hand or automatically) uses up the arrival: after the user disconnects, the device + // stays disconnected until re-plugged. + if state == .running || state.isTransitional { + autoConnectPolicy.markAllHandled() + } + autoConnectWaiting = decision == .waitingForOtherNetwork + if case .connect(let deviceID) = decision { + selectedDeviceID = deviceID + Task { await startSession() } + } + } + + /// Hides the last failure. Local only: the daemon already dropped the dead session, so there is nothing to + /// stop and no authorization to ask for. + func dismissFailure() { + lastFailure = nil + } + /// Stops the session. func stopSession() async { guard !isBusy else { return } @@ -574,18 +777,23 @@ final class AppModel { isBusy = true defer { isBusy = false } - await authorized { [self] authorization in + let applied = await authorized { [self] authorization in try await client.applyNetwork(authorization: authorization, interface: interface, configuration: networkConfiguration) - // Immediately read back once, so the UI reflects the address actually in effect right away, without waiting for the next polling period. + // Read back once so the UI shows the address actually in effect without waiting for the next poll. networkState = (try? await client.queryNetwork(interface: interface)) ?? .empty } + if applied { + // The saved settings replaced whatever was applied for this session only. + sessionOnlyAddress = nil + autoConfigureNote = nil + } } - /// Revokes the IP configuration on the NIC. + /// Revokes the IP configuration on the interface. /// - /// A separate action rather than "choose 'do not configure' as the connectivity method and click apply": revoking is a one-time operation, - /// and mixing it into the mode selector would make people think choosing it already takes effect. + /// A separate action rather than a "do not configure" mode plus Apply: revoking is a one-time operation, and + /// putting it in the mode selector would suggest that choosing it already takes effect. func clearNetworkConfiguration() async { guard !isBusy else { return } let interface = status.systemInterface @@ -594,22 +802,29 @@ final class AppModel { isBusy = true defer { isBusy = false } - await authorized { [self] authorization in + let cleared = await authorized { [self] authorization in try await client.applyNetwork(authorization: authorization, interface: interface, configuration: NetworkConfiguration(mode: .none)) networkState = (try? await client.queryNetwork(interface: interface)) ?? .empty } + if cleared { + sessionOnlyAddress = nil + autoConfigureNote = nil + } } - /// Manually refreshes the device list (the refresh button on the UI). + /// Manually refreshes the device list (the refresh button). /// - /// Not subject to throttling when triggered manually -- the user clicking the button wants to see results immediately. + /// Not throttled: the user clicking the button wants to see results immediately. func refreshDevices() async { lastDeviceRefresh = .now devices = (try? await client.listDevices()) ?? [] + if let selected = selectedDeviceID, !devices.contains(where: { $0.id == selected }) { + selectedDeviceID = nil + } } - /// Whether it has been long enough since the last enumeration. Also records the moment of this one. + /// Whether enough time has passed since the last enumeration. Also records this one. private func shouldRefreshDevices() -> Bool { let now = ContinuousClock.now if let last = lastDeviceRefresh, now - last < Self.deviceRefreshInterval { @@ -624,25 +839,22 @@ final class AppModel { droppedLogCount = 0 } - /// The library version the App bundles -- the standard answer to "which version the privileged component should be". + /// The library version this app bundles, which is the version the background component should have. /// - /// The **library's** version is used rather than the App version number in Info.plist: what gets installed into - /// /Library/PrivilegedHelperTools is exactly a copy of the libtetherkitnext inside the .app - /// (see the payload-assembly section of build-gui.sh), and comparing is more accurate when both sides share a source. Also the bare executable of `swift run` - /// has no bundle at all, and on the path that reads Info.plist this judgment would fail entirely. + /// The library's version is used rather than the Info.plist version: the daemon in the bundle loads the same + /// libtetherkitnext as the app, so both sides share a source. A bare `swift run` executable has no bundle, + /// where reading Info.plist would fail. /// - /// It is safe to cache with `static let` because it is a constant burned into the dylib at compile time and does not - /// change while the process lives -- unlike the several hint strings above that must follow the language. The version number extraction is also - /// done along the way: this judgment hangs on polling that runs every 500 ms, and there is no need to rerun a regex every time. + /// Cached in a `static let` because it is burned into the dylib at compile time and never changes while the + /// process lives, unlike the hint strings that follow the language. The regex extraction also runs once, + /// since this check hangs on the 500 ms polling. private static let bundledVersion = HelperConstants.semanticVersion(of: TetherKitNextLibrary.versionInfo.version) - /// Whether the installed component and the App-bundled one are the same version. Returns nil when consistent. + /// Whether the running component and the bundled one are the same version. Returns nil when they match. /// - /// Also compares build IDs: two builds can share a version number (every - /// 0.2.0 prerelease), and the daemon keeps running the old binary after the - /// app is replaced until it is restarted. Without this, a same-version - /// update never offered the restart and the new daemon code never ran. + /// Build IDs are compared too: two builds can share a version number, and the daemon keeps running the old + /// binary after the app is replaced until it is restarted. private static func versionMismatch(installed: String, build: String) -> HelperVersionMismatch? { let installedVersion = HelperConstants.semanticVersion(of: installed) let installedBuild = HelperConstants.buildID(of: build) @@ -659,12 +871,11 @@ final class AppModel { private static let bundledBuild = HelperConstants.buildID(of: TetherKitNextLibrary.versionInfo.build) - /// Registers the daemon with SMAppService (onboarding card), or restarts - /// it from this app bundle when its version differs ("Update helper"). + /// Registers the daemon with SMAppService (onboarding card), or restarts it from this app bundle when its + /// version differs ("Restart background component"). /// - /// No password prompt: macOS asks the user to approve the background item - /// in System Settings › Login Items instead. When approval is pending we - /// open that pane; polling picks the daemon up as soon as it is enabled. + /// No password prompt: macOS asks the user to approve the background item in System Settings › Login Items. + /// When approval is pending we open that pane; polling picks the daemon up as soon as it is enabled. func installHelper() async { guard !isBusy else { return } isBusy = true @@ -674,6 +885,8 @@ final class AppModel { || HelperInstaller.status == .enabled isRestartingHelper = restarting defer { isRestartingHelper = false } + // The (re)started daemon begins in its default language; resend on next contact. + languageSyncedDaemon = nil do { if restarting { try await HelperInstaller.reregister() @@ -704,8 +917,8 @@ final class AppModel { await refresh() } - /// Unregisters the daemon. launchd sends it SIGTERM, which stops a running - /// session and destroys the virtual interfaces (the UI warns first). + /// Unregisters the daemon. launchd sends it SIGTERM, which stops a running session and destroys the virtual + /// interfaces (the UI warns first). func uninstallHelper() async { guard !isBusy else { return } isBusy = true @@ -754,8 +967,15 @@ final class AppModel { // MARK: - Checking for updates - /// Manual check (the App menu "Check for Updates..."). The result pops up a dialog whether good or bad. + /// Manual check (the App menu "Check for Updates..."). The result is shown in a dialog either way. + /// + /// Builds that update themselves hand this to Sparkle, whose dialog offers to download, verify and install + /// the update; others show the release page. func checkForUpdates() async { + if SoftwareUpdater.shared.isAvailable { + SoftwareUpdater.shared.checkForUpdates() + return + } guard let current = UpdateChecker.currentVersion else { updateCheckResult = .unavailable return @@ -775,8 +995,8 @@ final class AppModel { } } - /// Automatic check: at most once a day, silent on failure, and on finding a new version only lights up the hint in the management row, - /// never popping up to interrupt -- an update is something to learn "in passing" and does not deserve a modal box. + /// Automatic check: at most once a day, silent on failure. A new version only lights up the hint in + /// Settings and never interrupts with a popup. /// It can be turned off with `defaults write com.tetherkitnext.app updateCheckDisabled -bool YES`. private func checkForUpdatesQuietly() async { guard let current = UpdateChecker.currentVersion else { return } @@ -793,15 +1013,15 @@ final class AppModel { availableUpdate = UpdateChecker.isNewer(latest.version, than: current) ? latest : nil } - /// Records the latest version found into defaults -- when tomorrow's launch is blocked by throttling, the hint should not disappear. + /// Records the latest version found, so the hint survives a launch that throttling skips. private func remember(_ release: UpdateChecker.Release) { let defaults = UserDefaults.standard defaults.set(release.version, forKey: Self.updateKnownVersionKey) defaults.set(release.pageURL.absoluteString, forKey: Self.updateKnownPageKey) } - /// Restores the new-version hint found last time at startup. After the upgrade completes (current version >= the remembered version) - /// it naturally becomes invalid, needing no cleanup logic whatsoever. + /// Restores the new-version hint found last time. Once the app is upgraded (current >= remembered) it + /// stops matching, so no cleanup is needed. private func restoreKnownUpdate() { guard let current = UpdateChecker.currentVersion, let version = UserDefaults.standard.string(forKey: Self.updateKnownVersionKey), @@ -817,38 +1037,30 @@ final class AppModel { private static let updateKnownVersionKey = "updateKnownVersion" private static let updateKnownPageKey = "updateKnownPageURL" - /// Executes a privileged operation carrying an authorization credential, popping up the system authorization dialog only when necessary. - /// - /// * Why the token is cached * - /// The measured parameters of `system.privilege.admin` are `shared = false` and `timeout = 300`. - /// `shared = false` means the credential is **not shared across AuthorizationRefs** -- creating a new ref - /// for every operation necessarily makes the user authenticate again, so "connect, configure network, disconnect" - /// would pop up the dialog three times in a row. And `timeout = 300` means the credential on the same ref - /// stays valid for 5 minutes. + /// Executes a privileged operation with an authorization credential, showing the system dialog only when + /// necessary. /// - /// So the token is cached and reused: the first operation pops up a dialog once, and afterwards none is needed for 5 minutes. - /// After expiry the helper's verification fails and explicitly says "this is an authorization problem", and on that basis we discard the - /// cache, pop up a dialog again, and retry this operation -- what the user sees is still "a dialog popped up - /// before the operation", rather than an inexplicable failure. + /// The token is cached because `system.privilege.admin` has `shared = false` and `timeout = 300`: + /// a credential is not shared across AuthorizationRefs, so a fresh ref per operation would make the user + /// authenticate again ("connect, configure network, disconnect" would prompt three times), while the + /// credential on one ref stays valid for 5 minutes. The first operation prompts; later ones within 5 + /// minutes do not. After expiry the helper's verification fails and says it is an authorization problem; + /// we then drop the cache, prompt again and retry, so the user sees a dialog before the operation instead + /// of an inexplicable failure. /// - /// * Why we cannot catch the credential ourselves and use it later * - /// The external form is only a key pointing to that authorization in securityd, not the credential itself. - /// Once the AuthorizationRef is released, the helper reports -60005 when restoring. So the token is held by - /// `cachedAuthorization`, and `withExtendedLifetime` guarantees it lives until after the - /// XPC round trip ends. + /// The token has to be kept alive rather than only its external form: the external form is a key into the + /// authorization in securityd, and once the AuthorizationRef is released the helper reports -60005 when + /// restoring it. `cachedAuthorization` holds the token and `withExtendedLifetime` keeps it alive until the + /// XPC round trip ends. /// - /// On user cancellation **no** error hint is popped up -- cancelling is a normal action, and popping up another "cancelled" box - /// would only be annoying. - /// Returns whether `body` ran to completion. + /// Cancelling is normal, so it shows no error. Returns whether `body` ran to completion. @discardableResult private func authorized(prompt: String = L(.authPromptSession), reason: String = L(.presenceReasonSession), _ body: @escaping (Data) async throws -> Void) async -> Bool { - // Team-signed builds: Touch ID (or the login password) instead of the - // administrator dialog, and no authorization data at all. See - // UserPresence for why that is safe. The daemon still refuses it for - // non-admin users; then we fall through to the admin dialog below, and - // stop trying for the rest of this run. + // Team-signed builds: Touch ID (or the login password) instead of the administrator dialog, with no + // authorization data at all (see UserPresence for why that is safe). The daemon still refuses it for + // non-admin users; then we fall through to the admin dialog below and stop trying for the rest of this run. if UserPresence.isAvailable && !presenceRejected { do { try await UserPresence.confirm(reason: reason) @@ -866,17 +1078,17 @@ final class AppModel { } } - // First pass: if there is a cache, use it directly without disturbing the user. + // First pass: use the cache if there is one, without disturbing the user. if let cached = cachedAuthorization { - // withExtendedLifetime cannot take an async closure, so defer is used to pin the token until the - // end of scope -- a local let alone is not enough, since ARC may release it right after the last read of - // externalForm, when the XPC round trip has not yet come back. + // withExtendedLifetime cannot take an async closure, so defer pins the token until the end of scope. A + // local let is not enough: ARC may release it right after the last read of externalForm, before the XPC + // round trip returns. defer { withExtendedLifetime(cached) {} } do { try await body(cached.externalForm) return true } catch let failure as HelperClient.Failure where failure.isAuthorizationProblem { - // The credential expired. Discard the cache and go on to "re-authorize + retry". + // The credential expired. Drop the cache and fall through to "re-authorize + retry". cachedAuthorization = nil } catch { alertMessage = error.localizedDescription @@ -884,7 +1096,7 @@ final class AppModel { } } - // Second pass: pop up a dialog to get a new credential, then execute (or retry). + // Second pass: show the dialog to get a new credential, then execute (or retry). do { let token = try AuthorizationBroker.requestAuthorization(prompt: prompt) defer { withExtendedLifetime(token) {} } @@ -899,3 +1111,67 @@ final class AppModel { } } } + +#if DEBUG +// MARK: - UI snapshots (debug builds only) + +/// The state one UI snapshot shows (UISnapshotRenderer). Lives in this file so it can set the model's +/// private(set) state directly; nothing here touches the daemon, USB or the network, and `start()` is never called. +struct UISnapshotState { + var helper: HelperAvailability = .available(version: "1.3.0") + var needsApproval = false + var style: InterfaceStyle? = .simple + var announcementPending = false + var devices: [DeviceDescriptor] = [] + var selectedDeviceID: String? + var status: SessionStatus = .idle + var network: NetworkState = .empty + /// Down / up in bits per second; also fills the 60-second chart. + var rates: (down: Double, up: Double)? + var failureMessage: String? + var autoConnectEnabled = false + var autoConnectWaiting = false + var updateVersion: String? + var logs: [LogEntry] = [] + var connectedFor: TimeInterval = 0 + var environment: EnvironmentReport? +} + +extension AppModel { + func applySnapshotState(_ state: UISnapshotState) { + helperAvailability = state.helper + helperNeedsApproval = state.needsApproval + interfaceStyle = state.style + interfaceStyleAnnouncementPending = state.announcementPending + devices = state.devices + selectedDeviceID = state.selectedDeviceID + status = state.status + networkState = state.network + lastFailure = state.failureMessage.map(SessionFailure.init(message:)) + autoConnectEnabled = state.autoConnectEnabled + autoConnectWaiting = state.autoConnectWaiting + availableUpdate = state.updateVersion.map { + UpdateChecker.Release(version: $0, + pageURL: URL(string: "https://github.com/AA-EION/TetherKitNext/releases")!) + } + logs = state.logs + environment = state.environment + sessionStartedAt = state.status.runState == .running + ? Date().addingTimeInterval(-state.connectedFor) : nil + if let rates = state.rates { + let now = Date() + throughputHistory = (0.. Color { switch state { case .idle, .stopped: return .secondary @@ -53,6 +53,16 @@ enum Design { } } + /// The fill of the connected power button. White text on it must stay at least 4.5:1 (WCAG AA): system green + /// is only ~2.2:1. The light end is #1D8639 (4.6:1 with white), the dark end #17702F. + static let connectedGreen = Color(red: 23 / 255, green: 112 / 255, blue: 47 / 255) + static let connectedGreenLight = Color(red: 29 / 255, green: 134 / 255, blue: 57 / 255) + + static var connectedGradient: LinearGradient { + LinearGradient(colors: [connectedGreenLight, connectedGreen], + startPoint: .top, endPoint: .bottom) + } + static func statusLabel(for status: SessionStatus) -> String { switch status.runState { case .idle: return L(.statusDisconnected) @@ -86,7 +96,7 @@ enum Design { // MARK: - Reusable containers -/// The card container. All content panels wrap themselves in it, guaranteeing consistent corner radii, padding and strokes. +/// The card container. All content panels wrap themselves in it for consistent corner radii, padding and strokes. struct Card: View { var title: String? var systemImage: String? @@ -128,16 +138,13 @@ struct Card: View { // MARK: - Liquid Glass // -// Apple's guidance for Liquid Glass (macOS 26): glass belongs to the -// *navigation and control* layer that floats above content — sidebars, -// toolbars, the primary action, status chrome — not to every content card. -// So the sidebar and toolbar get it from the system automatically; the status -// hero, primary buttons and menu bar controls use it explicitly; content -// cards stay on a quiet material surface that the glass refracts. +// Apple's guidance for Liquid Glass (macOS 26): glass belongs to the navigation and control layer that +// floats above content (sidebars, toolbars, the primary action, status chrome), not to every content card. +// So the sidebar and toolbar get it from the system automatically; the status hero, primary buttons and menu +// bar controls use it explicitly; content cards stay on a quiet material surface that the glass refracts. // -// Every API is gated twice: `#if compiler(>=6.2)` so the package still builds -// with an older toolchain, and `#available(macOS 26, *)` so the app runs on -// macOS 14/15 with the material look. +// Every API is gated twice: `#if compiler(>=6.2)` so the package still builds with an older toolchain, and +// `#available(macOS 26, *)` so the app runs on macOS 14/15 with the material look. extension View { /// Quiet surface for content cards. @@ -207,20 +214,6 @@ extension View { #endif } - /// Groups adjacent glass shapes so they blend and morph together. - @ViewBuilder - func glassGroup(spacing: CGFloat = Design.Spacing.small) -> some View { - #if compiler(>=6.2) - if #available(macOS 26.0, *) { - GlassEffectContainer(spacing: spacing) { self } - } else { - self - } - #else - self - #endif - } - private func materialGlassFallback(cornerRadius: CGFloat, tint: Color?) -> some View { background(.thinMaterial, in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)) @@ -297,17 +290,18 @@ struct StatusBadge: View { // MARK: - Formatting -/// The formatting of all numeric values on the UI goes through here, avoiding the same quantity being displayed looking different in different panels. +/// The formatting of all numeric values in the UI goes through here, so the same quantity looks the same in every +/// panel. enum Format { - /// Rate. Automatically picks the unit among bit/s, Kbps, Mbps, Gbps. + /// Rate. Automatically picks the unit among bps, kbps, Mbps, Gbps (SI prefixes: lowercase k). /// - /// Bits rather than bytes: the industry convention for network throughput is bits, consistent with the figures the user sees on routers and - /// at carriers. + /// Bits rather than bytes: the industry convention for network throughput is bits, matching the figures on + /// routers and from carriers. static func bitrate(_ bitsPerSecond: Double) -> String { let units: [(threshold: Double, suffix: String, divisor: Double)] = [ (1_000_000_000, "Gbps", 1_000_000_000), (1_000_000, "Mbps", 1_000_000), - (1_000, "Kbps", 1_000), + (1_000, "kbps", 1_000), ] for unit in units where bitsPerSecond >= unit.threshold { return String(format: "%.1f %@", bitsPerSecond / unit.divisor, unit.suffix) @@ -317,8 +311,8 @@ enum Format { /// Cumulative byte count. static func bytes(_ value: UInt64) -> String { - // ByteCountFormatter renders 0 as "Zero KB" (its localized behavior), - // which looks especially abrupt in a row of numbers, so it is handled separately. + // ByteCountFormatter renders 0 as "Zero KB" (its localized behavior), which looks abrupt in a row of + // numbers, so it is handled separately. guard value > 0 else { return "0 B" } let formatter = ByteCountFormatter() formatter.countStyle = .binary @@ -332,9 +326,8 @@ enum Format { return formatter.string(from: NSNumber(value: value)) ?? "\(value)" } - /// Fixed-width rate for the menu bar (upstream issue #1): always three - /// significant characters plus a unit, so the status item does not jump - /// around as the rate changes between 1K and 100K. + /// Fixed-width rate for the menu bar: always three significant characters plus a unit, so the status item + /// does not jump around as the rate changes between 1K and 100K. static func compactBitrate(_ bitsPerSecond: Double) -> String { RateFormat.compact(bitsPerSecond) } @@ -345,8 +338,8 @@ enum Format { : String(format: "%.0f", max(0, value)) } - // DateFormatter is not Sendable, but formatting with a fixed format on an - // unmutated instance is thread-safe on every supported macOS. + // DateFormatter is not Sendable, but formatting with a fixed format on an unmutated instance is thread-safe + // on every supported macOS. nonisolated(unsafe) private static let timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "HH:mm:ss.SSS" diff --git a/gui/Sources/TetherKitNextApp/HelperClient.swift b/gui/Sources/TetherKitNextApp/HelperClient.swift index 3d1126e..173413f 100644 --- a/gui/Sources/TetherKitNextApp/HelperClient.swift +++ b/gui/Sources/TetherKitNextApp/HelperClient.swift @@ -1,22 +1,22 @@ import Foundation import TetherKitNextIPC -/// The client that communicates with tetherkitnext-helper. +/// The client that communicates with the helper daemon. /// -/// Wraps "reply-block based XPC" into async/await. It looks trivial, but there is one place that needs care: -/// NSXPCConnection's error-handling block and the method's reply block **may both be called** (for example the request has already been -/// sent and the connection then drops), and a CheckedContinuation resumed twice is a direct crash. -/// So every call is wrapped in a ContinuationGuard, guaranteeing it is fulfilled only once. -/// `@unchecked Sendable`: the cached connection is guarded by `connectionLock`; -/// everything else is immutable. AppModel (main actor) awaits these calls -/// while XPC replies arrive on XPC's own queues. +/// Wraps reply-block based XPC in async/await. One place needs care: NSXPCConnection's error-handling block +/// and the method's reply block may both be called (for example the request was sent and the connection then +/// drops), and a CheckedContinuation resumed twice crashes. Every call is therefore wrapped in a +/// ContinuationGuard so it is fulfilled only once. +/// `@unchecked Sendable`: the cached connection is guarded by `connectionLock` and everything else is +/// immutable. AppModel (main actor) awaits these calls while XPC replies arrive on XPC's own queues. final class HelperClient: @unchecked Sendable { enum Failure: LocalizedError { - /// Cannot connect -- the most common reason is that the helper is not installed yet. + /// Cannot connect; the most common reason is that the helper is not registered yet. case unreachable(String) /// The helper explicitly returned an error. case helper(String) - /// The helper's authorization verification did not pass -- most likely the credential expired, and popping up the dialog again is enough. + /// The helper's authorization verification did not pass, most likely because the credential expired and showing + /// the dialog again is enough. case authorizationRejected(String) /// The reply cannot be decoded (the versions on the two ends are inconsistent). case malformedResponse @@ -32,11 +32,6 @@ final class HelperClient: @unchecked Sendable { } } - var isUnreachable: Bool { - if case .unreachable = self { return true } - return false - } - /// Whether it is worth "fetching the authorization again and retrying". var isAuthorizationProblem: Bool { if case .authorizationRejected = self { return true } @@ -46,8 +41,8 @@ final class HelperClient: @unchecked Sendable { /// Guarantees a continuation is fulfilled only once. /// - /// It is possible for XPC's error block and reply block to both be called, and resuming twice crashes -- - /// this pitfall appears only in timing like "the connection drops after the request is sent", and is hard to hit through tests. + /// XPC's error block and reply block can both be called, and resuming twice crashes. It only happens when the + /// connection drops after a request was sent, which tests rarely hit. private final class ContinuationGuard: @unchecked Sendable { private let lock = NSLock() private var continuation: CheckedContinuation? @@ -88,19 +83,37 @@ final class HelperClient: @unchecked Sendable { let created = NSXPCConnection(machServiceName: HelperConstants.machServiceName, options: .privileged) created.remoteObjectInterface = NSXPCInterface(with: TetherKitNextHelperProtocol.self) - // Release builds only talk to the daemon signed by our own team, so - // a look-alike service registered under our name is refused. + // Release builds only talk to the daemon signed by our own team, so a look-alike service registered under + // our name is refused. if let requirement = CodeSigning.daemonRequirement { created.setCodeSigningRequirement(requirement) } - // After the connection drops the cache must be discarded, otherwise later calls would keep hitting a dead connection, - // showing up as "the helper is clearly installed but can never be connected to". - let invalidate: @Sendable () -> Void = { [weak self] in - self?.connectionLock.withLock { self?.cachedConnection = nil } + // After the connection drops the cache must be discarded, otherwise later calls keep hitting a dead + // connection ("the helper is clearly registered but can never be connected to"). + // + // Only drop the cache if it still holds this connection: a late handler from an older connection must not + // discard the newer one that replaced it. On interruption the discarded connection is invalidated too, so + // it is not left resumed. + // + // NSXPCConnection is not Sendable, so the handler identifies its connection by ObjectIdentifier. That is + // sound here: while the cache holds the connection it is alive, so the identifier cannot have been reused + // by another object. + let createdID = ObjectIdentifier(created) + let discard: @Sendable (Bool) -> Void = { [weak self] invalidateIt in + guard let self else { return } + let discarded = self.connectionLock.withLock { () -> NSXPCConnection? in + guard let cached = self.cachedConnection, + ObjectIdentifier(cached) == createdID else { return nil } + self.cachedConnection = nil + return cached + } + if invalidateIt { + discarded?.invalidate() + } } - created.invalidationHandler = invalidate - created.interruptionHandler = invalidate + created.invalidationHandler = { discard(false) } + created.interruptionHandler = { discard(true) } created.resume() cachedConnection = created @@ -108,12 +121,18 @@ final class HelperClient: @unchecked Sendable { } } - /// Makes one call. `body` gets the proxy and the guard, and is responsible for issuing the request and fulfilling the result. + /// Makes one call. `body` gets the proxy and the guard, issues the request and fulfills the result. private func invoke( _ body: @escaping (TetherKitNextHelperProtocol, ContinuationGuard) -> Void ) async throws -> T { try await withCheckedThrowingContinuation { continuation in let guarded = ContinuationGuard(continuation) + // A daemon that accepts a call but never replies (e.g. stuck behind a blocked SystemConfiguration lock) + // would otherwise leave the continuation pending forever, and with it AppModel.isBusy and the polling + // loop. The guard makes a late reply after the timeout harmless. + DispatchQueue.global().asyncAfter(deadline: .now() + HelperConstants.requestTimeout) { + guarded.resume(throwing: Failure.unreachable(L(.helperRequestTimedOut))) + } let proxy = connection().remoteObjectProxyWithErrorHandler { error in guarded.resume(throwing: Failure.unreachable(error.localizedDescription)) } @@ -192,9 +211,9 @@ final class HelperClient: @unchecked Sendable { } } - /// Tells the helper the UI language. **Failures are swallowed silently** -- the language failing to sync only means the log card - /// mixes in another language, and it should not pop the "cannot connect to helper" error to the user (in the normal startup - /// order the helper may not be installed yet). + /// Tells the helper the UI language. Failures are swallowed: a language that fails to sync only means the + /// log card mixes in another language, and it should not show "cannot connect to helper" (in the normal + /// startup order the helper may not be registered yet). func setLanguage(_ language: Language) async { _ = try? await invoke { proxy, guarded in proxy.setLanguage(language.rawValue) { guarded.resume(returning: ()) } diff --git a/gui/Sources/TetherKitNextApp/HelperInstaller.swift b/gui/Sources/TetherKitNextApp/HelperInstaller.swift index b465a81..386e79a 100644 --- a/gui/Sources/TetherKitNextApp/HelperInstaller.swift +++ b/gui/Sources/TetherKitNextApp/HelperInstaller.swift @@ -2,29 +2,15 @@ import Foundation import ServiceManagement import TetherKitNextIPC -/// Registers the privileged daemon with launchd through SMAppService. +/// Registers the privileged daemon with launchd through SMAppService (macOS 13+). /// -/// ★ Why SMAppService ★ -/// -/// The previous installer ran a setuid-root copy of the helper through -/// AuthorizationExecuteWithPrivileges (deprecated since macOS 10.7, looked up -/// via dlsym) and copied binaries into /Library. SMAppService (macOS 13+) is -/// Apple's supported mechanism for this: -/// * the daemon runs in place from the signed, notarized app bundle — -/// nothing root-owned is copied anywhere, so there is no install/upgrade -/// drift between the app and the daemon; -/// * the user approves it once in System Settings › Login Items, and can -/// see and revoke it there; -/// * uninstalling the app (dragging it to the Trash) removes the daemon. -/// -/// The old doc (GUI-SPIKE §3.3) rejected SMAppService because source builds -/// produce a different cdhash on every machine. That constraint went away -/// with the move to a signed DMG distribution. +/// The daemon runs in place from the signed, notarized app bundle, so nothing root-owned is copied anywhere +/// and the app and daemon cannot drift apart. The user approves it once in System Settings › Login Items, +/// where it can be seen and revoked, and removing the app (dragging it to the Trash) removes the daemon. enum HelperInstaller { enum Failure: LocalizedError { - /// Running from the DMG or from an App Translocation mount. launchd - /// refuses bundles on read-only/randomized paths, and a daemon pointing - /// into a DMG would vanish on eject anyway. + /// Running from the DMG or from an App Translocation mount. launchd refuses bundles on read-only or + /// randomized paths, and a daemon pointing into a DMG would vanish on eject anyway. case mustMoveToApplications case registrationFailed(String) @@ -56,29 +42,43 @@ enum HelperInstaller { /// Registers (or re-registers) the daemon. /// - /// Returns normally when the daemon is enabled *or* awaiting approval; the - /// caller checks `needsApproval` and guides the user to System Settings. + /// Returns normally when the daemon is enabled or awaiting approval; the caller checks `needsApproval` and + /// guides the user to System Settings. static func register() throws { if let problem = locationProblem { throw problem } + clearQuarantineOnDaemonPlist() do { try service.register() } catch { - // "Operation not permitted" here means "registered, awaiting user - // approval" — not a failure from the user's point of view. + // "Operation not permitted" here means "registered, awaiting user approval", which is not a failure from + // the user's point of view. if status == .requiresApproval || status == .enabled { return } throw Failure.registrationFailed(error.localizedDescription) } } - /// Restarts the daemon from the current app bundle, e.g. after the app was - /// replaced by a newer version while the old daemon kept running. + /// Removes `com.apple.quarantine` from the bundled LaunchDaemon plist. + /// + /// macOS 27 release notes (166415497): launchd no longer loads property lists that carry the quarantine + /// attribute, and a DMG download marks every file in the bundle. Whether SMAppService plists of notarized + /// apps are exempt is undocumented, so the attribute is dropped from this one file before registering. + /// Extended attributes are not part of the code signature, and Gatekeeper has already assessed the app by + /// the time it runs. Best effort: errors are ignored (the file may be read-only or carry no attribute). + static func clearQuarantineOnDaemonPlist() { + let plist = Bundle.main.bundleURL + .appendingPathComponent("Contents/Library/LaunchDaemons") + .appendingPathComponent(HelperConstants.daemonPlistName) + _ = plist.withUnsafeFileSystemRepresentation { path in + path.map { removexattr($0, "com.apple.quarantine", XATTR_NOFOLLOW) } + } + } + + /// Restarts the daemon from the current app bundle, e.g. after the app was replaced by a newer version while + /// the old daemon kept running. /// - /// `unregister()` returns before launchd has finished removing the job, - /// and a `register()` issued in that window fails with "Operation not - /// permitted" and leaves the daemon unregistered: the first click on - /// Restart failed and the app fell back to the setup steps, while a second - /// click, a moment later, worked. So wait for the removal to show in the - /// status, and retry registering for a few seconds. + /// `unregister()` returns before launchd has finished removing the job, and a `register()` issued in that + /// window fails with "Operation not permitted" and leaves the daemon unregistered. So wait for the removal + /// to show in the status, and retry registering for a few seconds. static func reregister() async throws { if let problem = locationProblem { throw problem } try? await service.unregister() @@ -119,7 +119,7 @@ enum HelperInstaller { enum CommandLineToolState: Equatable { case notInstalled case installed - /// Something else occupies the path (another copy of TetherKitNext, Homebrew). + /// Something else occupies the path (another copy of TetherKitNext or another tool). case occupied(String) static var current: CommandLineToolState { diff --git a/gui/Sources/TetherKitNextApp/MainWindowController.swift b/gui/Sources/TetherKitNextApp/MainWindowController.swift new file mode 100644 index 0000000..780efae --- /dev/null +++ b/gui/Sources/TetherKitNextApp/MainWindowController.swift @@ -0,0 +1,191 @@ +import AppKit +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// Owns the main window as a plain AppKit `NSWindow`. +/// +/// Why not a SwiftUI `Window` scene (AGENTS.md pitfall 29): with a `MenuBarExtra` alongside, SwiftUI recreates +/// a closed `Window` scene whenever the windowless app is activated, which clicking the menu bar item does, +/// and dismissing the resurrected window after the fact still let it flash. With no window scene SwiftUI has +/// nothing to resurrect. Presentation also becomes deterministic: the window exists from +/// `applicationDidFinishLaunching`, also for bare `swift run` binaries, and `applicationShouldHandleReopen` +/// (Dock / Finder double-click in menu-bar-only mode) reaches us. SwiftUI still renders everything inside an +/// `NSHostingController` with toolbar and title bridging, so `.toolbar` / `.navigationTitle` in ContentView +/// keep working. +/// +/// Closing: `isReleasedWhenClosed = false`, so 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]` makes the hosting controller push only the content's minimum +/// size into the window. By default it also publishes the preferred (intrinsic) size, and pages differ in +/// intrinsic height, so switching pages would resize the window, which macOS 26 animates in step with the +/// content change. It is 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 } + + // MARK: Layout + + /// Whether the window is currently sized for the simple layout. + private var isCompact = false + private static let fullFrameKey = "MainWindowFullFrame" + + /// Resizes the window for a layout: the simple view is a small, fixed window; the detailed view gets back its + /// last frame (remembered across launches) or the default size. The top-left corner stays put. + func applyLayout(compact: Bool, animate: Bool) { + guard compact != isCompact else { return } + isCompact = compact + if compact { + UserDefaults.standard.set(NSStringFromRect(window.frame), forKey: Self.fullFrameKey) + window.styleMask.remove(.resizable) + // A bare window: no title text or separator; the content runs up under the traffic lights (SimpleView + // keeps clear of them). + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + window.titlebarSeparatorStyle = .none + window.contentMinSize = SimpleView.windowSize + let size = window.frameRect(forContentRect: NSRect(origin: .zero, + size: SimpleView.windowSize)).size + var frame = window.frame + frame.origin.y += frame.height - size.height + frame.size = size + window.setFrame(frame, display: true, animate: animate) + } else { + window.styleMask.insert(.resizable) + window.titlebarAppearsTransparent = false + window.titleVisibility = .visible + window.titlebarSeparatorStyle = .automatic + window.contentMinSize = NSSize(width: Design.Window.minWidth, + height: Design.Window.minHeight) + var frame = UserDefaults.standard.string(forKey: Self.fullFrameKey) + .map(NSRectFromString) ?? .zero + if frame.width < Design.Window.minWidth || frame.height < Design.Window.minHeight { + let size = window.frameRect(forContentRect: NSRect( + x: 0, y: 0, width: Design.Window.defaultWidth, + height: Design.Window.defaultHeight)).size + frame = NSRect(x: window.frame.minX, y: window.frame.maxY - size.height, + width: size.width, height: size.height) + } + // Keep it on a screen (the saved frame may be from another display setup). + if let visible = (window.screen ?? NSScreen.main)?.visibleFrame, + !visible.intersects(frame) { + frame.origin = NSPoint(x: visible.midX - frame.width / 2, + y: visible.midY - frame.height / 2) + } + window.setFrame(frame, display: true, animate: animate) + } + } + + /// 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 { + let compact = model.interfaceStyle == .simple && model.helperAvailability.isAvailable + ContentView(model: model) + .frame(minWidth: compact ? SimpleView.windowSize.width : Design.Window.minWidth, + minHeight: compact ? SimpleView.windowSize.height : Design.Window.minHeight) + .onAppear { + MainWindowController.shared?.applyLayout(compact: compact, animate: false) + } + .onChange(of: compact) { _, compact in + MainWindowController.shared?.applyLayout(compact: compact, animate: true) + } + // 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/NetworkPathWatcher.swift b/gui/Sources/TetherKitNextApp/NetworkPathWatcher.swift new file mode 100644 index 0000000..507d115 --- /dev/null +++ b/gui/Sources/TetherKitNextApp/NetworkPathWatcher.swift @@ -0,0 +1,38 @@ +import Foundation +import Network + +/// Whether this Mac already has a Wi-Fi or Ethernet connection, for the +/// auto-connect rule "never take over a Mac that is already online" +/// (`AutoConnectPolicy`). +/// +/// Uses the system's own path evaluation (NWPathMonitor): a path is +/// "satisfied" when macOS considers it usable, and only Wi-Fi and wired +/// Ethernet interfaces count. Our own `feth` interfaces are excluded by name +/// (they are Ethernet to the system). Another phone tethered over USB or a +/// Thunderbolt Ethernet adapter count as Ethernet, which errs on the safe side. +@MainActor +final class NetworkPathWatcher { + /// nil until the first reading arrives (treated as "online": no auto-connect). + private(set) var hasOtherNetwork: Bool? + + private let monitor = NWPathMonitor() + private var started = false + + func start() { + guard !started else { return } + started = true + monitor.pathUpdateHandler = { [weak self] path in + let online = Self.hasOtherNetwork(path) + Task { @MainActor in self?.hasOtherNetwork = online } + } + monitor.start(queue: DispatchQueue(label: "com.tetherkitnext.app.network-path")) + } + + nonisolated static func hasOtherNetwork(_ path: NWPath) -> Bool { + guard path.status == .satisfied else { return false } + return path.availableInterfaces.contains { interface in + (interface.type == .wifi || interface.type == .wiredEthernet) + && !interface.name.hasPrefix("feth") + } + } +} diff --git a/gui/Sources/TetherKitNextApp/SoftwareUpdater.swift b/gui/Sources/TetherKitNextApp/SoftwareUpdater.swift new file mode 100644 index 0000000..52032fd --- /dev/null +++ b/gui/Sources/TetherKitNextApp/SoftwareUpdater.swift @@ -0,0 +1,70 @@ +import AppKit +@preconcurrency import Sparkle + +/// In-app updates through Sparkle: find, download, verify and install a new release, always after the user +/// confirms in Sparkle's update dialog ("Install and Relaunch" / "Remind Me Later" / "Skip This Version"). +/// +/// It is active only in builds that carry both `SUFeedURL` and `SUPublicEDKey` in Info.plist. build-gui.sh +/// adds them when TETHERKITNEXT_SPARKLE_PUBLIC_KEY is set, which the release workflow does for builds whose DMG +/// it signs. Local, ad-hoc and CI builds have no key: Sparkle is never started and the app keeps the +/// check-only flow (UpdateChecker, linking to the release page). +/// +/// Trust: the DMG's EdDSA signature must match the public key inside the running app +/// (`SUVerifyUpdateBeforeExtraction`, checked before anything is unpacked); Sparkle also requires the new app +/// to carry the same code-signing identity (our Developer ID Team ID) as the installed one; the feed is +/// served over HTTPS from GitHub releases. +/// +/// Background component: replacing the app does not restart the SMAppService daemon (AGENTS.md pitfall 24), +/// which keeps running the old binary. Before relaunching, this records that an update was installed; on the +/// next launch AppModel restarts the daemon once its build differs and no session is running. +@MainActor +final class SoftwareUpdater { + static let shared = SoftwareUpdater() + + /// UserDefaults flag consumed by `AppModel.restartHelperAfterUpdateIfNeeded()`. + nonisolated static let restartHelperAfterUpdateKey = "restartHelperAfterUpdate" + + private let controller: SPUStandardUpdaterController? + private let delegate = Delegate() + + private init() { + guard Self.isConfigured else { + controller = nil + return + } + controller = SPUStandardUpdaterController(startingUpdater: true, + updaterDelegate: delegate, + userDriverDelegate: nil) + } + + /// Whether this build updates itself. False means the check-only flow is used. + var isAvailable: Bool { controller != nil } + + /// Manual "Check for Updates…": Sparkle shows the result (up to date, an error, or the update dialog with + /// release notes). + func checkForUpdates() { + controller?.checkForUpdates(nil) + } + + /// Mirrors the "check for updates automatically" setting. Sparkle's scheduled check shows the same + /// confirmation dialog; it never installs silently (`SUAllowsAutomaticUpdates` is off). + func setAutomaticallyChecks(_ enabled: Bool) { + controller?.updater.automaticallyChecksForUpdates = enabled + } + + private static var isConfigured: Bool { + let bundle = Bundle.main + guard bundle.bundleURL.pathExtension == "app", + let feed = bundle.object(forInfoDictionaryKey: "SUFeedURL") as? String, + let url = URL(string: feed), url.scheme == "https", + let key = bundle.object(forInfoDictionaryKey: "SUPublicEDKey") as? String, + !key.trimmingCharacters(in: .whitespaces).isEmpty else { return false } + return true + } + + private final class Delegate: NSObject, SPUUpdaterDelegate { + nonisolated func updaterWillRelaunchApplication(_ updater: SPUUpdater) { + UserDefaults.standard.set(true, forKey: SoftwareUpdater.restartHelperAfterUpdateKey) + } + } +} diff --git a/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift b/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift index 94c546c..eae767b 100644 --- a/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift +++ b/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift @@ -1,66 +1,91 @@ import AppKit import SwiftUI import TetherKitNextIPC +import TetherKitNextUIModel /// TetherKitNext's GUI entry point. /// -/// The app runs as the logged-in user with no privileges; everything that needs -/// root (feth, BPF, IP configuration) is done by the SMAppService daemon over -/// XPC. See docs/GUI-ARCHITECTURE.md. +/// The app runs as the logged-in user with no privileges; everything that needs root (feth, BPF, IP +/// configuration) is done by the SMAppService daemon over XPC. See docs/GUI-ARCHITECTURE.md. /// -/// ★ Menu-bar-only mode ★ -/// -/// Closing the main window does not quit: the app drops to the `.accessory` -/// activation policy (no Dock icon, no app menu) and lives on as the menu bar -/// item with live rates. Sessions run in the daemon anyway; the app is only a -/// window onto them. Reopening the window from the menu bar item brings the -/// Dock icon back. Polling keeps going (the menu bar needs it) but slows to -/// 2 s while the window is closed and no session is running. +/// Menu-bar-only mode: closing the main window does not quit. The app drops to the `.accessory` activation +/// policy (no Dock icon, no app menu) and lives on as the menu bar item with live rates. Sessions run in the +/// daemon anyway; the app is only a window onto them. Reopening the window from the menu bar item brings the +/// Dock icon back. Polling keeps going (the menu bar needs it) but slows to 2 s while the window is closed +/// and no session is running. @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) } + CommandGroup(before: .toolbar) { LayoutMenuItem(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 -/// `onDisappear`, which does not fire reliably when a `Window` scene is closed -/// — the window was gone but the Dock icon stayed. AppKit's window -/// notifications are authoritative, so the policy is derived from them: any -/// visible, non-panel window → `.regular`; none → `.accessory`. +/// The activation policy is derived from AppKit window notifications, not SwiftUI's `onDisappear`, which does +/// not fire reliably when a window is closed and would leave the Dock icon behind (AGENTS.md pitfall 19). +/// Any visible, non-panel window gives `.regular`; none gives `.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] = [] + /// Whether macOS started the app as a login item ("Open at login" in Settings). + /// Read in applicationWillFinishLaunching, while the launch Apple event is current. + private var launchedAsLoginItem = false + + func applicationWillFinishLaunching(_ notification: Notification) { + // The 'oapp' event of a login-item launch carries keyAEPropData = keyAELaunchedAsLogInItem. + // Four-char codes spelled out to avoid importing Carbon for three constants. + let openApplication: AEEventID = 0x6F61_7070 // 'oapp' kAEOpenApplication + let propertyData: AEKeyword = 0x7072_6474 // 'prdt' keyAEPropData + let loginItem: OSType = 0x6C67_6974 // 'lgit' keyAELaunchedAsLogInItem + if let event = NSAppleEventManager.shared().currentAppleEvent, + event.eventID == openApplication, + event.paramDescriptor(forKeyword: propertyData)?.enumCodeValue == loginItem { + launchedAsLoginItem = true + } + } + func applicationDidFinishLaunching(_ notification: Notification) { + #if DEBUG + // CI: render every screen to PNG and exit (UISnapshotRenderer). The model is never started, so no daemon, + // USB or network access happens. + if let directory = UISnapshotRenderer.outputDirectory { + Task { await UISnapshotRenderer.run(to: directory) } + return + } + #endif + model.start() + let windowController = MainWindowController.install(model: model) + if launchedAsLoginItem { + // Start quietly in the menu bar; the window is one click away. + NSApp.setActivationPolicy(.accessory) + model.windowDidDisappear() + } else { + windowController.present() + } + let center = NotificationCenter.default for name in [NSWindow.willCloseNotification, NSWindow.didBecomeKeyNotification, NSWindow.didMiniaturizeNotification, NSWindow.didDeminiaturizeNotification] { @@ -80,6 +105,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate { false } + /// Dock icon click or Finder double-click while the app is running. The main window is AppKit-owned, so + /// reopen events arrive here; reopen the 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) @@ -93,16 +129,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } - /// Real document-style windows, as opposed to the menu bar extra's panel, - /// the status item itself, popovers and alerts' sheets. + /// Real document-style windows, as opposed to the menu bar extra's panel, the status item itself, popovers + /// and alerts' sheets. private static func isAppWindow(_ window: NSWindow) -> Bool { !(window is NSPanel) && window.canBecomeMain && window.styleMask.contains(.titled) } } -/// "About TetherKitNext", replaced so the panel carries the vendor credit and -/// a link to its website. +/// "About TetherKitNext", replaced so the panel carries the vendor credit and a link to its website. private struct AboutMenuItem: View { var model: AppModel @@ -116,8 +151,8 @@ private struct AppMenuItems: View { var model: AppModel var body: some View { - // Read the revision so the whole group re-renders on a language switch - // (see docs/GUI-ARCHITECTURE.md, SwiftUI and global lookup tables). + // Read the revision so the whole group re-renders on a language switch (see docs/GUI-ARCHITECTURE.md, + // SwiftUI and global lookup tables). let _ = model.languageRevision Button(L(.menuCheckForUpdates)) { @@ -155,39 +190,30 @@ struct LanguagePicker: View { } } -private struct MainWindowRoot: View { +/// View ▸ Use Simple View / Use Detailed View (⇧⌘L). Hidden until a layout has been chosen (setup assistant +/// and chooser come first). +private struct LayoutMenuItem: 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 + if let style = model.interfaceStyle, model.helperAvailability.isAvailable { + Button(L(style == .simple ? .menuUseFullView : .menuUseSimpleView)) { + model.setInterfaceStyle(style == .simple ? .full : .simple) + MainWindowController.shared?.present() } + .keyboardShortcut("l", modifiers: [.command, .shift]) + } } } -/// 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() +/// File ▸ Close (⌘W). +private struct CloseWindowMenuItem: View { + var model: AppModel + + var body: some View { + let _ = model.languageRevision + Button(L(.closeWindow)) { MainWindowController.shared?.closeFrontWindow() } + .keyboardShortcut("w") + } } diff --git a/gui/Sources/TetherKitNextApp/UISnapshotRenderer.swift b/gui/Sources/TetherKitNextApp/UISnapshotRenderer.swift new file mode 100644 index 0000000..c7c084f --- /dev/null +++ b/gui/Sources/TetherKitNextApp/UISnapshotRenderer.swift @@ -0,0 +1,358 @@ +#if DEBUG +import AppKit +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// Renders every screen of both layouts, in light and dark mode, to PNG files. +/// +/// TetherKitNextApp --render-ui-snapshots +/// +/// Debug builds only. Used by .github/workflows/ui-snapshots.yml to show the +/// whole flow (setup → layout choice → simple or detailed) without a device, +/// root or the background daemon: each scene fills a fresh AppModel with +/// sample data (`UISnapshotState`) and never calls `start()`. +/// +/// Capture: each scene is shown in a real window and captured with +/// `screencapture -l` (window server output, so Liquid Glass and materials look +/// as they do on screen). If that fails (no screen-recording permission), the +/// window is drawn in-process instead, which can miss glass effects; the +/// manifest records which method was used. +/// +/// Writes `manifest.json` next to the images: scene order, flow, title, size +/// and capture method. Preferences touched by scenes are restored at the end. +@MainActor +enum UISnapshotRenderer { + static var outputDirectory: URL? { + let arguments = CommandLine.arguments + guard let index = arguments.firstIndex(of: "--render-ui-snapshots"), + index + 1 < arguments.count else { return nil } + return URL(fileURLWithPath: arguments[index + 1], isDirectory: true) + } + + private struct Scene { + enum Kind { case window, panel } + let id: String + let flow: String + let title: String + let note: String + let kind: Kind + let size: CGSize + var preferences: [String: Any] = [:] + let state: UISnapshotState + let content: @MainActor (AppModel) -> AnyView + } + + static func run(to directory: URL) async { + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let touchedKeys = Set(scenes.flatMap { $0.preferences.keys }) + .union([PreferenceKey.selectedPane, PreferenceKey.advancedToolsEnabled, + AppModel.autoConnectKey]) + let saved = Dictionary(uniqueKeysWithValues: touchedKeys.map { + ($0, UserDefaults.standard.object(forKey: $0)) + }) + + NSApp.setActivationPolicy(.regular) + var manifest: [[String: Any]] = [] + for (appearanceName, appearance) in [("light", NSAppearance.Name.aqua), + ("dark", NSAppearance.Name.darkAqua)] { + NSApp.appearance = NSAppearance(named: appearance) + for (order, scene) in scenes.enumerated() { + UserDefaults.standard.set(Pane.overview.rawValue, forKey: PreferenceKey.selectedPane) + UserDefaults.standard.set(false, forKey: PreferenceKey.advancedToolsEnabled) + for (key, value) in scene.preferences { + UserDefaults.standard.set(value, forKey: key) + } + let model = AppModel() + model.applySnapshotState(scene.state) + let file = "\(scene.id)-\(appearanceName).png" + let method = await capture(scene: scene, model: model, + to: directory.appendingPathComponent(file)) + print("snapshot \(file): \(method)") + manifest.append([ + "order": order, "id": scene.id, "flow": scene.flow, "title": scene.title, + "note": scene.note, "appearance": appearanceName, "file": file, + "width": scene.size.width, "height": scene.size.height, "capture": method, + ]) + } + } + + for (key, value) in saved { + if let value { UserDefaults.standard.set(value, forKey: key) } + else { UserDefaults.standard.removeObject(forKey: key) } + } + let systemVersion = ProcessInfo.processInfo.operatingSystemVersionString + let document: [String: Any] = ["macOS": systemVersion, "scenes": manifest] + if let data = try? JSONSerialization.data(withJSONObject: document, + options: [.prettyPrinted, .sortedKeys]) { + try? data.write(to: directory.appendingPathComponent("manifest.json")) + } + exit(0) + } + + // MARK: Capture + + private static func capture(scene: Scene, model: AppModel, to url: URL) async -> String { + let root = scene.content(model) + let hosting = NSHostingController(rootView: root) + hosting.sizingOptions = [] + let window: NSWindow + switch scene.kind { + case .window: + hosting.sceneBridgingOptions = [.toolbars, .title] + window = NSWindow(contentRect: NSRect(origin: .zero, size: scene.size), + styleMask: [.titled, .closable, .miniaturizable, .resizable, + .fullSizeContentView], + backing: .buffered, defer: false) + window.title = "TetherKitNext" + window.toolbarStyle = .unified + case .panel: + window = NSWindow(contentRect: NSRect(origin: .zero, size: scene.size), + styleMask: [.titled, .fullSizeContentView], + backing: .buffered, defer: false) + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + for button in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] { + window.standardWindowButton(button)?.isHidden = true + } + } + window.isReleasedWhenClosed = false + window.contentViewController = hosting + window.setContentSize(scene.size) + window.setFrameOrigin(NSPoint(x: 120, y: 120)) + activate(window) + + // Layout, first data, and entrance animations. + try? await Task.sleep(for: .milliseconds(1800)) + // A launched-from-shell process is not always frontmost: make sure the + // window is key, or it is captured with inactive (grey) chrome and tints. + activate(window) + try? await Task.sleep(for: .milliseconds(400)) + + var method = "screencapture" + if !screencapture(windowNumber: window.windowNumber, to: url) { + method = drawInProcess(window: window, to: url) ? "cacheDisplay" : "failed" + } + window.orderOut(nil) + window.close() + return method + } + + private static func activate(_ window: NSWindow) { + NSRunningApplication.current.activate(options: [.activateAllWindows]) + NSApp.activate() + window.makeKeyAndOrderFront(nil) + window.makeMain() + window.orderFrontRegardless() + } + + private static func screencapture(windowNumber: Int, to url: URL) -> Bool { + try? FileManager.default.removeItem(at: url) + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture") + // -x silent, -o no shadow, -l one window. + process.arguments = ["-x", "-o", "-l\(windowNumber)", url.path] + do { + try process.run() + process.waitUntilExit() + } catch { + return false + } + let size = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0 + return process.terminationStatus == 0 && size > 0 + } + + private static func drawInProcess(window: NSWindow, to url: URL) -> Bool { + guard let view = window.contentView?.superview ?? window.contentView, + let representation = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { + return false + } + view.cacheDisplay(in: view.bounds, to: representation) + guard let data = representation.representation(using: .png, properties: [:]) else { + return false + } + return (try? data.write(to: url)) != nil + } + + // MARK: Sample data + + private static let pixel = DeviceDescriptor( + vendorID: 0x18D1, productID: 0x4EE4, busNumber: 20, deviceAddress: 3, + manufacturer: "Google", product: "Pixel 8", serial: "", summary: "Bus 020 Device 003: 18d1:4ee4", + usedAndroidQuirk: false) + private static let galaxy = DeviceDescriptor( + vendorID: 0x04E8, productID: 0x6863, busNumber: 20, deviceAddress: 5, + manufacturer: "Samsung", product: "Galaxy S24", serial: "", summary: "Bus 020 Device 005: 04e8:6863", + usedAndroidQuirk: false) + private static let drone = DeviceDescriptor( + vendorID: 0x2CA3, productID: 0x001F, busNumber: 20, deviceAddress: 7, + manufacturer: "", product: "RC Controller", serial: "", summary: "Bus 020 Device 007: 2ca3:001f", + usedAndroidQuirk: false) + + private static func session(_ state: RunState, device: DeviceDescriptor? = nil, + peer: String? = nil, failure: String = "") -> SessionStatus { + let device = device ?? pixel + let running = state == .running + return SessionStatus( + runState: state, rndisState: running ? .dataInitialized : .initializing, + linkUp: running, paused: false, + systemInterface: running ? "feth4012" : "", driverInterface: running ? "feth4013" : "", + deviceMAC: running ? "2a:41:9c:07:5e:11" : "", mtu: running ? 1500 : 0, + linkSpeedMbps: running ? 425 : 0, + vendorDescription: device.manufacturer, deviceDescription: device.product, + rxFrames: running ? 1_842_311 : 0, rxBytes: running ? 2_418_000_000 : 0, rxDropped: 0, + txFrames: running ? 912_440 : 0, txBytes: running ? 318_000_000 : 0, txDropped: 0, + rxQueueDepth: 0, linkKernelDrops: 0, txBackpressure: 0, + monotonicNanos: 1, fatalMessage: failure, peerAddress: peer) + } + + private static let internet = NetworkState( + hasAddress: true, address: "10.181.42.17", netmask: "255.255.255.0", + router: "10.181.42.1", dnsServers: ["10.181.42.1"], method: "DHCP", + serviceState: "BOUND", hasDefaultRoute: true, isPrimaryDefaultRoute: true) + + private static let logs: [LogEntry] = { + let start = Date().addingTimeInterval(-90) + let lines: [(LogLevel, String, String)] = [ + (.info, "control", "Found RNDIS device Google Pixel 8 (18d1:4ee4) on bus 20, address 3"), + (.info, "control", "RNDIS negotiation complete: version 1.0, MTU 1500, device aggregation limit 15800 bytes / 10 packets"), + (.info, "control", "Created feth4012 (host) / feth4013 (driver)"), + (.info, "bridge", "Data path running: 4 bulk OUT slots, 8 bulk IN transfers"), + (.info, "helper", "DHCP lease on feth4012: 10.181.42.17/24, router 10.181.42.1"), + (.warning, "usb", "bulk IN transfer timed out once; resubmitted"), + (.info, "helper", "Network service promoted to the top of the service order"), + ] + return lines.enumerated().map { index, line in + LogEntry(level: line.0, timestamp: start.addingTimeInterval(Double(index) * 6), + thread: line.1, message: line.2) + } + }() + + private static let windowSize = CGSize(width: Design.Window.defaultWidth, + height: Design.Window.defaultHeight) + + private static func content(_ model: AppModel) -> AnyView { + AnyView(ContentView(model: model) + .frame(width: model.interfaceStyle == .simple && model.helperAvailability.isAvailable + ? SimpleView.windowSize.width : nil)) + } + + private static func simple(_ id: String, _ title: String, _ note: String, + _ state: UISnapshotState) -> Scene { + var state = state + state.style = .simple + return Scene(id: id, flow: "simple", title: title, note: note, kind: .window, + size: SimpleView.windowSize, state: state, content: content) + } + + private static func detailed(_ id: String, _ title: String, _ note: String, + pane: Pane = .overview, advanced: Bool = false, + _ state: UISnapshotState) -> Scene { + var state = state + state.style = .full + return Scene(id: id, flow: "detailed", title: title, note: note, kind: .window, + size: windowSize, + preferences: [PreferenceKey.selectedPane: pane.rawValue, + PreferenceKey.advancedToolsEnabled: advanced], + state: state, content: content) + } + + private static var scenes: [Scene] { + var running = UISnapshotState() + running.devices = [pixel] + running.status = session(.running) + running.network = internet + running.rates = (down: 186_000_000, up: 24_000_000) + running.connectedFor = 754 + running.logs = logs + + var local = UISnapshotState() + local.devices = [drone] + local.status = session(.running, device: drone, peer: "192.168.42.1") + local.rates = (down: 3_200_000, up: 420_000) + local.connectedFor = 75 + + var failed = UISnapshotState() + failed.devices = [] + failed.failureMessage = "bulk IN transfer failed: [libusb: LIBUSB_ERROR_NO_DEVICE(-4)]" + + var ready = UISnapshotState() + ready.devices = [pixel] + + return [ + // Shared start + Scene(id: "01-setup", flow: "start", title: "Setup assistant", + note: "First launch: the background component must be enabled before anything else.", + kind: .window, size: windowSize, + state: UISnapshotState(helper: .missing(reason: "not registered"), style: nil), + content: content), + Scene(id: "02-setup-approval", flow: "start", title: "Setup: approve in System Settings", + note: "Shown when macOS asks the user to allow the background component.", + kind: .window, size: windowSize, + state: UISnapshotState(helper: .missing(reason: "approval"), needsApproval: true, + style: nil), + content: content), + Scene(id: "03-choose-layout", flow: "start", title: "Choose your look", + note: "Right after setup, new installs pick a layout; Simple is preselected.", + kind: .window, size: windowSize, state: UISnapshotState(style: nil), + content: content), + + // Simple + simple("10-simple-no-device", "No device", + "Plug-in hint; the button is dimmed.", UISnapshotState()), + simple("11-simple-ready", "Device ready", "One device found: one click to connect.", ready), + simple("12-simple-two-devices", "Two devices", + "The device chip becomes a menu to pick one.", + UISnapshotState(devices: [pixel, galaxy], selectedDeviceID: pixel.id)), + simple("13-simple-connecting", "Connecting", "Pulsing ring while the session starts.", + UISnapshotState(devices: [pixel], status: session(.starting))), + simple("14-simple-connected", "Connected", "Green button, status and live speed.", running), + simple("15-simple-local-device", "Local device without an address", + "A drone controller with no DHCP: one click applies a session-only address.", local), + simple("16-simple-failure", "Connection ended", + "Plain-language cause with Dismiss; details on hover.", failed), + simple("17-simple-auto-connect-waiting", "Auto-connect holding back", + "A phone is plugged in, but this Mac is on Wi-Fi, so it does not connect by itself.", + UISnapshotState(devices: [pixel], autoConnectEnabled: true, + autoConnectWaiting: true)), + Scene(id: "18-simple-settings", flow: "simple", title: "Gear: settings sheet", + note: "Layout, auto-connect, language, updates, and a way to all settings.", + kind: .panel, size: CGSize(width: 360, height: 520), + state: UISnapshotState(devices: [pixel], updateVersion: "1.4.0"), + content: { model in + AnyView(SimpleSettingsSheet(model: model, requestHelperUpdate: {})) + }), + + // Detailed + Scene(id: "20-announcement", flow: "detailed", title: "Announcement (updated installs)", + note: "Shown once to users updating from a version without layouts; they keep the detailed view.", + kind: .panel, size: CGSize(width: 520, height: 470), + state: UISnapshotState(style: .full, announcementPending: true), + content: { model in AnyView(LayoutAnnouncementSheet(model: model)) }), + detailed("21-detailed-no-device", "Overview: no device", "Waiting for a device.", + UISnapshotState()), + detailed("22-detailed-ready", "Overview: device ready", "Device found, not connected.", ready), + detailed("23-detailed-connected", "Overview: connected", + "Status, live chart, address.", running), + detailed("24-detailed-local-device", "Overview: local device", + "Explains a link without internet and offers a session-only address.", local), + detailed("25-detailed-failure", "Overview: connection ended", + "Failure banner with Dismiss.", failed), + detailed("26-detailed-device", "Device page", "Device choice and advanced options.", + pane: .device, running), + detailed("27-detailed-network", "Network page", "DHCP or static IP, DNS, route all traffic.", + pane: .network, running), + detailed("28-detailed-activity", "Activity page", "Live log.", pane: .activity, running), + detailed("29-detailed-settings", "Settings page", + "Background component, layout, general, updates.", pane: .settings, running), + detailed("30-detailed-interfaces", "Advanced: Interfaces", + "Opt-in advanced tools (shows the runner's own interfaces).", + pane: .interfaces, advanced: true, running), + Scene(id: "31-menu-bar-panel", flow: "detailed", title: "Menu bar panel", + note: "Same in both layouts: status, speeds, connect/disconnect.", + kind: .panel, size: CGSize(width: 280, height: 330), state: running, + content: { model in AnyView(MenuBarPanel(model: model)) }), + ] + } +} +#endif diff --git a/gui/Sources/TetherKitNextApp/UpdateChecker.swift b/gui/Sources/TetherKitNextApp/UpdateChecker.swift index af5ba62..863a322 100644 --- a/gui/Sources/TetherKitNextApp/UpdateChecker.swift +++ b/gui/Sources/TetherKitNextApp/UpdateChecker.swift @@ -3,21 +3,18 @@ import TetherKitNextIPC /// Checks GitHub Releases for a newer version. /// -/// * Only "check + guide", never automatically download and replace * -/// This project is distributed without a certificate (ad-hoc signing). Self-updating (the Sparkle kind) has to download a new .app to replace -/// itself, the download carries quarantine, and the replaced App would be blocked dead by Gatekeeper -- -/// the same wall as why Cask cannot be used. The real update channels are `brew upgrade` or a source rebuild, -/// and the App is only responsible for discovering the new version and putting the command within the user's reach. +/// This is the check-only fallback. Release builds update through Sparkle (SoftwareUpdater.swift); builds +/// without a Sparkle public key (local, ad-hoc, CI) use this instead, which only finds the new version and +/// links to its release page. In both cases it feeds the "new version" badge in Settings. /// -/// * Privacy * -/// Only GitHub's public REST API (releases/latest) is requested, carrying no local machine information. -/// The automatic check runs at most once a day and fails silently; -/// `defaults write com.tetherkitnext.app updateCheckDisabled -bool YES` turns it off completely. +/// Privacy: only GitHub's public REST API (releases/latest) is requested, with no local machine information. +/// The automatic check runs at most once a day and fails silently; +/// `defaults write com.tetherkitnext.app updateCheckDisabled -bool YES` turns it off completely. enum UpdateChecker { struct Release: Equatable, Sendable { /// The version number with the v prefix removed, such as "0.2.0". let version: String - /// The Release page, guiding the user to read the release notes / download. + /// The release page, guiding the user to the release notes / download. let pageURL: URL } @@ -38,13 +35,13 @@ enum UpdateChecker { } } - /// The current App's version number, from Info.plist (injected by build-gui.sh from CMakeLists). - /// The bare executable of `swift run` has no bundle, so it returns nil -- development builds do no checking. + /// The current app's version number, from Info.plist (injected by build-gui.sh from CMakeLists). + /// The bare executable of `swift run` has no bundle, so it returns nil and development builds do no checking. static var currentVersion: String? { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } - /// Gets the latest release. 404 = never released; any other non-200 is treated as failure. + /// Gets the latest release. 404 means never released; any other non-200 is treated as a failure. static func fetchLatestRelease() async throws -> Release { var request = URLRequest(url: endpoint) request.timeoutInterval = 10 @@ -56,15 +53,16 @@ enum UpdateChecker { guard http.statusCode == 200 else { throw Failure.badStatus(http.statusCode) } let payload = try JSONDecoder().decode(Payload.self, from: data) - // The URL is opened with NSWorkspace, so never trust the response to - // pick the scheme or host (file://, custom URL schemes, look-alikes). + // The URL is opened with NSWorkspace, so never trust the response to pick the scheme or host (file://, + // custom URL schemes, look-alikes). guard let pageURL = URL(string: payload.htmlURL), pageURL.scheme == "https", pageURL.host == "github.com" else { throw Failure.malformedPayload } return Release(version: normalize(payload.tagName), pageURL: pageURL) } - /// Whether candidate is newer than current. Compared segment by segment numerically, with missing segments as 0 and non-numeric segments as 0 -- - /// if it cannot be parsed, better to judge "not newer" than to pop up an update hint for a malformed tag. + /// Whether candidate is newer than current. Compared segment by segment numerically, with missing and + /// non-numeric segments as 0. If it cannot be parsed, "not newer" is better than an update hint for a malformed + /// tag. static func isNewer(_ candidate: String, than current: String) -> Bool { let lhs = components(of: candidate) let rhs = components(of: current) @@ -78,9 +76,8 @@ enum UpdateChecker { // MARK: - Implementation - /// `owner/repo` whose GitHub releases carry the DMGs. Read from the - /// `TetherKitNextUpdateRepository` Info.plist key so a fork publishes to (and - /// checks) its own releases without code changes. + /// `owner/repo` whose GitHub releases carry the DMGs. Read from the `TetherKitNextUpdateRepository` Info.plist + /// key so a fork publishes to (and checks) its own releases without code changes. static var repository: String { let configured = Bundle.main.object(forInfoDictionaryKey: "TetherKitNextUpdateRepository") as? String diff --git a/gui/Sources/TetherKitNextApp/UserPresence.swift b/gui/Sources/TetherKitNextApp/UserPresence.swift index 1dee8c5..5bb5da0 100644 --- a/gui/Sources/TetherKitNextApp/UserPresence.swift +++ b/gui/Sources/TetherKitNextApp/UserPresence.swift @@ -2,22 +2,18 @@ import Foundation import LocalAuthentication import TetherKitNextIPC -/// Confirms the user is at the Mac before a privileged action, with Touch ID -/// (or an Apple Watch, or the login password as fallback) instead of the -/// administrator password dialog. +/// Confirms the user is at the Mac before a privileged action, with Touch ID (or an Apple Watch, or the login +/// password as fallback) instead of the administrator password dialog. /// -/// ★ Why this is enough for a root daemon ★ +/// Why this is enough for a root daemon: the check runs in the app, so on its own it proves nothing to the +/// daemon. It is sound because of the XPC pinning of team-signed builds. The daemon only talks to +/// TetherKitNext.app signed by our own team, so the only program able to send it an "already confirmed" +/// request is this app, and this app always asks first. The daemon additionally requires the caller to be an +/// administrator (see `HelperService.authorize`), so the set of people who can connect is unchanged; only +/// how they prove it differs. /// -/// The check itself runs in the app, so on its own it proves nothing to the -/// daemon. What makes it sound is the XPC pinning of team-signed builds: the -/// daemon only talks to TetherKitNext.app signed by our own team, so the only -/// program able to send it an "already confirmed" request is this app, and -/// this app always asks first. The daemon additionally requires the caller -/// to be an administrator (see `HelperService.authorize`), so the set of -/// people who can connect is unchanged — only how they prove it is. -/// -/// Ad-hoc / development builds have no Team ID to pin, so `isAvailable` is -/// false there and the app keeps using the administrator dialog. +/// Ad-hoc / development builds have no Team ID to pin, so `isAvailable` is false there and the app keeps +/// using the administrator dialog. @MainActor enum UserPresence { enum Failure: Error { @@ -28,8 +24,8 @@ enum UserPresence { case unavailable } - /// One confirmation covers what follows it for this long, so Connect and - /// the automatic network setup right after it do not ask twice. + /// One confirmation covers what follows it for this long, so Connect and the automatic network setup right + /// after it do not ask twice. static let gracePeriod: TimeInterval = 5 * 60 private static var confirmedAt: Date? @@ -37,9 +33,8 @@ enum UserPresence { /// Team-signed builds only (see above). static var isAvailable: Bool { CodeSigning.currentTeamIdentifier != nil } - /// Asks for Touch ID / the login password unless a confirmation within the - /// grace period already exists. `reason` completes "TetherKitNext is trying - /// to …". + /// Asks for Touch ID / the login password unless a confirmation within the grace period already exists. + /// `reason` completes "TetherKitNext is trying to …". static func confirm(reason: String) async throws { if let confirmedAt, Date().timeIntervalSince(confirmedAt) < gracePeriod { return @@ -51,9 +46,8 @@ enum UserPresence { } do { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - // @Sendable: LocalAuthentication calls this on its own queue. - // Without it Swift 6 would infer main-actor isolation from the - // surrounding code and trap when it runs off the main thread. + // @Sendable: LocalAuthentication calls this on its own queue. Without it Swift 6 would infer main-actor + // isolation from the surrounding code and trap when it runs off the main thread. context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { @Sendable success, error in if success { diff --git a/gui/Sources/TetherKitNextApp/Views/Components.swift b/gui/Sources/TetherKitNextApp/Views/Components.swift index 5f5bc05..9288ad8 100644 --- a/gui/Sources/TetherKitNextApp/Views/Components.swift +++ b/gui/Sources/TetherKitNextApp/Views/Components.swift @@ -43,7 +43,8 @@ struct CopyableCommand: View { NSPasteboard.general.clearContents() NSPasteboard.general.setString(command, forType: .string) copied = true - // Restore after 2 seconds. What is given is the confirmation "copied", not a state that requires user action. + // Restore after 2 seconds. What is given is the confirmation "copied", not a state that requires user + // action. Task { try? await Task.sleep(for: .seconds(2)) copied = false diff --git a/gui/Sources/TetherKitNextApp/Views/ContentView.swift b/gui/Sources/TetherKitNextApp/Views/ContentView.swift index d7e0b2d..726f9f5 100644 --- a/gui/Sources/TetherKitNextApp/Views/ContentView.swift +++ b/gui/Sources/TetherKitNextApp/Views/ContentView.swift @@ -1,55 +1,55 @@ 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 { - mainSplit - } else { + // Setup assistant first; the layout is chosen only once the app works. + if !model.helperAvailability.isAvailable { OnboardingView(model: model) + } else if let style = model.interfaceStyle { + switch style { + case .simple: + SimpleView(model: model, requestHelperUpdate: requestHelperUpdate) + case .full: + mainSplit + .sheet(isPresented: Binding( + get: { model.interfaceStyleAnnouncementPending }, + set: { if !$0 { model.dismissInterfaceStyleAnnouncement() } })) { + LayoutAnnouncementSheet(model: model) + } + } + } else { + LayoutChooserView(model: model) } } .animation(.smooth(duration: 0.25), value: model.helperAvailability) + .animation(.smooth(duration: 0.25), value: model.interfaceStyle) + .onChange(of: advancedToolsEnabled) { _, enabled in + // Forget an advanced page once the section is hidden, so turning it back on later + // does not jump straight to it. + if !enabled, Pane(rawValue: storedPane)?.isAdvanced == true { + storedPane = Pane.overview.rawValue + } + } .alert(L(.alertOperationFailed), isPresented: Binding(get: { model.alertMessage != nil }, set: { if !$0 { model.alertMessage = nil } })) { @@ -92,14 +92,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) { @@ -144,6 +148,7 @@ struct ContentView: View { HelperMismatchBanner(mismatch: mismatch) { requestHelperUpdate() } } StatusHeroCard(model: model) + LinkKindCard(model: model) EnvironmentWarningCard(environment: model.environment) ThroughputCard(model: model) NetworkSummaryCard(model: model) { pane = .network } @@ -156,6 +161,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, @@ -216,6 +223,9 @@ struct Page: View { /// Connect / Disconnect — the one primary action, always in the toolbar. struct ConnectButton: View { @Bindable var model: AppModel + /// ⌘↩ belongs to one instance per window: the toolbar's. The copy in the + /// status card passes false so the shortcut is not registered twice. + var hasKeyboardShortcut = true var body: some View { let isRunning = model.status.runState == .running @@ -244,7 +254,7 @@ struct ConnectButton: View { .tint(isRunning ? .red : .accentColor) .disabled(model.isBusy || isTransitional || (!isRunning && model.devices.isEmpty)) .help(model.devices.isEmpty && !isRunning ? L(.connectDisabledHint) : "") - .keyboardShortcut(.return, modifiers: .command) + .keyboardShortcut(hasKeyboardShortcut ? KeyboardShortcut(.return, modifiers: .command) : nil) } } @@ -258,7 +268,7 @@ private struct SidebarStatus: View { .fill(Design.accent(for: model.status.runState)) .frame(width: 8, height: 8) VStack(alignment: .leading, spacing: 1) { - Text(Design.statusLabel(for: model.status)) + Text(model.statusLabel) .font(.callout.weight(.medium)) .lineLimit(1) if model.status.runState == .running { diff --git a/gui/Sources/TetherKitNextApp/Views/DeviceCard.swift b/gui/Sources/TetherKitNextApp/Views/DeviceCard.swift index ca8f989..ee98959 100644 --- a/gui/Sources/TetherKitNextApp/Views/DeviceCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/DeviceCard.swift @@ -3,8 +3,8 @@ import TetherKitNextIPC /// Device selection and session parameters. /// -/// Once the session is running the whole block becomes read-only -- changing the MTU or switching devices both require reconnecting, and making it "changeable but ineffective" -/// would be more confusing than simply disabling it. +/// Once the session is running the whole block is read-only: changing the MTU or switching devices requires +/// reconnecting, and "changeable but ineffective" would be more confusing than disabled. struct DeviceCard: View { @Bindable var model: AppModel @@ -43,7 +43,7 @@ struct DeviceCard: View { ContentUnavailableView { Label(L(.noDeviceDetected), systemImage: "cable.connector.slash") } description: { - // These three are exactly all the common reasons RNDIS cannot connect on macOS, ordered by hit rate. + // These three are the common reasons RNDIS cannot connect on macOS, ordered by hit rate. VStack(alignment: .leading, spacing: 4) { Text(L(.deviceChecklistCable)) Text(L(.deviceChecklistTethering)) @@ -66,16 +66,16 @@ struct DeviceCard: View { } } - // Long explanations always go into hover tooltips: these two parameters cannot be tuned once a year, yet explanatory text occupies - // the screen every day -- only the single sentence "when you need to touch it" is left on the UI. + // Long explanations go into hover tooltips: these two parameters are tuned maybe once a year, yet + // explanatory text would occupy the screen every day, so only the one-sentence "when you need to touch it" stays. private var tuningControls: some View { VStack(alignment: .leading, spacing: Design.Spacing.small) { HStack { Text("MTU") .font(.callout) .frame(width: 92, alignment: .leading) - // Step by 100 rather than 1: the MTU must be negotiated with the peer, byte-by-byte fine-tuning is meaningless, - // and round numbers like 1500 / 1400 / 2000 are the values users will really try. + // Step by 100 rather than 1: the MTU is negotiated with the peer, so byte-by-byte tuning is + // meaningless, and round numbers like 1500 / 1400 / 2000 are what users really try. Stepper(value: $model.requestedMTU, in: 576...2048, step: 100) { Text(L(.mtuBytes, String(model.requestedMTU))) .font(.system(.callout, design: .monospaced)) @@ -83,11 +83,12 @@ struct DeviceCard: View { .disabled(isLocked) Spacer() } - // The upper limit is known only after the environment preflight, so these are two independent messages rather than concatenation -- - // the half sentence "(this machine's limit N)" lands in another position in the English sentence and cannot be concatenated. + // The upper limit is known only after the environment preflight, so these are two independent messages + // rather than a concatenation: the half sentence "(this Mac's limit N)" lands in another position in + // the English sentence. Text(model.environment.map { L(.mtuHelpWithLimit, Int($0.fethMaxMTU)) } ?? L(.mtuHelp)) - .font(.caption) + .font(.footnote) .foregroundStyle(.secondary) .help(L(.mtuTooltip)) @@ -95,7 +96,7 @@ struct DeviceCard: View { VStack(alignment: .leading, spacing: 1) { Text(L(.adoptDeviceMAC)) Text(L(.adoptDeviceMACHelp)) - .font(.caption) + .font(.footnote) .foregroundStyle(.secondary) } } @@ -137,7 +138,7 @@ private struct DeviceRow: View { Spacer(minLength: 0) if device.usedAndroidQuirk { - // This information is very useful for troubleshooting: taking the fallback path indicates the device's CDC descriptor is not + // Useful for troubleshooting: taking the fallback path means the device's CDC descriptor is not // standard, and if problems arise later this is the first clue to look at. StatusBadge(text: L(.compatibilityMode), color: .orange) .help(L(.compatibilityModeTooltip)) diff --git a/gui/Sources/TetherKitNextApp/Views/FailureBanner.swift b/gui/Sources/TetherKitNextApp/Views/FailureBanner.swift new file mode 100644 index 0000000..a9237e7 --- /dev/null +++ b/gui/Sources/TetherKitNextApp/Views/FailureBanner.swift @@ -0,0 +1,79 @@ +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// The one way a failed session is presented, in the simple view, the status +/// card and the menu bar panel. +/// +/// A red symbol marks it as an error; the sentence that says what to do is in +/// the primary text color (red body text is hard to read and reads as alarm, +/// not guidance). The raw message sits behind "Details" (selectable, for bug +/// reports) and Dismiss is always the same bordered button. +struct FailureBanner: View { + enum Style { + /// Centered column for the simple view. + case centered + /// Leading-aligned, for the detailed status card. + case leading + /// Small and without the disclosure (the raw message is a tooltip); + /// the menu bar panel has little room. + case menuBar + } + + let failure: SessionFailure + var style: Style = .leading + let onDismiss: () -> Void + + @State private var showsDetails = false + + private var alignment: HorizontalAlignment { style == .centered ? .center : .leading } + private var textAlignment: TextAlignment { style == .centered ? .center : .leading } + + var body: some View { + VStack(alignment: alignment, spacing: Design.Spacing.tight) { + HStack(alignment: .firstTextBaseline, spacing: Design.Spacing.tight) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.red) + .accessibilityHidden(true) + Text(failure.cause.headline) + .font(style == .menuBar ? .callout : .body) + .foregroundStyle(.primary) + .multilineTextAlignment(textAlignment) + .fixedSize(horizontal: false, vertical: true) + } + .help(style == .menuBar ? failure.message : "") + + if style != .menuBar { + DisclosureGroup(L(.sessionFailureDetails), isExpanded: $showsDetails) { + ScrollView { + Text(failure.message) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .textSelection(.enabled) + } + .frame(maxHeight: 80) + } + .font(.footnote) + .frame(maxWidth: style == .centered ? 300 : .infinity) + } + + Button(L(.dismiss), action: onDismiss) + .buttonStyle(.bordered) + } + .accessibilityElement(children: .contain) + } +} + +extension SessionFailureCause { + /// What the user should do next, in a sentence. + var headline: String { + switch self { + case .disconnected: return L(.sessionFailureDisconnected) + case .accessDenied: return L(.sessionFailureAccessDenied) + case .busy: return L(.sessionFailureBusy) + case .timedOut: return L(.sessionFailureTimedOut) + case .other: return L(.sessionFailedTitle) + } + } +} diff --git a/gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift b/gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift new file mode 100644 index 0000000..9caf345 --- /dev/null +++ b/gui/Sources/TetherKitNextApp/Views/InterfacesPage.swift @@ -0,0 +1,130 @@ +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 while the page is shown and the window is visible; .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 { + // Closing the window only orders it out (MainWindowController keeps the view tree, + // so .task is not cancelled); do not sample for a window nobody can see. After + // reopening, the first sample shows 0 instead of an average over the gap. + if MainWindowController.shared?.isVisible == false { + tracker = InterfaceRateTracker() + } else { + 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/LayoutViews.swift b/gui/Sources/TetherKitNextApp/Views/LayoutViews.swift new file mode 100644 index 0000000..2340503 --- /dev/null +++ b/gui/Sources/TetherKitNextApp/Views/LayoutViews.swift @@ -0,0 +1,235 @@ +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// A miniature drawing of a layout, used wherever the user picks one (the +/// chooser after setup, the announcement for updated installs, Settings). +/// +/// Drawn with shapes rather than screenshots: it follows light/dark mode and +/// the accent color, needs no per-language images, and cannot go stale when a +/// card changes. +struct LayoutPreview: View { + let style: InterfaceStyle + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(.background) + RoundedRectangle(cornerRadius: 10, style: .continuous) + .strokeBorder(.quaternary) + switch style { + case .simple: simple + case .full: full + } + } + .aspectRatio(1.35, contentMode: .fit) + .accessibilityHidden(true) + } + + private var simple: some View { + GeometryReader { geometry in + let side = min(geometry.size.width, geometry.size.height) + VStack(spacing: side * 0.07) { + Capsule().fill(.quaternary) + .frame(width: side * 0.42, height: side * 0.08) + ZStack { + Circle().fill(Design.connectedGradient) + Image(systemName: "power") + .font(.system(size: side * 0.16, weight: .bold)) + .foregroundStyle(.white) + } + .frame(width: side * 0.4, height: side * 0.4) + HStack(spacing: 4) { + Circle().fill(.green).frame(width: side * 0.05, height: side * 0.05) + Capsule().fill(.quaternary).frame(width: side * 0.3, height: side * 0.05) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .overlay(alignment: .topTrailing) { + Image(systemName: "gearshape.fill") + .font(.system(size: side * 0.08)) + .foregroundStyle(.tertiary) + .padding(side * 0.06) + } + } + } + + private var full: some View { + GeometryReader { geometry in + let width = geometry.size.width + let height = geometry.size.height + HStack(spacing: width * 0.03) { + // Sidebar + VStack(alignment: .leading, spacing: height * 0.05) { + ForEach(0..<5, id: \.self) { index in + Capsule().fill(index == 0 ? AnyShapeStyle(.tint) : AnyShapeStyle(.quaternary)) + .frame(height: height * 0.05) + } + Spacer() + } + .padding(width * 0.03) + .frame(width: width * 0.24) + .background(.quinary) + // Cards + VStack(spacing: height * 0.04) { + HStack(spacing: width * 0.03) { + card + card + } + ZStack(alignment: .bottomLeading) { + card + Path { path in + let w = width * 0.62, h = height * 0.22 + path.move(to: CGPoint(x: 0, y: h)) + for step in 1...8 { + let x = w * CGFloat(step) / 8 + let y = h * (0.35 + 0.5 * abs(sin(CGFloat(step) * 1.3))) + path.addLine(to: CGPoint(x: x, y: y)) + } + } + .stroke(Color.accentColor, lineWidth: 1.5) + .padding(width * 0.03) + } + card + } + .padding(.vertical, height * 0.06) + .padding(.trailing, width * 0.04) + } + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + } + + private var card: some View { + RoundedRectangle(cornerRadius: 4, style: .continuous).fill(.quaternary.opacity(0.7)) + } +} + +/// Two selectable cards, one per layout. +struct LayoutChoiceCards: View { + let selection: InterfaceStyle? + let onSelect: (InterfaceStyle) -> Void + var compact = false + + var body: some View { + HStack(alignment: .top, spacing: Design.Spacing.medium) { + ForEach(InterfaceStyle.allCases, id: \.self) { style in + Button { onSelect(style) } label: { card(style) } + .buttonStyle(.plain) + .accessibilityElement(children: .combine) + .accessibilityAddTraits(selection == style ? [.isSelected] : []) + } + } + } + + private func card(_ style: InterfaceStyle) -> some View { + let selected = selection == style + return VStack(alignment: .leading, spacing: Design.Spacing.small) { + LayoutPreview(style: style) + HStack(spacing: Design.Spacing.tight) { + Image(systemName: selected ? "checkmark.circle.fill" : "circle") + .foregroundStyle(selected ? AnyShapeStyle(.tint) : AnyShapeStyle(.tertiary)) + Text(style.displayName).font(.headline) + } + if !compact { + Text(style.summary) + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(Design.Spacing.small) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: Design.Radius.card, style: .continuous) + .fill(selected ? AnyShapeStyle(.tint.opacity(0.12)) : AnyShapeStyle(.quinary))) + .overlay(RoundedRectangle(cornerRadius: Design.Radius.card, style: .continuous) + .strokeBorder(selected ? AnyShapeStyle(.tint) : AnyShapeStyle(Color.clear), lineWidth: 2)) + .contentShape(RoundedRectangle(cornerRadius: Design.Radius.card)) + } +} + +extension InterfaceStyle { + var displayName: String { + switch self { + case .simple: return L(.layoutSimpleName) + case .full: return L(.layoutFullName) + } + } + + var summary: String { + switch self { + case .simple: return L(.layoutSimpleDescription) + case .full: return L(.layoutFullDescription) + } + } +} + +/// Shown once, right after the setup assistant: the new user picks a layout +/// (simple preselected) before seeing the main window. +struct LayoutChooserView: View { + var model: AppModel + @State private var selection: InterfaceStyle = .simple + + var body: some View { + ScrollView { + VStack(spacing: Design.Spacing.large) { + VStack(spacing: Design.Spacing.small) { + Text(L(.layoutChooserTitle)) + .font(.system(.largeTitle, design: .rounded).weight(.semibold)) + Text(L(.layoutChooserSubtitle)) + .foregroundStyle(.secondary) + } + .multilineTextAlignment(.center) + + LayoutChoiceCards(selection: selection) { selection = $0 } + .frame(maxWidth: 620) + + Button { + model.setInterfaceStyle(selection) + } label: { + Text(L(.layoutContinue)).frame(minWidth: 140) + } + .primaryActionButtonStyle() + .controlSize(.large) + .keyboardShortcut(.defaultAction) + } + .padding(Design.Spacing.large) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + .scrollBounceBehavior(.basedOnSize) + } +} + +/// One-time announcement for installs updated from a version without layouts. +/// They keep the detailed view; this only shows the new one and how to switch. +struct LayoutAnnouncementSheet: View { + var model: AppModel + + var body: some View { + VStack(alignment: .leading, spacing: Design.Spacing.medium) { + Label(L(.layoutAnnouncementTitle), systemImage: "sparkles") + .font(.title2.weight(.semibold)) + Text(L(.layoutAnnouncementBody)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + // Choosing a card acts at once: Simple switches, Detailed keeps the + // current layout and closes the announcement. + LayoutChoiceCards(selection: model.interfaceStyle, onSelect: { style in + switch style { + case .simple: model.setInterfaceStyle(.simple) + case .full: model.dismissInterfaceStyleAnnouncement() + } + }, compact: true) + HStack { + Spacer() + Button(L(.dismiss)) { model.dismissInterfaceStyleAnnouncement() } + .buttonStyle(.bordered) + .keyboardShortcut(.cancelAction) + Button(L(.layoutTrySimple)) { model.setInterfaceStyle(.simple) } + .keyboardShortcut(.defaultAction) + .primaryActionButtonStyle() + } + } + .padding(Design.Spacing.large) + .frame(width: 520) + } +} diff --git a/gui/Sources/TetherKitNextApp/Views/LinkKindCard.swift b/gui/Sources/TetherKitNextApp/Views/LinkKindCard.swift new file mode 100644 index 0000000..23b1845 --- /dev/null +++ b/gui/Sources/TetherKitNextApp/Views/LinkKindCard.swift @@ -0,0 +1,163 @@ +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// Explains links that are not (yet) internet connections, on the overview. +/// +/// Hidden for the normal phone case (a lease with a router) and when not +/// connected, so everyday tethering looks exactly as before. Shown for: +/// * waiting for DHCP (slow phones; within the grace period), +/// * local devices (drones and controllers, FPV goggles, boards in USB gadget +/// mode, cameras): an address but no router, +/// * no address at all: offers a session-only address next to the device's +/// own address when the bridge has seen it. +/// Everything here is live (`AppModel.linkAssessment`) and nothing is saved. +struct LinkKindCard: View { + var model: AppModel + @State private var addressInput = "" + + var body: some View { + content + // The card view outlives sessions; an address typed for one device must not be + // applied to the next one with a stray Return. + .onChange(of: model.status.runState) { _, state in + if state != .running { addressInput = "" } + } + } + + @ViewBuilder + private var content: some View { + switch model.linkAssessment { + case .notConnected, .notConfigured, .internet: + EmptyView() + + case .waitingForAddress: + Card(title: L(.linkWaitingTitle), systemImage: "hourglass") { + HStack(spacing: Design.Spacing.small) { + ProgressView().controlSize(.small) + explanation(L(.linkWaitingBody)) + } + } + + case .localLink(let address, let peer, let selfAssigned): + Card(title: L(.linkLocalTitle), systemImage: "link") { + VStack(alignment: .leading, spacing: Design.Spacing.small) { + explanation(L(.linkLocalBody)) + addresses(mac: address, peer: peer) + if selfAssigned { + detail(L(.linkSelfAssignedNote)) + } + routeAllNote + sessionOnlyControls + autoConfigureNote + } + } + + case .noAddress(let peer, let suggestion): + Card(title: L(.linkNoAddressTitle), systemImage: "questionmark.circle") { + VStack(alignment: .leading, spacing: Design.Spacing.small) { + explanation(L(.linkNoAddressBody)) + addresses(mac: nil, peer: peer) + HStack(spacing: Design.Spacing.small) { + TextField(suggestion ?? L(.linkAddressPlaceholder), text: $addressInput) + .textFieldStyle(.roundedBorder) + .font(.body.monospaced()) + .frame(maxWidth: 220) + .onSubmit { useAddress(fallback: suggestion) } + Button(L(.linkUseAddress)) { useAddress(fallback: suggestion) } + .disabled(model.isBusy || (trimmedInput.isEmpty && suggestion == nil)) + Spacer() + Button(L(.linkRetryAutomatic)) { + Task { await model.retrySavedNetworkConfiguration() } + } + .disabled(model.isBusy) + } + detail(L(.linkNoAddressPhoneHint)) + routeAllNote + autoConfigureNote + } + } + } + } + + // MARK: - Pieces + + private var trimmedInput: String { + addressInput.trimmingCharacters(in: .whitespaces) + } + + private func useAddress(fallback: String?) { + let address = trimmedInput.isEmpty ? (fallback ?? "") : trimmedInput + guard !address.isEmpty else { return } + Task { await model.useSessionOnlyAddress(address) } + } + + private func explanation(_ text: String) -> some View { + Text(text) + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + private func detail(_ text: String) -> some View { + Text(text) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + private func addresses(mac: String?, peer: String?) -> some View { + Grid(alignment: .leading, horizontalSpacing: Design.Spacing.large, + verticalSpacing: Design.Spacing.tight) { + if let mac { + GridRow { + Text(L(.linkThisMac)).foregroundStyle(.secondary) + Text(verbatim: mac).font(.body.monospaced()).textSelection(.enabled) + } + } + GridRow { + Text(L(.linkDevice)).foregroundStyle(.secondary) + if let peer { + Text(verbatim: peer).font(.body.monospaced()).textSelection(.enabled) + } else { + Text(L(.linkPeerUnknown)).foregroundStyle(.secondary) + } + } + } + .font(.callout) + } + + @ViewBuilder + private var routeAllNote: some View { + if model.networkConfiguration.setDefaultRoute { + Label(L(.linkRouteAllSkipped), systemImage: "info.circle") + .font(.caption) + .foregroundStyle(.secondary) + } + } + + @ViewBuilder + private var sessionOnlyControls: some View { + if model.sessionOnlyAddress != nil { + HStack { + detail(L(.linkSessionOnlyNote)) + Spacer() + Button(L(.linkRetryAutomatic)) { + Task { await model.retrySavedNetworkConfiguration() } + } + .disabled(model.isBusy) + } + } + } + + @ViewBuilder + private var autoConfigureNote: some View { + if let note = model.autoConfigureNote { + Text(note) + .font(.caption2) + .foregroundStyle(.tertiary) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } + } +} diff --git a/gui/Sources/TetherKitNextApp/Views/LogCard.swift b/gui/Sources/TetherKitNextApp/Views/LogCard.swift index 8790313..efe7539 100644 --- a/gui/Sources/TetherKitNextApp/Views/LogCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/LogCard.swift @@ -1,11 +1,12 @@ import SwiftUI import TetherKitNextIPC -/// The log panel. Resident at the bottom of the right column, consuming all the height left over by the two-column layout -- the larger the window the more -/// can be seen, rather than being folded up waiting for the user to expand it (the old version's folding was a compromise a single-column layout could not fit). +/// The log panel. Resident at the bottom of the right column, consuming all the height left over by the +/// two-column layout: the larger the window, the more can be seen, instead of being folded up until the +/// user expands it. /// -/// When something goes wrong it is the only useful thing, so three things were done: filterable by level, automatic scroll to the bottom, -/// and one-click copy of everything (users can paste it directly when reporting an issue). +/// When something goes wrong it is the only useful thing, so it can be filtered by level, scrolls to the +/// bottom automatically, and copies everything with one click (users can paste it directly into an issue report). struct LogCard: View { @Bindable var model: AppModel @State private var autoScroll = true @@ -75,22 +76,25 @@ struct LogCard: View { .padding(Design.Spacing.small) .frame(maxWidth: .infinity, alignment: .leading) } - // Flexible height: consumes the remaining space of the right column. The minimum guarantees that in extreme cases (window pressed to the minimum, - // the cards above all in their tallest state) a few lines can still be seen, rather than being squeezed into a slit. - // 90 ~= four lines -- the whole page's budget is "fits even in the minimum window (content height 700)", - // and after the left column gained the privileged-component management row, this is the only reasonable stretch-absorbing layer. + // Flexible height: consumes the remaining space of the right column. The minimum guarantees that in extreme + // cases (window at its minimum, the cards above all in their tallest state) a few lines can still be seen + // instead of a slit. 90 ~= four lines; the whole page's budget is "fits in the minimum window (content + // height 700)", and this is the only reasonable stretch-absorbing layer in the left column's management + // row. // - // idealHeight must be pinned: outside the whole page there is a backstop ScrollView, which measures content - // using ideal sizes, and the ideal height of a nested ScrollView = the height of all logs expanded - // -- if not pinned, once there are many logs the whole page gets stretched open, and scrolling comes back. + // idealHeight must be pinned: a backstop ScrollView outside the whole page measures content by ideal sizes, + // and the ideal height of a nested ScrollView is the height of all logs expanded. Unpinned, many logs would + // stretch the whole page open and bring scrolling back. .frame(minHeight: 90, idealHeight: 90, maxHeight: .infinity) .background(.quaternary.opacity(0.35), in: RoundedRectangle(cornerRadius: Design.Radius.control)) + // Without the clip, rows scrolled past the edge draw over the rounded corners. + .clipShape(RoundedRectangle(cornerRadius: Design.Radius.control)) + // No animation: at several lines a second, each new animated scroll interrupts the previous one and the + // view jitters. .onChange(of: model.filteredLogs.last?.id) { _, newValue in guard autoScroll, let newValue else { return } - withAnimation(.easeOut(duration: 0.15)) { - proxy.scrollTo(newValue, anchor: .bottom) - } + proxy.scrollTo(newValue, anchor: .bottom) } } } diff --git a/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift b/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift index e598bfc..a21c55d 100644 --- a/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift +++ b/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift @@ -1,11 +1,12 @@ import AppKit import SwiftUI import TetherKitNextIPC +import TetherKitNextUIModel /// The resident label in the menu bar: status icon + real-time rate. /// -/// The rate text is shown only while a session is running -- a string of "0K" when idle is just noise, and the icon itself already makes the -/// state clear. Digits are monospaced, to avoid pushing other menu bar items on the right around when the rate jumps. +/// The rate text is shown only while a session is running: "0K" when idle is just noise, and the icon already +/// makes the state clear. Digits are monospaced so a changing rate does not push the other menu bar items around. struct MenuBarLabel: View { var model: AppModel @AppStorage(PreferenceKey.menuBarShowsSpeed) private var showsSpeed = true @@ -14,8 +15,7 @@ struct MenuBarLabel: View { HStack(spacing: 2) { Image(systemName: Design.statusSymbol(for: model.status)) if model.status.runState == .running, showsSpeed { - // Fully monospaced + fixed-width RateFormat: the status item - // keeps one width whatever the rate (upstream issue #1). + // Fully monospaced + fixed-width RateFormat: the status item keeps one width whatever the rate. Text(speedText) .font(.system(size: 11, weight: .medium, design: .monospaced)) } @@ -28,13 +28,12 @@ struct MenuBarLabel: View { } } -/// The small panel after clicking open a menu bar item. +/// The small panel shown after clicking the menu bar item. /// -/// Content is chosen by "what you need to know at a glance": status, rate, NIC and address, plus two actions -/// (open the main window, quit). Configuration, charts and logs all stay in the main window -- the panel is not a second UI. +/// Content is what you need to know at a glance: status, rate, interface and address, plus two actions (open +/// the main window, quit). Configuration, charts and logs 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 } @@ -43,18 +42,11 @@ struct MenuBarPanel: View { VStack(alignment: .leading, spacing: Design.Spacing.small) { header - switch status.runState { - case .running: + if status.runState == .running { runningDetails - case .failed: - if !status.fatalMessage.isEmpty { - Text(status.fatalMessage) - .font(.caption) - .foregroundStyle(.red) - .lineLimit(3) - .fixedSize(horizontal: false, vertical: true) - } - default: + } else if let failure = model.lastFailure, !status.runState.isTransitional { + FailureBanner(failure: failure, style: .menuBar) { model.dismissFailure() } + } else { idleHint } @@ -66,10 +58,9 @@ struct MenuBarPanel: View { } .padding(Design.Spacing.medium) .frame(width: 280) - // Same reason as the main window: messages come from a global table lookup, and changing the language will not make any @Observable property - // "appear" to change, so an explicit identity is needed to force a rebuild. The panel itself refreshes with polling, - // and without this line the language would also catch up in the next period -- but when changing the language from the panel, the user is staring at - // this very panel, and lagging a beat would be taken as not having taken effect. + // Same reason as the main window: messages come from a global table that SwiftUI cannot observe, so an + // explicit identity forces a rebuild. The panel would catch up on the next poll anyway, but when the user + // changes the language from the panel they are looking at it, and a lag would read as "did not take effect". .id(model.languageRevision) } @@ -78,7 +69,7 @@ struct MenuBarPanel: View { Circle() .fill(Design.accent(for: status.runState)) .frame(width: 8, height: 8) - Text(Design.statusLabel(for: status)) + Text(model.statusLabel) .font(.headline) Spacer() if let duration = model.connectedDuration { @@ -120,16 +111,17 @@ struct MenuBarPanel: View { HStack { Button(L(.openMainWindow)) { dismiss() - presentMainWindow(model, openWindow) + MainWindowController.shared?.present() } .secondaryActionButtonStyle() .controlSize(.small) Spacer() - // In menu-bar-only mode this panel is the sole entry point, and the language switch must be reachable here too -- - // otherwise a user who cannot understand the UI would first have to know "go to the App menu" to change the language, - // and in this mode the App menu is visible only when the window is opened. + // In menu-bar-only mode this panel is the sole entry point, so the language switch must be reachable + // here + // too; otherwise a user who cannot read the UI would first have to know to go to the App menu, which is + // visible only when the window is open. languageMenu Button(L(.quit)) { @@ -139,8 +131,8 @@ struct MenuBarPanel: View { } if status.runState == .running { - // The session belongs to the helper, and quitting the App does not affect it -- this must be said out loud, - // otherwise users would think "quit = disconnect" and not dare to click. + // The session belongs to the helper, and quitting the app does not affect it. Say so, or users would + // think "quit = disconnect" and not dare to click. Text(L(.quitTooltip)) .font(.caption2) .foregroundStyle(.tertiary) @@ -149,7 +141,7 @@ struct MenuBarPanel: View { } } - /// The language switch. Options are written as native-language names and are not translated with the UI language -- see the explanation of LanguageMenu. + /// The language switch. Options are written as native-language names and are not translated; see LanguageMenu. private var languageMenu: some View { Menu { LanguagePicker(model: model) @@ -157,11 +149,14 @@ struct MenuBarPanel: View { .labelsHidden() } label: { Image(systemName: "globe") + .frame(minWidth: 24, minHeight: 24) + .contentShape(Rectangle()) } .menuStyle(.borderlessButton) .menuIndicator(.hidden) .fixedSize() .help(L(.languageLabel)) + .accessibilityLabel(L(.languageMenuTitle)) } private func speedRow(symbol: String, caption: String, bitsPerSecond: Double, diff --git a/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift b/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift index 343e9a3..59183bd 100644 --- a/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift @@ -4,28 +4,29 @@ import TetherKitNextIPC /// Connectivity method configuration: DHCP or static IP. /// -/// * Why the "currently in effect" column exists separately * -/// It shows the state **read back from the system**, not the value we applied. The two may differ -- -/// the most typical is DNS in static mode: IPConfiguration publishes DNS only in DHCP mode, -/// and in static mode all we can do is best-effort add a key, and whether the system adopts it depends on IPMonitor. -/// Rather than promise the user a result that may not hold, it is better to lay out the real state. +/// The "currently in effect" column is separate because it shows the state read back from the system, not the +/// value we applied, and the two may differ. The typical case is DNS in static mode: IPConfiguration +/// publishes DNS only in DHCP mode, so we can only add a key on a best-effort basis, and whether the system +/// adopts it depends on IPMonitor. Showing the real state beats promising a result that may not hold. /// -/// The height of this card directly determines whether the left column fits on one screen (the tallest state is "static form + currently in effect" -/// both expanded), so the input cells and readback values are all arranged in two columns, and long explanations all go into hover tooltips. +/// The height of this card decides whether the left column fits on one screen (the tallest state is "static +/// form + currently in effect" both expanded), so input cells and readback values are arranged in two columns +/// and long explanations go into hover tooltips. struct NetworkCard: View { @Bindable var model: AppModel - /// Disable the whole block when the NIC has not been created yet -- there is no NIC to configure, and letting the user fill in and then report an error is the worst order. + /// Before a session there is no interface to apply to, but the settings stay editable: they are saved as they + /// change and applied automatically on connect, so only Apply/Clear wait for it. private var interfaceReady: Bool { !model.status.systemInterface.isEmpty } private var canAddDNS: Bool { - // The upper limit matches the C ABI's TK_DNS_MAX; extra ones would be dropped, so it is better simply not to let them be added. + // The upper limit matches the C ABI's TK_DNS_MAX; extra entries would be dropped, so do not let them be added. model.networkConfiguration.dnsServers.count < 4 } - /// The hover explanation of static DNS. It is information at the "when you need to care" level, - /// and does not deserve a permanent row. - /// A computed property rather than `static let`: the latter is evaluated only once and would no longer update after switching the language. + /// The hover explanation of static DNS. It is "when you need to care" information and does not deserve a + /// permanent row. A computed property rather than `static let`, which is evaluated once and would not update + /// after a language switch. private static var dnsHint: String { L(.dnsEffectivenessTooltip) } var body: some View { @@ -51,17 +52,6 @@ struct NetworkCard: View { interface: model.status.systemInterface) } } - .disabled(!interfaceReady) - .opacity(interfaceReady ? 1 : 0.55) - .overlay(alignment: .center) { - if !interfaceReady { - Text(L(.connectBeforeConfiguring)) - .font(.callout) - .foregroundStyle(.secondary) - .padding(Design.Spacing.small) - .background(.regularMaterial, in: Capsule()) - } - } } } @@ -74,8 +64,8 @@ struct NetworkCard: View { private var modePicker: some View { Picker(L(.ipModeLabel), selection: $model.networkConfiguration.mode) { - // Deliberately not putting "do not configure" in the picker: it is an action (revoke), not a connectivity - // method. Mixing them would make people think choosing it already takes effect. + // "Do not configure" is not in the picker: it is an action (revoke), not a connectivity method, and mixing + // them would suggest that choosing it already takes effect. Text(IPMode.dhcp.displayName).tag(IPMode.dhcp) Text(IPMode.manual.displayName).tag(IPMode.manual) } @@ -88,14 +78,14 @@ struct NetworkCard: View { Label(L(.dhcpHelp), systemImage: "wand.and.stars") .font(.callout) Text(L(.dhcpTooltip)) - .font(.caption) + .font(.footnote) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } } - /// The static form. The four address cells are arranged in a two-column grid -- IPv4 is short, half-column width is enough, - /// and the height is directly halved. + /// The static form. The four address cells are arranged in a two-column grid: IPv4 is short, so half-column + /// width is enough and the height is halved. private var manualForm: some View { Grid(alignment: .leading, horizontalSpacing: Design.Spacing.medium, @@ -122,7 +112,8 @@ struct NetworkCard: View { dnsField(at: 0) } } - // DNS entries from the 2nd on each occupy the right cell of a row, with the left cell empty -- aligned with the DNS above. + // DNS entries from the 2nd on each occupy the right cell of a row, with the left cell empty, aligned with + // the DNS above. ForEach(Array(model.networkConfiguration.dnsServers.indices.dropFirst()), id: \.self) { index in GridRow { @@ -135,15 +126,29 @@ struct NetworkCard: View { /// One DNS entry: input cell + delete, and the last one also carries an "Add". private func dnsField(at index: Int) -> some View { - HStack(spacing: Design.Spacing.tight) { + // Bounds-checked binding: after a row is removed SwiftUI can still evaluate the old row's binding once before + // rebuilding, and a plain array subscript would trap. + let text = Binding( + get: { + let servers = model.networkConfiguration.dnsServers + return servers.indices.contains(index) ? servers[index] : "" + }, + set: { newValue in + if model.networkConfiguration.dnsServers.indices.contains(index) { + model.networkConfiguration.dnsServers[index] = newValue + } + }) + return HStack(spacing: Design.Spacing.tight) { AddressField(label: index == 0 ? "DNS" : "", - placeholder: "223.5.5.5", - text: $model.networkConfiguration.dnsServers[index], - isValid: model.networkConfiguration.dnsServers[index].isEmpty - || NetworkValidator.isValidIPv4(model.networkConfiguration.dnsServers[index])) + placeholder: "1.1.1.1", + text: text, + isValid: text.wrappedValue.isEmpty + || NetworkValidator.isValidIPv4(text.wrappedValue)) Button { - model.networkConfiguration.dnsServers.remove(at: index) + if model.networkConfiguration.dnsServers.indices.contains(index) { + model.networkConfiguration.dnsServers.remove(at: index) + } } label: { Image(systemName: "minus.circle") } @@ -163,7 +168,7 @@ struct NetworkCard: View { .help(Self.dnsHint) } - /// The "Add" that holds the cell when there is not a single DNS entry. + /// The "Add" that holds the cell when there is no DNS entry at all. private var emptyDNSCell: some View { HStack(spacing: Design.Spacing.tight) { Text("DNS") @@ -187,7 +192,7 @@ struct NetworkCard: View { VStack(alignment: .leading, spacing: 1) { Text(L(.setDefaultRoute)) Text(L(.setDefaultRouteHelp)) - .font(.caption) + .font(.footnote) .foregroundStyle(.secondary) } } @@ -208,26 +213,33 @@ struct NetworkCard: View { .frame(minWidth: 56) } .buttonStyle(.borderedProminent) - .disabled(model.isBusy) + .disabled(model.isBusy || !interfaceReady) Button(L(.clearConfiguration)) { Task { await model.clearNetworkConfiguration() } } - .disabled(model.isBusy || !model.networkState.hasAddress) + .disabled(model.isBusy || !interfaceReady || !model.networkState.hasAddress) .help(L(.clearConfigurationTooltip)) + if !interfaceReady, model.networkConfiguration.mode != .none { + Text(L(.connectBeforeConfiguring)) + .font(.footnote) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer() } } } -/// A compact address input box with immediate validation feedback: the label on the left, and the validation icon overlaid on the inner side of the input box -/// (every bit of width is precious in a two-column layout). +/// A compact address input box with immediate validation feedback: the label on the left, and the validation +/// icon overlaid on the inner side of the input box (every bit of width is precious in a two-column layout). /// -/// Validation is done while typing rather than at submit: a wrongly entered address is the most common operation mistake, and reporting an error only after clicking "Apply" -/// would make the user guess back and forth which cell is wrong. +/// Validation runs while typing rather than at submit: a wrongly entered address is the most common mistake, +/// and an error reported only after clicking "Apply" would make the user guess which cell is wrong. private struct AddressField: View { - /// Label column width. The labels of the readback area use it too, so the vertical alignment lines of the two blocks are the same one. + /// Label column width. The readback area's labels use it too, so the two blocks share one vertical alignment line. static let labelWidth: CGFloat = 56 let label: String @@ -246,7 +258,7 @@ private struct AddressField: View { .textFieldStyle(.roundedBorder) .font(.system(.callout, design: .monospaced)) .overlay(alignment: .trailing) { - // Empty input is not marked red: not finished filling in yet does not count as wrong. + // Empty input is not marked red: not finished filling in does not count as wrong. if !text.isEmpty { Image(systemName: isValid ? "checkmark.circle.fill" : "exclamationmark.circle.fill") @@ -283,20 +295,28 @@ private struct EffectiveStateView: View { } if state.hasAddress { - // Two columns of four cells rather than four rows: this is a pure display area, and compactness comes first. Values that do not fit - // (multiple DNS) are truncated in the middle for display, and hovering shows the whole, and can also be selected and copied. + // Two columns of four cells rather than four rows: this is a pure display area, so compactness comes + // first. + // Values that do not fit (multiple DNS) are truncated in the middle, and hovering shows the whole + // value, which can also be selected and copied. Grid(alignment: .leading, horizontalSpacing: Design.Spacing.medium, verticalSpacing: Design.Spacing.tight) { + // Four columns (label, value, label, value) so the labels size to + // their text ("Subnet mask" must not wrap) and the values still align. GridRow { - readbackCell(L(.ipAddress), state.address) - readbackCell(L(.netmask), state.netmask) + readbackLabel(L(.ipAddress)) + readbackValue(state.address) + readbackLabel(L(.netmask)) + readbackValue(state.netmask) } GridRow { - readbackCell(L(.router), state.router) - readbackCell("DNS", state.dnsServers.isEmpty - ? L(.notEffective) - : state.dnsServers.joined(separator: L(.listSeparator))) + readbackLabel(L(.router)) + readbackValue(state.router) + readbackLabel("DNS") + readbackValue(state.dnsServers.isEmpty + ? L(.notEffective) + : state.dnsServers.joined(separator: L(.listSeparator))) } } } else { @@ -307,19 +327,21 @@ private struct EffectiveStateView: View { } } - private func readbackCell(_ label: String, _ value: String) -> some View { - HStack(alignment: .firstTextBaseline, spacing: Design.Spacing.tight) { - Text(label) - .font(.caption) - .foregroundStyle(.secondary) - .frame(width: AddressField.labelWidth, alignment: .leading) - Text(value.isEmpty ? "—" : value) - .font(.system(.caption, design: .monospaced)) - .textSelection(.enabled) - .lineLimit(1) - .truncationMode(.middle) - } - .frame(maxWidth: .infinity, alignment: .leading) - .help(value) + private func readbackLabel(_ label: String) -> some View { + Text(label) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .fixedSize(horizontal: true, vertical: false) + } + + private func readbackValue(_ value: String) -> some View { + Text(value.isEmpty ? "—" : value) + .font(.system(.caption, design: .monospaced)) + .textSelection(.enabled) + .lineLimit(1) + .truncationMode(.middle) + .frame(maxWidth: .infinity, alignment: .leading) + .help(value) } } diff --git a/gui/Sources/TetherKitNextApp/Views/OnboardingView.swift b/gui/Sources/TetherKitNextApp/Views/OnboardingView.swift index 886ce1e..47ef33a 100644 --- a/gui/Sources/TetherKitNextApp/Views/OnboardingView.swift +++ b/gui/Sources/TetherKitNextApp/Views/OnboardingView.swift @@ -1,4 +1,5 @@ import AppKit +import ServiceManagement import SwiftUI import TetherKitNextIPC @@ -10,6 +11,8 @@ import TetherKitNextIPC /// 3. Allow it in System Settings › Login Items (only if macOS asks) struct OnboardingView: View { @Bindable var model: AppModel + /// Set when the user has pressed the enable button at least once. + @State private var attemptedInstall = false private var locationProblem: Bool { HelperInstaller.locationProblem != nil } @@ -68,6 +71,25 @@ struct OnboardingView: View { } } + /// Whether "Show why the connection failed" belongs on screen. On the very + /// first launch the component is simply not enabled yet and nothing has + /// failed, so the raw reason ("could not connect") would only alarm. It is + /// shown when something is actually wrong: + /// * registered and enabled, yet the daemon does not answer; + /// * the daemon plist is missing from the bundle (`.notFound`); + /// * the user already pressed enable and it is still not working. + /// Waiting for the user's approval in Login Items is a normal step, and + /// while an install is in progress the daemon is expected to be unreachable. + private var showsFailureDetail: Bool { + guard !model.isBusy, !model.helperNeedsApproval else { return false } + switch HelperInstaller.status { + case .enabled, .notFound: return true + case .requiresApproval: return false + case .notRegistered: return attemptedInstall + @unknown default: return attemptedInstall + } + } + @ViewBuilder private func steps(reason: String) -> some View { VStack(spacing: Design.Spacing.gutter) { @@ -86,9 +108,20 @@ struct OnboardingView: View { state: locationProblem ? .pending : (model.helperNeedsApproval ? .done : .current), detail: model.helperNeedsApproval || locationProblem - ? nil : L(.needInstallBody) + "\n\n" + L(.installHelperDetail)) { + ? nil : L(.setupHelperPlain)) { if !locationProblem && !model.helperNeedsApproval { - primaryButton(L(.installHelperButton)) { await model.installHelper() } + DisclosureGroup(L(.setupLearnMore)) { + Text(L(.needInstallBody) + "\n\n" + L(.installHelperDetail)) + .font(.footnote) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, Design.Spacing.tight) + } + .font(.callout) + primaryButton(L(.installHelperButton)) { + attemptedInstall = true + await model.installHelper() + } } } @@ -108,16 +141,18 @@ struct OnboardingView: View { } } - DisclosureGroup(L(.showConnectFailureDetail)) { - Text(reason) - .font(.system(.caption, design: .monospaced)) - .textSelection(.enabled) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.top, Design.Spacing.tight) + if showsFailureDetail { + DisclosureGroup(L(.showConnectFailureDetail)) { + Text(reason) + .font(.system(.caption, design: .monospaced)) + .textSelection(.enabled) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.top, Design.Spacing.tight) + } + .font(.footnote) + .padding(.horizontal, Design.Spacing.small) } - .font(.caption) - .padding(.horizontal, Design.Spacing.small) } } diff --git a/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift b/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift index 803cc89..2911954 100644 --- a/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift +++ b/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift @@ -3,13 +3,21 @@ import ServiceManagement import SwiftUI import TetherKitNextCore import TetherKitNextIPC +import TetherKitNextUIModel /// Preference keys shared between views. enum PreferenceKey { - /// Show live rates next to the menu bar icon (upstream issue #1). + /// Show live rates next to the menu bar icon. 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 +30,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 @@ -29,6 +38,7 @@ struct SettingsPage: View { var body: some View { Form { backgroundSection + layoutSection commandLineSection generalSection updatesSection @@ -65,8 +75,15 @@ struct SettingsPage: View { .disabled(model.isBusy) .help(L(.updateHelperDetail)) Spacer() + } + + // Its own row, away from the routine restart: this one removes the + // component (and stops a running session). + HStack { + Spacer() Button(L(.uninstallHelperMenuItem), role: .destructive, action: requestHelperUninstall) + .foregroundStyle(.red) .disabled(model.isBusy) } } @@ -123,9 +140,22 @@ struct SettingsPage: View { // MARK: General + private var layoutSection: some View { + Section(L(.settingsLayoutSection)) { + LayoutChoiceCards(selection: model.interfaceStyle, + onSelect: { model.setInterfaceStyle($0) }, compact: true) + .frame(maxWidth: 420) + } + } + private var generalSection: some View { Section(L(.settingsGeneralSection)) { LanguagePicker(model: model) + Toggle(isOn: $model.autoConnectEnabled) { + Text(L(.autoConnectToggle)) + Text(L(.autoConnectHelp)) + } + .help(L(.autoConnectHelpDetail)) Toggle(isOn: $autoConfigureNetwork) { Text(L(.autoConfigureNetwork)) Text(L(.autoConfigureNetworkHelp)) @@ -135,11 +165,19 @@ struct SettingsPage: View { .onChange(of: launchAtLogin) { _, enabled in setLaunchAtLogin(enabled) } + Toggle(isOn: $advancedToolsEnabled) { + Text(L(.settingsAdvancedTools)) + Text(L(.settingsAdvancedToolsHelp)) + } } } private func setLaunchAtLogin(_ enabled: Bool) { let service = SMAppService.mainApp + // Writing `launchAtLogin` back below re-fires onChange; when it already matches the + // service, stop here, or a failed register() would be followed by a pointless + // unregister() whose error overwrites the first, useful one. + guard enabled != (service.status == .enabled) else { return } do { if enabled { try service.register() @@ -160,12 +198,19 @@ struct SettingsPage: View { private var updatesSection: some View { Section(L(.settingsUpdatesSection)) { Toggle(L(.autoCheckUpdates), isOn: Binding(get: { !updateCheckDisabled }, - set: { updateCheckDisabled = !$0 })) + set: { + updateCheckDisabled = !$0 + SoftwareUpdater.shared.setAutomaticallyChecks($0) + })) LabeledContent { HStack { if let update = model.availableUpdate { Button(L(.helperUpdateBadge, update.version)) { - model.updateCheckResult = .updateAvailable(update) + if SoftwareUpdater.shared.isAvailable { + SoftwareUpdater.shared.checkForUpdates() + } else { + model.updateCheckResult = .updateAvailable(update) + } } .buttonStyle(.link) } diff --git a/gui/Sources/TetherKitNextApp/Views/SimpleView.swift b/gui/Sources/TetherKitNextApp/Views/SimpleView.swift new file mode 100644 index 0000000..4ef8a3d --- /dev/null +++ b/gui/Sources/TetherKitNextApp/Views/SimpleView.swift @@ -0,0 +1,413 @@ +import SwiftUI +import TetherKitNextIPC +import TetherKitNextUIModel + +/// The simple layout: a device chip, one round power button, a status line +/// with live speed, and a gear for settings. +/// +/// What it leaves to the detailed view: charts, logs, MTU/MAC, the static-IP form, "route all traffic", +/// interface names and the advanced tools. What it must still handle, because otherwise the simple view +/// would be a dead end: +/// * several devices (the chip becomes a picker), +/// * failures (plain-language headline + Dismiss), +/// * local devices without DHCP (one-click session-only address, or a way +/// to the detailed view when no address can be suggested), +/// * auto-connect holding back because the Mac is already online, +/// * a pending app update or background-component restart (dot on the gear). +struct SimpleView: View { + @Bindable var model: AppModel + let requestHelperUpdate: () -> Void + @State private var showingSettings = false + + static let windowSize = CGSize(width: 380, height: 460) + + private var runState: RunState { model.status.runState } + private var isRunning: Bool { runState == .running } + + var body: some View { + VStack(spacing: Design.Spacing.large) { + // Equal springs center the group; the minimum keeps clear of the + // transparent title bar and the gear. + Spacer(minLength: 28) + deviceChip + PowerButton(model: model) + statusBlock + Spacer(minLength: 28) + } + .padding(.horizontal, Design.Spacing.large) + .padding(.bottom, Design.Spacing.large) + .frame(width: Self.windowSize.width, height: Self.windowSize.height) + .overlay(alignment: .topTrailing) { gearButton } + .sheet(isPresented: $showingSettings) { + SimpleSettingsSheet(model: model, requestHelperUpdate: requestHelperUpdate) + } + .onChange(of: model.statusLabel) { _, label in + // VoiceOver users hear connect/disconnect/failure without moving focus. + AccessibilityNotification.Announcement(label).post() + } + } + + // MARK: Device + + @ViewBuilder + private var deviceChip: some View { + VStack(spacing: Design.Spacing.tight) { + if isRunning || runState.isTransitional { + chip(icon: "iphone", title: connectedDeviceName, + detail: isRunning ? L(.simpleDeviceConnected) : nil, tint: .green) + } else if model.devices.isEmpty { + chip(icon: "iphone.slash", title: L(.simpleNoDevice), detail: nil, tint: nil) + Text(L(.simpleNoDeviceHint)) + .font(.callout) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + } else if model.devices.count == 1, let device = model.devices.first { + chip(icon: "iphone", title: device.displayName, + detail: L(.simpleDeviceReady), tint: .accentColor) + } else { + devicePicker + } + } + } + + /// Same name as the "ready" chip shows (`DeviceDescriptor.displayName`). + /// The session's own description is only the model ("Pixel 8"), so it is + /// a fallback, with the vendor put back in front. + private var connectedDeviceName: String { + if let name = model.selectedDevice?.displayName, !name.isEmpty { return name } + let combined = [model.status.vendorDescription, model.status.deviceDescription] + .filter { !$0.isEmpty } + .joined(separator: " ") + return combined.isEmpty ? L(.simpleDeviceConnected) : combined + } + + private func chip(icon: String, title: String, detail: String?, tint: Color?) -> some View { + HStack(spacing: Design.Spacing.tight) { + Image(systemName: icon) + Text(title).fontWeight(.medium).lineLimit(1) + if let detail { + Text("·").foregroundStyle(.tertiary) + Text(detail).foregroundStyle(.secondary).lineLimit(1) + } + } + .font(.callout) + .padding(.horizontal, Design.Spacing.medium) + .padding(.vertical, Design.Spacing.tight) + .glassCapsule(tint: tint) + .accessibilityElement(children: .combine) + } + + /// Several devices: the same chip as for one device (name · ready), plus a + /// small menu button to switch. A menu's own label shows only plain text on + /// macOS, so the chip is not put inside the menu. + private var devicePicker: some View { + HStack(spacing: Design.Spacing.tight) { + chip(icon: "iphone", + title: model.selectedDevice?.displayName ?? L(.simpleChooseDevice), + detail: L(.simpleDeviceReady), tint: .accentColor) + Menu { + Picker(L(.simpleChooseDevice), selection: $model.selectedDeviceID) { + ForEach(model.devices) { device in + Text(device.displayName).tag(Optional(device.id)) + } + } + .pickerStyle(.inline) + } label: { + Image(systemName: "chevron.up.chevron.down") + .font(.callout.weight(.semibold)) + .frame(minWidth: 28, minHeight: 28) + .contentShape(Rectangle()) + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .help(L(.simpleChooseDevice)) + .accessibilityLabel(L(.simpleChooseDevice)) + } + } + + // MARK: Status + + @ViewBuilder + private var statusBlock: some View { + VStack(spacing: Design.Spacing.small) { + if let failure = model.lastFailure, !isRunning, !runState.isTransitional { + FailureBanner(failure: failure, style: .centered) { model.dismissFailure() } + } else { + HStack(spacing: Design.Spacing.tight) { + Circle() + .fill(Design.accent(for: runState)) + .frame(width: 9, height: 9) + Text(model.statusLabel).font(.headline) + } + .accessibilityElement(children: .combine) + + if isRunning { + HStack(spacing: Design.Spacing.medium) { + Label(Format.bitrate(model.throughput.receiveBitsPerSecond), + systemImage: "arrow.down") + Label(Format.bitrate(model.throughput.transmitBitsPerSecond), + systemImage: "arrow.up") + } + .font(.callout.monospacedDigit()) + .foregroundStyle(.secondary) + .contentTransition(.numericText()) + } + } + + linkHint + } + } + + /// One line for the cases the simple view must not leave unexplained. + @ViewBuilder + private var linkHint: some View { + if isRunning { + switch model.linkAssessment { + case .waitingForAddress: + hint(L(.linkWaitingTitle)) + case .noAddress(_, let suggestion?): + VStack(spacing: Design.Spacing.tight) { + hint(L(.simpleNoAddressHint)) + Button(L(.simpleUseAddress, suggestion)) { + Task { await model.useSessionOnlyAddress(suggestion) } + } + .controlSize(.small) + .disabled(model.isBusy) + } + case .noAddress(_, nil): + VStack(spacing: Design.Spacing.tight) { + hint(L(.simpleNeedsAddress)) + Button(L(.simpleOpenFull)) { model.setInterfaceStyle(.full) } + .controlSize(.small) + } + case .notConnected, .notConfigured, .internet, .localLink: + EmptyView() + } + } else if model.autoConnectEnabled, model.autoConnectWaiting { + hint(L(.autoConnectWaiting)) + } + } + + private func hint(_ text: String) -> some View { + Text(text) + .font(.footnote) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + } + + // MARK: Settings + + private var needsAttention: Bool { + model.availableUpdate != nil || model.helperVersionMismatch != nil + } + + private var gearButton: some View { + Button { showingSettings = true } label: { + Image(systemName: "gearshape") + .font(.title3) + .frame(minWidth: 28, minHeight: 28) + .overlay(alignment: .topTrailing) { + if needsAttention { + Circle().fill(.red).frame(width: 8, height: 8) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .help(L(.paneSettings)) + .accessibilityLabel(L(.paneSettings)) + .keyboardShortcut(",", modifiers: .command) + .padding(.top, 8) + .padding(.trailing, 10) + } +} + +/// The big round button. Shape, icon and label change with the state, so it +/// does not rely on color alone. +private struct PowerButton: View { + var model: AppModel + + private static let diameter: CGFloat = 150 + + /// "Connecting…" / "Disconnecting…" while a transition is in flight; nil + /// otherwise. A start request runs a moment before the session reports + /// `.starting` (`isStartingSession`); other busy work (restarting the + /// background component, applying the network setup) keeps the normal label. + private var workingLabel: L10nKey? { + switch model.status.runState { + case .stopping: return .powerDisconnecting + case .starting: return .powerConnecting + case .running: return nil + case .idle, .stopped, .failed: return model.isStartingSession ? .powerConnecting : nil + } + } + + var body: some View { + let state = model.status.runState + let isRunning = state == .running + let working = workingLabel + let isWorking = working != nil + let canStart = !model.devices.isEmpty + let label: L10nKey = working ?? (isRunning ? .disconnect : .connect) + + Button { + // Not `.disabled`: that dims the label, and "Connecting…" must stay readable. + guard !isWorking, !model.isBusy else { return } + Task { + if isRunning { + await model.stopSession() + } else { + await model.startSession() + } + } + } label: { + ZStack { + Circle() + .fill(isWorking ? AnyShapeStyle(Color.orange.opacity(0.12)) + : isRunning ? AnyShapeStyle(Design.connectedGradient) + : AnyShapeStyle(.quaternary)) + Circle() + .strokeBorder(isWorking ? Color.orange + : isRunning ? Design.connectedGreen.opacity(0.35) + : Color.secondary.opacity(0.25), + lineWidth: isWorking ? 4 : 3) + if isWorking { + PulsingRing(diameter: Self.diameter) + } + VStack(spacing: 6) { + Image(systemName: "power") + .font(.system(size: 46, weight: .semibold)) + Text(L(label)) + .font(.callout.weight(.semibold)) + .lineLimit(1) + .minimumScaleFactor(0.8) + .padding(.horizontal, Design.Spacing.small) + } + .foregroundStyle(isRunning && !isWorking ? AnyShapeStyle(.white) + : AnyShapeStyle(.primary)) + } + .frame(width: Self.diameter, height: Self.diameter) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .shadow(color: isRunning && !isWorking ? Design.connectedGreen.opacity(0.35) : .clear, + radius: 16) + .opacity(!isRunning && !canStart ? 0.45 : 1) + .disabled(!isRunning && !canStart) + .animation(.smooth(duration: 0.3), value: isRunning) + .animation(.smooth(duration: 0.3), value: isWorking) + .keyboardShortcut(.return, modifiers: .command) + .help(!isRunning && !canStart ? L(.connectDisabledHint) : "") + .accessibilityLabel(L(.powerButtonLabel)) + .accessibilityValue(model.statusLabel) + .accessibilityHint(L(isRunning ? .disconnect : .connect)) + } +} + +/// An expanding ring while connecting or disconnecting. +private struct PulsingRing: View { + let diameter: CGFloat + + var body: some View { + Circle() + .stroke(Color.orange, lineWidth: 5) + .phaseAnimator([false, true]) { ring, expanded in + ring + .scaleEffect(expanded ? 1.16 : 1) + .opacity(expanded ? 0 : 1) + } animation: { expanded in + expanded ? .easeOut(duration: 1.1) : .linear(duration: 0.01) + } + .frame(width: diameter, height: diameter) + } +} + +/// The gear's sheet: only what a simple-view user needs, plus a way to +/// everything else. +struct SimpleSettingsSheet: View { + @Bindable var model: AppModel + let requestHelperUpdate: () -> Void + @Environment(\.dismiss) private var dismiss + + /// Switching to the detailed layout also closes the sheet (the window is + /// about to change size). + private var layoutBinding: Binding { + Binding( + get: { model.interfaceStyle ?? .simple }, + set: { style in + guard style != model.interfaceStyle else { return } + if style == .full { dismiss() } + model.setInterfaceStyle(style) + }) + } + + var body: some View { + VStack(spacing: 0) { + Form { + Section(L(.settingsLayoutSection)) { + Picker(L(.settingsLayoutSection), selection: layoutBinding) { + ForEach(InterfaceStyle.allCases, id: \.self) { style in + Text(style.displayName).tag(style) + } + } + .pickerStyle(.segmented) + .labelsHidden() + } + Section(L(.settingsGeneralSection)) { + Toggle(isOn: $model.autoConnectEnabled) { + Text(L(.autoConnectToggle)) + Text(L(.autoConnectHelp)) + } + .help(L(.autoConnectHelpDetail)) + LanguagePicker(model: model) + } + if let mismatch = model.helperVersionMismatch { + Section { + LabeledContent { + Button(L(.updateHelperButton)) { + dismiss() + requestHelperUpdate() + } + } label: { + Text(L(.helperVersionMismatch, mismatch.installed, mismatch.expected)) + } + } + } + Section(L(.settingsUpdatesSection)) { + LabeledContent { + HStack { + if let update = model.availableUpdate { + Button(L(.helperUpdateBadge, update.version)) { + Task { await model.checkForUpdates() } + } + .buttonStyle(.link) + } + Button(L(.checkNow)) { + Task { await model.checkForUpdates() } + } + } + } label: { + Text(L(.currentVersion, UpdateChecker.currentVersion ?? "dev")) + } + } + } + .formStyle(.grouped) + + HStack { + Button(L(.simpleAllSettings)) { + dismiss() + UserDefaults.standard.set(Pane.settings.rawValue, forKey: PreferenceKey.selectedPane) + model.setInterfaceStyle(.full) + } + Spacer() + Button(L(.done)) { dismiss() } + .keyboardShortcut(.defaultAction) + } + .padding(Design.Spacing.medium) + } + .frame(width: 360, height: 520) + } +} diff --git a/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift b/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift index 98b660c..7bee147 100644 --- a/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift @@ -1,10 +1,11 @@ import SwiftUI import TetherKitNextIPC +import TetherKitNextUIModel /// The main status card: the visual and operational focus of the entire UI. /// -/// Answers three questions within one screen: is it connected now, through which NIC, and with what IP. -/// All other details go into the cards below -- users spend ninety percent of their time looking only at this block. +/// Answers three questions within one screen: is it connected now, through which interface, and with what IP. +/// All other details go into the cards below; users spend most of their time looking only at this block. struct StatusHeroCard: View { @Bindable var model: AppModel @@ -12,8 +13,9 @@ struct StatusHeroCard: View { var body: some View { // The hero is status chrome, not content: it floats on Liquid Glass - // tinted with the connection state. Connect/Disconnect lives in the - // toolbar (ConnectButton) so it is reachable from every page. + // tinted with the connection state. Connect/Disconnect is here as the + // obvious primary action and also in the toolbar (ConnectButton) so it + // stays reachable from every page. HStack(alignment: .center, spacing: Design.Spacing.large) { StatusRing(status: model.status, accent: accent) @@ -23,6 +25,9 @@ struct StatusHeroCard: View { addressLine } .frame(maxWidth: .infinity, alignment: .leading) + + ConnectButton(model: model, hasKeyboardShortcut: false) + .controlSize(.large) } .padding(Design.Spacing.large) .frame(maxWidth: .infinity, alignment: .leading) @@ -32,7 +37,7 @@ struct StatusHeroCard: View { private var headline: some View { HStack(spacing: Design.Spacing.small) { - Text(Design.statusLabel(for: model.status)) + Text(model.statusLabel) .font(.system(.title2, design: .rounded).weight(.semibold)) if model.status.runState == .running { @@ -47,12 +52,8 @@ struct StatusHeroCard: View { @ViewBuilder private var subline: some View { - if model.status.runState == .failed, !model.status.fatalMessage.isEmpty { - Text(model.status.fatalMessage) - .font(.callout) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) - .textSelection(.enabled) + if let failure = model.lastFailure, model.status.runState != .running, !model.status.runState.isTransitional { + FailureBanner(failure: failure, style: .leading) { model.dismissFailure() } } else if !model.status.deviceDescription.isEmpty { Text(deviceSummary) .font(.callout) @@ -113,8 +114,9 @@ struct StatusHeroCard: View { /// The status ring. /// -/// While running the outer ring rotates slowly and the inner ring breathes -- this is the only animation on the UI, used to express "it is alive -/// and working". All other states are static, to avoid wasting attention on animations that carry no information. +/// While running the outer ring rotates slowly and the inner ring breathes. This is the only animation in the +/// UI and expresses "it is alive and working". All other states are static, to avoid spending attention on +/// animation that carries no information. private struct StatusRing: View { let status: SessionStatus let accent: Color diff --git a/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift b/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift index 174de02..ca9b510 100644 --- a/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift @@ -4,22 +4,29 @@ import TetherKitNextIPC /// Throughput and counters. /// -/// The chart deliberately draws only **rates** and not cumulative amounts: a cumulative curve rises monotonically forever and reveals nothing; -/// while a rate shows stalls, jitter and rate limiting at a glance. Cumulative amounts go in the metric cells below, readable when needed. +/// The chart draws only rates, not cumulative amounts: a cumulative curve rises monotonically forever and +/// reveals nothing, while a rate shows stalls, jitter and rate limiting at a glance. Cumulative amounts go in +/// the metric cells below, readable when needed. struct ThroughputCard: View { @Bindable var model: AppModel private var hasData: Bool { !model.throughputHistory.isEmpty } + /// Zero rates and totals before a session are noise: only the placeholder is shown. + private var isRunning: Bool { model.status.runState == .running } var body: some View { Card(title: L(.throughputSectionTitle), systemImage: "chart.line.uptrend.xyaxis", accessory: AnyView(liveBadge)) { VStack(alignment: .leading, spacing: Design.Spacing.medium) { - rateRow - chart - Divider() - counterRow - if hasDrops { - dropHint + if isRunning { + rateRow + chart + Divider() + counterRow + if hasDrops { + dropHint + } + } else { + placeholder } } } @@ -32,8 +39,8 @@ struct ThroughputCard: View { } } - // The four rate cells are arranged 2x2 rather than in one row: this card now lives in a half column, and four cells in a row would squeeze - // descriptions like "Download (device -> this machine)" into truncation. + // The four rate cells are arranged 2x2 rather than in one row: this card is placed in a half column, and + // four cells in a row would truncate descriptions like "Download (device → this Mac)". private var rateRow: some View { Grid(alignment: .leading, horizontalSpacing: Design.Spacing.medium, @@ -94,21 +101,28 @@ struct ThroughputCard: View { } } } - // The horizontal axis draws no ticks: this is a rolling "last 60 seconds" curve, specific moments are meaningless, - // and drawing them would only take up the plotting area that is not tall to begin with. + // The horizontal axis draws no ticks: this is a rolling "last 60 seconds" curve, so specific moments are + // meaningless, and ticks would only take plotting area that is not tall to begin with. .chartXAxis(.hidden) + // A new sample arrives every 500 ms; never interpolate the curve between them (an inherited animation + // would re-run it on every poll). + .animation(nil, value: model.throughputHistory) .frame(height: 120) } else { - RoundedRectangle(cornerRadius: Design.Radius.control) - .fill(.quaternary.opacity(0.35)) - .frame(height: 120) - .overlay( - Text(L(model.status.runState == .running ? .throughputCollecting : .throughputPlaceholder)) - .font(.callout) - .foregroundStyle(.secondary)) + placeholder } } + private var placeholder: some View { + RoundedRectangle(cornerRadius: Design.Radius.control) + .fill(.quaternary.opacity(0.35)) + .frame(height: 120) + .overlay( + Text(L(isRunning ? .throughputCollecting : .throughputPlaceholder)) + .font(.callout) + .foregroundStyle(.secondary)) + } + private var counterRow: some View { HStack(spacing: Design.Spacing.medium) { MetricTile(caption: L(.totalDownstream), value: Format.bytes(model.status.rxBytes)) @@ -125,9 +139,9 @@ struct ThroughputCard: View { /// Packet loss hint. /// - /// The four numbers are listed separately rather than merged into one "loss rate": they point to completely different bottlenecks -- - /// queue full means the downstream cannot write fast enough, kernel drops mean we read too slowly, and backpressure means the USB side cannot send. - /// After merging, one could no longer tell which parameter to tune. + /// The four numbers are listed separately rather than merged into one "loss rate" because they point to + /// different bottlenecks: queue full means the downstream cannot write fast enough, kernel drops mean we read + /// too slowly, and backpressure means the USB side cannot send. Merged, one could not tell which to tune. private var dropHint: some View { HStack(spacing: Design.Spacing.medium) { MetricTile(caption: L(.downstreamDropped), value: Format.count(model.status.rxDropped), tint: .orange) diff --git a/gui/Sources/TetherKitNextCore/CInterop.swift b/gui/Sources/TetherKitNextCore/CInterop.swift index 8f71395..c7ce557 100644 --- a/gui/Sources/TetherKitNextCore/CInterop.swift +++ b/gui/Sources/TetherKitNextCore/CInterop.swift @@ -1,15 +1,15 @@ import CTetherKitNext import Foundation -// C's fixed-size char arrays are imported into Swift as **tuples** (`char[16]` -> a tuple of 16 CChars), -// which can be neither subscripted nor converted directly to and from String. This file handles that in one place, -// avoiding writing unsafe pointer operations again for every field. +// C's fixed-size char arrays are imported into Swift as tuples (`char[16]` becomes a tuple of 16 CChars), +// which can be neither subscripted nor converted directly to and from String. This file handles that in one +// place instead of repeating unsafe pointer operations for every field. extension String { /// Reads a string from a C fixed-size char array (imported as a tuple). /// - /// `String(cString:)` is not used: it requires the buffer to be NUL-terminated, and once the C side fills the entire - /// buffer it would read out of bounds. This is changed to "scan to a NUL or to the end", which is safe in both cases. + /// `String(cString:)` is not used: it requires the buffer to be NUL-terminated, and once the C side fills + /// the entire buffer it would read out of bounds. This scans to a NUL or to the end, which is safe in both cases. init(fixedCArray tuple: T) { var mutableCopy = tuple self = withUnsafeBytes(of: &mutableCopy) { raw in @@ -21,24 +21,24 @@ extension String { /// Writes a string into a C fixed-size char array, guaranteeing NUL termination. /// -/// Truncates when too long, and **the truncation lands on a UTF-8 character boundary** -- cutting hard by bytes would leave -/// half a character at the end of the buffer, which the C side would then read out as a string of replacement characters. (The C side's CopyText has the same handling, -/// and both directions need care.) +/// Truncates when too long, and the truncation lands on a UTF-8 character boundary: cutting by bytes would +/// leave half a character at the end of the buffer, which the C side would read out as replacement +/// characters. (The C side's CopyText handles it the same way; both directions need care.) func setFixedCArray(_ tuple: inout T, to string: String) { withUnsafeMutableBytes(of: &tuple) { raw in writeCString(string, into: raw) } } -/// Writes a string into a raw buffer, NUL-terminated + UTF-8-boundary-safe truncation. +/// Writes a string into a raw buffer, NUL-terminated, with truncation on a UTF-8 boundary. private func writeCString(_ string: String, into raw: UnsafeMutableRawBufferPointer) { guard raw.count > 0 else { return } for index in raw.indices { raw[index] = 0 } let utf8 = Array(string.utf8) var length = min(utf8.count, raw.count - 1) - // length < utf8.count means truncation happened; if the cut point falls in the middle of a multi-byte sequence (the top two bits of a continuation byte - // are 0b10), back up all the way to the start of that sequence. + // length < utf8.count means truncation happened; if the cut falls in the middle of a multi-byte sequence + // (the top two bits of a continuation byte are 0b10), back up to the start of that sequence. while length > 0, length < utf8.count, utf8[length] & 0xC0 == 0x80 { length -= 1 } @@ -49,7 +49,8 @@ private func writeCString(_ string: String, into raw: UnsafeMutableRawBufferPoin /// Writes a string into row `row` of a C two-dimensional fixed-size array (such as `char dns[4][46]`). /// -/// A two-dimensional array in Swift is a "tuple of tuples" that cannot be subscripted and can only be located by byte offset. +/// A two-dimensional array in Swift is a "tuple of tuples" that cannot be subscripted, so rows are located by byte +/// offset. func setFixedCArrayRow(_ tuple: inout T, row: Int, stride: Int, to string: String) { withUnsafeMutableBytes(of: &tuple) { raw in let start = row * stride diff --git a/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift b/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift index 307f0f7..8d5dccc 100644 --- a/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift +++ b/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift @@ -2,19 +2,20 @@ import CTetherKitNext import Foundation import TetherKitNextIPC -/// Connectivity method configuration of the virtual NIC. +/// Connectivity method configuration of the virtual interface. /// /// `apply` / `clear` need root (called only inside the helper); `query` does not. public enum NetworkConfigurator { - /// The capacity of each address field in tk_ip_config_t, used to locate the rows of the two-dimensional array `dns[4][46]`. + /// The capacity of each address field in tk_ip_config_t, used to locate the rows of the two-dimensional array + /// `dns[4][46]`. private static let addressStride = Int(TK_ADDRESS_CAPACITY) private static let maxDNSServers = Int(TK_DNS_MAX) /// Applies the configuration. /// - /// WARNING: In DHCP mode it **blocks** until a lease is obtained or it times out (the library's internal cap is 10 seconds). This is deliberate: - /// "applied, go poll it yourself" cannot give meaningful success/failure feedback to the UI. The caller must - /// guarantee it is not called on the main thread. + /// WARNING: In DHCP mode it blocks until a lease is obtained or it times out (the library's cap is 10 + /// seconds). "Applied, go poll it yourself" cannot give the UI meaningful success/failure feedback. The + /// caller must guarantee it is not called on the main thread. public static func apply(_ configuration: NetworkConfiguration, to interface: String) throws { var raw = tk_ip_config_t() tk_ip_config_init(&raw) @@ -41,17 +42,17 @@ public enum NetworkConfigurator { try check(result, error) } - /// Revokes the IP configuration on the NIC. + /// Revokes the IP configuration on the interface. public static func clear(interface: String) throws { var error = tk_error_t() let result = interface.withCString { tk_net_clear($0, &error) } try check(result, error) } - /// Reads back the state the NIC **actually has in effect**. + /// Reads back the state the interface actually has in effect. /// - /// When the NIC does not exist yet it returns an all-empty state rather than throwing -- the UI also refreshes when a session has not started, - /// and showing a false error then would only mislead people. + /// When the interface does not exist yet it returns an all-empty state rather than throwing: the UI also + /// refreshes before a session has started, and a false error then would only mislead. public static func query(interface: String) throws -> NetworkState { var raw = tk_net_state_t() var error = tk_error_t() @@ -81,8 +82,8 @@ public enum NetworkConfigurator { /// Input validation of the static IP form. /// -/// Placed in the shared layer rather than in the UI: the helper side must also put up a barrier (XPC is reachable by any local process), -/// and using the same rules on both sides avoids the split of "the UI passed but the helper rejected". +/// Placed in the shared layer rather than in the UI: the helper must put up its own barrier too (XPC is +/// reachable by any local process), and the same rules on both sides avoid "the UI passed but the helper rejected". public enum NetworkValidator { /// Whether it is a legal dotted-decimal IPv4 address. public static func isValidIPv4(_ text: String) -> Bool { @@ -93,18 +94,23 @@ public enum NetworkValidator { /// Whether it is a legal subnet mask. /// /// Stricter than "is a legal IPv4": the mask in binary must be consecutive 1s followed by consecutive 0s. - /// Something like 255.255.0.255 passes inet_pton but is wrong as a mask, and the kernel's reaction to it - /// is to produce a weird route that is very hard to track down -- so it is blocked at the entrance. + /// Something like 255.255.0.255 passes inet_pton but is wrong as a mask, and the kernel reacts by producing + /// a strange route that is very hard to track down, so it is blocked at the entrance. public static func isValidNetmask(_ text: String) -> Bool { var address = in_addr() guard text.withCString({ inet_pton(AF_INET, $0, &address) }) == 1 else { return false } let host = UInt32(bigEndian: address.s_addr) - // The necessary and sufficient condition for a contiguous mask: after inverting and adding one it is a power of 2 (or 0, corresponding to 255.255.255.255). + // 0.0.0.0 (/0) is contiguous but means "every address is on this link", which would send all traffic to the + // interface without a router. + guard host != 0 else { return false } + // A mask is contiguous exactly when, after inverting and adding one, it is a power of 2 (or 0, for + // 255.255.255.255). let inverted = ~host return inverted & (inverted &+ 1) == 0 } - /// Validates a static IP configuration item by item, returning the description of the first one that fails; returns nil when all pass. + /// Validates a static IP configuration item by item and returns the description of the first failure, or nil when + /// all pass. public static func validationMessage(for configuration: NetworkConfiguration) -> String? { guard configuration.mode == .manual else { return nil } diff --git a/gui/Sources/TetherKitNextCore/TetherKitNextError.swift b/gui/Sources/TetherKitNextCore/TetherKitNextError.swift index 5ff2bbe..7410e3d 100644 --- a/gui/Sources/TetherKitNextCore/TetherKitNextError.swift +++ b/gui/Sources/TetherKitNextCore/TetherKitNextError.swift @@ -21,15 +21,13 @@ public struct TetherKitNextError: LocalizedError, Sendable { public var errorDescription: String? { message } - /// Whether it is "missing permission" -- the UI uses it to decide whether to pop up authorization or report an error. - public var isPermissionDenied: Bool { result == TK_ERR_PERMISSION.rawValue } - init(result: Int32, error: tk_error_t) { self.result = result self.domain = Domain(rawValue: error.domain) ?? .generic self.code = error.code let text = String(fixedCArray: error.message) - // On the argument-validation failure branches the C side does not necessarily fill in a message (such as a plain null-pointer check), + // On the argument-validation failure branches the C side does not necessarily fill in a message (such as a + // plain null-pointer check), // and in that case giving a fallback sentence is better than showing an empty error box on the UI. self.message = text.isEmpty ? L(.libraryGenericFailure, Int(result)) : text } diff --git a/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift b/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift index 0aa291f..aa2d864 100644 --- a/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift +++ b/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift @@ -4,25 +4,29 @@ import TetherKitNextIPC /// The process-level interface of libtetherkitnext: version, environment preflight, device enumeration, logs. /// -/// This group **needs no root**, and both the App and the helper can call it. +/// This group needs no root, and both the app and the helper can call it. public enum TetherKitNextLibrary { + /// The maximum number of devices enumerated at once. /// The maximum number of devices enumerated at once. /// - /// 16 is a limit that will never be hit: plugging in 16 RNDIS devices on one machine at once is already absurd, - /// and what the fixed-size array buys is "no need to manage memory". If it really is exceeded tk_list_devices honestly reports the total, - /// and we just do not show the excess. + /// 16 is a limit that will never be hit: plugging in 16 RNDIS devices at once is absurd, and a fixed-size + /// array means no memory management. If it is exceeded tk_list_devices still reports the total and we just + /// do not show the excess. private static let deviceCapacity = 16 - /// The maximum number of log entries taken away at once. + /// The maximum number of log entries drained at once. + /// The maximum number of log entries drained at once. /// - /// Consistent with the C-side ring buffer's capacity (256): smaller and the backlog would never be fully drained, larger is meaningless. + /// Matches the C-side ring buffer's capacity (256): smaller and the backlog would never be fully drained, + /// larger is meaningless. private static let logCapacity = 256 + /// Synchronizes the UI language to libtetherkitnext. /// Synchronizes the UI language to libtetherkitnext. /// - /// It must be called -- otherwise there would be a split like "the UI is English while the library logs in the log card are Chinese". - /// Logs already queued are not re-rendered (they were already strings at the moment they were produced), - /// so the earlier it is called the better; on a language switch, newly produced logs are immediately in the new language. + /// It must be called, or the UI would be in one language while the library logs in the log card are in + /// another. Logs already queued are not re-rendered (they were strings when produced), so call it early; on a + /// language switch, newly produced logs are immediately in the new language. public static func setLanguage(_ language: Language) { tk_set_language(language.cValue) } @@ -35,7 +39,7 @@ public enum TetherKitNextLibrary { String(fixedCArray: info.libusb)) } - /// Runtime environment preflight. Always succeeds -- "environment unacceptable" is a result, not a failure. + /// Runtime environment preflight. Always succeeds: "environment unacceptable" is a result, not a failure. public static func checkEnvironment() -> EnvironmentReport { var raw = tk_environment_t() _ = tk_check_environment(&raw) @@ -52,8 +56,8 @@ public enum TetherKitNextLibrary { /// Enumerates RNDIS devices. /// - /// - Parameter readStrings: Whether to read the vendor name / product name / serial number. This needs opening - /// the device, and during a session the device is already held exclusively, so pass false then to avoid trying in vain. + /// - Parameter readStrings: Whether to read the vendor name / product name / serial number. This needs + /// opening the device, and during a session the device is held exclusively, so pass false then. public static func listDevices(readStrings: Bool = true) throws -> [DeviceDescriptor] { var buffer = [tk_device_info_t](repeating: tk_device_info_t(), count: deviceCapacity) var count = 0 @@ -84,11 +88,7 @@ public enum TetherKitNextLibrary { tk_enable_log_capture(true) } - public static func stopLogCapture() { - tk_enable_log_capture(false) - } - - /// Takes away the buffered logs. Returns the entries and "the number dropped because the buffer filled". + /// Drains the buffered logs. Returns the entries and "the number dropped because the buffer filled". public static func drainLogs() -> (entries: [LogEntry], dropped: UInt64) { var buffer = [tk_log_record_t](repeating: tk_log_record_t(), count: logCapacity) var dropped: UInt64 = 0 @@ -104,12 +104,12 @@ public enum TetherKitNextLibrary { return (Array(entries), dropped) } - // MARK: - Orphan NICs + // MARK: - Orphan interfaces /// Cleans up feth interfaces left in the kernel after a process was forcibly killed. Needs root. /// - /// The helper should call it unconditionally once at startup: if the last run was SIGKILLed, the NIC is still left in the kernel, - /// and neither RAII nor signal handling can save that situation. + /// The helper should call it once unconditionally at startup: after a SIGKILL the interface is still in the + /// kernel, and neither RAII nor signal handling can recover from that. @discardableResult public static func cleanupOrphanInterfaces() throws -> Int { var removed = 0 diff --git a/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift b/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift index 6acb0ad..7bac5dc 100644 --- a/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift +++ b/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift @@ -2,24 +2,24 @@ import CTetherKitNext import Foundation import TetherKitNextIPC -/// One RNDIS session. **Needs root**, so it is used only inside the helper process. +/// One RNDIS session. Needs root, so it is used only inside the helper process. /// -/// Thread safety: the C-side session itself is thread-safe (both the state snapshot and the event queue have locks), but -/// the calling order of `start` / `stop` must be guaranteed non-concurrent by the caller. The helper strings all lifecycle calls +/// Thread safety: the C-side session is thread-safe (the state snapshot and the event queue both have +/// locks), but the caller must not run `start` / `stop` concurrently. The helper strings all lifecycle calls /// together on one serial queue to satisfy this. -/// `@unchecked Sendable`: the only state is the C handle, and the C ABI -/// documents every tk_session_* call as thread-safe (status snapshots are -/// taken under the runtime's own lock). The helper touches a session from its -/// lifecycle queue and from XPC status polls concurrently. +/// `@unchecked Sendable`: the only state is the C handle, and the C ABI documents every tk_session_* call as +/// thread-safe (status snapshots are taken under the runtime's own lock). The helper touches a session from +/// its lifecycle queue and from XPC status polls concurrently. public final class TetherKitNextSession: @unchecked Sendable { private let handle: OpaquePointer - /// The maximum number of events taken away at once, consistent with the C-side ring buffer capacity (128). + /// The maximum number of events drained at once, consistent with the C-side ring buffer capacity (128). private static let eventCapacity = 128 public init(configuration: SessionConfiguration) throws { var raw = tk_session_config_t() - // It must be init first and then modified: the struct has a pile of tuning knobs, and all-zero initialization would give an invalid configuration. + // Initialize first and then modify: the struct has many tuning knobs, and all-zero initialization would be an + // invalid configuration. tk_session_config_init(&raw) raw.vendor_id = configuration.vendorID raw.product_id = configuration.productID @@ -36,11 +36,12 @@ public final class TetherKitNextSession: @unchecked Sendable { } deinit { - // tk_session_destroy stops first internally (idempotent), so there is no need to stop first here. + // tk_session_destroy stops first internally (idempotent), so no explicit stop is needed here. tk_session_destroy(handle) } - /// Starts. **Non-blocking** -- returning only means the request was accepted; success or failure must be checked via the subsequent status. + /// Starts. Non-blocking: returning only means the request was accepted; check the subsequent status for success or + /// failure. public func start() throws { var error = tk_error_t() let result = tk_session_start(handle, &error) @@ -80,20 +81,25 @@ public final class TetherKitNextSession: @unchecked Sendable { linkKernelDrops: raw.link_kernel_drops, txBackpressure: raw.tx_backpressure, monotonicNanos: raw.monotonic_nanos, - fatalMessage: String(fixedCArray: raw.fatal)) + fatalMessage: String(fixedCArray: raw.fatal), + peerAddress: { + let peer = String(fixedCArray: raw.peer_ipv4) + return peer.isEmpty ? nil : peer + }()) } - /// Takes away the queued events, rendering them into one sentence for the user to read. + /// Drains the queued events, rendering them into one sentence for the user. /// - /// Keeps only the categories that "users care about": link changes, device resets, fatal errors. The RNDIS internal - /// state transitions and lifecycle transitions are already shown by the UI via status, and flooding them again as notifications would be just noise. + /// Keeps only the categories users care about: link changes, device resets, fatal errors. RNDIS internal + /// state transitions and lifecycle transitions are already shown through status, and notifying them again would be + /// noise. public func drainNotices() -> [String] { var buffer = [tk_event_t](repeating: tk_event_t(), count: Self.eventCapacity) let taken = tk_session_poll_events(handle, &buffer, Self.eventCapacity) return buffer.prefix(taken).compactMap { event -> String? in - // The C side's tk_event_kind values are all non-negative and are imported by Swift as UInt32, while the struct - // field is int32_t -- the two cannot be compared directly and must be converted explicitly once. + // The C side's tk_event_kind values are all non-negative and Swift imports them as UInt32, while the struct + // field is int32_t, so the two cannot be compared directly and need one explicit conversion. switch event.kind { case Int32(TK_EVENT_LINK.rawValue): return L(event.a == 1 ? .eventLinkUp : .eventLinkDown) diff --git a/gui/Sources/TetherKitNextHelper/HelperService.swift b/gui/Sources/TetherKitNextHelper/HelperService.swift index d161906..5df47d6 100644 --- a/gui/Sources/TetherKitNextHelper/HelperService.swift +++ b/gui/Sources/TetherKitNextHelper/HelperService.swift @@ -4,37 +4,34 @@ import TetherKitNextIPC /// The helper's XPC service implementation. /// -/// * Threading model * +/// Threading model: XPC methods are invoked on the connection's own queue. Any potentially slow operation +/// (starting a session does a USB handshake, DHCP waits for a lease) is dispatched at once to our own serial +/// queue with an asynchronous reply and never blocks the XPC queue; otherwise later status polls on the same +/// connection would stall and the UI would look frozen. Session lifecycle and interface configuration each +/// use one serial queue: they do not block each other, but each is strictly serial inside (concurrent +/// start/stop or concurrent ipconfig would be a disaster). State queries are not queued and go straight to +/// the C layer, whose snapshot is thread-safe. /// -/// XPC methods are invoked on the connection's own queue. Any potentially time-consuming operation (starting a session does a USB -/// handshake, DHCP waits for a lease) is **immediately dispatched to our own serial queue with an asynchronous reply**, and must never -/// block on the XPC queue -- otherwise subsequent status polls on the same connection get stuck too, and the UI shows up -/// as "everything frozen". -/// -/// The session lifecycle and NIC configuration each use one serial queue: the two do not block each other, but each is strictly serial internally -/// (concurrent start/stop or concurrent ipconfig would be a disaster). State queries are not queued and go straight to -/// the C layer -- the snapshot over there is thread-safe anyway. -/// -/// `@unchecked Sendable`: all mutable state is guarded by `stateLock`, and the -/// work queues are serial. XPC invokes methods on arbitrary threads. +/// `@unchecked Sendable`: all mutable state is guarded by `stateLock`, and the work queues are serial. XPC +/// invokes methods on arbitrary threads. final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sendable { private let lifecycleQueue = DispatchQueue(label: "com.tetherkitnext.helper.lifecycle") private let networkQueue = DispatchQueue(label: "com.tetherkitnext.helper.network") - /// Protects session and notices. Hold times are all extremely short, so an ordinary lock suffices. + /// Protects session and notices. Hold times are extremely short, so an ordinary lock suffices. private let stateLock = NSLock() private var session: TetherKitNextSession? - /// startSession is in the middle of constructing / handshaking. During this window session is not yet registered, yet the device - /// **has already** been opened by this process -- the occupancy judgment for enumeration must count it, otherwise string - /// reads would insert one more transfer onto the control endpoint that is mid-handshake. + /// startSession is constructing / handshaking. During this window session is not yet registered, yet the + /// device has already been opened by this process. The occupancy judgment for enumeration must count it, or + /// string reads would insert one more transfer onto the control endpoint that is mid-handshake. private var sessionStarting = false - /// Hints not yet taken away by the App. + /// Notices the app has not drained yet. private var pendingNotices: [String] = [] // MARK: - Probe interfaces that need no authorization func helperVersion(reply: @escaping @Sendable (String) -> Void) { - // Include the XPC interface revision number, so the App can detect "the helper is an old pre-upgrade version". + // Include the XPC interface revision number so the app can detect an outdated daemon. let info = TetherKitNextLibrary.versionInfo reply(HelperConstants.encodeVersion(info.version, build: info.build)) } @@ -44,11 +41,12 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen } func listDevices(reply: @escaping @Sendable (Data?, String?) -> Void) { - // While the device is held by this process, do not read string descriptors: reading needs libusb_open, which fails in vain, - // and would also insert a transfer onto the control endpoint that is mid-handshake. The judgment uses "really holding" rather than "session - // is non-nil" -- dead sessions that are failed / stopped have long since torn USB down cleanly, and counting them as - // "occupied" would make the name unreadable forever after the device is unplugged and replugged. - // Skipping does not lose names: the C layer backfills the value last read successfully (see environment.cc). + // While the device is held by this process, do not read string descriptors: reading needs libusb_open, which + // fails in vain and would also insert a transfer onto the control endpoint that is mid-handshake. The + // judgment uses "really holding" rather than "session is non-nil": dead (failed / stopped) sessions have + // long since torn USB down cleanly, and counting them as occupied would leave the name unreadable forever + // after the device is replugged. Skipping does not lose names: the C layer backfills the last value read + // successfully (see environment.cc). let deviceHeld = stateLock.withLock { () -> Bool in if sessionStarting { return true } guard let session else { return false } @@ -69,8 +67,8 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen let (status, deadSession) = stateLock.withLock { () -> (SessionStatus, TetherKitNextSession?) in guard let session else { return (.idle, nil) } let s = session.status() - // When a session stops or fails (such as device unplugged), clean it up so subsequent - // queries return .idle and the helper does not hold onto dead state. + // When a session stops or fails (such as device unplugged), clean it up so later queries return .idle and + // the helper does not hold onto dead state. if s.runState == .failed || s.runState == .stopped { self.session = nil return (s, session) @@ -107,8 +105,9 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen } func setLanguage(_ rawValue: String, reply: @escaping @Sendable () -> Void) { - // If it is not recognized, leave things as they are. Better to keep using the previous language than to fall back to the default because the App passed a new value - // -- that would show up as "switched language, and the helper's logs turned back to English instead". + // If it is not recognized, leave things as they are. Keeping the previous language is better than falling + // back to the default because the app passed a new value: that would look like "switched language, and the + // helper's logs turned back to English". if let language = Language(rawValue: rawValue) { L10n.apply(language) TetherKitNextLibrary.setLanguage(language) @@ -128,12 +127,12 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen lifecycleQueue.async { [weak self] in guard let self else { return } - // An old session that is completely dead (failed / stopped) must not block a new connection. + // A completely dead session (failed / stopped) must not block a new connection. // - // Typical scenario: the device is unplugged -> consecutive keepalive failures -> the session enters failed. The C++ side - // has already torn down USB and the NIC entirely by then, and the Swift layer is left with only a shell -- but it is - // non-nil. If we only rejected on "session != nil", after the user replugs the device it could never - // connect again, and only reinstalling the helper would help. This pitfall was really hit. + // Typical scenario: the device is unplugged, consecutive keepalives fail and the session enters failed. The + // C++ side has already torn down USB and the interface by then, leaving only a shell in the Swift layer + // that is still non-nil. Rejecting on "session != nil" alone would make connecting impossible after the + // device is replugged until the helper is restarted. if let existing = self.withState({ $0 }) { let state = existing.status().runState guard state == .failed || state == .stopped else { @@ -144,8 +143,8 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen self.stateLock.withLock { self.session = nil } } - // Expose "the device is already held" throughout the whole handshake period from construction to start() returning, - // so a concurrently arriving listDevices skips string reads (see the explanation over there). + // Expose "the device is already held" for the whole handshake from construction to start() returning, so a + // concurrent listDevices skips string reads (see the explanation there). self.stateLock.withLock { self.sessionStarting = true } defer { self.stateLock.withLock { self.sessionStarting = false } } do { @@ -164,8 +163,8 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen lifecycleQueue.async { [weak self] in guard let self else { return } - // First take the session out of the state and then stop it: stopping has to join the control thread and may take - // hundreds of milliseconds, during which it should not keep claiming "the session is running" externally. + // Take the session out of the state first, then stop it: stopping joins the control thread and may take + // hundreds of milliseconds, during which it should not claim "the session is running" externally. let session = self.stateLock.withLock { () -> TetherKitNextSession? in defer { self.session = nil } return self.session @@ -182,14 +181,14 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen authorize(authorization, reply: reply) else { return } - // The UI has already validated once, but XPC is reachable by any local process, and the helper must put up its own barrier - // -- and it uses the same rules, so the two sides never judge inconsistently. + // The UI has already validated once, but XPC is reachable by any local process, so the helper must put up + // its own barrier, using the same rules so the two sides never judge inconsistently. if let message = NetworkValidator.validationMessage(for: configuration) { reply(message, false) return } - // DHCP blocks until a lease is obtained (the library's internal cap is 10 seconds), so it must reply asynchronously. + // DHCP blocks until a lease is obtained (the library's cap is 10 seconds), so it must reply asynchronously. networkQueue.async { [weak self] in do { try NetworkConfigurator.apply(configuration, to: interface) @@ -222,9 +221,9 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen /// Called on receiving SIGTERM (`launchctl bootout`). /// - /// Swift's deinit does not run when the process is terminated, and without actively stopping, the feth NIC would leak in the - /// kernel. The on-disk registration can catch SIGKILL, but when a graceful exit is possible it should still exit gracefully -- - /// that way even the "clean up at next launch" step is saved. + /// Swift's deinit does not run when the process is terminated, and without actively stopping, the feth + /// interface would leak in the kernel. The on-disk registry can catch SIGKILL, but a graceful exit avoids + /// the "clean up at next launch" step. func shutdown() { let session = stateLock.withLock { () -> TetherKitNextSession? in defer { self.session = nil } @@ -235,25 +234,20 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen // MARK: - Internal utilities - /// Verifies authorization; when it does not pass, replies with an error and sets the second parameter to true, telling the App - /// "this is an authorization problem, popping up the dialog again and trying once more may succeed". - /// - /// ★ Empty authorization (Touch ID path, protocol revision 5) ★ + /// Verifies authorization; when it does not pass, replies with an error and sets the second parameter to + /// true, telling the app this is an authorization problem and showing the dialog again may succeed. /// - /// A team-signed app confirms the user with LocalAuthentication (Touch - /// ID, Apple Watch or the login password) and then sends no admin - /// authorization at all. That is only acceptable when both hold: - /// * this daemon pinned the connection to TetherKitNext.app signed by - /// our own team (`CodeSigning.clientRequirement`), so the caller is - /// our app and not some other local process skipping the prompt; - /// * the calling user is an administrator — the same population the - /// `system.privilege.admin` dialog accepts, so the policy does not - /// widen, only the way an admin proves presence changes. - /// Anything else is rejected as an authorization problem, and the app - /// falls back to the administrator dialog. + /// Empty authorization (Touch ID path, protocol revision 5): a team-signed app confirms the user with + /// LocalAuthentication (Touch ID, Apple Watch or the login password) and then sends no admin authorization + /// at all. That is only acceptable when both hold: + /// - this daemon pinned the connection to TetherKitNext.app signed by our own team + /// (`CodeSigning.clientRequirement`), so the caller is our app and not some other local process skipping + /// the prompt; + /// - the calling user is an administrator, the same population the `system.privilege.admin` dialog + /// accepts, so the policy does not widen; only the way an admin proves presence changes. + /// Anything else is rejected as an authorization problem, and the app falls back to the administrator dialog. /// - /// Must be called synchronously from the XPC method, where - /// `NSXPCConnection.current()` is the caller's connection. + /// Must be called synchronously from the XPC method, where `NSXPCConnection.current()` is the caller's connection. private func authorize(_ data: Data, reply: @escaping @Sendable (String?, Bool) -> Void) -> Bool { if data.isEmpty { guard CodeSigning.clientRequirement != nil, @@ -299,7 +293,8 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen guard !notices.isEmpty else { return } stateLock.withLock { pendingNotices.append(contentsOf: notices) - // Cap of 200: if the App does not come to take them for a long time (say it is suspended), it should not be allowed to grow without bound. + // Capped at 200: if the app does not come to take them for a long time (say it is suspended), they must not + // grow without bound. if pendingNotices.count > 200 { pendingNotices.removeFirst(pendingNotices.count - 200) } @@ -324,14 +319,11 @@ final class HelperListenerDelegate: NSObject, NSXPCListenerDelegate { func listener(_ listener: NSXPCListener, shouldAcceptNewConnection connection: NSXPCConnection) -> Bool { - // ★ Who may connect ★ - // - // Team-signed (Developer ID) builds only accept TetherKitNext.app signed by - // the same team; the check runs against the peer's audit token for - // every message. Ad-hoc development builds have no Team ID to pin, so - // they fall back to the original model: anyone may connect, but every - // privileged call must carry an admin authorization that is re-verified - // here (AuthorizationVerifier). Release builds enforce both layers. + // Who may connect: team-signed (Developer ID) builds only accept TetherKitNext.app signed by the same team; + // the check runs against the peer's audit token for every message. Ad-hoc development builds have no Team + // ID to pin, so they fall back to the authorization-only model: anyone may connect, but every privileged + // call must carry an admin authorization that is re-verified here (AuthorizationVerifier). Release builds + // enforce both layers. if let requirement = CodeSigning.clientRequirement { connection.setCodeSigningRequirement(requirement) } diff --git a/gui/Sources/TetherKitNextHelper/SystemIntegration.swift b/gui/Sources/TetherKitNextHelper/SystemIntegration.swift index 461a476..d3798c6 100644 --- a/gui/Sources/TetherKitNextHelper/SystemIntegration.swift +++ b/gui/Sources/TetherKitNextHelper/SystemIntegration.swift @@ -4,13 +4,11 @@ import TetherKitNextIPC /// Where this daemon's own app bundle is, if it runs from one. /// -/// Under SMAppService the daemon executes in place from -/// `TetherKitNext.app/Contents/MacOS/tetherkitnext-helper` (the plist's -/// `BundleProgram`). Everything bundle-relative is derived from the kernel's -/// view of our executable path, never from anything a client sends. +/// Under SMAppService the daemon executes in place from `TetherKitNext.app/Contents/MacOS/tetherkitnext-helper` +/// (the plist's `BundleProgram`). Everything bundle-relative is derived from the kernel's view of our +/// executable path, never from anything a client sends. enum OwnBundle { - /// `…/TetherKitNext.app/Contents`, or nil when not running from an app bundle - /// (e.g. a development LaunchDaemon install). + /// `…/TetherKitNext.app/Contents`, or nil when not running from an app bundle (e.g. a development LaunchDaemon). static let contentsDirectory: URL? = { var size = UInt32(PATH_MAX) var buffer = [CChar](repeating: 0, count: Int(size)) @@ -25,13 +23,11 @@ enum OwnBundle { }() } -/// Removes the pre-SMAppService installation (LaunchDaemon + files under -/// /Library/PrivilegedHelperTools) that upstream TetherKit 0.1.x builds installed -/// through AuthorizationExecuteWithPrivileges. +/// Removes the pre-SMAppService installation (LaunchDaemon + files under /Library/PrivilegedHelperTools) that +/// TetherKit 0.1.x builds installed through AuthorizationExecuteWithPrivileges. /// -/// Doing it here, as root, on the new daemon's first start means an upgrade -/// needs no extra password prompt and leaves no stale root-owned binaries -/// behind. Only paths belonging to the legacy install are touched. +/// Doing it here, as root, on the daemon's first start means an upgrade needs no extra password prompt and +/// leaves no stale root-owned binaries behind. Only paths belonging to the legacy install are touched. enum LegacyHelper { static func removeIfPresent() -> Bool { let fileManager = FileManager.default @@ -41,8 +37,7 @@ enum LegacyHelper { return false } - // bootout sends SIGTERM; the legacy helper stops its session and - // destroys its feth pair on the way out. + // bootout sends SIGTERM; the legacy helper stops its session and destroys its feth pair on the way out. _ = run("/bin/launchctl", ["bootout", "system/\(legacy.label)"]) var paths = [legacy.launchDaemonPlistPath, legacy.executablePath] @@ -78,13 +73,11 @@ enum LegacyHelper { /// Manages the `/usr/local/bin/tetherkitnext-cli` symlink. /// /// Security notes (this runs as root): -/// * The link target is always the CLI inside *this daemon's own* bundle. -/// * /usr/local/bin may be user-writable (Homebrew on Intel chowns it), so -/// the directory itself must be a real directory, and an existing entry is -/// only replaced when it is a symlink that already points into a -/// TetherKitNext.app bundle or dangles. A regular file or a foreign symlink -/// (e.g. a Homebrew formula) is reported, never clobbered. -/// * symlink(2)/unlink(2) operate on the link itself and never follow it. +/// - The link target is always the CLI inside this daemon's own bundle. +/// - /usr/local/bin may be user-writable (Homebrew on Intel chowns it), so the directory itself must be a +/// real directory, and an existing entry is only replaced when it is a symlink that already points into a +/// TetherKitNext.app bundle or dangles. A regular file or a foreign symlink is reported, never clobbered. +/// - symlink(2)/unlink(2) operate on the link itself and never follow it. enum CommandLineToolLink { enum Failure: LocalizedError { case notInBundle @@ -159,8 +152,8 @@ enum CommandLineToolLink { return } guard errno == ENOENT else { throw Failure.system("lstat", errno) } - // /usr/local exists on every macOS install; only bin/ may be missing - // (Apple Silicon Macs without Homebrew in /usr/local). + // /usr/local exists on every macOS install; only bin/ may be missing (Apple Silicon Macs without Homebrew in + // /usr/local). guard mkdir(path, 0o755) == 0 || errno == EEXIST else { throw Failure.system("mkdir", errno) } @@ -168,14 +161,13 @@ enum CommandLineToolLink { } } -/// Membership of the local `admin` group, the population -/// `system.privilege.admin` authenticates. +/// Membership of the local `admin` group, the population `system.privilege.admin` authenticates. enum AdminGroup { static func contains(uid: uid_t) -> Bool { guard let adminGroup = adminGroupID() else { return false } - // pw_name points into `buffer`, so the buffer must outlive every use - // of it; an explicit allocation makes that lifetime obvious. + // pw_name points into `buffer`, so the buffer must outlive every use of it; an explicit allocation makes that + // lifetime obvious. let bufferSize = 4096 let buffer = UnsafeMutablePointer.allocate(capacity: bufferSize) defer { buffer.deallocate() } @@ -186,8 +178,8 @@ enum AdminGroup { return false } - // getgrouplist fills at most `count` entries and returns -1 when the - // list was longer; the entries it did fill are still valid. + // getgrouplist fills at most `count` entries and returns -1 when the list was longer; the entries it did fill + // are still valid. let capacity: Int32 = 1024 var count = capacity var groups = [Int32](repeating: -1, count: Int(capacity)) diff --git a/gui/Sources/TetherKitNextHelper/main.swift b/gui/Sources/TetherKitNextHelper/main.swift index 5221352..649f1fc 100644 --- a/gui/Sources/TetherKitNextHelper/main.swift +++ b/gui/Sources/TetherKitNextHelper/main.swift @@ -1,35 +1,29 @@ -// tetherkitnext-helper -- the privileged helper running as root. +// tetherkitnext-helper: the privileged daemon running as root. // -// * Where its root comes from * -// From launchd: the com.tetherkitnext.helperd.plist embedded in the App (registered via SMAppService) declares -// MachServices, and as soon as the App connects to this Mach service, launchd launches it on demand, -// and it is root from the moment it starts. **It has nothing to do with whether the user pressed the fingerprint** -- so "who is calling" must be -// re-verified by the helper itself every time; see TetherKitNextIPC/Authorization.swift. +// Where its root comes from: launchd. The com.tetherkitnext.helperd.plist embedded in the app (registered via +// SMAppService) declares MachServices, and launchd starts the daemon on demand when the app connects to this +// Mach service, as root from the first instruction. That has nothing to do with whether the user pressed +// the fingerprint, so the helper must re-verify "who is calling" itself on every call; see +// TetherKitNextIPC/Authorization.swift. // -// ★ How it is installed ★ -// Through SMAppService: the app registers Contents/Library/LaunchDaemons/ -// com.tetherkitnext.helperd.plist, whose BundleProgram points at this binary -// inside TetherKitNext.app. launchd runs it in place (nothing is copied into -// /Library), macOS asks the user to approve it in System Settings › Login -// Items, and replacing the app updates the daemon. This replaced the old -// AuthorizationExecuteWithPrivileges + setuid installer, which relied on an -// API deprecated since macOS 10.7. +// How it is installed: the app registers Contents/Library/LaunchDaemons/com.tetherkitnext.helperd.plist +// through SMAppService, whose BundleProgram points at this binary inside TetherKitNext.app. launchd runs it in +// place (nothing is copied into /Library), macOS asks the user to approve it in System Settings › Login +// Items, and replacing the app updates the daemon. import Foundation import TetherKitNextCore import TetherKitNextIPC -/// Writes one line to stderr. The helper is launched by launchd, and stderr goes into the LaunchDaemon's -/// log file -- when troubleshooting problems like "the helper will not start", that is the only place where anything can be seen. +/// Writes one line to stderr. The helper is launched by launchd, and stderr goes into the LaunchDaemon's log +/// file, which is the only place to look when troubleshooting problems like "the helper will not start". func writeToStandardError(_ message: String) { FileHandle.standardError.write(Data((message + "\n").utf8)) } // ---- Only as launchd's root daemon ---- // -// Run by hand (as a user, or with sudo from a shell) the binary would register -// no Mach service, hold no session, and block forever in dispatchMain(). -// Refuse clearly instead; this also makes stray invocations such as the old -// `--install` flag fail fast. +// Run by hand (as a user, or with sudo from a shell) the binary would register no Mach service, hold no +// session, and block forever in dispatchMain(). Refuse clearly instead, so stray invocations fail fast. if geteuid() != 0 || getppid() != 1 { writeToStandardError( "tetherkitnext-helper is TetherKitNext's background component and is started by launchd. " @@ -39,21 +33,21 @@ if geteuid() != 0 || getppid() != 1 { // ---- Logging ---- // -// Turns on capture so the App can see the library's internal logs on the UI. Output to stderr is unaffected. +// Turns on capture so the app can show the library's internal logs in the UI. Output to stderr is unaffected. TetherKitNextLibrary.startLogCapture(level: .info) // ---- Legacy install ---- // -// Must run before orphan cleanup: bootout makes the legacy daemon tear down -// its own feth pair, and only then are its registry entries truly orphaned. +// Must run before orphan cleanup: bootout makes the legacy daemon tear down its own feth pair, and only +// then are its registry entries truly orphaned. if LegacyHelper.removeIfPresent() { writeToStandardError("Removed the legacy com.tetherkit.helper LaunchDaemon") } // ---- Backstop cleanup ---- // -// If the last run was SIGKILLed, destructors do not run and the feth NIC is still left in the kernel. This is the only place that can rescue -// that situation -- a signal handler cannot intercept SIGKILL. +// If the last run was SIGKILLed, destructors did not run and the feth interface is still in the kernel. This +// is the only place that can recover from that; a signal handler cannot intercept SIGKILL. do { let removed = try TetherKitNextLibrary.cleanupOrphanInterfaces() if removed > 0 { @@ -68,19 +62,21 @@ let delegate = HelperListenerDelegate(service: service) // ---- Graceful shutdown ---- // -// What `launchctl bootout` sends is SIGTERM, and Swift's deinit does not run when the process is terminated. -// Without catching it the NIC would leak in the kernel (although the on-disk registration is a backstop, cleaning up on the spot is better). +// `launchctl bootout` sends SIGTERM, and Swift's deinit does not run when the process is terminated. Without +// catching it the interface would leak in the kernel (the on-disk registry is a backstop, but cleaning up +// on the spot is better). // -// DispatchSource is used rather than a signal(2) handler: the latter runs in signal context, -// where what can be done is extremely limited (no locking, no memory allocation), while the shutdown teardown we have to do -// needs both. DispatchSource turns it into a callback on an ordinary queue, and the restrictions vanish. +// A DispatchSource is used rather than a signal(2) handler: the latter runs in signal context, where very +// little is allowed (no locking, no allocation), while the shutdown teardown needs both. DispatchSource +// turns it into a callback on an ordinary queue. // -// SIG_IGN must come first: before DispatchSource takes over, the default behavior (terminating the process) is still in effect. +// SIG_IGN must come first: until the DispatchSource takes over, the default behavior (terminating the +// process) is still in effect. signal(SIGTERM, SIG_IGN) let terminationSource = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main) terminationSource.setEventHandler { - // The source delivers on the main queue, which is where top-level state - // (`service`) lives under Swift 6's main-actor isolation of main.swift. + // The source delivers on the main queue, which is where top-level state (`service`) lives under Swift 6's + // main-actor isolation of main.swift. MainActor.assumeIsolated { writeToStandardError(L(.helperSigtermReceived)) service.shutdown() @@ -97,7 +93,7 @@ writeToStandardError(L(.helperReady, TetherKitNextLibrary.versionInfo.version)) // Block on the main runloop. // -// Deliberately **not** doing "exit after being idle for a while": once a session is running, the helper owns the feth NIC and the -// BPF descriptor, and exiting would cut off the user's network. The LaunchDaemon is launched on demand, -// and staying alive does not occupy resources when nobody is using it -- because it was not launched at all then. +// There is no "exit after being idle for a while": once a session is running, the helper owns the feth +// interface and the BPF descriptor, and exiting would cut off the user's network. The LaunchDaemon is +// started on demand, so staying alive costs nothing when nobody is using it (it was never launched then). dispatchMain() diff --git a/gui/Sources/TetherKitNextIPC/Authorization.swift b/gui/Sources/TetherKitNextIPC/Authorization.swift index 90d9f19..ae32b5f 100644 --- a/gui/Sources/TetherKitNextIPC/Authorization.swift +++ b/gui/Sources/TetherKitNextIPC/Authorization.swift @@ -1,38 +1,28 @@ import Foundation import Security -/// Obtaining the authorization credential (App side) and verifying it (helper side). +/// Obtaining the authorization credential (app side) and verifying it (helper side). /// -/// * The two sides are deliberately placed in the same file * -/// The difference between them is only one flag (`.interactionAllowed`), and getting that one bit wrong is a -/// security hole. Written together, when one side is changed the other is right in front of you. +/// Both sides live in one file because they differ in a single flag (`.interactionAllowed`), and getting that +/// bit wrong is a security hole. Keeping them together puts the other side in view whenever one is changed. /// -/// * One sentence that must be remembered: authorization != root * -/// A successful `AuthorizationCopyRights` **changes nothing about the process** -- neither uid nor euid -/// is touched. What it produces is only a credential saying "the user confirmed with password/fingerprint at some moment". -/// The privilege itself must have another source (here, the helper launched by launchd as root). -/// -/// So the order cannot be reversed: it is not "first pop up the fingerprint to get root, then create the NIC", but "first have a resident -/// root helper, and for each operation pop up the fingerprint to get a credential and hand it to it for verification". +/// Authorization is not root. A successful `AuthorizationCopyRights` changes nothing about the process (neither +/// uid nor euid); it only yields a credential saying the user confirmed at some moment. The privilege itself +/// comes from elsewhere, here the helper that launchd runs as root. So the flow is not "authenticate to get root, +/// then create the interface" but "a resident root helper exists, and each operation hands it a credential to verify". /// The holder of one authorization. /// -/// * Its sole reason to exist: the external form is **not the credential itself, only a reference** * -/// -/// The 32 bytes produced by `AuthorizationMakeExternalForm` contain no rights information whatsoever; it is just -/// a key pointing to that authorization inside securityd. As soon as the App side releases the AuthorizationRef -/// (especially with `.destroyRights`), what is in securityd is gone -- -/// and the helper's subsequent `AuthorizationCreateFromExternalForm` will fail, -/// reporting `errAuthorizationDenied (-60005)`. -/// -/// So the AuthorizationRef must **live until after the XPC round trip ends**. Holding it in a class -/// and letting ARC manage it is far more reliable than hand-writing "remember to free it at the end" at every call site. +/// The external form is a reference, not the credential: the 32 bytes from `AuthorizationMakeExternalForm` +/// contain no rights information, only a key to that authorization inside securityd. Once the app releases the +/// AuthorizationRef (especially with `.destroyRights`), the authorization is gone and the helper's +/// `AuthorizationCreateFromExternalForm` fails with `errAuthorizationDenied (-60005)`. The ref therefore has +/// to live until the XPC round trip ends, and holding it in a class that ARC frees is more reliable than +/// freeing it by hand at every call site. /// -/// * Why it is safe to mark @unchecked Sendable * -/// HelperInstaller has to hand the token to a background queue (AEWP blocks on the authorization dialog and cannot occupy the main -/// thread). There is no mutable state here -- both stored properties are let; the AuthorizationRef itself -/// is thread-safe per the Authorization Services documentation (the real state is in the securityd -/// process, and cross-process calls are naturally serialized); and deinit is guaranteed by ARC to run only once. +/// `@unchecked Sendable` is safe: the token crosses actors (AppModel awaits XPC calls that complete on XPC +/// queues), both stored properties are `let`, an AuthorizationRef is thread-safe per the Authorization +/// Services documentation (the state lives in securityd), and ARC runs deinit exactly once. public final class AuthorizationToken: @unchecked Sendable { /// The 32-byte external form that can be passed across processes to the helper. public let externalForm: Data @@ -44,19 +34,10 @@ public final class AuthorizationToken: @unchecked Sendable { self.externalForm = externalForm } - /// Briefly lends the underlying AuthorizationRef to an API that needs the thing itself (currently only - /// `AuthorizationExecuteWithPrivileges` -- it wants the ref, not the external form). - /// - /// Made a scoped borrow rather than exposing a property directly: the ref's lifetime belongs to this class, and if anyone stores it - /// outside the closure, it becomes a dangling reference once the token is released -- an error the compiler cannot catch. - public func withReference(_ body: (AuthorizationRef) throws -> T) rethrows -> T { - try body(authorization) - } - deinit { - // With .destroyRights: the credential belongs to the App, is destroyed after use, and no long-lived pass - // is left in the process. (On the helper side, verification **must not** carry this flag, - // otherwise it would invalidate this side's authorization too -- see AuthorizationVerifier.) + // With .destroyRights: the credential belongs to the app, is destroyed after use, and leaves no long-lived + // pass in the process. The helper's verification must not carry this flag, or it would invalidate this side's + // authorization too (see AuthorizationVerifier). AuthorizationFree(authorization, [.destroyRights]) } } @@ -80,29 +61,21 @@ public enum AuthorizationBroker { } } - /// Pops up the system authorization dialog, and on success returns a token holding this authorization. + /// Shows the system authorization dialog and, on success, returns a token holding the authorization. /// - /// * The token should be **cached and reused**, rather than fetched anew for every operation * + /// Cache and reuse the token rather than fetching one per operation. The `system.privilege.admin` rule has + /// `shared = false` and `timeout = 300`: a credential is not shared across AuthorizationRefs, so every new ref + /// asks the user to authenticate again, while on the same ref it stays valid for 5 minutes. Reusing one + /// token needs a single authentication per 5 minutes, as in Apple's EvenBetterAuthorizationSample. After + /// expiry the helper's verification fails and the caller can drop the cache and fetch again. /// - /// The measured parameters of the `system.privilege.admin` rule are `shared = false` and - /// `timeout = 300`: - /// * `shared = false` -- the credential is **not shared across AuthorizationRefs**. Every time - /// `AuthorizationCreate` creates a new ref, the user must authenticate again. - /// * `timeout = 300` -- but on the **same ref**, the credential is valid for 5 minutes. + /// The caller must keep the token alive until the XPC round trip ends: once it is released, the authorization + /// in securityd is gone and the helper reports `errAuthorizationDenied (-60005)` when restoring the external form. /// - /// So "connect, configure network, disconnect" each popping up a dialog is purely because we create a new ref every time. - /// Reusing the same token needs only one authentication within 5 minutes. This is also what Apple itself does in - /// EvenBetterAuthorizationSample. + /// - Parameter prompt: A sentence shown in the system dialog saying what the authorization is for. Without + /// it the dialog only says "wants to make changes". /// - /// After expiry the helper-side verification will fail, and the caller can discard the cache and fetch again accordingly. - /// - /// WARNING: **The caller must keep the token alive until after the XPC round trip ends.** Once the token is released, the authorization - /// in securityd is gone, and when the helper restores the external form it reports `errAuthorizationDenied (-60005)`. - /// - /// - Parameter prompt: A sentence shown in the system authorization dialog, telling the user what this authorization is - /// for. If not passed, the dialog has only the bland "wants to make changes". - /// - /// Must be called on the main thread -- it presents UI. + /// Must be called on the main thread because it presents UI. public static func requestAuthorization( right: String = HelperConstants.privilegedRightName, prompt: String? = nil @@ -112,7 +85,7 @@ public enum AuthorizationBroker { guard createStatus == errAuthorizationSuccess, let authorization else { throw Failure.internalFailure(createStatus) } - // On the failure path release immediately; on the success path ownership is handed to AuthorizationToken. + // On the failure path release immediately; on success, ownership moves to AuthorizationToken. var handedOff = false defer { if !handedOff { @@ -138,11 +111,11 @@ public enum AuthorizationBroker { externalForm: withUnsafeBytes(of: &external) { Data($0) }) } - /// Requests rights, popping up a dialog if necessary. + /// Requests rights, showing a dialog if necessary. /// - /// Factored out separately because constructing the environment items needs several layers of nested `withUnsafe*` -- those buffers must live - /// until after `AuthorizationCopyRights` returns, and if written in the main flow, a later person could easily - /// "tidy it up in passing" into a dangling pointer. + /// Separate because building the environment items needs several nested `withUnsafe*` calls whose buffers + /// must live until `AuthorizationCopyRights` returns; inlined in the main flow, a later "tidy-up" could + /// turn them into dangling pointers. private static func copyRights(_ authorization: AuthorizationRef, right: String, prompt: String?) -> OSStatus { @@ -156,9 +129,10 @@ public enum AuthorizationBroker { return withUnsafeMutablePointer(to: &rightItem) { rightPointer in var rights = AuthorizationRights(count: 1, items: rightPointer) - // The App side **does** carry .interactionAllowed -- popping up the dialog is exactly what we want. - // .preAuthorize makes the right be granted on the spot rather than at actual use, - // so that the credential enters this ref's cache and can be reused by subsequent operations. + // The app side carries .interactionAllowed because showing the dialog is the point. .preAuthorize + // grants + // the right on the spot rather than at actual use, so the credential enters this ref's cache and later + // operations can reuse it. let flags: AuthorizationFlags = [.extendRights, .interactionAllowed, .preAuthorize] guard prompt != nil else { @@ -184,7 +158,7 @@ public enum AuthorizationBroker { } } -/// helper side: verifies the credential handed over by the caller. +/// Helper side: verifies the credential handed over by the caller. public enum AuthorizationVerifier { public enum Failure: LocalizedError { case malformedCredential @@ -205,18 +179,14 @@ public enum AuthorizationVerifier { /// Verifies that the credential really contains the specified right. Throws if it does not. /// - /// * Three details that must be followed * - /// - /// 1. **Must never carry `.interactionAllowed`.** The daemon has no UI session; if it were really allowed to - /// pop up a dialog, any process able to connect to the Mach service could trigger system authorization dialogs at will to harass - /// the user. This step only checks "does this credential already contain this right", and acquires no new rights. - /// - /// 2. **`AuthorizationFree` must not carry `.destroyRights`.** The credential belongs to the App, - /// and the helper only borrows it for checking; carrying it would invalidate the App's authorization too. - /// - /// 3. Verification must be done for **every privileged call**. The helper's root comes from launchd, - /// and has nothing to do with whether the user pressed the fingerprint -- it is root from the moment it starts, and any process able to connect to the Mach - /// service can send requests. So "who is calling" can only be answered by the helper itself. + /// 1. Never carry `.interactionAllowed`. The daemon has no UI session, and if it could show a dialog, any + /// process able to connect to the Mach service could trigger authorization dialogs at will. This step only + /// checks that the credential already contains the right and acquires nothing. + /// 2. `AuthorizationFree` must not carry `.destroyRights`. The credential belongs to the app and the helper + /// only borrows it; the flag would invalidate the app's authorization too. + /// 3. Verify on every privileged call. The helper's root comes from launchd and has nothing to do with the + /// user's fingerprint, and any process able to connect to the Mach service can send requests, so only + /// the helper itself can answer "who is calling". public static func verify(externalForm data: Data, right: String = HelperConstants.privilegedRightName) throws { guard data.count == MemoryLayout.size else { @@ -233,7 +203,7 @@ public enum AuthorizationVerifier { guard restoreStatus == errAuthorizationSuccess, let authorization else { throw Failure.restoreFailed(restoreStatus) } - // Note: **without** .destroyRights; see item 2 above. + // Without .destroyRights; see item 2 above. defer { AuthorizationFree(authorization, []) } var name = Array(right.utf8CString) @@ -242,7 +212,7 @@ public enum AuthorizationVerifier { value: nil, flags: 0) return withUnsafeMutablePointer(to: &item) { itemPointer in var rights = AuthorizationRights(count: 1, items: itemPointer) - // Only .extendRights, **without** .interactionAllowed; see item 1 above. + // Only .extendRights, without .interactionAllowed; see item 1 above. return AuthorizationCopyRights(authorization, &rights, nil, [.extendRights], nil) } } diff --git a/gui/Sources/TetherKitNextIPC/CodeSigning.swift b/gui/Sources/TetherKitNextIPC/CodeSigning.swift index 9617d84..754eda6 100644 --- a/gui/Sources/TetherKitNextIPC/CodeSigning.swift +++ b/gui/Sources/TetherKitNextIPC/CodeSigning.swift @@ -1,30 +1,21 @@ import Foundation import Security -/// Code-signing identity checks for the XPC connection between the app and the -/// privileged daemon. +/// Code-signing identity checks for the XPC connection between the app and the privileged daemon. /// -/// ★ Why this exists ★ +/// Why this exists: the daemon runs as root and listens on a Mach service that any local process can look up. +/// Safety would otherwise rest entirely on each privileged call carrying an admin AuthorizationRef. That is +/// still enforced, but a Developer ID build can do better and refuse the connection outright unless the peer +/// is TetherKitNext.app signed by the same team. This is Apple's documented pattern for privileged helpers +/// (NSXPCConnection.setCodeSigningRequirement, validated against the peer's audit token, so it is not +/// spoofable by PID reuse). /// -/// The daemon runs as root and listens on a Mach service that any local -/// process can look up. Before this, *who* connected was never checked — -/// safety rested entirely on each privileged call carrying an admin -/// AuthorizationRef. That still holds and is still enforced, but a -/// Developer ID build can do strictly better: refuse the connection outright -/// unless the peer is TetherKitNext.app signed by the same team. This is Apple's -/// documented pattern for privileged helpers -/// (NSXPCConnection.setCodeSigningRequirement, validated against the -/// peer's audit token, so it is not spoofable by PID reuse). -/// -/// ★ Why the requirement is derived at runtime ★ -/// -/// The Team ID is read from the running binary's own signature instead of -/// being compiled in, so a fork signed with a different Developer ID works -/// without source changes, and ad-hoc development builds (no Team ID) fall -/// back to the authorization-only model instead of locking themselves out. +/// The requirement is derived at runtime: the Team ID is read from the running binary's own signature +/// instead of being compiled in, so a fork signed with a different Developer ID works without source changes, +/// and ad-hoc development builds (no Team ID) fall back to the authorization-only model instead of locking +/// themselves out. public enum CodeSigning { - /// Team identifier of the running process's signature, or nil for ad-hoc / - /// unsigned builds. + /// Team identifier of the running process's signature, or nil for ad-hoc / unsigned builds. public static let currentTeamIdentifier: String? = { var code: SecCode? guard SecCodeCopySelf([], &code) == errSecSuccess, let code else { return nil } @@ -39,9 +30,8 @@ public enum CodeSigning { return dictionary[kSecCodeInfoTeamIdentifier as String] as? String }() - /// Requirement a peer must satisfy: signed by Apple-issued Developer ID - /// (or Apple Development) certificate of `teamIdentifier`, with the given - /// bundle identifier. + /// Requirement a peer must satisfy: signed by an Apple-issued Developer ID (or Apple Development) + /// certificate of `teamIdentifier`, with the given bundle identifier. public static func requirement(identifier: String, teamIdentifier: String) -> String { // `anchor apple generic` = chain ends in Apple's root CA; // `certificate leaf[subject.OU]` = the team the leaf cert was issued to. @@ -49,25 +39,23 @@ public enum CodeSigning { + "and certificate leaf[subject.OU] = \"\(teamIdentifier)\"" } - /// Requirement the daemon places on connecting clients, or nil when this - /// build is not team-signed (development). + /// Requirement the daemon places on connecting clients, or nil when this build is not team-signed (development). public static var clientRequirement: String? { currentTeamIdentifier.map { requirement(identifier: HelperConstants.appBundleIdentifier, teamIdentifier: $0) } } - /// Requirement the app places on the daemon it talks to, or nil when this - /// build is not team-signed. The daemon binary lives inside the app bundle - /// and carries its own identifier (the Mach service name). + /// Requirement the app places on the daemon it talks to, or nil when this build is not team-signed. The daemon + /// binary lives inside the app bundle and carries its own identifier (the Mach service name). public static var daemonRequirement: String? { currentTeamIdentifier.map { requirement(identifier: HelperConstants.machServiceName, teamIdentifier: $0) } } - /// Whether `requirement` compiles. Used by tests; a typo in the requirement - /// language would otherwise surface only as "every connection rejected". + /// Whether `requirement` compiles. Used by tests: a typo in the requirement language would otherwise show up + /// only as "every connection rejected". public static func isValidRequirement(_ requirement: String) -> Bool { var compiled: SecRequirement? return SecRequirementCreateWithString(requirement as CFString, [], &compiled) diff --git a/gui/Sources/TetherKitNextIPC/HelperConstants.swift b/gui/Sources/TetherKitNextIPC/HelperConstants.swift index 47141c6..3309dac 100644 --- a/gui/Sources/TetherKitNextIPC/HelperConstants.swift +++ b/gui/Sources/TetherKitNextIPC/HelperConstants.swift @@ -1,42 +1,38 @@ import Foundation -/// A set of constants fixed by agreement between the App and the helper. +/// Constants fixed by agreement between the app and the helper. /// -/// Made a separate file so that the question "when one name changes, where else must be changed in sync" has exactly one answer -- -/// these strings appear at once in the LaunchDaemon's plist, the install scripts, and the code on both ends, -/// and any one out of sync manifests as "cannot connect to the helper", with no useful error whatsoever. +/// One file so that "when a name changes, where else must it change" has one answer: these strings appear in +/// the LaunchDaemon plist and in the code on both ends, and any mismatch shows up as "cannot connect to the +/// helper" with no useful error. public enum HelperConstants { /// Mach service name and launchd label of the privileged daemon. /// - /// Must match `Label` / `MachServices` in - /// Resources/com.tetherkitnext.helperd.plist (embedded in the app at + /// Must match `Label` / `MachServices` in Resources/com.tetherkitnext.helperd.plist (embedded in the app at /// Contents/Library/LaunchDaemons and registered through SMAppService). /// - /// Deliberately different from the legacy `com.tetherkit.helper` label: - /// launchd refuses to register a second job under a label that is still - /// loaded, and the legacy daemon (installed by older builds via - /// AuthorizationExecuteWithPrivileges) may be. The new daemon removes the - /// legacy one on first start — see LegacyHelper. + /// It differs from the legacy `com.tetherkit.helper` label because launchd refuses to register a second job + /// under a label that is still loaded, and the legacy daemon may be. The daemon removes the legacy one on + /// first start (see LegacyHelper). public static let machServiceName = "com.tetherkitnext.helperd" - /// File name of the daemon plist inside Contents/Library/LaunchDaemons, - /// as SMAppService.daemon(plistName:) expects it. + /// File name of the daemon plist inside Contents/Library/LaunchDaemons, as `SMAppService.daemon(plistName:)` + /// expects it. public static let daemonPlistName = "com.tetherkitnext.helperd.plist" - /// Bundle identifier of TetherKitNext.app. The daemon only accepts XPC - /// connections from code signed with this identifier (and its own Team ID). + /// Bundle identifier of TetherKitNext.app. The daemon only accepts XPC connections from code signed with this + /// identifier (and its own Team ID). public static let appBundleIdentifier = "com.tetherkitnext.app" - /// Where the command-line tool is linked for terminal use. /usr/local/bin is - /// in the default PATH of every shell on macOS (/etc/paths) and survives - /// `sudo`, so a symlink there makes `tetherkitnext-cli` and + /// Where the command-line tool is linked for terminal use. /usr/local/bin is in the default PATH of every + /// shell on macOS (/etc/paths) and survives `sudo`, so a symlink there makes `tetherkitnext-cli` and /// `sudo tetherkitnext-cli` work without touching shell profiles. public static let commandLineToolLinkPath = "/usr/local/bin/tetherkitnext-cli" /// Location of the CLI inside the app bundle, relative to Contents/. public static let commandLineToolBundlePath = "MacOS/tetherkitnext-cli" - /// Legacy (pre-SMAppService) installation, removed on upgrade. + /// Legacy (pre-SMAppService) installation, removed on first start of the current daemon. public enum Legacy { public static let label = "com.tetherkit.helper" public static let executablePath = "/Library/PrivilegedHelperTools/com.tetherkit.helper" @@ -46,43 +42,41 @@ public enum HelperConstants { /// The authorization right required by privileged operations. /// - /// * Why use the system built-in system.privilege.admin rather than a custom right * - /// A custom right must first be written into the policy database with AuthorizationRightSet, which itself needs - /// administrator privileges -- hence the chicken-and-egg problem of "installing the authorization needs authorization". - /// The rule of system.privilege.admin is authenticate-admin, popping up exactly the - /// password / Touch ID dialog we want, and the semantics fit too: "this is an operation that needs administrator identity". + /// The built-in `system.privilege.admin` is used rather than a custom right: a custom right must be written + /// into the policy database with AuthorizationRightSet, which itself needs administrator privileges, so + /// installing the right would need authorization. The rule is authenticate-admin, which shows exactly the + /// password / Touch ID dialog we want, and its meaning ("needs administrator identity") fits. public static let privilegedRightName = "system.privilege.admin" - /// The revision number of the XPC interface. **Add one every time TetherKitNextHelperProtocol is changed.** + /// The revision number of the XPC interface. Increment it whenever TetherKitNextHelperProtocol changes. /// - /// Why it is needed: the helper is installed in a system directory, and if the helper is forgotten when upgrading the App, - /// the method signatures on the two ends will not match -- the symptom is a call hanging or a direct crash, with no hint that it is a version problem. - /// With this number, as soon as the App connects it can detect the mismatch and explicitly tell the user "please reinstall the privileged component". + /// A daemon that keeps running after the app is replaced can have different method signatures, which shows + /// up as a hanging call or a crash with no hint that it is a version problem. With this number the app + /// detects the mismatch on connect and tells the user to restart the background component. /// - /// Revision history: - /// 1 -- initial version - /// 2 -- the reply of privileged methods changed from (String?) to (String?, Bool), to distinguish authorization failures - /// 3 -- added setLanguage, so the helper's prompts and library logs follow the UI language - /// 4 —— SMAppService daemon (new label); adds setCommandLineToolInstalled - /// 5 —— privileged calls may carry an empty authorization: a team-signed - /// app has already confirmed the user with Touch ID / the login - /// password, and the daemon accepts it for admin users only + /// Revisions: + /// 1: initial version + /// 2: the reply of privileged methods changed from (String?) to (String?, Bool), to flag authorization failures + /// 3: added setLanguage, so the helper's prompts and library logs follow the UI language + /// 4: SMAppService daemon (new label); adds setCommandLineToolInstalled + /// 5: privileged calls may carry an empty authorization: a team-signed app has already confirmed the user + /// with Touch ID / the login password, and the daemon accepts that for admin users only public static let protocolRevision = 5 /// Encodes the revision number into the version string. /// - /// Deliberately reuses the existing `helperVersion` method rather than adding a new one -- adding a method is itself - /// a protocol change, and an old helper simply does not have it, which would bring us back to "mismatched and undetectable". - /// Only a method that even an old helper will certainly answer can reliably identify an old helper. + /// This reuses the `helperVersion` method instead of adding a new one: a new method is itself a protocol + /// change that an older daemon does not have, which would again leave a mismatch undetectable. Only a method + /// every daemon answers can identify an old one. /// - /// Format: `revision|version|build`. The trailing build description (which - /// starts with the git build ID) was added so builds that share a version - /// number can be told apart; older daemons omit it. + /// Format: `revision|version|build`. The build description (which starts with the git build ID) tells builds + /// apart that share a version number; older daemons omit it. public static func encodeVersion(_ version: String, build: String = "") -> String { build.isEmpty ? "\(protocolRevision)|\(version)" : "\(protocolRevision)|\(version)|\(build)" } - /// Parses the version string. The string returned by an old helper has no separator, in which case the revision number is recorded as 0. + /// Parses the version string. A daemon that predates the revision number returns a string without a + /// separator, and its revision is recorded as 0. public static func decodeVersion(_ encoded: String) -> (revision: Int, version: String, build: String) { guard let separator = encoded.firstIndex(of: "|"), @@ -108,15 +102,14 @@ public enum HelperConstants { /// Extracts the semantic version number from the library's version string: /// `"TetherKitNext 0.1.4 (C++23, macOS 13.3+)"` -> `"0.1.4"`. /// - /// * Why not compare the whole string directly * - /// Besides the version number, the string also carries the C++ standard and the minimum macOS version -- those are the **build configuration**, - /// not the version. If the whole string were the criterion, rebuilding once with different compile options would pop up a - /// false alarm of "component needs updating", and clicking it would change nothing for the user. + /// The whole string is not compared because it also carries the C++ standard and minimum macOS version, + /// which are build configuration, not version. Comparing it would raise a false "component needs updating" + /// alarm after any rebuild with different options, and restarting would change nothing for the user. /// - /// When it cannot be extracted (no dotted number in the string) fall back to the whole string: better a false alarm than a missed one -- a missed alarm - /// means the user keeps running the pre-upgrade library without knowing it. + /// When nothing can be extracted (no dotted number) the whole string is used: a false alarm is better than a + /// missed one, which leaves the user on the old library unknowingly. public static func semanticVersion(of text: String) -> String { - // There must be at least one dot, otherwise something like "C++23" would also be taken as a version number. + // Require at least one dot, otherwise something like "C++23" would also be taken as a version number. guard let range = text.range(of: "[0-9]+(\\.[0-9]+)+", options: .regularExpression) else { return text.trimmingCharacters(in: .whitespacesAndNewlines) } @@ -125,7 +118,7 @@ public enum HelperConstants { /// Timeout of XPC calls (seconds). /// - /// 30 seconds is used because the slowest call is the DHCP configuration: the library waits up to 10 seconds for a lease internally, - /// plus the USB handshake and NIC creation, leaving a 3x margin. + /// 30 seconds because the slowest call is the DHCP configuration: the library waits up to 10 seconds for a + /// lease, plus the USB handshake and interface creation, which leaves a 3x margin. public static let requestTimeout: TimeInterval = 30 } diff --git a/gui/Sources/TetherKitNextIPC/HelperProtocol.swift b/gui/Sources/TetherKitNextIPC/HelperProtocol.swift index 5617af2..30d09c7 100644 --- a/gui/Sources/TetherKitNextIPC/HelperProtocol.swift +++ b/gui/Sources/TetherKitNextIPC/HelperProtocol.swift @@ -1,28 +1,22 @@ import Foundation -/// The XPC interface through which the App calls the helper. +/// The XPC interface through which the app calls the helper. /// -/// * Which methods need authorization and which do not * +/// Every method with an `authorization` parameter requires it: the external form (32 bytes) of the credential +/// the app obtained through AuthorizationCopyRights, which the helper verifies really contains the required +/// right. Probe methods (helperVersion / status / queryNetwork / drainFeed) do not, because needing a +/// fingerprint just to ask "is the helper registered" would make "not registered" and "authorization failed" +/// indistinguishable. They are read-only and only expose the local network state. /// -/// Every one with an `authorization` parameter does -- it is the external form (32 bytes) of the credential the App obtained through -/// AuthorizationCopyRights, and the helper **verifies** that it really contains the required right. +/// Privileged replies are two values `(String?, Bool)`. The second says the failure is an authorization +/// problem: an expired authorization should show the dialog again and retry, while an operation failure +/// (say no device plugged in) will not change on retry. One merged message would force the app to match strings. /// -/// Probe-type methods (helperVersion / status / queryNetwork / drainFeed) deliberately **do not** -/// require authorization. The reason is: if even "is the helper installed" required popping up a fingerprint first, the user could not tell apart -/// the two entirely different failures "helper not installed" and "authorization did not pass". These methods are read-only, -/// and the information they leak is limited to the local machine's network state. -/// -/// * Why the reply of privileged methods is two values (String?, Bool) * -/// The second value means "this failure is an authorization problem". The App needs to tell the two cases apart: an expired authorization -/// should pop up the dialog again and retry, while if the operation itself failed (say no device plugged in), retrying any number of times is the same. -/// Mixed into one error message, the App could only match strings -- the most brittle kind of coupling. -/// -/// * Why errors use String? rather than NSError * -/// Passing NSError across XPC requires both ends to be able to deserialize its userInfo, and once an object that cannot be -/// encoded slips in, it is a runtime exception. And what we need to show the user is only one sentence of text anyway, -/// so passing a string is both simple and cannot fail. nil means success. +/// Errors are `String?` rather than NSError: passing NSError over XPC needs both ends to decode its +/// userInfo, and one non-encodable object is a runtime exception. The user only needs one sentence, so a +/// string is simple and cannot fail. nil means success. @objc public protocol TetherKitNextHelperProtocol { - /// Connectivity probe. **Does not require authorization** -- otherwise the two failures "not installed" and "not authorized" would be mixed together. + /// Connectivity probe. Does not require authorization, or "not registered" and "not authorized" would be mixed. func helperVersion(reply: @escaping @Sendable (String) -> Void) /// Preflight of the runtime environment (root status, feth's creation-time sysctls, MTU upper limit). @@ -30,52 +24,51 @@ import Foundation /// Enumerates RNDIS devices. /// - /// Enumerated by the helper rather than the App: the App side can also enumerate (no root needed), but once a session is running - /// the device is held exclusively by the helper, and the App reading string descriptors would only fail. Going through the helper uniformly - /// avoids this inconsistency. + /// Enumerated by the helper rather than the app: the app could enumerate too (no root needed), but while a + /// session runs the helper holds the device exclusively and the app reading string descriptors would only + /// fail. Going through the helper avoids that inconsistency. func listDevices(reply: @escaping @Sendable (Data?, String?) -> Void) - /// Starts an RNDIS session. **Needs authorization.** + /// Starts an RNDIS session. Needs authorization. func startSession(authorization: Data, configuration: Data, reply: @escaping @Sendable (String?, Bool) -> Void) - /// Stops the session and destroys the virtual NIC. **Needs authorization.** + /// Stops the session and destroys the virtual interface. Needs authorization. func stopSession(authorization: Data, reply: @escaping @Sendable (String?, Bool) -> Void) /// Takes a snapshot of the session state. func sessionStatus(reply: @escaping @Sendable (Data?, String?) -> Void) - /// Applies a connectivity method (DHCP / static IP / revoke) to the NIC. **Needs authorization.** + /// Applies a connectivity method (DHCP / static IP / revoke) to the interface. Needs authorization. /// - /// In DHCP mode this call blocks until a lease is obtained or it times out (the library's internal cap is 10 seconds), - /// so the helper side must not queue it on a queue that would serially block other requests. + /// In DHCP mode this call blocks until a lease is obtained or it times out (the library's cap is 10 seconds), + /// so the helper must not queue it where it would serially block other requests. func applyNetwork(authorization: Data, interface: String, configuration: Data, reply: @escaping @Sendable (String?, Bool) -> Void) - /// Reads back the IP state the NIC actually has in effect. + /// Reads back the IP state the interface actually has in effect. func queryNetwork(interface: String, reply: @escaping @Sendable (Data?, String?) -> Void) - /// Takes away the logs and hints accumulated on the helper side. + /// Drains the logs and notices accumulated on the helper side. func drainFeed(reply: @escaping @Sendable (Data?) -> Void) - /// Tells the helper which language to render the text it produces in. **Does not require authorization** -- it only affects - /// messages and cannot change any behavior. + /// Tells the helper which language to use for the text it produces. Does not require authorization: it only + /// affects messages. /// - /// Why this one must exist: the helper runs as root under launchd and cannot see the user's language - /// preference, yet the hints it produces ("session stopped") and libtetherkitnext's logs are both shown as-is - /// in the App's log card. Without synchronization the UI would be in one language and the logs in another. + /// The helper runs as root under launchd and cannot see the user's language preference, yet its hints + /// ("session stopped") and libtetherkitnext's logs are shown as-is in the log card, so without this the UI + /// and the logs would be in different languages. /// - /// The parameter is the rawValue of `Language` (`"chinese"` / `"english"`). A string is passed rather than - /// an integer: when a language is added in the future, an old helper receiving an unrecognized value simply ignores it, rather than - /// treating it as some enum value that happens to exist. + /// The parameter is the rawValue of `Language` (`"chinese"` / `"english"`). It is a string rather than an + /// integer so that a daemon receiving an unrecognized value from a newer app ignores it instead of mapping + /// it onto some enum case that happens to exist. func setLanguage(_ rawValue: String, reply: @escaping @Sendable () -> Void) - /// Link (`install == true`) or unlink the bundled command-line tool at - /// HelperConstants.commandLineToolLinkPath. **Requires authorization.** + /// Links (`install == true`) or unlinks the bundled command-line tool at + /// HelperConstants.commandLineToolLinkPath. Requires authorization. /// - /// The link target is never taken from the caller: the daemon derives it - /// from its own location inside the app bundle, so a client cannot use this - /// call to plant an arbitrary root-owned symlink. + /// The link target never comes from the caller: the daemon derives it from its own location inside the app + /// bundle, so a client cannot use this call to plant an arbitrary root-owned symlink. func setCommandLineToolInstalled(authorization: Data, install: Bool, reply: @escaping @Sendable (String?, Bool) -> Void) } diff --git a/gui/Sources/TetherKitNextIPC/Localization.swift b/gui/Sources/TetherKitNextIPC/Localization.swift index 5793055..0aad764 100644 --- a/gui/Sources/TetherKitNextIPC/Localization.swift +++ b/gui/Sources/TetherKitNextIPC/Localization.swift @@ -2,28 +2,18 @@ import Foundation // Language switching for UI messages. // -// * Why not Localizable.strings / String(localized:) * +// Messages are compiled into the binary rather than shipped as Localizable.strings / String(localized:). +// Those need .lproj directories in a bundle, but the code runs in two product forms: the bare executables +// from `swift build` (development) and the TetherKitNext.app, whose bundled daemon is also a bare +// executable that must produce user-visible text (hints, errors) without a resource bundle next to it. +// Compiled-in messages behave identically in all forms and cannot fail at runtime with a missing .lproj +// that turns everything English. It is the same model as the C++ side (include/tetherkitnext/common/messages.def). +// The cost is Xcode's string catalog editor, which this project (no Xcode project file) does not use. // -// The standard approach packs .lproj directories into the bundle, while this project has three mutually independent product forms: -// * the bare executable produced by `swift build` (run directly during development); -// * the TetherKitNext.app assembled by hand by Scripts/build-gui.sh; -// * the **bare** helper executable installed to /Library/PrivilegedHelperTools. -// The last one is fatal: the helper has no resource bundle beside it and should not have one, yet it too has to -// produce text shown to users (hints, errors). Going through a bundle, the helper could only ever output -// the development language, or the install script would have to move another set of resources over. -// -// Compiling the messages into the binary has none of these problems: all three forms behave identically, the install script needs no changes, -// and there is no runtime failure of the kind "installed on another machine, .lproj not found, so everything turns English". -// Incidentally, it is the same mental model as the C++ side (include/tetherkitnext/common/messages.def). -// -// The cost is not being able to use Xcode's string catalog editor -- and this project has no Xcode -// project file to begin with, so the cost is zero. -// -// * Adding a message * -// -// 1. Add a case to `L10nKey` in LocalizedStrings.swift; -// 2. Fill in every language (english, spanish, chinese, japanese, german, korean) in the per-language switches in the same file. -// The switch is exhaustive, so **omissions fail to compile** -- one notch stronger than the X-macro on the C++ side. +// To add a message: +// 1. Add a case to `L10nKey` in LocalizedStrings.swift. +// 2. Fill in every language (english, spanish, chinese, japanese, german, korean) in the per-language +// switches in the same file. The switches are exhaustive, so an omission fails to compile. /// The language preferences a user can choose. `system` means follow macOS. public enum LanguagePreference: String, CaseIterable, Codable, Sendable { @@ -57,9 +47,9 @@ public enum Language: String, CaseIterable, Codable, Sendable { /// Message lookup and language state. /// -/// The state is **process-wide**: logs and hints are produced from multiple threads, and making it thread-local would only make the output of a single -/// session appear in two languages. Reads far outnumber writes, and one small lock suffices -- each lookup costs one extra -/// uncontended lock acquisition, negligible relative to the cost of one SwiftUI render. +/// The state is process-wide: logs and hints are produced from several threads, and thread-local state would +/// show one session's output in two languages. Reads far outnumber writes, so one small lock suffices; each +/// lookup costs one uncontended lock acquisition, negligible next to a SwiftUI render. public enum L10n { private static let lock = NSLock() nonisolated(unsafe) private static var storedPreference: LanguagePreference = .system @@ -79,10 +69,10 @@ public enum L10n { return storedPreference } - /// Applies a preference, and returns the resolved language actually in effect. + /// Applies a preference and returns the resolved language actually in effect. /// - /// After getting the return value the caller **must also** push it to libtetherkitnext (see - /// `TetherKitNextLibrary.setLanguage`), otherwise the logs the library produces will be inconsistent with the UI language. + /// The caller must also push the result to libtetherkitnext (see `TetherKitNextLibrary.setLanguage`), + /// otherwise the logs the library produces will not match the UI language. @discardableResult public static func apply(_ preference: LanguagePreference) -> Language { let resolved = resolve(preference) @@ -93,7 +83,7 @@ public enum L10n { return resolved } - /// Directly applies a language (used by the helper daemon when informed by the client App). + /// Applies a language directly (used by the helper daemon when the client app tells it). @discardableResult public static func apply(_ language: Language) -> Language { lock.lock() @@ -135,7 +125,7 @@ public enum L10n { return key.translation(for: language) } - /// Gets the original text of a message in the **specified** language. Tests use it to check placeholders language by language. + /// Gets the original text of a message in the specified language. Tests use it to check placeholders per language. public static func text(_ key: L10nKey, in language: Language) -> String { return key.translation(for: language) } @@ -143,19 +133,19 @@ public enum L10n { /// Gets a message and substitutes arguments by the rules of `String(format:)`. /// -/// Made a global function rather than `L10n.text(...)`: there are over two hundred call sites, the vast majority in SwiftUI -/// view bodies, where every extra character crowds out the layout code that really matters. A name short as one letter is not -/// ambiguous either -- on seeing `L(` you know "there is a message to be translated here". +/// A global function rather than `L10n.text(...)`: there are over two hundred call sites, mostly in SwiftUI +/// view bodies, where every extra character crowds out the layout code. The one-letter name is not ambiguous: +/// `L(` means "a message to be translated is here". /// -/// Placeholders use printf style (`%@` string, `%d` integer, `%.1f` float). When a different word order is needed -/// use the positional form: `%1$@`, `%2$d`. +/// Placeholders use printf style (`%@` string, `%d` integer, `%.1f` float). When a different word order is +/// needed use the positional form: `%1$@`, `%2$d`. public func L(_ key: L10nKey, _ arguments: CVarArg...) -> String { let pattern = L10n.text(key) return arguments.isEmpty ? pattern : String(format: pattern, arguments: arguments) } -/// Same as above, but with a specified language. For the helper -- it renders in the language the App pushed over, rather than by -/// its own process state (a root process has no such thing as "user preferences"). +/// Same as above, but with a specified language. For the helper, which renders in the language the app pushed +/// rather than by its own process state (a root process has no user preferences). public func L(_ key: L10nKey, in language: Language, _ arguments: CVarArg...) -> String { let pattern = L10n.text(key, in: language) return arguments.isEmpty ? pattern : String(format: pattern, arguments: arguments) diff --git a/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift b/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift index ad096d1..7d32dac 100644 --- a/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift +++ b/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift @@ -2,22 +2,13 @@ import Foundation // All user-facing messages of the GUI and the helper. // -// Supported languages: -// - Spanish (es) -// - English (en) -// - Chinese (zh) -// - Japanese (ja) -// - German (de) -// - Korean (ko) -// Default to English when the system language is not available. +// Supported languages: Spanish (es), English (en), Chinese (zh), Japanese (ja), German (de), Korean (ko). +// English is the default when the system language is not available. // -// * Placeholder rules * -// -// Goes through `String(format:)`, printf style: `%@` string, `%ld` integer, `%.1f` float. -// The placeholders across all languages must correspond one to one (count, order, type). -// When a translation needs a different word order, switch to the positional form (`%1$@`, `%2$ld`). -// -// These rules are checked entry by entry by LocalizationTests in TetherKitNextIPCTests. +// Placeholder rules: messages go through `String(format:)`, printf style: `%@` string, `%ld` integer, +// `%.1f` float. The placeholders across all languages must correspond one to one (count, order, type). When +// a translation needs a different word order, use the positional form (`%1$@`, `%2$ld`). LocalizationTests +// in TetherKitNextIPCTests checks these rules entry by entry. /// The identifier of a message. public enum L10nKey: String, CaseIterable, Sendable { @@ -124,6 +115,36 @@ 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 statusConnectedLocal + case linkWaitingTitle + case linkWaitingBody + case linkLocalTitle + case linkLocalBody + case linkThisMac + case linkDevice + case linkPeerUnknown + case linkSelfAssignedNote + case linkSessionOnlyNote + case linkRetryAutomatic + case linkNoAddressTitle + case linkNoAddressBody + case linkUseAddress + case linkAddressPlaceholder + case linkNoAddressPhoneHint + case linkRouteAllSkipped + case helperRequestTimedOut case configureNetwork case setupTitle case setupSubtitle @@ -170,7 +191,6 @@ public enum L10nKey: String, CaseIterable, Sendable { case updateCheckFailed case updateDevBuild case uninstallWhileRunningWarning - case helperComponentVersion case helperVersionMismatch case helperUpdateBadge case checkingHelper @@ -243,6 +263,40 @@ public enum L10nKey: String, CaseIterable, Sendable { case interfaceLabel case interfaceCreating case connectDisabledHint + case dismiss + case sessionFailedTitle + case sessionFailureDisconnected + case sessionFailureAccessDenied + case sessionFailureBusy + case sessionFailureTimedOut + case sessionFailureDetails + case done + case layoutChooserTitle + case layoutChooserSubtitle + case layoutSimpleName + case layoutSimpleDescription + case layoutFullName + case layoutFullDescription + case layoutContinue + case layoutAnnouncementTitle + case layoutAnnouncementBody + case layoutTrySimple + case settingsLayoutSection + case menuUseSimpleView + case menuUseFullView + case simpleNoDevice + case simpleNoDeviceHint + case simpleDeviceReady + case simpleDeviceConnected + case simpleChooseDevice + case simpleUseAddress + case simpleNeedsAddress + case simpleOpenFull + case simpleAllSettings + case autoConnectToggle + case autoConnectHelp + case autoConnectWaiting + case powerButtonLabel case throughputSectionTitle case throughputLive case throughputDownstream @@ -262,6 +316,12 @@ public enum L10nKey: String, CaseIterable, Sendable { case upstreamDropped case kernelDrops case transmitBackpressure + case powerConnecting + case powerDisconnecting + case simpleNoAddressHint + case setupHelperPlain + case setupLearnMore + case autoConnectHelpDetail } extension L10nKey { @@ -382,6 +442,36 @@ 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 .statusConnectedLocal: return "Connected · local device" + case .linkWaitingTitle: return "Waiting for an address" + case .linkWaitingBody: return "The device hasn't given this Mac an address yet. Phones can take a few seconds; this updates by itself." + case .linkLocalTitle: return "Local device connected" + case .linkLocalBody: return "This device offers a private link, not an internet connection, so your Mac keeps using Wi-Fi or Ethernet for the internet. Apps that work with the device can reach it now." + case .linkThisMac: return "This Mac" + case .linkDevice: return "Device" + case .linkPeerUnknown: return "Not seen yet" + case .linkSelfAssignedNote: return "The device has no DHCP server, so both sides use automatic link-local addresses (169.254.x.x)." + case .linkSessionOnlyNote: return "Using an address set for this connection only. Your saved network settings are unchanged." + case .linkRetryAutomatic: return "Try automatic again" + case .linkNoAddressTitle: return "No address from the device" + case .linkNoAddressBody: return "The device hasn't handed out an address. If it uses a fixed address, give this Mac one in the same network. It applies to this connection only." + case .linkUseAddress: return "Use this address" + case .linkAddressPlaceholder: return "e.g. 192.168.1.10" + case .linkNoAddressPhoneHint: return "Connecting a phone? Check that USB tethering is on. This updates by itself if an address arrives later." + case .linkRouteAllSkipped: return "“Route all traffic through this interface” is not applied: this device has no router." + case .helperRequestTimedOut: return "it did not answer in time" 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." @@ -428,7 +518,6 @@ extension L10nKey { case .updateCheckFailed: return "The check could not be completed: %@" case .updateDevBuild: return "This is a development build with no version number, so there is nothing to compare against." case .uninstallWhileRunningWarning: return "The current connection will be dropped and the virtual interface destroyed." - case .helperComponentVersion: return "Helper · %@" case .helperVersionMismatch: return "Helper %1$@ · app %2$@" case .helperUpdateBadge: return "%@ available" case .checkingHelper: return "Checking the privileged helper…" @@ -478,7 +567,7 @@ extension L10nKey { case .quitTooltip: return "Quitting only closes the interface; an established connection keeps running." case .dnsEffectivenessTooltip: return "In manual mode, whether DNS takes effect is up to the system resolver, so trust what \"Currently effective\" reads back." case .ipModeLabel: return "Configure IPv4" - case .connectBeforeConfiguring: return "Connect a device before configuring the network" + case .connectBeforeConfiguring: return "Saved now, applied automatically when a device connects" case .dhcpHelp: return "The system asks the device for an address; DNS and routes are set up automatically" case .dhcpTooltip: return "Nearly every phone's USB tethering runs its own DHCP server, so this is the recommended choice. Applying it waits up to 10 seconds; a timeout usually means tethering is not enabled on the device." case .routerOptional: return "Optional" @@ -493,18 +582,52 @@ extension L10nKey { case .primaryDefaultRoute: return "Primary default route" case .notEffective: return "Not in effect" case .noAddressYet: return "%@ has no IP address yet. Pick a configuration and press Apply." - case .linkUp: return "Link up" - case .linkDown: return "Link down" + case .linkUp: return "Link active" + case .linkDown: return "Link inactive" case .transferPaused: return "Transfer paused" case .pendingDevice: return "Ready to connect: %@" - case .noRNDISDeviceDetected: return "No RNDIS device detected. Connect a phone with a data cable and turn on \"USB tethering\" on the phone." + case .noRNDISDeviceDetected: return "No phone or device found. Connect it with a data cable and turn on USB tethering on the phone." case .interfaceLabel: return "Interface" case .interfaceCreating: return "Creating…" case .connectDisabledHint: return "Connect a device with USB tethering switched on first" + case .dismiss: return "Dismiss" + case .sessionFailedTitle: return "Connection ended" + case .sessionFailureDisconnected: return "The device disconnected. Check the cable and that USB tethering is still on, then connect again." + case .sessionFailureAccessDenied: return "macOS did not allow access to the device. Another app or driver may be using it." + case .sessionFailureBusy: return "Another app is using the device. Quit it, then connect again." + case .sessionFailureTimedOut: return "The device stopped responding. Unplug it, plug it back in, then connect again." + case .sessionFailureDetails: return "Details" + case .done: return "Done" + case .layoutChooserTitle: return "Choose your look" + case .layoutChooserSubtitle: return "You can change this any time in Settings." + case .layoutSimpleName: return "Simple" + case .layoutSimpleDescription: return "One button to connect, with your device and status at a glance." + case .layoutFullName: return "Detailed" + case .layoutFullDescription: return "Every option: network settings, live charts, logs and tools." + case .layoutContinue: return "Continue" + case .layoutAnnouncementTitle: return "New: a simpler view" + case .layoutAnnouncementBody: return "TetherKitNext now has a simple view: one button to connect, with your device and status at a glance. Your current view stays as it is unless you switch, and you can change it any time in Settings." + case .layoutTrySimple: return "Try the simple view" + case .settingsLayoutSection: return "Layout" + case .menuUseSimpleView: return "Use Simple View" + case .menuUseFullView: return "Use Detailed View" + case .simpleNoDevice: return "No device" + case .simpleNoDeviceHint: return "Plug in your phone and turn on USB tethering" + case .simpleDeviceReady: return "Ready to connect" + case .simpleDeviceConnected: return "Connected" + case .simpleChooseDevice: return "Choose a device" + case .simpleUseAddress: return "Use %1$@ for this session" + case .simpleNeedsAddress: return "This device needs an address. Set one in the detailed view." + case .simpleOpenFull: return "Open detailed view" + case .simpleAllSettings: return "All settings" + case .autoConnectToggle: return "Connect automatically" + case .autoConnectHelp: return "Only when this Mac has no Wi-Fi or Ethernet, once per plug-in." + case .autoConnectWaiting: return "Not connecting automatically: this Mac is already on Wi-Fi or Ethernet." + case .powerButtonLabel: return "Connection" case .throughputSectionTitle: return "Throughput" case .throughputLive: return "Live" - case .throughputDownstream: return "Down (device -> Mac)" - case .throughputUpstream: return "Up (Mac -> device)" + case .throughputDownstream: return "Down (device → Mac)" + case .throughputUpstream: return "Up (Mac → device)" case .throughputDownstreamFPS: return "Down frame rate" case .throughputUpstreamFPS: return "Up frame rate" case .chartTime: return "Time" @@ -520,6 +643,12 @@ extension L10nKey { case .upstreamDropped: return "Up dropped" case .kernelDrops: return "Kernel drops" case .transmitBackpressure: return "TX backpressure" + case .powerConnecting: return "Connecting…" + case .powerDisconnecting: return "Disconnecting…" + case .simpleNoAddressHint: return "This device didn't give your Mac an address." + case .setupHelperPlain: return "TetherKitNext needs a small background helper to create the network connection. macOS asks you to allow it once." + case .setupLearnMore: return "Learn more" + case .autoConnectHelpDetail: return "Connects when a device is plugged in, but only if this Mac has no Wi-Fi or Ethernet connection. Once per plug-in: after you disconnect, it stays disconnected until you plug it in again." } } @@ -627,6 +756,36 @@ 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 .statusConnectedLocal: return "Conectado · dispositivo local" + case .linkWaitingTitle: return "Esperando una dirección" + case .linkWaitingBody: return "El dispositivo aún no ha asignado una dirección a este Mac. Los teléfonos pueden tardar unos segundos; esto se actualiza solo." + case .linkLocalTitle: return "Dispositivo local conectado" + case .linkLocalBody: return "Este dispositivo ofrece un enlace privado, no una conexión a internet, así que tu Mac sigue usando Wi-Fi o Ethernet para internet. Las apps que trabajan con el dispositivo ya pueden comunicarse con él." + case .linkThisMac: return "Este Mac" + case .linkDevice: return "Dispositivo" + case .linkPeerUnknown: return "Aún no detectado" + case .linkSelfAssignedNote: return "El dispositivo no tiene servidor DHCP, así que ambos lados usan direcciones automáticas de enlace local (169.254.x.x)." + case .linkSessionOnlyNote: return "Se usa una dirección solo para esta conexión. Tu configuración de red guardada no cambia." + case .linkRetryAutomatic: return "Probar automático de nuevo" + case .linkNoAddressTitle: return "El dispositivo no asignó dirección" + case .linkNoAddressBody: return "El dispositivo no ha asignado ninguna dirección. Si usa una dirección fija, da a este Mac una en la misma red. Solo se aplica a esta conexión." + case .linkUseAddress: return "Usar esta dirección" + case .linkAddressPlaceholder: return "p. ej. 192.168.1.10" + case .linkNoAddressPhoneHint: return "¿Conectas un teléfono? Comprueba que el anclaje USB esté activado. Esto se actualiza solo si la dirección llega más tarde." + case .linkRouteAllSkipped: return "«Enrutar todo el tráfico a través de esta interfaz» no se aplica: este dispositivo no tiene router." + case .helperRequestTimedOut: return "no respondió a tiempo" 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." @@ -673,7 +832,6 @@ extension L10nKey { case .updateCheckFailed: return "No se pudo completar la comprobación: %@" case .updateDevBuild: return "Esta es una compilación de desarrollo sin número de versión, por lo que no hay nada con qué comparar." case .uninstallWhileRunningWarning: return "La conexión actual se interrumpirá y la interfaz virtual será destruida." - case .helperComponentVersion: return "Asistente · %@" case .helperVersionMismatch: return "Asistente %1$@ · app %2$@" case .helperUpdateBadge: return "%@ disponible" case .checkingHelper: return "Comprobando el componente privilegiado…" @@ -723,7 +881,7 @@ extension L10nKey { case .quitTooltip: return "Salir solo cierra la interfaz; una conexión establecida seguirá funcionando." case .dnsEffectivenessTooltip: return "En modo manual, que el DNS surta efecto depende del resolución del sistema; confía en el valor de «Actualmente en vigor»." case .ipModeLabel: return "Configurar IPv4" - case .connectBeforeConfiguring: return "Conecta un dispositivo antes de configurar la red" + case .connectBeforeConfiguring: return "Se guarda ahora y se aplica automáticamente al conectar un dispositivo" case .dhcpHelp: return "El sistema solicita una dirección al dispositivo; el DNS y las rutas se configuran automáticamente" case .dhcpTooltip: return "Casi todas las conexiones compartidas por USB de teléfonos ejecutan su propio servidor DHCP, por lo que esta es la opción recomendada. La aplicación espera hasta 10 segundos; un tiempo de espera suele indicar que la conexión compartida no está activada en el dispositivo." case .routerOptional: return "Opcional" @@ -742,14 +900,48 @@ extension L10nKey { case .linkDown: return "Enlace inactivo" case .transferPaused: return "Transferencia en pausa" case .pendingDevice: return "Listo para conectar: %@" - case .noRNDISDeviceDetected: return "No se detectó ningún dispositivo RNDIS. Conecta un teléfono con un cable de datos y activa la «Conexión compartida por USB» en el teléfono." + case .noRNDISDeviceDetected: return "No se encontró ningún teléfono o dispositivo. Conéctalo con un cable de datos y activa la «Conexión compartida por USB» en el teléfono." case .interfaceLabel: return "Interfaz" case .interfaceCreating: return "Creando…" case .connectDisabledHint: return "Conecta primero un dispositivo con la conexión compartida por USB activada" + case .dismiss: return "Descartar" + case .sessionFailedTitle: return "La conexión terminó" + case .sessionFailureDisconnected: return "El dispositivo se desconectó. Revisa el cable y que la conexión compartida por USB siga activada, y vuelve a conectar." + case .sessionFailureAccessDenied: return "macOS no permitió el acceso al dispositivo. Puede que otra app o controlador lo esté usando." + case .sessionFailureBusy: return "Otra app está usando el dispositivo. Ciérrala y vuelve a conectar." + case .sessionFailureTimedOut: return "El dispositivo dejó de responder. Desconéctalo, vuelve a enchufarlo y conecta de nuevo." + case .sessionFailureDetails: return "Detalles" + case .done: return "Listo" + case .layoutChooserTitle: return "Elige tu vista" + case .layoutChooserSubtitle: return "Puedes cambiarla cuando quieras en Ajustes." + case .layoutSimpleName: return "Sencilla" + case .layoutSimpleDescription: return "Un botón para conectar, con tu dispositivo y el estado de un vistazo." + case .layoutFullName: return "Detallada" + case .layoutFullDescription: return "Todas las opciones: ajustes de red, gráficos en vivo, registros y herramientas." + case .layoutContinue: return "Continuar" + case .layoutAnnouncementTitle: return "Novedad: una vista más sencilla" + case .layoutAnnouncementBody: return "TetherKitNext ahora tiene una vista sencilla: un botón para conectar, con tu dispositivo y el estado de un vistazo. Tu vista actual se mantiene a menos que cambies, y puedes cambiarla cuando quieras en Ajustes." + case .layoutTrySimple: return "Probar la vista sencilla" + case .settingsLayoutSection: return "Vista" + case .menuUseSimpleView: return "Usar vista sencilla" + case .menuUseFullView: return "Usar vista detallada" + case .simpleNoDevice: return "Sin dispositivo" + case .simpleNoDeviceHint: return "Conecta tu teléfono y activa la conexión compartida por USB" + case .simpleDeviceReady: return "Listo para conectar" + case .simpleDeviceConnected: return "Conectado" + case .simpleChooseDevice: return "Elegir un dispositivo" + case .simpleUseAddress: return "Usar %1$@ en esta sesión" + case .simpleNeedsAddress: return "Este dispositivo necesita una dirección. Configúrala en la vista detallada." + case .simpleOpenFull: return "Abrir vista detallada" + case .simpleAllSettings: return "Todos los ajustes" + case .autoConnectToggle: return "Conectar automáticamente" + case .autoConnectHelp: return "Solo si este Mac no tiene Wi-Fi ni Ethernet, una vez por conexión." + case .autoConnectWaiting: return "No se conecta automáticamente: este Mac ya tiene Wi-Fi o Ethernet." + case .powerButtonLabel: return "Conexión" case .throughputSectionTitle: return "Rendimiento" case .throughputLive: return "En vivo" - case .throughputDownstream: return "Bajada (dispositivo -> Mac)" - case .throughputUpstream: return "Subida (Mac -> dispositivo)" + case .throughputDownstream: return "Bajada (dispositivo → Mac)" + case .throughputUpstream: return "Subida (Mac → dispositivo)" case .throughputDownstreamFPS: return "Tasa de tramas de bajada" case .throughputUpstreamFPS: return "Tasa de tramas de subida" case .chartTime: return "Tiempo" @@ -765,6 +957,12 @@ extension L10nKey { case .upstreamDropped: return "Subida descartada" case .kernelDrops: return "Descartes de kernel" case .transmitBackpressure: return "Retropresión TX" + case .powerConnecting: return "Conectando…" + case .powerDisconnecting: return "Desconectando…" + case .simpleNoAddressHint: return "Este dispositivo no le dio una dirección a tu Mac." + case .setupHelperPlain: return "TetherKitNext necesita un pequeño ayudante en segundo plano para crear la conexión de red. macOS te pedirá que lo permitas una vez." + case .setupLearnMore: return "Más información" + case .autoConnectHelpDetail: return "Conecta cuando enchufas un dispositivo, pero solo si este Mac no tiene conexión Wi-Fi ni Ethernet. Una vez por conexión: si desconectas, sigue desconectado hasta que lo vuelvas a enchufar." } } @@ -872,6 +1070,36 @@ 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 .statusConnectedLocal: return "已连接 · 本地设备" + case .linkWaitingTitle: return "正在等待地址" + case .linkWaitingBody: return "设备还没有给这台 Mac 分配地址。手机可能需要几秒钟,此处会自动更新。" + case .linkLocalTitle: return "已连接本地设备" + case .linkLocalBody: return "该设备提供的是一条私有链路,而不是互联网连接,因此 Mac 仍通过 Wi-Fi 或以太网上网。与该设备配合使用的应用现在已可访问它。" + case .linkThisMac: return "这台 Mac" + case .linkDevice: return "设备" + case .linkPeerUnknown: return "尚未发现" + case .linkSelfAssignedNote: return "设备没有 DHCP 服务器,因此双方使用自动分配的链路本地地址(169.254.x.x)。" + case .linkSessionOnlyNote: return "正在使用仅限本次连接的地址,已保存的网络设置不会改变。" + case .linkRetryAutomatic: return "重新尝试自动配置" + case .linkNoAddressTitle: return "设备未分配地址" + case .linkNoAddressBody: return "设备没有分配地址。如果它使用固定地址,请给这台 Mac 设置一个同网段的地址。仅对本次连接生效。" + case .linkUseAddress: return "使用此地址" + case .linkAddressPlaceholder: return "例如 192.168.1.10" + case .linkNoAddressPhoneHint: return "连接的是手机?请确认已开启 USB 网络共享。如果稍后获得地址,此处会自动更新。" + case .linkRouteAllSkipped: return "“让所有流量默认走这张网卡”未生效:该设备没有网关。" + case .helperRequestTimedOut: return "它没有及时响应" case .configureNetwork: return "配置…" case .setupTitle: return "欢迎使用 TetherKitNext" case .setupSubtitle: return "只需几步,就能把 Android 手机的 USB 网络共享变成 Mac 上的一张网卡。" @@ -918,7 +1146,6 @@ extension L10nKey { case .updateCheckFailed: return "无法完成检查:%@" case .updateDevBuild: return "这是开发构建(没有版本号),无从比较。" case .uninstallWhileRunningWarning: return "当前连接会被断开、虚拟网卡销毁。" - case .helperComponentVersion: return "特权组件 · %@" case .helperVersionMismatch: return "特权组件 %1$@ · App %2$@" case .helperUpdateBadge: return "有新版 %@" case .checkingHelper: return "正在检查特权组件……" @@ -968,7 +1195,7 @@ extension L10nKey { case .quitTooltip: return "退出只是关闭界面,已建立的连接会继续运行。" case .dnsEffectivenessTooltip: return "静态模式下 DNS 是否生效取决于系统的解析器管理,请以「当前生效」里的回读结果为准。" case .ipModeLabel: return "上网方式" - case .connectBeforeConfiguring: return "连接设备后才能配置网络" + case .connectBeforeConfiguring: return "设置已保存,设备连接后自动应用" case .dhcpHelp: return "由系统向设备申请地址,DNS 与路由都自动配好" case .dhcpTooltip: return "绝大多数手机的 USB 网络共享都自带 DHCP 服务器,这是推荐选项。应用后最多等待 10 秒;超时通常意味着设备侧没有开启网络共享。" case .routerOptional: return "可留空" @@ -987,10 +1214,44 @@ extension L10nKey { case .linkDown: return "链路未连通" case .transferPaused: return "已暂停搬运" case .pendingDevice: return "待连接:%@" - case .noRNDISDeviceDetected: return "没有检测到 RNDIS 设备。请用数据线连接手机,并在手机上打开「USB 网络共享」。" + case .noRNDISDeviceDetected: return "没有找到手机或设备。请用数据线连接,并在手机上打开「USB 网络共享」。" case .interfaceLabel: return "网卡" case .interfaceCreating: return "创建中…" case .connectDisabledHint: return "先连接一台开启了 USB 网络共享的设备" + case .dismiss: return "关闭" + case .sessionFailedTitle: return "连接已结束" + case .sessionFailureDisconnected: return "设备已断开。请检查数据线,并确认 USB 网络共享仍处于开启状态,然后重新连接。" + case .sessionFailureAccessDenied: return "macOS 未允许访问该设备,可能有其他应用或驱动正在使用它。" + case .sessionFailureBusy: return "另一个应用正在使用该设备。请退出该应用后重新连接。" + case .sessionFailureTimedOut: return "设备已停止响应。请拔下后重新插入,然后再次连接。" + case .sessionFailureDetails: return "详细信息" + case .done: return "完成" + case .layoutChooserTitle: return "选择界面样式" + case .layoutChooserSubtitle: return "之后可随时在设置中更改。" + case .layoutSimpleName: return "简洁" + case .layoutSimpleDescription: return "一个按钮即可连接,设备和状态一目了然。" + case .layoutFullName: return "详细" + case .layoutFullDescription: return "全部选项:网络设置、实时图表、日志和工具。" + case .layoutContinue: return "继续" + case .layoutAnnouncementTitle: return "新功能:更简洁的界面" + case .layoutAnnouncementBody: return "TetherKitNext 现在提供简洁界面:一个按钮即可连接,设备和状态一目了然。除非你切换,当前界面保持不变;之后也可随时在设置中更改。" + case .layoutTrySimple: return "试用简洁界面" + case .settingsLayoutSection: return "界面样式" + case .menuUseSimpleView: return "使用简洁界面" + case .menuUseFullView: return "使用详细界面" + case .simpleNoDevice: return "没有设备" + case .simpleNoDeviceHint: return "插入手机并开启 USB 网络共享" + case .simpleDeviceReady: return "可以连接" + case .simpleDeviceConnected: return "已连接" + case .simpleChooseDevice: return "选择设备" + case .simpleUseAddress: return "本次会话使用 %1$@" + case .simpleNeedsAddress: return "该设备需要一个地址,请在详细界面中设置。" + case .simpleOpenFull: return "打开详细界面" + case .simpleAllSettings: return "全部设置" + case .autoConnectToggle: return "自动连接" + case .autoConnectHelp: return "仅在本 Mac 没有 Wi-Fi 或以太网时,每次插入只连接一次。" + case .autoConnectWaiting: return "未自动连接:本 Mac 已连接 Wi-Fi 或以太网。" + case .powerButtonLabel: return "连接" case .throughputSectionTitle: return "吞吐" case .throughputLive: return "实时" case .throughputDownstream: return "下行(设备 → 本机)" @@ -1010,6 +1271,12 @@ extension L10nKey { case .upstreamDropped: return "上行丢弃" case .kernelDrops: return "内核丢包" case .transmitBackpressure: return "发送背压" + case .powerConnecting: return "正在连接…" + case .powerDisconnecting: return "正在断开…" + case .simpleNoAddressHint: return "该设备没有给你的 Mac 分配地址。" + case .setupHelperPlain: return "TetherKitNext 需要一个小型后台组件来创建网络连接。macOS 会请你允许它一次。" + case .setupLearnMore: return "了解更多" + case .autoConnectHelpDetail: return "插入设备时自动连接,但仅在本 Mac 没有 Wi-Fi 或以太网连接时。每次插入只连接一次:断开后会保持断开,直到重新插入。" } } @@ -1117,6 +1384,36 @@ 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 .statusConnectedLocal: return "接続済み · ローカルデバイス" + case .linkWaitingTitle: return "アドレスを待っています" + case .linkWaitingBody: return "デバイスはまだこの Mac にアドレスを割り当てていません。電話では数秒かかることがあります。この表示は自動で更新されます。" + case .linkLocalTitle: return "ローカルデバイスに接続しました" + case .linkLocalBody: return "このデバイスはインターネット接続ではなく専用のリンクを提供するため、Mac は引き続き Wi-Fi または Ethernet でインターネットに接続します。デバイス用のアプリから今すぐアクセスできます。" + case .linkThisMac: return "この Mac" + case .linkDevice: return "デバイス" + case .linkPeerUnknown: return "まだ検出されていません" + case .linkSelfAssignedNote: return "デバイスに DHCP サーバがないため、双方が自動のリンクローカルアドレス(169.254.x.x)を使用しています。" + case .linkSessionOnlyNote: return "この接続だけに設定したアドレスを使用しています。保存済みのネットワーク設定は変更されません。" + case .linkRetryAutomatic: return "自動設定を再試行" + case .linkNoAddressTitle: return "デバイスからアドレスが割り当てられていません" + case .linkNoAddressBody: return "デバイスはアドレスを割り当てていません。固定アドレスを使うデバイスなら、同じネットワーク内のアドレスをこの Mac に設定してください。この接続にのみ適用されます。" + case .linkUseAddress: return "このアドレスを使用" + case .linkAddressPlaceholder: return "例: 192.168.1.10" + case .linkNoAddressPhoneHint: return "電話を接続していますか?USB テザリングがオンになっているか確認してください。後からアドレスが届けば自動で更新されます。" + case .linkRouteAllSkipped: return "「すべての通信をこのインターフェース経由にする」は適用されません:このデバイスにはルータがありません。" + case .helperRequestTimedOut: return "時間内に応答がありませんでした" case .configureNetwork: return "設定…" case .setupTitle: return "TetherKitNext へようこそ" case .setupSubtitle: return "いくつかのステップで、Android スマホの USB テザリングを Mac のネットワークインターフェースに変換できます。" @@ -1163,7 +1460,6 @@ extension L10nKey { case .updateCheckFailed: return "確認を完了できませんでした: %@" case .updateDevBuild: return "これはバージョン番号のない開発用ビルドのため、比較対象がありません。" case .uninstallWhileRunningWarning: return "現在の接続は切断され、仮想インターフェースは破棄されます。" - case .helperComponentVersion: return "ヘルパー · %@" case .helperVersionMismatch: return "ヘルパー %1$@ · アプリ %2$@" case .helperUpdateBadge: return "%@ が利用可能" case .checkingHelper: return "特権ヘルパーを確認中…" @@ -1213,7 +1509,7 @@ extension L10nKey { case .quitTooltip: return "終了してもインターフェースが閉じるだけで、確立された接続は継続します。" case .dnsEffectivenessTooltip: return "静的モードでは DNS が有効になるかどうかはシステムのリゾルバーに依存するため、「現在有効」に表示される値を参照してください。" case .ipModeLabel: return "IPv4 の設定" - case .connectBeforeConfiguring: return "ネットワークを設定する前にデバイスを接続してください" + case .connectBeforeConfiguring: return "設定は保存され、デバイスの接続時に自動で適用されます" case .dhcpHelp: return "システムがデバイスにアドレスを要求し、DNS とルートが自動的に設定されます" case .dhcpTooltip: return "ほぼすべてのスマホの USB テザリングは独自の DHCP サーバーを備えているため、これが推奨設定です。適用には最大 10 秒待機します。タイムアウトは通常、端末側でテザリングが無効であることを意味します。" case .routerOptional: return "任意" @@ -1228,18 +1524,52 @@ extension L10nKey { case .primaryDefaultRoute: return "プライマリデフォルトルート" case .notEffective: return "無効" case .noAddressYet: return "%@ にはまだ IP アドレスがありません。設定を選択して「適用」をクリックしてください。" - case .linkUp: return "リンクアップ" - case .linkDown: return "リンクダウン" + case .linkUp: return "リンク有効" + case .linkDown: return "リンク無効" case .transferPaused: return "転送一時停止中" case .pendingDevice: return "接続待機中: %@" - case .noRNDISDeviceDetected: return "RNDIS デバイスが検出されませんでした。データ通信対応ケーブルでスマホを接続し、スマホで「USB テザリング」をオンにしてください。" + case .noRNDISDeviceDetected: return "スマホやデバイスが見つかりません。データ通信対応ケーブルで接続し、スマホで「USB テザリング」をオンにしてください。" case .interfaceLabel: return "インターフェース" case .interfaceCreating: return "作成中…" case .connectDisabledHint: return "先に USB テザリングをオンにしたデバイスを接続してください" + case .dismiss: return "閉じる" + case .sessionFailedTitle: return "接続が終了しました" + case .sessionFailureDisconnected: return "デバイスが切断されました。ケーブルと USB テザリングがオンのままか確認してから、再接続してください。" + case .sessionFailureAccessDenied: return "macOS がデバイスへのアクセスを許可しませんでした。別のアプリやドライバが使用している可能性があります。" + case .sessionFailureBusy: return "別のアプリがデバイスを使用しています。そのアプリを終了してから再接続してください。" + case .sessionFailureTimedOut: return "デバイスが応答しなくなりました。抜き差ししてから再接続してください。" + case .sessionFailureDetails: return "詳細" + case .done: return "完了" + case .layoutChooserTitle: return "表示スタイルを選択" + case .layoutChooserSubtitle: return "設定でいつでも変更できます。" + case .layoutSimpleName: return "シンプル" + case .layoutSimpleDescription: return "ボタンひとつで接続。デバイスと状態がひと目でわかります。" + case .layoutFullName: return "詳細" + case .layoutFullDescription: return "すべてのオプション:ネットワーク設定、リアルタイムのグラフ、ログ、ツール。" + case .layoutContinue: return "続ける" + case .layoutAnnouncementTitle: return "新機能:シンプルな表示" + case .layoutAnnouncementBody: return "TetherKitNext にシンプルな表示が加わりました。ボタンひとつで接続でき、デバイスと状態がひと目でわかります。切り替えない限り現在の表示はそのままで、設定でいつでも変更できます。" + case .layoutTrySimple: return "シンプルな表示を試す" + case .settingsLayoutSection: return "表示スタイル" + case .menuUseSimpleView: return "シンプル表示を使用" + case .menuUseFullView: return "詳細表示を使用" + case .simpleNoDevice: return "デバイスなし" + case .simpleNoDeviceHint: return "スマートフォンを接続して USB テザリングをオンにしてください" + case .simpleDeviceReady: return "接続できます" + case .simpleDeviceConnected: return "接続済み" + case .simpleChooseDevice: return "デバイスを選択" + case .simpleUseAddress: return "このセッションで %1$@ を使用" + case .simpleNeedsAddress: return "このデバイスにはアドレスが必要です。詳細表示で設定してください。" + case .simpleOpenFull: return "詳細表示を開く" + case .simpleAllSettings: return "すべての設定" + case .autoConnectToggle: return "自動的に接続" + case .autoConnectHelp: return "この Mac に Wi-Fi も Ethernet もない場合のみ、接続ごとに 1 回。" + case .autoConnectWaiting: return "自動接続していません:この Mac はすでに Wi-Fi または Ethernet に接続しています。" + case .powerButtonLabel: return "接続" case .throughputSectionTitle: return "スループット" case .throughputLive: return "リアルタイム" - case .throughputDownstream: return "下り (デバイス -> Mac)" - case .throughputUpstream: return "上り (Mac -> デバイス)" + case .throughputDownstream: return "下り (デバイス → Mac)" + case .throughputUpstream: return "上り (Mac → デバイス)" case .throughputDownstreamFPS: return "下りフレームレート" case .throughputUpstreamFPS: return "上りフレームレート" case .chartTime: return "時間" @@ -1255,6 +1585,12 @@ extension L10nKey { case .upstreamDropped: return "上りドロップ" case .kernelDrops: return "カーネルドロップ" case .transmitBackpressure: return "送信バックプレッシャー" + case .powerConnecting: return "接続中…" + case .powerDisconnecting: return "切断中…" + case .simpleNoAddressHint: return "このデバイスは Mac にアドレスを割り当てませんでした。" + case .setupHelperPlain: return "TetherKitNext はネットワーク接続を作成するために、小さなバックグラウンドコンポーネントを必要とします。macOS が一度だけ許可を求めます。" + case .setupLearnMore: return "詳しく見る" + case .autoConnectHelpDetail: return "デバイスを接続したときに自動で接続します。ただし、この Mac に Wi-Fi または Ethernet の接続がない場合のみです。接続ごとに 1 回:切断すると、差し直すまで切断されたままです。" } } @@ -1362,6 +1698,36 @@ 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 .statusConnectedLocal: return "Verbunden · lokales Gerät" + case .linkWaitingTitle: return "Warte auf eine Adresse" + case .linkWaitingBody: return "Das Gerät hat diesem Mac noch keine Adresse zugewiesen. Telefone brauchen manchmal ein paar Sekunden; die Anzeige aktualisiert sich von selbst." + case .linkLocalTitle: return "Lokales Gerät verbunden" + case .linkLocalBody: return "Dieses Gerät bietet eine private Verbindung, keinen Internetzugang. Dein Mac nutzt für das Internet weiterhin WLAN oder Ethernet. Apps für das Gerät können es jetzt erreichen." + case .linkThisMac: return "Dieser Mac" + case .linkDevice: return "Gerät" + case .linkPeerUnknown: return "Noch nicht erkannt" + case .linkSelfAssignedNote: return "Das Gerät hat keinen DHCP-Server, daher verwenden beide Seiten automatische Link-Local-Adressen (169.254.x.x)." + case .linkSessionOnlyNote: return "Es wird eine nur für diese Verbindung gesetzte Adresse verwendet. Deine gespeicherten Netzwerkeinstellungen bleiben unverändert." + case .linkRetryAutomatic: return "Automatisch erneut versuchen" + case .linkNoAddressTitle: return "Keine Adresse vom Gerät" + case .linkNoAddressBody: return "Das Gerät vergibt keine Adresse. Nutzt es eine feste Adresse, gib diesem Mac eine im selben Netz. Das gilt nur für diese Verbindung." + case .linkUseAddress: return "Diese Adresse verwenden" + case .linkAddressPlaceholder: return "z. B. 192.168.1.10" + case .linkNoAddressPhoneHint: return "Verbindest du ein Telefon? Prüfe, ob USB-Tethering eingeschaltet ist. Kommt die Adresse später, aktualisiert sich die Anzeige von selbst." + case .linkRouteAllSkipped: return "„Gesamten Datenverkehr über diese Schnittstelle leiten“ wird nicht angewendet: Dieses Gerät hat keinen Router." + case .helperRequestTimedOut: return "er hat nicht rechtzeitig geantwortet" 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." @@ -1408,7 +1774,6 @@ extension L10nKey { case .updateCheckFailed: return "Prüfung konnte nicht abgeschlossen werden: %@" case .updateDevBuild: return "Dies ist ein Entwicklungs-Build ohne Versionsnummer; es gibt nichts zum Vergleichen." case .uninstallWhileRunningWarning: return "Die aktuelle Verbindung wird getrennt und die virtuelle Schnittstelle zerstört." - case .helperComponentVersion: return "Helfer · %@" case .helperVersionMismatch: return "Helfer %1$@ · App %2$@" case .helperUpdateBadge: return "%@ verfügbar" case .checkingHelper: return "Privilegierter Helfer wird überprüft…" @@ -1458,7 +1823,7 @@ extension L10nKey { case .quitTooltip: return "Beenden schließt nur die Oberfläche; eine bestehende Verbindung bleibt aktiv." case .dnsEffectivenessTooltip: return "Im manuellen Modus hängt die DNS-Wirksamkeit vom System-Resolver ab; maßgeblich ist die Rückmeldung unter „Zurzeit aktiv“." case .ipModeLabel: return "IPv4 konfigurieren" - case .connectBeforeConfiguring: return "Vor der Netzwerkkonfiguration ein Gerät verbinden" + case .connectBeforeConfiguring: return "Wird gespeichert und beim Verbinden eines Geräts automatisch angewendet" case .dhcpHelp: return "Das System fordert eine Adresse vom Gerät an; DNS und Routen werden automatisch eingerichtet" case .dhcpTooltip: return "Nahezu jedes Telefon-USB-Tethering betreibt einen eigenen DHCP-Server; dies ist die empfohlene Wahl. Die Anwendung wartet bis zu 10 Sekunden; ein Timeout bedeutet meist, dass Tethering am Gerät nicht aktiv ist." case .routerOptional: return "Optional" @@ -1477,14 +1842,48 @@ extension L10nKey { case .linkDown: return "Verbindung getrennt" case .transferPaused: return "Übertragung pausiert" case .pendingDevice: return "Bereit zum Verbinden: %@" - case .noRNDISDeviceDetected: return "Kein RNDIS-Gerät erkannt. Telefon mit Datenkabel verbinden und „USB-Tethering“ am Telefon aktivieren." + case .noRNDISDeviceDetected: return "Kein Telefon oder Gerät gefunden. Mit einem Datenkabel verbinden und „USB-Tethering“ am Telefon aktivieren." case .interfaceLabel: return "Schnittstelle" case .interfaceCreating: return "Wird erstellt…" case .connectDisabledHint: return "Verbinden Sie zuerst ein Gerät mit aktivem USB-Tethering" + case .dismiss: return "Schließen" + case .sessionFailedTitle: return "Verbindung beendet" + case .sessionFailureDisconnected: return "Das Gerät wurde getrennt. Prüfen Sie das Kabel und ob USB-Tethering noch aktiv ist, und verbinden Sie erneut." + case .sessionFailureAccessDenied: return "macOS hat den Zugriff auf das Gerät verweigert. Möglicherweise verwendet es eine andere App oder ein anderer Treiber." + case .sessionFailureBusy: return "Eine andere App verwendet das Gerät. Beenden Sie sie und verbinden Sie erneut." + case .sessionFailureTimedOut: return "Das Gerät reagiert nicht mehr. Trennen Sie es, schließen Sie es wieder an und verbinden Sie erneut." + case .sessionFailureDetails: return "Details" + case .done: return "Fertig" + case .layoutChooserTitle: return "Ansicht auswählen" + case .layoutChooserSubtitle: return "Sie können das jederzeit in den Einstellungen ändern." + case .layoutSimpleName: return "Einfach" + case .layoutSimpleDescription: return "Eine Taste zum Verbinden, Gerät und Status auf einen Blick." + case .layoutFullName: return "Detailliert" + case .layoutFullDescription: return "Alle Optionen: Netzwerkeinstellungen, Live-Diagramme, Protokolle und Werkzeuge." + case .layoutContinue: return "Weiter" + case .layoutAnnouncementTitle: return "Neu: eine einfachere Ansicht" + case .layoutAnnouncementBody: return "TetherKitNext hat jetzt eine einfache Ansicht: eine Taste zum Verbinden, Gerät und Status auf einen Blick. Ihre aktuelle Ansicht bleibt, solange Sie nicht wechseln, und Sie können sie jederzeit in den Einstellungen ändern." + case .layoutTrySimple: return "Einfache Ansicht ausprobieren" + case .settingsLayoutSection: return "Ansicht" + case .menuUseSimpleView: return "Einfache Ansicht verwenden" + case .menuUseFullView: return "Detaillierte Ansicht verwenden" + case .simpleNoDevice: return "Kein Gerät" + case .simpleNoDeviceHint: return "Schließen Sie Ihr Telefon an und aktivieren Sie USB-Tethering" + case .simpleDeviceReady: return "Bereit zum Verbinden" + case .simpleDeviceConnected: return "Verbunden" + case .simpleChooseDevice: return "Gerät auswählen" + case .simpleUseAddress: return "%1$@ für diese Sitzung verwenden" + case .simpleNeedsAddress: return "Dieses Gerät braucht eine Adresse. Legen Sie sie in der detaillierten Ansicht fest." + case .simpleOpenFull: return "Detaillierte Ansicht öffnen" + case .simpleAllSettings: return "Alle Einstellungen" + case .autoConnectToggle: return "Automatisch verbinden" + case .autoConnectHelp: return "Nur wenn dieser Mac kein WLAN und kein Ethernet hat, einmal pro Anschließen." + case .autoConnectWaiting: return "Keine automatische Verbindung: Dieser Mac ist bereits über WLAN oder Ethernet verbunden." + case .powerButtonLabel: return "Verbindung" case .throughputSectionTitle: return "Durchsatz" case .throughputLive: return "Echtzeit" - case .throughputDownstream: return "Down (Gerät -> Mac)" - case .throughputUpstream: return "Up (Mac -> Gerät)" + case .throughputDownstream: return "Down (Gerät → Mac)" + case .throughputUpstream: return "Up (Mac → Gerät)" case .throughputDownstreamFPS: return "Down-Framerate" case .throughputUpstreamFPS: return "Up-Framerate" case .chartTime: return "Zeit" @@ -1500,6 +1899,12 @@ extension L10nKey { case .upstreamDropped: return "Up verworfen" case .kernelDrops: return "Kernel-Verwürfe" case .transmitBackpressure: return "TX-Gegendruck" + case .powerConnecting: return "Verbinden…" + case .powerDisconnecting: return "Trennen…" + case .simpleNoAddressHint: return "Dieses Gerät hat Ihrem Mac keine Adresse zugewiesen." + case .setupHelperPlain: return "TetherKitNext benötigt eine kleine Hintergrundkomponente, um die Netzwerkverbindung herzustellen. macOS fordert Sie einmalig zur Freigabe auf." + case .setupLearnMore: return "Mehr erfahren" + case .autoConnectHelpDetail: return "Verbindet, wenn ein Gerät angeschlossen wird, aber nur, wenn dieser Mac keine WLAN- oder Ethernet-Verbindung hat. Einmal pro Anschließen: Nach dem Trennen bleibt es getrennt, bis Sie es erneut anschließen." } } @@ -1607,6 +2012,36 @@ 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 .statusConnectedLocal: return "연결됨 · 로컬 기기" + case .linkWaitingTitle: return "주소를 기다리는 중" + case .linkWaitingBody: return "기기가 아직 이 Mac에 주소를 할당하지 않았습니다. 휴대폰은 몇 초 걸릴 수 있으며, 이 화면은 자동으로 업데이트됩니다." + case .linkLocalTitle: return "로컬 기기 연결됨" + case .linkLocalBody: return "이 기기는 인터넷 연결이 아닌 전용 링크를 제공하므로 Mac은 계속 Wi-Fi 또는 이더넷으로 인터넷을 사용합니다. 기기용 앱에서 지금 기기에 접근할 수 있습니다." + case .linkThisMac: return "이 Mac" + case .linkDevice: return "기기" + case .linkPeerUnknown: return "아직 감지되지 않음" + case .linkSelfAssignedNote: return "기기에 DHCP 서버가 없어 양쪽 모두 자동 링크 로컬 주소(169.254.x.x)를 사용합니다." + case .linkSessionOnlyNote: return "이번 연결에만 적용되는 주소를 사용 중입니다. 저장된 네트워크 설정은 바뀌지 않습니다." + case .linkRetryAutomatic: return "자동 설정 다시 시도" + case .linkNoAddressTitle: return "기기에서 주소를 받지 못함" + case .linkNoAddressBody: return "기기가 주소를 할당하지 않았습니다. 기기가 고정 주소를 사용한다면 같은 네트워크의 주소를 이 Mac에 지정하세요. 이번 연결에만 적용됩니다." + case .linkUseAddress: return "이 주소 사용" + case .linkAddressPlaceholder: return "예: 192.168.1.10" + case .linkNoAddressPhoneHint: return "휴대폰을 연결했나요? USB 테더링이 켜져 있는지 확인하세요. 나중에 주소를 받으면 자동으로 업데이트됩니다." + case .linkRouteAllSkipped: return "‘모든 트래픽을 이 인터페이스로 라우팅’이 적용되지 않습니다. 이 기기에는 라우터가 없습니다." + case .helperRequestTimedOut: return "제시간에 응답하지 않았습니다" case .configureNetwork: return "구성…" case .setupTitle: return "TetherKitNext에 오신 것을 환영합니다" case .setupSubtitle: return "몇 가지 단계만으로 Android 스마트폰의 USB 테더링을 Mac의 네트워크 인터페이스로 변환할 수 있습니다." @@ -1653,7 +2088,6 @@ extension L10nKey { case .updateCheckFailed: return "확인을 완료할 수 없습니다: %@" case .updateDevBuild: return "버전 번호가 없는 개발 빌드이므로 비교할 대상이 없습니다." case .uninstallWhileRunningWarning: return "현재 연결이 끊어지고 가상 인터페이스가 파기됩니다." - case .helperComponentVersion: return "헬퍼 · %@" case .helperVersionMismatch: return "헬퍼 %1$@ · 앱 %2$@" case .helperUpdateBadge: return "%@ 사용 가능" case .checkingHelper: return "권한 있는 헬퍼 확인 중…" @@ -1703,7 +2137,7 @@ extension L10nKey { case .quitTooltip: return "종료해도 인터페이스만 닫히며 이미 설정된 연결은 계속 유지됩니다." case .dnsEffectivenessTooltip: return "수동 모드에서 DNS 적용 여부는 시스템 확인자에 따라 결정되므로 \"현재 유효\"에 표시된 값을 신뢰하십시오." case .ipModeLabel: return "IPv4 구성" - case .connectBeforeConfiguring: return "네트워크를 구성하기 전에 먼저 장치를 연결하십시오" + case .connectBeforeConfiguring: return "설정이 저장되며 장치가 연결되면 자동으로 적용됩니다" case .dhcpHelp: return "시스템이 장치에 주소를 요청하고 DNS와 경로가 자동으로 설정됩니다" case .dhcpTooltip: return "거의 모든 휴대폰의 USB 테더링은 자체 DHCP 서버를 실행하므로 이 설정이 권장됩니다. 적용 시 최대 10초 동안 대기하며, 시간 초과는 대개 장치에서 테더링이 켜져 있지 않음을 의미합니다." case .routerOptional: return "선택 사항" @@ -1722,14 +2156,48 @@ extension L10nKey { case .linkDown: return "링크 끊김" case .transferPaused: return "전송 일시 중지됨" case .pendingDevice: return "연결 준비됨: %@" - case .noRNDISDeviceDetected: return "RNDIS 장치가 감지되지 않았습니다. 데이터 케이블로 휴대폰을 연결하고 휴대폰에서 \"USB 테더링\"을 켜십시오." + case .noRNDISDeviceDetected: return "휴대폰 또는 장치를 찾을 수 없습니다. 데이터 케이블로 연결하고 휴대폰에서 \"USB 테더링\"을 켜십시오." case .interfaceLabel: return "인터페이스" case .interfaceCreating: return "생성 중…" case .connectDisabledHint: return "먼저 USB 테더링이 켜진 장치를 연결하십시오" + case .dismiss: return "닫기" + case .sessionFailedTitle: return "연결이 종료됨" + case .sessionFailureDisconnected: return "장치 연결이 끊어졌습니다. 케이블과 USB 테더링이 켜져 있는지 확인한 후 다시 연결하십시오." + case .sessionFailureAccessDenied: return "macOS에서 장치 접근을 허용하지 않았습니다. 다른 앱이나 드라이버가 사용 중일 수 있습니다." + case .sessionFailureBusy: return "다른 앱이 장치를 사용 중입니다. 해당 앱을 종료한 후 다시 연결하십시오." + case .sessionFailureTimedOut: return "장치가 응답하지 않습니다. 장치를 뽑았다가 다시 꽂은 후 연결하십시오." + case .sessionFailureDetails: return "세부 정보" + case .done: return "완료" + case .layoutChooserTitle: return "화면 스타일 선택" + case .layoutChooserSubtitle: return "설정에서 언제든지 변경할 수 있습니다." + case .layoutSimpleName: return "간단히" + case .layoutSimpleDescription: return "버튼 하나로 연결하고, 장치와 상태를 한눈에 확인합니다." + case .layoutFullName: return "자세히" + case .layoutFullDescription: return "모든 옵션: 네트워크 설정, 실시간 차트, 로그 및 도구." + case .layoutContinue: return "계속" + case .layoutAnnouncementTitle: return "새 기능: 더 간단한 화면" + case .layoutAnnouncementBody: return "TetherKitNext에 간단한 화면이 추가되었습니다. 버튼 하나로 연결하고, 장치와 상태를 한눈에 확인할 수 있습니다. 전환하지 않으면 현재 화면은 그대로 유지되며, 설정에서 언제든지 변경할 수 있습니다." + case .layoutTrySimple: return "간단한 화면 사용해 보기" + case .settingsLayoutSection: return "화면 스타일" + case .menuUseSimpleView: return "간단한 화면 사용" + case .menuUseFullView: return "자세한 화면 사용" + case .simpleNoDevice: return "장치 없음" + case .simpleNoDeviceHint: return "휴대폰을 연결하고 USB 테더링을 켜십시오" + case .simpleDeviceReady: return "연결 준비됨" + case .simpleDeviceConnected: return "연결됨" + case .simpleChooseDevice: return "장치 선택" + case .simpleUseAddress: return "이번 세션에 %1$@ 사용" + case .simpleNeedsAddress: return "이 장치에는 주소가 필요합니다. 자세한 화면에서 설정하십시오." + case .simpleOpenFull: return "자세한 화면 열기" + case .simpleAllSettings: return "모든 설정" + case .autoConnectToggle: return "자동으로 연결" + case .autoConnectHelp: return "이 Mac에 Wi-Fi나 이더넷이 없을 때만, 연결할 때마다 한 번." + case .autoConnectWaiting: return "자동으로 연결하지 않음: 이 Mac은 이미 Wi-Fi 또는 이더넷에 연결되어 있습니다." + case .powerButtonLabel: return "연결" case .throughputSectionTitle: return "처리량" case .throughputLive: return "실시간" - case .throughputDownstream: return "다운로드 (장치 -> Mac)" - case .throughputUpstream: return "업로드 (Mac -> 장치)" + case .throughputDownstream: return "다운로드 (장치 → Mac)" + case .throughputUpstream: return "업로드 (Mac → 장치)" case .throughputDownstreamFPS: return "다운로드 프레임 레이트" case .throughputUpstreamFPS: return "업로드 프레임 레이트" case .chartTime: return "시간" @@ -1745,6 +2213,12 @@ extension L10nKey { case .upstreamDropped: return "업로드 드롭" case .kernelDrops: return "커널 드롭" case .transmitBackpressure: return "TX 역압력" + case .powerConnecting: return "연결 중…" + case .powerDisconnecting: return "연결 해제 중…" + case .simpleNoAddressHint: return "이 장치가 Mac에 주소를 할당하지 않았습니다." + case .setupHelperPlain: return "TetherKitNext는 네트워크 연결을 만들기 위해 작은 백그라운드 구성 요소가 필요합니다. macOS가 한 번 허용을 요청합니다." + case .setupLearnMore: return "자세히 알아보기" + case .autoConnectHelpDetail: return "장치를 연결하면 자동으로 연결합니다. 단, 이 Mac에 Wi-Fi 또는 이더넷 연결이 없을 때만 연결합니다. 연결할 때마다 한 번만: 연결을 끊으면 다시 꽂을 때까지 끊긴 상태로 유지됩니다." } } diff --git a/gui/Sources/TetherKitNextIPC/Models.swift b/gui/Sources/TetherKitNextIPC/Models.swift index 8e77540..abb308b 100644 --- a/gui/Sources/TetherKitNextIPC/Models.swift +++ b/gui/Sources/TetherKitNextIPC/Models.swift @@ -1,27 +1,26 @@ import Foundation -// Data models transferred between the App and the helper. +// Data models transferred between the app and the helper. // -// * Why everything goes through Codable + Data rather than NSSecureCoding classes * -// XPC accepts only plist types or classes implementing NSSecureCoding, and the latter requires both ends to register the allowed -// class set; getting one wrong is a runtime "disallowed class" exception, with an error message that is hard to pin down. -// Directly encoding Codable structs into JSON Data and passing them over lets both ends share the same type definitions, -// with validation left to JSONDecoder -- simple, and adding fields is naturally backward compatible. +// Everything goes through Codable + Data rather than NSSecureCoding classes. XPC accepts only plist types or +// NSSecureCoding classes, and the latter needs both ends to register the allowed class set; a mistake is a +// runtime "disallowed class" exception that is hard to pin down. Encoding Codable structs as JSON Data lets +// both ends share the type definitions, leaves validation to JSONDecoder, and makes added fields backward compatible. // MARK: - Sessions -/// The startup configuration of an RNDIS session. The fields correspond one-to-one with the C ABI's tk_session_config_t. +/// The startup configuration of an RNDIS session. The fields correspond one-to-one to the C ABI's tk_session_config_t. public struct SessionConfiguration: Codable, Hashable, Sendable { /// Device filter. All 0 means use the first RNDIS device found. public var vendorID: UInt16 public var productID: UInt16 - /// The bus number and device address must be given together, used to tell apart two devices of the same model. + /// The bus number and device address must be given together; they tell apart two devices of the same model. public var busNumber: UInt8 public var deviceAddress: UInt8 /// The desired MTU. Lowered by negotiation when the device cannot fit it. public var mtu: UInt32 - /// Whether to set the system-side NIC's MAC to the address the device reported. + /// Whether to set the system-side interface's MAC to the address the device reported. public var adoptDeviceMAC: Bool public init(vendorID: UInt16 = 0, @@ -48,7 +47,7 @@ public enum RunState: Int32, Codable, Sendable { case stopped = 4 case failed = 5 - /// Whether it is in a "busy" transitional state -- the UI uses it to disable buttons and show progress. + /// Whether it is in a "busy" transitional state; the UI uses it to disable buttons and show progress. public var isTransitional: Bool { self == .starting || self == .stopping } } @@ -70,9 +69,9 @@ public struct SessionStatus: Codable, Hashable, Sendable { /// Whether data movement is paused (during link down or a device soft reset). public var paused: Bool - /// System-side NIC name -- the user configures IP on this one. + /// System-side interface name; the user configures IP on this one. public var systemInterface: String - /// Driver-side NIC name, for troubleshooting display only. + /// Driver-side interface name, shown for troubleshooting only. public var driverInterface: String /// In the form "aa:bb:cc:dd:ee:ff"; empty when not negotiated. @@ -92,13 +91,19 @@ public struct SessionStatus: Codable, Hashable, Sendable { public var linkKernelDrops: UInt64 public var txBackpressure: UInt64 - /// Monotonic nanosecond count at the sampling moment. **It must be used as the denominator when computing rates**, and the period of the UI timer - /// must not be used -- the real interval between two pulls gets stretched by scheduling, and rates computed that way come out too high. + /// Monotonic nanosecond count at the sampling moment. Use it as the denominator when computing rates, not the + /// UI timer period: scheduling stretches the real interval between pulls, which would make rates too high. public var monotonicNanos: Int64 /// The cause when runState == .failed. public var fatalMessage: String + /// The device's own IPv4 address, learned passively from frames only it can have sent; nil until seen. + /// + /// Optional so JSON from an older daemon (without the key) still decodes: synthesized Codable uses + /// decodeIfPresent for optionals. + public var peerAddress: String? + /// The empty state when not connected. public static let idle = SessionStatus( runState: .idle, rndisState: .uninitialized, linkUp: false, paused: false, @@ -114,7 +119,7 @@ public struct SessionStatus: Codable, Hashable, Sendable { deviceDescription: String, rxFrames: UInt64, rxBytes: UInt64, rxDropped: UInt64, txFrames: UInt64, txBytes: UInt64, txDropped: UInt64, rxQueueDepth: UInt64, linkKernelDrops: UInt64, txBackpressure: UInt64, monotonicNanos: Int64, - fatalMessage: String) { + fatalMessage: String, peerAddress: String? = nil) { self.runState = runState self.rndisState = rndisState self.linkUp = linkUp @@ -137,6 +142,7 @@ public struct SessionStatus: Codable, Hashable, Sendable { self.txBackpressure = txBackpressure self.monotonicNanos = monotonicNanos self.fatalMessage = fatalMessage + self.peerAddress = peerAddress } } @@ -148,10 +154,10 @@ public struct DeviceDescriptor: Codable, Hashable, Identifiable, Sendable { public var productID: UInt16 public var busNumber: UInt8 public var deviceAddress: UInt8 - /// Vendor name / product name / serial number are best effort: reading them requires opening the device, and when the device is occupied - /// they cannot be obtained -- but the helper backfills the value last read successfully, so the name stays - /// stable before and after connecting. Only when even the backfill value is missing (never read since the helper started) is it an empty string, and the UI then - /// falls back to showing `description`. + /// Vendor name / product name / serial number are best effort: reading them requires opening the device, which + /// fails while the device is occupied. The helper backfills the last value read successfully so the name stays + /// stable before and after connecting. Only when no backfill exists (never read since the helper started) is it + /// an empty string, and the UI then falls back to `description`. public var manufacturer: String public var product: String public var serial: String @@ -159,7 +165,7 @@ public struct DeviceDescriptor: Codable, Hashable, Identifiable, Sendable { public var summary: String public var usedAndroidQuirk: Bool - /// Bus + address uniquely identify one connected device; two of the same model can also be told apart. + /// Bus + address uniquely identify one connected device, so two of the same model can be told apart. public var id: String { "\(busNumber).\(deviceAddress)" } /// The primary title displayed in the UI. @@ -211,11 +217,11 @@ public struct NetworkConfiguration: Codable, Hashable, Sendable { public var netmask: String public var router: String public var dnsServers: [String] - /// Whether to point the **global** default route at this NIC as well. + /// Whether to point the global default route at this interface as well. /// - /// When off there is only one scoped default route bound to this interface. It only needs to be turned on when a higher-priority - /// connected service (Wi-Fi, VPN) exists at the same time -- while the typical USB tethering scenario is precisely - /// that no other network is available, in which case this NIC is naturally the primary service. + /// When off there is only one scoped default route bound to this interface. It is only needed when a + /// higher-priority connected service (Wi-Fi, VPN) exists at the same time; in the typical USB tethering + /// scenario no other network is available, so this interface is naturally the primary service. public var setDefaultRoute: Bool public static let dhcp = NetworkConfiguration(mode: .dhcp) @@ -235,10 +241,10 @@ public struct NetworkConfiguration: Codable, Hashable, Sendable { } } -/// The state the NIC **actually has in effect** at present. +/// The state the interface actually has in effect. /// -/// Deliberately does not restate "what we applied" but reads back the system: in static mode whether DNS takes effect depends on -/// whether IPMonitor accepts this service, and only a readback gives the user accurate feedback. +/// It reads back the system instead of restating what we applied: in static mode whether DNS takes effect +/// depends on whether IPMonitor accepts the service, and only a readback gives accurate feedback. public struct NetworkState: Codable, Hashable, Sendable { public var hasAddress: Bool public var address: String @@ -250,7 +256,7 @@ public struct NetworkState: Codable, Hashable, Sendable { /// The service state reported by IPConfiguration (such as "BOUND"). public var serviceState: String public var hasDefaultRoute: Bool - /// Whether the global default route currently points at this NIC. + /// Whether the global default route currently points at this interface. public var isPrimaryDefaultRoute: Bool public static let empty = NetworkState( @@ -313,15 +319,16 @@ public struct LogEntry: Codable, Hashable, Identifiable, Sendable { } } -/// The reply to one helper "take away pending content". +/// The reply to one `drainFeed` call: pending logs and notices. /// -/// Events and logs are merged into one call to press the number of XPC round trips down to one per refresh period -- -/// the UI refreshes once every 500 ms, and fetching them separately would double the inter-process round trips. +/// Events and logs share one call to keep XPC round trips at one per refresh period; the UI refreshes every +/// 500 ms, and separate fetches would double the inter-process round trips. public struct HelperFeed: Codable, Sendable { public var logs: [LogEntry] - /// The number of dropped log entries (the oldest are dropped when the buffer fills). The UI uses it to show "the log has gaps". + /// The number of dropped log entries (the oldest are dropped when the buffer fills); the UI uses it to show "the + /// log has gaps". public var droppedLogs: UInt64 - /// Key events that have occurred but not yet been consumed by the UI, given in text form. + /// Key events that have occurred but not yet been consumed by the UI, in text form. public var notices: [String] public static let empty = HelperFeed(logs: [], droppedLogs: 0, notices: []) diff --git a/gui/Sources/TetherKitNextIPC/RateFormat.swift b/gui/Sources/TetherKitNextIPC/RateFormat.swift index a34ed99..fbe58dd 100644 --- a/gui/Sources/TetherKitNextIPC/RateFormat.swift +++ b/gui/Sources/TetherKitNextIPC/RateFormat.swift @@ -2,11 +2,10 @@ import Foundation /// Compact, fixed-width bit-rate text for the menu bar status item. /// -/// Upstream issue #1: the status item changed width as the rate moved between -/// "0K", "12K" and "120K", shoving every icon to its left around several times -/// a second. The output here is always exactly four characters — three for the -/// number (left-padded with FIGURE SPACE, which has digit width) plus a unit — -/// and is rendered in a monospaced font, so the width never changes. +/// The width is fixed so the status item does not jitter as the rate moves between "0K", "12K" and "120K", +/// which would shove every icon to its left around several times a second. The output is always exactly four +/// characters (three for the number, left-padded with FIGURE SPACE which has digit width, plus a unit) and is +/// rendered in a monospaced font. /// /// 0 → " 0K" 12_300 → " 12K" 9_870_000 → "9.9M" 123_000_000 → "123M" public enum RateFormat { diff --git a/gui/Sources/TetherKitNextUIModel/AutoConnectPolicy.swift b/gui/Sources/TetherKitNextUIModel/AutoConnectPolicy.swift new file mode 100644 index 0000000..fdd5a20 --- /dev/null +++ b/gui/Sources/TetherKitNextUIModel/AutoConnectPolicy.swift @@ -0,0 +1,107 @@ +import Foundation + +/// When "Connect automatically" may start a session by itself. +/// +/// The rules exist so that plugging in a phone never takes over a Mac that is +/// already online: +/// +/// 1. Only on arrival. A device triggers once per plug-in. If the user +/// disconnects, it stays disconnected until it is unplugged and plugged in +/// again (or the app restarts). A failed or cancelled attempt counts too, so +/// there is no retry loop and no repeated Touch ID prompts. +/// 2. Never with another network. If the Mac has Wi-Fi or Ethernet (other +/// than our own interfaces), nothing happens. The device waits instead. +/// 3. Failover only when the loss is stable. If that other network goes +/// away while the device is still plugged in, the device is connected only +/// after the Mac has been without it for `offlineGracePeriod`, so Wi-Fi +/// roaming or a short drop never triggers it. An unknown network state +/// (before the first reading) counts as "has a network". +/// 4. Only when idle. Not while a session runs, starts or stops, or while +/// another action is in progress. +public struct AutoConnectPolicy: Sendable { + /// How long the Mac must have had no other network before a waiting + /// device is connected. + public static let offlineGracePeriod: TimeInterval = 10 + + /// Devices present at the previous evaluation. + private var present: Set = [] + /// Devices already tried (or skipped by the user) during this plug-in. + private var handled: Set = [] + /// Since when the Mac has had no other network; nil while it has one. + private var offlineSince: TimeInterval? + + public init() {} + + public struct Inputs: Sendable { + public var enabled: Bool + /// Present devices in display order (`DeviceDescriptor.id`). + public var deviceIDs: [String] + /// The device the user selected, if any. + public var preferredDeviceID: String? + /// Idle: daemon reachable, no session starting/running/stopping, no action in progress. + public var idle: Bool + /// true / false once known; nil before the first reading. + public var hasOtherNetwork: Bool? + /// Monotonic seconds. + public var now: TimeInterval + + public init(enabled: Bool, deviceIDs: [String], preferredDeviceID: String?, + idle: Bool, hasOtherNetwork: Bool?, now: TimeInterval) { + self.enabled = enabled + self.deviceIDs = deviceIDs + self.preferredDeviceID = preferredDeviceID + self.idle = idle + self.hasOtherNetwork = hasOtherNetwork + self.now = now + } + } + + public enum Decision: Equatable, Sendable { + case none + /// Start a session with this device. The device is marked handled. + case connect(deviceID: String) + /// A device is waiting because the Mac already has Wi-Fi or Ethernet. + case waitingForOtherNetwork + } + + /// Marks every present device as handled, e.g. when the user disconnects + /// or a session is running: none of them may trigger until re-plugged. + public mutating func markAllHandled() { + handled.formUnion(present) + } + + public mutating func evaluate(_ inputs: Inputs) -> Decision { + let current = Set(inputs.deviceIDs) + // Unplugged devices are forgotten, so plugging them in again counts as a new arrival. + handled.formIntersection(current) + present = current + + switch inputs.hasOtherNetwork { + case false?: + if offlineSince == nil { offlineSince = inputs.now } + case true?, nil: + offlineSince = nil + } + + guard inputs.enabled else { + // While off, plugged-in devices are not "waiting": turning the + // option on later must not connect a device the user ignored. + handled = current + return .none + } + guard inputs.idle else { return .none } + + let candidates = inputs.deviceIDs.filter { !handled.contains($0) } + guard !candidates.isEmpty else { return .none } + + guard let offlineSince, inputs.now - offlineSince >= Self.offlineGracePeriod else { + return inputs.hasOtherNetwork == false ? .none : .waitingForOtherNetwork + } + + let chosen = inputs.preferredDeviceID.flatMap { candidates.contains($0) ? $0 : nil } + ?? candidates[0] + // One device per arrival: the others count as handled, since only one session can run. + handled.formUnion(candidates) + return .connect(deviceID: chosen) + } +} diff --git a/gui/Sources/TetherKitNextUIModel/InterfaceStyle.swift b/gui/Sources/TetherKitNextUIModel/InterfaceStyle.swift new file mode 100644 index 0000000..fa59411 --- /dev/null +++ b/gui/Sources/TetherKitNextUIModel/InterfaceStyle.swift @@ -0,0 +1,62 @@ +import Foundation + +/// The two layouts of the main window. +/// +/// * `.simple`: one round button to connect, the device and the status at a +/// glance, settings behind a gear. +/// * `.full`: the original sidebar layout with every card, chart and tool. +/// +/// Nothing is lost by choosing either: sessions, network settings and the menu +/// bar item are the same; only the window differs. +public enum InterfaceStyle: String, CaseIterable, Sendable { + case simple + case full +} + +/// The stored layout choice, and the one-time decision for installs that +/// predate it. +/// +/// * New install → no style yet. The window shows the layout chooser right +/// after the setup assistant (the background component must work first), with +/// `.simple` preselected. +/// * Existing install (updated from a version without layouts) → keeps +/// `.full`, exactly as before, and gets a one-time announcement that offers +/// the simple view. +/// +/// "Existing" is decided once, at the first launch of a version with layouts, +/// before anything else writes preferences: an install that already has +/// preferences was used before. The decision is stored, so a new user who +/// quits halfway through setup is not mistaken for an existing one later. +public struct InterfaceStylePreference { + public static let styleKey = "interfaceStyle" + public static let announcementPendingKey = "interfaceStyleAnnouncementPending" + public static let decidedKey = "interfaceStyleDecided" + + private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + /// Runs once per install. `hadPreferencesBefore` must be measured before + /// this launch writes anything (window frame, updater state, ...). + public func migrateIfNeeded(hadPreferencesBefore: Bool) { + guard !defaults.bool(forKey: Self.decidedKey) else { return } + defaults.set(true, forKey: Self.decidedKey) + guard style == nil, hadPreferencesBefore else { return } + style = .full + defaults.set(true, forKey: Self.announcementPendingKey) + } + + /// nil until the user has chosen (new installs, before the chooser). + public var style: InterfaceStyle? { + get { defaults.string(forKey: Self.styleKey).flatMap(InterfaceStyle.init(rawValue:)) } + nonmutating set { defaults.set(newValue?.rawValue, forKey: Self.styleKey) } + } + + /// Whether the "new: simple view" announcement still has to be shown. + public var announcementPending: Bool { + get { defaults.bool(forKey: Self.announcementPendingKey) } + nonmutating set { defaults.set(newValue, forKey: Self.announcementPendingKey) } + } +} diff --git a/gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift b/gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift new file mode 100644 index 0000000..e0375b3 --- /dev/null +++ b/gui/Sources/TetherKitNextUIModel/InterfaceTraffic.swift @@ -0,0 +1,270 @@ +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 + var buffer: [UInt8] = [] + // Interfaces can appear between sizing and reading (ENOMEM): leave headroom, and + // retry a few times instead of losing the whole sample. + var read = false + for _ in 0..<3 { + guard sysctl(&mib, UInt32(mib.count), nil, &length, nil, 0) == 0, length > 0 else { + return [:] + } + length += length / 8 + buffer = [UInt8](repeating: 0, count: length) + if sysctl(&mib, UInt32(mib.count), &buffer, &length, nil, 0) == 0 { + read = true + break + } + guard errno == ENOMEM else { return [:] } + } + guard read 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: Int32 + if Int32(address.pointee.sa_family) == AF_INET6 { + // The kernel embeds a link-local address's interface index in bytes 2-3 of the + // address (the KAME convention), so getifaddrs returns e.g. fe80:4::1. Move it + // to sin6_scope_id, as ifconfig does, so it prints as fe80::1%en0. + var copy = address.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { $0.pointee } + var embedded: UInt32 = 0 + withUnsafeMutableBytes(of: ©.sin6_addr) { bytes in + guard bytes[0] == 0xFE, bytes[1] & 0xC0 == 0x80 else { return } + embedded = UInt32(bytes[2]) << 8 | UInt32(bytes[3]) + bytes[2] = 0 + bytes[3] = 0 + } + if embedded != 0 && copy.sin6_scope_id == 0 { + copy.sin6_scope_id = embedded + } + status = withUnsafePointer(to: ©) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { + getnameinfo($0, socklen_t(MemoryLayout.size), + &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) + } + } + } else { + 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.. LinkAssessment { + guard isRunning else { return .notConnected } + if mode == IPMode.none && !network.hasAddress { return .notConfigured } + + let peer = peerAddress.flatMap { $0.isEmpty ? nil : $0 } + if network.hasAddress { + if !network.router.isEmpty { + return .internet(address: network.address, router: network.router) + } + let selfAssigned = isLinkLocal(network.address) + // macOS self-assigns 169.254.x.x while DHCP keeps retrying, so early + // on that only means "no lease yet", not "no DHCP server". + if selfAssigned && connectedFor < gracePeriod && mode == .dhcp { + return .waitingForAddress + } + return .localLink(address: network.address, peer: peer, selfAssigned: selfAssigned) + } + + if connectedFor < gracePeriod && mode == .dhcp { + return .waitingForAddress + } + return .noAddress(peer: peer, suggestion: peer.flatMap(suggestedHostAddress(forPeer:))) + } + + /// Whether routing all of the Mac's traffic through this link can work. + /// "Route all traffic" is only honoured for links that name a router. + public var canCarryInternet: Bool { + if case .internet = self { return true } + return false + } + + public var isLocalOnly: Bool { + switch self { + case .localLink, .noAddress: return true + default: return false + } + } + + // MARK: - Helpers + + static func isLinkLocal(_ address: String) -> Bool { + address.hasPrefix("169.254.") + } + + /// A host address in the device's /24 for a temporary manual setup. + /// + /// Picks the first of .10, .20, .100, .200 that is not the device itself. + /// Not offered for link-local peers (macOS already self-assigns in + /// 169.254/16) or anything that is not a plain IPv4 host address. macOS's + /// IPConfiguration runs ARP conflict detection when the address is applied. + public static func suggestedHostAddress(forPeer peer: String) -> String? { + let parts = peer.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 4 else { return nil } + let octets = parts.compactMap { UInt8($0) } + guard octets.count == 4, octets[0] != 0, octets[0] != 127, octets[0] < 224, + !(octets[0] == 169 && octets[1] == 254) else { return nil } + for host: UInt8 in [10, 20, 100, 200] where host != octets[3] { + return "\(octets[0]).\(octets[1]).\(octets[2]).\(host)" + } + return nil + } +} diff --git a/gui/Sources/TetherKitNextUIModel/Pane.swift b/gui/Sources/TetherKitNextUIModel/Pane.swift new file mode 100644 index 0000000..5b542f9 --- /dev/null +++ b/gui/Sources/TetherKitNextUIModel/Pane.swift @@ -0,0 +1,75 @@ +import TetherKitNextIPC + +/// Sidebar destinations of the main window. +/// +/// A library target of its own (not part of `TetherKitNextApp`) because a +/// SwiftPM executable target cannot be `@testable`-imported: the selection +/// rules below are exactly the kind of thing that breaks silently (a page +/// that cannot be reached, a stale selection pointing at a hidden page), so +/// they are pinned by `TetherKitNextUIModelTests`. +/// +/// The selection is persisted by `rawValue` (`@AppStorage`). Renaming a case +/// drops a stored selection once (it falls back to `.overview`); adding or +/// reordering cases is harmless. +public enum Pane: String, CaseIterable, Identifiable, Hashable, Sendable { + case overview, device, network, activity + /// Advanced tools: only listed when the user opts in (Settings → General). + case interfaces + case settings + + public var id: Self { self } + + public var titleKey: L10nKey { + switch self { + case .overview: return .paneOverview + case .device: return .paneDevice + case .network: return .paneNetwork + case .activity: return .paneActivity + case .interfaces: return .paneInterfaces + case .settings: return .paneSettings + } + } + + public var title: String { L(titleKey) } + + public 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 .interfaces: return "point.3.connected.trianglepath.dotted" + case .settings: return "gearshape" + } + } + + /// Pages that belong to the opt-in "Advanced" sidebar section. + /// + /// Everyday users of the app never see these unless they turn them on, so + /// diagnostic tooling can grow here without cluttering the tethering flow. + public var isAdvanced: Bool { + switch self { + case .interfaces: return true + case .overview, .device, .network, .activity, .settings: return false + } + } + + /// The sidebar, top to bottom: everyday pages, the optional advanced + /// section, then Settings on its own. Empty sections are omitted. + public static func sidebarSections(advancedToolsEnabled: Bool) -> [[Pane]] { + let everyday: [Pane] = [.overview, .device, .network, .activity] + let advanced = advancedToolsEnabled ? allCases.filter(\.isAdvanced) : [] + return [everyday, advanced, [.settings]].filter { !$0.isEmpty } + } + + /// Resolves a persisted selection. + /// + /// Unknown or empty values (a renamed case, a fresh install) and advanced + /// pages while advanced tools are turned off all land on `.overview`: the + /// window must never open on a page the sidebar does not list. + public static func resolveStored(_ rawValue: String?, advancedToolsEnabled: Bool) -> Pane { + guard let rawValue, let pane = Pane(rawValue: rawValue) else { return .overview } + if pane.isAdvanced && !advancedToolsEnabled { return .overview } + return pane + } +} diff --git a/gui/Sources/TetherKitNextUIModel/SessionFailure.swift b/gui/Sources/TetherKitNextUIModel/SessionFailure.swift new file mode 100644 index 0000000..b4bf46b --- /dev/null +++ b/gui/Sources/TetherKitNextUIModel/SessionFailure.swift @@ -0,0 +1,55 @@ +import Foundation + +/// A plain-language reading of why a session ended in failure. +/// +/// The library reports failures as a chain of context strings ending in the +/// libusb error, e.g. `"... [libusb: LIBUSB_ERROR_NO_DEVICE(-4)]"`. The context +/// is localized (English or Chinese), but the libusb error *name* never is, so +/// only that name is matched: classifying by localized wording would silently +/// break whenever a message is reworded or translated. +/// +/// The raw message is always kept and shown as detail; the cause only picks a +/// headline that tells the user what to do next. +public enum SessionFailureCause: Equatable, Sendable { + /// The device went away: unplugged, tethering switched off, or the phone re-enumerated. + case disconnected + /// macOS refused access to the interface. + case accessDenied + /// Another app or driver holds the interface. + case busy + /// The device stopped answering. + case timedOut + /// Anything else; the raw message is the best explanation available. + case other + + public init(fatalMessage: String) { + // Most specific first: a keep-alive failure on an unplugged device + // carries NO_DEVICE, not TIMEOUT. + if fatalMessage.contains("LIBUSB_ERROR_NO_DEVICE") { + self = .disconnected + } else if fatalMessage.contains("LIBUSB_ERROR_ACCESS") { + self = .accessDenied + } else if fatalMessage.contains("LIBUSB_ERROR_BUSY") { + self = .busy + } else if fatalMessage.contains("LIBUSB_ERROR_TIMEOUT") { + self = .timedOut + } else { + self = .other + } + } +} + +/// The last session failure, kept after the daemon has moved on. +/// +/// The daemon reports `.failed` exactly once and then drops the dead session +/// (the next status is `.idle`), so without this the reason would flash for a +/// single poll. It stays until the user dismisses it or starts a new session. +public struct SessionFailure: Equatable, Sendable { + public let message: String + public let cause: SessionFailureCause + + public init(message: String) { + self.message = message + cause = SessionFailureCause(fatalMessage: message) + } +} diff --git a/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift b/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift index 8f16f43..02c0e65 100644 --- a/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift +++ b/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift @@ -5,21 +5,20 @@ import XCTest /// Regression tests of the authorization credential lifecycle. /// -/// * What is pinned down here is a pitfall that was really hit * -/// The 32 bytes produced by `AuthorizationMakeExternalForm` are **not the credential itself**, only -/// a key pointing to that authorization in securityd. Once the App side releases the AuthorizationRef early -/// (especially with `.destroyRights`), the helper's restore fails -- and the failure information is just one -/// `-60005`, from which it is completely impossible to tell from the code that "it was destroyed early by ourselves". +/// Invariant: the 32 bytes produced by `AuthorizationMakeExternalForm` are not the credential itself, only a +/// key to that authorization in securityd. If the app releases the AuthorizationRef early (especially with +/// `.destroyRights`), the external form is invalidated and the helper's restore fails with `-60005`, which +/// gives no hint that we destroyed it ourselves. /// -/// These cases **do not pop up an authorization dialog**: they only call `AuthorizationCreate` (creating an empty authorization session), -/// and do not call `AuthorizationCopyRights`, so no user interaction is needed and they can go into CI. +/// These cases do not show an authorization dialog: they only call `AuthorizationCreate` (creating an empty +/// authorization session) and never `AuthorizationCopyRights`, so they need no user interaction and can run in CI. final class AuthorizationTests: XCTestCase { /// Externalizes an AuthorizationRef. private func externalForm(of authorization: AuthorizationRef) throws -> Data { var external = AuthorizationExternalForm() let status = AuthorizationMakeExternalForm(authorization, &external) try XCTSkipUnless(status == errAuthorizationSuccess, - "AuthorizationMakeExternalForm 失败(\(status)),跳过") + "AuthorizationMakeExternalForm failed (\(status)); skipping") return withUnsafeBytes(of: &external) { Data($0) } } @@ -47,15 +46,15 @@ final class AuthorizationTests: XCTestCase { externalForm: try externalForm(of: reference)) XCTAssertEqual(restore(token.externalForm), errAuthorizationSuccess, - "令牌还活着的时候,helper 侧必须能还原出凭据") + "while the token is alive, the helper side must be able to restore the credential") withExtendedLifetime(token) {} } - /// After the token is released it can no longer be restored -- this is exactly the cause of -60005 back then. + /// After the token is released it can no longer be restored, which is the cause of -60005. /// - /// Conversely: once this case turns red, it means "releasing early is fine", and then the whole AuthorizationToken - /// layer has no reason to exist, and you should first find out what changed in system behavior before touching it. + /// If this case turns red, releasing early has become harmless, and the whole AuthorizationToken layer has no + /// reason to exist; find out what changed in system behavior before touching it. func testExternalFormUnusableAfterTokenReleased() throws { var authorization: AuthorizationRef? XCTAssertEqual(AuthorizationCreate(nil, nil, [], &authorization), errAuthorizationSuccess) @@ -69,6 +68,6 @@ final class AuthorizationTests: XCTestCase { } // token is destroyed here, together with the rights XCTAssertEqual(restore(capturedForm), errAuthorizationDenied, - "令牌释放后外部形式必须失效;当初就是它导致了 -60005") + "once the token is released the external form must stop working; this caused -60005") } } diff --git a/gui/Tests/TetherKitNextIPCTests/HelperConstantsTests.swift b/gui/Tests/TetherKitNextIPCTests/HelperConstantsTests.swift index b897ac9..a5d5d8a 100644 --- a/gui/Tests/TetherKitNextIPCTests/HelperConstantsTests.swift +++ b/gui/Tests/TetherKitNextIPCTests/HelperConstantsTests.swift @@ -4,12 +4,12 @@ import XCTest /// Encoding/decoding and comparison of the helper version string. /// -/// * What these cases pin down * -/// "Which version the installed component is" is the only fact the App can ask for (`helperVersion` is the method that even an old component -/// will certainly answer), and the following two judgments both rely on it: a protocol mismatch must be stopped at the guidance page, -/// and a version mismatch must light up "Update privileged component". A parsing mistake manifests as **silently not reporting** -- -/// either treating an old component as new (the user keeps running the pre-upgrade library), or popping up every day an update hint that -/// does nothing when clicked. Neither gives any error, and only test cases can guard against them. +/// What these cases pin down: which version the running component is is the only fact the app can ask for +/// (`helperVersion` is the method every component answers), and two judgments rely on it. A protocol mismatch +/// must be stopped at the setup page, and a version mismatch must light up "Restart background component". +/// A parsing mistake means silently not reporting: either treating an old component as new (the user keeps +/// running the old library), or showing an update hint every day that does nothing when clicked. Neither +/// gives any error, so only test cases guard against them. final class HelperConstantsTests: XCTestCase { // MARK: - Encoding/decoding @@ -22,7 +22,8 @@ final class HelperConstantsTests: XCTestCase { XCTAssertEqual(version, "TetherKitNext 0.1.4 (C++23, macOS 13.3+)") } - /// The string returned by an old component has no separator -- this is exactly the kind of component to be recognized, with the revision number recorded as 0. + /// The string returned by an old component has no separator; it must still be recognized, with the revision + /// recorded as 0. func testDecodeLegacyVersionWithoutRevision() { let (revision, version, _) = HelperConstants.decodeVersion("TetherKitNext 0.1.2 (C++23, macOS 13.3+)") @@ -30,7 +31,7 @@ final class HelperConstantsTests: XCTestCase { XCTAssertEqual(revision, 0) XCTAssertEqual(version, "TetherKitNext 0.1.2 (C++23, macOS 13.3+)") XCTAssertNotEqual(revision, HelperConstants.protocolRevision, - "0 必须与任何真实修订号都不同,否则旧组件会被当成匹配的") + "0 must differ from every real revision, or an old component would count as a match") } // MARK: - Build identity @@ -70,15 +71,16 @@ final class HelperConstantsTests: XCTestCase { HelperConstants.semanticVersion(of: "TetherKitNext 0.1.4 (C++23, macOS 13.3+)"), "0.1.4") } - /// The other two numbers in the string (the C++ standard, the minimum macOS version) must not be taken as the version number: - /// the former has no dot, and the latter comes after the version number. + /// The other two numbers in the string (the C++ standard, the minimum macOS version) must not be taken as the + /// version number: the former has no dot, and the latter comes after the version number. func testSemanticVersionIgnoresBuildConfigurationNumbers() { let text = "TetherKitNext 1.0.0 (C++23, macOS 13.3+)" XCTAssertEqual(HelperConstants.semanticVersion(of: text), "1.0.0") } - /// Differing only in build configuration (the same version rebuilt with different compile options) **does not count** as a version mismatch -- - /// this is why the whole string is not compared directly: otherwise a false alarm that does not go away even when clicked would appear. + /// Differing only in build configuration (the same version rebuilt with different compile options) does not + /// count as a version mismatch. This is why the whole string is not compared: it would raise a false alarm + /// that does not go away when clicked. func testSemanticVersionEqualAcrossBuildConfigurations() { let installed = HelperConstants.semanticVersion(of: "TetherKitNext 0.1.4 (C++23, macOS 13.3+)") let bundled = HelperConstants.semanticVersion(of: "TetherKitNext 0.1.4 (C++26, macOS 15.0+)") @@ -95,16 +97,16 @@ final class HelperConstantsTests: XCTestCase { XCTAssertEqual(bundled, "0.1.4") } - /// When it cannot be parsed, fall back to the whole string: better a false alarm (a superfluous update hint) than a missed one - /// (the user keeps running the old component without knowing it). + /// When it cannot be parsed, fall back to the whole string: a false alarm (a superfluous update hint) is + /// better than a missed one (the user keeps running the old component without knowing it). func testSemanticVersionFallsBackToWholeString() { XCTAssertEqual(HelperConstants.semanticVersion(of: " TetherKitNext dev "), "TetherKitNext dev") XCTAssertNotEqual(HelperConstants.semanticVersion(of: "TetherKitNext dev-a"), HelperConstants.semanticVersion(of: "TetherKitNext dev-b")) } - /// After installation, comparing it to itself must be consistent -- once this turns red, the UI would show a - /// dead-loop hint of "component needs updating" that is still there after updating. + /// The running component compared to itself must be consistent; if this turns red, the UI would show a + /// "component needs updating" hint that never goes away. func testSemanticVersionIsStableForSameInput() { let text = "TetherKitNext 0.1.4 (C++23, macOS 13.3+)" XCTAssertEqual(HelperConstants.semanticVersion(of: text), diff --git a/gui/Tests/TetherKitNextIPCTests/LocalizationTests.swift b/gui/Tests/TetherKitNextIPCTests/LocalizationTests.swift index 5ba1a02..575ec7a 100644 --- a/gui/Tests/TetherKitNextIPCTests/LocalizationTests.swift +++ b/gui/Tests/TetherKitNextIPCTests/LocalizationTests.swift @@ -4,19 +4,18 @@ import XCTest /// Consistency check of the message table. /// -/// * The sole reason these cases exist * +/// Why these cases exist: `L(...)` goes through `String(format:)`, and the format string comes from a runtime +/// table lookup that the compiler cannot check. When the placeholders of two languages do not match, +/// `String(format:)` reports no error: it reads an argument by the type the format claims. `%@` meeting an +/// integer dereferences the integer as a pointer and crashes; `%ld` meeting a string prints an address. Both +/// are "translation written wrong, blows up at runtime on the user's machine", and one language can be fine +/// while another crashes. /// -/// `L(...)` goes through `String(format:)`, and the format string comes from a runtime table lookup -- the compiler cannot manage it. -/// When the placeholders of the two languages do not match, `String(format:)` **does not report an error**: it quietly interprets -/// an argument that is not of that type at all by the type it reads. `%@` meeting an integer dereferences the integer -/// as a pointer and crashes directly; `%ld` meeting a string prints an address. Both are -/// "translation written wrong -> blows up at runtime on the user's machine", and moreover the Chinese version is fine while the English version blows up. -/// -/// So this safeguard must be made up here. `L10nKey` is CaseIterable, so newly added messages -/// are covered automatically, with no manual registration. +/// So this safeguard lives here. `L10nKey` is CaseIterable, so new messages are covered automatically. final class LocalizationTests: XCTestCase { - /// One replacement field: the position (the number of an explicit `%1$`, or by order of appearance if implicit) + the conversion type. + /// One replacement field: the position (the number of an explicit `%1$`, or by order of appearance if implicit) + + /// the conversion type. private struct Placeholder: Equatable, CustomStringConvertible { let position: Int let conversion: String @@ -26,8 +25,8 @@ final class LocalizationTests: XCTestCase { /// Parses a printf-style format string. /// - /// Covers only the subset this table really uses: `%@`, `%ld`, `%lx`, `%f` and their forms with width/precision/position, - /// plus the `%%` escape. + /// Covers only the subset this table really uses: `%@`, `%ld`, `%lx`, `%f` and their forms with + /// width/precision/position, plus the `%%` escape. private func placeholders(in text: String) -> [Placeholder] { var result: [Placeholder] = [] var automatic = 0 @@ -59,7 +58,7 @@ final class LocalizationTests: XCTestCase { index = lookahead + 1 } - // Flags, width, precision -- all skipped, since they do not affect the argument type. + // Flags, width, precision: all skipped, since they do not affect the argument type. while index < characters.count, "0123456789.-+ #'".contains(characters[index]) { index += 1 @@ -105,8 +104,8 @@ final class LocalizationTests: XCTestCase { """) } - // Positions must be consecutive 1...n. With a gap String(format:) can still render, - // but that means some argument is ignored by languages at once, which is almost always a mistake. + // Positions must be consecutive 1...n. With a gap String(format:) can still render, but that means some + // argument is ignored by a language, which is almost always a mistake. for (offset, placeholder) in englishPlaceholders.enumerated() { XCTAssertEqual(placeholder.position, offset + 1, "\(key.rawValue) placeholder numbering is not consecutive: \(englishPlaceholders)") @@ -114,7 +113,8 @@ final class LocalizationTests: XCTestCase { } } - /// Integers are always `%ld`: `%d` takes only the low 32 bits of a 64-bit argument, and the Swift side passes `Int`. + /// Integers are always `%ld`: `%d` takes only the low 32 bits of a 64-bit argument, and the Swift side passes + /// `Int`. func testIntegerPlaceholdersUseLongModifier() { for key in L10nKey.allCases { for language in Language.allCases { @@ -190,8 +190,8 @@ final class LocalizationTests: XCTestCase { XCTAssertTrue(failure.hasSuffix("File exists"), failure) } - /// The language tags are aligned with the C ABI's `tk_language_t` -- if misaligned the GUI would be in one language and - /// the library logs in another, with no error whatsoever. + /// The language tags are aligned with the C ABI's `tk_language_t`; if misaligned the GUI would be in one + /// language and the library logs in another, with no error. func testCValueMatchesCABI() { XCTAssertEqual(Language.english.cValue, 0) XCTAssertEqual(Language.spanish.cValue, 0) @@ -201,7 +201,7 @@ final class LocalizationTests: XCTestCase { XCTAssertEqual(Language.korean.cValue, 0) } - /// The options in the language menu are always written as native-language names and are not translated with the UI language. + /// The options in the language menu are always native-language names and are not translated with the UI language. func testLanguageNamesAreNotTranslated() { for language in Language.allCases { XCTAssertEqual(L10nKey.languageEnglish.translation(for: language), "English") diff --git a/gui/Tests/TetherKitNextIPCTests/RateFormatTests.swift b/gui/Tests/TetherKitNextIPCTests/RateFormatTests.swift index 84327c0..25fcf60 100644 --- a/gui/Tests/TetherKitNextIPCTests/RateFormatTests.swift +++ b/gui/Tests/TetherKitNextIPCTests/RateFormatTests.swift @@ -1,7 +1,7 @@ import XCTest @testable import TetherKitNextIPC -/// Upstream issue #1: the menu bar item must not change width with the rate. +/// The menu bar item must not change width with the rate. final class RateFormatTests: XCTestCase { func testAlwaysFourCharacters() { var value = 0.0 diff --git a/gui/Tests/TetherKitNextUIModelTests/AutoConnectPolicyTests.swift b/gui/Tests/TetherKitNextUIModelTests/AutoConnectPolicyTests.swift new file mode 100644 index 0000000..8271a85 --- /dev/null +++ b/gui/Tests/TetherKitNextUIModelTests/AutoConnectPolicyTests.swift @@ -0,0 +1,94 @@ +import XCTest + +@testable import TetherKitNextUIModel + +/// The auto-connect rules. A wrong answer here takes over a Mac that is +/// already online, or loops on Touch ID prompts, so each rule is pinned. +final class AutoConnectPolicyTests: XCTestCase { + + private func inputs(_ devices: [String], enabled: Bool = true, idle: Bool = true, + network: Bool?, now: TimeInterval, preferred: String? = nil) + -> AutoConnectPolicy.Inputs { + .init(enabled: enabled, deviceIDs: devices, preferredDeviceID: preferred, + idle: idle, hasOtherNetwork: network, now: now) + } + + func testNeverConnectsWhileTheMacHasWiFiOrEthernet() { + var policy = AutoConnectPolicy() + XCTAssertEqual(policy.evaluate(inputs(["a"], network: true, now: 0)), .waitingForOtherNetwork) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: true, now: 100)), .waitingForOtherNetwork) + } + + func testUnknownNetworkStateCountsAsOnline() { + var policy = AutoConnectPolicy() + XCTAssertEqual(policy.evaluate(inputs(["a"], network: nil, now: 0)), .waitingForOtherNetwork) + } + + func testConnectsOnlyAfterAStableOfflinePeriod() { + var policy = AutoConnectPolicy() + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 0)), .none) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 5)), .none) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 10)), + .connect(deviceID: "a")) + } + + func testABriefWiFiDropDoesNotTrigger() { + var policy = AutoConnectPolicy() + _ = policy.evaluate(inputs(["a"], network: true, now: 0)) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 1)), .none) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: true, now: 4)), .waitingForOtherNetwork) + // The clock restarts after the network came back. + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 6)), .none) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 12)), .none) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 16)), + .connect(deviceID: "a")) + } + + func testOneAttemptPerPlugIn() { + var policy = AutoConnectPolicy() + _ = policy.evaluate(inputs(["a"], network: false, now: 0)) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 10)), + .connect(deviceID: "a")) + // The attempt failed or the user disconnected: no retry while still plugged in. + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 20)), .none) + // Unplugged and plugged in again: a new arrival. + _ = policy.evaluate(inputs([], network: false, now: 30)) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 31)), + .connect(deviceID: "a")) + } + + func testUserDisconnectKeepsTheDeviceDisconnected() { + var policy = AutoConnectPolicy() + _ = policy.evaluate(inputs(["a"], idle: false, network: false, now: 0)) + policy.markAllHandled() // a session was running, then the user stopped it + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 60)), .none) + } + + func testNothingWhileBusyOrRunning() { + var policy = AutoConnectPolicy() + _ = policy.evaluate(inputs(["a"], network: false, now: 0)) + XCTAssertEqual(policy.evaluate(inputs(["a"], idle: false, network: false, now: 30)), .none) + // Still eligible once idle again. + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 31)), + .connect(deviceID: "a")) + } + + func testDevicesPluggedInWhileDisabledAreNotConnectedWhenEnabledLater() { + var policy = AutoConnectPolicy() + _ = policy.evaluate(inputs(["a"], enabled: false, network: false, now: 0)) + XCTAssertEqual(policy.evaluate(inputs(["a"], network: false, now: 30)), .none) + } + + func testPrefersTheSelectedDeviceAndConnectsOnlyOne() { + var policy = AutoConnectPolicy() + _ = policy.evaluate(inputs(["a", "b"], network: false, now: 0, preferred: "b")) + XCTAssertEqual(policy.evaluate(inputs(["a", "b"], network: false, now: 10, preferred: "b")), + .connect(deviceID: "b")) + XCTAssertEqual(policy.evaluate(inputs(["a", "b"], network: false, now: 20)), .none) + } + + func testNoDevicesNoDecision() { + var policy = AutoConnectPolicy() + XCTAssertEqual(policy.evaluate(inputs([], network: true, now: 0)), .none) + } +} diff --git a/gui/Tests/TetherKitNextUIModelTests/InterfaceStyleTests.swift b/gui/Tests/TetherKitNextUIModelTests/InterfaceStyleTests.swift new file mode 100644 index 0000000..c7a7448 --- /dev/null +++ b/gui/Tests/TetherKitNextUIModelTests/InterfaceStyleTests.swift @@ -0,0 +1,55 @@ +import XCTest + +@testable import TetherKitNextUIModel + +/// Layout choice and the one-time decision for existing installs. +final class InterfaceStyleTests: XCTestCase { + private var defaults: UserDefaults! + private var suiteName: String! + + override func setUp() { + suiteName = "InterfaceStyleTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suiteName) + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + } + + func testNewInstallHasNoStyleSoTheChooserShows() { + let preference = InterfaceStylePreference(defaults: defaults) + preference.migrateIfNeeded(hadPreferencesBefore: false) + XCTAssertNil(preference.style) + XCTAssertFalse(preference.announcementPending) + } + + func testExistingInstallKeepsTheFullViewAndIsToldAboutTheSimpleOne() { + let preference = InterfaceStylePreference(defaults: defaults) + preference.migrateIfNeeded(hadPreferencesBefore: true) + XCTAssertEqual(preference.style, .full) + XCTAssertTrue(preference.announcementPending) + } + + func testDecisionIsMadeOnlyOnce() { + let preference = InterfaceStylePreference(defaults: defaults) + preference.migrateIfNeeded(hadPreferencesBefore: false) + // Second launch of a new user who quit during setup: preferences exist + // now, but this is still not an existing install. + preference.migrateIfNeeded(hadPreferencesBefore: true) + XCTAssertNil(preference.style) + XCTAssertFalse(preference.announcementPending) + } + + func testAnExplicitChoiceIsNeverOverridden() { + let preference = InterfaceStylePreference(defaults: defaults) + preference.style = .simple + preference.migrateIfNeeded(hadPreferencesBefore: true) + XCTAssertEqual(preference.style, .simple) + XCTAssertFalse(preference.announcementPending) + } + + func testUnknownStoredValueReadsAsNotChosen() { + defaults.set("compact", forKey: InterfaceStylePreference.styleKey) + XCTAssertNil(InterfaceStylePreference(defaults: defaults).style) + } +} diff --git a/gui/Tests/TetherKitNextUIModelTests/InterfaceTrafficTests.swift b/gui/Tests/TetherKitNextUIModelTests/InterfaceTrafficTests.swift new file mode 100644 index 0000000..33509d8 --- /dev/null +++ b/gui/Tests/TetherKitNextUIModelTests/InterfaceTrafficTests.swift @@ -0,0 +1,82 @@ +import XCTest + +@testable import TetherKitNextUIModel + +final class InterfaceTrafficTests: XCTestCase { + + private func snapshot(_ name: String, rx: UInt64, tx: UInt64) -> InterfaceSnapshot { + InterfaceSnapshot(name: name, isUp: true, isRunning: true, isLoopback: false, + linkAddress: nil, mtu: 1500, receivedBytes: rx, sentBytes: tx, + ipv4Addresses: ["192.0.2.1"], ipv6Addresses: []) + } + + func testFirstSampleReportsZero() { + var tracker = InterfaceRateTracker() + let rates = tracker.update(with: [snapshot("en0", rx: 1_000, tx: 2_000)], at: 10) + XCTAssertEqual(rates["en0"], .zero) + } + + func testRateIsBitsPerSecond() { + var tracker = InterfaceRateTracker() + _ = tracker.update(with: [snapshot("en0", rx: 0, tx: 0)], at: 10) + let rates = tracker.update(with: [snapshot("en0", rx: 125_000, tx: 250_000)], at: 11) + XCTAssertEqual(rates["en0"]?.receiveBitsPerSecond ?? -1, 1_000_000, accuracy: 0.001) + XCTAssertEqual(rates["en0"]?.transmitBitsPerSecond ?? -1, 2_000_000, accuracy: 0.001) + } + + func testRateAcrossHalfSecondInterval() { + var tracker = InterfaceRateTracker() + _ = tracker.update(with: [snapshot("en0", rx: 0, tx: 0)], at: 0) + let rates = tracker.update(with: [snapshot("en0", rx: 1_000, tx: 0)], at: 0.5) + XCTAssertEqual(rates["en0"]?.receiveBitsPerSecond ?? -1, 16_000, accuracy: 0.001) + } + + /// A recreated interface (same name, counters back near 0) must not + /// report a spike; the direction that did not go backwards still works. + func testCounterResetReportsZero() { + var tracker = InterfaceRateTracker() + _ = tracker.update(with: [snapshot("feth0", rx: 3_000_000_000, tx: 10)], at: 0) + let rates = tracker.update(with: [snapshot("feth0", rx: 100, tx: 20)], at: 0.1) + XCTAssertEqual(rates["feth0"]?.receiveBitsPerSecond, 0) + XCTAssertEqual(rates["feth0"]?.transmitBitsPerSecond ?? -1, 800, accuracy: 0.001) + } + + /// Counters beyond 4 GiB (the 32-bit if_data limit) keep working. + func testLargeCountersDoNotWrap() { + var tracker = InterfaceRateTracker() + let base: UInt64 = 5_000_000_000 + _ = tracker.update(with: [snapshot("en0", rx: base, tx: 0)], at: 0) + let rates = tracker.update(with: [snapshot("en0", rx: base + 1_250_000, tx: 0)], at: 1) + XCTAssertEqual(rates["en0"]?.receiveBitsPerSecond ?? -1, 10_000_000, accuracy: 0.001) + } + + func testVanishedInterfaceStartsFreshWhenItReturns() { + var tracker = InterfaceRateTracker() + _ = tracker.update(with: [snapshot("en5", rx: 0, tx: 0)], at: 0) + _ = tracker.update(with: [], at: 1) + let rates = tracker.update(with: [snapshot("en5", rx: 50_000, tx: 0)], at: 2) + XCTAssertEqual(rates["en5"], .zero) + } + + func testNonIncreasingTimeReportsZero() { + var tracker = InterfaceRateTracker() + _ = tracker.update(with: [snapshot("en0", rx: 0, tx: 0)], at: 5) + let rates = tracker.update(with: [snapshot("en0", rx: 9_000, tx: 0)], at: 5) + XCTAssertEqual(rates["en0"], .zero) + } + + /// Smoke test against the real system: every Mac has a loopback. + func testSamplerFindsLoopback() { + let interfaces = InterfaceSampler.snapshot() + let loopback = interfaces.first { $0.name == "lo0" } + XCTAssertNotNil(loopback) + XCTAssertEqual(loopback?.isLoopback, true) + XCTAssertTrue(loopback?.ipv4Addresses.contains("127.0.0.1") ?? false) + XCTAssertEqual(Set(interfaces.map(\.name)).count, interfaces.count, "one entry per name") + } + + /// The 64-bit counter dump parses and names the loopback interface. + func testCounterDumpIncludesLoopback() { + XCTAssertNotNil(InterfaceSampler.counters64()["lo0"]) + } +} diff --git a/gui/Tests/TetherKitNextUIModelTests/LinkAssessmentTests.swift b/gui/Tests/TetherKitNextUIModelTests/LinkAssessmentTests.swift new file mode 100644 index 0000000..f9b4ab6 --- /dev/null +++ b/gui/Tests/TetherKitNextUIModelTests/LinkAssessmentTests.swift @@ -0,0 +1,99 @@ +import XCTest + +import TetherKitNextIPC +@testable import TetherKitNextUIModel + +/// The link assessment decides whether the app talks about "internet" or a +/// "local device". These cases pin the rules that keep it from misjudging a +/// slow phone as a local device, and a local device as a broken phone. +final class LinkAssessmentTests: XCTestCase { + + private func network(address: String = "", router: String = "") -> NetworkState { + NetworkState(hasAddress: !address.isEmpty, address: address, netmask: "255.255.255.0", + router: router, dnsServers: [], method: "DHCP", serviceState: "", + hasDefaultRoute: !router.isEmpty, isPrimaryDefaultRoute: false) + } + + private func assess(_ seconds: TimeInterval, mode: IPMode = .dhcp, + _ state: NetworkState, peer: String? = nil) -> LinkAssessment { + LinkAssessment.assess(isRunning: true, connectedFor: seconds, mode: mode, + network: state, peerAddress: peer) + } + + func testNotRunning() { + XCTAssertEqual(LinkAssessment.assess(isRunning: false, connectedFor: 100, mode: .dhcp, + network: network(address: "10.0.0.2"), + peerAddress: nil), + .notConnected) + } + + func testLeaseWithRouterIsInternet() { + let result = assess(3, network(address: "172.19.0.5", router: "172.19.0.1")) + XCTAssertEqual(result, .internet(address: "172.19.0.5", router: "172.19.0.1")) + XCTAssertTrue(result.canCarryInternet) + XCTAssertFalse(result.isLocalOnly) + } + + /// A slow phone: nothing yet within the grace period must read "waiting", + /// never "local device". + func testSlowDhcpIsWaitingDuringGrace() { + XCTAssertEqual(assess(5, network()), .waitingForAddress) + XCTAssertEqual(assess(LinkAssessment.gracePeriod - 0.1, network()), .waitingForAddress) + } + + /// macOS self-assigns 169.254.x.x while DHCP retries; early on that is + /// still "waiting". + func testEarlySelfAssignedAddressIsStillWaiting() { + XCTAssertEqual(assess(8, network(address: "169.254.3.4")), .waitingForAddress) + } + + func testSelfAssignedAfterGraceIsLocalLink() { + XCTAssertEqual(assess(40, network(address: "169.254.3.4"), peer: "169.254.9.9"), + .localLink(address: "169.254.3.4", peer: "169.254.9.9", selfAssigned: true)) + } + + /// A device whose DHCP server hands out an address but no gateway. + func testLeaseWithoutRouterIsLocalLinkImmediately() { + let result = assess(2, network(address: "192.168.42.10"), peer: "192.168.42.1") + XCTAssertEqual(result, + .localLink(address: "192.168.42.10", peer: "192.168.42.1", selfAssigned: false)) + XCTAssertFalse(result.canCarryInternet) + XCTAssertTrue(result.isLocalOnly) + } + + func testNoAddressAfterGraceSuggestsNeighbourOfPeer() { + XCTAssertEqual(assess(30, network(), peer: "192.168.7.2"), + .noAddress(peer: "192.168.7.2", suggestion: "192.168.7.10")) + XCTAssertEqual(assess(30, network(), peer: nil), .noAddress(peer: nil, suggestion: nil)) + XCTAssertEqual(assess(30, network(), peer: ""), .noAddress(peer: nil, suggestion: nil)) + } + + /// Live re-evaluation: a late lease flips the result without any state. + func testLateLeaseFlipsToInternet() { + XCTAssertEqual(assess(45, network(), peer: "172.19.0.1").isLocalOnly, true) + XCTAssertEqual(assess(46, network(address: "172.19.0.5", router: "172.19.0.1")), + .internet(address: "172.19.0.5", router: "172.19.0.1")) + } + + /// A manual address chosen by the user: no waiting, judged by the router. + func testManualWithoutRouterIsLocalLink() { + XCTAssertEqual(assess(1, mode: .manual, network(address: "192.168.1.50")), + .localLink(address: "192.168.1.50", peer: nil, selfAssigned: false)) + XCTAssertEqual(assess(1, mode: .manual, network()), .noAddress(peer: nil, suggestion: nil)) + } + + func testDoNotConfigure() { + XCTAssertEqual(assess(60, mode: .none, network()), .notConfigured) + } + + func testSuggestedHostAddress() { + XCTAssertEqual(LinkAssessment.suggestedHostAddress(forPeer: "192.168.42.10"), "192.168.42.20") + XCTAssertEqual(LinkAssessment.suggestedHostAddress(forPeer: "10.1.2.3"), "10.1.2.10") + XCTAssertNil(LinkAssessment.suggestedHostAddress(forPeer: "169.254.1.1")) + XCTAssertNil(LinkAssessment.suggestedHostAddress(forPeer: "127.0.0.1")) + XCTAssertNil(LinkAssessment.suggestedHostAddress(forPeer: "224.0.0.251")) + XCTAssertNil(LinkAssessment.suggestedHostAddress(forPeer: "not an address")) + XCTAssertNil(LinkAssessment.suggestedHostAddress(forPeer: "1.2.3")) + XCTAssertNil(LinkAssessment.suggestedHostAddress(forPeer: "1.2.3.400")) + } +} diff --git a/gui/Tests/TetherKitNextUIModelTests/PaneTests.swift b/gui/Tests/TetherKitNextUIModelTests/PaneTests.swift new file mode 100644 index 0000000..fcd8112 --- /dev/null +++ b/gui/Tests/TetherKitNextUIModelTests/PaneTests.swift @@ -0,0 +1,52 @@ +import XCTest + +@testable import TetherKitNextUIModel + +/// Sidebar composition and persisted-selection rules. +/// +/// Failure modes guarded here are silent in the UI: an advanced page left +/// selected after the user turns advanced tools off would open the window on +/// a page the sidebar no longer lists, with no way to see which row is active. +final class PaneTests: XCTestCase { + + func testAdvancedPagesHiddenByDefault() { + let panes = Pane.sidebarSections(advancedToolsEnabled: false).flatMap { $0 } + XCTAssertFalse(panes.contains(where: \.isAdvanced)) + XCTAssertEqual(Pane.sidebarSections(advancedToolsEnabled: false).count, 2) + } + + func testAdvancedSectionSitsBetweenEverydayPagesAndSettings() { + let sections = Pane.sidebarSections(advancedToolsEnabled: true) + XCTAssertEqual(sections.count, 3) + XCTAssertEqual(sections.first?.first, .overview) + XCTAssertTrue(sections[1].allSatisfy(\.isAdvanced)) + XCTAssertEqual(sections.last, [.settings]) + } + + func testEveryPaneIsReachableWhenAdvancedToolsAreOn() { + let listed = Set(Pane.sidebarSections(advancedToolsEnabled: true).flatMap { $0 }) + XCTAssertEqual(listed, Set(Pane.allCases)) + } + + func testResolveStoredFallsBackToOverview() { + XCTAssertEqual(Pane.resolveStored(nil, advancedToolsEnabled: true), .overview) + XCTAssertEqual(Pane.resolveStored("", advancedToolsEnabled: true), .overview) + XCTAssertEqual(Pane.resolveStored("renamedPage", advancedToolsEnabled: true), .overview) + } + + func testResolveStoredKeepsVisiblePages() { + XCTAssertEqual(Pane.resolveStored("network", advancedToolsEnabled: false), .network) + XCTAssertEqual(Pane.resolveStored("interfaces", advancedToolsEnabled: true), .interfaces) + } + + func testResolveStoredDropsHiddenAdvancedPage() { + XCTAssertEqual(Pane.resolveStored("interfaces", advancedToolsEnabled: false), .overview) + } + + /// The persisted raw values are a storage format: renaming one silently + /// resets everyone's selection once. + func testRawValuesAreStable() { + XCTAssertEqual(Pane.allCases.map(\.rawValue), + ["overview", "device", "network", "activity", "interfaces", "settings"]) + } +} diff --git a/gui/Tests/TetherKitNextUIModelTests/SessionFailureTests.swift b/gui/Tests/TetherKitNextUIModelTests/SessionFailureTests.swift new file mode 100644 index 0000000..e448ff5 --- /dev/null +++ b/gui/Tests/TetherKitNextUIModelTests/SessionFailureTests.swift @@ -0,0 +1,47 @@ +import XCTest + +@testable import TetherKitNextUIModel + +/// Classification of fatal session messages. +/// +/// Only the libusb error name decides the cause; the surrounding context is +/// localized and must not matter. +final class SessionFailureTests: XCTestCase { + + func testLibusbErrorNamesPickTheCause() { + XCTAssertEqual(SessionFailureCause( + fatalMessage: "bulk IN transfer failed [libusb: LIBUSB_ERROR_NO_DEVICE(-4)]"), .disconnected) + XCTAssertEqual(SessionFailureCause( + fatalMessage: "failed to claim data interface [libusb: LIBUSB_ERROR_ACCESS(-3)]"), .accessDenied) + XCTAssertEqual(SessionFailureCause( + fatalMessage: "failed to claim data interface [libusb: LIBUSB_ERROR_BUSY(-6)]"), .busy) + XCTAssertEqual(SessionFailureCause( + fatalMessage: "3 consecutive keep-alive failures; treating the link as dead: " + + "[libusb: LIBUSB_ERROR_TIMEOUT(-7)]"), .timedOut) + } + + func testLocalizedContextDoesNotMatter() { + XCTAssertEqual(SessionFailureCause( + fatalMessage: "连续 3 次保活失败,判定链路已死 [libusb: LIBUSB_ERROR_NO_DEVICE(-4)]"), + .disconnected) + } + + func testUnplugDuringKeepAliveCountsAsDisconnected() { + // The keep-alive context mentions a timeout in words; the error name wins. + XCTAssertEqual(SessionFailureCause( + fatalMessage: "keep-alive timed out [libusb: LIBUSB_ERROR_NO_DEVICE(-4)]"), .disconnected) + } + + func testUnknownMessagesFallBackToOther() { + XCTAssertEqual(SessionFailureCause(fatalMessage: "failed to create feth pair"), .other) + XCTAssertEqual(SessionFailureCause(fatalMessage: ""), .other) + // Words alone never classify: only the libusb name does. + XCTAssertEqual(SessionFailureCause(fatalMessage: "permission denied"), .other) + } + + func testFailureKeepsTheRawMessage() { + let failure = SessionFailure(message: "x [libusb: LIBUSB_ERROR_BUSY(-6)]") + XCTAssertEqual(failure.message, "x [libusb: LIBUSB_ERROR_BUSY(-6)]") + XCTAssertEqual(failure.cause, .busy) + } +} diff --git a/include/tetherkitnext/capi/tetherkitnext_c.h b/include/tetherkitnext/capi/tetherkitnext_c.h index 15b5385..1541e90 100644 --- a/include/tetherkitnext/capi/tetherkitnext_c.h +++ b/include/tetherkitnext/capi/tetherkitnext_c.h @@ -1,36 +1,37 @@ -// TetherKitNext's C ABI -- the **only** `extern "C"` boundary in the whole project. +// TetherKitNext's C ABI: the only `extern "C"` boundary in the project. // -// Reason for existing: Swift's C++ interop cannot swallow this project's C++23 interfaces (`std::expected`, -// `std::span`, abstract base classes, move semantics), so the GUI cannot call the C++ layer directly. This layer translates those -// types into "plain PODs + opaque handles", so Swift, Objective-C, and even other languages can use it. +// Swift's C++ interop cannot consume this project's C++23 interfaces (`std::expected`, `std::span`, +// abstract base classes, move semantics), so this layer translates them into plain PODs and opaque +// handles that Swift, Objective-C and other languages can use. // -// * Design conventions (follow them and nothing goes wrong) * +// Design rules: // -// 1. **No ownership crosses the boundary.** All outputs are written into fixed-size structs provided by the caller, and the library does not -// allocate memory internally that the caller has to free. The only exception is the opaque handle `tk_session_t`, -// which is created by `tk_session_create` and destroyed by `tk_session_destroy`, a clearly paired lifecycle. +// 1. No ownership crosses the boundary. Outputs are written into fixed-size structs provided by +// the caller; the library never allocates memory the caller must free. The one exception is +// the opaque handle `tk_session_t`, paired by `tk_session_create` / `tk_session_destroy`. // -// 2. **No callbacks; use an event queue.** The underlying observer callbacks come from the libusb event thread and the control -// thread, so the Swift side would have to marshal across threads; worse still is reentrancy -- calling stop from inside a callback -// is a self-wait deadlock (`Stop()` has to join the control thread). So everything is turned into "queue inside the library, host polls". -// Logs are the same; see `tk_drain_logs`. +// 2. No callbacks; use an event queue. Observer callbacks come from the libusb event thread and +// the control thread, so a Swift callback would need cross-thread marshalling, and calling +// stop from inside a callback is a self-wait deadlock (`Stop()` joins the control thread). +// Events and logs are queued inside the library and polled by the host (`tk_drain_logs`). // -// 3. **All functions return `tk_result_t` (0 for success, negative for failure)**, and the failure cause is written into -// an optional `tk_error_t*`. Passing NULL means you do not care about the cause. No errno and no thread-local -// last-error is used -- both are easy to misread in a multi-threaded host. +// 3. Every function returns `tk_result_t` (0 for success, negative for failure) and writes the +// cause into an optional `tk_error_t*` (NULL means the cause is not needed). No errno and no +// thread-local last-error, both easy to misread in a multi-threaded host. // -// 4. **Strings are always fixed-size UTF-8 buffers, NUL-terminated**, truncated rather than failing when capacity is insufficient. -// Truncation affects only display, not functionality, and is much simpler than making the caller handle a two-call length negotiation. +// 4. Strings are fixed-size, NUL-terminated UTF-8 buffers, truncated rather than failing when +// capacity is insufficient. Truncation only affects display, and avoids a two-call length +// negotiation. // -// * Privileges (which functions need root) * +// Privileges: // -// No root needed: `tk_version`, `tk_check_environment`, `tk_list_devices`, -// `tk_drain_logs`, `tk_net_query` -// Root needed : `tk_session_*` (creates feth, opens /dev/bpf*), `tk_net_apply`, -// `tk_net_clear`, `tk_cleanup_orphan_interfaces` +// No root needed: `tk_version`, `tk_check_environment`, `tk_list_devices`, `tk_drain_logs`, +// `tk_net_query` +// Root needed: `tk_session_*` (creates feth, opens /dev/bpf*), `tk_net_apply`, +// `tk_net_clear`, `tk_cleanup_orphan_interfaces` // -// The GUI's approach: the App itself only calls the ones that need no root, and hands the ones that need root to -// `tetherkitnext-helper` (launched by launchd as root). See docs/GUI-ARCHITECTURE.md for details. +// The App itself only calls the functions that need no root and hands the rest to +// `tetherkitnext-helper` (launched by launchd as root). See docs/GUI-ARCHITECTURE.md. #ifndef TETHERKITNEXT_CAPI_TETHERKITNEXT_C_H_ #define TETHERKITNEXT_CAPI_TETHERKITNEXT_C_H_ @@ -51,11 +52,13 @@ extern "C" { // ============================================================================= // Capacity constants // -// The reason capacities are hard-coded in the header rather than having the caller negotiate lengths: these structs are mapped directly by Swift -// into structs and copied by value, and only fixed sizes eliminate all memory management. The values all leave ample margin. +// The reason capacities are hard-coded in the header rather than having the caller negotiate +// lengths: these structs are mapped directly by Swift into structs and copied by value, and only +// fixed sizes eliminate all memory management. The values all leave ample margin. // ============================================================================= -/// Capacity of the error message buffer. Underlying error strings carry multi-line "what to do next" hints; 1 KiB is enough. +/// Capacity of the error message buffer. Underlying error strings carry multi-line "what to do +/// next" hints; 1 KiB is enough. #define TK_ERROR_MESSAGE_CAPACITY 1024 /// Capacity of a NIC name. Aligned with the kernel's IFNAMSIZ (16, including the terminator). #define TK_INTERFACE_NAME_CAPACITY 16 @@ -75,16 +78,18 @@ extern "C" { // ============================================================================= typedef enum tk_result { - TK_OK = 0, ///< Success. - TK_ERR_INVALID_ARGUMENT = -1, ///< Invalid argument (null pointer, out-of-range enum, malformed address). - TK_ERR_INVALID_STATE = -2, ///< The operation is not allowed in the current state (such as a repeated start). - TK_ERR_FAILED = -3, ///< The underlying operation failed; see tk_error_t for details. - TK_ERR_PERMISSION = -4, ///< Root is needed but the process is not root. - TK_ERR_NOT_FOUND = -5, ///< The target does not exist (no device, no such NIC). + TK_OK = 0, ///< Success. + /// Invalid argument (null pointer, out-of-range enum, malformed address). + TK_ERR_INVALID_ARGUMENT = -1, + /// The operation is not allowed in the current state (such as a repeated start). + TK_ERR_INVALID_STATE = -2, + TK_ERR_FAILED = -3, ///< The underlying operation failed; see tk_error_t for details. + TK_ERR_PERMISSION = -4, ///< Root is needed but the process is not root. + TK_ERR_NOT_FOUND = -5, ///< The target does not exist (no device, no such NIC). } tk_result_t; -/// The source domain of an error code, which determines how the `code` field is interpreted. It and the C++ side's `tetherkitnext::ErrorDomain` -/// correspond one-to-one. +/// The source domain of an error code, which determines how the `code` field is interpreted. It and +/// the C++ side's `tetherkitnext::ErrorDomain` correspond one-to-one. typedef enum tk_error_domain { TK_ERROR_DOMAIN_GENERIC = 0, ///< Pure logic error; `code` is meaningless. TK_ERROR_DOMAIN_ERRNO = 1, ///< POSIX errno. @@ -92,7 +97,8 @@ typedef enum tk_error_domain { TK_ERROR_DOMAIN_RNDIS = 3, ///< RNDIS_STATUS_*. } tk_error_domain_t; -/// A complete description of a failure. `message` is already text that can be shown directly to the user, in the current interface language. +/// A complete description of a failure. `message` is already text that can be shown directly to the +/// user, in the current interface language. typedef struct tk_error { int32_t domain; ///< tk_error_domain_t int64_t code; @@ -102,11 +108,13 @@ typedef struct tk_error { // ============================================================================= // Interface language // -// All text the library itself produces -- error messages, log lines, event text -- is rendered in the language set here. -// The host (the GUI) is responsible for pushing the user's choice in; the command line decides by environment variables and --lang itself. +// All text the library itself produces: error messages, log lines, event text: is rendered in the +// language set here. The host (the GUI) is responsible for pushing the user's choice in; the +// command line decides by environment variables and --lang itself. // -// **A single process-wide state**, not one per session: logs and errors are produced from multiple threads, and making it -// thread-local would only make the output of a single session appear in two languages. +// **A single process-wide state**, not one per session: logs and errors are produced from multiple +// threads, and making it thread-local would only make the output of a single session appear in two +// languages. // ============================================================================= typedef enum tk_language { @@ -116,18 +124,21 @@ typedef enum tk_language { /// Sets the interface language. Callable from any thread, at any time. /// -/// Takes effect immediately, but **logs and events already queued are not re-rendered** -- they were already -/// strings at the moment they were produced. The GUI should call it as early as possible at startup, and afterwards only when the user switches language. -/// Ignores the call when `language` is out of range. +/// Takes effect immediately, but **logs and events already queued are not re-rendered**; they were +/// already strings at the moment they were produced. The GUI should call it as early as possible at +/// startup, and afterwards only when the user switches language. Ignores the call when `language` +/// is out of range. TK_API void tk_set_language(int32_t language); /// Reads the current interface language (tk_language_t). TK_API int32_t tk_get_language(void); -/// Infers the language from environment variables, checking in order TETHERKITNEXT_LANG, LC_ALL, LC_MESSAGES, LANG. +/// Infers the language from environment variables, checking in order TETHERKITNEXT_LANG, LC_ALL, +/// LC_MESSAGES, LANG. /// -/// **Only infers; does not change the current setting.** The GUI usually has no use for it (macOS language preferences should be asked of -/// NSLocale); it is prepared for command-line hosts and third-party bindings. +/// **Only infers; does not change the current setting.** The GUI usually has no use for it (macOS +/// language preferences should be asked of NSLocale); it is prepared for command-line hosts and +/// third-party bindings. TK_API int32_t tk_detect_system_language(void); // ============================================================================= @@ -140,9 +151,9 @@ typedef struct tk_version_info { uint16_t patch; /// In the form "TetherKitNext 0.1.1 (C++23, macOS 13.3+)". char text[64]; - /// Build configuration description, in the form "build 1a2b3c4d5e, RelWithDebInfo, AppleClang 21.0.0, ...". - /// The leading build ID (git commit) distinguishes builds that share a - /// version number; the app compares it with the background daemon's. + /// Build configuration description, in the form "build 1a2b3c4d5e, RelWithDebInfo, AppleClang + /// 21.0.0, ...". The leading build ID (git commit) distinguishes builds that share a version + /// number; the app compares it with the background daemon's. char build[192]; /// libusb version string. char libusb[64]; @@ -150,23 +161,26 @@ typedef struct tk_version_info { TK_API void tk_version(tk_version_info_t* out_version); -/// Environment preflight result. The GUI shows it before startup, explaining "why it cannot run" up front. +/// Environment preflight result. The GUI shows it before startup, explaining "why it cannot run" up +/// front. typedef struct tk_environment { /// Whether the current process runs as root. bool is_root; /// Whether feth's creation-time sysctls are all at the values we require. /// - /// These switches (hwcsum / fcs / tso_support / lro / trailer_length / - /// separate_frame_header) are **creation-time snapshots**; changing them after creation has no effect, so they must be checked in advance. + /// These switches (hwcsum / fcs / tso_support / lro / trailer_length / separate_frame_header) are + /// **creation-time snapshots**; changing them after creation has no effect, so they must be + /// checked in advance. bool sysctls_ok; /// Specific explanation when the sysctls are unacceptable; an empty string when acceptable. char sysctl_detail[TK_ERROR_MESSAGE_CAPACITY]; - /// The upper limit of MTU supported by feth (sysctl net.link.fake.max_mtu). 0 when the query fails. + /// The upper limit of MTU supported by feth (sysctl net.link.fake.max_mtu). 0 when the query + /// fails. uint32_t feth_max_mtu; } tk_environment_t; -/// Collects environment information. **This function always returns TK_OK** -- "the environment is unacceptable" is not a call failure, -/// but a result to be shown to the user. +/// Collects environment information. **This function always returns TK_OK**: "the environment is +/// unacceptable" is not a call failure, but a result to be shown to the user. TK_API tk_result_t tk_check_environment(tk_environment_t* out_environment); // ============================================================================= @@ -187,12 +201,15 @@ typedef struct tk_device_info { uint8_t interface_class; uint8_t interface_subclass; uint8_t interface_protocol; - /// Whether the Android quirk fallback path was taken (when the CDC Union descriptor is untrustworthy). + /// Whether the Android quirk fallback path was taken (when the CDC Union descriptor is + /// untrustworthy). bool used_android_quirk; /// The following three string descriptors are **best effort**: reading them needs libusb_open, - /// and the device may already be held exclusively by another process on this machine. When they cannot be read this time, the value most recently - /// read successfully **within this process** is filled back (the device has not changed, so its name should not vanish just because it is occupied); only - /// if there is not even a previous value is it an empty string, in which case the GUI should fall back to showing `description` (the VID:PID form). + /// and the device may already be held exclusively by another process on this Mac. When they + /// cannot be read this time, the value most recently read successfully **within this process** is + /// filled back (the device has not changed, so its name should not vanish just because it is + /// occupied); only if there is not even a previous value is it an empty string, in which case the + /// GUI should fall back to showing `description` (the VID:PID form). char manufacturer[TK_USB_STRING_CAPACITY]; char product[TK_USB_STRING_CAPACITY]; char serial[TK_USB_STRING_CAPACITY]; @@ -202,13 +219,18 @@ typedef struct tk_device_info { /// Enumerates the currently connected RNDIS devices. /// -/// @param out_devices Array provided by the caller; may be NULL (in which case only the count is computed). -/// @param capacity Array capacity. When more devices are actually found than the capacity, only the first capacity are filled. -/// @param out_count Receives the total number of devices actually found (may be greater than capacity). -/// @param read_strings Whether to try reading the vendor name / product name / serial number. This needs +/// @param out_devices Array provided by the caller; may be NULL (in which case only the count is +/// computed). +/// @param capacity Array capacity. When more devices are actually found than the capacity, +/// only the first capacity are filled. +/// @param out_count Receives the total number of devices actually found (may be greater than +/// capacity). +/// @param read_strings Whether to try reading the vendor name / product name / serial number. +/// This needs /// libusb_open, and fails when the device is already occupied (not fatal). -/// Passing false is recommended when refreshing the list while a session is running -- whether skipped or -/// failed to read, the value most recently read successfully within this process is filled back, so the name does not +/// Passing false is recommended when refreshing the list while a session is +/// running: whether skipped or failed to read, the value most recently read +/// successfully within this process is filled back, so the name does not /// become an empty string because of that. TK_API tk_result_t tk_list_devices(tk_device_info_t* out_devices, size_t capacity, size_t* out_count, bool read_strings, tk_error_t* out_error); @@ -228,8 +250,8 @@ typedef enum tk_log_level { typedef struct tk_log_record { int32_t level; ///< tk_log_level_t - /// Wall-clock time (nanoseconds since the Unix epoch). Wall time is used rather than monotonic time: logs must be able to line up with the system - /// log. + /// Wall-clock time (nanoseconds since the Unix epoch). Wall time is used rather than monotonic + /// time: logs must be able to line up with the system log. int64_t wall_nanos; char thread[TK_THREAD_NAME_CAPACITY]; char message[TK_TEXT_CAPACITY]; @@ -239,15 +261,17 @@ TK_API void tk_set_log_level(int32_t level); /// Opens / closes log capture. /// -/// **Off** by default -- command-line programs do not need it, and leaving it on wastes an extra copy. The GUI host calls -/// `tk_enable_log_capture(true)` at startup, and afterwards periodically `tk_drain_logs` to take them away. +/// **Off** by default: command-line programs do not need it, and leaving it on wastes an extra +/// copy. The GUI host calls `tk_enable_log_capture(true)` at startup, and afterwards periodically +/// `tk_drain_logs` to take them away. TK_API void tk_enable_log_capture(bool enabled); -/// Takes away buffered log lines (first in, first out), returning the number actually taken. +/// Drains buffered log lines (first in, first out), returning the number actually taken. /// -/// The buffer is a fixed-size ring queue; when full, it discards the **oldest** records -- keeping the latest scene when the host is stuck -/// is more useful than keeping the beginning. The number of dropped records is reported through `out_dropped`, and the GUI can use it to show -/// "the log has gaps". +/// The buffer is a fixed-size ring queue; when full, it discards the **oldest** records; keeping +/// the latest scene when the host is stuck is more useful than keeping the beginning. The number of +/// dropped records is reported through `out_dropped`, and the GUI can use it to show "the log has +/// gaps". TK_API size_t tk_drain_logs(tk_log_record_t* out_records, size_t capacity, uint64_t* out_dropped); @@ -255,7 +279,8 @@ TK_API size_t tk_drain_logs(tk_log_record_t* out_records, size_t capacity, // Sessions (root needed) // ============================================================================= -/// RNDIS host-side state, corresponding one-to-one with the C++ side's `tetherkitnext::rndis::State`. +/// RNDIS host-side state, corresponding one-to-one with the C++ side's +/// `tetherkitnext::rndis::State`. typedef enum tk_rndis_state { TK_RNDIS_UNINITIALIZED = 0, TK_RNDIS_INITIALIZING = 1, @@ -266,26 +291,30 @@ typedef enum tk_rndis_state { /// The lifecycle state of a session. This is the state the GUI's main screen binds to directly. typedef enum tk_run_state { - TK_RUN_IDLE = 0, ///< Created, not yet started. - TK_RUN_STARTING = 1, ///< Running the startup sequence (enumerate -> handshake -> create NIC -> open bridge). + TK_RUN_IDLE = 0, ///< Created, not yet started. + /// Running the startup sequence (enumerate -> handshake -> create NIC -> open bridge). + TK_RUN_STARTING = 1, TK_RUN_RUNNING = 2, ///< The data path is up and running. TK_RUN_STOPPING = 3, TK_RUN_STOPPED = 4, - TK_RUN_FAILED = 5, ///< Startup failed or an unrecoverable error occurred while running; see status.fatal for the cause. + /// Startup failed or an unrecoverable error occurred while running; see status.fatal for the + /// cause. + TK_RUN_FAILED = 5, } tk_run_state_t; -/// Session configuration. Fill in the defaults with `tk_session_config_init` and then change the fields that need changing -- -/// initializing directly with `{0}` gives a bunch of invalid zeros. +/// Session configuration. Fill in the defaults with `tk_session_config_init` and then change the +/// fields that need changing; initializing directly with `{0}` gives a bunch of invalid zeros. typedef struct tk_session_config { /// Device filter. All 0 means use the first RNDIS device found. uint16_t vendor_id; uint16_t product_id; - /// Match only the specified address on the specified bus (both must be given together). Used to tell apart two devices of the same model. + /// Match only the specified address on the specified bus (both must be given together). Used to + /// tell apart two devices of the same model. uint8_t bus_number; uint8_t device_address; - /// The desired MTU. Lowered by negotiation when the device cannot fit it; the upper limit is constrained by feth's - /// sysctl net.link.fake.max_mtu. + /// The desired MTU. Lowered by negotiation when the device cannot fit it; the upper limit is + /// constrained by feth's sysctl net.link.fake.max_mtu. uint32_t mtu; /// Whether to set the system-side NIC's MAC to the address the device reported. On by default. bool adopt_device_mac; @@ -295,8 +324,8 @@ typedef struct tk_session_config { uint32_t tx_transfer_count; /// KiB per bulk IN buffer. uint32_t rx_transfer_kib; - /// The MaxTransferSize claimed in INITIALIZE_MSG (KiB). This is the only means of getting the device to aggregate multiple packets, - /// and also the main lever for throughput. + /// The MaxTransferSize claimed in INITIALIZE_MSG (KiB). This is the only means of getting the + /// device to aggregate multiple packets, and also the main lever for throughput. uint32_t max_transfer_kib; /// KiB of the BPF kernel capture buffer. uint32_t bpf_buffer_kib; @@ -307,7 +336,8 @@ TK_API void tk_session_config_init(tk_session_config_t* out_config); /// Session events. typedef enum tk_event_kind { - /// RNDIS state transition. `a` = state before the transition, `b` = state after (both tk_rndis_state_t). + /// RNDIS state transition. `a` = state before the transition, `b` = state after (both + /// tk_rndis_state_t). TK_EVENT_RNDIS_STATE = 0, /// Negotiation complete. `a` = final MTU, `b` = link speed (Mbps). TK_EVENT_NEGOTIATED = 1, @@ -329,7 +359,8 @@ typedef struct tk_event { char text[TK_TEXT_CAPACITY]; } tk_event_t; -/// A complete snapshot of the data path and link. The GUI pulls it periodically (500 ms~1 s recommended) to refresh the UI. +/// A complete snapshot of the data path and link. The GUI pulls it periodically (500 ms~1 s +/// recommended) to refresh the UI. typedef struct tk_session_status { int32_t run_state; ///< tk_run_state_t int32_t rndis_state; ///< tk_rndis_state_t @@ -338,7 +369,8 @@ typedef struct tk_session_status { /// System-side NIC name (the host configures IP on this one). An empty string when not created. char system_interface[TK_INTERFACE_NAME_CAPACITY]; - /// Driver-side NIC name (TetherKitNext's BPF attaches to this one). For troubleshooting display only. + /// Driver-side NIC name (TetherKitNext's BPF attaches to this one). For troubleshooting display + /// only. char driver_interface[TK_INTERFACE_NAME_CAPACITY]; /// The permanent MAC reported by the device. All 0 when not negotiated. @@ -353,7 +385,8 @@ typedef struct tk_session_status { char device_description[64]; /// Cumulative counters (RX = device -> host, TX = host -> device). - /// Rates are computed by the GUI itself as the difference of two snapshots; the library does no window smoothing. + /// Rates are computed by the GUI itself as the difference of two snapshots; the library does no + /// window smoothing. uint64_t rx_frames; uint64_t rx_bytes; uint64_t rx_dropped; @@ -367,12 +400,17 @@ typedef struct tk_session_status { /// Number of backpressure events caused by the TX transfer pool having no free slot. uint64_t tx_backpressure; - /// Monotonic nanosecond count at the sampling moment. The GUI uses it to compute rates; do not use your own clock -- - /// the real interval between two pulls may be stretched by scheduling. + /// Monotonic nanosecond count at the sampling moment. The GUI uses it to compute rates; do not + /// use your own clock: the real interval between two pulls may be stretched by scheduling. int64_t monotonic_nanos; /// The cause when run_state == TK_RUN_FAILED; otherwise an empty string. char fatal[TK_ERROR_MESSAGE_CAPACITY]; + + /// The device's own IPv4 address in dotted form, learned passively from frames only it can have + /// sent (ARP, link-scoped broadcast/multicast). Empty until seen. Lets the GUI find devices that + /// have a fixed address and no DHCP server (drones, controllers, gadget-mode boards). + char peer_ipv4[16]; } tk_session_status_t; /// Opaque session handle. @@ -381,20 +419,24 @@ typedef struct tk_session tk_session_t; /// Creates a session. **Does no I/O**, just records the configuration. TK_API tk_session_t* tk_session_create(const tk_session_config_t* config, tk_error_t* out_error); -/// Starts a session. **Non-blocking**: internally starts a control thread to run the startup sequence and the keepalive loop, and this function returns immediately. +/// Starts a session. **Non-blocking**: internally starts a control thread to run the startup +/// sequence and the keepalive loop, and this function returns immediately. /// -/// Returning TK_OK only means "the start request has been accepted"; real success or failure must be observed through the run_state of `tk_session_status` -/// and the event queue. It is designed this way because the startup sequence includes a USB handshake, which on slow devices -/// may take hundreds of milliseconds to several seconds, and blocking the GUI main thread is unacceptable. +/// Returning TK_OK only means "the start request has been accepted"; real success or failure must +/// be observed through the run_state of `tk_session_status` and the event queue. It is designed +/// this way because the startup sequence includes a USB handshake, which on slow devices may take +/// hundreds of milliseconds to several seconds, and blocking the GUI main thread is unacceptable. /// -/// The control channel must run on a **non-libusb-event thread** (the synchronous API returns on the event thread -/// LIBUSB_ERROR_BUSY); the library guarantees this internally, and callers need not care about threads. +/// The control channel must run on a **non-libusb-event thread** (the synchronous API returns on +/// the event thread LIBUSB_ERROR_BUSY); the library guarantees this internally, and callers need +/// not care about threads. TK_API tk_result_t tk_session_start(tk_session_t* session, tk_error_t* out_error); /// Requests shutdown and waits for the control thread to exit. Idempotent. /// -/// WARNING: **Must not be called from a callback of event polling** -- this function joins the control thread. The C ABI layer -/// has no callbacks, so it is fine as long as the caller does not hold, inside its own event handling, a lock that could cause reentrancy. +/// WARNING: **Must not be called from a callback of event polling**; this function joins the +/// control thread. The C ABI layer has no callbacks, so it is fine as long as the caller does not +/// hold, inside its own event handling, a lock that could cause reentrancy. TK_API tk_result_t tk_session_stop(tk_session_t* session); /// Stops and destroys. Passing NULL is a no-op. @@ -403,10 +445,11 @@ TK_API void tk_session_destroy(tk_session_t* session); /// Takes a state snapshot. Callable from any thread. TK_API tk_result_t tk_session_status_get(tk_session_t* session, tk_session_status_t* out_status); -/// Takes away queued events (first in, first out), returning the number actually taken. +/// Drains queued events (first in, first out), returning the number actually taken. /// -/// Like logs, it is a fixed-size ring queue that drops the oldest when full. The GUI missing a few state-transition events does not affect correctness -/// -- the authoritative state is always the `tk_session_status_get` snapshot, and events are only used for animation and hints. +/// Like logs, it is a fixed-size ring queue that drops the oldest when full. The GUI missing a few +/// state-transition events does not affect correctness; the authoritative state is always the +/// `tk_session_status_get` snapshot, and events are only used for animation and hints. TK_API size_t tk_session_poll_events(tk_session_t* session, tk_event_t* out_events, size_t capacity); @@ -416,12 +459,14 @@ TK_API size_t tk_session_poll_events(tk_session_t* session, tk_event_t* out_even /// Connection method. typedef enum tk_ip_mode { - /// Hand it to the system's IPConfiguration to run DHCP. It automatically does four things: get a lease, configure - /// scoped DNS, install a scoped default route, and publish the service to the dynamic store. + /// Hand it to the system's IPConfiguration to run DHCP. It automatically does four things: get a + /// lease, configure scoped DNS, install a scoped default route, and publish the service to the + /// dynamic store. TK_IP_MODE_DHCP = 0, - /// Static IP. The address is still applied through IPConfiguration (rather than a bare SIOCAIFADDR), - /// so that a service "registered through the proper path" is obtained -- hand-writing entries into the dynamic store is - /// **not adopted by IPMonitor**, which has been confirmed by measurement. + /// Static IP. The address is still applied through IPConfiguration (rather than a bare + /// SIOCAIFADDR), so that a service "registered through the proper path" is obtained; hand-writing + /// entries into the dynamic store is **not adopted by IPMonitor**, which has been confirmed by + /// measurement. TK_IP_MODE_MANUAL = 1, /// Revokes the configuration (equivalent to `ipconfig set NONE`). TK_IP_MODE_NONE = 2, @@ -440,10 +485,11 @@ typedef struct tk_ip_config { /// Whether to point the **global** default route at this NIC as well. /// - /// When off there is only one scoped default route (`RTF_IFSCOPE`), which traffic bound to this interface uses, - /// while unbound traffic still goes through the system's primary service. It only needs to be turned on when a higher-priority connected service (Wi-Fi, - /// VPN) exists at the same time -- the typical USB tethering scenario is precisely that no other network is available, - /// in which case this NIC is naturally the primary service, and this switch need not be touched. + /// When off there is only one scoped default route (`RTF_IFSCOPE`), which traffic bound to this + /// interface uses, while unbound traffic still goes through the system's primary service. It only + /// needs to be turned on when a higher-priority connected service (Wi-Fi, VPN) exists at the same + /// time; the typical USB tethering scenario is precisely that no other network is available, in + /// which case this NIC is naturally the primary service, and this switch need not be touched. bool set_default_route; } tk_ip_config_t; @@ -452,8 +498,9 @@ TK_API void tk_ip_config_init(tk_ip_config_t* out_config); /// The IP state that the NIC **actually has in effect** at present. /// -/// Deliberately does not restate "what we applied" but reads back the system state: in static mode, whether DNS takes effect -/// depends on whether IPMonitor accepts this service, and only a readback gives the user accurate feedback. +/// Does not restate "what we applied" but reads back the system state: in static mode, whether DNS +/// takes effect depends on whether IPMonitor accepts this service, and only a readback gives the +/// user accurate feedback. typedef struct tk_net_state { bool has_address; char address[TK_ADDRESS_CAPACITY]; @@ -488,9 +535,10 @@ TK_API tk_result_t tk_net_query(const char* interface_name, tk_net_state_t* out_ /// Destroys feth interfaces left in the kernel after a process was forcibly killed. /// -/// Why it is needed: when a process is SIGKILLed, C++ destructors do not run and the feth stays in the kernel; signal -/// handlers cannot intercept SIGKILL, so the only option is a **backstop cleanup on the next launch**. When a session creates a feth, -/// it records the interface name into `/var/run/tetherkitnext-interfaces`, and this function reads it and destroys them one by one. +/// Why it is needed: when a process is SIGKILLed, C++ destructors do not run and the feth stays in +/// the kernel; signal handlers cannot intercept SIGKILL, so the only option is a **backstop cleanup +/// on the next launch**. When a session creates a feth, it records the interface name into +/// `/var/run/tetherkitnext-interfaces`, and this function reads it and destroys them one by one. /// /// @param out_removed Receives the number of interfaces actually destroyed; may be NULL. TK_API tk_result_t tk_cleanup_orphan_interfaces(size_t* out_removed, tk_error_t* out_error); diff --git a/include/tetherkitnext/common/byte_order.h b/include/tetherkitnext/common/byte_order.h index 36c0957..0c43b2a 100644 --- a/include/tetherkitnext/common/byte_order.h +++ b/include/tetherkitnext/common/byte_order.h @@ -1,15 +1,17 @@ // Wire-format byte order reads and writes. // -// The RNDIS wire format is **fixed little-endian** (the protocol originates from Windows NDIS), while fields such as -// EtherType in the Ethernet frame header are big-endian. Both are needed, so both Le/Be families of functions are provided here. +// The RNDIS wire format is **fixed little-endian** (the protocol originates from Windows NDIS), +// while fields such as EtherType in the Ethernet frame header are big-endian. Both are needed, so +// both Le/Be families of functions are provided here. // // Implementation notes: -// * Everything goes through std::memcpy rather than pointer casts, avoiding the undefined behavior of unaligned accesses -- -// the start offset of an RNDIS message in the USB transfer buffer is only guaranteed to be 4-byte aligned, and -// the start offset of the Ethernet frame right after REMOTE_NDIS_PACKET_MSG can be arbitrary. -// clang optimizes "memcpy into a local variable + byteswap" into a single ldr/rev instruction, -// so this is a zero-cost abstraction. -// * std::endian is used to branch at compile time, so it is also correct on big-endian hosts (although macOS has none). +// * Everything goes through std::memcpy rather than pointer casts, avoiding the undefined +// behavior of unaligned accesses; the start offset of an RNDIS message in the USB transfer +// buffer is only guaranteed to be 4-byte aligned, and the start offset of the Ethernet frame +// right after REMOTE_NDIS_PACKET_MSG can be arbitrary. clang optimizes "memcpy into a local +// variable + byteswap" into a single ldr/rev instruction, so this is a zero-cost abstraction. +// * std::endian is used to branch at compile time, so it is also correct on big-endian hosts +// (although macOS has none). #pragma once #include @@ -65,7 +67,8 @@ inline void StoreBe(std::byte* dst, T value) noexcept { std::memcpy(dst, &value, sizeof(T)); } -// Convenience aliases for common widths, so protocol-parsing code reads closer to the field types in the spec documents. +// Convenience aliases for common widths, so protocol-parsing code reads closer to the field types +// in the spec documents. [[nodiscard]] inline std::uint16_t LoadLe16(const std::byte* p) noexcept { return LoadLe(p); } diff --git a/include/tetherkitnext/common/cache.h b/include/tetherkitnext/common/cache.h index 1bbd11a..4e1e00f 100644 --- a/include/tetherkitnext/common/cache.h +++ b/include/tetherkitnext/common/cache.h @@ -7,16 +7,16 @@ namespace tetherkitnext { /// Cache line size. Hard-coded to 128. /// -/// Why 128: `sysctl hw.cachelinesize` on Apple Silicon reports **128**. -/// With the customary 64-byte alignment, the producer and consumer indices could still land on the same 128-byte -/// cache line, so false sharing would remain -- measured cross-core bouncing raises the per-entry cost of a lock-free queue -/// from single-digit nanoseconds to 60+ nanoseconds. +/// Why 128: `sysctl hw.cachelinesize` on Apple Silicon reports 128. With the customary 64-byte +/// alignment, the producer and consumer indices could still land on the same 128-byte cache line, +/// so false sharing would remain; measured cross-core bouncing raises the per-entry cost of a +/// lock-free queue from single-digit nanoseconds to 60+ nanoseconds. /// -/// Why **not** `std::hardware_destructive_interference_size`: -/// It does exist on Apple libc++ (in ``, `__cpp_lib_hardware_interference_size` -/// = 201703), but it reports **256** (constructive reports 64), which does not match the real 128. -/// Using it would double all the padding, wasting twice the cache and memory for nothing, and would also introduce cross-TU ABI warnings. -/// The measured hardware value is the correct one, so it is hard-coded. +/// Why not `std::hardware_destructive_interference_size`: It does exist on Apple libc++ (in +/// ``, `__cpp_lib_hardware_interference_size` = 201703), but it reports 256 (constructive +/// reports 64), which does not match the real 128. Using it would double all the padding, wasting +/// twice the cache and memory for nothing, and would also introduce cross-TU ABI warnings. The +/// measured hardware value is the correct one, so it is hard-coded. inline constexpr std::size_t kCacheLineSize = 128; /// Alignment specifier that gives a member an entire cache line to itself. diff --git a/include/tetherkitnext/common/error.h b/include/tetherkitnext/common/error.h index a284737..bc1ad85 100644 --- a/include/tetherkitnext/common/error.h +++ b/include/tetherkitnext/common/error.h @@ -1,11 +1,13 @@ // Unified error representation and propagation utilities. // // Layering principle (consistent across the whole project): -// * Initialization path / control path -- propagate errors with Result; the error object carries the source domain, -// the raw error code and a human-readable context string, making it possible to translate "libusb returned -3" into -// "failed to claim the RNDIS data interface: LIBUSB_ERROR_ACCESS (root required)". -// * Data hot path -- **never** use this header. The std::string inside Result allocates heap memory, -// which is unacceptable at 25k~80k pps. The hot path expresses failures with return counts + atomic statistics counters. +// * Initialization path / control path: propagate errors with Result; the error object carries +// the source domain, the raw error code and a human-readable context string, making it possible +// to translate "libusb returned -3" into "failed to claim the RNDIS data interface: +// LIBUSB_ERROR_ACCESS (root required)". +// * Data hot path: **never** use this header. The std::string inside Result allocates heap +// memory, which is unacceptable at 25k~80k pps. The hot path expresses failures with return +// counts + atomic statistics counters. #pragma once #include @@ -22,7 +24,8 @@ namespace detail { /// The separator in "outer cause inner cause", which changes with the current language. /// /// Forward-declared here (implemented in common/i18n.cc) rather than including i18n.h directly: -/// error.h is included by the whole project, and making it drag in and the entire message table is not worthwhile. +/// error.h is included by the whole project, and making it drag in and the entire message +/// table is not worthwhile. [[nodiscard]] std::string_view ContextSeparator() noexcept; } // namespace detail @@ -37,8 +40,9 @@ enum class ErrorDomain : std::uint8_t { /// A complete description of a failure. /// -/// Deliberately a value type rather than an exception: the vast majority of this project's errors are "expected environment problems" -/// (no device plugged in, no root, a kernel driver holding the interface); callers always have to handle them, so they should not propagate via exceptions. +/// A value type rather than an exception: the vast majority of this project's errors are "expected +/// environment problems" (no device plugged in, no root, a kernel driver holding the interface); +/// callers always have to handle them, so they should not propagate via exceptions. class Error { public: Error() = default; @@ -72,13 +76,15 @@ class Error { /// Appends a layer of context to an existing error, forming an "outer cause: inner cause" chain. /// Usage: `return std::unexpected(std::move(e).WithContext(Tr(Msg::kNetOpenBpfFailed)));` /// - /// The separator changes with the language (a full-width colon in Chinese, ": " in English), so it cannot be hard-coded here. + /// The separator changes with the language (a full-width colon in Chinese, ": " in English), so + /// it cannot be hard-coded here. [[nodiscard]] Error WithContext(std::string_view outer) && { context_ = std::string{outer} + std::string{detail::ContextSeparator()} + context_; return std::move(*this); } - /// Renders a readable string like `failed to claim data interface [libusb: LIBUSB_ERROR_ACCESS(-3)]`. + /// Renders a readable string like `failed to claim data interface [libusb: + /// LIBUSB_ERROR_ACCESS(-3)]`. [[nodiscard]] std::string ToString() const; private: @@ -104,7 +110,8 @@ inline Status Ok() noexcept { namespace detail { -// Used to generate unique temporary variable names, avoiding variable shadowing during macro expansion. +// Used to generate unique temporary variable names, avoiding variable shadowing during macro +// expansion. #define TETHERKITNEXT_CONCAT_INNER(a, b) a##b #define TETHERKITNEXT_CONCAT(a, b) TETHERKITNEXT_CONCAT_INNER(a, b) #define TETHERKITNEXT_UNIQUE(base) TETHERKITNEXT_CONCAT(base, __LINE__) @@ -126,7 +133,8 @@ namespace detail { /// /// Usage: `TETHERKITNEXT_ASSIGN_OR_RETURN(auto fd, OpenBpfDevice());` /// -/// `decl` is a declaration rather than an expression and cannot be parenthesized, so the macro-parentheses check is exempted here. +/// `decl` is a declaration rather than an expression and cannot be parenthesized, so the +/// macro-parentheses check is exempted here. // NOLINTNEXTLINE(bugprone-macro-parentheses) #define TETHERKITNEXT_ASSIGN_OR_RETURN(decl, expr) \ auto TETHERKITNEXT_UNIQUE(tk_result_) = (expr); \ diff --git a/include/tetherkitnext/common/frame_ring.h b/include/tetherkitnext/common/frame_ring.h index c18d925..72cca3e 100644 --- a/include/tetherkitnext/common/frame_ring.h +++ b/include/tetherkitnext/common/frame_ring.h @@ -1,8 +1,8 @@ // SPSC lock-free ring queue for variable-length Ethernet frames. // // Difference from SpscRing: Ethernet frames are variable-length (14~2048 bytes), and we want -// **exactly one memory copy along the entire data path**. So this provides a "reserve slot -> write directly -> -// commit" interface, instead of "assemble elsewhere first, then enqueue": +// **exactly one memory copy along the entire data path**. So this provides a "reserve slot -> write +// directly -> commit" interface, instead of "assemble elsewhere first, then enqueue": // // Producer (libusb callback thread) Consumer (BPF write thread) // ------------------------------------ ----------------------------------- @@ -12,14 +12,17 @@ // copy // // Why this one copy is necessary (rather than zero-copy): -// libusb's bulk IN transfer buffer must be resubmitted as soon as possible to keep the USB pipe saturated; if the -// buffer is handed to a downstream holder, far more buffers than the "in-flight transfer count" would have to be prepared, -// and a return mechanism introduced. Measured, a 1500-byte memcpy takes about 40~60 ns on Apple Silicon, while one BPF write() -// system call is 30~50 times that -- the copy is not the bottleneck at all, and going zero-copy for it is the wrong optimization direction. +// libusb's bulk IN transfer buffer must be resubmitted as soon as possible to keep the USB pipe +// saturated; if the buffer is handed to a downstream holder, far more buffers than the "in-flight +// transfer count" would have to be prepared, and a return mechanism introduced. Measured, a +// 1500-byte memcpy takes about 40~60 ns on Apple Silicon, while one BPF write() system call is +// 30~50 times that: the copy is not the bottleneck at all, and going zero-copy for it is the +// wrong optimization direction. // -// Storage layout: `capacity` fixed-size slots, each slot = a cache-line-aligned header (length) + a frame data area. -// Why fixed-size slots rather than a compact arena: an arena has to handle wrap-around splicing across the ring tail, which would turn -// "one write() per frame" into two, making it slower. +// Storage layout: `capacity` fixed-size slots, each slot = a cache-line-aligned header (length) + a +// frame data area. Why fixed-size slots rather than a compact arena: an arena has to handle +// wrap-around splicing across the ring tail, which would turn "one write() per frame" into two, +// making it slower. #pragma once #include @@ -37,10 +40,11 @@ namespace tetherkitnext { /// Maximum size of an Ethernet frame in bytes (excluding FCS). /// -/// Why 2048: feth's `net.link.fake.max_mtu` is 2048, so the MTU upper bound -/// is 2048; adding the 14-byte Ethernet header would nominally be 2062; but an RNDIS device may negotiate a larger +/// Why 2048: feth's `net.link.fake.max_mtu` is 2048, so the MTU upper bound is 2048; adding the +/// 14-byte Ethernet header would nominally be 2062; but an RNDIS device may negotiate a larger /// `OID_GEN_MAXIMUM_FRAME_SIZE`, and power-of-two slot alignment makes address computation easier, -/// so 2048 is simply taken as the frame data area capacity; oversized frames are dropped and counted before enqueueing. +/// so 2048 is simply taken as the frame data area capacity; oversized frames are dropped and +/// counted before enqueueing. inline constexpr std::uint32_t kMaxEthernetFrameBytes = 2048; /// Minimum legal Ethernet frame (destination MAC 6 + source MAC 6 + EtherType 2). @@ -59,8 +63,8 @@ struct FrameView { /// SPSC lock-free bounded queue of variable-length frames. class FrameRing { public: - /// `capacity_frames` is rounded up to a power of two. - /// `max_frame_bytes` is the per-frame limit, defaulting to kMaxEthernetFrameBytes. + /// `capacity_frames` is rounded up to a power of two. `max_frame_bytes` is the per-frame limit, + /// defaulting to kMaxEthernetFrameBytes. explicit FrameRing(std::size_t capacity_frames, std::uint32_t max_frame_bytes = kMaxEthernetFrameBytes) : cursor_(RoundUpToPowerOfTwo(capacity_frames)), @@ -68,9 +72,10 @@ class FrameRing { slot_stride_(ComputeSlotStride(max_frame_bytes)), storage_(AllocateStorage(RoundUpToPowerOfTwo(capacity_frames), ComputeSlotStride(max_frame_bytes))) { - // The storage start is cached after being aligned to a cache line, avoiding recomputing the alignment on every slot access. - // std::align is used instead of integer modulo: the latter needs uintptr_t <-> pointer conversions, which weaken the - // compiler's alias analysis (which is what clang-tidy's performance-no-int-to-ptr is hinting at). + // The storage start is cached after being aligned to a cache line, avoiding recomputing the + // alignment on every slot access. std::align is used instead of integer modulo: the latter + // needs uintptr_t <-> pointer conversions, which weaken the compiler's alias analysis (which is + // what clang-tidy's performance-no-int-to-ptr is hinting at). void* base = storage_.get(); std::size_t space = cursor_.Capacity() * slot_stride_ + kCacheLineSize; void* aligned = std::align(kCacheLineSize, cursor_.Capacity() * slot_stride_, base, space); @@ -97,7 +102,8 @@ class FrameRing { // Producer side // --------------------------------------------------------------------------- - /// Reserves a slot and returns a buffer to which `MaxFrameBytes()` bytes can be written; returns an empty span when the queue is full. + /// Reserves a slot and returns a buffer to which `MaxFrameBytes()` bytes can be written; returns + /// an empty span when the queue is full. /// /// Must be paired with CommitWrite; BeginWrite must not be called again between the two calls. [[nodiscard]] std::span BeginWrite() noexcept { @@ -115,7 +121,8 @@ class FrameRing { NotifyConsumer(); } - /// Convenience entry point: copies an entire frame into the queue. Returns true on success, false if the queue is full or the frame is oversized. + /// Convenience entry point: copies an entire frame into the queue. Returns true on success, false + /// if the queue is full or the frame is oversized. [[nodiscard]] bool TryPush(std::span frame) noexcept { if (frame.size() > max_frame_bytes_) [[unlikely]] { return false; @@ -129,26 +136,24 @@ class FrameRing { return true; } - /// Number of free slots from the producer's point of view. Used before unpacking to decide whether the whole batch fits, avoiding half-batch drops. + /// Number of free slots from the producer's point of view. Used before unpacking to decide + /// whether the whole batch fits, avoiding half-batch drops. [[nodiscard]] std::size_t WritableApprox() noexcept { return cursor_.WritableApprox(); } /// Batch write session. **On the data path, always use this instead of per-frame TryPush.** /// - /// One release store makes the cache line holding the write position bounce across cores once (measured about 60 ns). - /// Publishing per frame makes that a fixed cost per frame; batch publishing amortizes it to 60/N: + /// One release store makes the cache line holding the write position bounce across cores once + /// (measured about 60 ns). Publishing per frame makes that a fixed cost per frame; batch + /// publishing amortizes it to 60/N: /// batch=1 about 63 ns/frame, batch=8 about 5.5 ns/frame, batch=32 about 1.9 ns/frame. /// - /// Usage (unpacking the multiple RNDIS packets of one transfer inside a libusb callback): - /// ``` - /// auto batch = ring.BeginBatchWrite(); - /// while (reader.Next(frame) == ReadOutcome::kFrame) { + /// Usage (unpacking the multiple RNDIS packets of one transfer inside a libusb callback): ``` + /// auto batch = ring.BeginBatchWrite(); while (reader.Next(frame) == ReadOutcome::kFrame) { /// const std::span dst = batch.Begin(); /// if (dst.empty()) { break; } // queue full /// std::memcpy(dst.data(), frame.data(), frame.size()); /// batch.Commit(frame.size()); - /// } - /// // all frames are published at once when batch is destroyed - /// ``` + /// } // all frames are published at once when batch is destroyed ``` class BatchWrite { public: explicit BatchWrite(FrameRing& ring) noexcept : ring_(&ring) {} @@ -161,7 +166,8 @@ class FrameRing { /// Publishes automatically on destruction. Forgetting an explicit Publish will not lose data. ~BatchWrite() { Publish(); } - /// Reserves the next slot and returns a writable buffer; returns an empty span if the queue is full. + /// Reserves the next slot and returns a writable buffer; returns an empty span if the queue is + /// full. [[nodiscard]] std::span Begin() noexcept { if (!ring_->cursor_.TryAcquireWriteAt(staged_, staged_index_)) [[unlikely]] { return {}; @@ -169,7 +175,8 @@ class FrameRing { return {ring_->FrameDataAt(staged_index_), ring_->max_frame_bytes_}; } - /// Records the length of the frame just written. **Performs no atomic operations** -- this is the key to batching. + /// Records the length of the frame just written. **Performs no atomic operations**: this is the + /// key to batching. void Commit(std::uint32_t length) noexcept { assert(length <= ring_->max_frame_bytes_); ring_->StoreLength(staged_index_, length); @@ -190,7 +197,8 @@ class FrameRing { return true; } - /// Publishes all staged frames immediately. May be called early; afterwards this session can keep staging new frames. + /// Publishes all staged frames immediately. May be called early; afterwards this session can + /// keep staging new frames. void Publish() noexcept { if (staged_ != 0) { ring_->cursor_.PublishWrite(staged_); @@ -219,7 +227,8 @@ class FrameRing { // Consumer side // --------------------------------------------------------------------------- - /// Takes a read-only view of the frame at the head; returns a view with length == 0 when the queue is empty. + /// Takes a read-only view of the frame at the head; returns a view with length == 0 when the + /// queue is empty. /// /// The view is valid until the next CommitRead. Must be paired with CommitRead. [[nodiscard]] FrameView BeginRead() noexcept { @@ -233,26 +242,22 @@ class FrameRing { /// Releases the frame at the head. void CommitRead() noexcept { cursor_.PublishRead(); } - /// Number of readable frames from the consumer's point of view. Use it to get the batch size at once during batch consumption. + /// Number of readable frames from the consumer's point of view. Use it to get the batch size at + /// once during batch consumption. [[nodiscard]] std::size_t ReadableApprox() noexcept { return cursor_.ReadableApprox(); } - /// Batch read session. Symmetric to BatchWrite; performs only one release store at the end of the batch. + /// Batch read session. Symmetric to BatchWrite; performs only one release store at the end of the + /// batch. /// - /// This is exactly the shape the BPF write thread wants: take dozens of frames at once, gather them into one BIOCSBATCHWRITE - /// batch write, and then release all slots at once. + /// This is exactly the shape the BPF write thread wants: take dozens of frames at once, gather + /// them into one BIOCSBATCHWRITE batch write, and then release all slots at once. /// - /// Usage: - /// ``` - /// auto batch = ring.BeginBatchRead(); - /// std::vector views; - /// while (views.size() < kMaxBatch) { + /// Usage: ``` auto batch = ring.BeginBatchRead(); std::vector views; while + /// (views.size() < kMaxBatch) { /// const FrameView view = batch.Next(); /// if (view.Empty()) { break; } /// views.push_back(view); // the view is valid until batch is destroyed - /// } - /// link.WriteFrames(views); - /// // all slots are released at once when batch is destroyed - /// ``` + /// } link.WriteFrames(views); // all slots are released at once when batch is destroyed ``` class BatchRead { public: explicit BatchRead(FrameRing& ring) noexcept : ring_(&ring) {} @@ -265,10 +270,12 @@ class FrameRing { /// Releases the taken slots automatically on destruction. ~BatchRead() { Release(); } - /// Takes a read-only view of the next frame; returns a view with length == 0 when there are no more frames. + /// Takes a read-only view of the next frame; returns a view with length == 0 when there are no + /// more frames. /// - /// The returned view is valid **until** this session's Release() (or destruction) -- because the slot has not yet been - /// returned to the producer, its content will not be overwritten. This is the precondition for zero-copy batch writes. + /// The returned view is valid **until** this session's Release() (or destruction), because the + /// slot has not yet been returned to the producer, its content will not be overwritten. This is + /// the precondition for zero-copy batch writes. [[nodiscard]] FrameView Next() noexcept { std::size_t index = 0; if (!ring_->cursor_.TryAcquireReadAt(staged_, index)) [[unlikely]] { @@ -279,7 +286,8 @@ class FrameRing { .length = ring_->LoadLength(index)}; } - /// Releases the taken slots immediately. All previously returned views are invalidated after the call. + /// Releases the taken slots immediately. All previously returned views are invalidated after + /// the call. void Release() noexcept { if (staged_ != 0) { ring_->cursor_.PublishRead(staged_); @@ -309,17 +317,14 @@ class FrameRing { // --------------------------------------------------------------------------- // Consumer parking (eventcount). // - // The consumer used to spin on std::this_thread::yield() while the ring was - // empty. yield() is not a sleep: with no other runnable thread at the same - // priority it returns immediately, so an idle session pinned one core at - // ~100% (upstream XiaoMiku01/TetherKit#5). The consumer now parks on a futex - // (std::atomic::wait -> __ulock_wait) and producers wake it only when it is - // actually parked, so the hot path pays a single fence + relaxed load. + // Spinning on std::this_thread::yield() while the ring is empty would pin a core: yield() is not + // a sleep, and with no other runnable thread at the same priority it returns immediately. The + // consumer therefore parks on a futex (std::atomic::wait -> __ulock_wait) and producers wake it + // only when it is actually parked, so the hot path pays a single fence plus a relaxed load. // - // Correctness is the classic Dekker handshake: the consumer publishes - // `parked = true`, fences, then re-checks the ring; the producer publishes - // the frame, fences, then checks `parked`. With both seq_cst fences at least - // one side observes the other, so a wakeup can never be lost. + // Correctness is the classic Dekker handshake: the consumer publishes `parked = true`, fences, + // then re-checks the ring; the producer publishes the frame, fences, then checks `parked`. With + // both seq_cst fences at least one side observes the other, so a wakeup can never be lost. // --------------------------------------------------------------------------- /// Producer side: wake the consumer if (and only if) it is parked. @@ -330,19 +335,18 @@ class FrameRing { } } - /// Unconditionally wake a parked consumer. Used by producers (via - /// NotifyConsumer) and by the control path to deliver stop/pause requests. + /// Unconditionally wake a parked consumer. Used by producers (via NotifyConsumer) and by the + /// control path to deliver stop/pause requests. /// - /// Callers that want the consumer to observe a flag must store that flag - /// *before* calling Wake(): the release on the doorbell pairs with the - /// acquire in WaitForReadable(). + /// Callers that want the consumer to observe a flag must store that flag *before* calling Wake(): + /// the release on the doorbell pairs with the acquire in WaitForReadable(). void Wake() noexcept { park_.doorbell.fetch_add(1, std::memory_order_release); park_.doorbell.notify_one(); } - /// Consumer side: block until the ring is non-empty, Wake() is called, or - /// `should_abort()` returns true. May return spuriously; callers loop. + /// Consumer side: block until the ring is non-empty, Wake() is called, or `should_abort()` + /// returns true. May return spuriously; callers loop. template void WaitForReadable(AbortPredicate&& should_abort) noexcept { const std::uint32_t ticket = park_.doorbell.load(std::memory_order_acquire); @@ -361,14 +365,15 @@ class FrameRing { [[nodiscard]] std::uint64_t TotalDequeued() const noexcept { return cursor_.TotalDequeued(); } private: - // The two batch session classes need direct access to the cursors and slot addressing, avoiding an extra forwarding layer on the hot path. + // The two batch session classes need direct access to the cursors and slot addressing, avoiding + // an extra forwarding layer on the hot path. friend class BatchWrite; friend class BatchRead; /// In-slot layout: [0, 4) stores the length, [kSlotHeaderBytes, ...) stores the frame data. /// - /// Frame data starts at a kCacheLineSize offset, ensuring each frame's start address is cache-line aligned -- - /// both memcpy and the subsequent write() can take the optimal path. + /// Frame data starts at a kCacheLineSize offset, ensuring each frame's start address is + /// cache-line aligned; both memcpy and the subsequent write() can take the optimal path. static constexpr std::size_t kSlotHeaderBytes = kCacheLineSize; static std::size_t RoundUpToPowerOfTwo(std::size_t requested) noexcept { @@ -379,15 +384,16 @@ class FrameRing { return value; } - /// Slot stride: header + frame data area, rounded up to a cache line, so each slot exclusively owns whole lines. + /// Slot stride: header + frame data area, rounded up to a cache line, so each slot exclusively + /// owns whole lines. static std::size_t ComputeSlotStride(std::uint32_t max_frame_bytes) noexcept { const std::size_t raw = kSlotHeaderBytes + max_frame_bytes; return ((raw + kCacheLineSize - 1) / kCacheLineSize) * kCacheLineSize; } static std::unique_ptr AllocateStorage(std::size_t capacity, std::size_t stride) { - // new[] is used instead of aligned_alloc: the alignment of the whole block's start is handled by AlignedBase below, - // so destruction remains a simple unique_ptr and needs no custom deleter. + // new[] is used instead of aligned_alloc: the alignment of the whole block's start is handled + // by AlignedBase below, so destruction remains a simple unique_ptr and needs no custom deleter. return std::make_unique(capacity * stride + kCacheLineSize); } @@ -411,20 +417,22 @@ class FrameRing { SpscCursor cursor_; - // Read-only after construction; threads on both sides only read, so they can safely share the same cache line. + // Read-only after construction; threads on both sides only read, so they can safely share the + // same cache line. std::uint32_t max_frame_bytes_; std::size_t slot_stride_; std::unique_ptr storage_; std::byte* aligned_base_ = nullptr; - // Index of the "reserved but not yet committed" slot: private to the producer and the consumer respectively; they **must** be on different - // cache lines -- otherwise every frame's BeginWrite/BeginRead would invalidate each other, - // and the cache-line isolation done earlier for SpscCursor would be wasted. + // Index of the "reserved but not yet committed" slot: private to the producer and the consumer + // respectively; they **must** be on different cache lines; otherwise every frame's + // BeginWrite/BeginRead would invalidate each other, and the cache-line isolation done earlier for + // SpscCursor would be wasted. TETHERKITNEXT_CACHE_ALIGNED std::size_t pending_write_index_ = 0; TETHERKITNEXT_CACHE_ALIGNED std::size_t pending_read_index_ = 0; - // Park state lives on its own cache line: `parked` is read by the producer - // on every publish but written only when the consumer goes to sleep. + // Park state lives on its own cache line: `parked` is read by the producer on every publish but + // written only when the consumer goes to sleep. struct TETHERKITNEXT_CACHE_ALIGNED ParkState { std::atomic doorbell{0}; std::atomic parked{false}; diff --git a/include/tetherkitnext/common/i18n.h b/include/tetherkitnext/common/i18n.h index ad55874..2f4ccab 100644 --- a/include/tetherkitnext/common/i18n.h +++ b/include/tetherkitnext/common/i18n.h @@ -1,34 +1,38 @@ // User-facing messages and runtime language switching. // -// * Why not gettext * +// Why not gettext: // -// gettext needs libintl, needs msgfmt to generate .mo files at build time, and needs a runtime lookup of -// directories by path. This project needs only two languages and a few hundred fixed messages, and must serve the command line, -// the shared library and the GUI at the same time (the GUI switches language through the C ABI). A table compiled into the binary is the simplest, -// and avoids runtime failures such as "installed on another machine, .mo not found, so everything turns English". +// gettext needs libintl, needs msgfmt to generate .mo files at build time, and needs a runtime +// lookup of directories by path. This project needs only two languages and a few hundred fixed +// messages, and must serve the command line, the shared library and the GUI at the same time (the +// GUI switches language through the C ABI). A table compiled into the binary is the simplest, and +// avoids runtime failures such as "installed on another machine, .mo not found, so everything +// turns English". // -// * How the message table is organized * +// How the message table is organized: // // All messages are centralized in messages.def, one per line: // // TETHERKITNEXT_MESSAGE(kCliUnknownOption, "未知选项 \"{}\"", "unknown option \"{}\"") // -// This file is expanded three times by the X-macro, generating the `Msg` enum, the Chinese table and the English table. All three -// are generated from the same source, so it is **structurally impossible for one language to miss an entry**. The only remaining -// place where things can go wrong is placeholders that do not match between the two languages, which tests/test_common_i18n.cc checks entry by entry. +// This file is expanded three times by the X-macro, generating the `Msg` enum, the Chinese table +// and the English table. All three are generated from the same source, so it is **structurally +// impossible for one language to miss an entry**. The only remaining place where things can go +// wrong is placeholders that do not match between the two languages, which +// tests/test_common_i18n.cc checks entry by entry. // -// * How to use * +// How to use: // -// * Plain messages: `Tr(Msg::kCliUnknownOption, argument)` -- the arguments are exactly the same as std::format, -// and it returns std::string. -// * Logging: use macros like TETHERKITNEXT_INFO_TR (see logging.h), which keep the laziness of "do not evaluate -// if the level is off". +// * Plain messages: `Tr(Msg::kCliUnknownOption, argument)`: the arguments are exactly the same as +// std::format, and it returns std::string. +// * Logging: use macros like TETHERKITNEXT_INFO_TR (see logging.h), which keep the laziness of +// "do not evaluate if the level is off". // * Errors: `Error::Generic(Tr(Msg::kFoo, x))`. // -// * Forbidden on the hot path * +// Forbidden on the hot path: // -// Tr() does a vformat and returns std::string, which necessarily allocates heap memory. Like error.h, -// **it must never be called on the data hot path**. +// Tr() does a vformat and returns std::string, which necessarily allocates heap memory. Like +// error.h, **it must never be called on the data hot path**. #pragma once #include @@ -40,8 +44,9 @@ namespace tetherkitnext { /// Currently supported UI languages. /// -/// Deliberately not an open-ended language tag string: each additional language needs an additional column of messages, and catching -/// "a missing entry" at compile time is worth more than falling back to some default language at runtime. +/// Not an open-ended language tag string: each additional language needs an additional column of +/// messages, and catching "a missing entry" at compile time is worth more than falling back to some +/// default language at runtime. enum class Language : std::uint8_t { kEnglish = 0, kChinese = 1, @@ -52,36 +57,41 @@ enum class Msg : std::uint16_t { #define TETHERKITNEXT_MESSAGE(id, zh, en) id, #include "tetherkitnext/common/messages.def" // NOLINT(bugprone-suspicious-include) #undef TETHERKITNEXT_MESSAGE - /// Sentinel: the number of messages. Only for table-length assertions and test iteration; not a real message. + /// Sentinel: the number of messages. Only for table-length assertions and test iteration; not a + /// real message. kMessageCount, }; /// Sets the current language. Thread-safe; may be called at any time. /// -/// Process-wide single state: log and error strings are produced from multiple threads, and making it thread-local would only make the output of a single -/// session appear in two languages. +/// Process-wide single state: log and error strings are produced from multiple threads, and making +/// it thread-local would only make the output of a single session appear in two languages. void SetLanguage(Language language) noexcept; [[nodiscard]] Language GetLanguage() noexcept; -/// Infers the language from environment variables, checking in order `TETHERKITNEXT_LANG`, `LC_ALL`, `LC_MESSAGES`, `LANG`. +/// Infers the language from environment variables, checking in order `TETHERKITNEXT_LANG`, +/// `LC_ALL`, `LC_MESSAGES`, `LANG`. /// -/// Takes the first non-empty value; if it starts with `zh` (case-insensitive) it is judged Chinese, and everything else is English; -/// if none of the four is set it is also English -- consistent with POSIX's default "C" locale. +/// Takes the first non-empty value; if it starts with `zh` (case-insensitive) it is judged Chinese, +/// and everything else is English; if none of the four is set it is also English; consistent with +/// POSIX's default "C" locale. /// -/// WARNING: Whether `sudo` passes `LANG` through to the command depends on sudoers' `env_keep`, so the command line -/// also provides an explicit `--lang`; do not count on environment variables surviving under sudo. +/// WARNING: Whether `sudo` passes `LANG` through to the command depends on sudoers' `env_keep`, so +/// the command line also provides an explicit `--lang`; do not count on environment variables +/// surviving under sudo. [[nodiscard]] Language DetectLanguageFromEnvironment() noexcept; /// Judges a locale string (`"zh_CN.UTF-8"`, `"en_US"`, `"C"`, ...) as a language. /// -/// There is only one criterion: starting with `zh` (case-insensitive) counts as Chinese, everything else is English. An empty string is likewise -/// English. DetectLanguageFromEnvironment feeds the environment variable's value to it -- -/// it is split into a separate function so this criterion can be tested cleanly without touching environment variables. +/// There is only one criterion: starting with `zh` (case-insensitive) counts as Chinese, everything +/// else is English. An empty string is likewise English. DetectLanguageFromEnvironment feeds the +/// environment variable's value to it; it is split into a separate function so this criterion can +/// be tested cleanly without touching environment variables. [[nodiscard]] Language LanguageFromLocaleString(std::string_view locale) noexcept; -/// Parses the value of `--lang`. Accepts `zh` / `zh-Hans` / `zh_CN` / `chinese`, -/// `en` / `en-US` / `english`, and `auto` (infer from the environment). +/// Parses the value of `--lang`. Accepts `zh` / `zh-Hans` / `zh_CN` / `chinese`, `en` / `en-US` / +/// `english`, and `auto` (infer from the environment). /// /// @return true on successful parse, writing `out_language`; false if unrecognized, leaving /// `out_language` unchanged. @@ -92,27 +102,33 @@ void SetLanguage(Language language) noexcept; /// Gets the original text of a message in the **current language** (without argument substitution). /// -/// Returns an empty string instead of crashing when `id` is out of range -- a message table lookup failure must never bring down the driver. +/// Returns an empty string instead of crashing when `id` is out of range; a message table lookup +/// failure must never bring down the driver. [[nodiscard]] std::string_view Text(Msg id) noexcept; -/// Gets the original text of a message in the **specified language**. Tests use it to check placeholders language by language. +/// Gets the original text of a message in the **specified language**. Tests use it to check +/// placeholders language by language. [[nodiscard]] std::string_view TextIn(Language language, Msg id) noexcept; namespace detail { -/// Implementation of Tr(). Made a non-template function to avoid instantiating a copy of vformat at every call site. +/// Implementation of Tr(). Made a non-template function to avoid instantiating a copy of vformat at +/// every call site. /// -/// Swallows std::format_error internally: when the placeholders in the message table do not match the call site (which can only happen if a -/// translation is wrong), it returns the unsubstituted original text instead of letting one log line take down the process. +/// Swallows std::format_error internally: when the placeholders in the message table do not match +/// the call site (which can only happen if a translation is wrong), it returns the unsubstituted +/// original text instead of letting one log line take down the process. [[nodiscard]] std::string FormatMessage(Msg id, std::format_args args) noexcept; } // namespace detail -/// Fetches a message in the current language and substitutes arguments. The argument semantics are exactly the same as `std::format`. +/// Fetches a message in the current language and substitutes arguments. The argument semantics are +/// exactly the same as `std::format`. /// -/// The only difference from `std::format` is that the format string comes from a runtime table lookup, so **the compiler cannot** check -/// whether the placeholders match the arguments. That safeguard is provided by tests/test_common_i18n.cc: it checks that -/// each message's placeholder set is identical in both languages, and does a trial run with real arguments. +/// The only difference from `std::format` is that the format string comes from a runtime table +/// lookup, so **the compiler cannot** check whether the placeholders match the arguments. That +/// safeguard is provided by tests/test_common_i18n.cc: it checks that each message's placeholder +/// set is identical in both languages, and does a trial run with real arguments. template [[nodiscard]] std::string Tr(Msg id, const Args&... args) { return detail::FormatMessage(id, std::make_format_args(args...)); diff --git a/include/tetherkitnext/common/logging.h b/include/tetherkitnext/common/logging.h index 6c3bfab..a597d0e 100644 --- a/include/tetherkitnext/common/logging.h +++ b/include/tetherkitnext/common/logging.h @@ -2,12 +2,13 @@ // // Design constraints: // 1. **Forbidden on the data hot path.** The Trace/Debug levels are removed wholesale by the -// preprocessor in Release builds (even argument evaluation does not happen), so writing TETHERKITNEXT_TRACE -// on a hot path is safe; but Info and above really do formatting and take a lock to write stderr, so they are forbidden on the hot path. -// 2. Thread-safe: multiple threads writing stderr at once would interleave, so whole lines are written under a mutex. -// Logging is not on the hot path, so lock contention does not matter. -// 3. No third-party logging library is introduced: only "time + level + thread name + location + message" is needed, -// and std::format is enough. +// preprocessor in Release builds (even argument evaluation does not happen), so writing +// TETHERKITNEXT_TRACE on a hot path is safe; but Info and above really do formatting and take +// a lock to write stderr, so they are forbidden on the hot path. +// 2. Thread-safe: multiple threads writing stderr at once would interleave, so whole lines are +// written under a mutex. Logging is not on the hot path, so lock contention does not matter. +// 3. No third-party logging library is introduced: only "time + level + thread name + location + +// message" is needed, and std::format is enough. #pragma once #include @@ -21,8 +22,10 @@ namespace tetherkitnext { enum class LogLevel : std::uint8_t { kTrace = 0, ///< Per-frame level detail; removed at compile time in Release builds. - kDebug = 1, ///< Protocol interaction detail (every RNDIS control message); removed at compile time in Release. - kInfo = 2, ///< Lifecycle events (device connected, state machine transitions, statistics reports). + /// Protocol interaction detail (every RNDIS control message); removed at compile time in Release. + kDebug = 1, + /// Lifecycle events (device connected, state machine transitions, statistics reports). + kInfo = 2, kWarn = 3, ///< Recoverable anomalies (USB stall, BPF packet drops, keepalive timeout retries). kError = 4, ///< Unrecoverable errors. kOff = 5, ///< Everything off. @@ -30,8 +33,8 @@ enum class LogLevel : std::uint8_t { /// Compile-time log floor. Log calls below this level are removed wholesale by the preprocessor. /// -/// In Release builds (NDEBUG), Trace/Debug are removed, ensuring that TETHERKITNEXT_TRACE on the hot path -/// does not even evaluate its arguments. +/// In Release builds (NDEBUG), Trace/Debug are removed, ensuring that TETHERKITNEXT_TRACE on the +/// hot path does not even evaluate its arguments. #ifndef TETHERKITNEXT_COMPILED_MIN_LOG_LEVEL #ifdef NDEBUG #define TETHERKITNEXT_COMPILED_MIN_LOG_LEVEL 2 // kInfo @@ -48,20 +51,23 @@ LogLevel GetLogLevel() noexcept; /// Whether to enable colored output. By default enabled only when stderr is a tty. void SetLogColorEnabled(bool enabled) noexcept; -/// Gives the current thread a short name that appears in log lines, making it easy to tell usb-event / bpf-rx / bpf-tx apart. -/// Also calls pthread_setname_np so it is visible in Instruments / lldb too. +/// Gives the current thread a short name that appears in log lines, making it easy to tell +/// usb-event / bpf-rx / bpf-tx apart. Also calls pthread_setname_np so it is visible in Instruments +/// / lldb too. void SetCurrentThreadName(std::string_view name) noexcept; -/// Log sink: **additionally** forwards already-formatted log lines to the host (the GUI needs to show logs in the interface, -/// while the logs themselves only go to stderr). stderr output is unaffected; the two run in parallel. +/// Log sink: additionally forwards already-formatted log lines to the host (the GUI needs to show +/// logs in the interface, while the logs themselves only go to stderr). stderr output is +/// unaffected; the two run in parallel. /// -/// * Three hard constraints when implementing a log sink * -/// 1. It is called on **any thread** (including the libusb event thread); -/// 2. It is called **inside** the log mutex -- so the implementation **must never log again** -/// (std::mutex is not reentrant and would deadlock on the spot); -/// 3. It must never do blocking I/O -- it would hold up all threads that are currently logging. +/// Three hard constraints when implementing a log sink: +/// 1. It is called on any thread (including the libusb event thread); +/// 2. It is called inside the log mutex, so the implementation must never log again (std::mutex +/// is not reentrant and would deadlock on the spot); +/// 3. It must never do blocking I/O: it would hold up all threads that are currently logging. /// -/// The only reasonable implementation satisfying these three is "copy into a fixed-size ring buffer that the host polls and takes away". +/// The only reasonable implementation satisfying these three is "copy into a fixed-size ring buffer +/// that the host polls and drains". using LogSink = void (*)(LogLevel level, std::string_view thread_name, std::string_view message, void* user) noexcept; @@ -82,7 +88,8 @@ constexpr std::string_view BaseName(std::string_view path) noexcept { return pos == std::string_view::npos ? path : path.substr(pos + 1); } -/// Formats and outputs. Deliberately a function template rather than macro-inlined, to shrink macro expansion size. +/// Formats and outputs. A function template rather than macro-inlined, to shrink macro expansion +/// size. template void LogFormatted(LogLevel level, std::string_view file, unsigned line, std::format_string fmt, Args&&... args) noexcept { @@ -90,14 +97,16 @@ void LogFormatted(LogLevel level, std::string_view file, unsigned line, try { EmitLogLine(level, file, line, std::format(fmt, std::forward(args)...)); } catch (...) { // NOLINT(bugprone-empty-catch) - // Text() is only a table lookup returning string_view; it does not allocate or throw -- it is safe inside this catch. + // Text() is only a table lookup returning string_view; it does not allocate or throw: it is + // safe inside this catch. EmitLogLine(LogLevel::kError, file, line, Text(Msg::kCommonLogFormatFailed)); } } } // namespace detail -/// Log macros. Compile-time level pruning first, then a runtime level check (branch-prediction friendly). +/// Log macros. Compile-time level pruning first, then a runtime level check (branch-prediction +/// friendly). #define TETHERKITNEXT_LOG(level, ...) \ do { \ if constexpr (static_cast(level) >= TETHERKITNEXT_COMPILED_MIN_LOG_LEVEL) { \ @@ -114,11 +123,13 @@ void LogFormatted(LogLevel level, std::string_view file, unsigned line, #define TETHERKITNEXT_WARN(...) TETHERKITNEXT_LOG(::tetherkitnext::LogLevel::kWarn, __VA_ARGS__) #define TETHERKITNEXT_ERROR(...) TETHERKITNEXT_LOG(::tetherkitnext::LogLevel::kError, __VA_ARGS__) -/// Emits a **translatable** log line. `id` is a `Msg` enum value, followed by arguments identical to std::format. +/// Emits a **translatable** log line. `id` is a `Msg` enum value, followed by arguments identical +/// to std::format. /// -/// Why this group exists instead of writing `TETHERKITNEXT_INFO("{}", Tr(id, ...))` directly: only as macros can -/// Tr() stay **inside** the level check, so when the level is off both the lookup and the formatting are saved -- the -/// hand-written form above easily slips and puts Tr() outside the macro, computing it for nothing on every log line. +/// Why this group exists instead of writing `TETHERKITNEXT_INFO("{}", Tr(id, ...))` directly: only +/// as macros can Tr() stay **inside** the level check, so when the level is off both the lookup and +/// the formatting are saved; the hand-written form above easily slips and puts Tr() outside the +/// macro, computing it for nothing on every log line. #define TETHERKITNEXT_LOG_TR(level, id, ...) \ TETHERKITNEXT_LOG(level, "{}", ::tetherkitnext::Tr((id)__VA_OPT__(, ) __VA_ARGS__)) diff --git a/include/tetherkitnext/common/messages.def b/include/tetherkitnext/common/messages.def index dab6cab..17e7c3a 100644 --- a/include/tetherkitnext/common/messages.def +++ b/include/tetherkitnext/common/messages.def @@ -304,6 +304,8 @@ TETHERKITNEXT_MESSAGE(kRndisCondisMessageReceived, "supports connectionless 802.3 devices") TETHERKITNEXT_MESSAGE(kRndisDiscardUnexpectedMessage, "丢弃一条非预期的控制消息 {}({:#010x})", "discarding an unexpected control message {} ({:#010x})") +TETHERKITNEXT_MESSAGE(kRndisDiscardStaleReply, "丢弃迟到的 {}(RequestId {},正在等待 {})", + "discarding a late {} (RequestId {}, waiting for {})") TETHERKITNEXT_MESSAGE(kRndisNotificationReceived, "收到 RESPONSE_AVAILABLE 通知", "received a RESPONSE_AVAILABLE notification") TETHERKITNEXT_MESSAGE(kRndisWaitReplyTimeout, "等待 {} 超时(轮询 {} 次 × {} ms)", @@ -639,6 +641,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") @@ -677,8 +681,6 @@ TETHERKITNEXT_MESSAGE(kCapiDnsPublishFailed, "写入 DNS 键失败(服务 {} "failed to write the DNS key (service {}); DNS may not take effect in manual " "mode") TETHERKITNEXT_MESSAGE(kCapiWhatAddScopedRoute, "添加 scoped 默认路由", "adding a scoped default route") -TETHERKITNEXT_MESSAGE(kCapiWhatUpdateScopedRoute, "更新 scoped 默认路由", - "updating the scoped default route") TETHERKITNEXT_MESSAGE(kCapiWhatSwitchGlobalRoute, "切换全局默认路由", "switching the global default route") TETHERKITNEXT_MESSAGE(kCapiWhatAddGlobalRoute, "添加全局默认路由", "adding a global default route") @@ -692,6 +694,12 @@ TETHERKITNEXT_MESSAGE(kCapiDhcpTimeout, "DHCP server.\n" " The service keeps retrying in the background, so an address may still appear " "if you refresh later; you can also switch to a static IP.") +TETHERKITNEXT_MESSAGE(kCapiDefaultRouteRestored, "默认路由已恢复为经 {}({})", + "restored the default route via {} ({})") +TETHERKITNEXT_MESSAGE(kCapiDemoteServiceFailed, + "设备没有网关,但无法把 TetherKitNext 网络服务移回服务顺序末尾:{}", + "the device has no router, but the TetherKitNext network service could not be moved " + "back to the end of the service order: {}") TETHERKITNEXT_MESSAGE(kCapiDhcpNoRouter, "已拿到 DHCP 租约,但租约里没有网关地址,无法把全局默认路由指向它。", "got a DHCP lease, but it carries no router address, so the global default route " diff --git a/include/tetherkitnext/common/scheduling.h b/include/tetherkitnext/common/scheduling.h index 450897e..21cd7dd 100644 --- a/include/tetherkitnext/common/scheduling.h +++ b/include/tetherkitnext/common/scheduling.h @@ -1,21 +1,23 @@ // Thread scheduling policy. // -// Why it is needed: Apple Silicon is a big.LITTLE architecture (this machine's 10 cores = 4 performance cores + -// 6 efficiency cores). Under the default QoS, data-path threads may be scheduled onto efficiency cores, and throughput drops noticeably, -// with more jitter as well. macOS **does not provide** an interface to bind a thread to a specific physical core -// (there is no sched_setaffinity); what can be done is to express intent through the QoS class and let the kernel decide: +// Why it is needed: Apple Silicon is a big.LITTLE architecture (performance and efficiency cores). +// Under the default QoS, data-path threads may be scheduled onto efficiency cores, and throughput +// drops noticeably, with more jitter as well. macOS **does not provide** an interface to bind a +// thread to a specific physical core (there is no sched_setaffinity); what can be done is to +// express intent through the QoS class and let the kernel decide: // -// QOS_CLASS_USER_INTERACTIVE -- highest priority; the kernel prefers to place it on performance cores. -// QOS_CLASS_USER_INITIATED -- next. -// QOS_CLASS_DEFAULT -- default. -// QOS_CLASS_UTILITY / BACKGROUND -- tend toward efficiency cores. +// QOS_CLASS_USER_INTERACTIVE: highest priority; the kernel prefers to place it on performance +// cores. QOS_CLASS_USER_INITIATED: next. QOS_CLASS_DEFAULT: default. QOS_CLASS_UTILITY / +// BACKGROUND: tend toward efficiency cores. // -// We use USER_INTERACTIVE for data-path threads, and UTILITY for auxiliary threads such as statistics/logging. +// We use USER_INTERACTIVE for data-path threads, and UTILITY for auxiliary threads such as +// statistics/logging. // // About real-time threads (THREAD_TIME_CONSTRAINT_POLICY): -// The Core Audio style time-constraint policy can get stronger latency guarantees, but it requires the thread -// to yield voluntarily within the declared time budget, and overrunning is penalized with demotion. Our BPF read() is a blocking -// call of unpredictable duration, which does not satisfy the prerequisites of time-constraint, so it is not adopted. +// The Core Audio style time-constraint policy can get stronger latency guarantees, but it +// requires the thread to yield voluntarily within the declared time budget, and overrunning is +// penalized with demotion. Our BPF read() is a blocking call of unpredictable duration, which +// does not satisfy the prerequisites of time-constraint, so it is not adopted. #pragma once #include @@ -27,17 +29,22 @@ namespace tetherkitnext { /// Thread purpose, which determines the QoS level. enum class ThreadRole : std::uint8_t { - kDataPath, ///< USB event loop, BPF read/write -- critical for throughput and latency; aim for performance cores. - kControl, ///< RNDIS control channel, keepalive -- low frequency but needs a timely response. - kAuxiliary, ///< Statistics reports, log flushing -- may yield. + /// USB event loop, BPF read/write: critical for throughput and latency; aim for performance + /// cores. + kDataPath, + kControl, ///< RNDIS control channel, keepalive: low frequency but needs a timely response. + kAuxiliary, ///< Statistics reports, log flushing; may yield. }; -/// Sets the name and QoS of the current thread. Should be called once at the very start of the thread function. +/// Sets the name and QoS of the current thread. Should be called once at the very start of the +/// thread function. /// -/// The name is written both to thread_local (for the log prefix) and to the kernel (for lldb / Instruments). +/// The name is written both to thread_local (for the log prefix) and to the kernel (for lldb / +/// Instruments). void ConfigureCurrentThread(std::string_view name, ThreadRole role) noexcept; -/// Maps a ThreadRole to the numeric value of qos_class_t. Exposed separately for testing and log printing. +/// Maps a ThreadRole to the numeric value of qos_class_t. Exposed separately for testing and log +/// printing. [[nodiscard]] unsigned int QosClassFor(ThreadRole role) noexcept; } // namespace tetherkitnext diff --git a/include/tetherkitnext/common/spsc_ring.h b/include/tetherkitnext/common/spsc_ring.h index 10442d3..ce744d1 100644 --- a/include/tetherkitnext/common/spsc_ring.h +++ b/include/tetherkitnext/common/spsc_ring.h @@ -1,14 +1,18 @@ // Single-producer single-consumer (SPSC) lock-free bounded ring queue. // // Why write our own instead of using the ready-made std::queue + mutex: -// The data path carries 25k~80k frames per second, with one queue in each direction. Locking and unlocking a mutex -// goes through the kernel futex under contention, at a cost of microseconds per operation; an SPSC lock-free queue's enqueue/dequeue needs only -// one release store / acquire load, about a few nanoseconds. +// The data path carries 25k~80k frames per second, with one queue in each direction. Locking and +// unlocking a mutex goes through the kernel futex under contention, at a cost of microseconds per +// operation; an SPSC lock-free queue's enqueue/dequeue needs only one release store / acquire +// load, about a few nanoseconds. // // This file provides two layers: -// * SpscCursor -- only responsible for index advancement and memory ordering, indifferent to the storage form. -// * SpscRing -- a fixed-size element queue, suited to small PODs (completion events, indices, statistics snapshots). -// Variable-length Ethernet frames go through FrameRing (frame_ring.h), which reuses the same SpscCursor. +// * SpscCursor, only responsible for index advancement and memory ordering, indifferent to the +// storage form. +// * SpscRing: a fixed-size element queue, suited to small PODs (completion events, indices, +// statistics snapshots). +// Variable-length Ethernet frames go through FrameRing (frame_ring.h), which reuses the same +// SpscCursor. // // Correctness is verified by ThreadSanitizer: // cmake -B build-tsan -DTETHERKITNEXT_ENABLE_TSAN=ON && ctest --test-dir build-tsan @@ -24,22 +28,27 @@ namespace tetherkitnext { -/// Index cursor of an SPSC queue: manages "how far written / how far read" and the cross-thread memory ordering. +/// Index cursor of an SPSC queue: manages "how far written / how far read" and the cross-thread +/// memory ordering. /// -/// Uses freely incrementing 64-bit counters rather than the classic "leave one slot empty" approach: -/// * The queue length is directly `write_pos - read_pos`, with no need to handle wrap-around comparisons; +/// Uses freely incrementing 64-bit counters rather than the classic "leave one slot empty" +/// approach: +/// * The queue length is directly `write_pos - read_pos`, with no need to handle wrap-around +/// comparisons; /// * The capacity can be fully used (the classic approach wastes one slot); -/// * A 64-bit counter at 100 Mpps takes 5800 years to wrap, so it can be treated as never wrapping. +/// * A 64-bit counter at 100 Mpps takes 5800 years to wrap, so it can be treated as never +/// wrapping. /// -/// The layout deliberately gives each of the four indices its own cache line: +/// The layout gives each of the four indices its own cache line: /// * `write_pos_` is written by the producer and read by the consumer; -/// * `cached_read_pos_` is the producer's private copy of `read_pos_`, used to avoid reading -/// the consumer's cache line on every enqueue (this is the most important optimization of this class -- only when it "looks full" -/// does it actually synchronize once); +/// * `cached_read_pos_` is the producer's private copy of `read_pos_`, used to avoid reading the +/// consumer's cache line on every enqueue (this is the most important optimization of this +/// class, only when it "looks full" does it actually synchronize once); /// * `read_pos_` / `cached_write_pos_` are symmetric. /// If `write_pos_` and `cached_read_pos_` were placed on the same cache line, the consumer reading -/// `write_pos_` would demote that line to Shared, and the producer's subsequent write to `cached_read_pos_` would have to -/// take it back to Exclusive, wasting a round trip of cache coherence. +/// `write_pos_` would demote that line to Shared, and the producer's subsequent write to +/// `cached_read_pos_` would have to take it back to Exclusive, wasting a round trip of cache +/// coherence. class SpscCursor { public: /// `capacity` must be a power of two and greater than 0 (a bit mask is used for modulo). @@ -51,18 +60,21 @@ class SpscCursor { // Producer side (only the producer thread may call) // --------------------------------------------------------------------------- - /// Tries to obtain the index of the slot at "current write position + offset". Returns false when the queue is full. + /// Tries to obtain the index of the slot at "current write position + offset". Returns false when + /// the queue is full. /// - /// `offset` is relative to the **not yet published** write position, used for batch writes: - /// take slots and write with offset = 0,1,2,... in succession, and finally call PublishWrite(n) once. + /// `offset` is relative to the **not yet published** write position, used for batch writes: take + /// slots and write with offset = 0,1,2,... in succession, and finally call PublishWrite(n) once. /// - /// Deliberately only reads its own write_pos_ here (relaxed; this cache line is exclusively the producer's), - /// so taking a slot itself costs almost nothing -- what is really expensive is publishing; see PublishWrite. + /// Only reads its own write_pos_ here (relaxed; this cache line is exclusively the producer's), + /// so taking a slot itself costs almost nothing; what is really expensive is publishing; see + /// PublishWrite. [[nodiscard]] bool TryAcquireWriteAt(std::uint64_t offset, std::size_t& index) noexcept { const std::uint64_t position = write_pos_.load(std::memory_order_relaxed) + offset; if (position - cached_read_pos_ >= capacity_) [[unlikely]] { - // The cached read position is stale; synchronize the real value once before deciding. acquire guarantees: when we see the consumer's - // advanced read_pos_, the consumer's read of that slot has also completed, so it is safe to overwrite. + // The cached read position is stale; synchronize the real value once before deciding. acquire + // guarantees: when we see the consumer's advanced read_pos_, the consumer's read of that slot + // has also completed, so it is safe to overwrite. cached_read_pos_ = read_pos_.load(std::memory_order_acquire); if (position - cached_read_pos_ >= capacity_) { return false; @@ -79,26 +91,28 @@ class SpscCursor { /// Publishes `count` just-written slots, making them visible to the consumer. /// - /// release guarantees: after the consumer reads the new write_pos_ with acquire, it will certainly see all of our - /// writes to the contents of these slots. + /// release guarantees: after the consumer reads the new write_pos_ with acquire, it will + /// certainly see all of our writes to the contents of these slots. /// - /// * **Batch publishing is the most important optimization of this class.** * - /// This release store makes the cache line holding write_pos_ bounce across cores once, at a measured cost of about - /// 60 ns. When publishing one at a time it is the per-entry cost; when publishing N at once it is amortized to 60/N: + /// * **Batch publishing is the most important optimization of this class.** * This release store + /// makes the cache line holding write_pos_ bounce across cores once, at a measured cost of + /// about 60 ns. When publishing one at a time it is the per-entry cost; when publishing N at + /// once it is amortized to 60/N: /// /// batch=1 -> about 63 ns/entry /// batch=8 -> about 5.5 ns/entry (about 11x) /// batch=32 -> about 1.9 ns/entry (about 33x) /// - /// So on the data path publishing **must** be done in batches -- use FrameRing's BatchWriter / - /// BatchReader, which separate "take slot + write" from "publish", and do - /// one atomic operation only at the end of the batch. + /// So on the data path publishing **must** be done in batches; use FrameRing's BatchWriter / + /// BatchReader, which separate "take slot + write" from "publish", and do one atomic operation + /// only at the end of the batch. void PublishWrite(std::uint64_t count = 1) noexcept { write_pos_.store(write_pos_.load(std::memory_order_relaxed) + count, std::memory_order_release); } - /// Remaining writable slots from the producer's point of view (may be conservative, because the cached read position is used). + /// Remaining writable slots from the producer's point of view (may be conservative, because the + /// cached read position is used). [[nodiscard]] std::size_t WritableApprox() noexcept { const std::uint64_t write_pos = write_pos_.load(std::memory_order_relaxed); cached_read_pos_ = read_pos_.load(std::memory_order_acquire); @@ -109,9 +123,11 @@ class SpscCursor { // Consumer side (only the consumer thread may call) // --------------------------------------------------------------------------- - /// Tries to obtain the index of the slot at "current read position + offset". Returns false when the queue is empty. + /// Tries to obtain the index of the slot at "current read position + offset". Returns false when + /// the queue is empty. /// - /// Symmetric to the write side: take a batch with offset = 0,1,2,..., and finally call PublishRead(n) once. + /// Symmetric to the write side: take a batch with offset = 0,1,2,..., and finally call + /// PublishRead(n) once. [[nodiscard]] bool TryAcquireReadAt(std::uint64_t offset, std::size_t& index) noexcept { const std::uint64_t position = read_pos_.load(std::memory_order_relaxed) + offset; if (position >= cached_write_pos_) [[unlikely]] { @@ -131,13 +147,15 @@ class SpscCursor { /// Releases `count` just-read slots so they can be reused by the producer. /// - /// For the same reason as PublishWrite, batch release amortizes the cost of cross-core cache line bouncing by a factor of N. + /// For the same reason as PublishWrite, batch release amortizes the cost of cross-core cache line + /// bouncing by a factor of N. void PublishRead(std::uint64_t count = 1) noexcept { read_pos_.store(read_pos_.load(std::memory_order_relaxed) + count, std::memory_order_release); } - /// Readable slots from the consumer's point of view. Use it to get the batch size at once during batch dequeue, reducing synchronization count. + /// Readable slots from the consumer's point of view. Use it to get the batch size at once during + /// batch dequeue, reducing synchronization count. [[nodiscard]] std::size_t ReadableApprox() noexcept { const std::uint64_t read_pos = read_pos_.load(std::memory_order_relaxed); cached_write_pos_ = write_pos_.load(std::memory_order_acquire); @@ -145,7 +163,8 @@ class SpscCursor { } // --------------------------------------------------------------------------- - // May be called from any thread (for statistics/observation only; the result is an instantaneous snapshot) + // May be called from any thread (for statistics/observation only; the result is an instantaneous + // snapshot) // --------------------------------------------------------------------------- /// Approximate number of elements currently in the queue. @@ -166,7 +185,8 @@ class SpscCursor { } private: - // Read-only shared data gets a line of its own, to keep it from being crowded together with frequently changing indices. + // Read-only shared data gets a line of its own, to keep it from being crowded together with + // frequently changing indices. TETHERKITNEXT_CACHE_ALIGNED const std::size_t capacity_; const std::size_t mask_; @@ -178,7 +198,8 @@ class SpscCursor { /// SPSC lock-free bounded queue of fixed-size elements. /// -/// Element types must be trivially copyable (POD): the data path does not accept types that may allocate memory or throw. +/// Element types must be trivially copyable (POD): the data path does not accept types that may +/// allocate memory or throw. template requires std::is_trivially_copyable_v && std::is_default_constructible_v class SpscRing { diff --git a/include/tetherkitnext/common/stats.h b/include/tetherkitnext/common/stats.h index b3943d1..3f9e8d0 100644 --- a/include/tetherkitnext/common/stats.h +++ b/include/tetherkitnext/common/stats.h @@ -1,15 +1,15 @@ // Data-path statistics counters. // // Design points: -// * Counters on the hot path **must not** be shared std::atomics -- two threads doing -// fetch_add on the same atomic would turn that cache line into a ping-pong ball at 25k~80k pps. -// * So the structure is "one private counter set per direction + a snapshot at read time": the writer is a single thread -// that updates with a relaxed store (which compiles to an ordinary str instruction); the observing thread -// reads a snapshot with relaxed loads, allowing it to read a slightly inconsistent set of values -- statistics do not need -// strong consistency. -// * std::atomic + relaxed rather than a bare uint64_t is used so that -// ThreadSanitizer does not judge "observer thread reads, worker thread writes" a data race. -// A relaxed atomic is just an ordinary ldr/str on arm64, with no extra overhead. +// * Counters on the hot path **must not** be shared std::atomics; two threads doing fetch_add on +// the same atomic would turn that cache line into a ping-pong ball at 25k~80k pps. +// * So the structure is "one private counter set per direction + a snapshot at read time": the +// writer is a single thread that updates with a relaxed store (which compiles to an ordinary +// str instruction); the observing thread reads a snapshot with relaxed loads, allowing it to +// read a slightly inconsistent set of values; statistics do not need strong consistency. +// * std::atomic + relaxed rather than a bare uint64_t is used so that ThreadSanitizer +// does not judge "observer thread reads, worker thread writes" a data race. A relaxed atomic is +// just an ordinary ldr/str on arm64, with no extra overhead. #pragma once #include @@ -25,14 +25,21 @@ namespace tetherkitnext { /// Only **one** thread may call the Add* methods; any thread may call Snapshot(). struct alignas(kCacheLineSize) DirectionCounters { std::atomic frames{0}; ///< Number of frames successfully moved. - std::atomic bytes{0}; ///< Number of bytes successfully moved (Ethernet frame payload). - std::atomic dropped_full{0}; ///< Number of frames dropped because the downstream queue was full. - std::atomic dropped_oversize{0}; ///< Number of frames dropped for exceeding the per-frame limit. - std::atomic dropped_malformed{0}; ///< Number of frames dropped for an invalid format. - std::atomic io_errors{0}; ///< Number of underlying I/O failures (write / transfer errors). - std::atomic batches{0}; ///< Number of batches, used to compute the average batch size. - - /// Records one frame successfully moved. This is the hottest line of code, deliberately kept to only two relaxed additions. + /// Number of bytes successfully moved (Ethernet frame payload). + std::atomic bytes{0}; + /// Number of frames dropped because the downstream queue was full. + std::atomic dropped_full{0}; + /// Number of frames dropped for exceeding the per-frame limit. + std::atomic dropped_oversize{0}; + /// Number of frames dropped for an invalid format. + std::atomic dropped_malformed{0}; + /// Number of underlying I/O failures (write / transfer errors). + std::atomic io_errors{0}; + /// Number of batches, used to compute the average batch size. + std::atomic batches{0}; + + /// Records one frame successfully moved. This is the hottest line of code, kept to only two + /// relaxed additions. void AddFrame(std::uint32_t frame_bytes) noexcept { Bump(frames, 1); Bump(bytes, frame_bytes); @@ -53,14 +60,16 @@ struct alignas(kCacheLineSize) DirectionCounters { void AddIoError(std::uint64_t count = 1) noexcept { Bump(io_errors, count); } private: - /// Relaxed read-modify-write. Because there is only a single writer thread, the atomicity of fetch_add is not needed here; - /// load+store suffices, saving the LSE atomic instruction (ldadd) on arm64. + /// Relaxed read-modify-write. Because there is only a single writer thread, the atomicity of + /// fetch_add is not needed here; load+store suffices, saving the LSE atomic instruction (ldadd) + /// on arm64. static void Bump(std::atomic& counter, std::uint64_t delta) noexcept { counter.store(counter.load(std::memory_order_relaxed) + delta, std::memory_order_relaxed); } }; -/// Plain (non-atomic) snapshot of DirectionCounters, convenient for taking differences and formatting. +/// Plain (non-atomic) snapshot of DirectionCounters, convenient for taking differences and +/// formatting. struct DirectionSnapshot { std::uint64_t frames = 0; std::uint64_t bytes = 0; diff --git a/include/tetherkitnext/common/time.h b/include/tetherkitnext/common/time.h index 3d54af0..81b33ea 100644 --- a/include/tetherkitnext/common/time.h +++ b/include/tetherkitnext/common/time.h @@ -1,10 +1,10 @@ // Monotonic clock and timing utilities. // // Why not use std::chrono::steady_clock directly: -// libc++'s steady_clock on Darwin goes through clock_gettime(CLOCK_MONOTONIC), -// while clock_gettime_nsec_np(CLOCK_UPTIME_RAW) is cheaper (it reads mach absolute time directly, -// with no timespec struct round trip, and is unaffected by NTP adjustments). Benchmarks and keepalive timers call it -// tens of thousands of times per second, so the difference is worth it. +// libc++'s steady_clock on Darwin goes through clock_gettime(CLOCK_MONOTONIC), while +// clock_gettime_nsec_np(CLOCK_UPTIME_RAW) is cheaper (it reads mach absolute time directly, with +// no timespec struct round trip, and is unaffected by NTP adjustments). Benchmarks and keepalive +// timers call it tens of thousands of times per second, so the difference is worth it. #pragma once #include @@ -19,7 +19,8 @@ inline constexpr Nanos kNanosPerMicro = 1'000; inline constexpr Nanos kNanosPerMilli = 1'000'000; inline constexpr Nanos kNanosPerSecond = 1'000'000'000; -/// Monotonic nanoseconds since system boot. Unaffected by system time adjustments, and does not stop during sleep. +/// Monotonic nanoseconds since system boot. Unaffected by system time adjustments, and does not +/// stop during sleep. /// /// CLOCK_UPTIME_RAW is the cheapest time source on Darwin: no NTP correction, no struct conversion. [[nodiscard]] inline Nanos MonotonicNanos() noexcept { @@ -40,35 +41,35 @@ class Stopwatch { return static_cast(Elapsed()) / static_cast(kNanosPerMilli); } - [[nodiscard]] double ElapsedSeconds() const noexcept { - return static_cast(Elapsed()) / static_cast(kNanosPerSecond); - } - private: Nanos start_; }; -/// Monotonically increasing periodic trigger, used for "do a keepalive / statistics report every N milliseconds". +/// Monotonically increasing periodic trigger, used for "do a keepalive / statistics report every N +/// milliseconds". /// -/// Deliberately does not use a timer thread or a kqueue timer: the caller already wakes up periodically in its event loop, -/// and only needs a cheap "is it time yet?" check. +/// Does not use a timer thread or a kqueue timer: the caller already wakes up periodically in its +/// event loop, and only needs a cheap "is it time yet?" check. class PeriodicTimer { public: /// @param period Trigger period. - /// @param start Timing origin. **Passed in explicitly rather than reading the clock internally**, so that: - /// (1) unit tests can inject a deterministic time base (otherwise the moment the constructor reads + /// @param start Timing origin. **Passed in explicitly rather than reading the clock + /// internally**, so that: + /// (1) unit tests can inject a deterministic time base (otherwise the moment the + /// constructor reads /// is slightly later than the caller's `now`, making "now + period" /// not yet expired, and the test results unreproducible); - /// (2) a caller that creates multiple timers in one loop can share the same time base. - /// The default preserves the convenient "start timing on construction" usage. + /// (2) a caller that creates multiple timers in one loop can share the same time + /// base. The default preserves the convenient "start timing on construction" usage. explicit PeriodicTimer(Nanos period, Nanos start = MonotonicNanos()) noexcept : period_(period), next_deadline_(start + period) {} /// Returns true when expired and advances the next deadline by one period. /// - /// Uses "accumulated deadlines" rather than "reset to now + period", to avoid the timer as a whole - /// drifting when the caller is delayed by scheduling. If it has fallen behind by more than a whole period, it aligns directly to after the current moment, - /// avoiding a long string of expired triggers being replayed after waking up. + /// Uses "accumulated deadlines" rather than "reset to now + period", to avoid the timer as a + /// whole drifting when the caller is delayed by scheduling. If it has fallen behind by more than + /// a whole period, it aligns directly to after the current moment, avoiding a long string of + /// expired triggers being replayed after waking up. [[nodiscard]] bool Expired(Nanos now) noexcept { if (now < next_deadline_) { return false; @@ -82,7 +83,8 @@ class PeriodicTimer { [[nodiscard]] bool Expired() noexcept { return Expired(MonotonicNanos()); } - /// Nanoseconds remaining until the next expiry; returns 0 if already expired. Used by the event loop to compute select/kevent timeouts. + /// Nanoseconds remaining until the next expiry; returns 0 if already expired. Used by the event + /// loop to compute select/kevent timeouts. [[nodiscard]] Nanos RemainingNanos(Nanos now) const noexcept { return now >= next_deadline_ ? 0 : next_deadline_ - now; } diff --git a/include/tetherkitnext/core/bridge.h b/include/tetherkitnext/core/bridge.h index 603edf8..337f2e7 100644 --- a/include/tetherkitnext/core/bridge.h +++ b/include/tetherkitnext/core/bridge.h @@ -1,6 +1,6 @@ // Data-path bridge: connects the RNDIS data channel with the feth/BPF link. // -// * Threading model (the most important design decision in this file) * +// Threading model (the most important design decision in this file): // // ┌─────────────────────────────────────────────────────────────────────┐ // │ RX direction (device -> host) │ @@ -22,50 +22,55 @@ // │ └→ DataChannel::SendFrames (RNDIS multi-packet, async bulk OUT) │ // └─────────────────────────────────────────────────────────────────────┘ // -// In total there are three data-path threads (plus libusb's own IOKit runloop thread and the state machine's control -// thread). This machine has 4 performance cores + 6 efficiency cores; three hot threads + libusb's runloop thread exactly -// fill the performance-core cluster without oversubscribing. +// In total there are three data-path threads (plus libusb's own IOKit runloop thread and the +// state machine's control thread). Apple Silicon has at least four performance cores, enough for +// the three hot threads plus libusb's runloop thread without oversubscribing. // // Why must RX be split into two threads? -// libusb's transfer callback holds ctx->event_waiters_lock, and doing blocking I/O in the callback would -// hold up all threads waiting on synchronous transfers (including the state machine thread running the control channel). And BPF's -// write() is a system call (about 660 ns and up on macOS, longer for batch writes). So the callback only does -// "unpack + memcpy into the lock-free queue + resubmit immediately", and the real write-out is handed to the injection thread. +// libusb's transfer callback holds ctx->event_waiters_lock, and doing blocking I/O in the +// callback would hold up all threads waiting on synchronous transfers (including the state +// machine thread running the control channel). And BPF's write() is a system call (about 660 ns +// and up on macOS, longer for batch writes). So the callback only does "unpack + memcpy into +// the lock-free queue + resubmit immediately", and the real write-out is handed to the +// injection thread. // // Why does TX need only one thread? -// BPF's read() itself blocks and aggregates automatically (with BIOCIMMEDIATE=1 it wakes on every arriving packet, -// and on waking delivers all packets accumulated in the meantime at once), and SendFrames submits **asynchronously** without blocking. -// So "read a batch -> submit a batch" in the same thread is the optimal shape; one more thread would only add one more +// BPF's read() itself blocks and aggregates automatically (with BIOCIMMEDIATE=1 it wakes on +// every arriving packet, and on waking delivers all packets accumulated in the meantime at +// once), and SendFrames submits **asynchronously** without blocking. So "read a batch -> submit +// a batch" in the same thread is the optimal shape; one more thread would only add one more // cross-core queue handoff. // // Why not merge the three things with a single kqueue event loop? -// Measured on macOS, one empty kevent() (timeout={0,0}, no events) takes 13.4~13.7 us, -// 20 times more expensive than an ordinary system call. At 25 kpps, probing alone would consume 34% of a single core. kqueue can only be -// used for genuinely blocking waits, never for polling -- and each of our three paths already has a natural -// blocking point, so merging brings no benefit. +// Measured on macOS, one empty kevent() (timeout={0,0}, no events) takes 13.4~13.7 us, 20 times +// more expensive than an ordinary system call. At 25 kpps, probing alone would consume 34% of a +// single core. kqueue can only be used for genuinely blocking waits, never for polling, and +// each of our three paths already has a natural blocking point, so merging brings no benefit. #pragma once -#include -#include -#include -#include -#include - #include "tetherkitnext/common/error.h" #include "tetherkitnext/common/frame_ring.h" #include "tetherkitnext/common/stats.h" +#include "tetherkitnext/core/peer_address.h" #include "tetherkitnext/net/link_backend.h" #include "tetherkitnext/usb/data_channel.h" +#include +#include +#include +#include +#include + namespace tetherkitnext::core { /// Bridge layer configuration. struct BridgeConfig { /// RX queue capacity (in frames). /// - /// Capacity derivation: it must buffer the mismatch between "libusb callback bursts" and "BPF write thread scheduling delay". - /// With a worst-case 10 ms scheduling delay and 1 Gbps full speed (82k pps), about 820 frames are needed; 2048 leaves - /// a 2.5x margin. Each slot is 2048+128 bytes, so 2048 slots come to about 4.25 MiB. + /// Capacity derivation: it must buffer the mismatch between "libusb callback bursts" and "BPF + /// write thread scheduling delay". With a worst-case 10 ms scheduling delay and 1 Gbps full speed + /// (82k pps), about 820 frames are needed; 2048 leaves a 2.5x margin. Each slot is 2048+128 + /// bytes, so 2048 slots come to about 4.25 MiB. std::size_t rx_ring_frames = 2048; /// Per-frame limit (including the Ethernet header). Should match feth's MTU + 14. @@ -73,16 +78,17 @@ struct BridgeConfig { /// The maximum number of frames the RX injection thread gathers before writing out. /// - /// Batch writes amortize "the system-call cost of one write()" to each frame; the measured benefit basically saturates at batch>=8, - /// but larger batches during bursts can further reduce the number of system calls. 64 balances both: - /// batches are small when idle (low latency) and automatically grow during bursts (high throughput). + /// Batch writes amortize "the system-call cost of one write()" to each frame; the measured + /// benefit basically saturates at batch>=8, but larger batches during bursts can further reduce + /// the number of system calls. 64 balances both: batches are small when idle (low latency) and + /// automatically grow during bursts (high throughput). std::uint32_t rx_write_batch = 64; /// How many empty polls the RX injector spins before parking on the ring. /// - /// A short spin covers the "producer is writing the next frame" window - /// without a futex round-trip; after that the thread blocks (zero idle CPU) - /// until the USB callback publishes a frame. See FrameRing::WaitForReadable. + /// A short spin covers the "producer is writing the next frame" window without a futex + /// round-trip; after that the thread blocks (zero idle CPU) until the USB callback publishes a + /// frame. See FrameRing::WaitForReadable. std::uint32_t rx_spin_before_park = 64; /// The maximum number of frames per batch submitted to USB in the TX direction. @@ -102,16 +108,21 @@ struct BridgeStats { std::uint64_t link_kernel_drops = 0; /// Number of times TX entered a wait because the transfer pool had no free slot. /// - /// This counts **events**, not frames: every time SendFrames fails to submit even one frame and the TX thread goes into - /// a wait, it goes +1 (under sustained pressure at most one more every ~50 ms). It measures "how frequently the TX side hits - /// the pool limit"; its presence does not mean frames were dropped -- during the wait the frames remain safely in the batch, upstream bursts are absorbed by the - /// kernel BPF buffer, and a real overflow would show up in link_kernel_drops. + /// This counts **events**, not frames: every time SendFrames fails to submit even one frame and + /// the TX thread goes into a wait, it goes +1 (under sustained pressure at most one more every + /// ~50 ms). It measures "how frequently the TX side hits the pool limit"; its presence does not + /// mean frames were dropped; during the wait the frames remain safely in the batch, bursts are + /// absorbed by the kernel BPF buffer, and a real overflow would show up in link_kernel_drops. std::uint64_t tx_backpressure_events = 0; + /// The device's own IPv4 address as last seen on the link (host byte order), 0 when unknown. See + /// peer_address.h. + std::uint32_t peer_ipv4 = 0; }; /// Data-path bridge. /// -/// Lifecycle: Create -> Start -> (running) -> Stop. Stop is idempotent, and the destructor calls it as a backstop. +/// Lifecycle: Create -> Start -> (running) -> Stop. Stop is idempotent, and the destructor calls it +/// as a backstop. class Bridge { public: Bridge(usb::DataChannel& data_channel, net::LinkBackend& link, const BridgeConfig& config); @@ -128,7 +139,8 @@ class Bridge { /// Stops the data path. /// - /// The teardown order is deliberate; see the comments in the implementation -- a wrong order loses frames or deadlocks. + /// The teardown order matters; see the comments in the implementation: a wrong order loses frames + /// or deadlocks. void Stop(); [[nodiscard]] bool Running() const noexcept { @@ -137,27 +149,29 @@ class Bridge { [[nodiscard]] BridgeStats Snapshot() const; - /// Counters for the RX direction. The data channel's receive callback writes it directly. - [[nodiscard]] DirectionCounters& RxCounters() noexcept { return counters_.rx; } - /// Pauses / resumes data movement. /// - /// Used during an RNDIS soft reset: the device discards all outstanding packets, and continuing to send frames to it during that time - /// is only a waste, and may hit the window when the device rebuilds its internal state. + /// Used during an RNDIS soft reset: the device discards all outstanding packets, and continuing + /// to send frames to it during that time is only a waste, and may hit the window when the device + /// rebuilds its internal state. /// - /// `SetPaused(true)` is **synchronous**: after it returns it is guaranteed that the RX injection thread has stopped at the pause branch, - /// and will neither touch rx_ring_ nor write frames to the link any more. + /// `SetPaused(true)` is **synchronous**: after it returns it is guaranteed that the RX injection + /// thread has stopped at the pause branch, and will neither touch rx_ring_ nor write frames to + /// the link any more. /// - /// This synchronization is required; a flag alone cannot give the guarantee: the worker may have just passed the flag check and be about - /// to write out a batch of taken frames, while the caller thinks it has already stopped. That is exactly how one - /// rx_write_batch (16 frames) once slipped out. + /// This synchronization is required; a flag alone cannot give the guarantee: the worker may have + /// just passed the flag check and be about to write out a batch of taken frames, while the caller + /// thinks it has already stopped. That is exactly how one rx_write_batch (16 frames) once slipped + /// out. /// - /// The TX direction cannot get an equally strong guarantee -- it must keep draining BPF, otherwise the kernel buffer would fill up - /// and turn into kernel-side drops. During a pause it instead discards what it reads, and re-checks before each submit slice, - /// so after this function returns at most one already in-transit slice can still finish submitting. + /// The TX direction cannot get an equally strong guarantee; it must keep draining BPF, otherwise + /// the kernel buffer would fill up and turn into kernel-side drops. During a pause it instead + /// discards what it reads, and re-checks before each submit slice, so after this function returns + /// at most one already in-transit slice can still finish submitting. /// - /// WARNING: Must not be called from inside the RX/TX worker threads -- it would deadlock waiting on itself. The existing callers are all on the control path - /// (link state changes, device soft reset), and satisfy this precondition. + /// WARNING: Must not be called from inside the RX/TX worker threads; it would deadlock waiting on + /// itself. The existing callers are all on the control path (link state changes, device soft + /// reset), and satisfy this precondition. void SetPaused(bool paused) noexcept; [[nodiscard]] bool Paused() const noexcept { return paused_.load(std::memory_order_acquire); } @@ -177,6 +191,10 @@ class Bridge { std::unique_ptr rx_ring_; PathCounters counters_; + /// RX drops/errors seen by the RX injection thread (link writes). Kept apart from counters_.rx, + /// which the libusb event thread writes: DirectionCounters is single-writer (relaxed load+store), + /// so sharing it would lose increments. + DirectionCounters rx_inject_counters_; std::atomic tx_backpressure_events_{0}; std::atomic link_kernel_drops_{0}; @@ -187,15 +205,21 @@ class Bridge { std::atomic stop_requested_{false}; std::atomic paused_{false}; - /// The RX injection thread's acknowledgement bit for paused_, which is what SetPaused(true) waits for. + /// The RX injection thread's acknowledgement bit for paused_, which is what SetPaused(true) waits + /// for. /// - /// **Written exclusively** by the RX injection thread: cleared at the start of each loop iteration, and set after confirming it has stopped. - /// Clearing on every iteration is key -- otherwise when SetPaused(false) is immediately followed by SetPaused(true), - /// the latter might read a leftover true from the previous round and return directly, and the guarantee would fail on the spot. + /// **Written exclusively** by the RX injection thread: cleared at the start of each loop + /// iteration, and set after confirming it has stopped. Clearing on every iteration is key: + /// otherwise when SetPaused(false) is immediately followed by SetPaused(true), the latter might + /// read a leftover true from the previous round and return directly, and the guarantee would fail + /// on the spot. std::atomic rx_paused_ack_{false}; /// The frame view array reused by the RX injection thread, avoiding an allocation per batch. std::vector rx_batch_; + + /// Learns the device's own IPv4 address from frames it sends (RX thread writes). + PeerAddressObserver peer_observer_; }; /// Renders a statistics snapshot into one line of human-readable text. diff --git a/include/tetherkitnext/core/peer_address.h b/include/tetherkitnext/core/peer_address.h new file mode 100644 index 0000000..8785a4e --- /dev/null +++ b/include/tetherkitnext/core/peer_address.h @@ -0,0 +1,105 @@ +// Passive discovery of the attached device's own IPv4 address. +// +// Why: not every RNDIS device is a phone that hands out a DHCP lease. Drones, remote controllers, +// FPV goggles, single-board computers in USB gadget mode and cameras are *local links*: they often +// have a fixed address and no DHCP server, so the host never learns where the device is. The bridge +// sees every frame the device sends, so it can learn that address without sending anything. +// +// Only frames that can *only* originate from the device itself are trusted. A phone forwards +// internet traffic, so the IPv4 source of an ordinary unicast packet is usually some remote server, +// not the phone. These are trustworthy: +// * ARP: the sender protocol address is the sender's own interface address (ARP is never +// forwarded across a router). Probes (sender 0.0.0.0) are ignored. +// * IPv4 to the limited broadcast 255.255.255.255 or to link-local multicast 224.0.0.0/24 (mDNS, +// IGMP, DHCP server replies): routers never forward these, so the source is on the link. +// +// Hot path: called for every device→host frame from the RX injection thread. No allocation, no +// locks, a handful of byte loads, and one relaxed atomic store only when the address changes. +#pragma once + +#include "tetherkitnext/common/byte_order.h" + +#include +#include +#include +#include + +namespace tetherkitnext::core { + +inline constexpr std::uint16_t kEtherTypeIpv4 = 0x0800; +inline constexpr std::uint16_t kEtherTypeArp = 0x0806; + +/// Whether `address` (host order) can be a unicast interface address. +[[nodiscard]] constexpr bool IsPlausibleHostIpv4(std::uint32_t address) noexcept { + const std::uint32_t first_octet = address >> 24; + return address != 0 && address != 0xFFFFFFFFU // unspecified, broadcast + && first_octet != 0 && first_octet != 127 // "this network", loopback + && first_octet < 224; // multicast and reserved +} + +/// The IPv4 address (host byte order) this frame proves the sender owns, or 0. +[[nodiscard]] inline std::uint32_t OnLinkSenderIpv4(std::span frame) noexcept { + constexpr std::size_t kEthernetHeader = 14; + if (frame.size() < kEthernetHeader) { + return 0; + } + const std::byte* base = frame.data(); + const std::uint16_t ether_type = LoadBe16(base + 12); + + if (ether_type == kEtherTypeArp) { + // htype(2) ptype(2) hlen(1) plen(1) oper(2) sha(6) spa(4) tha(6) tpa(4) = 28 + constexpr std::size_t kArpBody = 28; + if (frame.size() < kEthernetHeader + kArpBody) { + return 0; + } + const std::byte* arp = base + kEthernetHeader; + if (LoadBe16(arp) != 1 || LoadBe16(arp + 2) != kEtherTypeIpv4 || arp[4] != std::byte{6} || + arp[5] != std::byte{4}) { + return 0; + } + const std::uint32_t sender = LoadBe(arp + 14); + return IsPlausibleHostIpv4(sender) ? sender : 0; + } + + if (ether_type == kEtherTypeIpv4) { + constexpr std::size_t kIpv4MinHeader = 20; + if (frame.size() < kEthernetHeader + kIpv4MinHeader) { + return 0; + } + const std::byte* ip = base + kEthernetHeader; + if ((std::to_integer(ip[0]) >> 4) != 4) { + return 0; + } + const std::uint32_t source = LoadBe(ip + 12); + const std::uint32_t destination = LoadBe(ip + 16); + const bool link_scoped_destination = + destination == 0xFFFFFFFFU || (destination & 0xFFFFFF00U) == 0xE0000000U; + return link_scoped_destination && IsPlausibleHostIpv4(source) ? source : 0; + } + + return 0; +} + +/// Remembers the most recent address `OnLinkSenderIpv4` found. +/// +/// One writer (the RX injection thread), any number of readers (status snapshots). The value is a +/// hint for the UI, so relaxed ordering suffices. +class PeerAddressObserver { + public: + void Observe(std::span frame) noexcept { + const std::uint32_t address = OnLinkSenderIpv4(frame); + if (address != 0 && address != latest_.load(std::memory_order_relaxed)) { + latest_.store(address, std::memory_order_relaxed); + } + } + + /// Host byte order; 0 when nothing has been seen yet. + [[nodiscard]] std::uint32_t Latest() const noexcept { + return latest_.load(std::memory_order_relaxed); + } + + private: + std::atomic latest_{0}; +}; + +} // namespace tetherkitnext::core diff --git a/include/tetherkitnext/core/runtime.h b/include/tetherkitnext/core/runtime.h index 5f07db5..6a24a2b 100644 --- a/include/tetherkitnext/core/runtime.h +++ b/include/tetherkitnext/core/runtime.h @@ -1,28 +1,34 @@ -// Runtime orchestration: assembles USB, the RNDIS state machine, feth, BPF and the bridge into a runnable driver. +// Runtime orchestration: assembles USB, the RNDIS state machine, feth, BPF and the bridge into a +// runnable driver. // -// * Startup order (each step depends on the product of the previous one; they cannot be swapped) * +// Startup order (each step depends on the product of the previous one; they cannot be swapped): // -// 1. Permission check -- give a plain-language error early, rather than letting a pile of EPERM pop up later +// 1. Permission check: give a plain-language error early, rather than letting a pile of EPERM pop +// up later // 2. libusb context + event thread // 3. Discover and open the RNDIS device (claim the two interfaces, parse the endpoints) -// 4. RNDIS control channel + state machine Start() -// └→ Only this step yields: the device MAC, the negotiated MTU, the aggregation limit, the alignment requirement -// 5. Use the result of step 4 to create the feth pair (system-side MAC = the MAC the device reported) +// 4. RNDIS control channel + state machine Start() └→ Only this step yields: the device MAC, the +// negotiated MTU, the aggregation limit, the alignment requirement +// 5. Use the result of step 4 to create the feth pair (system-side MAC = the MAC the device +// reported) // 6. Open BPF on the driver-side interface // 7. Use the negotiated parameters of step 4 to create the USB data channel // 8. Start the bridge layer // 9. The control thread enters its loop: periodic Poll() (keepalive + draining device pushes) // -// Why feth must be created **after** RNDIS negotiation: the MAC of the system-side NIC must be set to -// the OID_802_3_PERMANENT_ADDRESS reported by the device, and the MTU must use the negotiation result -- neither value can be obtained -// before step 4. And the MAC must be set before the interface goes IFF_UP. +// Why feth must be created **after** RNDIS negotiation: the MAC of the system-side NIC must be +// set to the OID_802_3_PERMANENT_ADDRESS reported by the device, and the MTU must use the +// negotiation result: neither value can be obtained before step 4. And the MAC must be set before +// the interface goes IFF_UP. // -// * Shutdown order is the strict reverse of startup order * +// Shutdown order is the strict reverse of startup order: // -// Bridge layer -> data channel (wait for in-flight transfers to be reclaimed) -> BPF -> feth -> state machine HALT -> device -> libusb +// Bridge layer -> data channel (wait for in-flight transfers to be reclaimed) -> BPF -> feth -> +// state machine HALT -> device -> libusb // -// The step "data channel waits for in-flight transfers to be reclaimed" must complete **before** destroying the device, -// otherwise it is a use-after-free (see the explanation in usb/data_channel.h). +// The step "data channel waits for in-flight transfers to be reclaimed" must complete **before** +// destroying the device, otherwise it is a use-after-free (see the explanation in +// usb/data_channel.h). #pragma once #include @@ -45,23 +51,30 @@ namespace tetherkitnext::core { -/// Lifecycle state of the runtime. This is the only state dimension the host (CLI / GUI) needs to care about. +/// Lifecycle state of the runtime. This is the only state dimension the host (CLI / GUI) needs to +/// care about. enum class RunState : std::uint8_t { - kIdle, ///< Created, Start() not yet called. - kStarting, ///< The control thread is running the startup sequence (enumerate -> handshake -> create NIC -> open bridge). + kIdle, ///< Created, Start() not yet called. + /// The control thread is running the startup sequence (enumerate -> handshake -> create NIC -> + /// open bridge). + kStarting, kRunning, ///< The data path is up and running. kStopping, ///< Being torn down in reverse order. kStopped, ///< Stopped normally. - kFailed, ///< Startup failed or an unrecoverable error occurred while running; see RuntimeSnapshot::fatal_message for the cause. + /// Startup failed or an unrecoverable error occurred while running; see + /// RuntimeSnapshot::fatal_message for the cause. + kFailed, }; [[nodiscard]] std::string_view RunStateName(RunState state) noexcept; /// An event the runtime reports outward. /// -/// "Events + the host queues them itself" is used instead of having the host implement StateMachineObserver directly: -/// the latter's five callbacks have varied semantics and take C++ references, which cross-language hosts cannot use; and in a callback the host -/// can easily call back into the runtime by accident (e.g. "stop on receiving a fatal error"), which is a self-wait deadlock. +/// "Events + the host queues them itself" is used instead of having the host implement +/// StateMachineObserver directly: the latter's five callbacks have varied semantics and take C++ +/// references, which cross-language hosts cannot use; and in a callback the host can easily call +/// back into the runtime by accident (e.g. "stop on receiving a fatal error"), which is a self-wait +/// deadlock. struct RuntimeEvent { enum class Kind : std::uint8_t { kRndisState, ///< a = rndis::State before the transition, b = after. @@ -80,11 +93,13 @@ struct RuntimeEvent { /// Event sink: the host implements it to receive runtime events. /// -/// * Two hard constraints * -/// 1. Callbacks **always occur on the control thread** (all event sources are on that one thread), but the host's own -/// thread may be calling Snapshot() at the same time -- not a single lock that should be added in the implementation may be omitted. -/// 2. **The implementation must never call any Runtime method.** Stop() has to join the control thread, -/// and calling it from an event is a self-wait deadlock. The correct approach is to queue the event and let the host thread handle it. +/// Two hard constraints: +/// 1. Callbacks **always occur on the control thread** (all event sources are on that one +/// thread), but the host's own thread may be calling Snapshot() at the same time, not a single +/// lock that should be added in the implementation may be omitted. +/// 2. **The implementation must never call any Runtime method.** Stop() has to join the control +/// thread, and calling it from an event is a self-wait deadlock. The correct approach is to +/// queue the event and let the host thread handle it. class RuntimeEventSink { public: RuntimeEventSink() = default; @@ -99,9 +114,10 @@ class RuntimeEventSink { /// A complete observable snapshot of the runtime. /// -/// Why copy the whole block rather than provide a bunch of per-item accessors: what the host needs is a **consistent** set of values -/// (a UI whose state does not match the NIC name is hard to make sense of), and per-item reads would give torn combinations. One copy is -/// a few hundred bytes, which is no problem at all for a 2 Hz refresh rate. +/// Why copy the whole block rather than provide a bunch of per-item accessors: what the host needs +/// is a **consistent** set of values (a UI whose state does not match the NIC name is hard to make +/// sense of), and per-item reads would give torn combinations. One copy is a few hundred bytes, +/// which is no problem at all for a 2 Hz refresh rate. struct RuntimeSnapshot { RunState run_state = RunState::kIdle; rndis::State rndis_state = rndis::State::kUninitialized; @@ -124,24 +140,27 @@ struct RuntimeSnapshot { std::string fatal_message; }; -/// Runtime configuration. The derivation of the default values is explained in each field's comment. +/// Runtime configuration. The derivation of the default values is explained in each field's +/// comment. struct RuntimeConfig { /// Device filter. All 0 means use the first RNDIS device found. usb::DeviceFilter device_filter; /// The desired MTU. Lowered by negotiation when the device cannot fit it. /// - /// The upper limit is constrained by feth's sysctl net.link.fake.max_mtu (2048 on this machine). + /// The upper limit is constrained by feth's sysctl net.link.fake.max_mtu (2048 on macOS 26). std::uint32_t mtu = rndis::kDefaultMtu; - /// Specifies the feth interface name (such as "feth7"); empty means let the kernel choose the number automatically. + /// Specifies the feth interface name (such as "feth7"); empty means let the kernel choose the + /// number automatically. std::string system_interface_name; std::string driver_interface_name; /// Whether to set the system-side NIC's MAC to the address the device reported. /// - /// On by default: under RNDIS semantics the device is this NIC, and the peer's ARP table and DHCP lease are both built on this - /// MAC. Turning it off is only useful when investigating MAC conflicts. + /// On by default: under RNDIS semantics the device is this NIC, and the peer's ARP table and DHCP + /// lease are both built on this MAC. Turning it off is only useful when investigating MAC + /// conflicts. bool adopt_device_mac = true; rndis::StateMachineConfig rndis; @@ -152,7 +171,8 @@ struct RuntimeConfig { /// Statistics report period (milliseconds); 0 means no reports. std::uint32_t stats_interval_millis = 5'000; - /// Event sink. nullptr means no event reports are needed (the CLI does not need them; it reads the logs). + /// Event sink. nullptr means no event reports are needed (the CLI does not need them; it reads + /// the logs). /// /// The lifetime is the caller's responsibility; it must outlive the Runtime. RuntimeEventSink* event_sink = nullptr; @@ -160,27 +180,28 @@ struct RuntimeConfig { /// Assembles and runs the whole driver. /// -/// * Threading model: Start() is **non-blocking** * +/// Threading model: Start() is **non-blocking**: /// -/// Runtime owns a control thread itself, and the startup sequence, the keepalive loop and the shutdown teardown all -/// run on it **entirely**. The host thread is only responsible for issuing commands and reading snapshots. +/// Runtime owns a control thread itself, and the startup sequence, the keepalive loop and the +/// shutdown teardown all run on it **entirely**. The host thread is only responsible for issuing +/// commands and reading snapshots. /// /// Why it must be this way: -/// * The startup sequence includes the USB handshake, which takes hundreds of milliseconds to several seconds on slow devices; blocking the GUI main thread is not acceptable; +/// * The startup sequence includes the USB handshake, which takes hundreds of milliseconds to +/// several seconds on slow devices; blocking the GUI main thread is not acceptable; /// * The control channel uses libusb's synchronous API, and the synchronous API returns -/// LIBUSB_ERROR_BUSY on the libusb event thread -- having Runtime create its own thread removes the need to require that the host "must -/// call from some specific thread", a convention that is very easy to violate; -/// * The teardown order includes RNDIS's graceful shutdown (control messages must be sent); putting it on the same -/// thread as well naturally satisfies `StateMachine`'s constraint that "all methods are called on the same thread". +/// LIBUSB_ERROR_BUSY on the libusb event thread; having Runtime create its own thread removes +/// the need to require that the host "must call from some specific thread", a convention that +/// is very easy to violate; +/// * The teardown order includes RNDIS's graceful shutdown (control messages must be sent); +/// putting it on the same thread as well naturally satisfies `StateMachine`'s constraint that +/// "all methods are called on the same thread". /// -/// Usage: -/// ``` -/// TETHERKITNEXT_ASSIGN_OR_RETURN(auto runtime, Runtime::Create(config)); +/// Usage: ``` TETHERKITNEXT_ASSIGN_OR_RETURN(auto runtime, Runtime::Create(config)); /// TETHERKITNEXT_RETURN_IF_ERROR(runtime->Start()); // returns immediately -/// runtime->WaitUntilStopped(); // CLI: park the main thread -/// runtime->Stop(); // idempotent -/// ``` -/// The GUI does not call WaitUntilStopped; instead it calls Snapshot() periodically to refresh the UI. +/// runtime->WaitUntilStopped(); // CLI: park the main thread runtime->Stop(); +/// // idempotent ``` The GUI does not call WaitUntilStopped; instead it calls Snapshot() +/// periodically to refresh the UI. class Runtime final : public rndis::StateMachineObserver { public: [[nodiscard]] static Result> Create(const RuntimeConfig& config); @@ -194,23 +215,28 @@ class Runtime final : public rndis::StateMachineObserver { /// Starts the control thread and returns immediately. /// - /// A successful return only means "the start request has been accepted"; real success or failure must be checked via Snapshot().run_state. - /// The only thing that returns failure **synchronously** is the root check -- it needs no I/O, and reporting it early lets the - /// command line give an immediate plain-language hint. + /// A successful return only means "the start request has been accepted"; real success or failure + /// must be checked via Snapshot().run_state. The only thing that returns failure + /// **synchronously** is the root check; it needs no I/O, and reporting it early lets the command + /// line give an immediate plain-language hint. [[nodiscard]] Status Start(); - /// Blocks until the runtime stops (normal shutdown or fatal error). The command line uses it to park the main thread. + /// Blocks until the runtime stops (normal shutdown or fatal error). The command line uses it to + /// park the main thread. void WaitUntilStopped(); - /// Requests shutdown. May be called from a signal handler or any thread; async-signal-safe (only writes an atomic). + /// Requests shutdown. May be called from a signal handler or any thread; async-signal-safe (only + /// writes an atomic). /// - /// The cost is that the control thread takes up to one loop period (<=250 ms) to see it. To stop immediately use - /// Stop(), which additionally wakes the control thread -- but Stop() takes a lock and is **not** async-signal-safe. + /// The cost is that the control thread takes up to one loop period (<=250 ms) to see it. To stop + /// immediately use Stop(), which additionally wakes the control thread, but Stop() takes a lock + /// and is **not** async-signal-safe. void RequestStop() noexcept { stop_requested_.store(true, std::memory_order_release); } /// Requests shutdown and waits for the control thread to finish all teardown. Idempotent. /// - /// WARNING: Must not be called from the event sink (RuntimeEventSink) -- that is the control thread itself, a self-wait deadlock. + /// WARNING: Must not be called from the event sink (RuntimeEventSink); that is the control thread + /// itself, a self-wait deadlock. void Stop(); /// Takes a consistent state snapshot. **Callable from any thread**. @@ -219,7 +245,7 @@ class Runtime final : public rndis::StateMachineObserver { /// System-side NIC name, used to print "what to do next" for the user. [[nodiscard]] std::string SystemInterfaceName() const; - // ---- StateMachineObserver (all invoked on the control thread) ---- + // StateMachineObserver (all invoked on the control thread) void OnStateChanged(rndis::State from, rndis::State to) override; void OnNegotiated(const rndis::NegotiatedParameters& parameters, const rndis::DeviceInfo& info) override; @@ -233,7 +259,8 @@ class Runtime final : public rndis::StateMachineObserver { /// Control thread body: startup sequence -> control loop -> teardown. void RunControlThread() noexcept; - /// The complete startup sequence (the body of the original Start()). Runs only on the control thread. + /// The complete startup sequence (the body of the original Start()). Runs only on the control + /// thread. [[nodiscard]] Status RunStartSequence(); /// The loop of keepalive + statistics + shutdown checks. Runs only on the control thread. @@ -248,7 +275,8 @@ class Runtime final : public rndis::StateMachineObserver { /// Records a fatal error: writes it into the snapshot, sets the kFailed flag, reports the event. void RecordFatal(const Error& error); - /// Refreshes the current state of each component into the snapshot. Called only on the control thread. + /// Refreshes the current state of each component into the snapshot. Called only on the control + /// thread. void RefreshSnapshot(); /// Hands an event to the host. A no-op when the sink is null. @@ -259,10 +287,11 @@ class Runtime final : public rndis::StateMachineObserver { RuntimeConfig config_; - // ---- The following components are **created, accessed and destroyed only by the control thread** ---- + // The following components are **created, accessed and destroyed only by the control thread** // - // The host thread always reads state through snapshot_ and never touches these pointers -- otherwise the reset() in Stop() - // and the host's reads would constitute a data race, which on real hardware shows up as random crashes. + // The host thread always reads state through snapshot_ and never touches these pointers; + // otherwise the reset() in Stop() and the host's reads would constitute a data race, which on + // real hardware shows up as random crashes. std::unique_ptr usb_context_; std::unique_ptr device_; std::unique_ptr control_channel_; @@ -274,21 +303,26 @@ class Runtime final : public rndis::StateMachineObserver { std::thread control_thread_; - /// Protects snapshot_. The reading side is the host thread (the GUI, once every 500 ms), the writing side is the control thread, - /// contention is extremely light, and an ordinary mutex suffices. + /// Protects snapshot_. The reading side is the host thread (the GUI, once every 500 ms), the + /// writing side is the control thread, contention is extremely light, and an ordinary mutex + /// suffices. mutable std::mutex snapshot_mutex_; RuntimeSnapshot snapshot_; - /// Lets Stop() immediately wake a sleeping control thread, without waiting for a full loop period. + /// Lets Stop() immediately wake a sleeping control thread, without waiting for a full loop + /// period. std::mutex stop_mutex_; std::condition_variable stop_condition_; std::atomic stop_requested_{false}; std::atomic fatal_error_{false}; - /// Read and written only on the host thread (Start / Stop / destructor); no synchronization needed. - bool started_ = false; - bool stopped_ = false; + /// Read and written only on the host thread (Start / Stop / destructor); no synchronization + /// needed. + // Atomic: Stop() can race the destructor or another host thread (the C ABI calls tk_session_stop + // from the daemon's XPC queue). + std::atomic started_{false}; + std::atomic stopped_{false}; }; } // namespace tetherkitnext::core diff --git a/include/tetherkitnext/net/bpf_link.h b/include/tetherkitnext/net/bpf_link.h index d2077ce..4d39a40 100644 --- a/include/tetherkitnext/net/bpf_link.h +++ b/include/tetherkitnext/net/bpf_link.h @@ -1,49 +1,52 @@ -// BPF link backend: reads and writes raw Ethernet frames directly on the driver-side interface of feth. +// BPF link backend: reads and writes raw Ethernet frames directly on the driver-side interface of +// feth. // -// * Every ioctl ordering and parameter choice in this file has a source-level reason; read all the comments before changing anything * +// Every ioctl ordering and parameter choice in this file has a source-level reason; read all the +// comments before changing anything. // // Configuration sequence (the order has hard constraints, from xnu bsd/net/bpf.c): -// 1. open("/dev/bpf%d") -- macOS **has no** /dev/bpf cloning node; the numbers must be iterated. -// 2. BIOCSBLEN -- **must come before BIOCSETIF** (bpf.c has -// `if (d->bd_bif != 0) return EINVAL`). -// 3. BIOCSHDRCMPLT = 1 -- **must come before BIOCSBATCHWRITE**, and it decides whether frames -// pass through as-is (see below). -// 4. BIOCSETIF -- bind to the interface; only afterwards can the DLT be queried. -// 5. BIOCGDLT -- verify it is DLT_EN10MB. -// 6. BIOCIMMEDIATE = 1 -- determines the latency characteristics of reads (see below). -// 7. BIOCSSEESENT = 0 -- see only the input direction (see below). -// 8. BIOCSBATCHWRITE = 1 -- optional optimization, feature probe. -// 9. BIOCSNOTSTAMP = 1 -- optional optimization, feature probe. +// 1. open("/dev/bpf%d") macOS has no /dev/bpf cloning node; the numbers must be iterated. +// 2. BIOCSBLEN must come before BIOCSETIF (bpf.c has +// `if (d->bd_bif != 0) return EINVAL`). +// 3. BIOCSHDRCMPLT = 1 must come before BIOCSBATCHWRITE, and it decides whether frames pass +// through as-is (see below). +// 4. BIOCSETIF bind to the interface; only afterwards can the DLT be queried. +// 5. BIOCGDLT verify it is DLT_EN10MB. +// 6. BIOCIMMEDIATE = 1 determines the latency characteristics of reads (see below). +// 7. BIOCSSEESENT = 0 see only the input direction (see below). +// 8. BIOCSBATCHWRITE = 1 optional optimization, feature probe. +// 9. BIOCSNOTSTAMP = 1 optional optimization, feature probe. // // The three most critical parameter choices: // -// * **BIOCSHDRCMPLT = 1 is mandatory.** With hdrcmplt=0, bpfwrite strips the first -// 14 bytes of user data into a sockaddr and lets ether_frameout rebuild the frame header -- the source MAC would be -// rewritten by the driver, and the frames forwarded out would no longer be the original frames sent by the device. Only hdrcmplt=1 takes -// DLIL_OUTPUT_FLAGS_RAW, passing frames through as-is. +// * BIOCSHDRCMPLT = 1 is mandatory. With hdrcmplt=0, bpfwrite strips the first 14 bytes of user +// data into a sockaddr and lets ether_frameout rebuild the frame header, which rewrites the +// source MAC, so the forwarded frames would no longer be the original frames sent by the +// device. Only hdrcmplt=1 takes DLIL_OUTPUT_FLAGS_RAW and passes frames through as-is. // -// * **BIOCSSEESENT = 0 happens to filter out the frames we wrote ourselves.** When attached to the driver-side interface: -// frames the host sends from the system side are the **input** direction here; frames we write in are the -// **output** direction here. SEESENT=0 -> bd_direction = BPF_D_IN, keeping only input, -// which is exactly what we want to forward to USB. If not set, we would read back the frames we just wrote, forming a loop. +// * BIOCSSEESENT = 0 filters out the frames we wrote ourselves. On the driver-side interface, +// frames the host sends from the system side are the input direction and frames we write are +// the output direction. SEESENT=0 sets bd_direction = BPF_D_IN, keeping only input, which is +// exactly what is forwarded to USB. Without it we would read back our own writes and loop. // -// * **BIOCIMMEDIATE = 1 + a dedicated thread doing blocking read() is the optimal model; do not use kqueue.** -// Under immediate, bpf_wakeup fires on every arriving packet, and after read() wakes up it delivers all packets accumulated in the meantime -// as one batch -- low latency at low rates, automatically aggregating into large batches at high rates (behavior similar to Linux's NAPI), -// costing only one system call per batch. The kqueue approach has exactly the same readiness criterion, but needs an extra kevent(). -// And if immediate is not enabled while wanting to avoid "returns only once the buffer fills", the only option is to rely on -// BIOCSRTIMEOUT -- but its actual resolution is pinned by the 10 ms clock tick -// (the kernel stores tvtohz(tv)-1, hz=100 on this machine), and the latency is unacceptable. +// * BIOCIMMEDIATE = 1 plus a dedicated thread doing blocking read() is the best model; do not use +// kqueue. With immediate, bpf_wakeup fires on every arriving packet and read() delivers +// everything accumulated meanwhile as one batch: low latency at low rates, automatic +// aggregation at high rates (similar to Linux NAPI), one system call per batch. kqueue has the +// same readiness criterion but needs an extra kevent(). Without immediate, the only way to +// avoid waiting for the buffer to fill is BIOCSRTIMEOUT, whose resolution is pinned to the 10 +// ms clock tick (the kernel stores tvtohz(tv)-1, hz=100), which is too slow. // // Two read details that must be remembered: // -// * **The read() buffer length must exactly equal bd_bufsize**, otherwise bpfread returns at the start with -// `if (uio_resid(uio) != d->bd_bufsize) return EINVAL`. And BIOCSBLEN, when the limit is exceeded, **does not report an error**, -// silently clamps to the cap and writes the actual value back into the parameter, so the written-back value must be used. +// * The read() buffer length must exactly equal bd_bufsize, otherwise bpfread returns EINVAL at +// once (`if (uio_resid(uio) != d->bd_bufsize) return EINVAL`). BIOCSBLEN does not report an +// error when the limit is exceeded; it silently clamps to the cap and writes the actual value +// back into the parameter, so use the written-back value. // -// * **Records must be iterated with bh_hdrlen, not sizeof(struct bpf_hdr).** -// Under LP64, sizeof is 20 (the 18 bytes of content are padded), while the kernel writes -// a bh_hdrlen of 18 for DLT_EN10MB. Using 20 would immediately misalign. +// * Iterate records with bh_hdrlen, not sizeof(struct bpf_hdr). Under LP64, sizeof is 20 (the 18 +// bytes of content are padded) while the kernel writes a bh_hdrlen of 18 for DLT_EN10MB. Using +// 20 would misalign at once. #pragma once #include @@ -63,36 +66,42 @@ namespace tetherkitnext::net { struct BpfConfig { /// Kernel capture buffer size. /// - /// The upper limit is the sysctl debug.bpf_bufsize_cap (32 MiB on macOS 13+); exceeding it is silently - /// truncated. The kernel allocates **2 copies** of this size for every descriptor (store + free double buffering), - /// so the actual wired memory usage is twice this value. + /// The upper limit is the sysctl debug.bpf_bufsize_cap (32 MiB on macOS 13+); exceeding it is + /// silently truncated. The kernel allocates **2 copies** of this size for every descriptor (store + /// + free double buffering), so the actual wired memory usage is twice this value. /// - /// Derivation of the 4 MiB default: at full 1 Gbps speed, 1514-byte frames are about 82k pps; with a single copyout - /// window estimated at a worst-case 10 ms, about 1.2 MB of buffering is needed; 4 MiB leaves a 3x margin. Anything larger just - /// wastes wired memory, since BPF has only two buffers, and enlarging each one does not improve the packet-loss window. + /// Derivation of the 4 MiB default: at full 1 Gbps speed, 1514-byte frames are about 82k pps; + /// with a single copyout window estimated at a worst-case 10 ms, about 1.2 MB of buffering is + /// needed; 4 MiB leaves a 3x margin. Anything larger just wastes wired memory, since BPF has only + /// two buffers, and enlarging each one does not improve the packet-loss window. std::uint32_t kernel_buffer_bytes = 4U * 1024 * 1024; - /// Per-frame length limit (including the Ethernet header). Should equal interface MTU + Ethernet header, and must not exceed MTU + 18. + /// Per-frame length limit (including the Ethernet header). Should equal interface MTU + Ethernet + /// header, and must not exceed MTU + 18. std::uint32_t max_frame_bytes = 1518; /// The maximum number of frames one ReadFrames call can decode. /// - /// This is the capacity of the FrameView array. A 4 MiB buffer can hold at most about 4Mi/32 ≈ 131k minimum-size - /// frames (64-byte frame + 18-byte header + alignment), but in practice they will not all be minimum-size; 8192 covers - /// the vast majority of batches, and the excess is left to be parsed after the next read. + /// This is the capacity of the FrameView array. A 4 MiB buffer can hold at most about 4Mi/32 ≈ + /// 131k minimum-size frames (64-byte frame + 18-byte header + alignment), but in practice they + /// will not all be minimum-size; 8192 covers the vast majority of batches. Records beyond the + /// limit are **dropped** (the read has already copied them out of the kernel; ReadFrames logs + /// kNetBpfBatchFrameLimit), so keep this large. std::size_t max_frames_per_batch = 8192; /// Whether to try enabling batch writes (BIOCSBATCHWRITE, macOS 14+). bool try_batch_write = true; - /// Whether to try turning off capture timestamps (BIOCSNOTSTAMP), saving one microtime() per frame. + /// Whether to try turning off capture timestamps (BIOCSNOTSTAMP), saving one microtime() per + /// frame. bool try_disable_timestamp = true; - /// Read timeout. Determines "how long after Interrupt() we can stop when there is no traffic at all". + /// Read timeout. Determines "how long after Interrupt() we can stop when there is no traffic at + /// all". /// - /// Note that the kernel's actual resolution is 10 ms (it stores tvtohz(tv) - 1 ticks, and on this machine - /// kern.clockrate hz=100), and passing {0,0} becomes **blocking forever**. 200 ms lets - /// shutdown be timely enough without producing needless wakeups. + /// The kernel's actual resolution is 10 ms (it stores tvtohz(tv) - 1 ticks, and kern.clockrate + /// hz=100), and passing {0,0} blocks forever. 200 ms keeps shutdown timely without needless + /// wakeups. std::uint32_t read_timeout_millis = 200; }; @@ -106,7 +115,8 @@ class BpfLink final : public LinkBackend { [[nodiscard]] static Result> Open(std::string_view interface_name, const BpfConfig& config); - // Copy and move are already deleted in the base class LinkBackend; they are restated explicitly here to satisfy static analysis. + // Copy and move are already deleted in the base class LinkBackend; they are restated explicitly + // here to satisfy static analysis. BpfLink(const BpfLink&) = delete; BpfLink& operator=(const BpfLink&) = delete; BpfLink(BpfLink&&) = delete; @@ -154,27 +164,31 @@ class BpfLink final : public LinkBackend { bool batch_write_enabled_ = false; bool timestamp_disabled_ = false; - /// Read buffer. Its length must exactly equal kernel_buffer_bytes_ (a hard requirement of bpfread). + /// Read buffer. Its length must exactly equal kernel_buffer_bytes_ (a hard requirement of + /// bpfread). std::vector read_buffer_; /// Frame views decoded in this batch, pointing into read_buffer_. std::vector read_frames_; /// The kernel's cumulative drop count (bs_drop) from the most recent successful read. /// - /// When BIOCGSTATS occasionally fails, **keep the previous value** rather than reporting 0: bs_drop is a cumulative counter, - /// and consumers use it for "current - previous" differencing; reporting 0 would make the difference under/overflow on unsigned numbers, - /// printing an astronomical "kernel drops" figure. Accessed only by the read thread, so no atomic is needed. + /// When BIOCGSTATS occasionally fails, **keep the previous value** rather than reporting 0: + /// bs_drop is a cumulative counter, and consumers use it for "current - previous" differencing; + /// reporting 0 would make the difference under/overflow on unsigned numbers, printing an + /// astronomical "kernel drops" figure. Accessed only by the read thread, so no atomic is needed. std::uint64_t last_kernel_drops_ = 0; /// Assembly buffer for batch writes. std::vector write_buffer_; - /// Stop flag. After Interrupt() sets it, ReadFrames returns an empty batch within one read-timeout period. + /// Stop flag. After Interrupt() sets it, ReadFrames returns an empty batch within one + /// read-timeout period. /// - /// Choice of wakeup mechanism: BPF's read() blocks, and there are three ways to interrupt it -- + /// Choice of wakeup mechanism: BPF's read() blocks, and there are three ways to interrupt it /// (a) send a signal so BPF_SLEEP (with PCATCH) returns EINTR; /// (b) close the fd (has a use-after-close race; not acceptable); /// (c) set a moderate BIOCSRTIMEOUT so read() wakes up periodically to check this flag. - /// Choose (c): no signal handler needs to be installed in the process, and there is no race. BIOCIMMEDIATE=1 guarantees - /// it still returns immediately when there are packets; the read timeout only affects "how quickly we respond to shutdown when there is no traffic at all". + /// Choose (c): no signal handler needs to be installed in the process, and there is no race. + /// BIOCIMMEDIATE=1 guarantees it still returns immediately when there are packets; the read + /// timeout only affects "how quickly we respond to shutdown when there is no traffic at all". std::atomic interrupted_{false}; }; diff --git a/include/tetherkitnext/net/darwin_abi.h b/include/tetherkitnext/net/darwin_abi.h index 5fbd332..17694ae 100644 --- a/include/tetherkitnext/net/darwin_abi.h +++ b/include/tetherkitnext/net/darwin_abi.h @@ -1,22 +1,26 @@ // Darwin private ABI declarations. // -// The things declared in this file are **not** in the public macOS SDK, yet the driver must use them. All definitions are copied -// from Apple's open-source xnu sources, and verified locally with static_assert + measured ioctl numbers. +// The things declared in this file are **not** in the public macOS SDK, yet the driver must use +// them. All definitions are copied from Apple's open-source xnu sources, and verified locally with +// static_assert + measured ioctl numbers. // // Why dare to use a private ABI (and the risk assessment): // * `net/if_fake_var.h` is byte-for-byte identical (same md5) across all release tags from // xnu-7195 (macOS 11) to xnu-12377 (macOS 26); it has not changed a single byte in 15 years. -// `ifconfig fethN peer fethM` uses exactly this ABI, and Apple's own ifconfig -// depends on it, so it is effectively frozen. -// * The same goes for `struct ifdrv`, and its size directly participates in the _IOW macro's computation of the ioctl number -- -// if the size is computed wrongly, the ioctl number is wrong, and the kernel returns ENOTTY without doing anything dangerous. -// The static_assert below pins the size to 40. -// * BPF's private ioctls (BIOCSBATCHWRITE / BIOCSNOTSTAMP) are **optional optimizations**, -// always feature-probed at runtime, falling back to the generic path on failure, without affecting functional correctness. -// macOS 26 moved them from net/bpf.h to net/bpf_private.h (a file the SDK does not provide). +// `ifconfig fethN peer fethM` uses exactly this ABI, and Apple's own ifconfig depends on it, so +// it is effectively frozen. +// * The same goes for `struct ifdrv`, and its size directly participates in the _IOW macro's +// computation of the ioctl number; if the size is computed wrongly, the ioctl number is wrong, +// and the kernel returns ENOTTY without doing anything dangerous. The static_assert below pins +// the size to 40. +// * BPF's private ioctls (BIOCSBATCHWRITE / BIOCSNOTSTAMP) are **optional optimizations**, always +// feature-probed at runtime, falling back to the generic path on failure, without affecting +// functional correctness. macOS 26 moved them from net/bpf.h to net/bpf_private.h (a file the +// SDK does not provide). // -// In one sentence: the functional ABI (feth peer) has been validated for 15 years and is backstopped by static_assert; -// the optimization ABI (BPF batch write) is feature-probed. Neither can silently take the wrong path. +// In one sentence: the functional ABI (feth peer) has been validated for 15 years and is +// backstopped by static_assert; the optimization ABI (BPF batch write) is feature-probed. Neither +// can silently take the wrong path. #pragma once #include @@ -33,7 +37,7 @@ namespace tetherkitnext::net { // ============================================================================= -// struct ifdrv -- the argument of SIOCSDRVSPEC / SIOCGDRVSPEC +// struct ifdrv: the argument of SIOCSDRVSPEC / SIOCGDRVSPEC // // Source: xnu/bsd/net/if.h (with #pragma pack(4), which does not change the layout on LP64/arm64). // The SDK's net/if.h does not have this struct, only the ioctl macro definitions that reference it. @@ -47,20 +51,22 @@ struct IfDrv { void* ifd_data; ///< Command argument. }; -// The size must be exactly 40 bytes: it participates in the ioctl number computation of _IOW('i', 123, struct ifdrv), -// and if computed wrongly the result is a nonexistent ioctl number. Measured SIOCSDRVSPEC = 0x8028697b. -static_assert(sizeof(IfDrv) == 40, "struct ifdrv 必须是 40 字节,否则 ioctl 编号会算错"); +// The size must be exactly 40 bytes: it participates in the ioctl number computation of _IOW('i', +// 123, struct ifdrv), and if computed wrongly the result is a nonexistent ioctl number. Measured +// SIOCSDRVSPEC = 0x8028697b. +static_assert(sizeof(IfDrv) == 40, "struct ifdrv must be 40 bytes, or the ioctl number is wrong"); static_assert(offsetof(IfDrv, ifd_cmd) == 16); static_assert(offsetof(IfDrv, ifd_len) == 24); static_assert(offsetof(IfDrv, ifd_data) == 32); -/// Sets driver-private parameters. Equivalent to the SDK's SIOCSDRVSPEC, but computed with our own IfDrv. +/// Sets driver-private parameters. Equivalent to the SDK's SIOCSDRVSPEC, but computed with our own +/// IfDrv. inline constexpr unsigned long kSetDriverSpec = _IOW('i', 123, IfDrv); /// Reads driver-private parameters. inline constexpr unsigned long kGetDriverSpec = _IOWR('i', 123, IfDrv); -static_assert(kSetDriverSpec == 0x8028'697BUL, "SIOCSDRVSPEC 编号与实测值不符"); -static_assert(kGetDriverSpec == 0xC028'697BUL, "SIOCGDRVSPEC 编号与实测值不符"); +static_assert(kSetDriverSpec == 0x8028'697BUL, "SIOCSDRVSPEC differs from the measured value"); +static_assert(kGetDriverSpec == 0xC028'697BUL, "SIOCGDRVSPEC differs from the measured value"); // ============================================================================= // if_fake (feth) private ABI @@ -68,7 +74,8 @@ static_assert(kGetDriverSpec == 0xC028'697BUL, "SIOCGDRVSPEC 编号与实测值 // Source: xnu/bsd/net/if_fake_var.h // ============================================================================= -/// The driver name of feth (the if_clone name, filled into ifr_name as a wildcard prefix at creation). +/// The driver name of feth (the if_clone name, filled into ifr_name as a wildcard prefix at +/// creation). inline constexpr const char* kFethCloneName = "feth"; /// Command codes for SIOCSDRVSPEC. @@ -116,7 +123,7 @@ struct FethRequest { } u; }; -static_assert(sizeof(FethRequest) == 160, "struct if_fake_request 必须是 160 字节"); +static_assert(sizeof(FethRequest) == 160, "struct if_fake_request must be 160 bytes"); static_assert(offsetof(FethRequest, u) == 32); static_assert(sizeof(FethRequest::u) == 128); static_assert(alignof(FethRequest) == 8); @@ -124,25 +131,27 @@ static_assert(alignof(FethRequest) == 8); // ============================================================================= // BPF private constants and ioctls // -// Source: the PRIVATE section of xnu/bsd/net/bpf.h (moved to bsd/net/bpf_private.h starting with macOS 26). -// Not provided by the SDK; all are feature-probed at runtime. +// Source: the PRIVATE section of xnu/bsd/net/bpf.h (moved to bsd/net/bpf_private.h starting with +// macOS 26). Not provided by the SDK; all are feature-probed at runtime. // ============================================================================= /// Enables batch writes: send multiple frames with one write(). /// -/// The kernel implementation appeared in macOS 14 / xnu-10063; macOS 13 and earlier have nothing at all. -/// Hence probing is required: if the ioctl returns ENOTTY / EINVAL, fall back to per-frame write. +/// The kernel implementation appeared in macOS 14 / xnu-10063; macOS 13 and earlier have nothing at +/// all. Hence probing is required: if the ioctl returns ENOTTY / EINVAL, fall back to per-frame +/// write. /// /// Precondition: BIOCSHDRCMPLT must already be set to 1, and BIOCSETTC must not have been set. inline constexpr unsigned long kBpfSetBatchWrite = _IOW('B', 143, int); -static_assert(kBpfSetBatchWrite == 0x8004'428FUL, "BIOCSBATCHWRITE 编号与实测值不符"); +static_assert(kBpfSetBatchWrite == 0x8004'428FUL, + "BIOCSBATCHWRITE differs from the measured value"); /// Turns off capture timestamps so catchpacket skips the microtime() call. /// -/// We do not need timestamps (frames are forwarded directly to USB); turning them off saves one clock read per frame. -/// Also feature-probed; failure is harmless. +/// We do not need timestamps (frames are forwarded directly to USB); turning them off saves one +/// clock read per frame. Also feature-probed; failure is harmless. inline constexpr unsigned long kBpfSetNoTimestamp = _IOW('B', 145, int); -static_assert(kBpfSetNoTimestamp == 0x8004'4291UL, "BIOCSNOTSTAMP 编号与实测值不符"); +static_assert(kBpfSetNoTimestamp == 0x8004'4291UL, "BIOCSNOTSTAMP differs from the measured value"); /// Explicitly sets the capture direction (a more precise version of BIOCSSEESENT). inline constexpr unsigned long kBpfSetDirection = _IOW('B', 138, unsigned int); @@ -157,41 +166,44 @@ inline constexpr unsigned int kBpfDirectionInOut = kBpfDirectionIn | kBpfDirecti /// /// The kernel check is `(len - hlen) > (ifp->if_mtu + BPF_WRITE_LEEWAY)` -> EMSGSIZE. /// Under BIOCSHDRCMPLT=1 (our usage) hlen == 0, so the **whole frame length (including the 14-byte -/// Ethernet header) must be <= interface MTU + 18**. With MTU=1500 the cap is 1518, which exactly fits a standard -/// 1514 frame and a 1518 frame with a VLAN tag. +/// Ethernet header) must be <= interface MTU + 18**. With MTU=1500 the cap is 1518, which exactly +/// fits a standard 1514 frame and a 1518 frame with a VLAN tag. inline constexpr std::uint32_t kBpfWriteLeeway = 18; /// Upper and lower bounds of BIOCSBLEN. /// -/// Starting with macOS 13 (xnu-8792) the upper bound is BPF_BUFSIZE_CAP, exposed on this machine through the read-only sysctl -/// debug.bpf_bufsize_cap as 32 MiB. **Exceeding it does not report an error**; it silently clamps to the cap and -/// writes the actually effective value back through _IOWR -- so the written-back value must be used; see bpf_link.cc. +/// Starting with macOS 13 (xnu-8792) the upper bound is BPF_BUFSIZE_CAP, exposed through the +/// read-only sysctl debug.bpf_bufsize_cap (32 MiB on macOS 26, see AGENTS.md section 2.3). +/// Exceeding it does not report an error; the kernel silently clamps to the cap and writes the +/// effective value back through _IOWR, so the written-back value must be used (see bpf_link.cc). inline constexpr std::uint32_t kBpfMinBufferBytes = 32; /// Minimum length of a BPF record header. /// -/// Key pitfall: `sizeof(struct bpf_hdr)` is **20** on LP64 (the 18 bytes of content are padded by the compiler -/// to 20), while the `bh_hdrlen` the kernel actually writes for DLT_EN10MB is **18** -/// (SIZEOF_BPF_HDR=18, bif_hdrlen = BPF_WORDALIGN(14+18) - 14 = 18). -/// **When reading, the bh_hdrlen in the record must be used; using sizeof misaligns immediately.** +/// Gotcha: `sizeof(struct bpf_hdr)` is 20 on LP64 (the 18 bytes of content are padded by the +/// compiler to 20), while the `bh_hdrlen` the kernel actually writes for DLT_EN10MB is 18 +/// (SIZEOF_BPF_HDR=18, bif_hdrlen = BPF_WORDALIGN(14+18) - 14 = 18). When reading, the bh_hdrlen in +/// the record must be used; using sizeof misaligns immediately. inline constexpr std::uint32_t kBpfHeaderMinBytes = 18; static_assert(sizeof(struct bpf_hdr) == 20, - "LP64 下 sizeof(struct bpf_hdr) 应为 20(内容 18 字节 + 2 字节填充)"); + "on LP64 sizeof(struct bpf_hdr) must be 20 (18 bytes of fields + 2 of padding)"); static_assert(sizeof(struct BPF_TIMEVAL) == 8, - "LP64 下 BPF 时间戳是 timeval32(8 字节),不是 64 位 timeval"); + "on LP64 the BPF timestamp is timeval32 (8 bytes), not a 64-bit timeval"); // ============================================================================= // sysctls snapshotted at feth creation time // -// These switches are read from sysctl into the interface's private flag bits at the moment of feth_clone_create(), -// and **changing the sysctl after creation has no effect**. They must therefore be verified before creating the feth. +// These switches are read from sysctl into the interface's private flag bits at the moment of +// feth_clone_create(), and **changing the sysctl after creation has no effect**. They must +// therefore be verified before creating the feth. // ============================================================================= /// A feth sysctl that must have a specific value. /// -/// `why` stores a message identifier rather than a ready-made string: this table is constexpr, while the "why" -/// must be rendered in the user's current language, so it can only be deferred to the moment of the error and looked up then. +/// `why` stores a message identifier rather than a ready-made string: this table is constexpr, +/// while the "why" must be rendered in the user's current language, so it can only be deferred to +/// the moment of the error and looked up then. struct RequiredFethSysctl { const char* name; std::int32_t required_value; diff --git a/include/tetherkitnext/net/feth_device.h b/include/tetherkitnext/net/feth_device.h index b45f885..62ec64d 100644 --- a/include/tetherkitnext/net/feth_device.h +++ b/include/tetherkitnext/net/feth_device.h @@ -10,9 +10,10 @@ // │(system)│ │(driver)│ // └────────┘ └────────┘ // -// * Frames the host sends out of feth0 -> are in the **input** direction on feth1 and are captured by BPF; -// * When we **write** a frame to feth1's BPF -> it goes through feth1's output path -> -// enters feth0's input -> and is received by the host IP stack. It **does not** loop back to feth1. +// * Frames the host sends out of feth0 -> are in the input direction on feth1 and are captured by +// BPF; +// * When we write a frame to feth1's BPF -> it goes through feth1's output path -> enters feth0's +// input -> and is received by the host IP stack. It does not loop back to feth1. // // So BPF only needs to attach to feth1, and one descriptor handles both receiving and sending. // @@ -35,40 +36,46 @@ using MacAddress = std::array; /// Maximum length of an feth interface name (IFNAMSIZ = 16, including the terminator). inline constexpr std::size_t kInterfaceNameCapacity = 16; -/// Upper limit of MTU supported by feth, determined by the sysctl net.link.fake.max_mtu (2048 on this machine). +/// Upper limit of MTU supported by feth, determined by the sysctl net.link.fake.max_mtu (2048 on +/// macOS 26, see AGENTS.md section 2.4). /// -/// Note that this sysctl is also a **creation-time snapshot**: feth_max_mtu is fixed at clone_create, -/// and changing the sysctl afterwards has no effect on existing interfaces. +/// Note that this sysctl is also a **creation-time snapshot**: feth_max_mtu is fixed at +/// clone_create, and changing the sysctl afterwards has no effect on existing interfaces. [[nodiscard]] Result QueryFethMaxMtu(); /// Verifies whether the sysctls snapshotted at feth creation are all at the values we require. /// -/// **Must be called before creating the feth.** Once these switches (hwcsum / fcs / tso_support / lro / -/// trailer_length / separate_frame_header) are snapshotted as non-zero at creation, what we read from -/// BPF is not a clean Ethernet frame, and changing the sysctl after creation is too late. +/// **Must be called before creating the feth.** Once these switches (hwcsum / fcs / tso_support / +/// lro / trailer_length / separate_frame_header) are snapshotted as non-zero at creation, what we +/// read from BPF is not a clean Ethernet frame, and changing the sysctl after creation is too late. [[nodiscard]] Status VerifyFethSysctls(); /// Registration callback for interface creation / destruction. /// -/// * Why it is needed * -/// When a process is SIGKILLed, C++ destructors do not run and the feth stays in the kernel; and SIGKILL cannot be intercepted by any -/// signal handler. The only reliable backstop is to **persist the names of created interfaces to disk and -/// clean up on the next launch**. RAII cannot manage a forcibly killed process; this hook exists for exactly that. +/// Why it is needed: +/// When a process is SIGKILLed, C++ destructors do not run and the feth stays in the kernel; and +/// SIGKILL cannot be intercepted by any signal handler. The only reliable backstop is to +/// **persist the names of created interfaces to disk and clean up on the next launch**. RAII +/// cannot manage a forcibly killed process; this hook exists for exactly that. /// -/// Constraint: it is called synchronously on the same thread as creation / destruction; the implementation should only do short operations like "append a line to a file / -/// delete a line", and must not log (the destruction path may be in a destructor, noexcept). +/// Constraint: it is called synchronously on the same thread as creation / destruction; the +/// implementation should only do short operations like "append a line to a file / delete a line", +/// and must not log (the destruction path may be in a destructor, noexcept). /// /// @param name Interface name. /// @param created true = just created, false = just destroyed. using InterfaceRegistry = void (*)(std::string_view name, bool created) noexcept; -/// Installs / uninstalls the registration callback. Pass nullptr to uninstall. Process-wide, thread-safe. +/// Installs / uninstalls the registration callback. Pass nullptr to uninstall. Process-wide, +/// thread-safe. void SetInterfaceRegistry(InterfaceRegistry registry) noexcept; -/// Destroys an feth interface specified by name. Used to clean up orphans left after a process was forcibly killed. +/// Destroys an feth interface specified by name. Used to clean up orphans left after a process was +/// forcibly killed. /// -/// Unlike the destructor of FethInterface, no object needs to be held first here -- orphans are exactly those "with no object -/// managing them". The name must be of the form `feth`; the caller is responsible for validation. +/// Unlike the destructor of FethInterface, no object needs to be held first here; orphans are +/// exactly those "with no object managing them". The name must be of the form `feth`; the +/// caller is responsible for validation. [[nodiscard]] Status DestroyInterfaceByName(std::string_view name); /// An feth interface. RAII: destroys the kernel interface on destruction. @@ -86,7 +93,8 @@ class FethInterface { /// Creates a new feth interface. /// - /// @param requested_name An empty string lets the kernel automatically choose the lowest free number (recommended); + /// @param requested_name An empty string lets the kernel automatically choose the lowest free + /// number (recommended); /// "feth7" specifies the number, and fails if it already exists (EEXIST). /// /// In wildcard mode the kernel writes back the full name, which can be obtained with Name(). @@ -117,17 +125,18 @@ class FethInterface { [[nodiscard]] Result QueryMtu() const; - /// Sets the MAC address. **Must be called before setting IFF_UP.** + /// Sets the MAC address. Must be called before setting IFF_UP. /// - /// The MAC the kernel assigns by default is 'f','e','t','h', unit>>8, unit&0xff - /// (so feth0 is 66:65:74:68:00:00). + /// The MAC the kernel assigns by default is 'f','e','t','h', unit>>8, unit&0xff (so feth0 is + /// 66:65:74:68:00:00). /// - /// For the RNDIS scenario, the MAC of the **system-side** one (feth0) should be set to the address the device reports via - /// OID_802_3_PERMANENT_ADDRESS -- under RNDIS semantics the device is this NIC, - /// and the peer's ARP table and DHCP lease are both built on this MAC. + /// For the RNDIS scenario, the MAC of the system-side one (feth0) should be set to the address + /// the device reports via OID_802_3_PERMANENT_ADDRESS; under RNDIS semantics the device is this + /// NIC, and the peer's ARP table and DHCP lease are both built on this MAC. /// - /// **The driver-side one (feth1) must keep the kernel-assigned MAC, different from feth0's**, - /// otherwise the IPv6 link-local addresses on both sides are the same, triggering a DAD address conflict. + /// The driver-side one (feth1) must keep the kernel-assigned MAC, different from feth0's, + /// otherwise the IPv6 link-local addresses on both sides are the same, triggering a DAD address + /// conflict. [[nodiscard]] Status SetMacAddress(const MacAddress& mac); [[nodiscard]] Result QueryMacAddress() const; @@ -137,13 +146,15 @@ class FethInterface { [[nodiscard]] Result IsUp() const; - /// Gives up ownership of the interface; it will no longer be destroyed on destruction (to preserve the scene when troubleshooting). + /// Gives up ownership of the interface; it will no longer be destroyed on destruction (to + /// preserve the scene when troubleshooting). void Release() noexcept { name_.clear(); } private: explicit FethInterface(std::string name) : name_(std::move(name)) {} - /// Destroys the kernel interface and clears name_. Failures are only logged -- the destructor path can neither throw nor return an error. + /// Destroys the kernel interface and clears name_. Failures are only logged: the destructor path + /// can neither throw nor return an error. void Destroy() noexcept; std::string name_; @@ -154,15 +165,15 @@ class FethPair { public: /// Creates and configures a pair of feth. /// - /// The order of operations is deliberate (a wrong order fails or produces a wrong state): - /// 1. verify creation-time sysctls -- must be before creation; + /// The order of operations matters (a wrong order fails or produces a wrong state): + /// 1. verify creation-time sysctls: must be before creation; /// 2. create the two interfaces; - /// 3. pair -- pair before UP, so that the link is up from the start - /// (IFM_ACTIVE of SIOCGIFMEDIA is immediately true); + /// 3. pair: pair before UP, so that the link is up from the start (IFM_ACTIVE of SIOCGIFMEDIA + /// is immediately true); /// 4. set MTU; - /// 5. set the system-side MAC -- must be before UP; - /// 6. bring both sides UP -- bpfwrite strictly requires feth1 to be UP (otherwise ENETDOWN), - /// and feth0 must also be UP for the host IP stack to process received frames. + /// 5. set the system-side MAC: must be before UP; + /// 6. bring both sides UP: bpfwrite strictly requires feth1 to be UP (otherwise ENETDOWN), and + /// feth0 must also be UP for the host IP stack to process received frames. /// /// @param mtu MTU of both sides. /// @param system_mac The MAC to set on the system side (host_side); passing std::nullopt @@ -191,7 +202,8 @@ class FethPair { /// Renders a MAC as "aa:bb:cc:dd:ee:ff". [[nodiscard]] std::array FormatMac(const MacAddress& mac) noexcept; -/// Whether the current process runs as root. Used to give a clear error at startup instead of a string of EPERM. +/// Whether the current process runs as root. Used to give a clear error at startup instead of a +/// string of EPERM. [[nodiscard]] bool IsRunningAsRoot() noexcept; } // namespace tetherkitnext::net diff --git a/include/tetherkitnext/net/link_backend.h b/include/tetherkitnext/net/link_backend.h index ecc4461..442e83a 100644 --- a/include/tetherkitnext/net/link_backend.h +++ b/include/tetherkitnext/net/link_backend.h @@ -1,13 +1,15 @@ // Link-layer backend abstraction. // -// Why an abstraction is needed: BPF needs root and a real feth interface, and cannot run on a development machine. -// After abstracting "send and receive raw Ethernet frames" into a narrow interface, end-to-end tests and throughput benchmarks can run with an in-memory -// loopback backend in any environment. +// Why an abstraction is needed: BPF needs root and a real feth interface, and cannot run on a +// development machine. After abstracting "send and receive raw Ethernet frames" into a narrow +// interface, end-to-end tests and throughput benchmarks can run with an in-memory loopback backend +// in any environment. // -// Performance trade-off: the interface uses **virtual functions**, but virtual calls are **not at per-frame granularity** -- -// ReadFrames / WriteFrames are both batch interfaces; one virtual call handles dozens to hundreds of frames, -// and the overhead amortized per frame is far below 1 ns, entirely negligible. -// (One virtual call per frame would be unacceptable; that is a design deliberately avoided.) +// Performance trade-off: the interface uses **virtual functions**, but virtual calls are **not at +// per-frame granularity**; ReadFrames / WriteFrames are both batch interfaces; one virtual call +// handles dozens to hundreds of frames, and the overhead amortized per frame is far below 1 ns, +// entirely negligible. (One virtual call per frame would be unacceptable; that is a design +// avoided.) #pragma once #include @@ -24,7 +26,8 @@ using FrameBatch = std::span; /// Result of one batch read. struct ReadBatch { - /// Frames decoded in this batch; views point into the backend's internal buffer and are valid until the next ReadFrames. + /// Frames decoded in this batch; views point into the backend's internal buffer and are valid + /// until the next ReadFrames. std::span frames; /// Kernel-side cumulative drop count (BPF's bs_drop). Used for backpressure warnings. std::uint64_t kernel_drops = 0; @@ -50,17 +53,19 @@ class LinkBackend { /// Blocking read of a batch of frames. /// - /// Returning an empty batch is legal (for example when interrupted by a signal); the caller should continue looping. - /// Only a real error returns Error. + /// Returning an empty batch is legal (for example when interrupted by a signal); the caller + /// should continue looping. Only a real error returns Error. [[nodiscard]] virtual Result ReadFrames() = 0; - /// Writes out a batch of frames. Best effort to write them all; oversized frames are skipped and counted. + /// Writes out a batch of frames. Best effort to write them all; oversized frames are skipped and + /// counted. [[nodiscard]] virtual Result WriteFrames(FrameBatch frames) = 0; /// Per-frame length limit (including the 14-byte Ethernet header). [[nodiscard]] virtual std::uint32_t MaxFrameBytes() const noexcept = 0; - /// Whether writing multiple frames per system call is supported. Used for logs and benchmark reports. + /// Whether writing multiple frames per system call is supported. Used for logs and benchmark + /// reports. [[nodiscard]] virtual bool SupportsBatchWrite() const noexcept = 0; /// Wakes the thread blocked in ReadFrames, used for graceful shutdown. diff --git a/include/tetherkitnext/net/loopback_link.h b/include/tetherkitnext/net/loopback_link.h index d5199dd..cd16a5e 100644 --- a/include/tetherkitnext/net/loopback_link.h +++ b/include/tetherkitnext/net/loopback_link.h @@ -1,13 +1,16 @@ -// In-memory loopback link backend -- for offline tests and throughput benchmarks. +// In-memory loopback link backend: for offline tests and throughput benchmarks. // -// Why it is a must: BpfLink needs root privileges + a real feth interface, while the development machine has neither -// root nor a USB device. After abstracting the link layer into LinkBackend, the end-to-end logic (the bridge layer's -// threading model, batching, backpressure, statistics) can be fully tested and benchmarked in any environment. +// Why it is a must: BpfLink needs root privileges + a real feth interface, while the development +// machine has neither root nor a USB device. After abstracting the link layer into LinkBackend, the +// end-to-end logic (the bridge layer's threading model, batching, backpressure, statistics) can be +// fully tested and benchmarked in any environment. // // Semantics: -// * Frames written by WriteFrames enter the `sent` queue, for tests to assert "what the driver sent toward the host side"; -// * ReadFrames takes frames from the `inbound` queue, for tests to inject "what the host side sent"; -// * Both queues are bounded; when full they drop and count -- consistent with real BPF behavior. +// * Frames written by WriteFrames enter the `sent` queue, for tests to assert "what the driver +// sent toward the host side"; +// * ReadFrames takes frames from the `inbound` queue, for tests to inject "what the host side +// sent"; +// * Both queues are bounded; when full they drop and count: consistent with real BPF behavior. #pragma once #include @@ -23,8 +26,10 @@ namespace tetherkitnext::net { /// Configuration of the loopback backend. struct LoopbackConfig { std::uint32_t max_frame_bytes = 1518; - std::size_t inbound_capacity = 4096; ///< Upper limit on frames waiting to be taken by ReadFrames. - std::size_t sent_capacity = 4096; ///< Upper limit on frames already written out by WriteFrames. + /// Upper limit on frames waiting to be taken by ReadFrames. + std::size_t inbound_capacity = 4096; + /// Upper limit on frames already written out by WriteFrames. + std::size_t sent_capacity = 4096; std::size_t max_frames_per_batch = 256; /// Whether to claim support for batch writes. Tests need to cover both paths. bool report_batch_write = true; @@ -36,13 +41,15 @@ struct LoopbackConfig { /// (consistent with the LinkBackend contract); while PushInbound / DrainSent / Interrupt may be /// called from any thread, protected internally by a mutex. /// -/// A mutex is deliberately used here instead of a lock-free queue: this class only serves the **injection side** of tests and benchmarks, -/// and is not on the data path under test; going lock-free would only add implementation complexity without testing anything more. +/// A mutex is used here instead of a lock-free queue: this class only serves the **injection side** +/// of tests and benchmarks, and is not on the data path under test; going lock-free would only add +/// implementation complexity without testing anything more. class LoopbackLink final : public LinkBackend { public: explicit LoopbackLink(const LoopbackConfig& config = {}); - // Copy and move are already deleted in the base class LinkBackend; they are restated explicitly here to satisfy static analysis. + // Copy and move are already deleted in the base class LinkBackend; they are restated explicitly + // here to satisfy static analysis. LoopbackLink(const LoopbackLink&) = delete; LoopbackLink& operator=(const LoopbackLink&) = delete; LoopbackLink(LoopbackLink&&) = delete; @@ -66,7 +73,8 @@ class LoopbackLink final : public LinkBackend { // Test injection and observation interfaces // --------------------------------------------------------------------------- - /// Injects one frame "from the host side" for ReadFrames to take out. Returns false when the queue is full. + /// Injects one frame "from the host side" for ReadFrames to take out. Returns false when the + /// queue is full. [[nodiscard]] bool PushInbound(std::span frame); /// Takes out and clears all frames "written by the driver to the host side". @@ -91,7 +99,8 @@ class LoopbackLink final : public LinkBackend { return interrupted_.load(std::memory_order_acquire); } - /// Makes WriteFrames return an error starting from the Nth call, for testing the error propagation path. + /// Makes WriteFrames return an error starting from the Nth call, for testing the error + /// propagation path. void FailWritesAfter(std::uint32_t successful_calls) noexcept { fail_writes_after_.store(successful_calls, std::memory_order_relaxed); } @@ -105,7 +114,8 @@ class LoopbackLink final : public LinkBackend { /// Frames already written out. std::vector> sent_; - /// The view returned by ReadFrames must remain valid until the next call, so this batch's data stays here. + /// The view returned by ReadFrames must remain valid until the next call, so this batch's data + /// stays here. std::vector> read_storage_; std::vector read_views_; diff --git a/include/tetherkitnext/rndis/control_channel.h b/include/tetherkitnext/rndis/control_channel.h index fc072fe..49528df 100644 --- a/include/tetherkitnext/rndis/control_channel.h +++ b/include/tetherkitnext/rndis/control_channel.h @@ -1,23 +1,29 @@ // Abstraction of the RNDIS control channel. // -// Why this interface lives in the rndis layer rather than the usb layer: it describes the **RNDIS protocol's** control channel -// semantics (send a message, fetch a message, wait for a "response is available" notification), not USB semantics. -// The state machine (tk_rndis) depends on it, and the libusb implementation (tk_usb) provides it -- so the dependency direction is -// the correct rndis <- usb, and tk_rndis never depends backward on tk_usb. +// Why this interface lives in the rndis layer rather than the usb layer: it describes the **RNDIS +// protocol's** control channel semantics (send a message, fetch a message, wait for a "response is +// available" notification), not USB semantics. The state machine (tk_rndis) depends on it, and the +// libusb implementation (tk_usb) provides it, so the dependency direction is the correct rndis <- +// usb, and tk_rndis never depends backward on tk_usb. // -// RNDIS control messages do not go over the bulk endpoints, but over two class requests on the USB control endpoint (EP0): +// RNDIS control messages do not go over the bulk endpoints, but over two class requests on the USB +// control endpoint (EP0): // SEND_ENCAPSULATED_COMMAND (bmRequestType=0x21, bRequest=0x00) // GET_ENCAPSULATED_RESPONSE (bmRequestType=0xA1, bRequest=0x01) -// plus the interrupt IN endpoint on the communications-class interface, used to notify "a response can be fetched". +// plus the interrupt IN endpoint on the communications-class interface, used to notify "a response +// can be fetched". // -// Why abstract into an interface: the state machine is the most logically complex part of the whole RNDIS implementation and the part that most needs testing, -// yet the development machine has no USB device at all. After abstracting the control channel away, the state machine can be driven entirely in memory, -// including paths that are extremely hard to reproduce on real hardware (the device proactively sending KEEPALIVE, -// INDICATE_STATUS cutting in, replay required after RESET, out-of-order responses, timeout retries). +// Why abstract into an interface: the state machine is the most logically complex part of the whole +// RNDIS implementation and the part that most needs testing, yet the development machine has no USB +// device at all. After abstracting the control channel away, the state machine can be driven +// entirely in memory, including paths that are extremely hard to reproduce on real hardware (the +// device proactively sending KEEPALIVE, INDICATE_STATUS cutting in, replay required after RESET, +// out-of-order responses, timeout retries). // -// Using virtual functions here is completely fine performance-wise: the control channel has one keepalive round trip only every 5 seconds, -// and libusb control transfers on Apple Silicon are themselves at the **millisecond** level -// (libusb issue #1288: on M2 a control transfer is about 10x slower than on x64). +// Using virtual functions here is completely fine performance-wise: the control channel has one +// keepalive round trip only every 5 seconds, and libusb control transfers on Apple Silicon are +// themselves at the **millisecond** level (libusb issue #1288: on M2 a control transfer is about +// 10x slower than on x64). #pragma once #include @@ -32,24 +38,25 @@ namespace tetherkitnext::rndis { /// The timeout value to pass when you "only want a quick probe, not a real wait". /// /// WARNING: **Do not pass 0.** On darwin libusb passes timeout to IOKit as both noDataTimeout and -/// completionTimeout, and **0 means wait forever** -- passing 0 would block the calling thread -/// forever in `libusb_wait_for_event`, hanging the entire control loop, unable even to respond to the shutdown signal. -/// (See items 12 and 13 of section 7 in AGENTS.md for details.) -/// libusb's synchronous API has no true non-blocking mode; the shortest wait achievable is 1 ms. +/// completionTimeout, and **0 means wait forever**; passing 0 would block the calling thread +/// forever in `libusb_wait_for_event`, hanging the entire control loop, unable even to respond to +/// the shutdown signal. (See items 12 and 13 of section 7 in AGENTS.md for details.) libusb's +/// synchronous API has no true non-blocking mode; the shortest wait achievable is 1 ms. inline constexpr std::uint32_t kProbeOnlyTimeoutMillis = 1; /// Result of waiting for a notification. enum class NotificationResult : std::uint8_t { kResponseAvailable, ///< The device explicitly notified that a response can be fetched. - kTimeout, ///< Wait timed out. **Not necessarily an error** -- see the note below. + kTimeout, ///< Wait timed out. **Not necessarily an error**; see the note below. kNotSupported, ///< The device has no interrupt endpoint; the caller should poll directly. }; /// The RNDIS control channel. /// -/// Implementations must guarantee: all methods are called from the **same thread** (the state machine thread). This is not to -/// simplify the implementation, but a hard libusb constraint -- calling the synchronous API from the event thread returns -/// LIBUSB_ERROR_BUSY, so the control channel must exclusively own a non-event thread. +/// Implementations must guarantee: all methods are called from the **same thread** (the state +/// machine thread). This is not to simplify the implementation, but a hard libusb constraint; +/// calling the synchronous API from the event thread returns LIBUSB_ERROR_BUSY, so the control +/// channel must exclusively own a non-event thread. class ControlChannel { public: ControlChannel() = default; @@ -64,26 +71,30 @@ class ControlChannel { /// Fetches one RNDIS control message (GET_ENCAPSULATED_RESPONSE). /// - /// The returned view points into the implementation's internal buffer and is valid until the next call of this method. + /// The returned view points into the implementation's internal buffer and is valid until the next + /// call of this method. /// - /// **Returning an empty view is not an error**: the spec says that when the device has no valid response yet it should return **1 byte of 0x00** - /// rather than STALLing the control endpoint. So when the caller receives a result shorter than 8 bytes it must treat it as - /// "not ready yet, retry later", not as a failure. + /// **Returning an empty view is not an error**: the spec says that when the device has no valid + /// response yet it should return **1 byte of 0x00** rather than STALLing the control endpoint. So + /// when the caller receives a result shorter than 8 bytes it must treat it as "not ready yet, + /// retry later", not as a failure. [[nodiscard]] virtual Result> ReceiveMessage() = 0; /// Waits for the device's RESPONSE_AVAILABLE notification. /// /// Handling of the interrupt endpoint must be compatible with both kinds of device behavior: - /// * The spec way: the host waits for an 8-byte notification on the interrupt IN - /// (two LE32: 0x00000001 = RESPONSE_AVAILABLE, 0); - /// * The Linux way: ignore the interrupt endpoint entirely and poll GET_ENCAPSULATED_RESPONSE directly - /// up to 10 times, 40 ms apart. - /// Conversely, there are also **some devices that must have the interrupt endpoint read once before they answer on the control endpoint**. - /// So the correct strategy is: wait for the notification first, and after a timeout still poll once. kTimeout is therefore not an error. + /// * The spec way: the host waits for an 8-byte notification on the interrupt IN (two LE32: + /// 0x00000001 = RESPONSE_AVAILABLE, 0); + /// * The Linux way: ignore the interrupt endpoint entirely and poll GET_ENCAPSULATED_RESPONSE + /// directly up to 10 times, 40 ms apart. + /// Conversely, there are also **some devices that must have the interrupt endpoint read once + /// before they answer on the control endpoint**. So the correct strategy is: wait for the + /// notification first, and after a timeout still poll once. kTimeout is therefore not an error. /// - /// @param timeout_millis Wait upper bound. **Passing 0 means wait forever** (consistent with libusb's - /// semantics) -- to "only probe", pass kProbeOnlyTimeoutMillis, not 0. - /// Implementations should defensively clamp 0; see UsbControlChannel. + /// @param timeout_millis Wait upper bound. **Passing 0 means wait forever** (consistent with + /// libusb's + /// semantics): to "only probe", pass kProbeOnlyTimeoutMillis, not 0. Implementations + /// should defensively clamp 0; see UsbControlChannel. [[nodiscard]] virtual NotificationResult WaitForNotification(std::uint32_t timeout_millis) = 0; /// Timeout of control transfers (milliseconds). diff --git a/include/tetherkitnext/rndis/messages.h b/include/tetherkitnext/rndis/messages.h index fe722e7..e65a19e 100644 --- a/include/tetherkitnext/rndis/messages.h +++ b/include/tetherkitnext/rndis/messages.h @@ -1,16 +1,19 @@ // Encoding and decoding of RNDIS control messages. // -// Design trade-off: **do not map the wire format directly with packed structs**, but use "logical structs + explicit -// offset reads/writes". There are three reasons: +// Design trade-off: **do not map the wire format directly with packed structs**, but use "logical +// structs + explicit offset reads/writes". There are three reasons: // 1. The wire format is little-endian, and packed structs fail silently on big-endian machines; -// 2. The start offset of an RNDIS message in the USB buffer is only guaranteed to be 4-byte aligned, and member access of a packed struct -// at some offsets is undefined behavior (-fsanitize=alignment reports it); -// 3. The base point of the offset fields follows the counter-intuitive rule "message start + 8" (see rule 2 in the file header of protocol.h), -// and explicit Encode/Decode functions concentrate this conversion in one place and add tests, -// whereas a struct mapping would make every use site remember the +/-8 itself. +// 2. The start offset of an RNDIS message in the USB buffer is only guaranteed to be 4-byte +// aligned, and member access of a packed struct at some offsets is undefined behavior +// (-fsanitize=alignment reports it); +// 3. The base point of the offset fields follows the counter-intuitive rule "message start + 8" +// (see rule 2 in the file header of protocol.h), and explicit Encode/Decode functions +// concentrate this conversion in one place and add tests, whereas a struct mapping would make +// every use site remember the +/-8 itself. // -// Decode functions all perform **complete bounds and self-consistency checks**: control channel data comes from an external device, -// and must be assumed potentially malicious or buggy. A failed check returns Error rather than crashing or reading out of bounds. +// Decode functions all perform **complete bounds and self-consistency checks**: control channel +// data comes from an external device, and must be assumed potentially malicious or buggy. A failed +// check returns Error rather than crashing or reading out of bounds. #pragma once #include @@ -50,11 +53,13 @@ struct InitializeRequest { std::uint32_t request_id = 0; std::uint32_t major_version = kMajorVersion; std::uint32_t minor_version = kMinorVersion; - /// The maximum number of bytes the host can receive from bulk IN at one time, computed with MaxTransferSizeFor(). + /// The maximum number of bytes the host can receive from bulk IN at one time, computed with + /// MaxTransferSizeFor(). std::uint32_t max_transfer_size = 0; }; -/// Encodes INITIALIZE_MSG. The buffer must be at least kInitializeMsgBytes bytes; returns the length written. +/// Encodes INITIALIZE_MSG. The buffer must be at least kInitializeMsgBytes bytes; returns the +/// length written. [[nodiscard]] Result Encode(const InitializeRequest& request, std::span buffer); @@ -65,10 +70,12 @@ struct InitializeComplete { std::uint32_t minor_version = 0; std::uint32_t device_flags = 0; std::uint32_t medium = 0; - /// Upper limit on the number of PACKET_MSGs the device can carry in one transfer. Most Android gadgets report 1, - /// while those with the Qualcomm aggregation patch report 3 or more. 0 is treated as 1. + /// Upper limit on the number of PACKET_MSGs the device can carry in one transfer. Most Android + /// gadgets report 1, while those with the Qualcomm aggregation patch report 3 or more. 0 is + /// treated as 1. std::uint32_t max_packets_per_message = 0; - /// Maximum bytes the device can receive at once -- determines the upper limit of host-side TX aggregation. + /// Maximum bytes the device can receive at once; determines the upper limit of host-side TX + /// aggregation. std::uint32_t max_transfer_size = 0; /// Host -> device alignment requirement; alignment bytes = 1 << this value, legal upper bound 7. std::uint32_t packet_alignment_factor = 0; @@ -91,11 +98,12 @@ struct NegotiatedParameters { /// /// All known device quirks are handled together here: /// * MaxPacketsPerMessage of 0 -> treated as 1; -/// * PacketAlignmentFactor > 7 -> clamped to 7 (a protocol violation; otherwise absurd padding would be computed); -/// * MaxTransferSize smaller than one full frame (hard_mtu) -> back-derive and lower the MTU; -/// too small (<= 58, cannot fit the headers) -> report an error; -/// * MaxTransferSize reporting 8KB/16KB jumbo frames (habit of WinCE / Windows Mobile) -> -/// do not follow blindly; clamp to our own buffer limit. +/// * PacketAlignmentFactor > 7 -> clamped to 7 (a protocol violation; otherwise absurd padding +/// would be computed); +/// * MaxTransferSize smaller than one full frame (hard_mtu) -> back-derive and lower the MTU; too +/// small (<= 58, cannot fit the headers) -> report an error; +/// * MaxTransferSize reporting 8KB/16KB jumbo frames (habit of WinCE / Windows Mobile) -> do not +/// follow blindly; clamp to our own buffer limit. [[nodiscard]] Result Negotiate(const InitializeComplete& complete, std::uint32_t requested_mtu, std::uint32_t host_transfer_size_limit); @@ -104,7 +112,8 @@ struct NegotiatedParameters { // HALT // ============================================================================= -/// Encodes HALT_MSG. **The device does not reply**; once sent, it can be considered to have entered uninitialized. +/// Encodes HALT_MSG. **The device does not reply**; once sent, it can be considered to have entered +/// uninitialized. [[nodiscard]] Result EncodeHalt(std::uint32_t request_id, std::span buffer); @@ -117,10 +126,11 @@ struct QueryRequest { Oid oid = Oid::kGenSupportedList; /// Expected response size in bytes. /// - /// For **fixed-length** OIDs it must be >= the expected response length, and the same number of zero bytes must be padded at the end of the message; - /// for **variable-length** OIDs it must be 0. This undocumented requirement comes from Microsoft's ActiveSync implementation, - /// and violating it yields RNDIS_STATUS_INVALID_LENGTH. Encode automatically corrects by IsVariableLengthOid(), - /// so the caller can fill 0 and let it decide on its own. + /// For **fixed-length** OIDs it must be >= the expected response length, and the same number of + /// zero bytes must be padded at the end of the message; for **variable-length** OIDs it must be + /// 0. This undocumented requirement comes from Microsoft's ActiveSync implementation, and + /// violating it yields RNDIS_STATUS_INVALID_LENGTH. Encode automatically corrects by + /// IsVariableLengthOid(), so the caller can fill 0 and let it decide on its own. std::uint32_t expected_response_bytes = 0; }; @@ -164,13 +174,14 @@ struct SetComplete { /// Encodes RESET_MSG. /// -/// **Note: RESET_MSG has no RequestId field** (offset 8 is Reserved), so responses cannot be paired by -/// ID, and only one RESET can be in flight at a time. +/// **Note: RESET_MSG has no RequestId field** (offset 8 is Reserved), so responses cannot be paired +/// by ID, and only one RESET can be in flight at a time. [[nodiscard]] Result EncodeReset(std::span buffer); struct ResetComplete { std::uint32_t status = 0; - /// Non-zero means addressing information (packet filter, multicast table) was lost in the reset, and the host must resend the corresponding SETs. + /// Non-zero means addressing information (packet filter, multicast table) was lost in the reset, + /// and the host must resend the corresponding SETs. bool addressing_reset = false; }; @@ -192,8 +203,9 @@ struct KeepAliveComplete { /// Encodes KEEPALIVE_CMPLT. /// -/// It is needed because the **device can also proactively send KEEPALIVE_MSG**, in which case the host must reply with -/// KEEPALIVE_CMPLT, otherwise the device may consider the host dead and disconnect. +/// It is needed because the **device can also proactively send KEEPALIVE_MSG**, in which case the +/// host must reply with KEEPALIVE_CMPLT, otherwise the device may consider the host dead and +/// disconnect. [[nodiscard]] Result EncodeKeepAliveComplete(std::uint32_t request_id, std::uint32_t status, std::span buffer); @@ -206,7 +218,8 @@ struct IndicateStatus { std::uint32_t status = 0; /// View of the status buffer; empty in most cases (MEDIA_CONNECT/DISCONNECT carry no payload). std::span status_buffer; - /// If the status buffer happens to be an 8-byte RNDIS_Diagnostic_Info, these two fields are filled. + /// If the status buffer happens to be an 8-byte RNDIS_Diagnostic_Info, these two fields are + /// filled. bool has_diagnostic_info = false; std::uint32_t diagnostic_status = 0; std::uint32_t diagnostic_error_offset = 0; @@ -214,13 +227,16 @@ struct IndicateStatus { /// Decodes INDICATE_STATUS_MSG. /// -/// **The base point of StatusBufferOffset is contradictory in the spec** (MS documentation says message start, while the QUERY/SET of the same -/// family are all message start + 8). This implementation tolerates both in the following order: -/// 1. If the length is 0 -- no payload, succeed directly (the vast majority of cases); -/// 2. First interpret with "base = message start + 8"; adopt it if it falls within the message range; +/// **The base point of StatusBufferOffset is contradictory in the spec** (MS documentation says +/// message start, while the QUERY/SET of the same family are all message start + 8). This +/// implementation tolerates both in the following order: +/// 1. If the length is 0: no payload, succeed directly (the vast majority of cases); +/// 2. First interpret with "base = message start + 8"; adopt it if it falls within the message +/// range; /// 3. Otherwise interpret with "base = message start"; -/// 4. If both are out of bounds -- discard the status buffer but **still return success**, because the status itself is useful, -/// and the link must not be dropped just because an optional payload cannot be parsed. +/// 4. If both are out of bounds: discard the status buffer but **still return success**, because +/// the status itself is useful, and the link must not be dropped just because an optional +/// payload cannot be parsed. [[nodiscard]] Result DecodeIndicateStatus(std::span buffer); // ============================================================================= diff --git a/include/tetherkitnext/rndis/packet_codec.h b/include/tetherkitnext/rndis/packet_codec.h index 8dceb68..b6775fe 100644 --- a/include/tetherkitnext/rndis/packet_codec.h +++ b/include/tetherkitnext/rndis/packet_codec.h @@ -1,20 +1,23 @@ -// Encoding and decoding of REMOTE_NDIS_PACKET_MSG -- **the data hot path**. +// Encoding and decoding of REMOTE_NDIS_PACKET_MSG: **the data hot path**. // // This is the only protocol code in the whole project that executes for every frame, therefore: -// * Everything is inline in the header, so the compiler can inline it into the bridge layer's loop; -// * It does not return std::expected (which would allocate a std::string), does not throw, and does not allocate memory; -// errors are expressed via enums + counters; +// * Everything is inline in the header, so the compiler can inline it into the bridge layer's +// loop; +// * It does not return std::expected (which would allocate a std::string), does not throw, and +// does not allocate memory; errors are expressed via enums + counters; // * Everything is noexcept. // // The two directions have different shapes; be sure to tell them apart: // // device -> host (PacketMessageReader): -// One bulk IN transfer strings together 1~N PACKET_MSGs, traversed by stepping by MessageLength. -// Trailing garbage must be tolerated (devices also use the trick of "padding one extra byte" to avoid a ZLP). +// One bulk IN transfer strings together 1~N PACKET_MSGs, traversed by stepping by +// MessageLength. Trailing garbage must be tolerated (devices also use the trick of "padding one +// extra byte" to avoid a ZLP). // // host -> device (PacketMessageWriter): -// Aggregates multiple frames into one bulk OUT, subject to three constraints: the device's MaxTransferSize, -// MaxPacketsPerMessage, and the per-packet alignment determined by PacketAlignmentFactor. +// Aggregates multiple frames into one bulk OUT, subject to three constraints: the device's +// MaxTransferSize, MaxPacketsPerMessage, and the per-packet alignment determined by +// PacketAlignmentFactor. #pragma once #include @@ -42,24 +45,20 @@ enum class ReadOutcome : std::uint8_t { /// Specific reason for illegal data, for statistics and troubleshooting. enum class MalformedReason : std::uint8_t { kNone, - kNotPacketMessage, ///< MessageType is not REMOTE_NDIS_PACKET_MSG. - kMessageTooShort, ///< MessageLength < 44. - kMessageOverruns, ///< MessageLength exceeds the remaining buffer. - kDataOutOfBounds, ///< DataOffset + DataLength exceeds MessageLength. - kFrameTooShort, ///< DataLength < 14; cannot fit the Ethernet header. - kFrameTooLong, ///< DataLength exceeds this machine's per-frame limit. + kNotPacketMessage, ///< MessageType is not REMOTE_NDIS_PACKET_MSG. + kMessageTooShort, ///< MessageLength < 44. + kMessageOverruns, ///< MessageLength exceeds the remaining buffer. + kDataOutOfBounds, ///< DataOffset + DataLength exceeds MessageLength. + kFrameTooShort, ///< DataLength < 14; cannot fit the Ethernet header. + kFrameTooLong, ///< DataLength exceeds the local per-frame limit. }; /// Extracts Ethernet frames one by one from a bulk IN transfer buffer. /// -/// Usage: -/// ``` -/// PacketMessageReader reader(transfer_bytes, max_frame_bytes); -/// std::span frame; -/// while (reader.Next(frame) == ReadOutcome::kFrame) { +/// Usage: ``` PacketMessageReader reader(transfer_bytes, max_frame_bytes); std::span frame; while (reader.Next(frame) == ReadOutcome::kFrame) { /// ... process frame ... -/// } -/// ``` +/// } ``` class PacketMessageReader { public: PacketMessageReader(std::span transfer, std::uint32_t max_frame_bytes) noexcept @@ -71,9 +70,11 @@ class PacketMessageReader { // Remaining bytes are less than a complete header: treat as trailing padding, end normally. // - // This tolerance is **required**: RNDIS specifies that neither host nor device sends a ZLP; instead, when the transfer length - // is exactly an integer multiple of the endpoint's max packet size, 1 extra byte is padded to make it a short packet. That byte falls outside all - // MessageLengths; treating it as an error would give a false report once on every 2048-byte transfer. + // This tolerance is **required**: RNDIS specifies that neither host nor device sends a ZLP; + // instead, when the transfer length is exactly an integer multiple of the endpoint's max packet + // size, 1 extra byte is padded to make it a short packet. That byte falls outside all + // MessageLengths; treating it as an error would give a false report once on every 2048-byte + // transfer. if (remaining < kPacketMsgHeaderBytes) { trailing_padding_bytes_ = static_cast(remaining); return ReadOutcome::kEndOfTransfer; @@ -97,8 +98,8 @@ class PacketMessageReader { const std::uint32_t data_offset = LoadLe32(message + kPacketDataOffsetOffset); const std::uint32_t data_length = LoadLe32(message + kPacketDataLengthOffset); - // Absolute offset = 8 + DataOffset (protocol.h rule 2). - // Use 64-bit arithmetic to avoid overflow when the device reports huge values. + // Absolute offset = 8 + DataOffset (protocol.h rule 2). Use 64-bit arithmetic to avoid overflow + // when the device reports huge values. const std::uint64_t data_begin = static_cast(kOffsetFieldBase) + data_offset; const std::uint64_t data_end = data_begin + data_length; if (data_end > message_length) [[unlikely]] { @@ -145,8 +146,9 @@ class PacketMessageReader { /// Message identifier corresponding to MalformedReason. /// -/// Returning an identifier rather than a ready-made string is to preserve constexpr -- the actual text must be rendered in the user's current -/// language, and callers fetch it with `Text(MalformedReasonMessage(r))`. +/// Returning an identifier rather than a ready-made string is to preserve constexpr; the actual +/// text must be rendered in the user's current language, and callers fetch it with +/// `Text(MalformedReasonMessage(r))`. [[nodiscard]] constexpr Msg MalformedReasonMessage(MalformedReason reason) noexcept { switch (reason) { case MalformedReason::kNone: @@ -179,10 +181,11 @@ class PacketMessageReader { /// Aggregates multiple Ethernet frames into one bulk OUT transfer. /// /// Details of alignment handling (this is the easiest place to get wrong): -/// RNDIS specifies that "except for the last one, every PACKET_MSG's MessageLength includes the trailing -/// alignment padding; the last one does not include external padding". So when appending the **next** message, this implementation -/// goes back and enlarges the **previous** message's MessageLength to swallow the padding bytes in between -- -/// this way the last message's MessageLength is naturally 44 + frame length, fully conforming to the spec. +/// RNDIS specifies that "except for the last one, every PACKET_MSG's MessageLength includes the +/// trailing alignment padding; the last one does not include external padding". So when appending +/// the **next** message, this implementation goes back and enlarges the **previous** message's +/// MessageLength to swallow the padding bytes in between this way the last message's +/// MessageLength is naturally 44 + frame length, fully conforming to the spec. class PacketMessageWriter { public: /// @param transfer Output buffer (usually the buffer of a libusb transfer) @@ -209,9 +212,11 @@ class PacketMessageWriter { capacity_ = usable > kZlpPadReserve ? usable - kZlpPadReserve : 0; } - /// Tries to append a frame. Returning false means this batch is full; the caller should submit first and then retry. + /// Tries to append a frame. Returning false means this batch is full; the caller should submit + /// first and then retry. /// - /// The frame length must be >= 14; the caller is responsible for guaranteeing this (frames read from BPF always satisfy it). + /// The frame length must be >= 14; the caller is responsible for guaranteeing this (frames read + /// from BPF always satisfy it). [[nodiscard]] bool TryAppend(std::span frame) noexcept { if (message_count_ >= max_messages_) [[unlikely]] { return false; @@ -219,7 +224,8 @@ class PacketMessageWriter { const auto frame_length = static_cast(frame.size()); - // If a message already exists, first compute how much padding must be inserted to satisfy alignment. + // If a message already exists, first compute how much padding must be inserted to satisfy + // alignment. const std::size_t aligned_cursor = message_count_ == 0 ? cursor_ : AlignUp(cursor_, alignment_bytes_); const std::size_t needed = aligned_cursor + kPacketMsgHeaderBytes + frame_length; @@ -227,7 +233,8 @@ class PacketMessageWriter { return false; } - // Attribute the padding bytes to the **previous** message's MessageLength (see the class documentation comment). + // Attribute the padding bytes to the **previous** message's MessageLength (see the class + // documentation comment). if (aligned_cursor != cursor_) { const auto padding = static_cast(aligned_cursor - cursor_); std::memset(transfer_.data() + cursor_, 0, padding); @@ -243,7 +250,7 @@ class PacketMessageWriter { StoreLe32(message + kMessageTypeOffset, ToRaw(MessageType::kPacket)); StoreLe32(message + kMessageLengthOffset, message_length); - // DataOffset is 36 rather than 44 -- the base point is message start + 8. + // DataOffset is 36 rather than 44: the base point is message start + 8. StoreLe32(message + kPacketDataOffsetOffset, kPacketInlineDataOffset); StoreLe32(message + kPacketDataLengthOffset, frame_length); // The remaining fields (OOB, per-packet info, VcHandle, Reserved) are always 0 in this project. @@ -261,10 +268,11 @@ class PacketMessageWriter { /// Finishes this batch, returning the number of bytes to submit to libusb. /// - /// Appends 1 byte of 0x00 when necessary to avoid a ZLP: RNDIS explicitly requires the host **not to** send - /// zero-length packets, and when the transfer length is exactly an integer multiple of the endpoint's wMaxPacketSize, the USB host controller - /// needs a short packet to mark the end of the transfer. Linux's usbnet does exactly this -- the extra byte is outside - /// all MessageLengths, and the device must tolerate trailing garbage. + /// Appends 1 byte of 0x00 when necessary to avoid a ZLP: RNDIS explicitly requires the host **not + /// to** send zero-length packets, and when the transfer length is exactly an integer multiple of + /// the endpoint's wMaxPacketSize, the USB host controller needs a short packet to mark the end of + /// the transfer. Linux's usbnet does exactly this: the extra byte is outside all MessageLengths, + /// and the device must tolerate trailing garbage. [[nodiscard]] std::uint32_t Finish() noexcept { if (cursor_ == 0) { return 0; @@ -279,7 +287,8 @@ class PacketMessageWriter { [[nodiscard]] std::uint32_t MessageCount() const noexcept { return message_count_; } - /// Number of Ethernet frame payload bytes aggregated so far (excluding RNDIS headers and padding), used to count throughput. + /// Number of Ethernet frame payload bytes aggregated so far (excluding RNDIS headers and + /// padding), used to count throughput. [[nodiscard]] std::uint64_t PayloadBytes() const noexcept { return payload_bytes_; } [[nodiscard]] bool ZlpPaddingAdded() const noexcept { return zlp_padding_added_; } @@ -287,7 +296,8 @@ class PacketMessageWriter { [[nodiscard]] bool Empty() const noexcept { return message_count_ == 0; } /// The maximum frame length the current batch can still hold (0 means it cannot fit any frame). - /// The caller can use it to avoid the fallback logic of "took out a frame only to find it does not fit". + /// The caller can use it to avoid the fallback logic of "took out a frame only to find it does + /// not fit". [[nodiscard]] std::uint32_t RemainingFrameCapacity() const noexcept { if (message_count_ >= max_messages_) { return 0; diff --git a/include/tetherkitnext/rndis/protocol.h b/include/tetherkitnext/rndis/protocol.h index 9be36d2..d738fbf 100644 --- a/include/tetherkitnext/rndis/protocol.h +++ b/include/tetherkitnext/rndis/protocol.h @@ -1,28 +1,32 @@ // RNDIS (Remote NDIS) wire-format constants and field layouts. // -// This file is the **sole source** of RNDIS protocol constants for the whole project; duplicating definitions elsewhere is not allowed. -// All values come from the Microsoft RNDIS specification and have been cross-validated against the Linux kernel implementation -// (drivers/net/usb/rndis_host.c, include/linux/usb/rndis_host.h, +// This file is the sole source of RNDIS protocol constants for the whole project; duplicating +// definitions elsewhere is not allowed. All values come from the Microsoft RNDIS specification and +// have been cross-validated against the Linux kernel implementation (drivers/net/usb/rndis_host.c, +// include/linux/usb/rndis_host.h, // drivers/usb/gadget/function/rndis.c, include/linux/usb/cdc.h). // See docs/RNDIS-PROTOCOL.md for detailed field tables and sources. // -// * Three rules that are the easiest to get wrong and must be remembered * +// Three rules that are the easiest to get wrong and must be remembered: // -// 1. **All multi-byte fields are little-endian** (the protocol originates from Windows NDIS); always access them with byte_order.h's +// 1. All multi-byte fields are little-endian (the protocol originates from Windows NDIS); +// always access them with byte_order.h's // LoadLe32 / StoreLe32, and do not map them directly with packed structs. // -// 2. **The base point of offset fields is not the message start, but message start + 8.** -// PACKET_MSG's DataOffset / OOBDataOffset / PerPacketInfoOffset, and -// QUERY/SET/QUERY_CMPLT's InformationBufferOffset all have the base point "the start of the block -// that this group of offset fields belongs to", i.e. at message start + 8 bytes. +// 2. The base point of offset fields is not the message start, but message start + 8. +// PACKET_MSG's DataOffset / OOBDataOffset / PerPacketInfoOffset, and QUERY/SET/QUERY_CMPLT's +// InformationBufferOffset all have the base point "the start of the block that this group of +// offset fields belongs to", i.e. at message start + 8 bytes. // absolute offset = 8 + field value // So when "the data immediately follows the 44-byte PACKET_MSG header", DataOffset = 36, not 44. // This is the number one trap when implementing RNDIS. // -// 3. **StatusBufferOffset of INDICATE_STATUS_MSG is the exception**: the MS documentation says its base point -// is the message start (+0), inconsistent with the +8 convention above. This is a contradiction in the spec itself. In practice this -// field is mostly 0 (MEDIA_CONNECT / MEDIA_DISCONNECT carry no status buffer), -// so parsing must tolerate both interpretations, and must not drop the connection because of an error in it. +// 3. StatusBufferOffset of INDICATE_STATUS_MSG is the exception: the MS documentation says its +// base point +// is the message start (+0), inconsistent with the +8 convention above. This is a contradiction +// in the spec itself. In practice this field is mostly 0 (MEDIA_CONNECT / MEDIA_DISCONNECT carry +// no status buffer), so parsing must tolerate both interpretations, and must not drop the +// connection because of an error in it. #pragma once #include @@ -42,19 +46,21 @@ inline constexpr std::uint32_t kMinorVersion = 0; /// Control channel timeout. /// -/// The spec gives a ControlTimeoutPeriod of 10 seconds, but Linux shrank it to 5 seconds because of the behavior of Microsoft's -/// ActiveSync implementation. 5 seconds is used here: if the device really needs 10 seconds to reply, the link is already unusable. +/// The spec gives a ControlTimeoutPeriod of 10 seconds, but Linux shrank it to 5 seconds because of +/// the behavior of Microsoft's ActiveSync implementation. 5 seconds is used here: if the device +/// really needs 10 seconds to reply, the link is already unusable. inline constexpr std::uint32_t kControlTimeoutMillis = 5'000; -/// Keepalive period. The spec's KeepAliveTimeoutPeriod is 5 seconds, and the semantics are to send only when "5 seconds have passed since -/// any message was last received from the device", not to send unconditionally every 5 seconds. +/// Keepalive period. The spec's KeepAliveTimeoutPeriod is 5 seconds, and the semantics are to send +/// only when "5 seconds have passed since any message was last received from the device", not to +/// send unconditionally every 5 seconds. inline constexpr std::uint32_t kKeepAliveTimeoutMillis = 5'000; /// Control message buffer size. /// -/// The spec requires at least 1024 bytes on the host side (GET_ENCAPSULATED_RESPONSE's -/// wLength is recommended to be 0x400). Windows actually uses the odd value 1025, and Linux copied it. -/// 1536 is used here to leave margin -- the return value of OID_GEN_SUPPORTED_LIST can be very long. +/// The spec requires at least 1024 bytes on the host side (GET_ENCAPSULATED_RESPONSE's wLength is +/// recommended to be 0x400). Windows actually uses the odd value 1025, and Linux copied it. 1536 is +/// used here to leave margin; the return value of OID_GEN_SUPPORTED_LIST can be very long. inline constexpr std::uint32_t kControlBufferBytes = 1536; // ============================================================================= @@ -84,8 +90,9 @@ enum class MessageType : std::uint32_t { kBus = 0xFF00'0001U, }; -/// Connection-oriented (CONDIS) message family. 802.3 Ethernet devices **never** use it; -/// it is listed here only so that on receipt we can explicitly report "connection-oriented devices are not supported" rather than "unknown message". +/// Connection-oriented (CONDIS) message family. 802.3 Ethernet devices **never** use it; it is +/// listed here only so that on receipt we can explicitly report "connection-oriented devices are +/// not supported" rather than "unknown message". enum class CondisMessageType : std::uint32_t { kCreateVc = 0x0000'8001U, kDeleteVc = 0x0000'8002U, @@ -96,19 +103,15 @@ enum class CondisMessageType : std::uint32_t { /// Converts any wire-format enum back to its raw LE32 value. /// -/// Constrained to "the underlying type must be exactly uint32_t", so that if someone accidentally shrinks the -/// underlying type of some protocol enum, this fails to compile directly instead of silently corrupting the wire format. +/// Constrained to "the underlying type must be exactly uint32_t", so that if someone accidentally +/// shrinks the underlying type of some protocol enum, this fails to compile directly instead of +/// silently corrupting the wire format. template requires std::is_enum_v && std::same_as, std::uint32_t> [[nodiscard]] constexpr std::uint32_t ToRaw(E value) noexcept { return static_cast(value); } -/// Whether it is a completion-type message. -[[nodiscard]] constexpr bool IsCompletion(std::uint32_t message_type) noexcept { - return (message_type & kMessageCompletionFlag) != 0; -} - /// Whether it belongs to the CONDIS (connection-oriented) message family. [[nodiscard]] constexpr bool IsCondis(std::uint32_t message_type) noexcept { return (message_type & ~kMessageCompletionFlag) >= 0x0000'8000U && @@ -121,8 +124,8 @@ template // ============================================================================= // Message lengths and field offsets // -// All fields are LE32. The kXxxOffset constants below are **byte offsets within the message**, -// for direct use by LoadLe32(buffer + kXxxOffset). +// All fields are LE32. The kXxxOffset constants below are **byte offsets within the message**, for +// direct use by LoadLe32(buffer + kXxxOffset). // ============================================================================= /// The first two fields common to every RNDIS message. @@ -135,14 +138,14 @@ inline constexpr std::uint32_t kMessageHeaderBytes = 8; /// The base point of "offset fields": message start + 8. See rule 2 in the file header. inline constexpr std::uint32_t kOffsetFieldBase = 8; -// ---- REMOTE_NDIS_INITIALIZE_MSG (24 bytes) ---- +// REMOTE_NDIS_INITIALIZE_MSG (24 bytes) inline constexpr std::uint32_t kInitializeMsgBytes = 24; inline constexpr std::uint32_t kInitializeRequestIdOffset = 8; inline constexpr std::uint32_t kInitializeMajorVersionOffset = 12; inline constexpr std::uint32_t kInitializeMinorVersionOffset = 16; inline constexpr std::uint32_t kInitializeMaxTransferSizeOffset = 20; -// ---- REMOTE_NDIS_INITIALIZE_CMPLT (52 bytes) ---- +// REMOTE_NDIS_INITIALIZE_CMPLT (52 bytes) inline constexpr std::uint32_t kInitializeCmpltBytes = 52; inline constexpr std::uint32_t kInitializeCmpltRequestIdOffset = 8; inline constexpr std::uint32_t kInitializeCmpltStatusOffset = 12; @@ -156,11 +159,11 @@ inline constexpr std::uint32_t kInitializeCmpltPacketAlignmentFactorOffset = 40; inline constexpr std::uint32_t kInitializeCmpltAfListOffsetOffset = 44; inline constexpr std::uint32_t kInitializeCmpltAfListSizeOffset = 48; -// ---- REMOTE_NDIS_HALT_MSG (12 bytes, the device does not reply) ---- +// REMOTE_NDIS_HALT_MSG (12 bytes, the device does not reply) inline constexpr std::uint32_t kHaltMsgBytes = 12; inline constexpr std::uint32_t kHaltRequestIdOffset = 8; -// ---- REMOTE_NDIS_QUERY_MSG / SET_MSG (28-byte header) ---- +// REMOTE_NDIS_QUERY_MSG / SET_MSG (28-byte header) inline constexpr std::uint32_t kQuerySetHeaderBytes = 28; inline constexpr std::uint32_t kQuerySetRequestIdOffset = 8; inline constexpr std::uint32_t kQuerySetOidOffset = 12; @@ -168,59 +171,62 @@ inline constexpr std::uint32_t kQuerySetInfoBufferLengthOffset = 16; inline constexpr std::uint32_t kQuerySetInfoBufferOffsetOffset = 20; inline constexpr std::uint32_t kQuerySetDeviceVcHandleOffset = 24; -/// The value InformationBufferOffset should be filled with when "the information buffer immediately follows the 28-byte header". +/// The value InformationBufferOffset should be filled with when "the information buffer immediately +/// follows the 28-byte header". inline constexpr std::uint32_t kQuerySetInlineInfoOffset = kQuerySetHeaderBytes - kOffsetFieldBase; static_assert(kQuerySetInlineInfoOffset == 20); -// ---- REMOTE_NDIS_QUERY_CMPLT (24-byte header) ---- +// REMOTE_NDIS_QUERY_CMPLT (24-byte header) inline constexpr std::uint32_t kQueryCmpltHeaderBytes = 24; inline constexpr std::uint32_t kQueryCmpltRequestIdOffset = 8; inline constexpr std::uint32_t kQueryCmpltStatusOffset = 12; inline constexpr std::uint32_t kQueryCmpltInfoBufferLengthOffset = 16; inline constexpr std::uint32_t kQueryCmpltInfoBufferOffsetOffset = 20; -/// The value of InformationBufferOffset when "the information buffer immediately follows the 24-byte header". +/// The value of InformationBufferOffset when "the information buffer immediately follows the +/// 24-byte header". inline constexpr std::uint32_t kQueryCmpltInlineInfoOffset = kQueryCmpltHeaderBytes - kOffsetFieldBase; static_assert(kQueryCmpltInlineInfoOffset == 16); -// ---- REMOTE_NDIS_SET_CMPLT (16 bytes) ---- +// REMOTE_NDIS_SET_CMPLT (16 bytes) inline constexpr std::uint32_t kSetCmpltBytes = 16; inline constexpr std::uint32_t kSetCmpltRequestIdOffset = 8; inline constexpr std::uint32_t kSetCmpltStatusOffset = 12; -// ---- REMOTE_NDIS_RESET_MSG (12 bytes, **no RequestId**) ---- +// REMOTE_NDIS_RESET_MSG (12 bytes, **no RequestId**) inline constexpr std::uint32_t kResetMsgBytes = 12; -/// Offset 8 is Reserved, not RequestId. So RESET cannot be paired by ID, -/// and only one RESET can be in flight at a time. +/// Offset 8 is Reserved, not RequestId. So RESET cannot be paired by ID, and only one RESET can be +/// in flight at a time. inline constexpr std::uint32_t kResetReservedOffset = 8; -// ---- REMOTE_NDIS_RESET_CMPLT (16 bytes, **no RequestId**) ---- +// REMOTE_NDIS_RESET_CMPLT (16 bytes, **no RequestId**) inline constexpr std::uint32_t kResetCmpltBytes = 16; inline constexpr std::uint32_t kResetCmpltStatusOffset = 8; -/// Non-zero means addressing information (packet filter, multicast table, functional address) was lost in the reset, -/// and the host must resend the corresponding SETs. +/// Non-zero means addressing information (packet filter, multicast table, functional address) was +/// lost in the reset, and the host must resend the corresponding SETs. inline constexpr std::uint32_t kResetCmpltAddressingResetOffset = 12; -// ---- REMOTE_NDIS_INDICATE_STATUS_MSG (20-byte header, **no RequestId**) ---- +// REMOTE_NDIS_INDICATE_STATUS_MSG (20-byte header, **no RequestId**) inline constexpr std::uint32_t kIndicateStatusHeaderBytes = 20; inline constexpr std::uint32_t kIndicateStatusStatusOffset = 8; inline constexpr std::uint32_t kIndicateStatusBufferLengthOffset = 12; /// Note the base point dispute; see rule 3 in the file header. inline constexpr std::uint32_t kIndicateStatusBufferOffsetOffset = 16; -/// The diagnostic information structure carried by INDICATE_STATUS (RNDIS_Diagnostic_Info, 8 bytes). +/// The diagnostic information structure carried by INDICATE_STATUS (RNDIS_Diagnostic_Info, 8 +/// bytes). inline constexpr std::uint32_t kDiagnosticInfoBytes = 8; inline constexpr std::uint32_t kDiagnosticInfoDiagStatusOffset = 0; inline constexpr std::uint32_t kDiagnosticInfoErrorOffsetOffset = 4; -// ---- REMOTE_NDIS_KEEPALIVE_MSG (12 bytes) / KEEPALIVE_CMPLT (16 bytes) ---- +// REMOTE_NDIS_KEEPALIVE_MSG (12 bytes) / KEEPALIVE_CMPLT (16 bytes) inline constexpr std::uint32_t kKeepAliveMsgBytes = 12; inline constexpr std::uint32_t kKeepAliveRequestIdOffset = 8; inline constexpr std::uint32_t kKeepAliveCmpltBytes = 16; inline constexpr std::uint32_t kKeepAliveCmpltRequestIdOffset = 8; inline constexpr std::uint32_t kKeepAliveCmpltStatusOffset = 12; -// ---- REMOTE_NDIS_PACKET_MSG (44-byte header) ---- +// REMOTE_NDIS_PACKET_MSG (44-byte header) inline constexpr std::uint32_t kPacketMsgHeaderBytes = 44; inline constexpr std::uint32_t kPacketDataOffsetOffset = 8; inline constexpr std::uint32_t kPacketDataLengthOffset = 12; @@ -232,15 +238,19 @@ inline constexpr std::uint32_t kPacketPerPacketInfoLengthOffset = 32; inline constexpr std::uint32_t kPacketVcHandleOffset = 36; inline constexpr std::uint32_t kPacketReservedOffset = 40; -/// The value DataOffset should be filled with when "the Ethernet frame immediately follows the 44-byte header". **It is 36, not 44.** +/// The value DataOffset should be filled with when "the Ethernet frame immediately follows the +/// 44-byte header". **It is 36, not 44.** inline constexpr std::uint32_t kPacketInlineDataOffset = kPacketMsgHeaderBytes - kOffsetFieldBase; -static_assert(kPacketInlineDataOffset == 36, "DataOffset 基准点是消息起始 +8,见文件头规则 2"); +static_assert(kPacketInlineDataOffset == 36, + "DataOffset counts from message start + 8; see rule 2 at the top of this file"); -/// In the device -> host direction, when multiple packets are aggregated, each PACKET_MSG should start at an offset that is a multiple of 8 bytes. +/// In the device -> host direction, when multiple packets are aggregated, each PACKET_MSG should +/// start at an offset that is a multiple of 8 bytes. inline constexpr std::uint32_t kDeviceToHostPacketAlignment = 8; -/// Legal upper bound of PacketAlignmentFactor (1 << 7 = 128 bytes). -/// A device reporting a larger value is a protocol violation; the implementation must clamp it, otherwise an absurd padding length would be computed. +/// Legal upper bound of PacketAlignmentFactor (1 << 7 = 128 bytes). A device reporting a larger +/// value is a protocol violation; the implementation must clamp it, otherwise an absurd padding +/// length would be computed. inline constexpr std::uint32_t kMaxPacketAlignmentFactor = 7; // ============================================================================= @@ -249,21 +259,22 @@ inline constexpr std::uint32_t kMaxPacketAlignmentFactor = 7; /// RNDIS_STATUS_* status codes. /// -/// Deliberately named StatusCode rather than Status: `tetherkitnext::Status` is already an alias of -/// `std::expected`, and defining another `Status` inside tetherkitnext::rndis would shadow it, -/// making it impossible to write "may fail but returns nothing" signatures within this namespace. +/// Named StatusCode rather than Status: `tetherkitnext::Status` is already an alias of +/// `std::expected`, and defining another `Status` inside tetherkitnext::rndis would +/// shadow it, making it impossible to write "may fail but returns nothing" signatures within this +/// namespace. enum class StatusCode : std::uint32_t { - // ---- Success / pending ---- + // Success / pending kSuccess = 0x0000'0000U, kPending = 0x0000'0103U, - // ---- Informational ---- + // Informational kNotRecognized = 0x0001'0001U, kNotCopied = 0x0001'0002U, kNotAccepted = 0x0001'0003U, kCallActive = 0x0001'0007U, - // ---- Indications (0x4001xxxx, appear in INDICATE_STATUS_MSG) ---- + // Indications (0x4001xxxx, appear in INDICATE_STATUS_MSG) kOnline = 0x4001'0003U, kResetStart = 0x4001'0004U, kResetEnd = 0x4001'0005U, @@ -272,7 +283,7 @@ enum class StatusCode : std::uint32_t { kWanLineUp = 0x4001'0008U, kWanLineDown = 0x4001'0009U, kWanFragment = 0x4001'000AU, - kMediaConnect = 0x4001'000BU, ///< Link up -- we use this to set feth UP. + kMediaConnect = 0x4001'000BU, ///< Link up; we use this to set feth UP. kMediaDisconnect = 0x4001'000CU, ///< Link down. kHardwareLineUp = 0x4001'000DU, kHardwareLineDown = 0x4001'000EU, @@ -283,13 +294,13 @@ enum class StatusCode : std::uint32_t { kLinkSpeedChange = 0x4001'0013U, kNetworkChange = 0x4001'0018U, - // ---- Warnings (0x8xxxxxxx) ---- + // Warnings (0x8xxxxxxx) kBufferOverflow = 0x8000'0005U, kNotResettable = 0x8001'0001U, kSoftErrors = 0x8001'0003U, kHardErrors = 0x8001'0004U, - // ---- Errors (0xCxxxxxxx) ---- + // Errors (0xCxxxxxxx) kFailure = 0xC000'0001U, kResources = 0xC000'009AU, kNotSupported = 0xC000'00BBU, @@ -321,11 +332,6 @@ enum class StatusCode : std::uint32_t { kTokenRingOpenError = 0xC001'1000U, }; -/// Whether it is a failure status (0xC0000000 and above are errors by NDIS convention). -[[nodiscard]] constexpr bool IsFailure(std::uint32_t status) noexcept { - return (status & 0xC000'0000U) == 0xC000'0000U; -} - /// Readable name of a status code; an unknown value returns empty. [[nodiscard]] std::string_view StatusName(std::uint32_t status) noexcept; @@ -334,36 +340,44 @@ enum class StatusCode : std::uint32_t { // ============================================================================= enum class Oid : std::uint32_t { - // ---- General (OID_GEN_*) ---- - kGenSupportedList = 0x0001'0101U, ///< Variable length: N LE32 OIDs. When querying, in_len must be 0. - kGenHardwareStatus = 0x0001'0102U, ///< LE32: 0=Ready 1=Initializing 2=Reset 3=Closing 4=NotReady - kGenMediaSupported = 0x0001'0103U, ///< LE32 array. - kGenMediaInUse = 0x0001'0104U, ///< LE32 array. - kGenMaximumFrameSize = 0x0001'0106U, ///< LE32: **excluding** the 14-byte Ethernet header, typically 1500. + // General (OID_GEN_*) + /// Variable length: N LE32 OIDs. When querying, in_len must be 0. + kGenSupportedList = 0x0001'0101U, + /// LE32: 0=Ready 1=Initializing 2=Reset 3=Closing 4=NotReady + kGenHardwareStatus = 0x0001'0102U, + kGenMediaSupported = 0x0001'0103U, ///< LE32 array. + kGenMediaInUse = 0x0001'0104U, ///< LE32 array. + /// LE32: **excluding** the 14-byte Ethernet header, typically 1500. + kGenMaximumFrameSize = 0x0001'0106U, kGenLinkSpeed = 0x0001'0107U, ///< LE32: unit is **100 bps**; 0 when disconnected. kGenTransmitBlockSize = 0x0001'010AU, ///< LE32 kGenReceiveBlockSize = 0x0001'010BU, ///< LE32 kGenVendorId = 0x0001'010CU, ///< LE32: the low 24 bits are the IEEE OUI. - kGenVendorDescription = 0x0001'010DU, ///< Variable-length ASCII, **NUL termination not guaranteed**. + /// Variable-length ASCII, **NUL termination not guaranteed**. + kGenVendorDescription = 0x0001'010DU, kGenCurrentPacketFilter = 0x0001'010EU, ///< LE32 bit mask, readable and writable. - kGenMaximumTotalSize = 0x0001'0111U, ///< LE32: maximum total frame length including headers. - kGenMacOptions = 0x0001'0113U, ///< LE32: MacOption bit mask. - kGenMediaConnectStatus = 0x0001'0114U, ///< LE32: **0=connected, 1=disconnected** (note that 0 means connected). - kGenPhysicalMedium = 0x0001'0202U, ///< LE32: PhysicalMedium; **optional OID**, failure is not fatal. - - // ---- Statistics (OID_GEN_*_OK/ERROR): may return 4 or 8 bytes, both must be accepted ---- + kGenMaximumTotalSize = 0x0001'0111U, ///< LE32: maximum total frame length including headers. + kGenMacOptions = 0x0001'0113U, ///< LE32: MacOption bit mask. + /// LE32: **0=connected, 1=disconnected** (note that 0 means connected). + kGenMediaConnectStatus = 0x0001'0114U, + /// LE32: PhysicalMedium; **optional OID**, failure is not fatal. + kGenPhysicalMedium = 0x0001'0202U, + + // Statistics (OID_GEN_*_OK/ERROR): may return 4 or 8 bytes, both must be accepted kGenXmitOk = 0x0002'0101U, kGenRcvOk = 0x0002'0102U, kGenXmitError = 0x0002'0103U, kGenRcvError = 0x0002'0104U, kGenRcvNoBuffer = 0x0002'0105U, - // ---- 802.3 specific ---- + // 802.3 specific kEthernetPermanentAddress = 0x0101'0101U, ///< 6-byte MAC. kEthernetCurrentAddress = 0x0101'0102U, ///< 6-byte MAC. - kEthernetMulticastList = 0x0101'0103U, ///< SET: array of 6N bytes of MACs. **Do not rely on QUERY**. - kEthernetMaximumListSize = 0x0101'0104U, ///< LE32: maximum number of entries in the multicast table. - kEthernetMacOptions = 0x0101'0105U, ///< LE32: Ethernet802_3MacOption bit mask. + /// SET: array of 6N bytes of MACs. **Do not rely on QUERY**. + kEthernetMulticastList = 0x0101'0103U, + /// LE32: maximum number of entries in the multicast table. + kEthernetMaximumListSize = 0x0101'0104U, + kEthernetMacOptions = 0x0101'0105U, ///< LE32: Ethernet802_3MacOption bit mask. }; /// Readable name of an OID; an unknown value returns empty. @@ -371,10 +385,12 @@ enum class Oid : std::uint32_t { /// Whether the return value of this OID is variable-length. /// -/// This distinction is crucial: for **fixed-length** OIDs, the QUERY's InformationBufferLength must be set to -/// >= the expected response length, with the same number of zero bytes appended at the end of the message, otherwise Microsoft's ActiveSync implementation replies with -/// RNDIS_STATUS_INVALID_LENGTH; while for **variable-length** OIDs 0 must be passed, otherwise the same error occurs. -/// This undocumented behavior was discovered only by sniffing the Windows driver of ActiveSync 4.1. +/// This distinction is crucial: for **fixed-length** OIDs, the QUERY's InformationBufferLength must +/// be set to >= the expected response length, with the same number of zero bytes appended at the +/// end of the message, otherwise Microsoft's ActiveSync implementation replies with +/// RNDIS_STATUS_INVALID_LENGTH; while for **variable-length** OIDs 0 must be passed, otherwise the +/// same error occurs. This undocumented behavior was discovered only by sniffing the Windows driver +/// of ActiveSync 4.1. [[nodiscard]] constexpr bool IsVariableLengthOid(Oid oid) noexcept { switch (oid) { case Oid::kGenSupportedList: @@ -393,12 +409,12 @@ enum class Oid : std::uint32_t { // ============================================================================= enum class PacketFilter : std::uint32_t { - kDirected = 0x0000'0001U, ///< Destination MAC equals this machine's address. - kMulticast = 0x0000'0002U, ///< Multicast addresses that are in the multicast table. - kAllMulticast = 0x0000'0004U, ///< All multicast, ignoring the multicast table. - kBroadcast = 0x0000'0008U, ///< ff:ff:ff:ff:ff:ff + kDirected = 0x0000'0001U, ///< Destination MAC equals the host's address. + kMulticast = 0x0000'0002U, ///< Multicast addresses that are in the multicast table. + kAllMulticast = 0x0000'0004U, ///< All multicast, ignoring the multicast table. + kBroadcast = 0x0000'0008U, ///< ff:ff:ff:ff:ff:ff kSourceRouting = 0x0000'0010U, - kPromiscuous = 0x0000'0020U, ///< All frames. + kPromiscuous = 0x0000'0020U, ///< All frames. kSmt = 0x0000'0040U, kAllLocal = 0x0000'0080U, kGroup = 0x0000'1000U, @@ -407,11 +423,13 @@ enum class PacketFilter : std::uint32_t { kMacFrame = 0x0000'8000U, }; -/// The packet filter combination used by this project, consistent with Linux rndis_host (0x0000002D). +/// The packet filter combination used by this project, consistent with Linux rndis_host +/// (0x0000002D). /// -/// Why enable PROMISCUOUS: we bridge the device as a "network cable" to feth, -/// and the host side may send and receive frames of arbitrary MACs (for example when an upper layer bridges again or VMs are involved), so it cannot only accept -/// directed. The same goes for ALL_MULTICAST -- it avoids maintaining a multicast table while also missing IPv6 neighbor discovery. +/// Why enable PROMISCUOUS: we bridge the device as a "network cable" to feth, and the host side may +/// send and receive frames of arbitrary MACs (for example when an upper layer bridges again or VMs +/// are involved), so it cannot only accept directed. The same goes for ALL_MULTICAST: it avoids +/// maintaining a multicast table while also missing IPv6 neighbor discovery. inline constexpr std::uint32_t kDefaultPacketFilter = ToRaw(PacketFilter::kDirected) | ToRaw(PacketFilter::kBroadcast) | ToRaw(PacketFilter::kAllMulticast) | ToRaw(PacketFilter::kPromiscuous); @@ -490,8 +508,7 @@ inline constexpr std::uint8_t kControlInRequestType = 0xA1; /// Notification on the interrupt IN endpoint: 8 bytes = two LE32. /// /// Note this is **not** CDC's usb_cdc_notification structure, but RNDIS's own format: -/// offset 0..3 = Notification (0x00000001 = RESPONSE_AVAILABLE) -/// offset 4..7 = Reserved (0) +/// offset 0..3 = Notification (0x00000001 = RESPONSE_AVAILABLE) offset 4..7 = Reserved (0) inline constexpr std::uint32_t kNotificationBytes = 8; inline constexpr std::uint32_t kNotificationResponseAvailable = 0x0000'0001U; inline constexpr std::uint32_t kNotificationValueOffset = 0; @@ -508,10 +525,9 @@ struct InterfaceSignature { /// All known forms of the RNDIS communications-class interface (four in measured use). /// -/// (a) Standard MS RNDIS: CDC Communication / ACM / vendor-specific protocol -/// (b) ActiveSync (Windows Mobile 5 / Windows Phone): USB_CLASS_MISC -/// (c) Wireless RNDIS (phone USB tethering, WWAN modules): Wireless Controller / RF / RNDIS -/// (d) Novatel/Verizon USB730L variant +/// (a) Standard MS RNDIS: CDC Communication / ACM / vendor-specific protocol (b) ActiveSync +/// (Windows Mobile 5 / Windows Phone): USB_CLASS_MISC (c) Wireless RNDIS (phone USB tethering, WWAN +/// modules): Wireless Controller / RF / RNDIS (d) Novatel/Verizon USB730L variant inline constexpr InterfaceSignature kControlSignatureMicrosoft{0x02, 0x02, 0xFF}; inline constexpr InterfaceSignature kControlSignatureActiveSync{0xEF, 0x01, 0x01}; inline constexpr InterfaceSignature kControlSignatureWireless{0xE0, 0x01, 0x03}; @@ -542,16 +558,17 @@ static_assert(kHardHeaderBytes == 58); /// The standard Ethernet MTU. inline constexpr std::uint32_t kDefaultMtu = 1500; -/// Given an MTU, computes the maximum number of bytes one frame occupies on USB (including the RNDIS header and the Ethernet header). +/// Given an MTU, computes the maximum number of bytes one frame occupies on USB (including the +/// RNDIS header and the Ethernet header). [[nodiscard]] constexpr std::uint32_t HardMtuFor(std::uint32_t mtu) noexcept { return mtu + kHardHeaderBytes; } /// Computes the MaxTransferSize that should be claimed in INITIALIZE_MSG. /// -/// Follows Linux's algorithm: `(hard_mtu + maxpacket + 1) & ~(maxpacket - 1)`, -/// i.e. round up to an integer multiple of the endpoint max packet size and leave one packet of margin. -/// At high speed (maxpacket=512) an MTU of 1500 yields 2048; at full speed (64) it yields 1600. +/// Follows Linux's algorithm: `(hard_mtu + maxpacket + 1) & ~(maxpacket - 1)`, i.e. round up to an +/// integer multiple of the endpoint max packet size and leave one packet of margin. At high speed +/// (maxpacket=512) an MTU of 1500 yields 2048; at full speed (64) it yields 1600. [[nodiscard]] constexpr std::uint32_t MaxTransferSizeFor(std::uint32_t mtu, std::uint32_t endpoint_max_packet) noexcept { const std::uint32_t hard_mtu = HardMtuFor(mtu); diff --git a/include/tetherkitnext/rndis/state_machine.h b/include/tetherkitnext/rndis/state_machine.h index 6739cbb..ca87f87 100644 --- a/include/tetherkitnext/rndis/state_machine.h +++ b/include/tetherkitnext/rndis/state_machine.h @@ -1,6 +1,7 @@ // RNDIS host-side state machine. // -// * State diagram (the spec defines three device-side states; the host side mirrors them and adds transition states) * +// State diagram (the spec defines three device-side states; the host side mirrors them and adds +// transition states): // // ┌──────────────────┐ // ┌────────────►│ kUninitialized │◄────────────┐ @@ -16,7 +17,7 @@ // │ ▼ │ // │ ┌──────────────────┐ │ // │ │ kInitialized │ │ <- control messages usable, -// │ └────────┬─────────┘ │ but data channel **not open** +// │ └────────┬─────────┘ │ but data channel not open // │ │ QUERY MAC/link etc. │ // │ │ SET packet filter≠0 │ // │ ▼ │ @@ -33,27 +34,30 @@ // Semantics of the spec's original text: // * After bus initialization the device is in RNDIS-uninitialized; // * On receiving INITIALIZE_MSG and replying INITIALIZE_CMPLT(SUCCESS) -> RNDIS-initialized; -// * On receiving SET(OID_GEN_CURRENT_PACKET_FILTER, **non-zero**) -> RNDIS-data-initialized, -// **only then does data start flowing**; +// * On receiving SET(OID_GEN_CURRENT_PACKET_FILTER, non-zero) -> RNDIS-data-initialized, only +// then does data start flowing; // * In data-initialized, on receiving SET(filter = 0) -> back to RNDIS-initialized; -// * At any time, on receiving HALT_MSG or a bus disconnect -> immediately back to RNDIS-uninitialized. +// * At any time, on receiving HALT_MSG or a bus disconnect -> immediately back to +// RNDIS-uninitialized. // -// * Three easy-to-get-wrong protocol details * +// Three easy-to-get-wrong protocol details: // -// 1. **Control requests must be serialized.** GET_ENCAPSULATED_RESPONSE can only "take the next queued -// response"; it has no ability to select by RequestId. So only one request can be in flight at a time. +// 1. Control requests must be serialized. GET_ENCAPSULATED_RESPONSE can only "take the next +// queued response"; it has no ability to select by RequestId. So only one request can be in +// flight at a time. // -// 2. **The device cuts in.** While waiting for some *_CMPLT, the device may well first slip in a -// REMOTE_NDIS_INDICATE_STATUS_MSG (media connect status change) or a **device-initiated** -// REMOTE_NDIS_KEEPALIVE_MSG (in which case the host must reply KEEPALIVE_CMPLT, otherwise the device may -// consider the host dead and disconnect). So the control read loop must be written as a dispatcher: dispatch by MessageType, -// rather than "blindly assuming that what was read is the one I want". +// 2. The device cuts in. While waiting for some *_CMPLT, the device may well first slip in a +// REMOTE_NDIS_INDICATE_STATUS_MSG (media connect status change) or a device-initiated +// REMOTE_NDIS_KEEPALIVE_MSG (in which case the host must reply KEEPALIVE_CMPLT, otherwise the +// device may consider the host dead and disconnect). So the control read loop must be written +// as a dispatcher: dispatch by MessageType, rather than "blindly assuming that what was read +// is the one I want". // -// 3. **RESET has no RequestId.** RESET_MSG's offset 8 is Reserved, -// and RESET_CMPLT's offset 8 is Status (not 12). So RESET cannot be paired by ID, -// and only one can be in flight at a time. Moreover, when AddressingReset in RESET_CMPLT is non-zero, -// the host **must resend** SET(OID_GEN_CURRENT_PACKET_FILTER) (and if a multicast list was set, also resend -// SET(OID_802_3_MULTICAST_LIST)) -- otherwise data will not flow again after the reset. +// 3. RESET has no RequestId. RESET_MSG's offset 8 is Reserved, and RESET_CMPLT's offset 8 is +// Status (not 12). So RESET cannot be paired by ID, and only one can be in flight at a time. +// Moreover, when AddressingReset in RESET_CMPLT is non-zero, the host must resend +// SET(OID_GEN_CURRENT_PACKET_FILTER) (and if a multicast list was set, also resend +// SET(OID_802_3_MULTICAST_LIST)); otherwise data will not flow again after the reset. #pragma once #include @@ -71,26 +75,30 @@ namespace tetherkitnext::rndis { /// Host-side state. enum class State : std::uint8_t { - kUninitialized, ///< Uninitialized. The control channel is usable, but the device has not yet agreed to start work. - kInitializing, ///< INITIALIZE_MSG sent, waiting for INITIALIZE_CMPLT. - kInitialized, ///< Negotiation complete. OIDs can be read and written, but the **data channel is not open yet**. - kDataInitialized, ///< A non-zero packet filter has been set; data starts flowing. - kHalting, ///< HALT_MSG sent, wrapping up. + /// Uninitialized. The control channel is usable, but the device has not yet agreed to start work. + kUninitialized, + kInitializing, ///< INITIALIZE_MSG sent, waiting for INITIALIZE_CMPLT. + /// Negotiation complete. OIDs can be read and written, but the **data channel is not open yet**. + kInitialized, + kDataInitialized, ///< A non-zero packet filter has been set; data starts flowing. + kHalting, ///< HALT_MSG sent, wrapping up. }; [[nodiscard]] std::string_view StateName(State state) noexcept; /// Device information reported by the device that the host cares about. struct DeviceInfo { - /// The device's permanent MAC. This is the address the host-side feth should adopt -- under RNDIS semantics the device is - /// that NIC, and the peer's ARP table and DHCP lease are both built on it. + /// The device's permanent MAC. This is the address the host-side feth should adopt; under RNDIS + /// semantics the device is that NIC, and the peer's ARP table and DHCP lease are both built on + /// it. MacAddress permanent_address{}; /// Current MAC. Same as permanent for most devices. MacAddress current_address{}; bool has_permanent_address = false; bool has_current_address = false; - /// Link speed, **in units of 100 bps** (this is NDIS's convention, not bps). 0 means disconnected. + /// Link speed, **in units of 100 bps** (this is NDIS's convention, not bps). 0 means + /// disconnected. std::uint32_t link_speed_100bps = 0; /// Maximum frame length, **excluding** the 14-byte Ethernet header. Typically 1500. std::uint32_t maximum_frame_size = 0; @@ -98,7 +106,8 @@ struct DeviceInfo { PhysicalMedium physical_medium = PhysicalMedium::kUnspecified; /// Media connect status. **Note that 0 means connected.** MediaState media_state = MediaState::kConnected; - /// Vendor description string (NUL termination not guaranteed; already normalized into std::string here). + /// Vendor description string (NUL termination not guaranteed; already normalized into std::string + /// here). std::string vendor_description; std::uint32_t vendor_id = 0; @@ -113,26 +122,31 @@ struct StateMachineConfig { /// The desired MTU. Lowered by Negotiate when the device cannot fit it. std::uint32_t requested_mtu = kDefaultMtu; - /// The MaxTransferSize the host claims in INITIALIZE_MSG, which is also the size of our bulk IN buffer. + /// The MaxTransferSize the host claims in INITIALIZE_MSG, which is also the size of our bulk IN + /// buffer. /// - /// **This is the most important lever for RNDIS throughput**: it is the **only** means of getting the device to aggregate multiple REMOTE_NDIS_PACKET_MSGs - /// into one bulk IN. The larger the reported value, the more the device aggregates, and the lower the USB - /// and system-call overhead amortized per frame. Linux conservatively reports only 2048 (one full frame); we report 16 KiB -- - /// leaving ample room for aggregation while not exceeding the spec's 0x4000 cap for USB 1.1 devices. + /// **This is the most important lever for RNDIS throughput**: it is the **only** means of getting + /// the device to aggregate multiple REMOTE_NDIS_PACKET_MSGs into one bulk IN. The larger the + /// reported value, the more the device aggregates, and the lower the USB and system-call overhead + /// amortized per frame. Linux conservatively reports only 2048 (one full frame); we report 16 + /// KiB: leaving ample room for aggregation while not exceeding the spec's 0x4000 cap for USB 1.1 + /// devices. std::uint32_t host_max_transfer_size = 16 * 1024; - /// How many PACKET_MSGs to aggregate at most per bulk OUT in the host -> device direction. 0 means no extra limit, - /// fully following the MaxPacketsPerMessage reported by the device. + /// How many PACKET_MSGs to aggregate at most per bulk OUT in the host -> device direction. 0 + /// means no extra limit, fully following the MaxPacketsPerMessage reported by the device. /// - /// This knob exists because the aggregation capability the device reports is **not necessarily trustworthy**. Mainline Linux gadget's - /// `rndis_rm_hdr()` splits only one PACKET_MSG per bulk OUT, while a vendor kernel may still report - /// MaxPacketsPerMessage=10. If such a device is really encountered, all frames except the first would be silently dropped by the peer, - /// and clamping to 1 falls back to "one frame per transfer". + /// This knob exists because the aggregation capability the device reports is not necessarily + /// trustworthy. Mainline Linux gadget's `rndis_rm_hdr()` splits only one PACKET_MSG per bulk OUT, + /// while a vendor kernel may still report MaxPacketsPerMessage=10. If such a device is really + /// encountered, all frames except the first would be silently dropped by the peer, and clamping + /// to 1 falls back to "one frame per transfer". /// - /// WARNING: **But do not take it as the default explanation for dropped frames.** On the Android device that was measured - /// (reporting 10 packets / 15800 bytes) an A/B test was done: clamping to 1 was actually slower (TCP TX 125 vs 234 Mbps), - /// and the drop rate did not improve either -- that device's aggregation **really works**. So this is a diagnostic / fallback - /// knob, not a switch for a known defect. See "real-device end-to-end measurements" in docs/BENCHMARKS.md. + /// WARNING: But do not take it as the default explanation for dropped frames. On the Android + /// device that was measured (reporting 10 packets / 15800 bytes) an A/B test was done: clamping + /// to 1 was actually slower (TCP TX 125 vs 234 Mbps), and the drop rate did not improve either; + /// that device's aggregation really works. So this is a diagnostic / fallback knob, not a switch + /// for a known defect. See "real-device end-to-end measurements" in docs/BENCHMARKS.md. std::uint32_t max_tx_packets_per_message = 0; /// The packet filter bit mask to set. @@ -143,15 +157,17 @@ struct StateMachineConfig { /// Keepalive period (milliseconds). /// - /// The semantics are to send only when "this long has passed since any message was last received from the device", not to send unconditionally on a timer. - /// Note that libusb control transfers on Apple Silicon are about 10x slower than on x64 (issue #1288), - /// so do not set this value too small. + /// The semantics are to send only when "this long has passed since any message was last received + /// from the device", not to send unconditionally on a timer. Note that libusb control transfers + /// on Apple Silicon are about 10x slower than on x64 (issue #1288), so do not set this value too + /// small. std::uint32_t keepalive_interval_millis = kKeepAliveTimeoutMillis; /// Upper limit on the number of response polls for a single control request. /// - /// Linux's approach is to poll up to 10 times, 40 ms apart (about 400 ms in total). We wait for the interrupt - /// endpoint's notification first and poll after a timeout, so this is mainly a backstop for devices "without an interrupt endpoint". + /// Linux's approach is to poll up to 10 times, 40 ms apart (about 400 ms in total). We wait for + /// the interrupt endpoint's notification first and poll after a timeout, so this is mainly a + /// backstop for devices "without an interrupt endpoint". std::uint32_t response_poll_attempts = 10; /// Wait between polls (milliseconds). @@ -163,8 +179,9 @@ struct StateMachineConfig { /// Events the state machine reports outward. /// -/// Callbacks are used instead of having the caller poll the state, because events such as "media connect status change" are actively -/// pushed by the device (INDICATE_STATUS), and polling would miss the edges. +/// Callbacks are used instead of having the caller poll the state, because events such as "media +/// connect status change" are actively pushed by the device (INDICATE_STATUS), and polling would +/// miss the edges. class StateMachineObserver { public: StateMachineObserver() = default; @@ -180,22 +197,25 @@ class StateMachineObserver { /// Negotiation complete; the data path can be built with these parameters. virtual void OnNegotiated(const NegotiatedParameters& parameters, const DeviceInfo& info) = 0; - /// Link up / down (from MEDIA_CONNECT / MEDIA_DISCONNECT in INDICATE_STATUS, - /// or the result of QUERY OID_GEN_MEDIA_CONNECT_STATUS). + /// Link up / down (from MEDIA_CONNECT / MEDIA_DISCONNECT in INDICATE_STATUS, or the result of + /// QUERY OID_GEN_MEDIA_CONNECT_STATUS). virtual void OnLinkStateChanged(bool connected) = 0; - /// Device reset complete, and the host is required to resend addressing configuration. The data path needs to pause briefly. + /// Device reset complete, and the host is required to resend addressing configuration. The data + /// path needs to pause briefly. virtual void OnDeviceReset(bool addressing_lost) = 0; - /// The link is no longer usable (consecutive keepalive failures / device disconnected / unrecoverable protocol error). + /// The link is no longer usable (consecutive keepalive failures / device disconnected / + /// unrecoverable protocol error). virtual void OnFatalError(const Error& error) = 0; }; /// The RNDIS host-side state machine. /// -/// **Thread constraint: all methods of this class must be called from the same thread** (the control thread). This is not the implementation -/// being lazy, but a hard libusb requirement -- synchronous control transfers return -/// LIBUSB_ERROR_BUSY on the event thread, so the control channel must exclusively own a non-event thread. +/// **Thread constraint: all methods of this class must be called from the same thread** (the +/// control thread). This is not the implementation being lazy, but a hard libusb requirement; +/// synchronous control transfers return LIBUSB_ERROR_BUSY on the event thread, so the control +/// channel must exclusively own a non-event thread. class StateMachine { public: StateMachine(ControlChannel& channel, StateMachineObserver& observer, @@ -219,35 +239,40 @@ class StateMachine { /// 1. INITIALIZE_MSG -> INITIALIZE_CMPLT, negotiating MaxTransferSize / alignment / MTU; /// 2. QUERY OID_GEN_PHYSICAL_MEDIUM (**optional OID, failure is not fatal**); /// 3. QUERY OID_802_3_PERMANENT_ADDRESS (get the MAC the host side will use); - /// 4. QUERY OID_802_3_CURRENT_ADDRESS / OID_GEN_MAXIMUM_FRAME_SIZE / - /// OID_GEN_LINK_SPEED / OID_GEN_MEDIA_CONNECT_STATUS (all non-fatal); + /// 4. QUERY OID_802_3_CURRENT_ADDRESS / OID_GEN_MAXIMUM_FRAME_SIZE / OID_GEN_LINK_SPEED / + /// OID_GEN_MEDIA_CONNECT_STATUS (all non-fatal); /// 5. SET OID_GEN_CURRENT_PACKET_FILTER = non-zero -> data starts flowing. /// Failure of any fatal step sends HALT_MSG and then returns the error. [[nodiscard]] Status Start(); /// Graceful shutdown: SET filter = 0, then send HALT_MSG. /// - /// Even if an error occurs midway, it makes a best effort to send the HALT -- if it is not sent, the device may keep thinking the host - /// is still there, and the state will not be clean the next time it is plugged in. + /// Even if an error occurs midway, it makes a best effort to send the HALT; if it is not sent, + /// the device may keep thinking the host is still there, and the state will not be clean the next + /// time it is plugged in. void Stop(); - /// Does one round of "periodic work that should be done". Should be called periodically in a loop by the control thread. + /// Does one round of "periodic work that should be done". Should be called periodically in a loop + /// by the control thread. /// /// Does two things: - /// * When more than the keepalive period has passed since a message was last received from the device, sends one KEEPALIVE; - /// * Drains messages actively pushed by the device on the control channel (INDICATE_STATUS / device-initiated - /// KEEPALIVE), not letting them pile up. + /// * When more than the keepalive period has passed since a message was last received from the + /// device, sends one KEEPALIVE; + /// * Drains messages actively pushed by the device on the control channel (INDICATE_STATUS / + /// device-initiated KEEPALIVE), not letting them pile up. /// /// Returning an error means the link is no longer usable, and the caller should reconnect. [[nodiscard]] Status Poll(); - /// How many milliseconds remain until the next periodic work is due. Lets the caller decide how long to sleep. + /// How many milliseconds remain until the next periodic work is due. Lets the caller decide how + /// long to sleep. [[nodiscard]] std::uint32_t MillisUntilNextPoll() const noexcept; /// Actively requests a soft reset of the device. /// - /// RESET is a soft reset: the control channel stays intact, but the device discards all outstanding requests and data packets. - /// If AddressingReset in RESET_CMPLT is non-zero, this method automatically resends the packet filter setting. + /// RESET is a soft reset: the control channel stays intact, but the device discards all + /// outstanding requests and data packets. If AddressingReset in RESET_CMPLT is non-zero, this + /// method automatically resends the packet filter setting. [[nodiscard]] Status Reset(); private: @@ -259,14 +284,15 @@ class StateMachine { /// Sends a request, then waits for its response. /// - /// In the meantime the device's cut-in messages (INDICATE_STATUS / device-initiated KEEPALIVE) are handled correctly: - /// they are dispatched away and it keeps waiting for the one we want. + /// In the meantime the device's cut-in messages (INDICATE_STATUS / device-initiated KEEPALIVE) + /// are handled correctly: they are dispatched away and it keeps waiting for the one we want. [[nodiscard]] Result Transact(std::span request, MessageType expected_reply); /// Reads and dispatches one device-pushed message. /// - /// @param expected_reply The message type we are waiting for; when it is read, returns true and writes the view + /// @param expected_reply The message type we are waiting for; when it is read, returns true and + /// writes the view /// into out_response. Passing std::nullopt means "only drain pushed /// messages, without waiting for any specific reply". [[nodiscard]] Result PumpOnce(std::optional expected_reply, @@ -275,10 +301,11 @@ class StateMachine { /// Handles one INDICATE_STATUS. void HandleIndicateStatus(std::span message); - /// Handles a KEEPALIVE_MSG actively sent by the device -- **KEEPALIVE_CMPLT must be replied**. + /// Handles a KEEPALIVE_MSG actively sent by the device; **KEEPALIVE_CMPLT must be replied**. [[nodiscard]] Status HandleDeviceKeepAlive(std::span message); - /// Queries an OID. When `fatal` is false, the device returning "unsupported" is not counted as an error. + /// Queries an OID. When `fatal` is false, the device returning "unsupported" is not counted as an + /// error. [[nodiscard]] Result> QueryOid(Oid oid, std::uint32_t expected_bytes, bool fatal); @@ -311,11 +338,17 @@ class StateMachine { NegotiatedParameters parameters_; std::uint32_t next_request_id_ = 1; + + /// RequestId of the request Transact() is waiting on; nullopt for RESET (its completion carries + /// no id) and outside Transact(). PumpOnce() discards completions of the right type but another + /// id: late replies to requests that already timed out. + std::optional awaited_request_id_; Nanos last_device_activity_ = 0; Nanos next_keepalive_deadline_ = 0; std::uint32_t consecutive_keepalive_failures_ = 0; - /// The packet filter value most recently set successfully. Used when a replay is required after RESET. + /// The packet filter value most recently set successfully. Used when a replay is required after + /// RESET. std::uint32_t active_packet_filter_ = 0; /// Assembly buffer for request messages. Control messages are small, so one buffer suffices. diff --git a/include/tetherkitnext/usb/context.h b/include/tetherkitnext/usb/context.h index 915e720..04a0b4e 100644 --- a/include/tetherkitnext/usb/context.h +++ b/include/tetherkitnext/usb/context.h @@ -1,34 +1,36 @@ // libusb context and the event loop thread. // -// * libusb's threading model on macOS (measured + confirmed against source; differs from intuition, be sure to understand it) * +// * libusb's threading model on macOS (measured + confirmed against source; differs from intuition, +// be sure to understand it) * // // libusb's darwin backend itself starts an internal thread (org.libusb.device-hotplug) that runs -// the CFRunLoop, and IOKit completion notifications arrive on that thread. But **the user's transfer callback does not execute on -// that thread** -- darwin_async_io_callback only hangs the transfer onto -// ctx->completed_transfers and writes the event pipe; what actually invokes the callback is **whichever thread -// calls libusb_handle_events*()**. +// the CFRunLoop, and IOKit completion notifications arrive on that thread. But the user's +// transfer callback does not execute on that thread: darwin_async_io_callback only hangs the +// transfer onto ctx->completed_transfers and writes the event pipe; what actually invokes the +// callback is whichever thread calls libusb_handle_events*(). // // From this follow three iron rules: // // 1. Someone must keep calling libusb_handle_events*(), otherwise callbacks are never invoked. // This class does exactly that: a dedicated thread loops on handle_events forever. // -// 2. **A callback must absolutely not call a synchronous API** (libusb_control_transfer / -// libusb_bulk_transfer). They start with -// `if (usbi_handling_events(ctx)) return LIBUSB_ERROR_BUSY;`, -// which is a TLS check -- calling from the event thread (including inside any callback) is bound to fail. -// -> The RNDIS control channel therefore must run on a **separate thread**; see rndis/state_machine. +// 2. A callback must absolutely not call a synchronous API (libusb_control_transfer / +// libusb_bulk_transfer). They start with `if (usbi_handling_events(ctx)) return +// LIBUSB_ERROR_BUSY;`, which is a TLS check; calling from the event thread (including inside +// any callback) is bound to fail. -> The RNDIS control channel therefore must run on a +// separate thread; see rndis/state_machine. // -// 3. **A callback must absolutely not do blocking I/O.** When usbi_handle_transfer_completion invokes the callback it -// holds ctx->event_waiters_lock; another thread waiting for a synchronous transfer to complete needs to grab this lock, -// and however long the callback blocks, it holds that thread up just as long. -// -> The RX callback only does "unpack RNDIS packets + memcpy into the lock-free queue + resubmit immediately", -// and the real BPF write() is handed to another thread. +// 3. A callback must absolutely not do blocking I/O. When usbi_handle_transfer_completion invokes +// the callback it holds ctx->event_waiters_lock; another thread waiting for a synchronous +// transfer to complete needs to grab this lock, and however long the callback blocks, it holds +// that thread up just as long. -> The RX callback only does "unpack RNDIS packets + memcpy +// into the lock-free queue + resubmit immediately", and the real BPF write() is handed to +// another thread. // -// 4. **Directly resubmitting the same transfer inside a callback is officially supported** -// (usbi_handle_transfer_completion has already removed it from the flying list before calling the callback, -// and cleared the IN_FLIGHT flag, and does not hold itransfer->lock). This is the key technique for keeping -// the USB pipe saturated. +// 4. Directly resubmitting the same transfer inside a callback is officially supported +// (usbi_handle_transfer_completion has already removed it from the flying list before calling +// the callback, and cleared the IN_FLIGHT flag, and does not hold itransfer->lock). This is +// the key technique for keeping the USB pipe saturated. #pragma once #include @@ -44,8 +46,8 @@ namespace tetherkitnext::usb { /// libusb context + dedicated event loop thread. /// -/// Lifetime constraint: all device handles and transfers must be released completely **before** this object is destroyed. -/// Destruction order = stop the event thread -> libusb_exit. +/// Lifetime constraint: all device handles and transfers must be released completely **before** +/// this object is destroyed. Destruction order = stop the event thread -> libusb_exit. class Context { public: /// Initializes libusb and starts the event thread. diff --git a/include/tetherkitnext/usb/data_channel.h b/include/tetherkitnext/usb/data_channel.h index a8969da..b56f308 100644 --- a/include/tetherkitnext/usb/data_channel.h +++ b/include/tetherkitnext/usb/data_channel.h @@ -1,41 +1,41 @@ // RNDIS data channel: asynchronous bulk IN / OUT transfer pools. // -// * Teardown algorithm free of use-after-free (the most important part of this file) * +// Teardown algorithm free of use-after-free (the most important part of this file): // -// libusb_close **does not** reclaim in-flight transfers for you. For transfers still in flight, do_close() -// only does list_del + nulls transfer->dev_handle, then prints a -// "Device handle closed while transfer was still being processed" log -- -// **it neither calls your callback nor frees memory**. And afterwards the darwin backend's close does -// USBInterfaceClose, which triggers an IOKit abort, and darwin_async_io_callback still runs on libusb's -// internal thread and calls usbi_signal_transfer_completion(). If by then you have already -// done libusb_free_transfer, it is a use-after-free. +// libusb_close does not reclaim in-flight transfers for you. For transfers still in flight, +// do_close() only does list_del + nulls transfer->dev_handle, then prints a "Device handle closed +// while transfer was still being processed" log. It neither calls your callback nor frees memory. +// And afterwards the darwin backend's close does USBInterfaceClose, which triggers an IOKit +// abort, and darwin_async_io_callback still runs on libusb's internal thread and calls +// usbi_signal_transfer_completion(). If by then you have already done libusb_free_transfer, it is +// a use-after-free. // // The correct order (this is what Shutdown() implements): -// 1. Set the shutdown flag -- callbacks that see it no longer resubmit, letting the in-flight count converge naturally; +// 1. Set the shutdown flag: callbacks that see it no longer resubmit, letting the in-flight +// count converge naturally; // 2. Call libusb_cancel_transfer on the in-flight transfers; -// 3. **Wait until the in-flight count reaches zero** (every callback has come back); +// 3. Wait until the in-flight count reaches zero (every callback has come back); // 4. Only then libusb_free_transfer + release the buffers; // 5. Only afterwards may the caller destroy the Device (release_interface -> close). // -// WARNING: step 3 **must never wait on the libusb event thread** -- callbacks run exactly on that thread, -// and waiting there means waiting on oneself, an inevitable deadlock. So Shutdown() may only be called from the control thread or the main thread; -// the code reminds you doubly, with comments and assertions. +// WARNING: step 3 must never wait on the libusb event thread. Callbacks run on that thread, so +// waiting there means waiting on oneself, an inevitable deadlock. Shutdown() may therefore only +// be called from the control thread or the main thread (enforced by an assertion). // -// About darwin's cancel granularity: libusb_cancel_transfer on darwin is -// darwin_abort_transfers -> **AbortPipe(pipeRef)**, i.e. canceling one transfer -// cancels **all** in-flight transfers on **that endpoint** (all come back as kIOReturnAborted -> -// LIBUSB_TRANSFER_CANCELLED). So it would actually suffice to call it once per endpoint, -// but calling it one by one is idempotent and clearer, so this micro-optimization is not done. +// About darwin's cancel granularity: libusb_cancel_transfer on darwin is darwin_abort_transfers +// -> AbortPipe(pipeRef), i.e. canceling one transfer cancels all in-flight transfers on that +// endpoint (all come back as kIOReturnAborted -> LIBUSB_TRANSFER_CANCELLED). So it would actually +// suffice to call it once per endpoint, but calling it one by one is idempotent and clearer, so +// this micro-optimization is not done. // -// * Why "fewer and larger, not more and smaller" * +// Why "fewer and larger, not more and smaller": // -// The darwin backend calls darwin_get_pipe_properties before **every** submit_bulk_transfer, -// which on IOUSBInterfaceInterface >= 550 amounts to two IOKit user-client calls -// (GetPipePropertiesV3 + GetEndpointPropertiesV3). That is, on macOS every -// libusb_submit_transfer costs at least 3 IOKit round trips, not 1. -// Conversely, the darwin backend has **no length limit and does no fragmentation** for a single bulk transfer -// (only the Linux backend has the MAX_BULK_BUFFER_LENGTH = 16384 URB splitting). -// -> Conclusion: use fewer, larger transfers. +// The darwin backend calls darwin_get_pipe_properties before every submit_bulk_transfer, which on +// IOUSBInterfaceInterface >= 550 amounts to two IOKit user-client calls (GetPipePropertiesV3 + +// GetEndpointPropertiesV3). That is, on macOS every libusb_submit_transfer costs at least 3 IOKit +// round trips, not 1. Conversely, the darwin backend has no length limit and does no +// fragmentation for a single bulk transfer (only the Linux backend has the MAX_BULK_BUFFER_LENGTH +// = 16384 URB splitting). Conclusion: use fewer, larger transfers. #pragma once #include @@ -64,21 +64,22 @@ namespace tetherkitnext::usb { struct DataChannelConfig { /// Number of concurrent in-flight bulk IN transfers. /// - /// 8 x 16 KiB = 128 KiB in flight. The rule of thumb from research is that a "total in flight >= 256 KiB" is needed - /// to keep the controller queue from running dry at USB 2.0 high speed (53.2 MB/s cap) -- at 50 MB/s, - /// a 1 ms gap wastes 50 KB. So the default is 16 x 16 KiB = 256 KiB. + /// 8 x 16 KiB = 128 KiB in flight. The rule of thumb from research is that a "total in flight >= + /// 256 KiB" is needed to keep the controller queue from running dry at USB 2.0 high speed (53.2 + /// MB/s cap); at 50 MB/s, a 1 ms gap wastes 50 KB. So the default is 16 x 16 KiB = 256 KiB. std::uint32_t rx_transfer_count = 16; /// Bytes per bulk IN buffer. /// - /// Must be >= the MaxTransferSize we claim in INITIALIZE_MSG, otherwise the large transfers the device aggregates - /// would overflow / be truncated. At runtime this value is overridden with the negotiation result. + /// Must be >= the MaxTransferSize we claim in INITIALIZE_MSG, otherwise the large transfers the + /// device aggregates would overflow / be truncated. At runtime this value is overridden with the + /// negotiation result. std::uint32_t rx_transfer_bytes = 16 * 1024; /// Number of concurrent in-flight bulk OUT transfers. /// - /// The TX side does not need as many as RX: frames are batched up and sent by us proactively, and 4 are enough to make - /// "assembling the next batch" and "the previous batch in flight" overlap. + /// The TX side does not need as many as RX: frames are batched up and sent by us proactively, and + /// 4 are enough to make "assembling the next batch" and "the previous batch in flight" overlap. std::uint32_t tx_transfer_count = 4; /// Bytes per bulk OUT buffer. Overridden at runtime by the negotiated device MaxTransferSize. @@ -86,37 +87,42 @@ struct DataChannelConfig { /// Timeout of bulk IN (milliseconds). /// - /// **Must be 0 (infinite)**: the RNDIS data channel may be idle for long periods (the user is not transferring data), - /// and with a timeout set it would keep timing out and resubmitting, each resubmit costing 3 IOKit round trips, purely wasteful. - /// darwin passes timeout to IOKit as both noDataTimeout and completionTimeout, - /// and 0 means wait forever. + /// **Must be 0 (infinite)**: the RNDIS data channel may be idle for long periods (the user is not + /// transferring data), and with a timeout set it would keep timing out and resubmitting, each + /// resubmit costing 3 IOKit round trips, purely wasteful. darwin passes timeout to IOKit as both + /// noDataTimeout and completionTimeout, and 0 means wait forever. std::uint32_t rx_timeout_millis = 0; - /// Timeout of bulk OUT (milliseconds). A timeout on TX is reasonable -- we need to notice when the device gets stuck. + /// Timeout of bulk OUT (milliseconds). A timeout on TX is reasonable: we need to notice when the + /// device gets stuck. std::uint32_t tx_timeout_millis = 5'000; }; /// Result of one SendFrames. /// -/// Why not return just a single number: it once returned only "number of frames sent", and as a result two kinds of skipped frames -/// (those exceeding the device's MaxTransferSize, and those shorter than an Ethernet header) were counted as "sent" -- -/// the comment claimed "the caller infers drops from the return value", yet the caller had no way to infer it. -/// Only by separating "how many consumed", "how many actually sent" and "how many skipped" can the books balance. +/// Why not return just a single number: it once returned only "number of frames sent", and as a +/// result two kinds of skipped frames (those exceeding the device's MaxTransferSize, and those +/// shorter than an Ethernet header) were counted as "sent"; the comment claimed "the caller infers +/// drops from the return value", yet the caller had no way to infer it. Only by separating "how +/// many consumed", "how many actually sent" and "how many skipped" can the books balance. struct SendOutcome { - /// The caller should advance its offset by this many frames (including skipped ones). 0 means the transfer pool is full and not a single frame got in. + /// The caller should advance its offset by this many frames (including skipped ones). 0 means the + /// transfer pool is full and not a single frame got in. std::uint32_t consumed = 0; /// Number of frames that actually entered bulk OUT transfers. std::uint32_t sent_frames = 0; /// Total payload bytes of the above frames (excluding RNDIS headers and padding). std::uint64_t sent_bytes = 0; - /// Number of frames skipped for illegal length (oversized / shorter than an Ethernet header). Always equals consumed - sent_frames. + /// Number of frames skipped for illegal length (oversized / shorter than an Ethernet header). + /// Always equals consumed - sent_frames. std::uint32_t skipped = 0; }; /// Abstraction of the data channel. /// -/// The abstraction granularity is the **batch**, not the frame: one virtual call handles dozens to hundreds of frames, and the amortized per-frame overhead is far below -/// 1 ns. This is deliberate -- one virtual call per frame would be unacceptable. +/// The abstraction granularity is the **batch**, not the frame: one virtual call handles dozens to +/// hundreds of frames, and the amortized per-frame overhead is far below 1 ns. This is intentional: +/// one virtual call per frame would be unacceptable. class DataChannel { public: DataChannel() = default; @@ -132,26 +138,31 @@ class DataChannel { [[nodiscard]] virtual Status StartReceiving(FrameRing& rx_ring, DirectionCounters& rx_counters) = 0; - /// Aggregates a batch of Ethernet frames into RNDIS messages and sends them to the device. **Does not block.** + /// Aggregates a batch of Ethernet frames into RNDIS messages and sends them to the device. **Does + /// not block.** /// - /// `consumed < frames.size()` means the transfer pool temporarily has no free slot (backpressure). - /// The caller should keep the remaining frames and use WaitForSendCapacity() to wait for a free slot before retrying -- - /// **do not drop them**: upstream (the kernel BPF buffer) is the elastic queue that should absorb bursts. + /// `consumed < frames.size()` means the transfer pool temporarily has no free slot + /// (backpressure). The caller should keep the remaining frames and use WaitForSendCapacity() to + /// wait for a free slot before retrying; **do not drop them**: the kernel BPF buffer is the + /// elastic queue that absorbs bursts. [[nodiscard]] virtual Result SendFrames(std::span frames) = 0; /// Waits for a free transfer slot to appear in the TX direction. /// - /// Returning true means "worth another SendFrames attempt": a slot has freed up, or the channel has entered - /// shutdown (a retry would then get an error, and the caller will exit by itself). false means the wait timed out with still no capacity. + /// Returning true means "worth another SendFrames attempt": a slot has freed up, or the channel + /// has entered shutdown (a retry would then get an error, and the caller will exit by itself). + /// false means the wait timed out with still no capacity. /// - /// May only be used by the same calling thread as SendFrames (the TX extractor thread). Implementations must guarantee - /// that Shutdown() can wake a waiting thread -- but the caller should not rely on this for shutdown either; - /// it should use a finite timeout and check the shutdown flag itself after each wakeup. + /// May only be used by the same calling thread as SendFrames (the TX extractor thread). + /// Implementations must guarantee that Shutdown() can wake a waiting thread, but the caller + /// should not rely on this for shutdown either; it should use a finite timeout and check the + /// shutdown flag itself after each wakeup. [[nodiscard]] virtual bool WaitForSendCapacity(std::uint32_t timeout_millis) = 0; /// Stops and reclaims all in-flight transfers. /// - /// **Must not be called from the libusb event thread** (it would deadlock; see the explanation in the file header). + /// **Must not be called from the libusb event thread** (it would deadlock; see the explanation in + /// the file header). virtual void Shutdown() = 0; /// Whether TX currently has a free transfer slot available. @@ -160,14 +171,16 @@ class DataChannel { /// Maximum bytes a single transfer can hold (TX direction). [[nodiscard]] virtual std::uint32_t MaxTransferBytes() const noexcept = 0; - /// Number of I/O errors accumulated in the asynchronous send completion callbacks (STALL, transfer failures, etc.). + /// Number of I/O errors accumulated in the asynchronous send completion callbacks (STALL, + /// transfer failures, etc.). /// - /// Why this separate interface exists, rather than having the data channel write directly to the bridge layer's TX counters: - /// the contract of DirectionCounters is "**only one thread** may call Add*" (it uses relaxed - /// load+store rather than fetch_add, which is safe only thanks to a single writer). And the TX direction has two writers -- - /// the submit side is on the TX extractor thread and the error side is on the libusb event thread. Forcing them into the same counter breaks - /// this invariant (TSan would report it too). - /// So it is split into two separately single-writer counts, merged by Bridge::Snapshot() **at read time**. + /// Why this separate interface exists, rather than having the data channel write directly to the + /// bridge layer's TX counters: the contract of DirectionCounters is "**only one thread** may call + /// Add*" (it uses relaxed load+store rather than fetch_add, which is safe only thanks to a single + /// writer). And the TX direction has two writers; the submit side is on the TX extractor thread + /// and the error side is on the libusb event thread. Forcing them into the same counter breaks + /// this invariant (TSan would report it too). So it is split into two separately single-writer + /// counts, merged by Bridge::Snapshot() **at read time**. [[nodiscard]] virtual std::uint64_t AsyncSendErrors() const noexcept = 0; }; @@ -181,7 +194,8 @@ class UsbDataChannel final : public DataChannel { Device& device, const rndis::NegotiatedParameters& parameters, const DataChannelConfig& config); - // Copy and move are already deleted in the base class DataChannel; they are restated explicitly here to satisfy static analysis. + // Copy and move are already deleted in the base class DataChannel; they are restated explicitly + // here to satisfy static analysis. UsbDataChannel(const UsbDataChannel&) = delete; UsbDataChannel& operator=(const UsbDataChannel&) = delete; UsbDataChannel(UsbDataChannel&&) = delete; @@ -204,7 +218,8 @@ class UsbDataChannel final : public DataChannel { return async_send_errors_.load(std::memory_order_relaxed); } - /// Cumulative number of transfers dropped because of malformed RNDIS messages, used to diagnose device bugs. + /// Cumulative number of transfers dropped because of malformed RNDIS messages, used to diagnose + /// device bugs. [[nodiscard]] std::uint64_t MalformedTransfers() const noexcept { return malformed_transfers_.load(std::memory_order_relaxed); } @@ -221,7 +236,7 @@ class UsbDataChannel final : public DataChannel { std::uint32_t index = 0; }; - // ---- libusb callbacks (static trampoline -> member function) ---- + // libusb callbacks (static trampoline -> member function) static void ReceiveCallbackTrampoline(::libusb_transfer* transfer); static void SendCallbackTrampoline(::libusb_transfer* transfer); @@ -229,8 +244,8 @@ class UsbDataChannel final : public DataChannel { void OnSendComplete(Slot& slot) noexcept; /// Allocates a pool. Buffers are page-aligned (darwin has no zero-copy DMA buffers, - /// libusb_dev_mem_alloc returns NULL, so we can only posix_memalign ourselves; aligning to hw.pagesize - /// reduces fragmentation when IOKit builds DMA descriptors). + /// libusb_dev_mem_alloc returns NULL, so we can only posix_memalign ourselves; aligning to + /// hw.pagesize reduces fragmentation when IOKit builds DMA descriptors). [[nodiscard]] Status AllocatePool(std::vector& pool, std::uint32_t count, std::uint32_t buffer_bytes); @@ -250,16 +265,24 @@ class UsbDataChannel final : public DataChannel { /// Index queue of free TX slots. /// - /// Producer = the libusb event thread (the send completion callback returns slots), - /// consumer = the BPF read thread (takes slots to assemble the next batch). Exactly SPSC. + /// Producer = the libusb event thread (the send completion callback returns slots), consumer = + /// the BPF read thread (takes slots to assemble the next batch). Exactly SPSC: the consumer must + /// never push. A slot it took but could not use goes to held_tx_slot_. std::unique_ptr> tx_free_slots_; + /// A free slot the send thread popped but did not submit (nothing to send, or a submit failure). + /// Reused by the next SendFrames before popping again. Touched only by the send thread, so + /// pushing it back into tx_free_slots_ (a second producer) is never needed. + static constexpr std::uint32_t kNoHeldSlot = 0xFFFF'FFFFU; + std::uint32_t held_tx_slot_ = kNoHeldSlot; + /// Receive target. Non-null after StartReceiving. FrameRing* rx_ring_ = nullptr; DirectionCounters* rx_counters_ = nullptr; - /// I/O errors accumulated in the asynchronous send completion callbacks. **Incremented only by the libusb event thread**, - /// kept separate from the bridge layer's TX counters; see the explanation of AsyncSendErrors(). + /// I/O errors accumulated in the asynchronous send completion callbacks. **Incremented only by + /// the libusb event thread**, kept separate from the bridge layer's TX counters; see the + /// explanation of AsyncSendErrors(). std::atomic async_send_errors_{0}; /// In-flight transfer count. Callbacks decrement it; Shutdown waits for it to reach zero. @@ -277,10 +300,13 @@ class UsbDataChannel final : public DataChannel { /// Waiting for a free TX slot. /// - /// The source of truth of the predicate is tx_free_slots_ (a lock-free SPSC ring); this mutex + condition variable pair is only a - /// wakeup mechanism: after the completion callback returns a slot it takes the lock and then notifies (the empty-critical-section idiom), guaranteeing that - /// the waiter either sees the new slot in the predicate check or has already entered wait and receives the notification, so no wakeup is missed. - /// The completion callback is on the libusb event thread, and this lock is held only momentarily, so it does not amount to "callback blocking". + /// The source of truth of the predicate is tx_free_slots_ (a lock-free SPSC ring); this mutex + + /// condition variable pair is only a wakeup mechanism: after the completion callback returns a + /// slot it takes the lock and then notifies (the empty-critical-section idiom), guaranteeing that + /// the waiter either sees the new slot in the predicate check or has already entered wait and + /// receives the notification, so no wakeup is missed. The completion callback is on the libusb + /// event thread, and this lock is held only momentarily, so it does not amount to "callback + /// blocking". std::mutex send_capacity_mutex_; std::condition_variable send_capacity_cv_; }; diff --git a/include/tetherkitnext/usb/device.h b/include/tetherkitnext/usb/device.h index ad2eccf..8cb7b9e 100644 --- a/include/tetherkitnext/usb/device.h +++ b/include/tetherkitnext/usb/device.h @@ -1,9 +1,9 @@ // Discovery, claiming and endpoint resolution of RNDIS USB devices. // -// * Can an RNDIS interface be claimed on macOS? -- Yes, and no root is needed * +// Can an RNDIS interface be claimed on macOS? Yes, and no root is needed: // -// This is this project's most critical feasibility premise; the conclusion comes from checking, one by one, the IOKitPersonalities of all -// CDC-family kexts under /System/Library/Extensions: +// This is this project's most critical feasibility premise; the conclusion comes from checking, +// one by one, the IOKitPersonalities of all CDC-family kexts under /System/Library/Extensions: // // AppleUSBACMControl0 = {class 2, subclass 2, protocol 0} // AppleUSBACMControl1 = {class 2, subclass 2, protocol 1} @@ -11,34 +11,36 @@ // AppleUSBNCMControl = {class 2, subclass 13, protocol *} // AppleUSBWCMControl = {class 2, subclass 8, protocol *} // -// The RNDIS communications-class interface is {class 0x02, subclass 0x02, protocol **0xFF**} -- -// the protocol is neither 0 nor 1, and **no personality matches**. The {0xE0, 0x01, 0x03} variant commonly used by Android does not even have -// a personality for class 0xE0. -// That is to say, **the macOS kernel has no RNDIS driver at all** (which is exactly why third-party -// kexts like HoRNDIS exist, and exactly why this project exists). +// The RNDIS communications-class interface is {class 0x02, subclass 0x02, protocol 0xFF} +// the protocol is neither 0 nor 1, and no personality matches. The {0xE0, 0x01, 0x03} variant +// commonly used by Android does not even have a personality for class 0xE0. That is to say, the +// macOS kernel has no RNDIS driver at all (which is exactly why third-party kexts like HoRNDIS +// exist, and exactly why this project exists). // -// The data-class interface {0x0A, 0x00, 0x00} is indeed probed by AppleUSBECMData0 / AppleUSBACMData0, -// but their start() needs to find a paired Control driver on the same device -// (via bMasterInterface of the CDC Union descriptor); in the RNDIS scenario the communications interface is not taken over by any -// Control driver, so the pairing lookup fails -> start() returns false -> the driver detaches, -// and that interface's IORegistry node ends up with no children, so libusb's -// darwin_kernel_driver_active() returns 0. +// The data-class interface {0x0A, 0x00, 0x00} is indeed probed by AppleUSBECMData0 / +// AppleUSBACMData0, but their start() needs to find a paired Control driver on the same device +// (via bMasterInterface of the CDC Union descriptor); in the RNDIS scenario the communications +// interface is not taken over by any Control driver, so the pairing lookup fails -> start() +// returns false -> the driver detaches, and that interface's IORegistry node ends up with no +// children, so libusb's darwin_kernel_driver_active() returns 0. // // At the device level AppleUSBCDCCompositeDevice attaches (its IOProviderClass is -// IOUSBHostDevice, with a very wide match surface), but it only does ConfigureDevice / publishes interfaces, -// **does not open any interface**, and therefore does not affect USBInterfaceOpen. +// IOUSBHostDevice, with a very wide match surface), but it only does ConfigureDevice / publishes +// interfaces, does not open any interface, and therefore does not affect USBInterfaceOpen. // -// -> Conclusion: an ordinary non-sandboxed command-line program **needs neither root nor an entitlement**; -// libusb_open + libusb_claim_interface will succeed. -// (This project as a whole still needs root, but that is a requirement of feth and BPF, not of libusb.) +// -> Conclusion: an ordinary non-sandboxed command-line program needs neither root nor an +// entitlement; +// libusb_open + libusb_claim_interface will succeed. (This project as a whole still needs root, +// but that is a requirement of feth and BPF, not of libusb.) // -// * Never enable libusb_set_auto_detach_kernel_driver * +// Never enable libusb_set_auto_detach_kernel_driver: // // On macOS it makes claim go through darwin_capture_claim_interface, and once -// darwin_kernel_driver_active is judged true it goes to "detach" -- while darwin's detach -// implementation **re-enumerates the entire device** (USBDeviceReEnumerate + CaptureDeviceMask), -// and needs the com.apple.vm.device-access entitlement or root, otherwise it returns -// LIBUSB_ERROR_ACCESS. In the RNDIS scenario nobody occupies the interface to begin with, so enabling it purely introduces a destructive operation. +// darwin_kernel_driver_active is judged true it goes to "detach", while darwin's detach +// implementation re-enumerates the entire device (USBDeviceReEnumerate + CaptureDeviceMask), and +// needs the com.apple.vm.device-access entitlement or root, otherwise it returns +// LIBUSB_ERROR_ACCESS. In the RNDIS scenario nobody occupies the interface to begin with, so +// enabling it purely introduces a destructive operation. #pragma once #include @@ -68,7 +70,8 @@ struct DeviceCandidate { std::uint8_t control_interface = 0; /// Data-class interface (carries bulk IN/OUT). std::uint8_t data_interface = 0; - /// The matched interface signature, used in logs to explain "which RNDIS form it was recognized as". + /// The matched interface signature, used in logs to explain "which RNDIS form it was recognized + /// as". rndis::InterfaceSignature signature{}; /// Whether the Android quirk fallback path was taken (see the comments of DeviceFinder). bool used_android_quirk = false; @@ -89,25 +92,29 @@ struct DeviceFilter { /// Enumerates the currently connected devices that look like RNDIS. /// /// Recognition logic (the order is the priority): -/// 1. Traverse all interfaces of all configurations, looking for interfaces whose signature hits kControlSignature*; +/// 1. Traverse all interfaces of all configurations, looking for interfaces whose signature hits +/// kControlSignature*; /// 2. Exclude fake RNDIS: those with class == 0x02 and a non-zero CDC ACM bmCapabilities are real -/// cdc-acm modems, not RNDIS. **This check only applies to class 0x02** -- -/// RNDIS functions of the wireless class (0xE0) repurpose bmCapabilities for their own use. -/// 3. Find the paired data interface: prefer reading bSlaveInterface of the CDC Union functional descriptor; +/// cdc-acm modems, not RNDIS. **This check only applies to class 0x02**; RNDIS functions of +/// the wireless class (0xE0) repurpose bmCapabilities for their own use. +/// 3. Find the paired data interface: prefer reading bSlaveInterface of the CDC Union functional +/// descriptor; /// 4. **Android quirk**: on many Android devices the CDC Union descriptor points to a nonexistent -/// interface number, or the CDC functional descriptors are missing entirely. In that case fall back to the hardcoded assumption "communications interface = 0, -/// data interface = 1" (which is what Linux's android_rndis_quirk does), -/// and require that the communications interface really is 0. +/// interface number, or the CDC functional descriptors are missing entirely. In that case fall +/// back to the hardcoded assumption "communications interface = 0, data interface = 1" (which +/// is what Linux's android_rndis_quirk does), and require that the communications interface +/// really is 0. [[nodiscard]] Result> FindRndisDevices(const Context& context, const DeviceFilter& filter = {}); /// An RNDIS device that has been opened with its interfaces claimed. /// -/// RAII: on destruction it is torn down in the order "release interfaces -> close handle". -/// **The caller must guarantee that all asynchronous transfers have been fully reclaimed before this object is destroyed** -- -/// libusb_close will not reclaim in-flight transfers for you (it only nulls transfer->dev_handle -/// and prints a usbi_err), after which IOKit aborts will still make callbacks run on libusb's internal thread, -/// and if the transfer has been freed by then it is a use-after-free. See the teardown algorithm of TransferPool. +/// RAII: on destruction it is torn down in the order "release interfaces -> close handle". **The +/// caller must guarantee that all asynchronous transfers have been fully reclaimed before this +/// object is destroyed**; libusb_close will not reclaim in-flight transfers for you (it only nulls +/// transfer->dev_handle and prints a usbi_err), after which IOKit aborts will still make callbacks +/// run on libusb's internal thread, and if the transfer has been freed by then it is a +/// use-after-free. See the teardown algorithm of TransferPool. class Device { public: /// Opens the device and claims the two interfaces. @@ -137,15 +144,17 @@ class Device { /// Address of the bulk OUT endpoint (host -> device). [[nodiscard]] std::uint8_t BulkOutEndpoint() const noexcept { return bulk_out_endpoint_; } - /// Address of the interrupt IN endpoint; 0 means the device has no interrupt endpoint (legal; must fall back to polling). + /// Address of the interrupt IN endpoint; 0 means the device has no interrupt endpoint (legal; + /// must fall back to polling). [[nodiscard]] std::uint8_t InterruptInEndpoint() const noexcept { return interrupt_in_endpoint_; } /// wMaxPacketSize of the bulk endpoints. /// - /// Used in two places: (1) deriving the MaxTransferSize to claim in INITIALIZE_MSG; - /// (2) judging whether the bulk OUT transfer length is exactly an integer multiple of it, to decide whether to pad 1 byte to avoid a ZLP. + /// Used in two places: (1) deriving the MaxTransferSize to claim in INITIALIZE_MSG; (2) judging + /// whether the bulk OUT transfer length is exactly an integer multiple of it, to decide whether + /// to pad 1 byte to avoid a ZLP. [[nodiscard]] std::uint16_t BulkMaxPacketSize() const noexcept { return bulk_max_packet_size_; } /// wMaxPacketSize of the interrupt endpoint (RNDIS notifications are fixed at 8 bytes). @@ -153,17 +162,15 @@ class Device { return interrupt_max_packet_size_; } - /// The device's USB speed, used for logs and throughput expectations. - [[nodiscard]] int Speed() const noexcept { return speed_; } - + /// The device's USB speed ("high-speed", ...), used for logs and throughput expectations. [[nodiscard]] std::string_view SpeedName() const noexcept; /// Clears the halt state of an endpoint. /// - /// STALL recovery can be called directly inside a transfer callback: libusb_clear_halt goes through - /// darwin_clear_halt -> ClearPipeStallBothEnds, which is one synchronous IOKit call, - /// bypassing the event loop, with no usbi_handling_events guard. The cost is that it blocks the event thread - /// for tens of microseconds to milliseconds, so call it only on a real STALL. + /// STALL recovery can be called directly inside a transfer callback: libusb_clear_halt goes + /// through darwin_clear_halt -> ClearPipeStallBothEnds, which is one synchronous IOKit call, + /// bypassing the event loop, with no usbi_handling_events guard. The cost is that it blocks the + /// event thread for tens of microseconds to milliseconds, so call it only on a real STALL. [[nodiscard]] Status ClearHalt(std::uint8_t endpoint); private: @@ -189,31 +196,32 @@ class Device { /// Control channel implementation based on libusb. /// -/// **Must be used from a dedicated thread that is not a libusb event thread** -- the synchronous API -/// (libusb_control_transfer) returns LIBUSB_ERROR_BUSY on the event thread -/// (usbi_handling_events is a TLS check). +/// Must be used from a dedicated thread that is not a libusb event thread; the synchronous API +/// (libusb_control_transfer) returns LIBUSB_ERROR_BUSY on the event thread (usbi_handling_events is +/// a TLS check). /// -/// * Interrupt notifications go through an **asynchronous** transfer; this is not an optimization but a necessity * +/// * Interrupt notifications go through an asynchronous transfer; this is not an optimization +/// but a necessity * /// -/// If WaitForNotification were changed to use the synchronous libusb_interrupt_transfer, -/// **the control thread would hang forever**, with the stack: +/// If WaitForNotification were changed to use the synchronous libusb_interrupt_transfer, the +/// control thread would hang forever, with the stack: /// Poll → WaitForNotification → do_sync_bulk_transfer /// → sync_transfer_wait_for_completion → handle_events → poll(∞) /// /// Causal chain: -/// 1. The darwin backend marks all transfers with USBI_TRANSFER_OS_HANDLES_TIMEOUT, -/// meaning "timeouts are handled by IOKit; libusb does not time them itself"; so -/// libusb_get_next_timeout skips them and returns "no timeout", -/// and the poll() in sync_transfer_wait_for_completion blocks indefinitely; -/// 2. And on the IOKit side, darwin's submit_interrupt_transfer uses -/// **ReadPipeAsync (the no-timeout variant)**, not the ReadPipeAsyncTO used by bulk -- -/// **the timeout parameter of interrupt transfers is not honored at all**; +/// 1. The darwin backend marks all transfers with USBI_TRANSFER_OS_HANDLES_TIMEOUT, meaning +/// "timeouts are handled by IOKit; libusb does not time them itself"; so +/// libusb_get_next_timeout skips them and returns "no timeout", and the poll() in +/// sync_transfer_wait_for_completion blocks indefinitely; +/// 2. And on the IOKit side, darwin's submit_interrupt_transfer uses ReadPipeAsync (the +/// no-timeout variant), not the ReadPipeAsyncTO used by bulk; the timeout parameter of +/// interrupt transfers is not honored at all; /// 3. So when there is no data on the endpoint, this synchronous transfer never completes. /// -/// Changing timeout from 0 to 1 ms is **useless** (point 2 decides that it has no effect on interrupt endpoints). -/// The only correct solution is: -/// submit a resident **asynchronous** interrupt transfer and let it complete on the libusb event thread, -/// with WaitForNotification only checking an atomic flag, never entering libusb's wait path. +/// Changing timeout from 0 to 1 ms is useless (point 2 decides that it has no effect on interrupt +/// endpoints). The only correct solution is: submit a resident asynchronous interrupt transfer +/// and let it complete on the libusb event thread, with WaitForNotification only checking an +/// atomic flag, never entering libusb's wait path. class UsbControlChannel final : public rndis::ControlChannel { public: UsbControlChannel(Device& device, std::uint32_t timeout_millis); @@ -225,10 +233,12 @@ class UsbControlChannel final : public rndis::ControlChannel { ~UsbControlChannel() override; - /// Submits the resident asynchronous interrupt transfer. A no-op when the device has no interrupt endpoint. + /// Submits the resident asynchronous interrupt transfer. A no-op when the device has no interrupt + /// endpoint. [[nodiscard]] Status StartNotificationListener(); - /// Cancels the interrupt transfer and waits for the callback to finish reclaiming. **Must not be called from the libusb event thread.** + /// Cancels the interrupt transfer and waits for the callback to finish reclaiming. **Must not be + /// called from the libusb event thread.** void StopNotificationListener(); [[nodiscard]] Status SendMessage(std::span message) override; @@ -255,9 +265,11 @@ class UsbControlChannel final : public rndis::ControlChannel { /// The resident asynchronous interrupt transfer. ::libusb_transfer* notification_transfer_ = nullptr; - /// Whether the device has signaled that "a response can be fetched". Set by the event thread, consumed by the control thread. + /// Whether the device has signaled that "a response can be fetched". Set by the event thread, + /// consumed by the control thread. std::atomic notification_pending_{false}; - /// Whether an interrupt transfer is in flight. Used to wait for the callback to finish reclaiming at shutdown (avoiding use-after-free). + /// Whether an interrupt transfer is in flight. Used to wait for the callback to finish reclaiming + /// at shutdown (avoiding use-after-free). std::atomic notification_in_flight_{false}; std::atomic notification_stopping_{false}; }; diff --git a/include/tetherkitnext/version.h b/include/tetherkitnext/version.h index 3cedae4..68c92ff 100644 --- a/include/tetherkitnext/version.h +++ b/include/tetherkitnext/version.h @@ -1,7 +1,8 @@ // TetherKitNext version information. // -// The version number is injected into version.cc by CMake at configure time; the header only exposes accessor functions, -// avoiding a full-project rebuild every time the version number changes. +// The version number is injected into version.cc by CMake at configure time; the header only +// exposes accessor functions, avoiding a full-project rebuild every time the version number +// changes. #pragma once #include @@ -22,10 +23,11 @@ Version GetVersion() noexcept; /// Returns a readable version string like "TetherKitNext 0.1.0 (C++23, macOS 13.3+)". std::string_view GetVersionString() noexcept; -/// Returns a description of the build configuration, like -/// "RelWithDebInfo, AppleClang 21.0.0, C++23, LTO=off, sanitizers=none". +/// Returns a description of the build configuration, like "RelWithDebInfo, AppleClang 21.0.0, +/// C++23, LTO=off, sanitizers=none". /// -/// Performance benchmark reports must include it -- an ns/op number detached from the build configuration is meaningless. +/// Performance benchmark reports must include it: an ns/op number detached from the build +/// configuration is meaningless. std::string_view GetBuildDescription() noexcept; } // namespace tetherkitnext diff --git a/scripts/build-libusb.sh b/scripts/build-libusb.sh index d334507..9b633f4 100755 --- a/scripts/build-libusb.sh +++ b/scripts/build-libusb.sh @@ -2,7 +2,7 @@ # # Build a universal (arm64 + x86_64) libusb dylib from a pinned, hash-verified # release tarball, so TetherKitNext.app ships its own copy instead of depending on -# Homebrew (which no longer supports Intel Macs, upstream issue #2). +# Homebrew (which does not support Intel Macs). # # ./scripts/build-libusb.sh [PREFIX] # default PREFIX: build/libusb-universal # @@ -46,7 +46,9 @@ mkdir -p "${WORK}" "${PREFIX}/lib" "${PREFIX}/include" log "Downloading libusb ${LIBUSB_VERSION}" tarball="${WORK}/libusb.tar.bz2" -curl -fsSL --retry 4 -o "${tarball}" "${LIBUSB_URL}" +# --retry alone skips non-standard statuses (GitHub's download CDN has +# answered 618); retrying everything is safe because the hash is checked below. +curl -fsSL --retry 5 --retry-all-errors --retry-delay 5 -o "${tarball}" "${LIBUSB_URL}" actual="$(shasum -a 256 "${tarball}" | awk '{print $1}')" [[ "${actual}" == "${LIBUSB_SHA256}" ]] \ || die "sha256 mismatch for libusb tarball: got ${actual}, expected ${LIBUSB_SHA256}" diff --git a/scripts/check-comment-only.py b/scripts/check-comment-only.py new file mode 100755 index 0000000..9965622 --- /dev/null +++ b/scripts/check-comment-only.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Check that a change touches comments only (AGENTS.md section 11). + +Usage: scripts/check-comment-only.py [BASE] (default BASE: HEAD, i.e. uncommitted changes) + scripts/check-comment-only.py origin/main (everything the branch changed) + +Fails if any changed source file differs from BASE in anything but comments. +Use it after a comment or documentation cleanup, before pushing. + +C-family (.h .hh .cc .cpp .c .swift .m .mm): removes // and /* */ outside +string/char literals (Swift: also handles triple-quoted strings and nested +block comments). Shell/YAML/Python/CMake: removes whole-line '#' comments and +trailing ' # ...' comments when the '#' is outside quotes. Whitespace is +normalized before comparing. +""" +import re +import subprocess +import sys + +C_EXT = ('.h', '.hh', '.hpp', '.cc', '.cpp', '.c', '.swift', '.m', '.mm', '.def') +HASH_EXT = ('.sh', '.yml', '.yaml', '.py', '.cmake', '.txt', '.in') + + +def strip_c(src: str, swift: bool) -> str: + out = [] + i, n = 0, len(src) + while i < n: + c = src[i] + two = src[i:i + 2] + if swift and src.startswith('"""', i): + j = src.find('"""', i + 3) + j = n if j < 0 else j + 3 + out.append(src[i:j]); i = j; continue + # C++14 digit separator (0x4001'000BU): not a character literal. + if (c == "'" and not swift and i > 0 and src[i - 1].isalnum() + and i + 1 < n and src[i + 1].isalnum()): + out.append(c); i += 1; continue + if c == '"' or (c == "'" and not swift): + q = c; j = i + 1 + while j < n and src[j] != q: + if src[j] == '\\': + j += 1 + if src[j:j + 1] == '\n': + break + j += 1 + out.append(src[i:j + 1]); i = j + 1; continue + if not swift and src.startswith('R"', i): + m = re.match(r'R"([^(\s]*)\(', src[i:]) + if m: + end = ')' + m.group(1) + '"' + j = src.find(end, i) + j = n if j < 0 else j + len(end) + out.append(src[i:j]); i = j; continue + if two == '//': + j = src.find('\n', i) + i = n if j < 0 else j + out.append(' '); continue + if two == '/*': + depth, j = 1, i + 2 + while j < n and depth: + if swift and src.startswith('/*', j): + depth += 1; j += 2; continue + if src.startswith('*/', j): + depth -= 1; j += 2; continue + j += 1 + out.append(' '); i = j; continue + out.append(c); i += 1 + return ''.join(out) + + +def strip_hash(src: str) -> str: + lines = [] + for line in src.splitlines(): + s = line.lstrip() + if s.startswith('#') and not s.startswith('#!'): + continue + # trailing comment: ' #' outside quotes + q = None + cut = None + for k, ch in enumerate(line): + if q: + if ch == q: + q = None + elif ch in '"\'': + q = ch + elif ch == '#' and k > 0 and line[k - 1] in ' \t': + cut = k + break + lines.append(line[:cut] if cut is not None else line) + return '\n'.join(lines) + + +def norm(s: str) -> str: + return re.sub(r'\s+', ' ', s).strip() + + +def main() -> int: + base = sys.argv[1] if len(sys.argv) > 1 else 'HEAD' + files = subprocess.run(['git', 'diff', '--name-only', base, '--diff-filter=M'], + capture_output=True, text=True, check=True).stdout.split() + bad = 0 + checked = 0 + for f in files: + if f.endswith('.md'): + continue + try: + old = subprocess.run(['git', 'show', f'{base}:{f}'], capture_output=True, + text=True, check=True).stdout + except subprocess.CalledProcessError: + continue + new = open(f, encoding='utf-8').read() + if f.endswith(C_EXT): + a, b = strip_c(old, f.endswith('.swift')), strip_c(new, f.endswith('.swift')) + elif f.endswith(HASH_EXT) or 'CMakeLists' in f: + a, b = strip_hash(old), strip_hash(new) + else: + print(f'SKIP (unknown type) {f}') + continue + checked += 1 + if norm(a) != norm(b): + bad += 1 + na, nb = norm(a), norm(b) + k = next((i for i in range(min(len(na), len(nb))) if na[i] != nb[i]), min(len(na), len(nb))) + print(f'CODE CHANGED: {f}\n old: ...{na[max(0,k-60):k+80]}\n new: ...{nb[max(0,k-60):k+80]}') + print(f'checked {checked} files, {bad} with non-comment changes') + return 1 if bad else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/make-appcast.py b/scripts/make-appcast.py new file mode 100755 index 0000000..11c20ef --- /dev/null +++ b/scripts/make-appcast.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Write the Sparkle appcast (update feed) for one release to stdout. + +Used by .github/workflows/release.yml. The feed holds only the newest stable +release: it is served as releases/latest/download/appcast.xml, so every +release replaces it, and Sparkle only needs the newest item. + +Versions come from the built app, never from the tag, so the feed always +describes exactly what was signed: + sparkle:version CFBundleVersion (the release workflow's run number; + Sparkle compares this and it only ever grows) + sparkle:shortVersionString CFBundleShortVersionString (shown to the user) + sparkle:minimumSystemVersion LSMinimumSystemVersion +""" + +import argparse +import email.utils +import os +import plistlib +import sys +from xml.sax.saxutils import escape, quoteattr + +SPARKLE_NS = "http://www.andymatuschak.org/xml-namespaces/sparkle" + + +def cdata(text: str) -> str: + # "]]>" cannot appear inside CDATA; split it across two sections. + return "", "]]]]>") + "]]>" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--app", required=True, help="built TetherKitNext.app") + parser.add_argument("--dmg", required=True, help="the signed, notarized DMG") + parser.add_argument("--signature", required=True, help="sign_update -p output") + parser.add_argument("--notes", required=True, help="release notes (Markdown)") + parser.add_argument("--download-url", required=True) + parser.add_argument("--release-url", required=True) + args = parser.parse_args() + + with open(os.path.join(args.app, "Contents", "Info.plist"), "rb") as handle: + info = plistlib.load(handle) + build = str(info["CFBundleVersion"]) + version = str(info["CFBundleShortVersionString"]) + minimum = str(info.get("LSMinimumSystemVersion", "14.0")) + if not build.isdigit(): + print(f"error: CFBundleVersion {build!r} is not a build number", file=sys.stderr) + return 1 + for url in (args.download_url, args.release_url): + if not url.startswith("https://"): + print(f"error: {url} is not https", file=sys.stderr) + return 1 + + with open(args.notes, encoding="utf-8") as handle: + notes = handle.read().strip() + length = os.path.getsize(args.dmg) + published = email.utils.formatdate(usegmt=True) + title = escape(f"TetherKitNext {version}") + + sys.stdout.write(f""" + + + TetherKitNext + {escape(args.release_url)} + en + + {title} + {published} + {escape(build)} + {escape(version)} + {escape(minimum)} + {escape(args.release_url)} + {cdata(notes)} + + + + +""") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/make-dmg.sh b/scripts/make-dmg.sh index bf09c3b..7d3b7d8 100755 --- a/scripts/make-dmg.sh +++ b/scripts/make-dmg.sh @@ -7,16 +7,16 @@ # # Environment: # TETHERKITNEXT_SIGN_IDENTITY Developer ID Application identity. Signs the DMG. -# The app must already be signed with it -# (gui/Scripts/build-gui.sh does that). +# The app must already be signed with it (gui/Scripts/build-gui.sh does +# that). # Notarization — either an App Store Connect API key (recommended for CI): # NOTARY_KEY_PATH path to AuthKey_XXXX.p8 # NOTARY_KEY_ID key ID # NOTARY_ISSUER_ID issuer UUID # …or an Apple ID with an app-specific password: # NOTARY_APPLE_ID, NOTARY_PASSWORD, NOTARY_TEAM_ID -# With neither set, notarization is skipped (the DMG still works, but -# Gatekeeper will block the app on other Macs). +# With neither set, notarization is skipped (the DMG still works, but Gatekeeper will block the +# app on other Macs). # # Order matters: the app is notarized and stapled *before* it goes into the # DMG, so the ticket travels with the app after the user copies it out and @@ -73,17 +73,17 @@ else log "Notarization credentials not set; skipping notarization" fi -# ★ Install window layout ★ +# Install window layout # # Finder itself lays the window out (background, icon positions, window size, # no toolbar) through AppleScript on a temporary read-write image, the way # create-dmg and most hand-made DMGs do it. The .DS_Store is then written by # the same Finder that will read it. # -# We used dmgbuild, which writes .DS_Store directly, before: its background -# picture does not show on macOS 15 or 26 (CI screenshots: layout applied, -# background blank), while the Finder-written one does. The dmg-look CI job -# screenshots every build so a regression is visible. +# dmgbuild is not used: it writes .DS_Store directly, and its background +# picture does not show on macOS 15 or 26, while the Finder-written one does +# (AGENTS.md pitfall 26). The dmg-look CI job ("DMG window") screenshots every +# build so a regression is visible. # # Needs a logged-in GUI session (Finder); GitHub's macOS runners have one. # The first local run asks once to let Terminal control Finder. Without @@ -120,11 +120,11 @@ mnt="$(hdiutil attach -readwrite -noverify -noautoopen "${rw}" \ [[ "${mnt}" == "/Volumes/${VOLNAME}" ]] || die "unexpected mount point: ${mnt}" # Custom volume icon. Copied onto the mounted volume rather than staged: -# `hdiutil create -srcfolder` leaves .VolumeIcon.icns out of the image (the -# built image had no icon file at all). The file alone is not enough; the volume root also needs the -# "has custom icon" Finder flag (kHasCustomIcon, 0x0400 in the Finder flags at -# byte 8 of FinderInfo). Written directly because SetFile is no longer on the -# PATH of current Xcode installs. +# `hdiutil create -srcfolder` leaves .VolumeIcon.icns out of the image. The +# file alone is not enough; the volume root also needs the "has custom icon" +# Finder flag (kHasCustomIcon, 0x0400 in the Finder flags at byte 8 of +# FinderInfo). Written directly because SetFile is not on the PATH of current +# Xcode installs. set_volume_icon() { cp "${APP}/Contents/Resources/AppIcon.icns" "${mnt}/.VolumeIcon.icns" xattr -wx com.apple.FinderInfo \ @@ -176,7 +176,7 @@ hdiutil detach -quiet "${mnt}" || { sleep 3; hdiutil detach -quiet -force "${mnt mnt="" hdiutil convert -quiet "${rw}" -format UDZO -imagekey zlib-level=9 -o "${DMG}" -# Check the finished image, since the icon has gone missing here before. +# Check the finished image: the volume icon is easy to lose in the conversion. check="$(hdiutil attach -readonly -nobrowse -noverify -noautoopen -mountrandom "${work}" "${DMG}" \ | awk -F'\t' '/Apple_HFS/ {print $NF}' | sed 's/[[:space:]]*$//')" if [[ -n "${check}" && -f "${check}/.VolumeIcon.icns" ]]; then diff --git a/scripts/verify-sparkle-signature.swift b/scripts/verify-sparkle-signature.swift new file mode 100644 index 0000000..4969e05 --- /dev/null +++ b/scripts/verify-sparkle-signature.swift @@ -0,0 +1,43 @@ +// Verifies a Sparkle EdDSA (Ed25519) signature with the public key a built app +// carries, the same check the installed app performs before installing. +// +// Usage: swift scripts/verify-sparkle-signature.swift +// +// Why: sign_update signs with the private key from the CI secret, while the app +// embeds the public key from a repository variable. If the two ever stop being +// a pair, every user's update would be rejected as "improperly signed", and +// the only way out would be a manual download. The release job runs this +// before publishing so a mismatch fails the release instead. +import CryptoKit +import Foundation + +func fail(_ message: String) -> Never { + FileHandle.standardError.write(Data("error: \(message)\n".utf8)) + exit(1) +} + +let arguments = CommandLine.arguments +guard arguments.count == 4 else { + fail("usage: verify-sparkle-signature.swift ") +} + +let infoURL = URL(fileURLWithPath: arguments[1]).appendingPathComponent("Contents/Info.plist") +guard let info = NSDictionary(contentsOf: infoURL), + let publicKeyText = info["SUPublicEDKey"] as? String else { + fail("\(infoURL.path) has no SUPublicEDKey") +} +guard let publicKeyData = Data(base64Encoded: publicKeyText), + let publicKey = try? Curve25519.Signing.PublicKey(rawRepresentation: publicKeyData) else { + fail("SUPublicEDKey is not a base64 Ed25519 public key") +} +guard let signature = Data(base64Encoded: arguments[3]) else { + fail("the signature is not base64") +} +guard let payload = FileManager.default.contents(atPath: arguments[2]) else { + fail("cannot read \(arguments[2])") +} +guard publicKey.isValidSignature(signature, for: payload) else { + fail("the signature does not verify with the app's SUPublicEDKey: " + + "SPARKLE_ED_PRIVATE_KEY and SPARKLE_ED_PUBLIC_KEY are not a pair") +} +print("✓ update signature verifies with the app's public key") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8f600f3..348d80c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,4 +1,4 @@ -# src -- feature modules +# src: feature modules # # The dependency direction is strictly one-way; reverse or circular dependencies are forbidden: # diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index e504066..195c188 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -1,7 +1,7 @@ -# app -- command-line executable tetherkitnext-cli +# app: command-line executable tetherkitnext-cli # -# The CMake target name is tetherkitnext, and the **output file name** is tetherkitnext-cli (the same as -# Contents/MacOS/tetherkitnext-cli in the App bundle and the link under /usr/local/bin). +# The CMake target name is tetherkitnext, and the **output file name** is tetherkitnext-cli (the +# same as Contents/MacOS/tetherkitnext-cli in the App bundle and the link under /usr/local/bin). add_executable(tetherkitnext main.cc) set_target_properties(tetherkitnext PROPERTIES OUTPUT_NAME tetherkitnext-cli) diff --git a/src/app/main.cc b/src/app/main.cc index e2074dd..581de63 100644 --- a/src/app/main.cc +++ b/src/app/main.cc @@ -1,7 +1,8 @@ // TetherKitNext command-line entry point. // -// Responsibilities are deliberately kept thin: parse arguments -> assemble RuntimeConfig -> hand to core::Runtime -> -// handle signals. All substantive logic is in the library, so that it can be covered by unit tests. +// Responsibilities are kept thin: parse arguments -> assemble RuntimeConfig -> hand to +// core::Runtime -> handle signals. All substantive logic is in the library, so that it can be +// covered by unit tests. #include // NOLINT(modernize-deprecated-headers) -- sigaction is only in this header #include @@ -33,11 +34,12 @@ using tetherkitnext::Tr; /// Global shutdown flag. /// -/// Process-level signal state is inherently global and unavoidable; after using a lock-free atomic to guarantee safety, it is not wrapped further. +/// Process-level signal state is inherently global and unavoidable; after using a lock-free atomic +/// to guarantee safety, it is not wrapped further. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) /// **In a signal handler only volatile sig_atomic_t or lock-free atomics may be touched**; locking, -/// allocating memory or logging must never be done -- none of those are async-signal-safe. Here only one atomic is written, -/// and the real shutdown is performed by the main thread after it sees it. +/// allocating memory or logging must never be done; none of those are async-signal-safe. Here only +/// one atomic is written, and the real shutdown is performed by the main thread after it sees it. std::atomic g_stop_requested{false}; extern "C" void HandleSignal(int /*signal_number*/) { @@ -51,10 +53,10 @@ extern "C" void HandleSignal(int /*signal_number*/) { [[nodiscard]] Status InstallSignalHandlers() { struct sigaction action{}; action.sa_handler = &HandleSignal; - // Note: on macOS sigemptyset is a **macro** (#define sigemptyset(set) (*(set)=0,0)), - // so it cannot be written as ::sigemptyset -- a macro name cannot be scope-qualified. + // Note: on macOS sigemptyset is a **macro** (#define sigemptyset(set) (*(set)=0,0)), so it cannot + // be written as ::sigemptyset; a macro name cannot be scope-qualified. sigemptyset(&action.sa_mask); - // Deliberately **not setting** SA_RESTART: we want signals to interrupt blocking system calls (such as BPF's + // **Not setting** SA_RESTART: we want signals to interrupt blocking system calls (such as BPF's // read()), giving threads a chance to see the shutdown flag. action.sa_flags = 0; @@ -65,7 +67,8 @@ extern "C" void HandleSignal(int /*signal_number*/) { } } - // Ignore SIGPIPE: writing to a closed BPF descriptor triggers it, and the default behavior is to terminate the process. + // Ignore SIGPIPE: writing to a closed BPF descriptor triggers it, and the default behavior is to + // terminate the process. struct sigaction ignore{}; ignore.sa_handler = SIG_IGN; sigemptyset(&ignore.sa_mask); @@ -81,8 +84,9 @@ extern "C" void HandleSignal(int /*signal_number*/) { /// Writes a message without arguments to stdout as-is. /// -/// fwrite is used instead of fputs: the string_view returned by `Text()` points to a literal in the table, -/// which in practice does carry a NUL, but string_view's contract does not include that; do not form bad habits. +/// fwrite is used instead of fputs: the string_view returned by `Text()` points to a literal in the +/// table, which in practice does carry a NUL, but string_view's contract does not include that; do +/// not form bad habits. void PrintText(Msg id) { const std::string_view text = Text(id); std::fwrite(text.data(), 1, text.size(), stdout); @@ -94,14 +98,15 @@ void PrintUsage() { /// Picks out `--lang` and makes it take effect **before** the arguments are formally parsed. /// -/// Why scan separately: the help text, and the errors produced during parsing itself, must all use the language the user wants. -/// By the time ParseArguments reaches `--lang` in order, the error messages of the earlier options -/// have already been emitted in the old language. +/// Why scan separately: the help text, and the errors produced during parsing itself, must all use +/// the language the user wants. By the time ParseArguments reaches `--lang` in order, the error +/// messages of the earlier options have already been emitted in the old language. /// -/// Only the `--lang ` form is recognized (none of the project's options support `--opt=value`, and no exception is made -/// here, otherwise ParseArguments would treat `--lang=en` as an unknown option, which is more confusing). -/// When the value is illegal no error is reported here, leaving it to ParseArguments to report -- by then the error itself is already in -/// the language the user wants. +/// Only the `--lang ` form is recognized (none of the project's options support +/// `--opt=value`, and no exception is made here, otherwise ParseArguments would treat `--lang=en` +/// as an unknown option, which is more confusing). When the value is illegal no error is reported +/// here, leaving it to ParseArguments to report; by then the error itself is already in the +/// language the user wants. void ApplyLanguageOption(int argc, char** argv) { for (int i = 1; i + 1 < argc; ++i) { if (std::string_view{argv[i]} != "--lang") { @@ -126,6 +131,24 @@ void ApplyLanguageOption(int argc, char** argv) { return value; } +/// A number no larger than `maximum`. Silently truncating would act on the wrong value (e.g. `--vid +/// 10002` as 0x0002, or a KiB size that wraps to a tiny buffer). +[[nodiscard]] Result ParseBoundedUint(std::string_view text, std::uint32_t maximum, + int base = 10) { + TETHERKITNEXT_ASSIGN_OR_RETURN(const auto value, ParseUint(text, base)); + if (value > maximum) { + return std::unexpected(Error::Generic(Tr(Msg::kCliParseNumberFailed, text))); + } + return value; +} + +/// A size in KiB, returned in bytes. +[[nodiscard]] Result ParseKilobytes(std::string_view text) { + constexpr std::uint32_t kMaxKilobytes = 0xFFFF'FFFFU / 1024; + TETHERKITNEXT_ASSIGN_OR_RETURN(const auto kilobytes, ParseBoundedUint(text, kMaxKilobytes)); + return kilobytes * 1024; +} + [[nodiscard]] Result ParseLogLevel(std::string_view text) { if (text == "trace") { return LogLevel::kTrace; @@ -195,13 +218,13 @@ struct ParsedArguments { if (argument == "--vid") { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto text, take_value(i, argument)); - TETHERKITNEXT_ASSIGN_OR_RETURN(const auto value, ParseUint(text, 16)); + TETHERKITNEXT_ASSIGN_OR_RETURN(const auto value, ParseBoundedUint(text, 0xFFFF, 16)); parsed.config.device_filter.vendor_id = static_cast(value); continue; } if (argument == "--pid") { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto text, take_value(i, argument)); - TETHERKITNEXT_ASSIGN_OR_RETURN(const auto value, ParseUint(text, 16)); + TETHERKITNEXT_ASSIGN_OR_RETURN(const auto value, ParseBoundedUint(text, 0xFFFF, 16)); parsed.config.device_filter.product_id = static_cast(value); continue; } @@ -222,14 +245,14 @@ struct ParsedArguments { } if (argument == "--rx-transfer-kb") { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto text, take_value(i, argument)); - TETHERKITNEXT_ASSIGN_OR_RETURN(const auto kilobytes, ParseUint(text)); - parsed.config.data_channel.rx_transfer_bytes = kilobytes * 1024; + TETHERKITNEXT_ASSIGN_OR_RETURN(parsed.config.data_channel.rx_transfer_bytes, + ParseKilobytes(text)); continue; } if (argument == "--max-transfer-kb") { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto text, take_value(i, argument)); - TETHERKITNEXT_ASSIGN_OR_RETURN(const auto kilobytes, ParseUint(text)); - parsed.config.rndis.host_max_transfer_size = kilobytes * 1024; + TETHERKITNEXT_ASSIGN_OR_RETURN(parsed.config.rndis.host_max_transfer_size, + ParseKilobytes(text)); continue; } if (argument == "--max-tx-packets") { @@ -239,8 +262,7 @@ struct ParsedArguments { } if (argument == "--bpf-buffer-kb") { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto text, take_value(i, argument)); - TETHERKITNEXT_ASSIGN_OR_RETURN(const auto kilobytes, ParseUint(text)); - parsed.config.bpf.kernel_buffer_bytes = kilobytes * 1024; + TETHERKITNEXT_ASSIGN_OR_RETURN(parsed.config.bpf.kernel_buffer_bytes, ParseKilobytes(text)); continue; } if (argument == "--stats") { @@ -255,8 +277,9 @@ struct ParsedArguments { continue; } if (argument == "--lang") { - // The value has already taken effect before parsing began via ApplyLanguageOption (so even this round's error messages - // are in the target language). Here we only consume it and re-check the spelling. + // The value has already taken effect before parsing began via ApplyLanguageOption (so even + // this round's error messages are in the target language). Here we only consume it and + // re-check the spelling. TETHERKITNEXT_ASSIGN_OR_RETURN(const auto text, take_value(i, argument)); Language ignored{}; if (!tetherkitnext::ParseLanguage(text, &ignored)) { @@ -297,8 +320,9 @@ struct ParsedArguments { } // namespace int main(int argc, char** argv) { - // The language must be settled before **any** output. Infer from the environment first, then let an explicit --lang override -- - // so that even the errors reported by argument parsing itself are in the language the user wants. + // The language must be settled before **any** output. Infer from the environment first, then let + // an explicit --lang override, so that even the errors reported by argument parsing itself are in + // the language the user wants. tetherkitnext::SetLanguage(tetherkitnext::DetectLanguageFromEnvironment()); ApplyLanguageOption(argc, argv); @@ -347,9 +371,10 @@ int main(int argc, char** argv) { return 1; } - // A signal handler can only set an atomic (the only async-signal-safe approach), so someone needs to relay it - // to the runtime. A lightweight watcher thread is used rather than having Runtime read a process-level global directly -- - // this way Runtime depends on no global state, which makes testing easier. + // A signal handler can only set an atomic (the only async-signal-safe approach), so someone needs + // to relay it to the runtime. A lightweight watcher thread is used rather than having Runtime + // read a process-level global directly; this way Runtime depends on no global state, which makes + // testing easier. std::thread signal_watcher([&runtime] { while (!g_stop_requested.load(std::memory_order_acquire)) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); @@ -358,19 +383,20 @@ int main(int argc, char** argv) { (*runtime)->RequestStop(); }); - // The control loop runs on Runtime's own thread (see the threading model explanation in core/runtime.h), - // and the main thread only needs to park here waiting for it to finish. + // The control loop runs on Runtime's own thread (see the threading model explanation in + // core/runtime.h), and the main thread only needs to park here waiting for it to finish. (*runtime)->WaitUntilStopped(); - // The control loop may have exited because of an internal fatal error (rather than receiving a signal), - // in which case the watcher thread must also be made to finish. + // The control loop may have exited because of an internal fatal error (rather than receiving a + // signal), in which case the watcher thread must also be made to finish. g_stop_requested.store(true, std::memory_order_release); signal_watcher.join(); (*runtime)->Stop(); - // The startup sequence runs asynchronously, and failure does not show up in the return value of Start() -- take it from the snapshot. - // The runtime has already logged the error content; here we only carry the exit code out, so scripts can tell. + // The startup sequence runs asynchronously, and failure does not show up in the return value of + // Start(); take it from the snapshot. The runtime has already logged the error content; here we + // only carry the exit code out, so scripts can tell. const auto snapshot = (*runtime)->Snapshot(); return snapshot.fatal_message.empty() ? 0 : 1; } diff --git a/src/capi/CMakeLists.txt b/src/capi/CMakeLists.txt index 22e3f73..557fc55 100644 --- a/src/capi/CMakeLists.txt +++ b/src/capi/CMakeLists.txt @@ -1,12 +1,14 @@ -# tk_capi -- C ABI layer +# tk_capi: C ABI layer # -# The **only** extern "C" boundary in the whole project; its sole reason to exist is to serve the Swift GUI. -# It sits at the very top of the dependency chain (the same layer as app) and depends on core and all modules below it. +# The **only** extern "C" boundary in the whole project; its sole reason to exist is to serve the +# Swift GUI. It sits at the very top of the dependency chain (the same layer as app) and depends on +# core and all modules below it. # -# It is built as an OBJECT library rather than STATIC so that the shared library libtetherkitnext gets **all** the object -# files. If built as a static library, the linker would only pick "referenced" members, and the C ABI's exported functions -# are referenced by nobody inside the library -- the result would be an empty dylib with no error at all. -# (The other route is -force_load, but an OBJECT library is the more direct expression in CMake.) +# It is built as an OBJECT library rather than STATIC so that the shared library libtetherkitnext +# gets **all** the object files. If built as a static library, the linker would only pick +# "referenced" members, and the C ABI's exported functions are referenced by nobody inside the +# library; the result would be an empty dylib with no error at all. (The other route is -force_load, +# but an OBJECT library is the more direct expression in CMake.) add_library( tk_capi OBJECT @@ -22,15 +24,17 @@ add_library( target_link_libraries(tk_capi PUBLIC tetherkitnext_base tk_version tk_core) -# Reading back the NIC IP configuration requires configd's dynamic store (the gateway and DNS actually in effect), which can only go through -# SystemConfiguration. This is a dependency unique to tk_capi -- lower-level modules never touch configd. +# Reading back the NIC IP configuration requires configd's dynamic store (the gateway and DNS +# actually in effect), which can only go through SystemConfiguration. This is a dependency unique to +# tk_capi; lower-level modules never touch configd. target_link_libraries(tk_capi PUBLIC "-framework CoreFoundation" "-framework SystemConfiguration") # ------------------------------------------------------------------------------ -# libtetherkitnext -- the shared library distributed externally +# libtetherkitnext: the shared library distributed externally # -# Swift can only link shared libraries or system libraries, not a pile of CMake static targets, so this layer is required. +# Swift can only link shared libraries or system libraries, not a pile of CMake static targets, so +# this layer is required. # ------------------------------------------------------------------------------ if(TETHERKITNEXT_BUILD_SHARED_LIB) add_library(tetherkitnext_shared SHARED) @@ -41,19 +45,20 @@ if(TETHERKITNEXT_BUILD_SHARED_LIB) PROPERTIES OUTPUT_NAME tetherkitnext VERSION "${PROJECT_VERSION}" SOVERSION "${PROJECT_VERSION_MAJOR}" - # Let dependents load via @rpath instead of burning in an absolute path -- so that when the .app embeds - # this dylib there is no need for a post-hoc install_name_tool (which would also require re-signing; - # see the pitfall in section 7 of docs/GUI-SPIKE.md). + # Let dependents load via @rpath instead of an absolute path, so embedding the dylib + # in the .app needs no install_name_tool afterwards (which would force re-signing; + # see docs/GUI-ARCHITECTURE.md). INSTALL_NAME_DIR "@rpath") - # Only export the C ABI; all other symbols (including C++ mangled names) are hidden. See the allowlist file for the reasons. + # Only export the C ABI; all other symbols (including C++ mangled names) are hidden. See the + # allowlist file for the reasons. target_link_options(tetherkitnext_shared PRIVATE "-Wl,-exported_symbols_list,${PROJECT_SOURCE_DIR}/cmake/tetherkitnext_exports.txt") install(TARGETS tetherkitnext_shared LIBRARY DESTINATION lib) endif() -# The C ABI header is installed for external use: after the Homebrew formula is installed, other projects can also use it for bindings. +# Installed so external projects can bind to the C ABI. install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/tetherkitnext/capi" DESTINATION include/tetherkitnext FILES_MATCHING diff --git a/src/capi/capi_support.cc b/src/capi/capi_support.cc index ec7fff4..8590c77 100644 --- a/src/capi/capi_support.cc +++ b/src/capi/capi_support.cc @@ -15,8 +15,9 @@ std::int64_t WallNanos() noexcept { void ReconcileDeviceStrings(std::vector& memory, std::span present, std::span infos) { - // First evict devices no longer on the bus -- the order matters: eviction comes before backfilling, so that "another" device - // that was unplugged and plugged back into the same address does not get the previous device's name. + // First evict devices no longer on the bus; the order matters: eviction comes before backfilling, + // so that "another" device that was unplugged and plugged back into the same address does not get + // the previous device's name. std::erase_if(memory, [present](const RememberedDeviceStrings& entry) { return std::ranges::find(present, entry.identity) == present.end(); }); @@ -31,7 +32,8 @@ void ReconcileDeviceStrings(std::vector& memory, }); if (read_succeeded) { - // Read -> remember by overwriting (when re-plugged with the same identity, the serial number also follows the latest read). + // Read -> remember by overwriting (when re-plugged with the same identity, the serial number + // also follows the latest read). RememberedDeviceStrings& slot = entry != memory.end() ? *entry @@ -40,8 +42,8 @@ void ReconcileDeviceStrings(std::vector& memory, CopyText(slot.product, info.product); CopyText(slot.serial, info.serial); } else if (entry != memory.end()) { - // Not read but there is a memory -> backfill. When a device truly provides no strings the memory never existed in the first place, - // so nothing is conjured out of thin air here. + // Not read but there is a memory -> backfill. When a device truly provides no strings the + // memory never existed in the first place, so nothing is conjured out of thin air here. CopyText(info.manufacturer, entry->manufacturer); CopyText(info.product, entry->product); CopyText(info.serial, entry->serial); diff --git a/src/capi/capi_support.h b/src/capi/capi_support.h index 5598427..94807a4 100644 --- a/src/capi/capi_support.h +++ b/src/capi/capi_support.h @@ -1,7 +1,9 @@ -// Internal utilities of the C ABI implementation layer. **Not installed externally**; used only inside src/capi. +// Internal utilities of the C ABI implementation layer. **Not installed externally**; used only +// inside src/capi. // -// This centralizes three repetitive chores of the "C++ world <-> C world" boundary: copying std::string_view into -// fixed-size buffers, translating tetherkitnext::Error into tk_error_t, and getting the wall-clock time. +// This centralizes three repetitive chores of the "C++ world <-> C world" boundary: copying +// std::string_view into fixed-size buffers, translating tetherkitnext::Error into tk_error_t, and +// getting the wall-clock time. #pragma once #include @@ -18,18 +20,21 @@ namespace tetherkitnext::capi { /// Copies text into a fixed-size buffer and guarantees NUL termination, truncating when too long. /// -/// * Truncation must land on a UTF-8 character boundary * -/// This project's error messages can be Chinese, where one Chinese character is 3 bytes. Cutting hard by bytes would leave -/// half a character at the end of the buffer, and when Swift's `String(cString:)` meets an illegal sequence the **whole string becomes replacement characters**, -/// which amounts to destroying the entire error message. So after truncating, back up to the nearest character start. +/// Truncation must land on a UTF-8 character boundary: +/// This project's error messages can be Chinese, where one Chinese character is 3 bytes. Cutting +/// hard by bytes would leave half a character at the end of the buffer, and when Swift's +/// `String(cString:)` meets an illegal sequence the **whole string becomes replacement +/// characters**, which amounts to destroying the entire error message. So after truncating, back +/// up to the nearest character start. inline void CopyText(char* destination, std::size_t capacity, std::string_view text) noexcept { if (destination == nullptr || capacity == 0) { return; } std::size_t length = text.size() < capacity - 1 ? text.size() : capacity - 1; - // length < text.size() means truncation occurred: if the cut point falls in the middle of a multi-byte sequence - // (text[length] is a 0b10xxxxxx continuation byte), back up all the way to the start of that sequence. + // length < text.size() means truncation occurred: if the cut point falls in the middle of a + // multi-byte sequence (text[length] is a 0b10xxxxxx continuation byte), back up all the way to + // the start of that sequence. while (length > 0 && length < text.size() && (static_cast(text[length]) & 0xC0U) == 0x80U) { --length; @@ -45,15 +50,17 @@ inline void CopyText(char (&destination)[N], std::string_view text) noexcept { CopyText(destination, N, text); } -/// Translates a C++-side error into a C struct. `out_error` may be nullptr (the caller does not care about the cause). +/// Translates a C++-side error into a C struct. `out_error` may be nullptr (the caller does not +/// care about the cause). inline void FillError(tk_error_t* out_error, const Error& error) noexcept { if (out_error == nullptr) { return; } out_error->domain = static_cast(error.Domain()); out_error->code = error.Code(); - // ToString() is used rather than Context(): the former includes the domain and code such as "[libusb: LIBUSB_ERROR_ACCESS(-3)]", - // which users can paste straight to us when reporting errors. + // ToString() is used rather than Context(): the former includes the domain and code such as + // "[libusb: LIBUSB_ERROR_ACCESS(-3)]", which users can paste straight to us when reporting + // errors. CopyText(out_error->message, error.ToString()); } @@ -67,7 +74,8 @@ inline void FillGenericError(tk_error_t* out_error, std::string_view message) no CopyText(out_error->message, message); } -/// Clears the error struct to "no error". Called on success paths, so callers do not read leftovers from the last time. +/// Clears the error struct to "no error". Called on success paths, so callers do not read leftovers +/// from the last time. inline void ClearError(tk_error_t* out_error) noexcept { if (out_error == nullptr) { return; @@ -79,8 +87,8 @@ inline void ClearError(tk_error_t* out_error) noexcept { /// The quadruple that uniquely identifies "one device plugged into the bus". /// -/// Bus addresses may be reused by the system after unplug/replug, so VID:PID is included as well to avoid attaching one device's memory -/// to another device that takes over the same address. +/// Bus addresses may be reused by the system after unplug/replug, so VID:PID is included as well to +/// avoid attaching one device's memory to another device that takes over the same address. struct DeviceIdentity { std::uint8_t bus_number = 0; std::uint8_t device_address = 0; @@ -106,46 +114,56 @@ struct RememberedDeviceStrings { char serial[TK_USB_STRING_CAPACITY]{}; }; -/// Maintains the memory of string descriptors: remember when read, backfill from memory when not read. +/// Maintains the memory of string descriptors: remember when read, backfill from memory when not +/// read. /// -/// * Why it is needed * -/// String descriptors need libusb_open to read, and during a session the device is held exclusively by this process, -/// so the read is skipped by the caller or fails outright -- but the device itself has not changed, and "could not get it this time" does not mean -/// "the device has no name". Without backfilling, a single enumeration at the moment of connecting would overwrite -/// "vivo iQOO Z10x" on the UI with "USB device 2d95:600b" and leave it hanging there for the entire session. +/// Why it is needed: +/// String descriptors need libusb_open to read, and during a session the device is held +/// exclusively by this process, so the read is skipped by the caller or fails outright, but the +/// device itself has not changed, and "could not get it this time" does not mean "the device has +/// no name". Without backfilling, a single enumeration at the moment of connecting would +/// overwrite "vivo iQOO Z10x" on the UI with "USB device 2d95:600b" and leave it hanging there +/// for the entire session. /// /// Rules (`infos` are the devices of this enumeration whose base fields are already filled): -/// - If **any** of the three strings of `infos[i]` is non-empty -> it was read this time; record it into `memory` by overwriting; -/// - All empty -> not read (skipped or the device is occupied); if `memory` has a memory of the same identity, backfill it; -/// - Entries in `memory` whose identity is not in `present` (all devices currently on the bus) are cleared -- -/// the device has been unplugged and the memory is stale; if another device whose name cannot be read is plugged in at the same address, -/// it is better to show VID:PID than to attach the previous device's name to it. +/// - If **any** of the three strings of `infos[i]` is non-empty -> it was read this time; record +/// it into `memory` by overwriting; +/// - All empty -> not read (skipped or the device is occupied); if `memory` has a memory of the +/// same identity, backfill it; +/// - Entries in `memory` whose identity is not in `present` (all devices currently on the bus) +/// are cleared; the device has been unplugged and the memory is stale; if another device whose +/// name cannot be read is plugged in at the same address, it is better to show VID:PID than to +/// attach the previous device's name to it. /// -/// `present` may be longer than `infos`: when the caller's array capacity is insufficient only the first few devices were filled, -/// and the rest are still present, so their memory must not be deleted by mistake. -/// Pure logic, touching no libusb, with locking the caller's responsibility -- this is what makes offline unit testing possible. +/// `present` may be longer than `infos`: when the caller's array capacity is insufficient only the +/// first few devices were filled, and the rest are still present, so their memory must not be +/// deleted by mistake. Pure logic, touching no libusb, with locking the caller's responsibility; +/// this is what makes offline unit testing possible. void ReconcileDeviceStrings(std::vector& memory, std::span present, std::span infos); /// Wall-clock time since the Unix epoch (nanoseconds). /// -/// Events and logs use wall time rather than monotonic time: they are displayed to humans and must line up with the system log -/// in Console.app. Rate computation has its own monotonic time; see tk_session_status.monotonic_nanos. +/// Events and logs use wall time rather than monotonic time: they are displayed to humans and must +/// line up with the system log in Console.app. Rate computation has its own monotonic time; see +/// tk_session_status.monotonic_nanos. [[nodiscard]] std::int64_t WallNanos() noexcept; /// Validates a NIC name: accepts only `feth`. /// -/// This is not fastidiousness -- the NIC name gets spliced into the argv of `ipconfig` / `route`. Although we pass an array via -/// posix_spawn rather than going through a shell (which already rules out injection), restricting interface names to the form -/// that we created ourselves also blocks more realistic accidents such as "mistakenly passing en0 in and -/// wiping out the user's Wi-Fi configuration". +/// This is not fastidiousness: the NIC name gets spliced into the argv of `ipconfig` / `route`. +/// Although we pass an array via posix_spawn rather than going through a shell (which already rules +/// out injection), restricting interface names to the form that we created ourselves also blocks +/// more realistic accidents such as "mistakenly passing en0 in and wiping out the user's Wi-Fi +/// configuration". [[nodiscard]] bool IsValidFethName(std::string_view name) noexcept; /// Installs the on-disk registration of feth interfaces (see orphan_cleanup.cc). Idempotent. /// -/// Called by tk_session_create -- registration is needed only when a NIC is really going to be created, keeping the root-free -/// group of interfaces (version, enumeration, preflight) free of side effects. +/// Called by tk_session_create: registration is needed only when a NIC is really going to be +/// created, keeping the root-free group of interfaces (version, enumeration, preflight) free of +/// side effects. void InstallInterfaceRegistry(); } // namespace tetherkitnext::capi diff --git a/src/capi/core_foundation_support.cc b/src/capi/core_foundation_support.cc index 86c0602..2691498 100644 --- a/src/capi/core_foundation_support.cc +++ b/src/capi/core_foundation_support.cc @@ -16,8 +16,9 @@ std::string CopyToStdString(CFStringRef text) { return {}; } - // Try the zero-copy fast path first: CFStringGetCStringPtr gives the pointer directly when the string is internally UTF-8 already, - // which hits in the vast majority of cases (what we read are ASCII things like NIC names and IPs). + // Try the zero-copy fast path first: CFStringGetCStringPtr gives the pointer directly when the + // string is internally UTF-8 already, which hits in the vast majority of cases (what we read are + // ASCII things like NIC names and IPs). if (const char* direct = ::CFStringGetCStringPtr(text, kCFStringEncodingUTF8); direct != nullptr) { return std::string{direct}; @@ -33,10 +34,12 @@ std::string CopyToStdString(CFStringRef text) { } SCDynamicStoreRef SharedDynamicStore() { - // Function-local static: created on the first call and not released before process exit. See the header for the reason. + // Function-local static: created on the first call and not released before process exit. See the + // header for the reason. // - // Not locking is safe -- since C++11, the initialization of a function-local static is guaranteed thread-safe by the compiler - // (magic static), and on concurrent first calls only one thread actually runs the initialization. + // Not locking is safe, since C++11, the initialization of a function-local static is guaranteed + // thread-safe by the compiler (magic static), and on concurrent first calls only one thread + // actually runs the initialization. static SCDynamicStoreRef store = ::SCDynamicStoreCreate( kCFAllocatorDefault, CFSTR("TetherKitNext"), /*callout=*/nullptr, /*context=*/nullptr); return store; diff --git a/src/capi/core_foundation_support.h b/src/capi/core_foundation_support.h index e3159e7..c1c3921 100644 --- a/src/capi/core_foundation_support.h +++ b/src/capi/core_foundation_support.h @@ -1,8 +1,8 @@ // Minimal RAII wrappers for CoreFoundation / SystemConfiguration. // -// Wrapped only to the point of "enough": the only place in the project that needs to touch CF is reading and writing SCDynamicStore, -// so introducing a full CF smart-pointer library is not worthwhile, yet hand-written CFRelease is too easy to miss -// on early-return branches. +// Wrapped only to the point of "enough": the only place in the project that needs to touch CF is +// reading and writing SCDynamicStore, so introducing a full CF smart-pointer library is not +// worthwhile, yet hand-written CFRelease is too easy to miss on early-return branches. #pragma once #include @@ -16,8 +16,9 @@ namespace tetherkitnext::capi { /// Owns a CF object, calling CFRelease on destruction. /// -/// Used only for references **we own** under the Create/Copy rule. References returned under the Get rule, such as by CFDictionaryGetValue, -/// are not owned and must never be put in here -- that would cause an over-release. +/// Used only for references **we own** under the Create/Copy rule. References returned under the +/// Get rule, such as by CFDictionaryGetValue, are not owned and must never be put in here; that +/// would cause an over-release. template class ScopedCFRef { public: @@ -61,17 +62,19 @@ class ScopedCFRef { /// CFString -> UTF-8 std::string. Passing nullptr yields an empty string. [[nodiscard]] std::string CopyToStdString(CFStringRef text); -/// The process-wide shared SCDynamicStore handle. Created on the first call and reused ever after; returns -/// nullptr on failure. +/// The process-wide shared SCDynamicStore handle. Created on the first call and reused ever after; +/// returns nullptr on failure. /// -/// * Why it must be process-wide and long-lived * -/// A value **set** in an SCDynamicStore by some session is deleted together when that session is released. -/// We need to write DNS keys into the dynamic store; if we used a store that is created temporarily and released after use, -/// the value we just wrote would vanish in an instant -- and the symptom is "the write returns success, the readback is empty", -/// which is very hard to track down. +/// Why it must be process-wide and long-lived: +/// A value **set** in an SCDynamicStore by some session is deleted together when that session is +/// released. We need to write DNS keys into the dynamic store; if we used a store that is created +/// temporarily and released after use, the value we just wrote would vanish in an instant, and +/// the symptom is "the write returns success, the readback is empty", which is very hard to track +/// down. /// -/// The cost is that this handle is not released until the process exits, which is exactly what we want: when the helper exits, -/// the dynamic store entries it wrote are cleaned up automatically, leaving no garbage. +/// The cost is that this handle is not released until the process exits, which is exactly what we +/// want: when the helper exits, the dynamic store entries it wrote are cleaned up automatically, +/// leaving no garbage. [[nodiscard]] SCDynamicStoreRef SharedDynamicStore(); } // namespace tetherkitnext::capi diff --git a/src/capi/environment.cc b/src/capi/environment.cc index 47b8594..fadfc57 100644 --- a/src/capi/environment.cc +++ b/src/capi/environment.cc @@ -1,7 +1,7 @@ // Three root-free things: version, environment preflight, device enumeration. // -// The GUI itself (uid 501) calls only this group; the root-requiring session and NIC configuration are all handed to -// tetherkitnext-helper. This split is one of the core conclusions of docs/GUI-SPIKE.md. +// The GUI itself (uid 501) calls only this group; the root-requiring session and NIC configuration +// are all handed to tetherkitnext-helper (see docs/GUI-ARCHITECTURE.md). #include #include @@ -29,11 +29,13 @@ using tetherkitnext::capi::ClearError; using tetherkitnext::capi::CopyText; using tetherkitnext::capi::FillError; -/// Reads a USB string descriptor into a fixed-size buffer. An index of 0 means the device does not provide that string. +/// Reads a USB string descriptor into a fixed-size buffer. An index of 0 means the device does not +/// provide that string. /// /// Uses libusb's `_ascii` variant: it replaces code points beyond ASCII in the UTF-16LE with '?'. -/// That is enough for us -- these strings are only used to let users tell two devices of the same model apart, and the vast majority of vendor names and -/// serial numbers are ASCII anyway. Doing a full UTF-16 -> UTF-8 conversion ourselves gains too little. +/// That is enough for us: these strings are only used to let users tell two devices of the same +/// model apart, and the vast majority of vendor names and serial numbers are ASCII anyway. Doing a +/// full UTF-16 -> UTF-8 conversion ourselves gains too little. void ReadStringDescriptor(::libusb_device_handle* handle, std::uint8_t index, char* destination, std::size_t capacity) noexcept { if (index == 0) { @@ -52,11 +54,12 @@ void ReadStringDescriptor(::libusb_device_handle* handle, std::uint8_t index, ch /// Fills in the vendor name / product name / serial number on a best-effort basis. /// -/// Why "best effort": reading string descriptors requires libusb_open first, and the device may already be held exclusively by another process -/// on this machine (such as the running tetherkitnext-helper), in which case the darwin backend returns -/// LIBUSB_ERROR_ACCESS. That is not an error, just the name being unobtainable -- then the string memory backfills -/// the value read last time (see the end of tk_list_devices), and only with no memory either does it fall back to VID:PID. -/// It must never make the whole enumeration fail because of this. +/// Why "best effort": reading string descriptors requires libusb_open first, and the device may +/// already be held exclusively by another process on this Mac (such as the running +/// tetherkitnext-helper), in which case the darwin backend returns LIBUSB_ERROR_ACCESS. That is not +/// an error, just the name being unobtainable; then the string memory backfills the value read last +/// time (see the end of tk_list_devices), and only with no memory either does it fall back to +/// VID:PID. It must never make the whole enumeration fail because of this. void TryReadStrings(::libusb_context* context, tk_device_info_t& info) noexcept { ::libusb_device** list = nullptr; const ssize_t count = ::libusb_get_device_list(context, &list); @@ -86,25 +89,30 @@ void TryReadStrings(::libusb_context* context, tk_device_info_t& info) noexcept break; } - // The second argument is 1: release together with the reference count of every device in the list. + // The second argument is 1: release together with the reference count of every device in the + // list. ::libusb_free_device_list(list, 1); } /// The process-wide shared libusb context, **for enumeration only**. /// -/// * Why it must be shared * -/// Creating a new context for every enumeration amounts to going through "initialize libusb -> start the event thread -/// -> start the IOKit runloop thread -> tear everything down after use" every single time. The GUI refreshes the device -/// list every few hundred milliseconds, so this overhead would repeat at the same frequency, and the log would also be flooded with "libusb initialized". +/// Why it must be shared: +/// Creating a new context for every enumeration amounts to going through "initialize libusb -> +/// start the event thread -> start the IOKit runloop thread -> tear everything down after use" +/// every single time. The GUI refreshes the device list every few hundred milliseconds, so this +/// overhead would repeat at the same frequency, and the log would also be flooded with "libusb +/// initialized". /// -/// After sharing, the whole process initializes only once. A long-lived context still sees newly plugged-in devices -- -/// libusb's darwin backend has its own hotplug thread maintaining the device list, which is the ordinary mechanism that all -/// libusb programs depend on. +/// After sharing, the whole process initializes only once. A long-lived context still sees newly +/// plugged-in devices libusb's darwin backend has its own hotplug thread maintaining the device +/// list, which is the ordinary mechanism that all libusb programs depend on. /// -/// A session (core::Runtime) has its own separate context and does not reuse this one: its lifetime is managed by the session -/// itself, and mixing them in would only complicate the shutdown order. libusb supports multiple contexts in one process. +/// A session (core::Runtime) has its own separate context and does not reuse this one: its lifetime +/// is managed by the session itself, and mixing them in would only complicate the shutdown order. +/// libusb supports multiple contexts in one process. /// -/// On initialization failure returns nullptr and fills the error, and **does not cache the failure**; the next call retries. +/// On initialization failure returns nullptr and fills the error, and **does not cache the +/// failure**; the next call retries. tetherkitnext::usb::Context* SharedEnumerationContext(tk_error_t* out_error) { static std::mutex mutex; static std::unique_ptr context; @@ -121,10 +129,12 @@ tetherkitnext::usb::Context* SharedEnumerationContext(tk_error_t* out_error) { return context.get(); } -/// The process-wide memory of string descriptors (lock + entries), a function-local static like the shared enumeration context. +/// The process-wide memory of string descriptors (lock + entries), a function-local static like the +/// shared enumeration context. /// -/// It is placed at process level rather than in the caller: the helper is a resident process, so after a mid-way GUI restart the first enumeration -/// can already get the backfilled names; for the pure logic see the explanation of ReconcileDeviceStrings. +/// It is placed at process level rather than in the caller: the helper is a resident process, so +/// after a mid-way GUI restart the first enumeration can already get the backfilled names; for the +/// pure logic see the explanation of ReconcileDeviceStrings. struct StringMemory { std::mutex mutex; std::vector entries; @@ -155,7 +165,8 @@ void FillDeviceInfo(const tetherkitnext::usb::DeviceCandidate& candidate, namespace { -/// tk_language_t -> the C++ side's Language. Returns nullopt when out of range, so the caller ignores this setting. +/// tk_language_t -> the C++ side's Language. Returns nullopt when out of range, so the caller +/// ignores this setting. [[nodiscard]] std::optional ToLanguage(std::int32_t value) noexcept { switch (value) { case TK_LANGUAGE_ENGLISH: @@ -210,9 +221,10 @@ tk_result_t tk_check_environment(tk_environment_t* out_environment) { out_environment->is_root = tetherkitnext::net::IsRunningAsRoot(); - // These sysctls are **creation-time snapshots** of feth; changing them after creation has no effect, so they must be checked in advance. - // When unacceptable, hand the reason as-is to the GUI to display -- only when the user sees exactly which switch is turned on - // do they know what to change. + // These sysctls are **creation-time snapshots** of feth; changing them after creation has no + // effect, so they must be checked in advance. When unacceptable, hand the reason as-is to the GUI + // to display, only when the user sees exactly which switch is turned on do they know what to + // change. if (const auto status = tetherkitnext::net::VerifyFethSysctls(); status) { out_environment->sysctls_ok = true; } else { @@ -224,7 +236,8 @@ tk_result_t tk_check_environment(tk_environment_t* out_environment) { out_environment->feth_max_mtu = *max_mtu; } - // Deliberately always return success: "environment unacceptable" is a **result** to be shown to the user, not a call failure. + // Always return success: "environment unacceptable" is a **result** to be shown to the user, not + // a call failure. return TK_OK; } @@ -260,9 +273,10 @@ tk_result_t tk_list_devices(tk_device_info_t* out_devices, size_t capacity, size } } - // Remember when read, backfill when not read -- only then does the name not disappear from the UI during a session (read_strings=false or the device occupied). - // present uses the complete candidate set rather than the writable prefix: when capacity is insufficient the devices further back - // are still present, and their memory must not be cleared as "unplugged". + // Remember when read, backfill when not read, only then does the name not disappear from the UI + // during a session (read_strings=false or the device occupied). present uses the complete + // candidate set rather than the writable prefix: when capacity is insufficient the devices + // further back are still present, and their memory must not be cleared as "unplugged". { std::vector present; present.reserve(candidates->size()); diff --git a/src/capi/log_ring.cc b/src/capi/log_ring.cc index 77baace..9e239fa 100644 --- a/src/capi/log_ring.cc +++ b/src/capi/log_ring.cc @@ -1,9 +1,10 @@ -// Log capture: buffers the library's internal log lines for the GUI to poll and take away. +// Log capture: buffers the library's internal log lines for the GUI to poll and drain. // -// Why not pass through to Swift via a callback: logs come up from the libusb event thread, the control thread and the two data-path -// threads, and are produced **inside** the log mutex. Running a Swift closure in that context -// would require cross-thread marshaling and would also carry the landmine of "the closure accidentally logs again -> self-wait deadlock". -// Buffer + polling eliminates both problems at once. +// Why not pass through to Swift via a callback: logs come up from the libusb event thread, the +// control thread and the two data-path threads, and are produced **inside** the log mutex. Running +// a Swift closure in that context would require cross-thread marshaling and would also carry the +// landmine of "the closure accidentally logs again -> self-wait deadlock". Buffer + polling +// eliminates both problems at once. #include #include #include @@ -21,19 +22,22 @@ using tetherkitnext::capi::WallNanos; /// Ring buffer capacity. /// -/// Basis for 256: the GUI pulls every 500 ms, while the library writes only one statistics line every 5 seconds in steady state. -/// 256 entries are enough to withstand the dense burst of logs from the startup sequence (about 30 lines) and any sudden warnings, -/// while keeping resident memory at 256 x 552 B ~= 138 KiB. +/// Basis for 256: the GUI pulls every 500 ms, while the library writes only one statistics line +/// every 5 seconds in steady state. 256 entries are enough to withstand the dense burst of logs +/// from the startup sequence (about 30 lines) and any sudden warnings, while keeping resident +/// memory at 256 x 552 B ~= 138 KiB. constexpr std::size_t kLogRingCapacity = 256; -/// A fixed-size ring buffer. When full it drops the **oldest** -- when the host is stuck, the latest scene is more useful than the beginning. +/// A fixed-size ring buffer. When full it drops the **oldest**: when the host is stuck, the latest +/// scene is more useful than the beginning. class LogRing { public: void Push(tk_log_level_t level, std::string_view thread_name, std::string_view message) noexcept { const std::lock_guard guard(mutex_); if (count_ == kLogRingCapacity) { - // Overwrite the oldest entry: advance the read pointer, which logically amounts to dropping it. + // Overwrite the oldest entry: advance the read pointer, which logically amounts to dropping + // it. head_ = (head_ + 1) % kLogRingCapacity; --count_; ++dropped_; @@ -81,8 +85,9 @@ class LogRing { std::uint64_t dropped_ = 0; }; -/// Process-wide singleton. A function-local static rather than a global object, to avoid static initialization order problems -- -/// the log sink may be triggered during the static construction of any translation unit. +/// Process-wide singleton. A function-local static rather than a global object, to avoid static +/// initialization order problems; the log sink may be triggered during the static construction of +/// any translation unit. LogRing& Ring() noexcept { static LogRing ring; return ring; @@ -90,8 +95,8 @@ LogRing& Ring() noexcept { /// The callback installed for tetherkitnext::SetLogSink. /// -/// It runs inside the log mutex, so the implementation may only do "copy + take one lock of its own", -/// and must never log again (a self-wait deadlock). +/// It runs inside the log mutex, so the implementation may only do "copy + take one lock of its +/// own", and must never log again (a self-wait deadlock). void SinkTrampoline(tetherkitnext::LogLevel level, std::string_view thread_name, std::string_view message, void* /*user*/) noexcept { Ring().Push(static_cast(level), thread_name, message); @@ -114,11 +119,12 @@ void tk_enable_log_capture(bool enabled) { // The order matters: **first** remove the log sink, **then** clear the buffer. // - // Reversed, a thread that was logging before the removal would stuff a new record into the just-cleared buffer, - // and after capture is turned off a few leftovers would remain instead. + // Reversed, a thread that was logging before the removal would stuff a new record into the + // just-cleared buffer, and after capture is turned off a few leftovers would remain instead. // - // Also, LogRing's lock is deliberately not held here while calling SetLogSink -- SetLogSink needs to take the log - // mutex, while the log sink path is "log lock -> LogRing lock", and holding locks in the reverse order would form a lock-order inversion. + // Also, LogRing's lock is not held here while calling SetLogSink; SetLogSink needs to take the + // log mutex, while the log sink path is "log lock -> LogRing lock", and holding locks in the + // reverse order would form a lock-order inversion. tetherkitnext::SetLogSink(nullptr, nullptr); Ring().Clear(); } diff --git a/src/capi/managed_network_service.cc b/src/capi/managed_network_service.cc index f042f74..1bc58f4 100644 --- a/src/capi/managed_network_service.cc +++ b/src/capi/managed_network_service.cc @@ -1,10 +1,9 @@ // Register feth as a real macOS network service while TetherKitNext owns it. // -// `ipconfig set DHCP` publishes a dynamic State:/ service, but no -// Setup:/Network/Service entry. Packet-tunnel providers can lose that transient -// interface when NetworkExtension takes over routing. A service in the current -// SCNetworkSet gives configd the durable interface metadata it needs to preserve -// the underlying path during tunnel startup. +// `ipconfig set DHCP` publishes a dynamic State:/ service, but no Setup:/Network/Service +// entry. Packet-tunnel providers can lose that transient interface when NetworkExtension takes over +// routing. A service in the current SCNetworkSet gives configd the durable interface metadata it +// needs to preserve the underlying path during tunnel startup. #include "managed_network_service.h" #include @@ -31,17 +30,15 @@ using tetherkitnext::capi::IsValidFethName; using tetherkitnext::capi::MakeCFString; using tetherkitnext::capi::ScopedCFRef; -// SystemConfiguration exports this SPI on every supported macOS version. The -// public API can enumerate only IOKit-backed interfaces, while feth is a pure -// ifnet. The SPI constructs the same Ethernet SCNetworkInterface object from a -// BSD name; all subsequent service/configuration calls are public API. -// Source: apple-oss-distributions/configd, SCNetworkConfigurationPrivate.h. +// SystemConfiguration exports this SPI on every supported macOS version. The public API can +// enumerate only IOKit-backed interfaces, while feth is a pure ifnet. The SPI constructs the same +// Ethernet SCNetworkInterface object from a BSD name; all subsequent service/configuration calls +// are public API. Source: apple-oss-distributions/configd, SCNetworkConfigurationPrivate.h. // -// Resolved at runtime with dlsym rather than linked directly: a hard reference -// to an SPI means that if a future macOS drops the symbol, dyld refuses to load -// libtetherkitnext at all and the whole app/helper dies at launch. Looked up -// lazily, a missing symbol only disables the managed service and DHCP falls -// back to the transient `ipconfig set` path. +// Resolved at runtime with dlsym rather than linked directly: a hard reference to an SPI means that +// if a future macOS drops the symbol, dyld refuses to load libtetherkitnext at all and the whole +// app/helper dies at launch. Looked up lazily, a missing symbol only disables the managed service +// and DHCP falls back to the transient `ipconfig set` path. using CreateWithBsdNameFunction = SCNetworkInterfaceRef (*)(CFAllocatorRef allocator, CFStringRef bsd_name, std::uint32_t flags); @@ -55,10 +52,9 @@ using CreateWithBsdNameFunction = SCNetworkInterfaceRef (*)(CFAllocatorRef alloc } constexpr std::uint32_t kIncludeAllVirtualInterfaces = 0xFFFF'FFFFU; -// Services are named "TetherKitNext (fethN)". Matching on the shorter -// "TetherKit" prefix also catches the "TetherKit (fethN)" services left behind -// by builds from before the rename, so orphan cleanup removes those too. A -// service only counts as ours if it is also bound to a feth interface. +// Services are named "TetherKitNext (fethN)". Matching on the shorter "TetherKit" prefix also +// catches the "TetherKit (fethN)" services left behind by builds from before the rename, so orphan +// cleanup removes those too. A service only counts as ours if it is also bound to a feth interface. constexpr std::string_view kManagedServicePrefix = "TetherKit"; [[nodiscard]] std::unexpected SystemConfigurationFailure( @@ -129,11 +125,10 @@ constexpr std::string_view kManagedServicePrefix = "TetherKit"; /// Holds the SCPreferences write lock for a scope. /// -/// Apple requires writers of the network preferences to take this lock so a -/// concurrent writer (System Settings, networksetup, configd itself) cannot -/// interleave with our read-modify-commit. `wait = true` blocks until the -/// other writer finishes instead of failing. Unlock is implicit on commit -/// failure paths via the destructor. +/// Apple requires writers of the network preferences to take this lock so a concurrent writer +/// (System Settings, networksetup, configd itself) cannot interleave with our read-modify-commit. +/// `wait = true` blocks until the other writer finishes instead of failing. Unlock is implicit on +/// commit failure paths via the destructor. class PreferencesLock { public: explicit PreferencesLock(SCPreferencesRef preferences) noexcept @@ -249,16 +244,14 @@ Result ConfigureManagedDhcpService(std::string_view interface_name, return SystemConfigurationFailure("SCNetworkSetAddService"); } - // SCNetworkSetAddService appends the service to the *end* of the set's - // service order, so without this step Ethernet/Wi-Fi always outrank the - // phone. The order is what IPMonitor uses to pick the primary service, and - // the primary service owns both the global default route *and* the DNS - // resolver configuration. Putting ours first is therefore the only way to - // send all traffic (including name lookups) through the phone when another - // network — e.g. a LAN without internet access — is also connected. - // It is the same setting as System Settings › Network › Set Service Order. - // Services are recreated on every apply, so turning the option off simply - // leaves the new service at the end again. + // SCNetworkSetAddService appends the service to the *end* of the set's service order, so without + // this step Ethernet/Wi-Fi always outrank the phone. The order is what IPMonitor uses to pick the + // primary service, and the primary service owns both the global default route *and* the DNS + // resolver configuration. Putting ours first is therefore the only way to send all traffic + // (including name lookups) through the phone when another network; e.g. a LAN without internet + // access: is also connected. It is the same setting as System Settings › Network › Set Service + // Order. Services are recreated on every apply, so turning the option off simply leaves the new + // service at the end again. if (make_primary) { const CFStringRef our_id = ::SCNetworkServiceGetServiceID(service.Get()); const CFArrayRef current_order = ::SCNetworkSetGetServiceOrder(network_set.Get()); @@ -284,6 +277,67 @@ Result ConfigureManagedDhcpService(std::string_view interface_name, return service_id; } +Status DemoteManagedNetworkService(std::string_view interface_name) { + const ScopedCFRef preferences = CreatePreferences(); + if (!preferences) { + return SystemConfigurationFailure("SCPreferencesCreate"); + } + const PreferencesLock lock{preferences.Get()}; + if (!lock.Locked()) { + return SystemConfigurationFailure("SCPreferencesLock"); + } + + const ScopedCFRef network_set{::SCNetworkSetCopyCurrent(preferences.Get())}; + if (!network_set) { + return SystemConfigurationFailure("SCNetworkSetCopyCurrent"); + } + const CFArrayRef current_order = ::SCNetworkSetGetServiceOrder(network_set.Get()); + if (current_order == nullptr) { + return tetherkitnext::Ok(); + } + + // IDs of our service(s) for this interface. + const ScopedCFRef services{::SCNetworkServiceCopyAll(preferences.Get())}; + if (!services) { + return SystemConfigurationFailure("SCNetworkServiceCopyAll"); + } + const ScopedCFRef ours{ + ::CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)}; + for (CFIndex index = 0; index < ::CFArrayGetCount(services.Get()); ++index) { + const auto service = + static_cast(::CFArrayGetValueAtIndex(services.Get(), index)); + if (IsManagedService(service, interface_name)) { + ::CFArrayAppendValue(ours.Get(), ::SCNetworkServiceGetServiceID(service)); + } + } + const CFRange all_ours = ::CFRangeMake(0, ::CFArrayGetCount(ours.Get())); + if (all_ours.length == 0) { + return tetherkitnext::Ok(); + } + + // Everyone else keeps their relative order; ours go last. + const ScopedCFRef new_order{ + ::CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)}; + const CFIndex count = ::CFArrayGetCount(current_order); + for (CFIndex i = 0; i < count; ++i) { + const void* const id = ::CFArrayGetValueAtIndex(current_order, i); + if (::CFArrayContainsValue(ours.Get(), all_ours, id) == 0) { + ::CFArrayAppendValue(new_order.Get(), id); + } + } + if (::CFArrayGetCount(new_order.Get()) == count) { + return tetherkitnext::Ok(); // ours were not in the order at all + } + ::CFArrayAppendArray(new_order.Get(), ours.Get(), all_ours); + if (::CFEqual(new_order.Get(), current_order) != 0) { + return tetherkitnext::Ok(); // already last + } + if (::SCNetworkSetSetServiceOrder(network_set.Get(), new_order.Get()) == 0) { + return SystemConfigurationFailure("SCNetworkSetSetServiceOrder"); + } + return CommitAndApply(preferences.Get()); +} + Status RemoveManagedNetworkService(std::string_view interface_name) { return RemoveManagedServices(interface_name); } diff --git a/src/capi/managed_network_service.h b/src/capi/managed_network_service.h index fe7f356..d6267e7 100644 --- a/src/capi/managed_network_service.h +++ b/src/capi/managed_network_service.h @@ -8,21 +8,25 @@ namespace tetherkitnext::capi { -/// Whether the SystemConfiguration SPI needed to build a service for a feth -/// interface exists on this macOS. When false, callers fall back to the -/// transient `ipconfig set DHCP` service. +/// Whether the SystemConfiguration SPI needed to build a service for a feth interface exists on +/// this macOS. When false, callers fall back to the transient `ipconfig set DHCP` service. [[nodiscard]] bool ManagedNetworkServiceAvailable() noexcept; -/// Replace any prior TetherKitNext service for the interface with a DHCP service -/// registered in the current macOS network set. Returns the new service ID. +/// Replace any prior TetherKitNext service for the interface with a DHCP service registered in the +/// current macOS network set. Returns the new service ID. /// -/// `make_primary` moves the service to the front of the set's service order, -/// making it the primary service: macOS then routes all traffic *and* DNS -/// through it, ahead of Ethernet/Wi-Fi, and keeps doing so across network -/// changes. +/// `make_primary` moves the service to the front of the set's service order, making it the primary +/// service: macOS then routes all traffic *and* DNS through it, ahead of Ethernet/Wi-Fi, and keeps +/// doing so across network changes. [[nodiscard]] Result ConfigureManagedDhcpService( std::string_view interface_name, bool make_primary); +/// Move TetherKitNext's service for this interface to the *end* of the service order, undoing +/// `make_primary`. Used when "route all traffic" was requested but the link turned out to have no +/// router (a local device such as a drone or a gadget-mode board): a service that cannot reach the +/// internet must never outrank Wi-Fi/Ethernet. Idempotent; a no-op when the service does not exist. +[[nodiscard]] Status DemoteManagedNetworkService(std::string_view interface_name); + /// Remove TetherKitNext-owned services for one feth interface. Idempotent. [[nodiscard]] Status RemoveManagedNetworkService(std::string_view interface_name); diff --git a/src/capi/net_config.cc b/src/capi/net_config.cc index 8fa1994..951c295 100644 --- a/src/capi/net_config.cc +++ b/src/capi/net_config.cc @@ -1,30 +1,40 @@ -// Configuration of the virtual NIC's connectivity method: DHCP / static IP / revoke, plus readback of the actual in-effect state. +// Configuration of the virtual NIC's connectivity method: DHCP / static IP / revoke, plus readback +// of the actual in-effect state. // -// * Why DHCP establishes a real macOS network service * +// Why DHCP establishes a real macOS network service: // -// `ipconfig set` only establishes a temporary service under State:/Network/Service. Ordinary traffic can use it, -// but when NetworkExtension takes over routing it does not treat such a service as a reliable underlying path: a VPN -// provider gets "No network route" even though feth0 still has an address and a scoped route. +// `ipconfig set` only establishes a temporary service under State:/Network/Service. Ordinary +// traffic can use it, but when NetworkExtension takes over routing it does not treat such a +// service as a reliable underlying path: a VPN provider gets "No network route" even though feth0 +// still has an address and a scoped route. // -// DHCP mode therefore registers feth in the current network set via SCPreferences / SCNetworkService. -// feth has no IOKit node, so public APIs cannot enumerate it; managed_network_service.cc uses only -// the BSD-name constructor SPI that Apple itself exports to fill in the SCNetworkInterface, and the subsequent service, -// protocol, commit and apply all go through public APIs. The service is removed when the feth is destroyed. +// DHCP mode therefore registers feth in the current network set via SCPreferences / +// SCNetworkService. feth has no IOKit node, so public APIs cannot enumerate it; +// managed_network_service.cc uses only the BSD-name constructor SPI that Apple itself exports to +// fill in the SCNetworkInterface, and the subsequent service, protocol, commit and apply all go +// through public APIs. The service is removed when the feth is destroyed. // -// * The DNS of a static IP is "best effort + readback verification" * +// The DNS of a static IP is "best effort + readback verification": // -// IPConfiguration publishes DNS only in DHCP mode (it comes from DHCP options). -// MANUAL mode has no DNS source, so all we can do is add a DNS key to the service it established. -// This move is **not verified on real hardware**, so success is never promised to upper layers: tk_net_query always reads back -// the resolvers actually in effect in the system, and what the GUI shows is the readback rather than the value we applied. -#include -#include +// IPConfiguration publishes DNS only in DHCP mode (it comes from DHCP options). MANUAL mode has +// no DNS source, so all we can do is add a DNS key to the service it established. This move is +// **not verified on real hardware**, so success is never promised to upper layers: tk_net_query +// always reads back the resolvers actually in effect in the system, and what the GUI shows is the +// readback rather than the value we applied. +#include "net_config.h" + +#include "tetherkitnext/capi/tetherkitnext_c.h" +#include "tetherkitnext/common/i18n.h" +#include "tetherkitnext/common/logging.h" + #include #include #include #include +#include #include +#include #include #include #include @@ -39,9 +49,6 @@ #include "core_foundation_support.h" #include "managed_network_service.h" #include "process_runner.h" -#include "tetherkitnext/capi/tetherkitnext_c.h" -#include "tetherkitnext/common/i18n.h" -#include "tetherkitnext/common/logging.h" namespace { @@ -68,15 +75,18 @@ constexpr std::string_view kRoutePath = "/sbin/route"; /// Upper limit of waiting for a DHCP lease. /// -/// Basis for 10 seconds: DHCP DISCOVER retransmits use exponential backoff (1/2/4/8 seconds), and 10 seconds is enough to cover -/// the first three retransmissions. Any longer and we should tell the user "there is probably no DHCP server on the other side" instead of spinning on. +/// Basis for 10 seconds: DHCP DISCOVER retransmits use exponential backoff (1/2/4/8 seconds), and +/// 10 seconds is enough to cover the first three retransmissions. Any longer and we should tell the +/// user "there is probably no DHCP server on the other side" instead of spinning on. constexpr std::chrono::seconds kDhcpLeaseTimeout{10}; constexpr std::chrono::milliseconds kDhcpPollInterval{250}; -/// How many consecutive times the gateway must read the same value before the lease is considered stable. +/// How many consecutive times the gateway must read the same value before the lease is considered +/// stable. /// -/// 8 times x 250 ms = 2 seconds. Basis: Android's USB tethering first hands out a 464XLAT transitional lease -/// (192.0.0.2 / gateway 192.0.0.1), and measurement shows it is replaced by the real subnet within 1 second; a 2-second quiet period -/// is enough to span that switch without making "right the first time" devices wait too long for nothing. +/// 8 times x 250 ms = 2 seconds. Basis: Android's USB tethering first hands out a 464XLAT +/// transitional lease (192.0.0.2 / gateway 192.0.0.1), and measurement shows it is replaced by the +/// real subnet within 1 second; a 2-second quiet period is enough to span that switch without +/// making "right the first time" devices wait too long for nothing. constexpr int kDhcpStableSamples = 8; // --------------------------------------------------------------------------- @@ -107,17 +117,19 @@ constexpr int kDhcpStableSamples = 8; // External tool invocation // --------------------------------------------------------------------------- -/// Runs a tool command; a non-zero exit is treated as failure and its output is carried along as-is. +/// Runs a tool command; a non-zero exit is treated as failure and its output is carried along +/// as-is. /// -/// Carrying it as-is matters: the error output of ipconfig / route is itself the most accurate diagnostic information, -/// and relaying it a second time ourselves would only lose information. +/// Carrying it as-is matters: the error output of ipconfig / route is itself the most accurate +/// diagnostic information, and relaying it a second time ourselves would only lose information. [[nodiscard]] Status RunOrFail(std::string_view executable, const std::vector& arguments, std::string_view what) { TETHERKITNEXT_ASSIGN_OR_RETURN(const ProcessResult result, RunTool(executable, arguments)); if (!result.Succeeded()) { std::string detail{result.output}; - // Tool output often has a trailing newline, which looks ugly when spliced into a single-line error. + // Tool output often has a trailing newline, which looks ugly when spliced into a single-line + // error. while (!detail.empty() && (detail.back() == '\n' || detail.back() == '\r')) { detail.pop_back(); } @@ -130,8 +142,8 @@ constexpr int kDhcpStableSamples = 8; /// Reads the interface's current IPv4 address; returns std::nullopt when there is no address. /// -/// Uses ioctl rather than `ipconfig getifaddr`: this is the real state in the kernel, going through no -/// intermediate layer, and needs no forked process. +/// Uses ioctl rather than `ipconfig getifaddr`: this is the real state in the kernel, going through +/// no intermediate layer, and needs no forked process. [[nodiscard]] std::optional QueryAddress(std::string_view interface_name, unsigned long request) noexcept { const int fd = ::socket(AF_INET, SOCK_DGRAM, 0); @@ -164,8 +176,9 @@ constexpr int kDhcpStableSamples = 8; /// Finds the service ID that IPConfiguration established for this interface. /// /// The approach is to enumerate `State:/Network/Service//IPv4` and match by `InterfaceName`, -/// rather than **guessing** how the service ID is spelled. Measured, the ID obtained from `ipconfig set feth0 DHCP` is -/// "DHCP-feth0", which looks like it could be assembled directly, but that is an implementation detail, and matching by field is what is reliable. +/// rather than **guessing** how the service ID is spelled. Measured, the ID obtained from `ipconfig +/// set feth0 DHCP` is "DHCP-feth0", which looks like it could be assembled directly, but that is an +/// implementation detail, and matching by field is what is reliable. [[nodiscard]] std::optional FindServiceId(SCDynamicStoreRef store, std::string_view interface_name) { const ScopedCFRef pattern = MakeCFString("State:/Network/Service/[^/]+/IPv4"); @@ -258,14 +271,15 @@ constexpr int kDhcpStableSamples = 8; /// Writes DNS servers onto the service that IPConfiguration established. /// -/// WARNING: **A move not verified on real hardware.** What is confirmed is that hand-**fabricating** a whole service is not adopted by IPMonitor -/// (GUI-SPIKE section 3.2). The bet here is that "adding a DNS key onto a service that is **already properly registered** -/// will be adopted". Losing the bet is not destructive, DNS just does not take effect -- so failures are only -/// logged and never make the whole static IP configuration fail. The real result is reported by the readback in tk_net_query. +/// Not verified on real hardware. What is confirmed is that a hand-fabricated service is not +/// adopted by IPMonitor (docs/MACOS-NETWORKING-NOTES.md). Assumption: adding a DNS key onto a +/// service that is already properly registered will be adopted. If it is not, DNS simply does not +/// take effect, so failures are only logged and never make the whole static IP configuration fail. +/// The real result is reported by the readback in tk_net_query. /// -/// Also note: values in SCDynamicStore are **held by the session that set them**, and once the session is released the values are gone. -/// So a process-wide long-lived store is used here (see the explanation of SharedDynamicStore), -/// and it must never be changed to a locally created one. +/// Also note: values in SCDynamicStore are **held by the session that set them**, and once the +/// session is released the values are gone. So a process-wide long-lived store is used here (see +/// the explanation of SharedDynamicStore), and it must never be changed to a locally created one. void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, const std::vector& servers) { if (servers.empty()) { @@ -296,26 +310,29 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, } } -/// Waits for the **newly created** service to publish a **stable** lease, and returns its gateway. +/// Waits for the newly created service to publish a stable lease, and returns its gateway. /// -/// The judgment uses `InterfaceName` + `Addresses` + `Router` in `State:/Network/Service//IPv4`, -/// rather than looking only at the interface address: when an old service has just been removed, the interface still carries the previous address. +/// The judgment uses `InterfaceName` + `Addresses` + `Router` in +/// `State:/Network/Service//IPv4`, rather than looking only at the interface address: when an +/// old service has just been removed, the interface still carries the previous address. /// -/// * Why we also wait for "stable" * -/// Android's USB tethering **first** issues a 464XLAT transitional lease -/// (192.0.0.2 / gateway 192.0.0.1), and only after a few seconds switches to the real 172.19.x.x range. Measured, installing a -/// scoped route from the first one leaves a route pointing to an invalidated gateway after the device changes leases -- -/// and that is exactly the route NetworkExtension uses when it looks up paths per interface. So the gateway must read the same value -/// kDhcpStableSamples times in a row to count as stable. +/// Why we also wait for "stable": +/// Android's USB tethering first issues a 464XLAT transitional lease (192.0.0.2 / gateway +/// 192.0.0.1), and only after a few seconds switches to the real 172.19.x.x range. Measured, +/// installing a scoped route from the first one leaves a route pointing to an invalidated gateway +/// after the device changes leases and that is exactly the route NetworkExtension uses when it +/// looks up paths per interface. So the gateway must read the same value kDhcpStableSamples times +/// in a row to count as stable. /// -/// WARNING: Do not query `ConfigMethod` or the `State` in the DHCP dictionary -- **the dynamic store entries of persistent services -/// do not have these two keys** (measured: a registered service has only Addresses / Router / InterfaceName / -/// AdditionalRoutes, and the DHCP dictionary has only Lease* and Option_*; those two keys appear only on the temporary service that -/// `ipconfig set` establishes). +/// WARNING: Do not query `ConfigMethod` or the `State` in the DHCP dictionary; the dynamic store +/// entries of persistent services do not have these two keys (measured: a registered service has +/// only Addresses / Router / InterfaceName / AdditionalRoutes, and the DHCP dictionary has only +/// Lease* and Option_*; those two keys appear only on the temporary service that `ipconfig set` +/// establishes). /// -/// `service_id` is nullopt on the transient-service fallback (`ipconfig set -/// DHCP`), whose ID is only known once IPConfiguration publishes it; it is then -/// looked up by InterfaceName on every poll. +/// `service_id` is nullopt on the transient-service fallback (`ipconfig set DHCP`), whose ID is +/// only known once IPConfiguration publishes it; it is then looked up by InterfaceName on every +/// poll. [[nodiscard]] std::optional WaitForStableLease( std::string_view interface_name, const std::optional& known_service_id) { SCDynamicStoreRef store = SharedDynamicStore(); @@ -323,7 +340,8 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, return std::nullopt; } - // Read once "the gateway this service currently publishes"; if the address and interface name do not match, treat it as not ready yet. + // Read once "the gateway this service currently publishes"; if the address and interface name do + // not match, treat it as not ready yet. const auto published_router = [&]() -> std::optional { const std::optional address = QueryAddress(interface_name, SIOCGIFADDR); if (!address.has_value()) { @@ -366,15 +384,18 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, /// Installs a default route **bound to this interface**. /// -/// A scoped route (RTF_IFSCOPE) is macOS's per-interface independent default route: traffic bound to that interface uses it, -/// without affecting the system's primary service. IPConfiguration usually installs this one for DHCP services; -/// but when feth becomes the primary service, macOS may keep only the global default route. It is explicitly filled in here, ensuring that -/// callers such as NetworkExtension that do route lookups per interface can still find a path. +/// A scoped route (RTF_IFSCOPE) is macOS's per-interface independent default route: traffic bound +/// to that interface uses it, without affecting the system's primary service. IPConfiguration +/// usually installs this one for DHCP services; but when feth becomes the primary service, macOS +/// may keep only the global default route. It is explicitly filled in here, ensuring that callers +/// such as NetworkExtension that do route lookups per interface can still find a path. /// -/// Delete first and then add, without using `change`: the interface may have a leftover scoped route pointing to the **old gateway** -/// (the device changed leases), and `change` has ambiguous semantics for one with the same destination but already invalid, -/// so deleting and rebuilding is the only way to guarantee exactly one at the end, pointing to the current gateway. A delete failure usually means there was none to begin with, -/// which is a normal situation, so its result is ignored. +/// Delete first and then add, without using `change`: the interface may have a leftover scoped +/// route pointing to the **old gateway** (the device changed leases), and `change` has ambiguous +/// semantics for one with the same destination but already invalid, so deleting and rebuilding is +/// the only way to guarantee exactly one at the end, pointing to the current gateway. A delete +/// failure usually means there was none to begin with, which is a normal situation, so its result +/// is ignored. [[nodiscard]] Status InstallScopedDefaultRoute(std::string_view interface_name, std::string_view router) { const std::vector delete_arguments{ @@ -388,21 +409,21 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, /// Changes the **global** default route to the specified gateway. /// -/// ⚠️ On its own this is not enough to send "all traffic" through the phone: -/// it changes the kernel route but not the DNS resolvers (those follow the -/// primary *service*), and configd reinstalls the primary service's route on -/// the next network change. In DHCP mode the real mechanism is putting the -/// managed service first in the service order (ConfigureManagedDhcpService); -/// this call only makes the switch immediate, and is the whole story only on -/// the transient-service fallback and in static mode. +/// ⚠️ On its own this is not enough to send "all traffic" through the phone: it changes the kernel +/// route but not the DNS resolvers (those follow the primary *service*), and configd reinstalls the +/// primary service's route on the next network change. In DHCP mode the real mechanism is putting +/// the managed service first in the service order (ConfigureManagedDhcpService); this call only +/// makes the switch immediate, and is the whole story only on the transient-service fallback and in +/// static mode. [[nodiscard]] Status PromoteToGlobalDefaultRoute(std::string_view router) { const std::vector arguments{"-n", "change", "-inet", "default", std::string{router}}; if (const auto status = RunOrFail(kRoutePath, arguments, Text(Msg::kCapiWhatSwitchGlobalRoute)); status) { return tetherkitnext::Ok(); } - // The system may currently have no global default route at all (not connected to any network), in which case change fails, - // and add should be used. This is exactly the most typical USB tethering scenario and must be handled. + // The system may currently have no global default route at all (not connected to any network), in + // which case change fails, and add should be used. This is exactly the most typical USB tethering + // scenario and must be handled. const std::vector add_arguments{"-n", "add", "-inet", "default", std::string{router}}; return RunOrFail(kRoutePath, add_arguments, Text(Msg::kCapiWhatAddGlobalRoute)); @@ -411,8 +432,8 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, [[nodiscard]] Status ApplyDhcp(std::string_view interface_name, bool set_default_route) { - // First clear the old service on the same interface. `ipconfig NONE` handles the temporary service left over from before the upgrade; - // the SCNetworkService is the service that DHCP actually uses this time. + // First clear any existing service on the same interface. `ipconfig NONE` removes a temporary + // IPConfiguration service; the SCNetworkService is the service DHCP actually uses. TETHERKITNEXT_RETURN_IF_ERROR(tetherkitnext::capi::RemoveManagedNetworkService(interface_name)); TETHERKITNEXT_RETURN_IF_ERROR( RunOrFail(kIpconfigPath, {"set", std::string{interface_name}, "NONE"}, @@ -424,35 +445,56 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, service_id, tetherkitnext::capi::ConfigureManagedDhcpService(interface_name, set_default_route)); } else { - // SPI gone on this macOS: fall back to the transient IPConfiguration - // service. Ordinary traffic works; only NetworkExtension VPNs lose the - // interface-scoped path (upstream XiaoMiku01/TetherKit#3). + // SPI gone on this macOS: fall back to the transient IPConfiguration service. Ordinary traffic + // works; only NetworkExtension VPNs lose the interface-scoped path. TETHERKITNEXT_RETURN_IF_ERROR( RunOrFail(kIpconfigPath, {"set", std::string{interface_name}, "DHCP"}, Text(Msg::kCapiWhatStartDhcp))); } - // Wait for a stable lease. IPConfiguration gets the lease, configures scoped DNS, and publishes the service to - // the dynamic store; the scoped default route must be filled in explicitly by us (when feth becomes the primary service macOS may keep only the - // global route, and NetworkExtension's scoped query for feth would get "No network route"). + // Wait for a stable lease. IPConfiguration gets the lease, configures scoped DNS, and publishes + // the service to the dynamic store; the scoped default route must be filled in explicitly by us + // (when feth becomes the primary service macOS may keep only the global route, and + // NetworkExtension's scoped query for feth would get "No network route"). const std::optional router = WaitForStableLease(interface_name, service_id); + if (!router.has_value() && set_default_route && service_id.has_value()) { + // "Route all traffic" put our service first in the order before we knew whether the device has + // a router. Without one this is a local link (a drone, a controller, a gadget-mode board): it + // must not outrank the Mac's real internet connection. DHCP keeps running in the background; + // the user can re-apply once a lease with a router exists. + if (const auto demoted = tetherkitnext::capi::DemoteManagedNetworkService(interface_name); + !demoted) { + TETHERKITNEXT_WARN_TR(Msg::kCapiDemoteServiceFailed, demoted.error().ToString()); + } + } if (!router.has_value()) { - // There is no address yet -- the other side is probably not doing tethering, and this is the real timeout. + // There is no address yet: the other side is probably not doing tethering, and this is the real + // timeout. if (!QueryAddress(interface_name, SIOCGIFADDR).has_value()) { return std::unexpected(Error::Generic(Tr(Msg::kCapiDhcpTimeout, kDhcpLeaseTimeout.count()))); } - // There is an address but the gateway never stabilized: install no default route, to avoid leaving one that points to a stale gateway. + // There is an address but the gateway never stabilized: install no default route, to avoid + // leaving one that points to a stale gateway. if (set_default_route) { return std::unexpected(Error::Generic(Tr(Msg::kCapiDhcpNoRouter))); } return tetherkitnext::Ok(); } - TETHERKITNEXT_RETURN_IF_ERROR(InstallScopedDefaultRoute(interface_name, *router)); - if (!set_default_route) { - return tetherkitnext::Ok(); + Status routed = InstallScopedDefaultRoute(interface_name, *router); + if (routed && set_default_route) { + routed = PromoteToGlobalDefaultRoute(*router); + } + if (!routed && set_default_route && service_id.has_value()) { + // Same rule as above: the service was ordered first before we knew routing would work. Without + // a working default route it must not stay primary (it would also own DNS), so hand the Mac + // back to its other connections. + if (const auto demoted = tetherkitnext::capi::DemoteManagedNetworkService(interface_name); + !demoted) { + TETHERKITNEXT_WARN_TR(Msg::kCapiDemoteServiceFailed, demoted.error().ToString()); + } } - return PromoteToGlobalDefaultRoute(*router); + return routed; } [[nodiscard]] Status ApplyManual(std::string_view interface_name, const tk_ip_config_t& config) { @@ -516,21 +558,74 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, [[nodiscard]] Status ApplyNone(std::string_view interface_name) { TETHERKITNEXT_RETURN_IF_ERROR(tetherkitnext::capi::RemoveManagedNetworkService(interface_name)); - return RunOrFail(kIpconfigPath, {"set", std::string{interface_name}, "NONE"}, - Text(Msg::kCapiWhatClearConfig)); + const Status cleared = RunOrFail(kIpconfigPath, {"set", std::string{interface_name}, "NONE"}, + Text(Msg::kCapiWhatClearConfig)); + tetherkitnext::capi::ReconcileSystemDefaultRoute(interface_name); + return cleared; +} + +/// The interface the kernel's IPv4 default route uses; nullopt when there is none. +[[nodiscard]] std::optional KernelDefaultRouteInterface() { + const auto result = RunTool(kRoutePath, {"-n", "get", "-inet", "default"}); + if (!result || !result->Succeeded()) { + return std::nullopt; // "route: writing to routing socket: not in table" + } + constexpr std::string_view kField = "interface: "; + const std::string& output = result->output; + const std::size_t start = output.find(kField); + if (start == std::string::npos) { + return std::nullopt; + } + const std::size_t begin = start + kField.size(); + const std::size_t end = output.find_first_of(" \r\n", begin); + return output.substr(begin, end == std::string::npos ? std::string::npos : end - begin); } } // namespace +namespace tetherkitnext::capi { + +void ReconcileSystemDefaultRoute(std::string_view interface_name) noexcept { + try { + SCDynamicStoreRef store = SharedDynamicStore(); + if (store == nullptr) { + return; + } + const ScopedCFRef key = MakeCFString("State:/Network/Global/IPv4"); + const ScopedCFRef global{ + static_cast(::SCDynamicStoreCopyValue(store, key.Get()))}; + const std::string primary = StringField(global.Get(), CFSTR("PrimaryInterface")); + const std::string router = StringField(global.Get(), CFSTR("Router")); + if (primary.empty() || primary == interface_name || !IsValidIpv4(router)) { + return; // no other primary service, or configd routes through us and will reroute itself + } + const std::optional kernel = KernelDefaultRouteInterface(); + if (kernel.has_value() && *kernel != interface_name) { + return; // a default route through something else exists (the primary, or e.g. a VPN) + } + if (const auto changed = RunTool(kRoutePath, {"-n", "change", "-inet", "default", router}); + !changed || !changed->Succeeded()) { + std::ignore = RunTool(kRoutePath, {"-n", "add", "-inet", "default", router}); + } + TETHERKITNEXT_INFO_TR(Msg::kCapiDefaultRouteRestored, router, primary); + } catch (...) { + // Best effort: this runs on teardown paths that must not throw. + } +} + +} // namespace tetherkitnext::capi + void tk_ip_config_init(tk_ip_config_t* out_config) { if (out_config == nullptr) { return; } *out_config = tk_ip_config_t{}; - // Default DHCP: RNDIS devices almost always come with their own DHCP server, and this is the only option most users need. + // Default DHCP: RNDIS devices almost always come with their own DHCP server, and this is the only + // option most users need. out_config->mode = TK_IP_MODE_DHCP; - // Default is **not** to grab the global default route. It is only needed when a higher-priority connected service exists at the same time, - // while the typical USB tethering scenario is precisely that no other network is available -- then this NIC is naturally the primary service. + // Default is **not** to grab the global default route. It is only needed when a higher-priority + // connected service exists at the same time, while the typical USB tethering scenario is + // precisely that no other network is available; then this NIC is naturally the primary service. out_config->set_default_route = false; } @@ -550,19 +645,30 @@ tk_result_t tk_net_apply(const char* interface_name, const tk_ip_config_t* confi return TK_ERR_PERMISSION; } + // The strings are fixed-size arrays filled by the caller (a Swift tuple copy, the CLI). Force NUL + // termination on a private copy so every later strlen stays inside them. + tk_ip_config_t safe = *config; + const auto nul_terminate = [](auto& field) { field[sizeof(field) - 1] = '\0'; }; + nul_terminate(safe.address); + nul_terminate(safe.netmask); + nul_terminate(safe.router); + for (auto& server : safe.dns) { + nul_terminate(server); + } + Status status = tetherkitnext::Ok(); - switch (config->mode) { + switch (safe.mode) { case TK_IP_MODE_DHCP: - status = ApplyDhcp(interface_name, config->set_default_route); + status = ApplyDhcp(interface_name, safe.set_default_route); break; case TK_IP_MODE_MANUAL: - status = ApplyManual(interface_name, *config); + status = ApplyManual(interface_name, safe); break; case TK_IP_MODE_NONE: status = ApplyNone(interface_name); break; default: - FillGenericError(out_error, Tr(Msg::kCapiUnknownIpMode, config->mode)); + FillGenericError(out_error, Tr(Msg::kCapiUnknownIpMode, safe.mode)); return TK_ERR_INVALID_ARGUMENT; } @@ -584,8 +690,9 @@ tk_result_t tk_net_clear(const char* interface_name, tk_error_t* out_error) { return TK_ERR_PERMISSION; } - // First remove the DNS key we wrote ourselves (if any), then let IPConfiguration tear down the service. - // With the order reversed the service would already be gone, and the key would become an orphan nobody claims. + // First remove the DNS key we wrote ourselves (if any), then let IPConfiguration tear down the + // service. With the order reversed the service would already be gone, and the key would become an + // orphan nobody claims. if (SCDynamicStoreRef store = SharedDynamicStore(); store != nullptr) { if (const std::optional service_id = FindServiceId(store, interface_name); service_id.has_value()) { @@ -614,7 +721,7 @@ tk_result_t tk_net_query(const char* interface_name, tk_net_state_t* out_state, } *out_state = tk_net_state_t{}; - // ---- Address and mask: the real state in the kernel ---- + // Address and mask: the real state in the kernel if (const std::optional address = QueryAddress(interface_name, SIOCGIFADDR); address.has_value()) { out_state->has_address = true; @@ -625,10 +732,11 @@ tk_result_t tk_net_query(const char* interface_name, tk_net_state_t* out_state, CopyText(out_state->netmask, *netmask); } - // ---- Service-level information: gateway, DNS, configuration method ---- + // Service-level information: gateway, DNS, configuration method SCDynamicStoreRef store = SharedDynamicStore(); if (store == nullptr) { - // Failing to get the dynamic store does not count as a query failure -- the address half is already in hand, so return as usual. + // Failing to get the dynamic store does not count as a query failure; the address half is + // already in hand, so return as usual. return TK_OK; } @@ -640,12 +748,14 @@ tk_result_t tk_net_query(const char* interface_name, tk_net_state_t* out_state, CopyText(out_state->router, router); out_state->has_default_route = true; } - // ConfigMethod / State are published only by temporary services; persistent services do not have these two keys, so here we infer the configuration method and service state from + // ConfigMethod / State are published only by temporary services; persistent services do not + // have these two keys, so here we infer the configuration method and service state from // "whether the DHCP lease dictionary exists", to keep the UI from showing blanks. // - // WARNING: The criterion must be **the dictionary itself**; do not read LeaseStartTime inside it -- that value is a - // **CFDate, not a CFString**, so StringField would always return an empty string, and every DHCP - // service would then be misjudged as MANUAL (this wrong badge really did appear in the UI). + // WARNING: The criterion must be **the dictionary itself**; do not read LeaseStartTime inside + // it: that value is a **CFDate, not a CFString**, so StringField would always return an empty + // string, and every DHCP service would then be misjudged as MANUAL (this wrong badge really did + // appear in the UI). const ScopedCFRef dhcp = CopyServiceEntry(store, *service_id, "DHCP"); std::string method = StringField(ipv4.Get(), CFSTR("ConfigMethod")); @@ -660,8 +770,9 @@ tk_result_t tk_net_query(const char* interface_name, tk_net_state_t* out_state, } CopyText(out_state->service_state, service_state); - // DNS is always read back from **what is actually in effect in the system**, rather than restating the values we applied -- - // in static mode whether DNS takes effect depends on whether IPMonitor accepts it, and only a readback is accurate. + // DNS is always read back from **what is actually in effect in the system**, rather than + // restating the values we applied; in static mode whether DNS takes effect depends on whether + // IPMonitor accepts it, and only a readback is accurate. const ScopedCFRef dns = CopyServiceEntry(store, *service_id, "DNS"); const std::vector servers = StringArrayField(dns.Get(), CFSTR("ServerAddresses")); for (const std::string& server : servers) { diff --git a/src/capi/net_config.h b/src/capi/net_config.h new file mode 100644 index 0000000..bf36a8e --- /dev/null +++ b/src/capi/net_config.h @@ -0,0 +1,23 @@ +// Network configuration helpers shared inside the C ABI implementation. +#pragma once + +#include + +namespace tetherkitnext::capi { + +/// Makes the kernel's IPv4 default route match what configd says it should be. +/// +/// "Route all traffic" in manual mode (and on the transient `ipconfig set DHCP` fallback) changes +/// the kernel's default route directly, so configd never sees our interface as the primary service. +/// When the configuration is cleared or the interface is destroyed, the kernel drops that route and +/// configd, whose primary service never changed, has no reason to reinstall the Wi-Fi/Ethernet one: +/// the Mac would be left without a default route until the next network change. +/// +/// Reads `State:/Network/Global/IPv4` (configd's current primary interface and router) and, only if +/// the kernel route is missing or still goes through `interface_name`, points it back at that +/// router. Never touches a route owned by something else (e.g. a VPN), and does nothing while +/// configd itself considers `interface_name` primary (it reroutes on its own when our service goes +/// away). Idempotent, best effort, never throws. +void ReconcileSystemDefaultRoute(std::string_view interface_name) noexcept; + +} // namespace tetherkitnext::capi diff --git a/src/capi/orphan_cleanup.cc b/src/capi/orphan_cleanup.cc index 6f10ed0..ee6cfc4 100644 --- a/src/capi/orphan_cleanup.cc +++ b/src/capi/orphan_cleanup.cc @@ -1,23 +1,28 @@ // Registration and cleanup of orphaned feth NICs. // -// * The problem to solve * -// FethInterface is RAII, and on normal exit the NIC is destroyed. But **when a process is SIGKILLed -// destructors do not run at all**, and the NIC stays in the kernel forever -- and SIGKILL cannot be intercepted by any signal -// handler, so "install a signal handler" cannot solve this. +// The problem to solve: +// FethInterface is RAII, and on normal exit the NIC is destroyed. But **when a process is +// SIGKILLed destructors do not run at all**, and the NIC stays in the kernel forever, and SIGKILL +// cannot be intercepted by any signal handler, so "install a signal handler" cannot solve this. // -// The only reliable backstop is to persist the names of created interfaces to disk and clean up on the next launch. This file is the implementation -// of that persistence and cleanup. +// The only reliable backstop is to persist the names of created interfaces to disk and clean up +// on the next launch. This file is the implementation of that persistence and cleanup. // -// * Why not "destroy all feth at startup" * -// feth is a shared facility, and other programs (or the user manually running ifconfig) may be using it too. Destroying only the ones -// we registered ourselves avoids collateral damage. +// Why not "destroy all feth at startup": +// feth is a shared facility, and other programs (or the user manually running ifconfig) may be +// using it too. Destroying only the ones we registered ourselves avoids collateral damage. +#include "tetherkitnext/capi/tetherkitnext_c.h" +#include "tetherkitnext/common/i18n.h" +#include "tetherkitnext/common/logging.h" +#include "tetherkitnext/net/feth_device.h" + +#include #include #include +#include #include #include - -#include #include #include #include @@ -29,10 +34,7 @@ #include "capi_support.h" #include "managed_network_service.h" -#include "tetherkitnext/capi/tetherkitnext_c.h" -#include "tetherkitnext/common/i18n.h" -#include "tetherkitnext/common/logging.h" -#include "tetherkitnext/net/feth_device.h" +#include "net_config.h" namespace { @@ -45,12 +47,13 @@ using tetherkitnext::capi::IsValidFethName; /// Path of the registry file. /// -/// Placed in /var/run (= /private/var/run) rather than /tmp: only root can write here, and being able to write -/// this file is equivalent to being able to make us destroy interfaces of arbitrary names -- although the feth name validation -/// is a backstop, tightening permissions to root-only is the correct first line of defense. +/// Placed in /var/run (= /private/var/run) rather than /tmp: only root can write here, and being +/// able to write this file is equivalent to being able to make us destroy interfaces of arbitrary +/// names; although the feth name validation is a backstop, tightening permissions to +/// root-only is the correct first line of defense. /// -/// At system reboot /var/run is cleared, and a reboot also clears all feth along the way -- the lifecycles of the two -/// coincide exactly, so no extra handling of stale entries is needed. +/// At system reboot /var/run is cleared, and a reboot also clears all feth along the way; the +/// lifecycles of the two coincide exactly, so no extra handling of stale entries is needed. constexpr const char* kRegistryPath = "/var/run/tetherkitnext-interfaces"; std::mutex& RegistryMutex() { @@ -58,9 +61,9 @@ std::mutex& RegistryMutex() { return mutex; } -/// One registry line: interface name plus the PID of the process that created -/// it. Lines written by older versions carry no PID and parse as pid 0 -/// ("owner unknown"), which cleanup treats as an orphan — the old behaviour. +/// One registry line: interface name plus the PID of the process that created it. Lines written by +/// older versions carry no PID and parse as pid 0 ("owner unknown"), which cleanup treats as an +/// orphan. struct RegistryEntry { std::string name; ::pid_t owner = 0; @@ -74,7 +77,8 @@ struct RegistryEntry { } std::string line; while (std::getline(input, line)) { - // Strip possible trailing whitespace, then validate the name once more -- file content is always treated as untrusted input. + // Strip possible trailing whitespace, then validate the name once more; file content is always + // treated as untrusted input. while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) { line.pop_back(); } @@ -98,28 +102,58 @@ struct RegistryEntry { } void WriteRegistry(const std::vector& entries) noexcept { - // If the list is empty, delete the file, to avoid leaving an empty file that makes people think there are still leftovers. + // If the list is empty, delete the file, to avoid leaving an empty file that makes people think + // there are still leftovers. if (entries.empty()) { ::unlink(kRegistryPath); return; } - std::ofstream output{kRegistryPath, std::ios::trunc}; - if (!output) { + std::string content; + for (const RegistryEntry& entry : entries) { + content += entry.name; + content += ' '; + content += std::to_string(entry.owner); + content += '\n'; + } + + // Write a temporary file and rename it over the registry: a crash mid-write then leaves the old + // registry instead of a truncated one (which would leak every interface it listed), and + // O_NOFOLLOW + O_EXCL mean root never writes through a planted symlink. + const std::string temporary = std::string{kRegistryPath} + ".tmp"; + ::unlink(temporary.c_str()); + const int fd = + ::open(temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd < 0) { return; } - for (const RegistryEntry& entry : entries) { - output << entry.name << ' ' << entry.owner << '\n'; + const char* cursor = content.data(); + std::size_t remaining = content.size(); + bool ok = true; + while (remaining > 0) { + const ssize_t written = ::write(fd, cursor, remaining); + if (written < 0) { + if (errno == EINTR) { + continue; + } + ok = false; + break; + } + cursor += written; + remaining -= static_cast(written); + } + ok = (::close(fd) == 0) && ok; + if (!ok || ::rename(temporary.c_str(), kRegistryPath) != 0) { + ::unlink(temporary.c_str()); } } /// Whether `pid` is a live process other than ourselves. /// -/// Cleanup must never destroy interfaces that belong to a *running* session in -/// another process (e.g. the legacy LaunchDaemon still alive while the new -/// SMAppService daemon starts, or two helper builds side by side). Before the -/// registry recorded owners, the second process's startup cleanup would tear -/// down the first one's live feth pair. PID reuse can only make us keep an -/// entry we could have removed — the safe direction. +/// Cleanup must never destroy interfaces that belong to a *running* session in another process +/// (e.g. the legacy LaunchDaemon still alive while the new SMAppService daemon starts, or two +/// helper builds side by side). Before the registry recorded owners, the second process's startup +/// cleanup would tear down the first one's live feth pair. PID reuse can only make us keep an entry +/// we could have removed; the safe direction. [[nodiscard]] bool IsOtherLiveProcess(::pid_t pid) noexcept { if (pid <= 0 || pid == ::getpid()) { return false; @@ -129,22 +163,31 @@ void WriteRegistry(const std::vector& entries) noexcept { /// The callback installed for net::SetInterfaceRegistry. /// -/// Every create/destroy reads and rewrites the whole file. It sounds wasteful, but a session creates only two NICs, -/// and switching to "append only" would require handling line deletion on destroy and file growth, which is not worth the complexity. +/// Every create/destroy reads and rewrites the whole file. It sounds wasteful, but a session +/// creates only two NICs, and switching to "append only" would require handling line deletion on +/// destroy and file growth, which is not worth the complexity. void OnInterfaceChanged(std::string_view name, bool created) noexcept { - // The whole callback must be noexcept -- the destroy path may be in a destructor. fstream does not throw by default - // (no exceptions() setting), while the SystemConfiguration cleanup explicitly catches exceptions. + // The whole callback must be noexcept: the destroy path may be in a destructor. fstream does not + // throw by default (no exceptions() setting), while the SystemConfiguration cleanup explicitly + // catches exceptions. { const std::lock_guard guard(RegistryMutex()); std::vector entries = ReadRegistry(); if (created) { - for (const RegistryEntry& existing : entries) { + // A stale entry with the same name (left by a process that died) must take the new owner: + // keeping the dead PID would let the next startup cleanup treat this live interface as an + // orphan and destroy it. + bool found = false; + for (RegistryEntry& existing : entries) { if (existing.name == name) { - return; + existing.owner = ::getpid(); + found = true; } } - entries.push_back(RegistryEntry{.name = std::string{name}, .owner = ::getpid()}); + if (!found) { + entries.push_back(RegistryEntry{.name = std::string{name}, .owner = ::getpid()}); + } } else { std::erase_if(entries, [name](const RegistryEntry& entry) { return entry.name == name; }); } @@ -152,8 +195,8 @@ void OnInterfaceChanged(std::string_view name, bool created) noexcept { } if (!created) { - // When the NIC is gone, the network service registered for it should go too, otherwise a dead entry pointing to a nonexistent interface - // would be left in "System Settings -> Network". + // When the NIC is gone, the network service registered for it should go too, otherwise a dead + // entry pointing to a nonexistent interface would be left in "System Settings -> Network". try { if (const auto status = tetherkitnext::capi::RemoveManagedNetworkService(name); !status) { TETHERKITNEXT_WARN_TR(Msg::kCapiServiceRemoveFailed, name, status.error().ToString()); @@ -161,6 +204,9 @@ void OnInterfaceChanged(std::string_view name, bool created) noexcept { } catch (...) { TETHERKITNEXT_WARN_TR(Msg::kCapiServiceRemoveFailed, name, Text(Msg::kCapiCommandNoOutput)); } + // If "route all traffic" pointed the kernel's default route at this interface behind configd's + // back, destroying it left the Mac without one; put configd's back. + tetherkitnext::capi::ReconcileSystemDefaultRoute(name); } } @@ -184,25 +230,29 @@ tk_result_t tk_cleanup_orphan_interfaces(size_t* out_removed, tk_error_t* out_er return TK_ERR_PERMISSION; } - // WARNING: The destroy loop **must never** hold RegistryMutex: after DestroyInterfaceByName succeeds it - // triggers the registration callback, and the callback takes the same lock -- std::mutex is not reentrant, and going in holding it is an instant - // self-wait deadlock. So "read", "destroy" and "wrap-up" are split into three phases here, with the lock held only in the first and last. + // WARNING: The destroy loop **must never** hold RegistryMutex: after DestroyInterfaceByName + // succeeds it triggers the registration callback, and the callback takes the same lock; + // std::mutex is not reentrant, and going in holding it is an instant self-wait deadlock. So + // "read", "destroy" and "wrap-up" are split into three phases here, with the lock held only in + // the first and last. std::vector entries; { const std::lock_guard guard(RegistryMutex()); entries = ReadRegistry(); } - // Setup:/Network/Service persists across processes and even reboots. Sweeping away the feth services marked TetherKitNext first - // is what covers the case where the helper was SIGKILLed last time and the system then rebooted: by then - // the interface registration in /var/run is gone, but the services in the network preferences may still remain. + // Setup:/Network/Service persists across processes and even reboots. Sweeping away the feth + // services marked TetherKitNext first is what covers the case where the helper was SIGKILLed last + // time and the system then rebooted: by then the interface registration in /var/run is gone, but + // the services in the network preferences may still remain. // - // Skipped while another live process still owns registered interfaces: its - // services are not stale, and deleting them would cut that session's - // network. The next cleanup after it exits catches anything left behind. + // Skipped while another live process still owns registered interfaces: its services are not + // stale, and deleting them would cut that session's network. The next cleanup after it exits + // catches anything left behind. // - // Failures are only logged: cleaning NICs matters far more than cleaning services, and one service that cannot be deleted must not block the whole round of backstop - // cleanup (a leftover feth would keep occupying kernel resources). + // Failures are only logged: cleaning NICs matters far more than cleaning services, and one + // service that cannot be deleted must not block the whole round of backstop cleanup (a leftover + // feth would keep occupying kernel resources). const bool another_session_alive = std::ranges::any_of( entries, [](const RegistryEntry& entry) { return IsOtherLiveProcess(entry.owner); }); if (!another_session_alive) { @@ -219,12 +269,13 @@ tk_result_t tk_cleanup_orphan_interfaces(size_t* out_removed, tk_error_t* out_er std::vector still_owned; for (const RegistryEntry& entry : entries) { if (IsOtherLiveProcess(entry.owner)) { - // Belongs to a session that is still running elsewhere — not an orphan. + // Belongs to a session that is still running elsewhere, not an orphan. still_owned.push_back(entry); continue; } - // The most common reason for a destroy failure is that the interface no longer exists (for example the system was rebooted), which is exactly what we - // want. Real failures are only logged and do not block the remaining entries. + // The most common reason for a destroy failure is that the interface no longer exists (for + // example the system was rebooted), which is exactly what we want. Real failures are only + // logged and do not block the remaining entries. if (const auto status = tetherkitnext::net::DestroyInterfaceByName(entry.name); status) { ++removed; continue; @@ -232,8 +283,9 @@ tk_result_t tk_cleanup_orphan_interfaces(size_t* out_removed, tk_error_t* out_er TETHERKITNEXT_DEBUG_TR(Msg::kCapiOrphanAlreadyGone, entry.name); } - // Wrap-up: those that could be destroyed were already deleted row by row by the callback, and what remains are entries that "were not in the kernel to begin with", - // and leaving them would only make the next launch retry repeatedly, so clear them all -- but keep entries that are still + // Wrap-up: those that could be destroyed were already deleted row by row by the callback, and + // what remains are entries that "were not in the kernel to begin with", and leaving them would + // only make the next launch retry repeatedly, so clear them all, but keep entries that are still // owned by a live process. { const std::lock_guard guard(RegistryMutex()); diff --git a/src/capi/process_runner.cc b/src/capi/process_runner.cc index 80df01d..182fc58 100644 --- a/src/capi/process_runner.cc +++ b/src/capi/process_runner.cc @@ -1,6 +1,8 @@ -#include "tetherkitnext/common/i18n.h" #include "process_runner.h" +#include "tetherkitnext/common/i18n.h" + +#include #include #include #include @@ -34,10 +36,10 @@ std::string ReadAll(int fd) { Result Spawn(std::string_view executable, const std::vector& arguments) { - // ---- Assemble argv ---- + // Assemble argv // - // posix_spawn wants char* const[], while we only have const strings. These pointers are not modified before - // posix_spawn returns, so passing them this way is legal per POSIX. + // posix_spawn wants char* const[], while we only have const strings. These pointers are not + // modified before posix_spawn returns, so passing them this way is legal per POSIX. const std::string executable_path{executable}; std::vector argv; argv.reserve(arguments.size() + 2); @@ -47,7 +49,7 @@ Result Spawn(std::string_view executable, } argv.push_back(nullptr); - // ---- Create pipes to collect output ---- + // Create pipes to collect output std::array pipe_fds{-1, -1}; if (::pipe(pipe_fds.data()) != 0) { return std::unexpected(Error::FromErrno(0, Tr(Msg::kCapiPipeFailed))); @@ -59,27 +61,44 @@ Result Spawn(std::string_view executable, ::close(pipe_fds[1]); 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. + // 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); ::posix_spawn_file_actions_addclose(&actions, pipe_fds[1]); - // Run system tools with a fixed, minimal environment instead of inheriting - // ours. This code runs as root; an inherited environment (DYLD_*, locale - // overrides, TMPDIR, ...) is attacker-influenced input for no benefit — - // ipconfig/route need nothing from it. LANG=C also keeps their error output - // stable for the messages we surface. + // Run system tools with a fixed, minimal environment instead of inheriting ours. This code runs + // as root; an inherited environment (DYLD_*, locale overrides, TMPDIR, ...) is + // attacker-influenced input for no benefit; ipconfig/route need nothing from it. LANG=C also + // keeps their error output stable for the messages we surface. static char kPathVar[] = "PATH=/usr/bin:/bin:/usr/sbin:/sbin"; 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. + // 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. ::close(pipe_fds[1]); if (spawn_rc != 0) { @@ -88,8 +107,8 @@ Result Spawn(std::string_view executable, Error::FromErrno(spawn_rc, Tr(Msg::kCapiExecFailed, executable_path))); } - // Must **drain the pipe first and then waitpid**: the other way around, the child fills the pipe buffer (64 KiB) - // and blocks on write, while we block on waitpid, and neither side moves. + // Must **drain the pipe first and then waitpid**: the other way around, the child fills the pipe + // buffer (64 KiB) and blocks on write, while we block on waitpid, and neither side moves. ProcessResult result; result.output = ReadAll(pipe_fds[0]); ::close(pipe_fds[0]); @@ -105,7 +124,8 @@ Result Spawn(std::string_view executable, if (WIFEXITED(status)) { result.exit_code = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { - // Killed by a signal: expressed as 128+signo, consistent with shell convention, making it easy to investigate against the logs. + // Killed by a signal: expressed as 128+signo, consistent with shell convention, making it easy + // to investigate against the logs. result.exit_code = 128 + WTERMSIG(status); } else { result.exit_code = -1; diff --git a/src/capi/process_runner.h b/src/capi/process_runner.h index 8ac561e..ff58a33 100644 --- a/src/capi/process_runner.h +++ b/src/capi/process_runner.h @@ -1,15 +1,16 @@ // Runs system tools (ipconfig / route) and collects their output. // -// * Why not system() / popen() * -// Both of them go through /bin/sh. Although we validate arguments such as NIC names and IP addresses, as long as -// they go through a shell the line of defense depends on the single point "did validation miss anything"; with posix_spawn passing the argv -// array directly, shell metacharacters in principle have no place that interprets them. +// Why not system() / popen(): +// Both go through /bin/sh. Even though arguments such as NIC names and IP addresses are +// validated, a shell makes the defense depend on a single point ("did validation miss anything"). +// With posix_spawn passing the argv array directly, shell metacharacters have nothing that +// interprets them. // -// * Why use external tools rather than issuing ioctls ourselves * -// `ipconfig set` takes IPConfiguration's proper registration path, and services it establishes are adopted by -// IPMonitor (DNS takes effect, the default route gets installed); while addresses configured by our own SIOCAIFADDR -// are not recognized by configd at all. This was confirmed by measurement in sections 3.2 / 6.3 of docs/GUI-SPIKE.md, -// and we must not regress to bare ioctls just to "save one fork". +// Why external tools rather than our own ioctls: +// `ipconfig set` takes IPConfiguration's proper registration path, and the services it +// establishes are adopted by IPMonitor (DNS takes effect, the default route gets installed). +// Addresses configured by our own SIOCAIFADDR are not recognized by configd at all (measured, see +// docs/MACOS-NETWORKING-NOTES.md). Do not fall back to bare ioctls just to save one fork. #pragma once #include @@ -25,8 +26,9 @@ struct ProcessResult { int exit_code = 0; /// The combined content of the child process's stdout and stderr. /// - /// Combining is deliberate: some of these tools' errors go to stdout and some to stderr, and collecting them separately would only make - /// the situation "it failed but we did not get the reason" more common. + /// Combining is intentional: some of these tools' errors go to stdout and some to stderr, and + /// collecting them separately would only make the situation "it failed but we did not get the + /// reason" more common. std::string output; [[nodiscard]] bool Succeeded() const noexcept { return exit_code == 0; } @@ -34,12 +36,15 @@ struct ProcessResult { /// Runs an executable and waits for it to finish. /// -/// @param executable An absolute path. It must be an absolute path -- depending on PATH would make behavior vary with the caller's -/// environment, and the helper is launched by launchd, whose PATH differs from a terminal's. +/// @param executable An absolute path. It must be an absolute path: depending on PATH would make +/// behavior vary with the caller's +/// environment, and the helper is launched by launchd, whose PATH differs from a +/// terminal's. /// @param arguments Excluding argv[0], which the function adds internally. /// -/// Returning an error only means "could not get the process running or did not get to wait for it to finish"; if the process ran but returned non-zero, that is a -/// successful return of a ProcessResult with exit_code != 0 -- the caller must judge it themselves. +/// Returning an error only means "could not get the process running or did not get to wait for it +/// to finish"; if the process ran but returned non-zero, that is a successful return of a +/// ProcessResult with exit_code != 0; the caller must judge it themselves. [[nodiscard]] Result RunTool(std::string_view executable, std::initializer_list arguments); diff --git a/src/capi/session.cc b/src/capi/session.cc index 01b8299..3760a00 100644 --- a/src/capi/session.cc +++ b/src/capi/session.cc @@ -1,11 +1,20 @@ // The session's C ABI: lifecycle, state snapshots, event polling. // -// This layer has almost no logic and does only three things: POD configuration -> RuntimeConfig, RuntimeSnapshot -> -// POD status, RuntimeEvent -> ring queue. The real orchestration is all in core::Runtime. +// This layer has almost no logic and does only three things: POD configuration -> RuntimeConfig, +// RuntimeSnapshot -> POD status, RuntimeEvent -> ring queue. The real orchestration is all in +// core::Runtime. +#include "tetherkitnext/capi/tetherkitnext_c.h" +#include "tetherkitnext/common/i18n.h" +#include "tetherkitnext/common/time.h" +#include "tetherkitnext/core/runtime.h" +#include "tetherkitnext/net/feth_device.h" +#include "tetherkitnext/rndis/state_machine.h" + #include #include #include #include +#include #include #include #include @@ -14,12 +23,6 @@ #include #include "capi_support.h" -#include "tetherkitnext/capi/tetherkitnext_c.h" -#include "tetherkitnext/common/i18n.h" -#include "tetherkitnext/common/time.h" -#include "tetherkitnext/core/runtime.h" -#include "tetherkitnext/net/feth_device.h" -#include "tetherkitnext/rndis/state_machine.h" namespace { @@ -33,9 +36,10 @@ using tetherkitnext::core::RuntimeEvent; // --------------------------------------------------------------------------- // Enum value alignment check // -// The C-side enums are values copied from the C++ side, and the two sides are directly cast to each other relying on "the order happening to be the same". This coupling -// silently misaligns as soon as someone inserts an enum value in the middle (the UI shows the wrong state, with no error whatsoever), -// so it is welded shut at compile time. +// The C-side enums are values copied from the C++ side, and the two sides are directly cast to each +// other relying on "the order happening to be the same". This coupling silently misaligns as soon +// as someone inserts an enum value in the middle (the UI shows the wrong state, with no error +// whatsoever), so it is welded shut at compile time. // --------------------------------------------------------------------------- static_assert(static_cast(RunState::kIdle) == TK_RUN_IDLE); static_assert(static_cast(RunState::kStarting) == TK_RUN_STARTING); @@ -60,9 +64,11 @@ static_assert(static_cast(RuntimeEvent::Kind::kRunState) == TK_EVENT_RUN_ST /// Event ring buffer. /// -/// Basis for capacity 128: events are produced only at state transitions, and a full startup sequence is about 10. 128 -/// is enough to cover continuous events such as "the device being repeatedly plugged and unplugged + link flapping", and the GUI drains it every 500 ms. -/// When full, drop the oldest -- events are only used for animation and hints, the authoritative state is in the snapshot, and missing a few does not affect correctness. +/// Basis for capacity 128: events are produced only at state transitions, and a full startup +/// sequence is about 10. 128 is enough to cover continuous events such as "the device being +/// repeatedly plugged and unplugged + link flapping", and the GUI drains it every 500 ms. When +/// full, drop the oldest: events are only used for animation and hints, the authoritative state is +/// in the snapshot, and missing a few does not affect correctness. constexpr std::size_t kEventRingCapacity = 128; class EventRing final : public tetherkitnext::core::RuntimeEventSink { @@ -105,10 +111,19 @@ class EventRing final : public tetherkitnext::core::RuntimeEventSink { std::size_t count_ = 0; }; +/// KiB from the C ABI to bytes, saturating instead of wrapping: 4 GiB / 1024 KiB or more would wrap +/// to a tiny buffer (or 0, which then reads as "use the default"). +[[nodiscard]] constexpr std::uint32_t KibToBytes(std::uint32_t kib) noexcept { + constexpr std::uint32_t kMaxKib = 0xFFFF'FFFFU / 1024; + return (kib > kMaxKib ? kMaxKib : kib) * 1024; +} + /// Takes a value; 0 is treated as "use the library default". /// -/// Be lenient with tuning knobs rather than reporting an error: the GUI may care only about the MTU and leave the other fields empty, and insisting they -/// be non-zero would only force callers to copy the defaults -- and the copied constants would sooner or later drift out of sync with the library's. +/// Be lenient with tuning knobs rather than reporting an error: the GUI may care only about the MTU +/// and leave the other fields empty, and insisting they be non-zero would only force callers to +/// copy the defaults, and the copied constants would sooner or later drift out of sync with the +/// library's. [[nodiscard]] std::uint32_t OrDefault(std::uint32_t value, std::uint32_t fallback) noexcept { return value != 0 ? value : fallback; } @@ -131,11 +146,11 @@ class EventRing final : public tetherkitnext::core::RuntimeEventSink { result.data_channel.tx_transfer_count = OrDefault(config.tx_transfer_count, defaults.data_channel.tx_transfer_count); result.data_channel.rx_transfer_bytes = - OrDefault(config.rx_transfer_kib * 1024, defaults.data_channel.rx_transfer_bytes); + OrDefault(KibToBytes(config.rx_transfer_kib), defaults.data_channel.rx_transfer_bytes); result.rndis.host_max_transfer_size = - OrDefault(config.max_transfer_kib * 1024, defaults.rndis.host_max_transfer_size); + OrDefault(KibToBytes(config.max_transfer_kib), defaults.rndis.host_max_transfer_size); result.bpf.kernel_buffer_bytes = - OrDefault(config.bpf_buffer_kib * 1024, defaults.bpf.kernel_buffer_bytes); + OrDefault(KibToBytes(config.bpf_buffer_kib), defaults.bpf.kernel_buffer_bytes); result.event_sink = &sink; return result; @@ -145,10 +160,10 @@ class EventRing final : public tetherkitnext::core::RuntimeEventSink { // The session object. // -// * Member declaration order is the reverse of destruction order; it must not be shuffled here * -// events must be declared **before** runtime, so that on destruction runtime goes first -- its destructor -// joins the control thread, and the control thread may push events into events up to the last moment. -// The reverse is a use-after-free. +// Member declaration order is the reverse of destruction order; it must not be shuffled here: +// events must be declared **before** runtime, so that on destruction runtime goes first; its +// destructor joins the control thread, and the control thread may push events into events up to +// the last moment. The reverse is a use-after-free. struct tk_session { EventRing events; std::unique_ptr runtime; @@ -177,8 +192,9 @@ tk_session_t* tk_session_create(const tk_session_config_t* config, tk_error_t* o return nullptr; } - // The session is the only entry point that creates a feth, so installing the registration callback here is enough -- the root-free group of - // interfaces (version, enumeration, preflight) therefore stays free of side effects and never touches /var/run. + // The session is the only entry point that creates a feth, so installing the registration + // callback here is enough; the root-free group of interfaces (version, enumeration, preflight) + // therefore stays free of side effects and never touches /var/run. tetherkitnext::capi::InstallInterfaceRegistry(); auto session = std::unique_ptr(new (std::nothrow) tk_session()); @@ -205,8 +221,9 @@ tk_result_t tk_session_start(tk_session_t* session, tk_error_t* out_error) { if (const auto status = session->runtime->Start(); !status) { FillError(out_error, status.error()); - // The only thing that fails synchronously is the root check (see Runtime::Start); give it a dedicated code, - // so the GUI can pop up "authorization needed" instead of a generic "startup failed". + // The only thing that fails synchronously is the root check (see Runtime::Start); give it a + // dedicated code, so the GUI can pop up "authorization needed" instead of a generic "startup + // failed". return tetherkitnext::net::IsRunningAsRoot() ? TK_ERR_FAILED : TK_ERR_PERMISSION; } return TK_OK; @@ -243,8 +260,9 @@ tk_result_t tk_session_status_get(tk_session_t* session, tk_session_status_t* ou CopyText(out_status->vendor_description, snapshot.device_info.vendor_description); CopyText(out_status->device_description, snapshot.device_description); - // permanent is used rather than current: under RNDIS semantics the device is this NIC, and the peer's ARP table and - // DHCP lease are both built on the permanent address, so showing it in the UI is what matches the entries the user sees in the router. + // permanent is used rather than current: under RNDIS semantics the device is this NIC, and the + // peer's ARP table and DHCP lease are both built on the permanent address, so showing it in the + // UI is what matches the entries the user sees in the router. static_assert(sizeof(out_status->device_mac) == std::tuple_size_v); std::ranges::copy(snapshot.device_info.permanent_address, std::begin(out_status->device_mac)); @@ -262,11 +280,17 @@ tk_result_t tk_session_status_get(tk_session_t* session, tk_session_status_t* ou out_status->link_kernel_drops = snapshot.bridge.link_kernel_drops; out_status->tx_backpressure = snapshot.bridge.tx_backpressure_events; - // The library's own monotonic clock is used to timestamp the snapshot, rather than having the host difference its own clock: - // the real interval between two pulls gets stretched by scheduling, and using the host's timer period as the denominator would overestimate the rate. + // The library's own monotonic clock is used to timestamp the snapshot, rather than having the + // host difference its own clock: the real interval between two pulls gets stretched by + // scheduling, and using the host's timer period as the denominator would overestimate the rate. out_status->monotonic_nanos = static_cast(tetherkitnext::MonotonicNanos()); CopyText(out_status->fatal, snapshot.fatal_message); + + if (const std::uint32_t peer = snapshot.bridge.peer_ipv4; peer != 0) { + std::snprintf(out_status->peer_ipv4, sizeof(out_status->peer_ipv4), "%u.%u.%u.%u", + (peer >> 24) & 0xFFU, (peer >> 16) & 0xFFU, (peer >> 8) & 0xFFU, peer & 0xFFU); + } return TK_OK; } diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 8b49ccb..108d244 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -1,8 +1,8 @@ -# tk_common -- infrastructure layer +# tk_common: infrastructure layer # -# Depends on no upper-layer module, nor on libusb / network system calls. The only external dependency is -# libusb's header files (error.cc needs libusb_error_name to translate error codes), so it is linked -# PRIVATE and libusb is not propagated to users of tk_common. +# Depends on no upper-layer module, nor on libusb / network system calls. The only external +# dependency is libusb's header files (error.cc needs libusb_error_name to translate error codes), +# so it is linked PRIVATE and libusb is not propagated to users of tk_common. add_library( tk_common STATIC diff --git a/src/common/error.cc b/src/common/error.cc index bc22440..8f6a63c 100644 --- a/src/common/error.cc +++ b/src/common/error.cc @@ -11,11 +11,13 @@ namespace { /// Thread-safe strerror. /// -/// std::strerror cannot be used: it returns a pointer to a static buffer, and concurrent calls from multiple threads overwrite each other -/// (which is what clang-tidy's concurrency-mt-unsafe is hinting at). +/// std::strerror cannot be used: it returns a pointer to a static buffer, and concurrent calls from +/// multiple threads overwrite each other (which is what clang-tidy's concurrency-mt-unsafe is +/// hinting at). std::string SafeStrerror(int err) { std::array buffer{}; - // Darwin provides the XSI version of strerror_r, returning int: 0 on success, ERANGE means the buffer is too small. + // Darwin provides the XSI version of strerror_r, returning int: 0 on success, ERANGE means the + // buffer is too small. if (::strerror_r(err, buffer.data(), buffer.size()) != 0) { return std::format("errno {}", err); } @@ -41,8 +43,9 @@ std::string Error::ToString() const { case ErrorDomain::kRndis: { // The mapping from RNDIS_STATUS_* to names exists only in tk_rndis (rndis/protocol.cc); - // tk_common is not allowed to depend on upper-layer modules, so only the raw numeric value is output here -- - // the symbolic name of the status code is spliced into the context string by the rndis layer when it constructs the Error. + // tk_common is not allowed to depend on upper-layer modules, so only the raw numeric value is + // output here; the symbolic name of the status code is spliced into the context string by the + // rndis layer when it constructs the Error. return std::format("{} [RNDIS_STATUS: {:#010x}]", context_, static_cast(code_)); } diff --git a/src/common/i18n.cc b/src/common/i18n.cc index 235442d..8ba4821 100644 --- a/src/common/i18n.cc +++ b/src/common/i18n.cc @@ -1,7 +1,8 @@ #include "tetherkitnext/common/i18n.h" // The declaration of ContextSeparator() is in error.h (which does not want to drag in ), -// and the implementation is at the bottom of this file -- including it lets the compiler verify that the declaration and definition agree. +// and the implementation is at the bottom of this file, including it lets the compiler verify that +// the declaration and definition agree. #include "tetherkitnext/common/error.h" #include @@ -15,7 +16,8 @@ namespace tetherkitnext { namespace { -/// Number of messages. Both tables are fixed-length by it, guaranteeing that "added an enum but missed a translation" blows up at compile time. +/// Number of messages. Both tables are fixed-length by it, guaranteeing that "added an enum but +/// missed a translation" blows up at compile time. constexpr std::size_t kMessageCount = static_cast(Msg::kMessageCount); /// The Chinese table. @@ -32,11 +34,13 @@ constexpr std::array kEnglishTable{ #undef TETHERKITNEXT_MESSAGE }; -/// The current language. Process-wide single state, using an atomic rather than a mutex: every message needs to read it. +/// The current language. Process-wide single state, using an atomic rather than a mutex: every +/// message needs to read it. /// -/// Default is English rather than Chinese: this table's call sites are all over the library's internals, and the host (CLI / GUI) overrides it at startup -/// immediately with SetLanguage. English is chosen as the default because "nobody ever set a language" usually means -/// the caller is a third-party binding, and English is more likely to be understood than Chinese. +/// Default is English rather than Chinese: this table's call sites are all over the library's +/// internals, and the host (CLI / GUI) overrides it at startup immediately with SetLanguage. +/// English is chosen as the default because "nobody ever set a language" usually means the caller +/// is a third-party binding, and English is more likely to be understood than Chinese. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) std::atomic g_language{Language::kEnglish}; @@ -60,8 +64,9 @@ std::atomic g_language{Language::kEnglish}; /// Reads an environment variable; returns an empty view when unset or an empty string. [[nodiscard]] std::string_view ReadEnvironment(const char* name) noexcept { - // getenv is flagged by concurrency-mt-unsafe because it is unsafe when concurrent with setenv. Here it - // is read only once at process startup, before any worker thread is started, and the whole project never calls setenv. + // getenv is flagged by concurrency-mt-unsafe because it is unsafe when concurrent with setenv. + // Here it is read only once at process startup, before any worker thread is started, and the + // whole project never calls setenv. // NOLINTNEXTLINE(concurrency-mt-unsafe) const char* value = std::getenv(name); if (value == nullptr || *value == '\0') { @@ -86,14 +91,16 @@ Language LanguageFromLocaleString(std::string_view locale) noexcept { Language DetectLanguageFromEnvironment() noexcept { // The order follows POSIX: LC_ALL overrides LC_MESSAGES, and LC_MESSAGES overrides LANG. - // TETHERKITNEXT_LANG comes first, so users can change only this program without touching locale settings. + // TETHERKITNEXT_LANG comes first, so users can change only this program without touching locale + // settings. for (const char* name : {"TETHERKITNEXT_LANG", "LC_ALL", "LC_MESSAGES", "LANG"}) { const std::string_view value = ReadEnvironment(name); if (value.empty()) { continue; } - // Once the first non-empty value is found it is decided and we do not look further -- otherwise LANG=zh_CN would be - // interfered with by anything other than an empty value further down, and the semantics would not match POSIX either. + // Once the first non-empty value is found it is decided and we do not look further; otherwise + // LANG=zh_CN would be interfered with by anything other than an empty value further down, and + // the semantics would not match POSIX either. return LanguageFromLocaleString(value); } return Language::kEnglish; @@ -142,14 +149,17 @@ std::string FormatMessage(Msg id, std::format_args args) noexcept { try { return std::vformat(pattern, args); } catch (...) { // NOLINT(bugprone-empty-catch) - // This can only be that the placeholders in a translation do not match the call site (tests will catch it, but at runtime we would rather degrade than - // throw). Fall back to the unsubstituted original text: incomplete information is still better than losing the whole message. + // This can only be that the placeholders in a translation do not match the call site (tests + // will catch it, but at runtime we would rather degrade than throw). Fall back to the + // unsubstituted original text: incomplete information is still better than losing the whole + // message. return std::string{pattern}; } } std::string_view ContextSeparator() noexcept { - // Chinese uses a full-width colon (no spaces around it); English uses a half-width colon plus a space. + // Chinese uses a full-width colon (no spaces around it); English uses a half-width colon plus a + // space. return GetLanguage() == Language::kChinese ? ":" : ": "; } diff --git a/src/common/logging.cc b/src/common/logging.cc index ffb6689..e1ddfc0 100644 --- a/src/common/logging.cc +++ b/src/common/logging.cc @@ -14,25 +14,28 @@ namespace tetherkitnext { namespace { -// Logging configuration is a process-wide single state, naturally a mutable global; after using atomics for thread safety, -// splitting it into a singleton class would only add an indirection layer with no real benefit, so the related checks are exempted wholesale here. +// Logging configuration is a process-wide single state, naturally a mutable global; after using +// atomics for thread safety, splitting it into a singleton class would only add an indirection +// layer with no real benefit, so the related checks are exempted wholesale here. // NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables) -/// Runtime log floor. An atomic rather than a mutex: it is read in the check branch of every log line. +/// Runtime log floor. An atomic rather than a mutex: it is read in the check branch of every log +/// line. std::atomic g_runtime_level{LogLevel::kInfo}; /// Whether to output ANSI colors. Lazily initialized to `isatty(STDERR_FILENO)`. std::atomic g_color_enabled{-1}; -/// Protects the whole-line output to stderr, avoiding interleaving of multi-threaded logs. -/// Logging is not on the data hot path, so lock contention can be ignored. +/// Protects the whole-line output to stderr, avoiding interleaving of multi-threaded logs. Logging +/// is not on the data hot path, so lock contention can be ignored. std::mutex& OutputMutex() { static std::mutex mutex; return mutex; } -/// The log sink installed by the host. sink and user must be updated **as a pair**, so they are protected by OutputMutex -/// rather than two independent atomics -- two atomics cannot be updated atomically together, and a mismatched combination could be read. +/// The log sink installed by the host. sink and user must be updated **as a pair**, so they are +/// protected by OutputMutex rather than two independent atomics; two atomics cannot be updated +/// atomically together, and a mismatched combination could be read. LogSink g_log_sink = nullptr; void* g_log_sink_user = nullptr; @@ -49,8 +52,8 @@ std::string_view CurrentThreadName() { /// Level labels and ANSI color codes. /// -/// Deliberately `const char*` rather than `std::string_view`: these values are fed directly to `%s`, -/// and the `data()` of an empty string_view is nullptr, which is undefined behavior when passed to printf. +/// `const char*` rather than `std::string_view`: these values are fed directly to `%s`, and the +/// `data()` of an empty string_view is nullptr, which is undefined behavior when passed to printf. struct LevelStyle { const char* label; const char* color; @@ -85,7 +88,8 @@ bool ColorEnabled() { /// Formats the current wall-clock time as `HH:MM:SS.mmm`. /// -/// Wall time is used rather than monotonic time: logs are for humans to read and need to line up with other system logs. +/// Wall time is used rather than monotonic time: logs are for humans to read and need to line up +/// with other system logs. void FormatTimestamp(std::array& out) { ::timespec ts{}; ::clock_gettime(CLOCK_REALTIME, &ts); @@ -143,18 +147,19 @@ void EmitLogLine(LogLevel level, std::string_view file, unsigned line, const char* color_off = color ? "\033[0m" : ""; const std::string_view thread_name = CurrentThreadName(); - // Output the whole line with a single fprintf, together with the mutex to guarantee that lines do not interleave. - // std::format is not used, to avoid the possibility of an exception here too -- the logging path must be noexcept. - // file / thread_name / message are string_views that may lack a terminator, - // so `%.*s` is used uniformly to pass the length explicitly. + // Output the whole line with a single fprintf, together with the mutex to guarantee that lines do + // not interleave. std::format is not used, to avoid the possibility of an exception here too; the + // logging path must be noexcept. file / thread_name / message are string_views that may lack a + // terminator, so `%.*s` is used uniformly to pass the length explicitly. const std::lock_guard guard(OutputMutex()); std::fprintf(stderr, "%s%s%s %s [%-10.*s] %.*s:%u %.*s\n", color_on, style.label, color_off, timestamp.data(), static_cast(thread_name.size()), thread_name.data(), static_cast(file.size()), file.data(), line, static_cast(message.size()), message.data()); - // Hand off to the host. Calling inside the lock is deliberate: this way the line order the host sees is exactly the same as on stderr. - // The cost is that the sink must never log again (a self-wait deadlock); this constraint is written in logging.h. + // Hand off to the host. Calling inside the lock is intentional: this way the line order the host + // sees is exactly the same as on stderr. The cost is that the sink must never log again (a + // self-wait deadlock); this constraint is written in logging.h. if (g_log_sink != nullptr) { g_log_sink(level, thread_name, message, g_log_sink_user); } diff --git a/src/common/scheduling.cc b/src/common/scheduling.cc index 1962a49..205a5a7 100644 --- a/src/common/scheduling.cc +++ b/src/common/scheduling.cc @@ -25,7 +25,8 @@ void ConfigureCurrentThread(std::string_view name, ThreadRole role) noexcept { // Passing 0 for relative_priority means the default priority within that QoS class. const int rc = ::pthread_set_qos_class_self_np(qos, 0); if (rc != 0) { - // A QoS setting failure does not affect functionality, only performance, so it only warns and returns no error. + // A QoS setting failure does not affect functionality, only performance, so it only warns and + // returns no error. TETHERKITNEXT_WARN_TR(Msg::kCommonThreadQosFailed, static_cast(qos), rc); } } diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index e59c192..e4d2b71 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -1,4 +1,4 @@ -# tk_core -- data-path bridge and runtime orchestration +# tk_core: data-path bridge and runtime orchestration # # Connects tk_usb's RNDIS data channel to tk_net's link backend and manages the data-path threads. # It is the only layer that depends on all three of the usb / net / rndis modules. diff --git a/src/core/bridge.cc b/src/core/bridge.cc index 59f94a4..9b21c07 100644 --- a/src/core/bridge.cc +++ b/src/core/bridge.cc @@ -14,9 +14,11 @@ namespace { /// Upper limit of a single wait for a free transfer slot under TX backpressure (milliseconds). /// -/// The value only affects the trade-off between two things: the upper bound of shutdown/pause response latency (the flags are re-checked on every wakeup), -/// and the frequency of needless wakeups during the wait. The slot's actual release period is a few hundred microseconds (the completion -/// time of one bulk OUT), and the vast majority of waits are woken early by the completion callback's notify, almost never waiting the full time. +/// The value only affects the trade-off between two things: the upper bound of shutdown/pause +/// response latency (the flags are re-checked on every wakeup), and the frequency of needless +/// wakeups during the wait. The slot's actual release period is a few hundred microseconds (the +/// completion time of one bulk OUT), and the vast majority of waits are woken early by the +/// completion callback's notify, almost never waiting the full time. constexpr std::uint32_t kTxCapacityWaitMillis = 50; /// Converts a byte count to Mbps. @@ -53,10 +55,18 @@ Status Bridge::Start() { } stop_requested_.store(false, std::memory_order_release); - // Let the data channel start receiving first -- it pushes frames into rx_ring_. - // Whether this comes **before** or after starting the injection thread does not matter for ordering (the queue is bounded, and drops - // and counts when full), but opening receiving first lets the link start receiving as soon as it is ready, dropping a few fewer frames. - TETHERKITNEXT_RETURN_IF_ERROR(data_channel_->StartReceiving(*rx_ring_, counters_.rx)); + // Let the data channel start receiving first; it pushes frames into rx_ring_. Whether this comes + // **before** or after starting the injection thread does not matter for ordering (the queue is + // bounded, and drops and counts when full), but opening receiving first lets the link start + // receiving as soon as it is ready, dropping a few fewer frames. + if (auto started = data_channel_->StartReceiving(*rx_ring_, counters_.rx); !started) { + // Some bulk IN transfers may already be in flight (e.g. the device was unplugged halfway + // through submitting). running_ stays false, so Stop() would not shut the channel down, and + // their callbacks would later write into rx_ring_/counters_ after this bridge is destroyed. + // Reclaim them here, while both still exist. + data_channel_->Shutdown(); + return started; + } running_.store(true, std::memory_order_release); receive_injector_ = std::thread([this] { RunReceiveInjector(); }); @@ -78,17 +88,20 @@ void Bridge::Stop() { // --------------------------------------------------------------------------- // Teardown order (a wrong order loses frames or deadlocks) // - // 1. Set the shutdown flag -- the loop conditions of both threads look at it; - // 2. Interrupt the link's blocking read() -- otherwise the TX extractor thread would stay stuck in it; + // 1. Set the shutdown flag: the loop conditions of both threads look at it; + // 2. Interrupt the link's blocking read(): otherwise the TX extractor thread would stay stuck in + // it; // 3. Join the two data-path threads; // 4. Stop the data channel **last**. // // Step 4 must come last, for two reasons: - // * DataChannel::Shutdown() has to wait for all callbacks of in-flight USB transfers to come back, and those callbacks - // write into rx_ring_ -- stopping the channel first and then joining would not be wrong; but conversely, if - // rx_ring_ were destroyed first it would be a use-after-free. The order here guarantees rx_ring_ stays alive throughout. - // * Shutdown() must never be called on the libusb event thread (it would deadlock waiting on itself), - // and here is the thread that calls Stop() (the main thread or the control thread), so it is safe. + // * DataChannel::Shutdown() has to wait for all callbacks of in-flight USB transfers to come + // back, and those callbacks write into rx_ring_; stopping the channel first and then joining + // would not be wrong; but conversely, if rx_ring_ were destroyed first it would be a + // use-after-free. The order here guarantees rx_ring_ stays alive throughout. + // * Shutdown() must never be called on the libusb event thread (it would deadlock waiting on + // itself), and here is the thread that calls Stop() (the main thread or the control thread), + // so it is safe. // --------------------------------------------------------------------------- stop_requested_.store(true, std::memory_order_release); @@ -118,14 +131,15 @@ void Bridge::SetPaused(bool paused) noexcept { return; } - // Wait for the RX injection thread to confirm it has really stopped. Without this step, after this function returns the worker may still - // write a batch of already-taken frames onto the link: it may have just passed the flag check above. + // Wait for the RX injection thread to confirm it has really stopped. Without this step, after + // this function returns the worker may still write a batch of already-taken frames onto the link: + // it may have just passed the flag check above. // - // Wait only when the thread is really running -- before Start() or after Stop() nobody will come to set it, - // and waiting unconditionally would never return. + // Wait only when the thread is really running; before Start() or after Stop() nobody will come to + // set it, and waiting unconditionally would never return. // - // The injector may be parked on the ring's doorbell, so ring it first — - // otherwise it would never loop around to observe paused_. + // The injector may be parked on the ring's doorbell, so ring it first; otherwise it would never + // loop around to observe paused_. rx_ring_->Wake(); while (running_.load(std::memory_order_acquire) && !stop_requested_.load(std::memory_order_acquire) && @@ -141,25 +155,29 @@ void Bridge::RunReceiveInjector() noexcept { std::uint32_t idle_spins = 0; while (!stop_requested_.load(std::memory_order_acquire)) { - // Withdraw the acknowledgement bit first, then judge whether paused. The order must not be reversed -- leaving the previous round's true would make - // SetPaused(true) mistakenly think this thread has already stopped, when it is actually about to go take frames. + // Withdraw the acknowledgement bit first, then judge whether paused. The order must not be + // reversed: leaving the previous round's true would make SetPaused(true) mistakenly think this + // thread has already stopped, when it is actually about to go take frames. rx_paused_ack_.store(false, std::memory_order_release); if (paused_.load(std::memory_order_acquire)) { - // During a reset: do not move data, but do not drop it either -- frames in the queue continue to be sent after resuming. + // During a reset: do not move data, but do not drop it either; frames in the queue continue + // to be sent after resuming. // - // Setting the acknowledgement bit is for SetPaused(true) to see: from here until the next round sees paused_ change back to - // false, this thread will not touch rx_ring_, so this acknowledgement is trustworthy. + // Setting the acknowledgement bit is for SetPaused(true) to see: from here until the next + // round sees paused_ change back to false, this thread will not touch rx_ring_, so this + // acknowledgement is trustworthy. rx_paused_ack_.store(true, std::memory_order_release); - // Sleep, don't yield: yield() returns immediately when nothing else is - // runnable and turns this branch into a 100% CPU spin. Pauses are rare - // (RNDIS soft reset) and a 1 ms resume latency is irrelevant there. + // Sleep, don't yield: yield() returns immediately when nothing else is runnable and turns + // this branch into a 100% CPU spin. Pauses are rare (RNDIS soft reset) and a 1 ms resume + // latency is irrelevant there. std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } - // Gather a batch and then write. The batch session releases slots all at once only at the end of its scope, so all the views taken in the meantime - // remain valid -- this is precisely the precondition for "handing zero-copy to one batch write()". + // Gather a batch and then write. The batch session releases slots all at once only at the end + // of its scope, so all the views taken in the meantime remain valid; this is precisely the + // precondition for "handing zero-copy to one batch write()". rx_batch_.clear(); { auto batch = rx_ring_->BeginBatchRead(); @@ -172,12 +190,9 @@ void Bridge::RunReceiveInjector() noexcept { } if (rx_batch_.empty()) { - // Ring is empty. Spin briefly to cover the "producer is mid-write" - // window, then park until a producer publishes (or stop/pause). - // - // This used to std::this_thread::yield() instead of parking. yield() - // returns immediately when no other thread is runnable, so an idle - // link burned a full core (upstream XiaoMiku01/TetherKit#5). + // Ring is empty. Spin briefly to cover the "producer is mid-write" window, then park until + // a producer publishes (or stop/pause). Spinning on yield() would burn a full core on an + // idle link, because yield() returns at once when no other thread is runnable. if (++idle_spins < config_.rx_spin_before_park) { continue; } @@ -190,25 +205,33 @@ void Bridge::RunReceiveInjector() noexcept { } idle_spins = 0; + // Learn the device's own address (local-link devices often have no DHCP server). A few byte + // loads per frame; see peer_address.h. + for (const FrameView& view : rx_batch_) { + peer_observer_.Observe(view.Bytes()); + } + const auto result = link_->WriteFrames(rx_batch_); if (!result) { - counters_.rx.AddIoError(); + rx_inject_counters_.AddIoError(); TETHERKITNEXT_WARN_TR(Msg::kCoreLinkWriteFailed, rx_batch_.size(), result.error().ToString()); - // A write failure does not exit the thread -- it may just be that the interface is temporarily down. The batch session releases the slots as usual - // (the frames can no longer be delivered, and keeping them would only clog the queue). + // A write failure does not exit the thread; it may just be that the interface is + // temporarily down. The batch session releases the slots as usual (the frames can no longer + // be delivered, and keeping them would only clog the queue). } else { if (result->frames_skipped != 0) { - counters_.rx.AddDroppedOversize(result->frames_skipped); + rx_inject_counters_.AddDroppedOversize(result->frames_skipped); } const auto written = result->frames_written; if (written < rx_batch_.size()) { - // The link did not take the whole batch (the kernel send queue is full). The remaining frames have already been taken out of the queue, - // so they can only be dropped and counted -- this is real packet loss and must be made visible to operators. - counters_.rx.AddDroppedFull(rx_batch_.size() - written); + // The link did not take the whole batch (the kernel send queue is full). The remaining + // frames have already been taken out of the queue, so they can only be dropped and + // counted; this is real packet loss and must be made visible to operators. + rx_inject_counters_.AddDroppedFull(rx_batch_.size() - written); } - // Note: the kernel-side bs_drop is a statistic for the **read** direction, updated by the TX extractor thread - // from the ReadFrames result, and is not touched here. + // Note: the kernel-side bs_drop is a statistic for the **read** direction, updated by the + // TX extractor thread from the ReadFrames result, and is not touched here. } } // batch session destructor -> one PublishRead(n) } @@ -225,13 +248,15 @@ void Bridge::RunTransmitExtractor() noexcept { TETHERKITNEXT_DEBUG_TR(Msg::kCoreTxExtractorStarted); while (!stop_requested_.load(std::memory_order_acquire)) { - // Blocking read. Under BIOCIMMEDIATE=1 BPF automatically delivers the packets accumulated in the meantime as a batch, - // so this is naturally "low latency at low rates, large batches at high rates", and we need not batch ourselves. + // Blocking read. Under BIOCIMMEDIATE=1 BPF automatically delivers the packets accumulated in + // the meantime as a batch, so this is naturally "low latency at low rates, large batches at + // high rates", and we need not batch ourselves. const auto batch = link_->ReadFrames(); if (!batch) { counters_.tx.AddIoError(); TETHERKITNEXT_WARN_TR(Msg::kCoreLinkReadFailed, batch.error().ToString()); - // A read failure may mean the interface was torn down. Wait a bit and retry, to avoid a busy loop flooding the log. + // A read failure may mean the interface was torn down. Wait a bit and retry, to avoid a busy + // loop flooding the log. std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } @@ -242,7 +267,8 @@ void Bridge::RunTransmitExtractor() noexcept { continue; // read timeout expired with no packets in the meantime; normal } if (paused_.load(std::memory_order_acquire)) { - // During a reset the device discards all outstanding data packets, so sending to it is only a waste. + // During a reset the device discards all outstanding data packets, so sending to it is only a + // waste. counters_.tx.AddDroppedFull(batch->frames.size()); continue; } @@ -251,9 +277,10 @@ void Bridge::RunTransmitExtractor() noexcept { std::size_t offset = 0; while (offset < batch->frames.size()) { // Re-check shutdown and pause before every slice: the backpressure wait below lets this loop - // dwell for a long time, so we cannot rely only on the outer check. Dropping the remaining frames while paused is deliberate (during an RNDIS reset - // the device discards all outstanding data packets); TX cannot get the strong guarantee RX has (it must keep - // draining BPF and cannot really stop), but narrowing the leak window to "one slice" is free. + // dwell for a long time, so we cannot rely only on the outer check. Dropping the remaining + // frames while paused is intentional (during an RNDIS reset the device discards all + // outstanding data packets); TX cannot get the strong guarantee RX has (it must keep draining + // BPF and cannot really stop), but narrowing the leak window to "one slice" is free. if (stop_requested_.load(std::memory_order_acquire) || paused_.load(std::memory_order_acquire)) { counters_.tx.AddDroppedFull(batch->frames.size() - offset); @@ -267,17 +294,18 @@ void Bridge::RunTransmitExtractor() noexcept { const auto sent = data_channel_->SendFrames(slice); if (!sent) { counters_.tx.AddIoError(); - // The abandoned remaining frames must be counted as drops -- this used to only +1 io_error and break, - // and the remaining frames entered no counter, vanishing from the statistics out of thin air. + // The abandoned remaining frames must be counted as drops, otherwise they would vanish from + // the statistics. counters_.tx.AddDroppedFull(batch->frames.size() - offset); TETHERKITNEXT_WARN_TR(Msg::kCoreUsbSubmitFailed, chunk, sent.error().ToString()); break; } // The bridge layer is the **sole writer** of the TX counters (DirectionCounters uses relaxed - // load+store, safe only thanks to a single writer). The data channel side only counts errors in the asynchronous completion callbacks, - // merged in by Snapshot() at read time. The sent frame and byte counts are taken directly from SendOutcome, - // and skipped illegal-length frames are counted into oversize drops rather than "sent". + // load+store, safe only thanks to a single writer). The data channel side only counts errors + // in the asynchronous completion callbacks, merged in by Snapshot() at read time. The sent + // frame and byte counts are taken directly from SendOutcome, and skipped illegal-length + // frames are counted into oversize drops rather than "sent". if (sent->sent_frames != 0) { counters_.tx.AddBatch(sent->sent_frames, sent->sent_bytes); } @@ -286,19 +314,17 @@ void Bridge::RunTransmitExtractor() noexcept { } if (sent->consumed == 0) { - // The transfer pool has no free slot -- this is backpressure. **Wait; do not drop.** + // The transfer pool has no free slot; this is backpressure. **Wait; do not drop.** // - // The old implementation dropped the remaining frames immediately here, on the grounds that "waiting would let the BPF kernel buffer pile up into - // invisible kernel drops". That premise was wrong: the kernel buffer is 4 MiB by default (about 130 ms of elasticity - // at 250 Mbps), and its overflow counter bs_drop is brought back on every ReadFrames - // and shown in the "kernel drops" of the statistics line -- it is not invisible at all. - // The consequence measured on real hardware: one full-frame slice needs about 26 transfer slots while the pool has only 4, - // and slots are released within a few hundred microseconds, yet the old code did not wait for even a microsecond, dropping - // 30%+ of TX traffic here under high load (docs/BENCHMARKS.md "real-device end-to-end measurements"). + // Dropping here would lose 30%+ of TX under load: one full-frame slice needs about 26 + // transfer slots while the pool has only 4, and slots are released within a few hundred + // microseconds (docs/BENCHMARKS.md, real-device measurements). Waiting is safe because the + // kernel BPF buffer (4 MiB by default, about 130 ms at 250 Mbps) absorbs the burst, and its + // overflow counter bs_drop is reported through ReadFrames in the "kernel drops" statistic. // - // The wait uses a finite timeout: on every wakeup it returns to the top of the loop to re-check the shutdown/pause flags, so shutdown latency - // has an upper bound. The real overflow backstop is still the kernel buffer -- only when it is full should we drop, - // and the drop is then visible in the statistics. + // The wait has a finite timeout: on every wakeup the loop re-checks the shutdown/pause + // flags, so shutdown latency is bounded. Only when the kernel buffer is full are frames + // dropped, and that drop is visible in the statistics. tx_backpressure_events_.fetch_add(1, std::memory_order_relaxed); (void)data_channel_->WaitForSendCapacity(kTxCapacityWaitMillis); continue; @@ -315,17 +341,26 @@ void Bridge::RunTransmitExtractor() noexcept { // ============================================================================= BridgeStats Bridge::Snapshot() const { + // RX has two writers, each with its own counters (DirectionCounters allows one writer): the + // libusb event thread (counters_.rx) and the RX injection thread (rx_inject_counters_). + DirectionSnapshot rx = tetherkitnext::Snapshot(counters_.rx); + const DirectionSnapshot injected = tetherkitnext::Snapshot(rx_inject_counters_); + rx.dropped_full += injected.dropped_full; + rx.dropped_oversize += injected.dropped_oversize; + rx.io_errors += injected.io_errors; DirectionSnapshot tx = tetherkitnext::Snapshot(counters_.tx); - // Merge the errors accumulated by the data channel in its asynchronous completion callbacks -- that part is incremented by the libusb event thread, - // deliberately kept separate from the bridge layer's counters to maintain the invariant "each counter has only one writer". + // Merge the errors accumulated by the data channel in its asynchronous completion callbacks; that + // part is incremented by the libusb event thread, kept separate from the bridge layer's counters + // to maintain the invariant "each counter has only one writer". tx.io_errors += data_channel_->AsyncSendErrors(); return BridgeStats{ - .rx = tetherkitnext::Snapshot(counters_.rx), + .rx = rx, .tx = tx, .rx_queue_depth = rx_ring_->SizeSnapshot(), .link_kernel_drops = link_kernel_drops_.load(std::memory_order_relaxed), .tx_backpressure_events = tx_backpressure_events_.load(std::memory_order_relaxed), + .peer_ipv4 = peer_observer_.Latest(), }; } diff --git a/src/core/runtime.cc b/src/core/runtime.cc index cc5de6a..075d226 100644 --- a/src/core/runtime.cc +++ b/src/core/runtime.cc @@ -46,16 +46,19 @@ Runtime::~Runtime() { // ============================================================================= Status Runtime::Start() { - if (started_) { + // A runtime is single-use. Starting after Stop() would spawn a control thread that the + // already-stopped destructor never joins (std::terminate on a joinable std::thread). + if (started_.load() || stopped_.load()) { return std::unexpected(Error::Generic(Tr(Msg::kCoreRuntimeAlreadyStarted))); } - // The root check is deliberately kept on the **synchronous** path. + // The root check is kept on the **synchronous** path. // - // It needs no I/O, and "forgot sudo" is the most common failure; reporting it synchronously and early lets the command line - // reflect it in the return code, and spares the user from staring at a spinning UI waiting for an asynchronous event. - // Note that libusb claiming the RNDIS interface **does not need** root (macOS has no RNDIS kernel driver), - // what needs root is feth creation and opening /dev/bpf*. + // It needs no I/O, and "forgot sudo" is the most common failure; reporting it synchronously and + // early lets the command line reflect it in the return code, and spares the user from staring at + // a spinning UI waiting for an asynchronous event. Note that libusb claiming the RNDIS interface + // **does not need** root (macOS has no RNDIS kernel driver), what needs root is feth creation and + // opening /dev/bpf*. if (!net::IsRunningAsRoot()) { return std::unexpected(Error::Generic(Tr(Msg::kCoreNeedsRoot))); } @@ -73,19 +76,19 @@ void Runtime::WaitUntilStopped() { } void Runtime::Stop() { - if (stopped_) { + if (stopped_.exchange(true)) { return; } - stopped_ = true; - if (!started_) { + if (!started_.load()) { return; } // Set the shutdown flag and wake the control thread that may be sleeping. // - // The flag must be written while holding the lock: the control thread's wait_for uses it as the predicate, and writing without the lock leaves a - // lost-wakeup window of "checked the predicate, not yet asleep". RequestStop() not taking the lock is a deliberate - // trade-off (it must stay async-signal-safe), at the cost of being seen up to one loop period later. + // The flag must be written while holding the lock: the control thread's wait_for uses it as the + // predicate, and writing without the lock leaves a lost-wakeup window of "checked the predicate, + // not yet asleep". RequestStop() not taking the lock is a trade-off (it must stay + // async-signal-safe), at the cost of being seen up to one loop period later. { const std::lock_guard guard(stop_mutex_); stop_requested_.store(true, std::memory_order_release); @@ -112,8 +115,9 @@ std::string Runtime::SystemInterfaceName() const { // ============================================================================= void Runtime::RunControlThread() noexcept { - // The control thread uses the kControl QoS rather than kDataPath: it does a bit of work only every few seconds, - // and competing for performance cores is meaningless for it, and might instead crowd out the three real data-path threads. + // The control thread uses the kControl QoS rather than kDataPath: it does a bit of work only + // every few seconds, and competing for performance cores is meaningless for it, and might instead + // crowd out the three real data-path threads. ConfigureCurrentThread("rndis-ctl", ThreadRole::kControl); if (const auto status = RunStartSequence(); !status) { @@ -124,8 +128,9 @@ void Runtime::RunControlThread() noexcept { SetRunState(RunState::kStopping); } - // Tear down whether startup succeeded or not: the startup sequence may have built half of things already (for example the feth was built - // but BPF could not be opened), and missing this would leave the NIC in the kernel. + // Tear down whether startup succeeded or not: the startup sequence may have built half of things + // already (for example the feth was built but BPF could not be opened), and missing this would + // leave the NIC in the kernel. Teardown(); SetRunState(fatal_error_.load(std::memory_order_acquire) ? RunState::kFailed @@ -133,12 +138,12 @@ void Runtime::RunControlThread() noexcept { } Status Runtime::RunStartSequence() { - // ---- Step 1: libusb context and event thread ---- + // Step 1: libusb context and event thread // // (The root check was already done synchronously in Start().) TETHERKITNEXT_ASSIGN_OR_RETURN(usb_context_, usb::Context::Create()); - // ---- Step 2: discover and open the device ---- + // Step 2: discover and open the device TETHERKITNEXT_ASSIGN_OR_RETURN(const auto candidates, usb::FindRndisDevices(*usb_context_, config_.device_filter)); if (candidates.empty()) { @@ -150,33 +155,37 @@ Status Runtime::RunStartSequence() { TETHERKITNEXT_ASSIGN_OR_RETURN(device_, usb::Device::Open(*usb_context_, candidates.front())); RefreshSnapshot(); - // ---- Step 3: RNDIS control channel and state machine ---- + // Step 3: RNDIS control channel and state machine // - // The control channel uses the synchronous libusb API, so it must run on a **non-event thread** -- this function is on - // Runtime's own control thread, which satisfies the requirement. + // The control channel uses the synchronous libusb API, so it must run on a **non-event thread**; + // this function is on Runtime's own control thread, which satisfies the requirement. control_channel_ = std::make_unique(*device_, config_.rndis.control_timeout_millis); - // Interrupt notifications must go through an asynchronous transfer, otherwise the control thread would hang forever -- see - // the explanation of UsbControlChannel in include/tetherkitnext/usb/device.h. - // It must be started **before** the state machine Start(), because the initialization handshake itself waits for a notification. + // Interrupt notifications must go through an asynchronous transfer, otherwise the control thread + // would hang forever; see the explanation of UsbControlChannel in + // include/tetherkitnext/usb/device.h. It must be started **before** the state machine Start(), + // because the initialization handshake itself waits for a notification. TETHERKITNEXT_RETURN_IF_ERROR(control_channel_->StartNotificationListener()); - // Let RNDIS negotiation use the real endpoint max packet size (which affects the derivation of MaxTransferSize). + // Let RNDIS negotiation use the real endpoint max packet size (which affects the derivation of + // MaxTransferSize). rndis::StateMachineConfig rndis_config = config_.rndis; rndis_config.requested_mtu = config_.mtu; state_machine_ = std::make_unique(*control_channel_, *this, rndis_config); TETHERKITNEXT_RETURN_IF_ERROR(state_machine_->Start()); - // Only here do we have the negotiation result: device MAC, final MTU, aggregation limit, alignment requirement. + // Only here do we have the negotiation result: device MAC, final MTU, aggregation limit, + // alignment requirement. const rndis::NegotiatedParameters& parameters = state_machine_->Parameters(); const rndis::DeviceInfo& info = state_machine_->Info(); - // ---- Step 4: create the feth pair ---- + // Step 4: create the feth pair // - // It must come after negotiation: the system-side MAC must be set to the address the device reported, the MTU must use the negotiation result, - // and the MAC must be set before the interface goes IFF_UP. + // It must come after negotiation: the system-side MAC must be set to the address the device + // reported, the MTU must use the negotiation result, and the MAC must be set before the interface + // goes IFF_UP. { const net::MacAddress* system_mac = nullptr; net::MacAddress adopted{}; @@ -187,40 +196,53 @@ Status Runtime::RunStartSequence() { TETHERKITNEXT_ASSIGN_OR_RETURN(auto pair, net::FethPair::Create(parameters.mtu, system_mac)); feth_pair_ = std::make_unique(std::move(pair)); } - // Flush into the snapshot as soon as the NIC is built: if any later step fails, the GUI should also be able to see the NIC name, - // otherwise the user would not even know "which NIC was just built". + // Flush into the snapshot as soon as the NIC is built: if any later step fails, the GUI should + // also be able to see the NIC name, otherwise the user would not even know "which NIC was just + // built". RefreshSnapshot(); - // ---- Step 5: open BPF on the **driver-side** interface ---- + // Step 5: open BPF on the **driver-side** interface // - // Attaching to the driver side rather than the system side is because frames the host sends out of the system side appear as the input direction on the driver side, - // while frames we write into the driver side enter the system side's input -- one descriptor handles both receiving and sending. + // Attaching to the driver side rather than the system side is because frames the host sends out + // of the system side appear as the input direction on the driver side, while frames we write into + // the driver side enter the system side's input; one descriptor handles both receiving and + // sending. { net::BpfConfig bpf_config = config_.bpf; - // Per-frame limit = MTU + Ethernet header. Note that the kernel bpfwrite's hard cap is MTU + 18, - // so it must never be exceeded here. + // Per-frame limit = MTU + Ethernet header. Note that the kernel bpfwrite's hard cap is MTU + + // 18, so it must never be exceeded here. bpf_config.max_frame_bytes = parameters.mtu + rndis::kEthernetHeaderBytes; TETHERKITNEXT_ASSIGN_OR_RETURN(bpf_link_, net::BpfLink::Open(feth_pair_->DriverSide().Name(), bpf_config)); } - // ---- Step 6: create the USB data channel ---- + // Step 6: create the USB data channel { usb::DataChannelConfig data_config = config_.data_channel; - // The bulk IN buffer must be >= the MaxTransferSize we claim in INITIALIZE_MSG, - // otherwise the large transfers the device aggregates would overflow / be truncated. + // The bulk IN buffer must be >= the MaxTransferSize we claim in INITIALIZE_MSG, otherwise the + // large transfers the device aggregates would overflow / be truncated. data_config.rx_transfer_bytes = std::max(data_config.rx_transfer_bytes, config_.rndis.host_max_transfer_size); TETHERKITNEXT_ASSIGN_OR_RETURN(data_channel_, usb::UsbDataChannel::Create(*device_, parameters, data_config)); } - // ---- Step 7: start the bridge layer ---- + // Step 7: start the bridge layer { BridgeConfig bridge_config = config_.bridge; bridge_config.max_frame_bytes = parameters.mtu + rndis::kEthernetHeaderBytes; bridge_ = std::make_unique(*data_channel_, *bpf_link_, bridge_config); TETHERKITNEXT_RETURN_IF_ERROR(bridge_->Start()); + // The state machine reported the initial media state before the bridge existed + // (OnLinkStateChanged saw bridge_ == nullptr), so apply it now. + bool link_up = false; + { + const std::lock_guard guard(snapshot_mutex_); + link_up = snapshot_.link_up; + } + if (!link_up) { + bridge_->SetPaused(true); + } } RefreshSnapshot(); @@ -231,39 +253,55 @@ Status Runtime::RunStartSequence() { void Runtime::RunControlLoop() { BridgeStats previous = bridge_->Snapshot(); Nanos last_stats_nanos = MonotonicNanos(); + std::uint32_t idle_stats_periods = 0; const Nanos stats_interval_nanos = static_cast(config_.stats_interval_millis) * kNanosPerMilli; while (!stop_requested_.load(std::memory_order_acquire) && !fatal_error_.load(std::memory_order_acquire)) { - // ---- Periodic work of the state machine: keepalive + draining messages pushed by the device ---- + // Periodic state machine work: keepalive + draining device-pushed messages if (const auto status = state_machine_->Poll(); !status) { RecordFatal(std::move(status).error()); break; } - // ---- Refresh the snapshot ---- + // Refresh the snapshot // - // Done in every loop iteration rather than only when events occur: the statistics counters change continuously, - // and the GUI computes rates from the difference of two snapshots. The loop period cap is 250 ms, enough for a 2 Hz UI refresh. + // Done in every loop iteration rather than only when events occur: the statistics counters + // change continuously, and the GUI computes rates from the difference of two snapshots. The + // loop period cap is 250 ms, enough for a 2 Hz UI refresh. RefreshSnapshot(); - // ---- Periodic statistics ---- + // Periodic statistics const Nanos now = MonotonicNanos(); if (stats_interval_nanos != 0 && now - last_stats_nanos >= stats_interval_nanos) { const BridgeStats current = bridge_->Snapshot(); const double seconds = static_cast(now - last_stats_nanos) / static_cast(kNanosPerSecond); - TETHERKITNEXT_INFO("{}", FormatStatsLine(previous, current, seconds)); + // An idle link would print an identical all-zero line every period. Print the first idle + // line, then one every kIdleStatsEvery periods as a heartbeat; any traffic, drop or + // backpressure resumes every line. + constexpr std::uint32_t kIdleStatsEvery = 12; + const DirectionSnapshot rx_delta = current.rx - previous.rx; + const DirectionSnapshot tx_delta = current.tx - previous.tx; + const bool idle = rx_delta.frames == 0 && tx_delta.frames == 0 && + rx_delta.TotalDropped() == 0 && tx_delta.TotalDropped() == 0 && + current.link_kernel_drops == previous.link_kernel_drops && + current.tx_backpressure_events == previous.tx_backpressure_events; + idle_stats_periods = idle ? idle_stats_periods + 1 : 0; + if (idle_stats_periods <= 1 || idle_stats_periods % kIdleStatsEvery == 0) { + TETHERKITNEXT_INFO("{}", FormatStatsLine(previous, current, seconds)); + } previous = current; last_stats_nanos = now; } - // ---- Sleep until the next moment we need to wake ---- + // Sleep until the next moment we need to wake // - // Take the nearer of the two deadlines "next keepalive" and "next statistics", to avoid needless wakeups. - // The 250 ms cap is so that RequestStop(), which only writes an atomic, is also noticed in time. + // Take the nearer of the two deadlines "next keepalive" and "next statistics", to avoid + // needless wakeups. The 250 ms cap is so that RequestStop(), which only writes an atomic, is + // also noticed in time. std::uint32_t sleep_millis = std::min(state_machine_->MillisUntilNextPoll(), 250); if (stats_interval_nanos != 0) { @@ -272,11 +310,12 @@ void Runtime::RunControlLoop() { sleep_millis = std::min(sleep_millis, static_cast(remaining / kNanosPerMilli)); } - // Sleep at least 10 ms: to avoid spinning busily right at the boundary when the keepalive has just expired. + // Sleep at least 10 ms: to avoid spinning busily right at the boundary when the keepalive has + // just expired. sleep_millis = std::max(sleep_millis, 10); - // A condition variable is used rather than sleep_for: Stop() can wake us immediately, so when the user presses "Stop" - // there is no need to wait up to 250 ms for a reaction. + // A condition variable is used rather than sleep_for: Stop() can wake us immediately, so when + // the user presses "Stop" there is no need to wait up to 250 ms for a reaction. std::unique_lock lock(stop_mutex_); stop_condition_.wait_for(lock, std::chrono::milliseconds(sleep_millis), [this] { return stop_requested_.load(std::memory_order_acquire); }); @@ -313,9 +352,9 @@ void Runtime::Teardown() { // Tear down in the strict **reverse** of the startup order. // // 1. Stop the bridge layer first: internally it joins the two data-path threads, then calls - // DataChannel::Shutdown() to wait for all in-flight USB transfers to be reclaimed. This step must complete before destroying - // device_ -- libusb_close will not reclaim in-flight transfers for us, - // and closing the handle first then freeing the transfers is a use-after-free. + // DataChannel::Shutdown() to wait for all in-flight USB transfers to be reclaimed. This step + // must complete before destroying device_: libusb_close will not reclaim in-flight transfers + // for us, and closing the handle first then freeing the transfers is a use-after-free. if (bridge_ != nullptr) { bridge_->Stop(); bridge_.reset(); @@ -328,16 +367,19 @@ void Runtime::Teardown() { // 3. Destroy the feth pair. The kernel's feth_clone_destroy automatically unpairs the peer first. feth_pair_.reset(); - // 4. Make the device leave RNDIS: first SET filter = 0 to make it stop sending data, then send HALT. - // This must be done before closing the USB handle -- otherwise the device will keep thinking the host is still there, - // and the state will not be clean the next time it is plugged in. + // 4. Make the device leave RNDIS: first SET filter = 0 to make it stop sending data, then send + // HALT. + // This must be done before closing the USB handle; otherwise the device will keep thinking the + // host is still there, and the state will not be clean the next time it is plugged in. // - // This step sends synchronous control messages, so it must be on the control thread -- and this function is. + // This step sends synchronous control messages, so it must be on the control thread, and this + // function is. if (state_machine_ != nullptr) { state_machine_->Stop(); state_machine_.reset(); } - // First stop interrupt listening (it waits for the in-flight asynchronous transfers to be reclaimed), then destroy the channel object. + // First stop interrupt listening (it waits for the in-flight asynchronous transfers to be + // reclaimed), then destroy the channel object. if (control_channel_ != nullptr) { control_channel_->StopNotificationListener(); control_channel_.reset(); @@ -349,9 +391,10 @@ void Runtime::Teardown() { // 6. Finally stop the libusb event thread and release the context. usb_context_.reset(); - // Refresh once more after teardown: the NIC name and statistics should be zeroed, and the GUI should not keep showing a NIC that no longer exists. - // link_up is maintained by events and RefreshSnapshot does not touch it, so it is cleared explicitly here -- - // a UI still lit up with "link connected" after shutdown would be misleading. + // Refresh once more after teardown: the NIC name and statistics should be zeroed, and the GUI + // should not keep showing a NIC that no longer exists. link_up is maintained by events and + // RefreshSnapshot does not touch it, so it is cleared explicitly here; a UI still lit up with + // "link connected" after shutdown would be misleading. { const std::lock_guard guard(snapshot_mutex_); snapshot_.link_up = false; @@ -365,8 +408,8 @@ void Runtime::Teardown() { // ============================================================================= void Runtime::RefreshSnapshot() { - // First read the state of each component outside the lock -- these reads go through ioctl / atomic loads, - // and should not occupy snapshot_mutex_. + // First read the state of each component outside the lock; these reads go through ioctl / atomic + // loads, and should not occupy snapshot_mutex_. RuntimeSnapshot fresh; if (device_ != nullptr) { fresh.device_description = std::string{device_->Describe()}; @@ -386,7 +429,8 @@ void Runtime::RefreshSnapshot() { } const std::lock_guard guard(snapshot_mutex_); - // run_state, link_up and fatal_message are maintained at their own transition points; they must not be overwritten here. + // run_state, link_up and fatal_message are maintained at their own transition points; they must + // not be overwritten here. fresh.run_state = snapshot_.run_state; fresh.link_up = snapshot_.link_up; fresh.fatal_message = snapshot_.fatal_message; @@ -415,7 +459,8 @@ void Runtime::RecordFatal(const Error& error) { { const std::lock_guard guard(snapshot_mutex_); - // Record only the **first** fatal error: later ones are mostly chain reactions caused by it, and overwriting would lose the root cause. + // Record only the **first** fatal error: later ones are mostly chain reactions caused by it, + // and overwriting would lose the root cause. if (snapshot_.fatal_message.empty()) { snapshot_.fatal_message = message; } @@ -435,7 +480,8 @@ void Runtime::Emit(const RuntimeEvent& event) const { // ============================================================================= void Runtime::OnStateChanged(rndis::State from, rndis::State to) { - // The state machine has already logged, so it is not repeated here; only the transition is forwarded to the host. + // The state machine has already logged, so it is not repeated here; only the transition is + // forwarded to the host. Emit(RuntimeEvent{.kind = RuntimeEvent::Kind::kRndisState, .a = static_cast(from), .b = static_cast(to), @@ -462,8 +508,9 @@ void Runtime::OnLinkStateChanged(bool connected) { snapshot_.link_up = connected; } - // Pause data movement when the link goes down. Continuing to send frames onto a disconnected link is only a waste, and would fill up the queue, - // so that upon real recovery a pile of stale frames would be sent out first. + // Pause data movement when the link goes down. Continuing to send frames onto a disconnected link + // is only a waste, and would fill up the queue, so that upon real recovery a pile of stale frames + // would be sent out first. if (bridge_ != nullptr) { bridge_->SetPaused(!connected); } @@ -475,18 +522,27 @@ void Runtime::OnDeviceReset(bool addressing_lost) { TETHERKITNEXT_WARN_TR(Msg::kCoreDeviceReset, Text(addressing_lost ? Msg::kCoreAddressingLost : Msg::kCoreAddressingKept)); - // During a reset the device discarded all outstanding data packets. A brief pause lets the state machine finish replaying the packet filter, - // avoiding continued flooding of data during the window when the device rebuilds its internal state. + // During a reset the device discarded all outstanding data packets. A brief pause lets the state + // machine finish replaying the packet filter, avoiding continued flooding of data during the + // window when the device rebuilds its internal state. SetPaused(true) also waits for the RX + // injector to stop, so this drains in-flight writes. Restore the link's own state afterwards + // instead of forcing "running": a reset while the medium is down must leave the bridge paused. if (bridge_ != nullptr) { + bool link_up = false; + { + const std::lock_guard guard(snapshot_mutex_); + link_up = snapshot_.link_up; + } bridge_->SetPaused(true); - bridge_->SetPaused(false); + bridge_->SetPaused(!link_up); } Emit(RuntimeEvent{.kind = RuntimeEvent::Kind::kDeviceReset, .a = addressing_lost ? 1 : 0}); } void Runtime::OnFatalError(const Error& error) { - // WithContext is &&-qualified, while what we hold here is a const reference, so a copy must be made first. + // WithContext is &&-qualified, while what we hold here is a const reference, so a copy must be + // made first. Error annotated = error; RecordFatal(std::move(annotated).WithContext(Tr(Msg::kCoreLinkUnrecoverable))); } diff --git a/src/net/CMakeLists.txt b/src/net/CMakeLists.txt index 842c011..3756b11 100644 --- a/src/net/CMakeLists.txt +++ b/src/net/CMakeLists.txt @@ -1,8 +1,9 @@ -# tk_net -- virtual NIC and link layer +# tk_net: virtual NIC and link layer # # Depends only on macOS system calls (ioctl / BPF), not on libusb nor on the RNDIS protocol layer. -# LinkBackend is this module's public abstraction; BpfLink is the production implementation and LoopbackLink is a pure in-memory implementation -# -- the latter lets the bridge layer's end-to-end tests and throughput benchmarks run on machines without root or real interfaces. +# LinkBackend is this module's public abstraction; BpfLink is the production implementation and +# LoopbackLink is a pure in-memory implementation; the latter lets the bridge layer's end-to-end +# tests and throughput benchmarks run on machines without root or real interfaces. add_library( tk_net STATIC diff --git a/src/net/bpf_link.cc b/src/net/bpf_link.cc index c13ad36..5e562b0 100644 --- a/src/net/bpf_link.cc +++ b/src/net/bpf_link.cc @@ -22,16 +22,17 @@ namespace { /// Upper limit for iterating /dev/bpf%d. /// -/// When the kernel opens the current last node it makes another on demand (in bpfopen, -/// `if (minor(dev) == nbpfilter - 1) bpf_make_dev_t(...)`), and the limit is controlled by the sysctl -/// debug.bpf_maxdevices (256 on this machine). 256 is used here to match. +/// When the kernel opens the current last node it makes another on demand (in bpfopen, `if +/// (minor(dev) == nbpfilter - 1) bpf_make_dev_t(...)`), and the limit is controlled by the sysctl +/// debug.bpf_maxdevices (256 on macOS 26, see AGENTS.md section 2.3). 256 is used here to match. constexpr int kMaxBpfDeviceIndex = 256; /// Upper limit in bytes of one write() during batch writes. /// -/// The absolute upper limit the kernel allows is BPF_WRITE_MAX = 16 MiB, but there is no need for something that large: -/// 256 KiB already holds over a hundred full frames, and the fixed overhead of a single system call is long since amortized, -/// while a larger assembly buffer would only worsen the L2 cache hit rate. +/// The absolute upper limit the kernel allows is BPF_WRITE_MAX = 16 MiB, but there is no need for +/// something that large: 256 KiB already holds over a hundred full frames, and the fixed overhead +/// of a single system call is long since amortized, while a larger assembly buffer would only +/// worsen the L2 cache hit rate. constexpr std::size_t kMaxBatchWriteBytes = std::size_t{256} * 1024; /// Issues one ioctl; on failure wraps errno and the call name into an Error. @@ -47,7 +48,8 @@ constexpr std::size_t kMaxBatchWriteBytes = std::size_t{256} * 1024; [[nodiscard]] bool TryOptionalIoctl(int fd, unsigned long request, void* argument, std::string_view what) { if (::ioctl(fd, request, argument) < 0) { - // ENOTTY / EINVAL means the current macOS version does not support this private ioctl, which is an expected case. + // ENOTTY / EINVAL means the current macOS version does not support this private ioctl, which is + // an expected case. TETHERKITNEXT_DEBUG_TR(Msg::kNetOptionalIoctlUnavailable, what, errno); return false; } @@ -84,8 +86,8 @@ Result> BpfLink::Open(std::string_view interface_name, // --------------------------------------------------------------------------- // 1. Open /dev/bpf%d // - // macOS **has no** /dev/bpf cloning node (measured: ls /dev/bpf -> No such file), - // so numbers must be tried one by one: EBUSY means that minor is already held by another process, try the next; + // macOS **has no** /dev/bpf cloning node (measured: ls /dev/bpf -> No such file), so numbers must + // be tried one by one: EBUSY means that minor is already held by another process, try the next; // ENOENT means the limit of nodes the kernel has currently made has been reached. // --------------------------------------------------------------------------- int last_errno = 0; @@ -117,11 +119,12 @@ Result> BpfLink::Open(std::string_view interface_name, } // --------------------------------------------------------------------------- - // 2. BIOCSBLEN -- **must be before BIOCSETIF** + // 2. BIOCSBLEN: **must be before BIOCSETIF** // // In bpf.c: `if (d->bd_bif != 0 || (d->bd_flags & BPF_DETACHING)) return EINVAL`. - // And when the limit is exceeded it **does not report an error**; it silently clamps to BPF_BUFSIZE_CAP and writes the actually effective value back - // into the parameter through _IOWR -- so every later read() must use this written-back value as its length. + // And when the limit is exceeded it **does not report an error**; it silently clamps to + // BPF_BUFSIZE_CAP and writes the actually effective value back into the parameter through _IOWR, + // so every later read() must use this written-back value as its length. // --------------------------------------------------------------------------- auto buffer_bytes = static_cast(config.kernel_buffer_bytes); TETHERKITNEXT_RETURN_IF_ERROR( @@ -132,21 +135,23 @@ Result> BpfLink::Open(std::string_view interface_name, } // --------------------------------------------------------------------------- - // 3. BIOCSHDRCMPLT = 1 -- **mandatory**, and must be before BIOCSBATCHWRITE + // 3. BIOCSHDRCMPLT = 1: **mandatory**, and must be before BIOCSBATCHWRITE // - // With hdrcmplt=0, bpfwrite strips the first 14 bytes to rebuild the frame header (the source MAC gets rewritten by the driver); - // =1 takes DLIL_OUTPUT_FLAGS_RAW and passes through as-is. Batch writes also strictly require it to be 1. + // With hdrcmplt=0, bpfwrite strips the first 14 bytes to rebuild the frame header (the source MAC + // gets rewritten by the driver); =1 takes DLIL_OUTPUT_FLAGS_RAW and passes through as-is. Batch + // writes also strictly require it to be 1. // - // WARNING: And on feth the consequence is far more severe than "the frame header gets rewritten": **without this ioctl, write() - // returns ENXIO directly** (if_fake's output path cannot handle the AF_UNSPEC rebuild branch). - // See item 14 of section 7 in AGENTS.md for the controlled experiment. When troubleshooting ENXIO, do not suspect the interface name. + // WARNING: And on feth the consequence is far more severe than "the frame header gets rewritten": + // **without this ioctl, write() returns ENXIO directly** (if_fake's output path cannot handle the + // AF_UNSPEC rebuild branch). See item 14 of section 7 in AGENTS.md for the controlled experiment. + // When troubleshooting ENXIO, do not suspect the interface name. // --------------------------------------------------------------------------- int header_complete = 1; TETHERKITNEXT_RETURN_IF_ERROR( CallIoctl(link->fd_, BIOCSHDRCMPLT, &header_complete, "ioctl(BIOCSHDRCMPLT)")); // --------------------------------------------------------------------------- - // 4. BIOCSETIF -- bind to the interface + // 4. BIOCSETIF: bind to the interface // --------------------------------------------------------------------------- ::ifreq bind_request{}; std::memcpy(bind_request.ifr_name, interface_name.data(), interface_name.size()); @@ -163,10 +168,11 @@ Result> BpfLink::Open(std::string_view interface_name, } // --------------------------------------------------------------------------- - // 5. BIOCGDLT -- verify the data link type + // 5. BIOCGDLT: verify the data link type // - // feth's bpfattach uses DLT_EN10MB, so this is necessarily 1; it is verified to prevent - // someone from mistakenly binding BPF to another interface type, in which case all frame format assumptions would be wrong. + // feth's bpfattach uses DLT_EN10MB, so this is necessarily 1; it is verified to prevent someone + // from mistakenly binding BPF to another interface type, in which case all frame format + // assumptions would be wrong. // --------------------------------------------------------------------------- unsigned int data_link_type = 0; TETHERKITNEXT_RETURN_IF_ERROR( @@ -177,31 +183,33 @@ Result> BpfLink::Open(std::string_view interface_name, } // --------------------------------------------------------------------------- - // 6. BIOCIMMEDIATE = 1 -- immediate delivery + // 6. BIOCIMMEDIATE = 1: immediate delivery // - // If not enabled, read() returns only when the buffer **fills**; with a 4 MiB buffer the latency is catastrophically high. - // Once enabled, it wakes on every arriving packet, and when read() wakes it delivers all packets accumulated in the meantime at once -- - // low latency at low rates, automatically large batches at high rates, with behavior similar to NAPI. + // If not enabled, read() returns only when the buffer **fills**; with a 4 MiB buffer the latency + // is catastrophically high. Once enabled, it wakes on every arriving packet, and when read() + // wakes it delivers all packets accumulated in the meantime at once; low latency at low rates, + // automatically large batches at high rates, with behavior similar to NAPI. // --------------------------------------------------------------------------- unsigned int immediate = 1; TETHERKITNEXT_RETURN_IF_ERROR( CallIoctl(link->fd_, BIOCIMMEDIATE, &immediate, "ioctl(BIOCIMMEDIATE)")); // --------------------------------------------------------------------------- - // 7. BIOCSSEESENT = 0 -- capture only the input direction + // 7. BIOCSSEESENT = 0: capture only the input direction // - // This step is **the key to preventing loops**: the frames we write in are the output direction on this interface, - // and SEESENT=0 filters them out, leaving only the input frames the host sent from the peer side. + // This step is **the key to preventing loops**: the frames we write in are the output direction + // on this interface, and SEESENT=0 filters them out, leaving only the input frames the host sent + // from the peer side. // --------------------------------------------------------------------------- unsigned int see_sent = 0; TETHERKITNEXT_RETURN_IF_ERROR( CallIoctl(link->fd_, BIOCSSEESENT, &see_sent, "ioctl(BIOCSSEESENT)")); // --------------------------------------------------------------------------- - // 8. BIOCSRTIMEOUT -- read timeout, used to respond to shutdown + // 8. BIOCSRTIMEOUT: read timeout, used to respond to shutdown // - // The kernel stores tvtohz(tv) - 1 ticks; on this machine hz=100 -> 10 ms resolution; - // passing {0,0} becomes **blocking forever**, so a non-zero value must be passed here. + // The kernel stores tvtohz(tv) - 1 ticks; with hz=100 the resolution is 10 ms. Passing {0,0} + // blocks forever, so a non-zero value must be passed here. // --------------------------------------------------------------------------- ::timeval read_timeout{}; read_timeout.tv_sec = config.read_timeout_millis / 1000; @@ -210,9 +218,10 @@ Result> BpfLink::Open(std::string_view interface_name, TETHERKITNEXT_RETURN_IF_ERROR( CallIoctl(link->fd_, BIOCSRTIMEOUT, &read_timeout, "ioctl(BIOCSRTIMEOUT)")); - // Deliberately **not setting** BIOCPROMISC: feth's feth_output_common unconditionally delivers frames to the peer - // and taps them, doing no MAC filtering at all; whether they can be read is determined only by direction. Setting promisc would only add an - // IFF_PROMISC reference count and a kernel event, purely wasteful. + // **Not setting** BIOCPROMISC: feth's feth_output_common unconditionally delivers frames to the + // peer and taps them, doing no MAC filtering at all; whether they can be read is determined only + // by direction. Setting promisc would only add an IFF_PROMISC reference count and a kernel event, + // purely wasteful. // --------------------------------------------------------------------------- // 9. Optional optimizations: batch writes and turning off timestamps (both feature-probed) @@ -259,37 +268,40 @@ Result BpfLink::ReadFrames() { read_frames_.clear(); // All early returns must carry last_kernel_drops_ rather than the default 0: kernel_drops is a - // **cumulative** counter, and the consumer differences two adjacent readings. When idle, a read timeout passes through here every 200 ms, - // and reporting 0 would "zero out" drops that already happened; the next sample with traffic would then re-report the full amount as new, - // and the difference of the sample in between would also under/overflow on unsigned numbers. + // **cumulative** counter, and the consumer differences two adjacent readings. When idle, a read + // timeout passes through here every 200 ms, and reporting 0 would "zero out" drops that already + // happened; the next sample with traffic would then re-report the full amount as new, and the + // difference of the sample in between would also under/overflow on unsigned numbers. if (interrupted_.load(std::memory_order_acquire)) { return ReadBatch{.kernel_drops = last_kernel_drops_}; } - // The length of read() **must exactly equal** the kernel's bd_bufsize, otherwise bpfread returns at the very start with - // `if (uio_resid(uio) != d->bd_bufsize) return EINVAL`. + // The length of read() **must exactly equal** the kernel's bd_bufsize, otherwise bpfread returns + // at the very start with `if (uio_resid(uio) != d->bd_bufsize) return EINVAL`. const ssize_t received = ::read(fd_, read_buffer_.data(), read_buffer_.size()); if (received < 0) { if (errno == EINTR || errno == EAGAIN) { - // Interrupted by a signal or timed out with no data; leave it to the caller to continue looping + // Interrupted by a signal or timed out with no data; leave it to the caller to continue + // looping return ReadBatch{.kernel_drops = last_kernel_drops_}; } return std::unexpected(Error::FromErrno(0, Tr(Msg::kNetBpfReadFailed, device_path_))); } if (received == 0) { - return ReadBatch{.kernel_drops = last_kernel_drops_}; // read timeout expired and there were no packets in the meantime + // read timeout expired and there were no packets in the meantime + return ReadBatch{.kernel_drops = last_kernel_drops_}; } // --------------------------------------------------------------------------- // Iterate BPF records // - // Record layout: [bpf_hdr (bh_hdrlen bytes, including alignment padding)][frame data (bh_caplen bytes)] - // Offset of the next record = BPF_WORDALIGN(bh_hdrlen + bh_caplen). + // Record layout: [bpf_hdr (bh_hdrlen bytes, including alignment padding)][frame data (bh_caplen + // bytes)] Offset of the next record = BPF_WORDALIGN(bh_hdrlen + bh_caplen). // - // * Must use bh_hdrlen from the record, not sizeof(struct bpf_hdr). * - // Under LP64 sizeof is 20 (18 bytes of content + 2 bytes of compiler padding), while the bh_hdrlen the kernel writes for - // DLT_EN10MB is 18 (SIZEOF_BPF_HDR=18, - // bif_hdrlen = BPF_WORDALIGN(14 + 18) - 14 = 18). Using 20 would immediately misalign. + // Must use bh_hdrlen from the record, not sizeof(struct bpf_hdr). Under LP64 sizeof is 20 (18 + // bytes of content + 2 bytes of compiler padding), while the bh_hdrlen the kernel writes for + // DLT_EN10MB is 18 (SIZEOF_BPF_HDR=18, bif_hdrlen = BPF_WORDALIGN(14 + 18) - 14 = 18). Using 20 + // would misalign at once. // --------------------------------------------------------------------------- const auto total = static_cast(received); std::size_t offset = 0; @@ -297,7 +309,8 @@ Result BpfLink::ReadFrames() { while (offset + kBpfHeaderMinBytes <= total) { const std::byte* record = read_buffer_.data() + offset; - // Read field by field rather than mapping a struct: the record start is only guaranteed 4-byte alignment. + // Read field by field rather than mapping a struct: the record start is only guaranteed 4-byte + // alignment. const std::uint32_t capture_length = LoadLe32(record + offsetof(::bpf_hdr, bh_caplen)); const std::uint32_t original_length = LoadLe32(record + offsetof(::bpf_hdr, bh_datalen)); const std::uint32_t header_length = LoadLe16(record + offsetof(::bpf_hdr, bh_hdrlen)); @@ -309,13 +322,15 @@ Result BpfLink::ReadFrames() { const std::size_t record_bytes = static_cast(header_length) + capture_length; if (offset + record_bytes > total) [[unlikely]] { - // Record truncated: should not happen normally (the kernel does not write records that cross the end of the buffer). + // Record truncated: should not happen normally (the kernel does not write records that cross + // the end of the buffer). TETHERKITNEXT_WARN_TR(Msg::kNetBpfRecordOutOfBounds, offset, record_bytes, total); break; } - // Only fully captured frames are forwarded. capture < original means a filter was installed and truncated it, - // and forwarding a partial frame to USB would only confuse the peer. We install no filter, so this should not trigger. + // Only fully captured frames are forwarded. capture < original means a filter was installed and + // truncated it, and forwarding a partial frame to USB would only confuse the peer. We install + // no filter, so this should not trigger. if (capture_length == original_length && capture_length >= kMinEthernetFrameBytes && capture_length <= max_frame_bytes_) [[likely]] { read_frames_.push_back(FrameView{.data = record + header_length, .length = capture_length}); @@ -327,15 +342,17 @@ Result BpfLink::ReadFrames() { offset += BPF_WORDALIGN(record_bytes); if (read_frames_.size() >= read_frames_.capacity()) { - // The frame array is full. The remaining records are not processed this time -- is the data still in the kernel buffer? No, it has already been copied out, - // so it will be lost. Hence max_frames_per_batch must be configured large enough. A warning is issued here rather than staying silent. + // The frame array is full. The remaining records are not processed this time; is the data + // still in the kernel buffer? No, it has already been copied out, so it will be lost. Hence + // max_frames_per_batch must be configured large enough. A warning is issued here rather than + // staying silent. TETHERKITNEXT_WARN_TR(Msg::kNetBpfBatchFrameLimit, read_frames_.capacity(), total - offset); break; } } - // When BIOCGSTATS occasionally fails, keep the previous cumulative value -- reporting 0 would make the consumer's difference underflow; - // see the explanation of last_kernel_drops_. + // When BIOCGSTATS occasionally fails, keep the previous cumulative value; reporting 0 would make + // the consumer's difference underflow; see the explanation of last_kernel_drops_. if (const auto stats = QueryKernelStats()) { last_kernel_drops_ = stats->dropped; } @@ -364,8 +381,9 @@ Result BpfLink::WriteFramesIndividually(FrameBatch frames) { if (errno == EINTR) { continue; } - // ENOBUFS is transient (the interface send queue is full) and should not be treated as a fatal error; the caller sees - // from frames_written < frames.size() that it has not finished writing. + // ENOBUFS is transient (the interface send queue is full) and should not be treated as a + // fatal error; the caller sees from frames_written < frames.size() that it has not finished + // writing. if (errno == ENOBUFS || errno == EAGAIN) { break; } @@ -383,12 +401,12 @@ Result BpfLink::WriteFramesBatched(FrameBatch frames) { // [bpf_hdr (bh_hdrlen bytes)][frame data (bh_caplen bytes)] // with each entry aligned to BPF_WORDALIGN(bh_hdrlen + bh_caplen). // - // Kernel checks: bh_hdrlen >= 18, bh_caplen == bh_datalen, bh_hdrlen <= remaining length. - // The timestamp field is ignored and need not be filled. + // Kernel checks: bh_hdrlen >= 18, bh_caplen == bh_datalen, bh_hdrlen <= remaining length. The + // timestamp field is ignored and need not be filled. // - // bh_hdrlen here takes 18 (kBpfHeaderMinBytes) rather than sizeof(struct bpf_hdr)=20: - // both are legal (the part beyond 18 is skipped by the kernel), but 18 is the most compact packing, - // and also matches the value the kernel writes in the read direction. + // bh_hdrlen here takes 18 (kBpfHeaderMinBytes) rather than sizeof(struct bpf_hdr)=20: both are + // legal (the part beyond 18 is skipped by the kernel), but 18 is the most compact packing, and + // also matches the value the kernel writes in the read direction. WriteResult result; std::size_t cursor = 0; std::uint32_t pending_frames = 0; @@ -445,7 +463,8 @@ Result BpfLink::WriteFramesBatched(FrameBatch frames) { static_cast(kBpfHeaderMinBytes)); std::memcpy(record + kBpfHeaderMinBytes, frame.data, frame.length); - // Zero the alignment padding, to avoid handing the previous batch's leftover data to the kernel. + // Zero the alignment padding, to avoid handing the previous batch's leftover data to the + // kernel. if (aligned_bytes > record_bytes) { std::memset(record + record_bytes, 0, aligned_bytes - record_bytes); } diff --git a/src/net/feth_device.cc b/src/net/feth_device.cc index 1e9ff54..9704812 100644 --- a/src/net/feth_device.cc +++ b/src/net/feth_device.cc @@ -22,8 +22,9 @@ namespace tetherkitnext::net { namespace { -/// The interface registration callback installed by the host. An atomic rather than a mutex: reads happen on every create/destroy, -/// and the destroy path is in a destructor and must be noexcept; taking a lock would introduce the possibility of throwing. +/// The interface registration callback installed by the host. An atomic rather than a mutex: reads +/// happen on every create/destroy, and the destroy path is in a destructor and must be noexcept; +/// taking a lock would introduce the possibility of throwing. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) std::atomic g_interface_registry{nullptr}; @@ -119,7 +120,8 @@ class IoctlSocket { IfDrv driver{}; std::memcpy(driver.ifd_name, interface_name.data(), interface_name.size()); driver.ifd_cmd = command; - // The kernel checks ifd_len >= sizeof(struct if_fake_request); anything shorter gets EINVAL directly. + // The kernel checks ifd_len >= sizeof(struct if_fake_request); anything shorter gets EINVAL + // directly. driver.ifd_len = sizeof(payload); driver.ifd_data = &payload; @@ -151,7 +153,8 @@ Status VerifyFethSysctls() { for (const RequiredFethSysctl& entry : kRequiredFethSysctls) { const auto value = ReadInt32Sysctl(entry.name); if (!value) { - // Some sysctls may not exist on particular macOS versions; a missing one is not an error, just log it. + // Some sysctls may not exist on particular macOS versions; a missing one is not an error, + // just log it. TETHERKITNEXT_DEBUG_TR(Msg::kNetSysctlUnreadableSkipped, entry.name, value.error().ToString()); continue; @@ -217,7 +220,8 @@ void FethInterface::Destroy() noexcept { TETHERKITNEXT_ERROR_TR(Msg::kNetDestroyFailed, name, request.error().ToString()); return; } - // feth_clone_destroy automatically unpairs the peer first internally, so we need not Unpeer first. + // feth_clone_destroy automatically unpairs the peer first internally, so we need not Unpeer + // first. if (const auto status = socket->Call(SIOCIFDESTROY, &*request, "ioctl(SIOCIFDESTROY)"); !status) { TETHERKITNEXT_ERROR_TR(Msg::kNetDestroyFailed, name, status.error().ToString()); return; @@ -229,13 +233,15 @@ void FethInterface::Destroy() noexcept { Result FethInterface::Create(std::string_view requested_name) { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto socket, IoctlSocket::Open()); - // Empty name -> fill in the driver name "feth" as a wildcard; the kernel picks the lowest free number and writes back the full name. + // Empty name -> fill in the driver name "feth" as a wildcard; the kernel picks the lowest free + // number and writes back the full name. const std::string_view name_to_request = requested_name.empty() ? std::string_view{kFethCloneName} : requested_name; TETHERKITNEXT_ASSIGN_OR_RETURN(::ifreq request, MakeIfreq(name_to_request)); - // SIOCIFCREATE and SIOCIFCREATE2 are fully equivalent for feth -- feth_clone_create ignores - // params, and the only difference of SIOCIFCREATE2 is passing one extra params pointer. Use the simple one. + // SIOCIFCREATE and SIOCIFCREATE2 are fully equivalent for feth; feth_clone_create ignores params, + // and the only difference of SIOCIFCREATE2 is passing one extra params pointer. Use the simple + // one. if (const auto status = socket.Call(SIOCIFCREATE, &request, "ioctl(SIOCIFCREATE)"); !status) { Error error = status.error(); if (error.Code() == EPERM) { @@ -253,8 +259,9 @@ Result FethInterface::Create(std::string_view requested_name) { // On wildcard creation the kernel writes the full name (including the number) back into ifr_name. std::string created_name(request.ifr_name, ::strnlen(request.ifr_name, kInterfaceNameCapacity)); - // Register first, then return: the point of registering is "in case the process is forcibly killed from this moment on, the next run can still clean it up", - // so no window may be left in between. + // Register first, then return: the point of registering is "in case the process is forcibly + // killed from this moment on, the next run can still clean it up", so no window may be left in + // between. NotifyRegistry(created_name, true); TETHERKITNEXT_INFO_TR(Msg::kNetCreated, created_name); return FethInterface{std::move(created_name)}; @@ -270,7 +277,7 @@ Status FethInterface::PeerWith(const FethInterface& peer) { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto socket, IoctlSocket::Open()); - // The reserved field is kept all zero -- the kernel checks it, and non-zero gets EINVAL directly. + // The reserved field is kept all zero; the kernel checks it, and non-zero gets EINVAL directly. FethRequest payload{}; std::memcpy(payload.u.peer_name, peer.Name().data(), peer.Name().size()); @@ -360,8 +367,8 @@ Status FethInterface::SetMacAddress(const MacAddress& mac) { TETHERKITNEXT_ASSIGN_OR_RETURN(const auto socket, IoctlSocket::Open()); TETHERKITNEXT_ASSIGN_OR_RETURN(::ifreq request, MakeIfreq(name_)); - // feth_ioctl passes ifr_addr directly to ifnet_set_lladdr(ifp, sa_data, sa_len), - // looking only at sa_len and sa_data, without verifying sa_family. + // feth_ioctl passes ifr_addr directly to ifnet_set_lladdr(ifp, sa_data, sa_len), looking only at + // sa_len and sa_data, without verifying sa_family. request.ifr_addr.sa_len = static_cast(mac.size()); request.ifr_addr.sa_family = AF_LINK; std::memcpy(request.ifr_addr.sa_data, mac.data(), mac.size()); @@ -379,9 +386,9 @@ Status FethInterface::SetMacAddress(const MacAddress& mac) { } Result FethInterface::QueryMacAddress() const { - // Reading the MAC goes through getifaddrs + AF_LINK rather than an ioctl: macOS's SDK only provides - // SIOCSIFLLADDR (write), with no corresponding read ioctl. getifaddrs is the - // standard way to read link addresses on BSD, and needs no extra privileges. + // Reading the MAC goes through getifaddrs + AF_LINK rather than an ioctl: macOS's SDK only + // provides SIOCSIFLLADDR (write), with no corresponding read ioctl. getifaddrs is the standard + // way to read link addresses on BSD, and needs no extra privileges. ::ifaddrs* list = nullptr; if (::getifaddrs(&list) != 0) { return std::unexpected(Error::FromErrno(0, Tr(Msg::kNetGetifaddrsFailed))); @@ -418,8 +425,8 @@ Status FethInterface::SetUp(bool up) { // Read back the current flags first and then modify, to avoid clearing other flag bits. TETHERKITNEXT_RETURN_IF_ERROR(socket.Call(SIOCGIFFLAGS, &request, "ioctl(SIOCGIFFLAGS)")); - // ifr_flags is a short, and IFF_* may exceed the range of short on 64-bit, - // so uint16 mask arithmetic is used by macOS convention. + // ifr_flags is a short, and IFF_* may exceed the range of short on 64-bit, so uint16 mask + // arithmetic is used by macOS convention. auto flags = static_cast(request.ifr_flags); if (up) { flags |= static_cast(IFF_UP); @@ -455,7 +462,7 @@ Result FethPair::Create(std::uint32_t mtu, const MacAddress* system_ma return std::unexpected(Error::Generic(Tr(Msg::kNetFethPairNeedsRoot))); } - // 1. Verify the sysctls that get snapshotted at creation -- **must be before creation**. + // 1. Verify the sysctls that get snapshotted at creation; **must be before creation**. TETHERKITNEXT_RETURN_IF_ERROR(VerifyFethSysctls()); TETHERKITNEXT_ASSIGN_OR_RETURN(const std::uint32_t max_mtu, QueryFethMaxMtu()); @@ -467,16 +474,17 @@ Result FethPair::Create(std::uint32_t mtu, const MacAddress* system_ma TETHERKITNEXT_ASSIGN_OR_RETURN(FethInterface system_side, FethInterface::Create()); TETHERKITNEXT_ASSIGN_OR_RETURN(FethInterface driver_side, FethInterface::Create()); - // 3. Pair -- done before UP, so that the link is up from the start. + // 3. Pair: done before UP, so that the link is up from the start. TETHERKITNEXT_RETURN_IF_ERROR(driver_side.PeerWith(system_side)); - // 4. The MTU of both sides must be the same, otherwise frames one side can send cannot be received by the other. + // 4. The MTU of both sides must be the same, otherwise frames one side can send cannot be + // received by the other. TETHERKITNEXT_RETURN_IF_ERROR(system_side.SetMtu(mtu)); TETHERKITNEXT_RETURN_IF_ERROR(driver_side.SetMtu(mtu)); - // 5. Set the system-side MAC -- **must be before UP**. - // The driver side deliberately keeps the kernel-assigned address: the MACs of the two sides must differ, otherwise the same IPv6 link-local - // address triggers a DAD conflict. + // 5. Set the system-side MAC: **must be before UP**. + // The driver side keeps the kernel-assigned address: the MACs of the two sides must differ, + // otherwise the same IPv6 link-local address triggers a DAD conflict. if (system_mac != nullptr) { TETHERKITNEXT_RETURN_IF_ERROR(system_side.SetMacAddress(*system_mac)); diff --git a/src/net/loopback_link.cc b/src/net/loopback_link.cc index 4790010..194b771 100644 --- a/src/net/loopback_link.cc +++ b/src/net/loopback_link.cc @@ -74,7 +74,8 @@ Result LoopbackLink::WriteFrames(FrameBatch frames) { continue; } if (sent_.size() >= config_.sent_capacity) { - // Consistent with real BPF: stop when it cannot fit, letting the caller see from frames_written that it did not finish writing. + // Consistent with real BPF: stop when it cannot fit, letting the caller see from + // frames_written that it did not finish writing. break; } sent_.emplace_back(frame.data, frame.data + frame.length); diff --git a/src/rndis/CMakeLists.txt b/src/rndis/CMakeLists.txt index fefcb3f..1941c96 100644 --- a/src/rndis/CMakeLists.txt +++ b/src/rndis/CMakeLists.txt @@ -1,8 +1,9 @@ -# tk_rndis -- RNDIS protocol layer +# tk_rndis: RNDIS protocol layer # -# A pure-logic module: it only does wire-format encoding/decoding and state-machine simulation, **and touches no I/O**. -# This constraint is deliberate -- it lets the entire RNDIS implementation be fully covered by unit tests on -# machines without a real device (this project's development machines have neither USB devices nor root privileges). +# A pure-logic module: it only does wire-format encoding/decoding and state-machine simulation, +# **and touches no I/O**. This constraint is intentional: it lets the entire RNDIS implementation be +# fully covered by unit tests on machines without a real device (this project's development machines +# have neither USB devices nor root privileges). add_library( tk_rndis STATIC diff --git a/src/rndis/messages.cc b/src/rndis/messages.cc index 05f8547..d75f57c 100644 --- a/src/rndis/messages.cc +++ b/src/rndis/messages.cc @@ -14,8 +14,9 @@ namespace { /// Constructs an error carrying the name of an RNDIS status code. /// -/// The mapping from status codes to names exists in only one place, protocol.cc (tk_common does not know RNDIS), -/// so the name is spliced directly into the context string here, and Error itself keeps only the raw numeric value. +/// The mapping from status codes to names exists in only one place, protocol.cc (tk_common does not +/// know RNDIS), so the name is spliced directly into the context string here, and Error itself +/// keeps only the raw numeric value. Error MakeStatusError(std::uint32_t status, std::string_view what) { const std::string_view name = StatusName(status); if (name.empty()) { @@ -69,9 +70,11 @@ void WriteHeader(std::span buffer, MessageType type, std::uint32_t me StoreLe32(buffer.data() + kMessageLengthOffset, message_length); } -/// Parses an embedded buffer described by an "offset + length", with the base point being message start + 8. +/// Parses an embedded buffer described by an "offset + length", with the base point being message +/// start + 8. /// -/// Returns a view pointing into `buffer`. Returns an error when the offset or length is out of bounds. +/// Returns a view pointing into `buffer`. Returns an error when the offset or length is out of +/// bounds. Result> ResolveInlineBuffer(std::span buffer, std::uint32_t message_length, std::uint32_t relative_offset, @@ -159,12 +162,12 @@ Result DecodeInitializeComplete(std::span b Result Negotiate(const InitializeComplete& complete, std::uint32_t requested_mtu, std::uint32_t host_transfer_size_limit) { - // ---- The medium must be Ethernet ---- + // The medium must be Ethernet if (complete.medium != ToRaw(Medium::kEthernet)) { return std::unexpected(Error::Generic(Tr(Msg::kRndisUnsupportedMedium, complete.medium))); } - // ---- Connection-oriented devices are not supported ---- + // Connection-oriented devices are not supported const bool connectionless = (complete.device_flags & static_cast(DeviceFlags::kConnectionless)) != 0; const bool connection_oriented = @@ -177,7 +180,7 @@ Result Negotiate(const InitializeComplete& complete, TETHERKITNEXT_WARN_TR(Msg::kRndisNoConnectionlessFlag, complete.device_flags); } - // ---- Version ---- + // Version if (complete.major_version != kMajorVersion) { return std::unexpected(Error::Generic( Tr(Msg::kRndisUnsupportedMajorVersion, complete.major_version, kMajorVersion))); @@ -186,12 +189,12 @@ Result Negotiate(const InitializeComplete& complete, NegotiatedParameters params; params.connectionless = true; - // ---- MaxPacketsPerMessage: treat 0 as 1 ---- - // Mainline Linux gadget reports 1; Android kernels with the Qualcomm uplink aggregation patch report 3 or more. + // MaxPacketsPerMessage: treat 0 as 1 Mainline Linux gadget reports 1; Android kernels with the + // Qualcomm uplink aggregation patch report 3 or more. params.max_packets_per_message = std::max(1, complete.max_packets_per_message); - // ---- PacketAlignmentFactor: clamp to 7 ---- - // Exceeding 7 is a protocol violation. Without clamping, 1u << factor would overflow or produce an absurd padding length. + // PacketAlignmentFactor: clamp to 7 Exceeding 7 is a protocol violation. Without clamping, 1u << + // factor would overflow or produce an absurd padding length. std::uint32_t alignment_factor = complete.packet_alignment_factor; if (alignment_factor > kMaxPacketAlignmentFactor) { TETHERKITNEXT_WARN_TR(Msg::kRndisAlignmentFactorClamped, alignment_factor, @@ -200,15 +203,16 @@ Result Negotiate(const InitializeComplete& complete, } params.tx_alignment_bytes = 1U << alignment_factor; - // ---- MaxTransferSize: clamp in both directions ---- + // MaxTransferSize: clamp in both directions std::uint32_t device_limit = complete.max_transfer_size; if (device_limit <= kHardHeaderBytes) { return std::unexpected( Error::Generic(Tr(Msg::kRndisMaxTransferTooSmall, device_limit, kHardHeaderBytes))); } - // Clamp upward: some WinCE / Windows Mobile devices claim an 8KB or 16KB jumbo-frame limit, - // which is meaningless at this link rate and would only make us allocate huge transfer buffers. Do not follow the device blindly. + // Clamp upward: some WinCE / Windows Mobile devices claim an 8KB or 16KB jumbo-frame limit, which + // is meaningless at this link rate and would only make us allocate huge transfer buffers. Do not + // follow the device blindly. if (device_limit > host_transfer_size_limit) { TETHERKITNEXT_INFO_TR(Msg::kRndisMaxTransferClampedToHost, device_limit, host_transfer_size_limit); @@ -216,8 +220,9 @@ Result Negotiate(const InitializeComplete& complete, } params.device_max_transfer_size = device_limit; - // Clamp downward: if the device cannot fit a full frame computed from requested_mtu, back-derive a feasible MTU. - // Measured case: the HTC Diamond reports 1536, smaller than hard_mtu(1558), and the MTU needs to drop to 1478. + // Clamp downward: if the device cannot fit a full frame computed from requested_mtu, back-derive + // a feasible MTU. Measured case: the HTC Diamond reports 1536, smaller than hard_mtu(1558), and + // the MTU needs to drop to 1478. params.mtu = requested_mtu; const std::uint32_t hard_mtu = HardMtuFor(requested_mtu); if (device_limit < hard_mtu) { @@ -247,7 +252,8 @@ Result EncodeHalt(std::uint32_t request_id, std::span Result Encode(const QueryRequest& request, std::span buffer) { // An undocumented but mandatory rule (see the comment on QueryRequest::expected_response_bytes): // variable-length OID -> InformationBufferLength must be 0; - // fixed-length OID -> must be >= the expected response length, and the message tail must really have that many bytes. + // fixed-length OID -> must be >= the expected response length, and the message tail must really + // have that many bytes. const bool variable_length = IsVariableLengthOid(request.oid); const std::uint32_t info_length = variable_length ? 0 : request.expected_response_bytes; @@ -288,8 +294,9 @@ Result DecodeQueryComplete(std::span buffer) { }; if (status != ToRaw(StatusCode::kSuccess)) { - // On failure the information buffer is not parsed -- the device may not have filled it. The status is returned as-is for the caller to judge, - // because "some optional OID is unsupported" is a normal situation and should not always be treated as fatal. + // On failure the information buffer is not parsed; the device may not have filled it. The + // status is returned as-is for the caller to judge, because "some optional OID is unsupported" + // is a normal situation and should not always be treated as fatal. return complete; } @@ -343,7 +350,7 @@ Result DecodeSetComplete(std::span buffer) { Result EncodeReset(std::span buffer) { TETHERKITNEXT_RETURN_IF_ERROR(RequireCapacity(buffer, kResetMsgBytes, "REMOTE_NDIS_RESET_MSG")); WriteHeader(buffer, MessageType::kReset, kResetMsgBytes); - // Offset 8 is Reserved, not RequestId -- 0 must be written. + // Offset 8 is Reserved, not RequestId: 0 must be written. StoreLe32(buffer.data() + kResetReservedOffset, 0); return kResetMsgBytes; } @@ -424,7 +431,8 @@ Result DecodeIndicateStatus(std::span buffer) { const std::uint32_t relative_offset = LoadLe32(base + kIndicateStatusBufferOffsetOffset); const std::uint64_t candidates[] = { static_cast(kOffsetFieldBase) + relative_offset, // consistent with QUERY/SET - relative_offset, // literal reading of the MS docs + // literal reading of the MS docs + relative_offset, }; for (const std::uint64_t offset : candidates) { if (offset + buffer_length <= message_length) { @@ -435,16 +443,16 @@ Result DecodeIndicateStatus(std::span buffer) { } if (indication.status_buffer.empty()) { - // Both interpretations are out of bounds: discard the optional payload, but **still return success** -- the status itself is useful - // (for example it may be MEDIA_DISCONNECT), and the link must not be judged dead - // just because an optional field cannot be parsed. + // Both interpretations are out of bounds: discard the optional payload, but **still return + // success**; the status itself is useful (for example it may be MEDIA_DISCONNECT), and the link + // must not be judged dead just because an optional field cannot be parsed. TETHERKITNEXT_WARN_TR(Msg::kRndisIndicateStatusBufferOutOfBounds, relative_offset, buffer_length, message_length); return indication; } - // When exactly 8 bytes, parse as RNDIS_Diagnostic_Info -- the device uses it to report what is invalid in the - // message we sent, which is highly valuable for troubleshooting. + // When exactly 8 bytes, parse as RNDIS_Diagnostic_Info; the device uses it to report what is + // invalid in the message we sent, which is highly valuable for troubleshooting. if (indication.status_buffer.size() == kDiagnosticInfoBytes) { indication.has_diagnostic_info = true; indication.diagnostic_status = diff --git a/src/rndis/protocol.cc b/src/rndis/protocol.cc index 0ddbae9..ea83ae4 100644 --- a/src/rndis/protocol.cc +++ b/src/rndis/protocol.cc @@ -34,7 +34,8 @@ std::string_view MessageTypeName(std::uint32_t message_type) noexcept { return "RNDIS_MSG_BUS"; } - // CONDIS (connection-oriented) message family: not supported by this project, but must be reportable explicitly. + // CONDIS (connection-oriented) message family: not supported by this project, but must be + // reportable explicitly. switch (static_cast(message_type & ~kMessageCompletionFlag)) { case CondisMessageType::kCreateVc: return "RNDIS_MSG_MP_CREATE_VC"; diff --git a/src/rndis/state_machine.cc b/src/rndis/state_machine.cc index 1916b57..0a42eea 100644 --- a/src/rndis/state_machine.cc +++ b/src/rndis/state_machine.cc @@ -14,9 +14,10 @@ namespace { /// Size of the placeholder buffer given when QUERYing a fixed-length OID. /// -/// For OIDs that return fixed-length results, InformationBufferLength must be >= the expected response length, otherwise Microsoft's -/// ActiveSync implementation replies RNDIS_STATUS_INVALID_LENGTH. Linux gives 48 when querying the MAC, -/// and the same "loose but sufficient" value is reused here as the default placeholder for most fixed-length OIDs. +/// For OIDs that return fixed-length results, InformationBufferLength must be >= the expected +/// response length, otherwise Microsoft's ActiveSync implementation replies +/// RNDIS_STATUS_INVALID_LENGTH. Linux gives 48 when querying the MAC, and the same "loose but +/// sufficient" value is reused here as the default placeholder for most fixed-length OIDs. constexpr std::uint32_t kFixedOidPlaceholderBytes = 48; /// Extracts a string from an ASCII buffer that may not be NUL-terminated. @@ -63,8 +64,9 @@ StateMachine::StateMachine(ControlChannel& channel, StateMachineObserver& observ } std::uint32_t StateMachine::NextRequestId() noexcept { - // Skip 0: some devices treat RequestId == 0 as an invalid value (FreeBSD's implementation simply fills in all 0s, - // which shows that devices generally do not validate it, but to be conservative we avoid it anyway). + // Skip 0: some devices treat RequestId == 0 as an invalid value (FreeBSD's implementation simply + // fills in all 0s, which shows that devices generally do not validate it, but to be conservative + // we avoid it anyway). const std::uint32_t id = next_request_id_++; if (next_request_id_ == 0) { next_request_id_ = 1; @@ -92,7 +94,8 @@ Result StateMachine::PumpOnce(std::optional expected_reply, channel_->ReceiveMessage()); if (message.empty()) { - // Spec: when the device has no valid response yet it returns 1 byte of 0x00 rather than a STALL. Not an error. + // Spec: when the device has no valid response yet it returns 1 byte of 0x00 rather than a + // STALL. Not an error. return false; } MarkDeviceActivity(); @@ -103,31 +106,46 @@ Result StateMachine::PumpOnce(std::optional expected_reply, name.empty() ? Text(Msg::kRndisUnknownMessage) : name, header.message_type, header.message_length); - // ---- Messages actively pushed by the device: dispatch them away and keep waiting for the one we want ---- + // Messages actively pushed by the device: dispatch them away and keep waiting for the one we want if (header.message_type == ToRaw(MessageType::kIndicateStatus)) { HandleIndicateStatus(message); return false; } if (header.message_type == ToRaw(MessageType::kKeepAlive)) { - // Device-initiated keepalive. **Must reply**, otherwise the device may judge the host dead and disconnect. + // Device-initiated keepalive. **Must reply**, otherwise the device may judge the host dead and + // disconnect. TETHERKITNEXT_RETURN_IF_ERROR(HandleDeviceKeepAlive(message)); return false; } - // ---- Messages of connection-oriented devices: explicitly report unsupported, rather than a vague "unknown message" ---- + // Messages of connection-oriented devices: explicitly report unsupported, rather than a vague + // "unknown message" if (IsCondis(header.message_type)) { return std::unexpected(Error::Generic(Tr(Msg::kRndisCondisMessageReceived, name.empty() ? Text(Msg::kRndisUnknown) : name))); } - // ---- Is it the one we are waiting for? ---- + // Is it the one we are waiting for? if (expected_reply.has_value() && header.message_type == ToRaw(*expected_reply)) { + // Same type is not enough: a QUERY that timed out may answer late, and two OIDs with 4-byte + // values (link speed, media state) would parse cleanly into the wrong field. Every completion + // except RESET_CMPLT echoes the RequestId at offset 8. + if (awaited_request_id_.has_value() && message.size() >= 12) { + const std::uint32_t reply_id = LoadLe32(message.data() + 8); + if (reply_id != *awaited_request_id_) { + TETHERKITNEXT_WARN_TR(Msg::kRndisDiscardStaleReply, + name.empty() ? Text(Msg::kRndisUnknown) : name, reply_id, + *awaited_request_id_); + return false; + } + } out_response = message; return true; } - // Not the one we are waiting for, and not a known push message either. Possibly a late response to a previous timed-out request -- - // discard it and continue (it cannot be treated as a fatal error, otherwise a single timeout would judge the link dead). + // Not the one we are waiting for, and not a known push message either. Possibly a late response + // to a previous timed-out request; discard it and continue (it cannot be treated as a fatal + // error, otherwise a single timeout would judge the link dead). TETHERKITNEXT_WARN_TR(Msg::kRndisDiscardUnexpectedMessage, name.empty() ? Text(Msg::kRndisUnknown) : name, header.message_type); return false; @@ -135,17 +153,32 @@ Result StateMachine::PumpOnce(std::optional expected_reply, Result StateMachine::Transact(std::span request, MessageType expected_reply) { + // Remember which RequestId the reply must echo (see PumpOnce). RESET has none. + struct AwaitGuard { + std::optional& slot; + + ~AwaitGuard() { slot.reset(); } + } const await_guard{awaited_request_id_}; + + if (expected_reply != MessageType::kResetComplete && request.size() >= 12) { + awaited_request_id_ = LoadLe32(request.data() + 8); + } + TETHERKITNEXT_RETURN_IF_ERROR(channel_->SendMessage(request)); - // Wait first for the RESPONSE_AVAILABLE notification on the interrupt endpoint, then fetch the response. + // Wait first for the RESPONSE_AVAILABLE notification on the interrupt endpoint, then fetch the + // response. // // Both kinds of device behavior must be supported: // * The spec way is to wait for the notification; - // * But there are also devices that "must have the interrupt endpoint read once before they answer on the control endpoint"; - // * And Linux simply ignores the interrupt endpoint entirely and polls the control endpoint directly. - // So: if there is an interrupt endpoint, wait for a notification once first (a timeout is not an error either), and then poll regardless. - // It likewise cannot be 0 (timeout=0 is an infinite wait on darwin). Note that response_poll_interval - // can be configured to 0 (it is in the tests), so max must be used as a backstop here. + // * But there are also devices that "must have the interrupt endpoint read once before they + // answer on the control endpoint"; + // * And Linux simply ignores the interrupt endpoint entirely and polls the control endpoint + // directly. + // So: if there is an interrupt endpoint, wait for a notification once first (a timeout is not an + // error either), and then poll regardless. It likewise cannot be 0 (timeout=0 is an infinite wait + // on darwin). Note that response_poll_interval can be configured to 0 (it is in the tests), so + // max must be used as a backstop here. const std::uint32_t notification_timeout = std::max(kProbeOnlyTimeoutMillis, std::min(config_.control_timeout_millis, config_.response_poll_interval_millis * 4)); @@ -161,8 +194,9 @@ Result StateMachine::Transact(std::span if (matched) { return Exchange{.response = response}; } - // Not ready yet. Sleep a little and try again -- it must sleep here, otherwise it would turn the control endpoint into busy polling, - // and on Apple Silicon each control transfer is itself a millisecond-level cost. + // Not ready yet. Sleep a little and try again: it must sleep here, otherwise it would turn the + // control endpoint into busy polling, and on Apple Silicon each control transfer is itself a + // millisecond-level cost. std::this_thread::sleep_for( std::chrono::milliseconds(config_.response_poll_interval_millis)); } @@ -180,7 +214,7 @@ Result StateMachine::Transact(std::span void StateMachine::HandleIndicateStatus(std::span message) { const auto indication = DecodeIndicateStatus(message); if (!indication) { - // A parse failure should not kill the link -- this is a purely informational message. + // A parse failure should not kill the link; this is a purely informational message. TETHERKITNEXT_WARN_TR(Msg::kRndisIndicateStatusParseFailed, indication.error().ToString()); return; } @@ -188,7 +222,8 @@ void StateMachine::HandleIndicateStatus(std::span message) { const std::string_view status_name = StatusName(indication->status); if (indication->has_diagnostic_info) { // The device uses Rndis_Diagnostic_Info to tell us "byte N of the message you sent is invalid", - // which is highly valuable for tracking down our own encoding bugs, so it is printed separately. + // which is highly valuable for tracking down our own encoding bugs, so it is printed + // separately. TETHERKITNEXT_WARN_TR(Msg::kRndisDeviceIndicatedWithDiagnostics, status_name.empty() ? Text(Msg::kRndisUnknownStatus) : status_name, indication->status, indication->diagnostic_status, @@ -217,14 +252,16 @@ void StateMachine::HandleIndicateStatus(std::span message) { break; default: - // Other statuses are only logged. In particular kInvalidData -- it means the message we sent has a problem, - // but the link should not be dropped on that basis (the diagnostic information has already been printed). + // Other statuses are only logged. In particular kInvalidData: it means the message we sent + // has a problem, but the link should not be dropped on that basis (the diagnostic information + // has already been printed). break; } } Status StateMachine::HandleDeviceKeepAlive(std::span message) { - // The RequestId of a device-initiated KEEPALIVE_MSG is at offset 8, the same layout as when initiated by the host. + // The RequestId of a device-initiated KEEPALIVE_MSG is at offset 8, the same layout as when + // initiated by the host. if (message.size() < kKeepAliveMsgBytes) { return std::unexpected(Error::Generic(Tr(Msg::kRndisKeepAliveMsgTooShort))); } @@ -268,7 +305,8 @@ Result> StateMachine::QueryOid(Oid oid, std::uint32_t if (complete.status != ToRaw(StatusCode::kSuccess)) { const std::string_view status_name = StatusName(complete.status); if (!fatal) { - // An optional OID returning NOT_SUPPORTED is completely normal (for example OID_GEN_PHYSICAL_MEDIUM). + // An optional OID returning NOT_SUPPORTED is completely normal (for example + // OID_GEN_PHYSICAL_MEDIUM). TETHERKITNEXT_DEBUG_TR(Msg::kRndisOptionalOidUnsupported, name, status_name.empty() ? Text(Msg::kRndisUnknownStatus) : status_name); return std::span{}; @@ -309,8 +347,8 @@ Status StateMachine::SetOidUint32(Oid oid, std::uint32_t value) { // ============================================================================= Status StateMachine::CollectDeviceInfo() { - // ---- Physical medium: **optional OID**, failure is not fatal ---- - // Linux passes in_len of 4 when querying it, and on failure just continues as UNSPECIFIED. + // Physical medium: **optional OID**, failure is not fatal Linux passes in_len of 4 when querying + // it, and on failure just continues as UNSPECIFIED. if (const auto medium = QueryOid(Oid::kGenPhysicalMedium, 4, /*fatal=*/false); medium && !medium->empty()) { if (const auto value = ParseUint32(*medium)) { @@ -318,8 +356,8 @@ Status StateMachine::CollectDeviceInfo() { } } - // ---- Permanent MAC: **fatal** ---- - // This is the address the host-side feth is to adopt; without it the NIC cannot be built correctly. + // Permanent MAC: **fatal** This is the address the host-side feth is to adopt; without it the NIC + // cannot be built correctly. { TETHERKITNEXT_ASSIGN_OR_RETURN( const std::span payload, @@ -329,7 +367,7 @@ Status StateMachine::CollectDeviceInfo() { TETHERKITNEXT_INFO_TR(Msg::kRndisPermanentMac, FormatMac(info_.permanent_address).data()); } - // ---- Current MAC: not fatal (the same as the permanent MAC on most devices) ---- + // Current MAC: not fatal (the same as the permanent MAC on most devices) if (const auto payload = QueryOid(Oid::kEthernetCurrentAddress, kFixedOidPlaceholderBytes, /*fatal=*/false); payload && !payload->empty()) { @@ -343,13 +381,14 @@ Status StateMachine::CollectDeviceInfo() { info_.has_current_address = true; } - // ---- Maximum frame length: not fatal (the negotiation result already gave the MTU) ---- + // Maximum frame length: not fatal (the negotiation result already gave the MTU) if (const auto payload = QueryOid(Oid::kGenMaximumFrameSize, 4, /*fatal=*/false); payload && !payload->empty()) { if (const auto value = ParseUint32(*payload)) { info_.maximum_frame_size = *value; - // The device says it can only receive at most N bytes of payload, while the MTU we negotiated is larger -- listen to the device. + // The device says it can only receive at most N bytes of payload, while the MTU we negotiated + // is larger; listen to the device. if (*value != 0 && *value < parameters_.mtu) { TETHERKITNEXT_WARN_TR(Msg::kRndisMtuLoweredToDeviceFrameSize, *value, parameters_.mtu); parameters_.mtu = *value; @@ -357,7 +396,7 @@ Status StateMachine::CollectDeviceInfo() { } } - // ---- Link speed: not fatal, used only for logging ---- + // Link speed: not fatal, used only for logging if (const auto payload = QueryOid(Oid::kGenLinkSpeed, 4, /*fatal=*/false); payload && !payload->empty()) { if (const auto value = ParseUint32(*payload)) { @@ -365,7 +404,7 @@ Status StateMachine::CollectDeviceInfo() { } } - // ---- Media connect status: not fatal. **Note that 0 means connected** ---- + // Media connect status: not fatal. **Note that 0 means connected** if (const auto payload = QueryOid(Oid::kGenMediaConnectStatus, 4, /*fatal=*/false); payload && !payload->empty()) { if (const auto value = ParseUint32(*payload)) { @@ -373,11 +412,12 @@ Status StateMachine::CollectDeviceInfo() { link_connected_ = info_.media_state == MediaState::kConnected; } } else { - // If it cannot be queried, assume connected -- since the device is running RNDIS, the link is most likely up. + // If it cannot be queried, assume connected, since the device is running RNDIS, the link is + // most likely up. link_connected_ = true; } - // ---- Vendor information: purely for diagnostics ---- + // Vendor information: purely for diagnostics if (const auto payload = QueryOid(Oid::kGenVendorId, 4, /*fatal=*/false); payload && !payload->empty()) { if (const auto value = ParseUint32(*payload)) { @@ -405,7 +445,7 @@ Status StateMachine::Start() { TransitionTo(State::kInitializing); - // ---- Step 1: INITIALIZE ---- + // Step 1: INITIALIZE { TETHERKITNEXT_ASSIGN_OR_RETURN( const std::uint32_t written, @@ -435,7 +475,8 @@ Status StateMachine::Start() { } parameters_ = *negotiated; - // The aggregated packet count the device reports is only its **claim**; the caller may distrust it (see the config item comments). + // The aggregated packet count the device reports is only its **claim**; the caller may distrust + // it (see the config item comments). if (config_.max_tx_packets_per_message != 0 && parameters_.max_packets_per_message > config_.max_tx_packets_per_message) { TETHERKITNEXT_INFO_TR(Msg::kRndisMaxPacketsClamped, parameters_.max_packets_per_message, @@ -450,14 +491,14 @@ Status StateMachine::Start() { TransitionTo(State::kInitialized); - // ---- Steps 2~4: collect device information ---- + // Steps 2~4: collect device information if (const auto status = CollectDeviceInfo(); !status) { SendHalt(); TransitionTo(State::kUninitialized); return status; } - // ---- Step 5: set the packet filter -> the device enters data-initialized and data starts flowing ---- + // Step 5: set the packet filter -> the device enters data-initialized and data starts flowing if (const auto status = SetOidUint32(Oid::kGenCurrentPacketFilter, config_.packet_filter); !status) { SendHalt(); @@ -494,17 +535,19 @@ Status StateMachine::Poll() { return Ok(); // not ready or shutting down, nothing to do } - // ---- First drain the messages actively pushed by the device ---- + // First drain the messages actively pushed by the device // - // If not drained they pile up in the device's response queue, pushing the responses to our later requests further back, - // so every Transact has to loop several more times to get the one it wants. + // If not drained they pile up in the device's response queue, pushing the responses to our later + // requests further back, so every Transact has to loop several more times to get the one it + // wants. // - // Read the control endpoint only when there is an interrupt notification -- otherwise every Poll would have to send one - // GET_ENCAPSULATED_RESPONSE, which is a millisecond-level cost on Apple Silicon. + // Read the control endpoint only when there is an interrupt notification; otherwise every Poll + // would have to send one GET_ENCAPSULATED_RESPONSE, which is a millisecond-level cost on Apple + // Silicon. // - // WARNING: **Never pass 0 here**: on darwin libusb a timeout=0 means wait forever, - // which would hang the control thread permanently. Use kProbeOnlyTimeoutMillis (1 ms) -- - // Poll itself only runs once every few hundred milliseconds, so a 1 ms block can be ignored. + // WARNING: **Never pass 0 here**: on darwin libusb a timeout=0 means wait forever, which would + // hang the control thread permanently. Use kProbeOnlyTimeoutMillis (1 ms): Poll itself only runs + // once every few hundred milliseconds, so a 1 ms block can be ignored. if (channel_->WaitForNotification(kProbeOnlyTimeoutMillis) == NotificationResult::kResponseAvailable) { std::span ignored; @@ -515,8 +558,8 @@ Status StateMachine::Poll() { return std::unexpected( Error{pumped.error()}.WithContext(Tr(Msg::kRndisDrainControlFailed))); } - // PumpOnce returns false without an error when there are no more messages, so it cannot distinguish "empty" from - // "handled one push". Judge once more using the notification state. + // PumpOnce returns false without an error when there are no more messages, so it cannot + // distinguish "empty" from "handled one push". Judge once more using the notification state. if (channel_->WaitForNotification(kProbeOnlyTimeoutMillis) != NotificationResult::kResponseAvailable) { break; @@ -524,10 +567,12 @@ Status StateMachine::Poll() { } } - // ---- Keepalive ---- + // Keepalive // - // The semantics are to send only when "more than the keepalive period has passed since any message was last received from the device", not to send unconditionally on a timer. - // Pointless keepalive round trips while the channel is active are purely wasteful (especially on Apple Silicon). + // The semantics are to send only when "more than the keepalive period has passed since any + // message was last received from the device", not to send unconditionally on a timer. Pointless + // keepalive round trips while the channel is active are purely wasteful (especially on Apple + // Silicon). const Nanos now = MonotonicNanos(); if (now < next_keepalive_deadline_) { return Ok(); @@ -567,7 +612,8 @@ Status StateMachine::Poll() { } if (complete->status != ToRaw(StatusCode::kSuccess)) { - // The device explicitly replied with a failure status. This usually means the device wants us to reset. + // The device explicitly replied with a failure status. This usually means the device wants us + // to reset. const std::string_view name = StatusName(complete->status); TETHERKITNEXT_WARN_TR(Msg::kRndisKeepAliveRejected, name.empty() ? Text(Msg::kRndisUnknownStatus) : name); @@ -586,8 +632,8 @@ Status StateMachine::Poll() { Status StateMachine::Reset() { TETHERKITNEXT_INFO_TR(Msg::kRndisResetStarted); - // RESET_MSG **has no RequestId** (offset 8 is Reserved), so it cannot be paired by ID, - // and only one RESET can be in flight at a time. + // RESET_MSG **has no RequestId** (offset 8 is Reserved), so it cannot be paired by ID, and only + // one RESET can be in flight at a time. TETHERKITNEXT_ASSIGN_OR_RETURN(const std::uint32_t written, EncodeReset(request_buffer_)); TETHERKITNEXT_ASSIGN_OR_RETURN( const Exchange exchange, @@ -610,10 +656,11 @@ Status StateMachine::Reset() { observer_->OnDeviceReset(complete.addressing_reset); if (complete.addressing_reset) { - // AddressingReset non-zero -> the device dropped the packet filter and multicast table, and **it must be resent**, - // otherwise data will not flow again after the reset. + // AddressingReset non-zero -> the device dropped the packet filter and multicast table, and + // **it must be resent**, otherwise data will not flow again after the reset. // - // (This driver does not maintain a multicast table -- ALL_MULTICAST is enabled in the packet filter, so only the filter needs resending. + // (This driver does not maintain a multicast table; ALL_MULTICAST is enabled in the packet + // filter, so only the filter needs resending. // If SET OID_802_3_MULTICAST_LIST is added in the future, it must be replayed here too.) const std::uint32_t filter = active_packet_filter_ != 0 ? active_packet_filter_ : config_.packet_filter; @@ -632,7 +679,8 @@ Status StateMachine::Reset() { // ============================================================================= void StateMachine::SendHalt() noexcept { - // The device **does not reply** to HALT_MSG; once sent it can be considered to have entered uninitialized. + // The device **does not reply** to HALT_MSG; once sent it can be considered to have entered + // uninitialized. const auto written = EncodeHalt(NextRequestId(), request_buffer_); if (!written) { TETHERKITNEXT_WARN_TR(Msg::kRndisEncodeHaltFailed, written.error().ToString()); @@ -641,7 +689,8 @@ void StateMachine::SendHalt() noexcept { if (const auto status = channel_->SendMessage(std::span{request_buffer_.data(), *written}); !status) { - // Failures on the shutdown path are only logged -- the device may already have been unplugged, which is quite normal. + // Failures on the shutdown path are only logged; the device may already have been unplugged, + // which is quite normal. TETHERKITNEXT_DEBUG_TR(Msg::kRndisSendHaltFailed, status.error().ToString()); return; } @@ -654,9 +703,10 @@ void StateMachine::Stop() { } TransitionTo(State::kHalting); - // First clear the packet filter to make the device stop sending data (spec: filter = 0 makes the device fall back to - // RNDIS-initialized), then send HALT. Continue to send HALT even if clearing fails -- - // if it is not sent, the device will keep thinking the host is still there, and the state will not be clean the next time it is plugged in. + // First clear the packet filter to make the device stop sending data (spec: filter = 0 makes the + // device fall back to RNDIS-initialized), then send HALT. Continue to send HALT even if clearing + // fails; if it is not sent, the device will keep thinking the host is still there, and the state + // will not be clean the next time it is plugged in. if (active_packet_filter_ != 0) { if (const auto status = SetOidUint32(Oid::kGenCurrentPacketFilter, 0); !status) { TETHERKITNEXT_DEBUG_TR(Msg::kRndisClearPacketFilterFailed, status.error().ToString()); diff --git a/src/usb/CMakeLists.txt b/src/usb/CMakeLists.txt index 4cc8207..40f82ec 100644 --- a/src/usb/CMakeLists.txt +++ b/src/usb/CMakeLists.txt @@ -1,7 +1,8 @@ -# tk_usb -- USB transport layer +# tk_usb: USB transport layer # -# Wraps libusb: device discovery and identification, interface claiming, control channel, interrupt notifications, async bulk transfer pool. -# It depends on tk_rndis only to get protocol constants (interface signatures, control request codes, notification format), not the state machine. +# Wraps libusb: device discovery and identification, interface claiming, control channel, interrupt +# notifications, async bulk transfer pool. It depends on tk_rndis only to get protocol constants +# (interface signatures, control request codes, notification format), not the state machine. add_library( tk_usb STATIC diff --git a/src/usb/context.cc b/src/usb/context.cc index 9bc96cd..6dafc7a 100644 --- a/src/usb/context.cc +++ b/src/usb/context.cc @@ -13,9 +13,9 @@ namespace { /// /// Why such a long timeout can be used: the darwin backend marks all bulk transfers with /// USBI_TRANSFER_OS_HANDLES_TIMEOUT (timeouts are IOKit's responsibility), and -/// libusb_get_next_timeout skips transfers carrying that flag -- so as long as everything in flight is -/// bulk, it always returns "no timeout", and the event thread can be woken purely by the event pipe. -/// 250 ms is given here only so that RequestStop() can be noticed within one period. +/// libusb_get_next_timeout skips transfers carrying that flag, so as long as everything in flight +/// is bulk, it always returns "no timeout", and the event thread can be woken purely by the event +/// pipe. 250 ms is given here only so that RequestStop() can be noticed within one period. constexpr long kEventLoopTimeoutSeconds = 0; constexpr long kEventLoopTimeoutMicros = 250'000; @@ -86,16 +86,18 @@ void Context::RunEventLoop() noexcept { timeout.tv_usec = kEventLoopTimeoutMicros; while (!stop_requested_.load(std::memory_order_acquire)) { - // The version with a timeout is used rather than libusb_handle_events(): the latter's internal timeout is a fixed 60 seconds, - // and shutdown would respond too slowly; libusb_handle_events_completed() is not used either, because our exit - // condition is our own atomic flag rather than the completion of some transfer. + // The version with a timeout is used rather than libusb_handle_events(): the latter's internal + // timeout is a fixed 60 seconds, and shutdown would respond too slowly; + // libusb_handle_events_completed() is not used either, because our exit condition is our own + // atomic flag rather than the completion of some transfer. const int rc = ::libusb_handle_events_timeout_completed(context_, &timeout, nullptr); if (rc == LIBUSB_SUCCESS || rc == LIBUSB_ERROR_INTERRUPTED) { continue; } if (rc == LIBUSB_ERROR_NO_DEVICE) { - // The device was unplugged. Not the event loop's fault; leave it to the upper layer's reconnection logic, and keep running here. + // The device was unplugged. Not the event loop's fault; leave it to the upper layer's + // reconnection logic, and keep running here. TETHERKITNEXT_DEBUG_TR(Msg::kUsbEventLoopNoDevice); continue; } diff --git a/src/usb/data_channel.cc b/src/usb/data_channel.cc index bed2628..9665310 100644 --- a/src/usb/data_channel.cc +++ b/src/usb/data_channel.cc @@ -16,7 +16,8 @@ namespace { /// /// The darwin backend does not provide zero-copy DMA buffers (libusb_dev_mem_alloc returns NULL), /// so we can only allocate them ourselves. Aligning to the system page size reduces the number of -/// memory segments IOKit needs when building DMA descriptors for the buffer. On Apple Silicon hw.pagesize is 16384. +/// memory segments IOKit needs when building DMA descriptors for the buffer. On Apple Silicon +/// hw.pagesize is 16384. [[nodiscard]] std::size_t QueryPageSize() { std::int64_t value = 0; std::size_t size = sizeof(value); @@ -40,7 +41,8 @@ Result> UsbDataChannel::Create( channel->parameters_ = parameters; channel->config_ = config; - // The TX buffer must not exceed the MaxTransferSize the device claims -- if it does, the device will reject or truncate. + // The TX buffer must not exceed the MaxTransferSize the device claims; if it does, the device + // will reject or truncate. channel->tx_transfer_bytes_ = std::min(config.tx_transfer_bytes, parameters.device_max_transfer_size); if (channel->tx_transfer_bytes_ < rndis::kPacketMsgHeaderBytes + parameters.mtu + @@ -145,13 +147,14 @@ Status UsbDataChannel::SubmitReceive(Slot& slot) { &UsbDataChannel::ReceiveCallbackTrampoline, &slot, static_cast(config_.rx_timeout_millis)); - // **Deliberately not setting LIBUSB_TRANSFER_SHORT_NOT_OK.** - // A short packet on bulk IN is completely normal semantics (the device ends the transfer with a short packet when it has only half a buffer of data). - // Setting this flag makes io.c re-judge "COMPLETED with actual_length != requested length" as - // LIBUSB_TRANSFER_ERROR -- then nearly every transfer would "fail". + // **Not setting LIBUSB_TRANSFER_SHORT_NOT_OK.** A short packet on bulk IN is completely normal + // semantics (the device ends the transfer with a short packet when it has only half a buffer of + // data). Setting this flag makes io.c re-judge "COMPLETED with actual_length != requested length" + // as LIBUSB_TRANSFER_ERROR; then nearly every transfer would "fail". slot.transfer->flags = 0; - // Increment the in-flight count first and then submit: otherwise the callback might finish running before the increment, making the count underflow. + // Increment the in-flight count first and then submit: otherwise the callback might finish + // running before the increment, making the count underflow. outstanding_.fetch_add(1, std::memory_order_acq_rel); const int rc = ::libusb_submit_transfer(slot.transfer); @@ -168,10 +171,11 @@ void UsbDataChannel::ReceiveCallbackTrampoline(::libusb_transfer* transfer) { } void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { - // WARNING: This function executes on the libusb **event thread** and holds ctx->event_waiters_lock. - // Therefore here: + // WARNING: This function executes on the libusb **event thread** and holds + // ctx->event_waiters_lock. Therefore here: // * a synchronous API must never be called (it would return LIBUSB_ERROR_BUSY); - // * blocking I/O must never be done (it would hold up all threads waiting on synchronous transfers); + // * blocking I/O must never be done (it would hold up all threads waiting on synchronous + // transfers); // * only do "unpack + memcpy into the lock-free queue + resubmit immediately". // The real BPF write() is handled by another thread. const ::libusb_transfer* transfer = slot.transfer; @@ -192,7 +196,8 @@ void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { const rndis::ReadOutcome outcome = reader.Next(frame); if (outcome == rndis::ReadOutcome::kFrame) { if (!batch.Push(frame)) [[unlikely]] { - // The downstream queue is full -- the BPF write thread cannot keep up. Drop and count; must not block here. + // The downstream queue is full: the BPF write thread cannot keep up. Drop and count; + // must not block here. rx_counters_->AddDroppedFull(); continue; } @@ -219,9 +224,10 @@ void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { } case LIBUSB_TRANSFER_STALL: - // Endpoint halt. Clear it and continue -- libusb_clear_halt goes through a synchronous IOKit call but has **no** - // usbi_handling_events guard, so calling it inside a callback is safe (the cost is blocking the event thread - // for tens of microseconds to milliseconds, so it is done only on a real STALL). + // Endpoint halt. Clear it and continue: libusb_clear_halt goes through a synchronous IOKit + // call but has **no** usbi_handling_events guard, so calling it inside a callback is safe + // (the cost is blocking the event thread for tens of microseconds to milliseconds, so it is + // done only on a real STALL). rx_counters_->AddIoError(); TETHERKITNEXT_WARN_TR(Msg::kUsbBulkInStall); if (const auto status = device_->ClearHalt(device_->BulkInEndpoint()); !status) { @@ -236,13 +242,15 @@ void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { break; case LIBUSB_TRANSFER_NO_DEVICE: - // The device was unplugged. Stop resubmitting, let the in-flight count converge, and leave it to the upper layer's reconnection logic. + // The device was unplugged. Stop resubmitting, let the in-flight count converge, and leave it + // to the upper layer's reconnection logic. should_resubmit = false; TETHERKITNEXT_INFO_TR(Msg::kUsbBulkInDeviceGone); break; case LIBUSB_TRANSFER_TIMED_OUT: - // rx_timeout_millis defaults to 0 (infinite), so this should not normally occur. If it occurs, keep submitting. + // rx_timeout_millis defaults to 0 (infinite), so this should not normally occur. If it + // occurs, keep submitting. rx_counters_->AddIoError(); break; @@ -260,7 +268,8 @@ void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { if (should_resubmit) { // Official guarantee: resubmitting the same transfer directly inside a callback is safe - // (usbi_handle_transfer_completion has already removed it from the flying list before calling the callback, + // (usbi_handle_transfer_completion has already removed it from the flying list before calling + // the callback, // and cleared the IN_FLIGHT flag, and does not hold itransfer->lock). const int rc = ::libusb_submit_transfer(slot.transfer); if (rc == LIBUSB_SUCCESS) { @@ -269,7 +278,8 @@ void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { TETHERKITNEXT_WARN_TR(Msg::kUsbBulkInResubmitFailed, ::libusb_error_name(rc)); } - // This transfer leaves flight here. Notifies Shutdown(), which may be waiting for the count to reach zero. + // This transfer leaves flight here. Notifies Shutdown(), which may be waiting for the count to + // reach zero. if (outstanding_.fetch_sub(1, std::memory_order_acq_rel) == 1) { const std::lock_guard guard(drain_mutex_); drain_condition_.notify_all(); @@ -281,7 +291,8 @@ void UsbDataChannel::OnReceiveComplete(Slot& slot) noexcept { // ============================================================================= bool UsbDataChannel::CanSend() const noexcept { - return tx_free_slots_ != nullptr && tx_free_slots_->SizeSnapshot() > 0; + return tx_free_slots_ != nullptr && + (held_tx_slot_ != kNoHeldSlot || tx_free_slots_->SizeSnapshot() > 0); } Result UsbDataChannel::SendFrames(std::span frames) { @@ -295,10 +306,12 @@ Result UsbDataChannel::SendFrames(std::span frames SendOutcome outcome; while (outcome.consumed < frames.size()) { - std::uint32_t slot_index = 0; - if (!tx_free_slots_->TryPop(slot_index)) { - // No free transfer slot -- this is backpressure. Faithfully return the number consumed; the caller should - // retry the remaining frames after WaitForSendCapacity(), rather than drop them. + std::uint32_t slot_index = held_tx_slot_; + held_tx_slot_ = kNoHeldSlot; + if (slot_index == kNoHeldSlot && !tx_free_slots_->TryPop(slot_index)) { + // No free transfer slot: this is backpressure. Faithfully return the number consumed; the + // caller should retry the remaining frames after WaitForSendCapacity(), rather than drop + // them. break; } Slot& slot = tx_pool_[slot_index]; @@ -313,36 +326,40 @@ Result UsbDataChannel::SendFrames(std::span frames }, device_->BulkMaxPacketSize()); - std::uint32_t scanned = 0; // number of frames consumed from the input (including skipped short frames) + // number of frames consumed from the input (including skipped short frames) + std::uint32_t scanned = 0; std::uint32_t appended = 0; // number of frames that actually went into this transfer bool append_failed = false; while (outcome.consumed + scanned < frames.size()) { const FrameView& frame = frames[outcome.consumed + scanned]; if (frame.length < kMinEthernetFrameBytes) [[unlikely]] { - // Illegal short frame: skip it and faithfully count it in skipped -- it was not sent. + // Illegal short frame: skip it and faithfully count it in skipped; it was not sent. ++scanned; ++outcome.skipped; continue; } if (!writer.TryAppend(frame.Bytes())) { append_failed = true; - break; // this batch is full (limited by bytes or packet count), or a single frame is oversized + // this batch is full (limited by bytes or packet count), or a single frame is oversized + break; } ++scanned; ++appended; } if (writer.Empty()) { - // Not a single frame was put in. Either this whole stretch is skipped short frames, or the first legal frame already exceeds - // the device's MaxTransferSize -- the latter must be skipped and advanced past, otherwise it would loop forever. + // Not a single frame was put in. Either this whole stretch is skipped short frames, or the + // first legal frame already exceeds the device's MaxTransferSize; the latter must be skipped + // and advanced past, otherwise it would loop forever. outcome.consumed += scanned; if (append_failed && outcome.consumed < frames.size()) { ++outcome.consumed; ++outcome.skipped; } - if (!tx_free_slots_->TryPush(slot_index)) { - TETHERKITNEXT_ERROR_TR(Msg::kUsbReturnTxSlotFailed, slot_index); - } + // Keep the slot for the next round. Pushing it back would make this thread a second producer + // on tx_free_slots_ next to the completion callback, and SPSC pushes from two threads can + // lose a slot (the 4-slot pool then drains and TX stalls for good). + held_tx_slot_ = slot_index; continue; } @@ -361,15 +378,13 @@ Result UsbDataChannel::SendFrames(std::span frames const int rc = ::libusb_submit_transfer(slot.transfer); if (rc != LIBUSB_SUCCESS) { outstanding_.fetch_sub(1, std::memory_order_acq_rel); - if (!tx_free_slots_->TryPush(slot_index)) { - TETHERKITNEXT_ERROR_TR(Msg::kUsbReturnTxSlotFailed, slot_index); - } + held_tx_slot_ = slot_index; // see above: never push from this thread async_send_errors_.fetch_add(1, std::memory_order_relaxed); return std::unexpected(Error::FromLibUsb(rc, Tr(Msg::kUsbSubmitBulkOutFailed))); } - // Frame counts and byte counts are tallied by the **bridge layer** (the sole writer of the TX counters). Here we only record - // the aggregation effect for diagnostics. + // Frame counts and byte counts are tallied by the **bridge layer** (the sole writer of the TX + // counters). Here we only record the aggregation effect for diagnostics. TETHERKITNEXT_TRACE_TR(Msg::kUsbBulkOutSubmitted, message_count, payload_bytes, transfer_bytes); outcome.consumed += scanned; outcome.sent_frames += appended; @@ -382,7 +397,7 @@ Result UsbDataChannel::SendFrames(std::span frames bool UsbDataChannel::WaitForSendCapacity(std::uint32_t timeout_millis) { std::unique_lock lock(send_capacity_mutex_); return send_capacity_cv_.wait_for(lock, std::chrono::milliseconds(timeout_millis), [this] { - return shutting_down_.load(std::memory_order_acquire) || + return shutting_down_.load(std::memory_order_acquire) || held_tx_slot_ != kNoHeldSlot || tx_free_slots_->SizeSnapshot() > 0; }); } @@ -410,19 +425,27 @@ void UsbDataChannel::OnSendComplete(Slot& slot) noexcept { case LIBUSB_TRANSFER_NO_DEVICE: break; + case LIBUSB_TRANSFER_TIMED_OUT: + // Mostly an idle device not reading broadcast/multicast frames (mDNS, SSDP). Still counted as + // an I/O error, but a WARN line every few seconds would flood the log panel. + async_send_errors_.fetch_add(1, std::memory_order_relaxed); + TETHERKITNEXT_DEBUG_TR(Msg::kUsbBulkOutFailed, static_cast(slot.transfer->status)); + break; + default: async_send_errors_.fetch_add(1, std::memory_order_relaxed); TETHERKITNEXT_WARN_TR(Msg::kUsbBulkOutFailed, static_cast(slot.transfer->status)); break; } - // Return the slot. Not returning it at shutdown does not matter -- nobody will take from it anyway. + // Return the slot. Not returning it at shutdown does not matter; nobody will take from it anyway. if (!shutting_down_.load(std::memory_order_acquire)) { if (!tx_free_slots_->TryPush(slot.index)) { TETHERKITNEXT_ERROR_TR(Msg::kUsbReturnTxSlotFailed, slot.index); } - // Wake the TX thread that may be waiting for a slot in WaitForSendCapacity. Empty-critical-section idiom: - // taking the lock guarantees the waiter will not miss this notification in the window between "checked the predicate" and "not yet asleep". + // Wake the TX thread that may be waiting for a slot in WaitForSendCapacity. + // Empty-critical-section idiom: taking the lock guarantees the waiter will not miss this + // notification in the window between "checked the predicate" and "not yet asleep". { const std::lock_guard guard(send_capacity_mutex_); } send_capacity_cv_.notify_one(); } @@ -441,22 +464,26 @@ void UsbDataChannel::Shutdown() { if (shutdown_complete_) { return; } - // WARNING: This function **must never** be called from the libusb event thread: below it waits for the in-flight count to reach zero, - // and the callbacks that decrement it run exactly on the event thread -- waiting there means waiting on oneself, an inevitable deadlock. - // The correct callers are the control thread or the main thread. - - // 1. Set the shutdown flag. Callbacks that see it no longer resubmit, and the in-flight count starts converging naturally. - // Also wake threads that may still be waiting for a slot in WaitForSendCapacity (under the normal teardown order - // the TX thread has already been joined by now, so this is a defensive backstop -- for example when tests drive the channel directly). + // WARNING: This function **must never** be called from the libusb event thread: below it waits + // for the in-flight count to reach zero, and the callbacks that decrement it run exactly on the + // event thread; waiting there means waiting on oneself, an inevitable deadlock. The correct + // callers are the control thread or the main thread. + + // 1. Set the shutdown flag. Callbacks that see it no longer resubmit, and the in-flight count + // starts converging naturally. + // Also wake threads that may still be waiting for a slot in WaitForSendCapacity (under the + // normal teardown order the TX thread has already been joined by now, so this is a defensive + // backstop; for example when tests drive the channel directly). shutting_down_.store(true, std::memory_order_release); { const std::lock_guard guard(send_capacity_mutex_); } send_capacity_cv_.notify_all(); // 2. Cancel the in-flight transfers. // - // On darwin libusb_cancel_transfer is AbortPipe, which cancels **all** in-flight transfers on **that endpoint**, - // so in fact each endpoint needs to be called only once; calling one by one here is an idempotent and clearer way to write it. - // LIBUSB_ERROR_NOT_FOUND means it was not in flight to begin with, which is a normal situation. + // On darwin libusb_cancel_transfer is AbortPipe, which cancels **all** in-flight transfers on + // **that endpoint**, so in fact each endpoint needs to be called only once; calling one by one + // here is an idempotent and clearer way to write it. LIBUSB_ERROR_NOT_FOUND means it was not in + // flight to begin with, which is a normal situation. for (Slot& slot : rx_pool_) { if (slot.transfer != nullptr) { const int rc = ::libusb_cancel_transfer(slot.transfer); @@ -474,8 +501,10 @@ void UsbDataChannel::Shutdown() { } } - // 3. Wait for the in-flight count to reach zero. **This step is the key to avoiding use-after-free** -- - // it must wait until every callback has finished running before transfers and buffers can be freed. + // 3. Wait for the in-flight count to reach zero. **This step is the key to avoiding + // use-after-free** + // it must wait until every callback has finished running before transfers and buffers can be + // freed. { constexpr auto kDrainTimeout = std::chrono::seconds(5); std::unique_lock lock(drain_mutex_); @@ -483,8 +512,8 @@ void UsbDataChannel::Shutdown() { return outstanding_.load(std::memory_order_acquire) == 0; }); if (!drained) { - // Timed out. Freeing the buffers now is dangerous (callbacks may still access them), so **deliberately leak** -- - // leaking a few hundred KB is far better than a use-after-free crash. + // Timed out. Freeing the buffers now is dangerous (callbacks may still access them), so + // **leak**; leaking a few hundred KB is far better than a use-after-free crash. const std::uint32_t stuck = outstanding_.load(std::memory_order_acquire); TETHERKITNEXT_ERROR_TR(Msg::kUsbTransferReclaimTimeout, stuck, (stuck * config_.rx_transfer_bytes) / 1024); diff --git a/src/usb/device.cc b/src/usb/device.cc index 708ad0b..28fd2a5 100644 --- a/src/usb/device.cc +++ b/src/usb/device.cc @@ -20,7 +20,8 @@ constexpr std::uint8_t kUnionFunctionalSubtype = 0x06; /// CDC ACM functional descriptor subtype (used to recognize real cdc-acm modems). constexpr std::uint8_t kAcmFunctionalSubtype = 0x02; -/// The hard-coded interface numbers of the Android quirk (consistent with Linux's android_rndis_quirk). +/// The hard-coded interface numbers of the Android quirk (consistent with Linux's +/// android_rndis_quirk). constexpr std::uint8_t kAndroidQuirkControlInterface = 0; constexpr std::uint8_t kAndroidQuirkDataInterface = 1; @@ -40,7 +41,8 @@ constexpr std::uint8_t kAndroidQuirkDataInterface = 1; const std::uint8_t* cursor = descriptor.extra; int remaining = descriptor.extra_length; - // The generic format of a CDC functional descriptor chain: [bLength][bDescriptorType][bDescriptorSubtype][...] + // The generic format of a CDC functional descriptor chain: + // [bLength][bDescriptorType][bDescriptorSubtype][...] while (remaining >= 3) { const std::uint8_t length = cursor[0]; if (length < 3 || length > remaining) { @@ -57,11 +59,12 @@ constexpr std::uint8_t kAndroidQuirkDataInterface = 1; return nullptr; } -/// Judges whether it is a "fake RNDIS" -- a real CDC ACM modem. +/// Judges whether it is a "fake RNDIS"; a real CDC ACM modem. /// -/// Criterion: class == 0x02 with an ACM functional descriptor carrying a **non-zero** bmCapabilities. -/// **This check can only apply to class == 0x02** -- the RNDIS function of the wireless class (0xE0) -/// repurposes the bmCapabilities field for its own use, and applying this rule to it would misjudge real RNDIS. +/// Criterion: class == 0x02 with an ACM functional descriptor carrying a **non-zero** +/// bmCapabilities. **This check can only apply to class == 0x02**; the RNDIS function of the +/// wireless class (0xE0) repurposes the bmCapabilities field for its own use, and applying this +/// rule to it would misjudge real RNDIS. [[nodiscard]] bool LooksLikeRealAcmModem(const ::libusb_interface_descriptor& descriptor) { if (descriptor.bInterfaceClass != 0x02) { return false; @@ -89,7 +92,8 @@ constexpr std::uint8_t kAndroidQuirkDataInterface = 1; return true; } -/// Whether a given interface number exists in a configuration and its signature is an RNDIS data interface. +/// Whether a given interface number exists in a configuration and its signature is an RNDIS data +/// interface. [[nodiscard]] bool HasDataInterface(const ::libusb_config_descriptor& config, std::uint8_t interface_number) { for (std::uint8_t i = 0; i < config.bNumInterfaces; ++i) { @@ -152,7 +156,8 @@ Result> FindRndisDevices(const Context& context, continue; } - // Look for the RNDIS communications interface configuration by configuration. Most devices have only one configuration, but there are exceptions. + // Look for the RNDIS communications interface configuration by configuration. Most devices have + // only one configuration, but there are exceptions. for (std::uint8_t config_index = 0; config_index < device_descriptor.bNumConfigurations; ++config_index) { ::libusb_config_descriptor* config = nullptr; @@ -194,10 +199,10 @@ Result> FindRndisDevices(const Context& context, resolved = true; } - // Android quirk: on many Android devices the CDC Union points to a nonexistent interface number, - // or there is no CDC functional descriptor at all. In this case Linux's android_rndis_quirk - // hard-codes "interface 0 = control, interface 1 = data", and requires that the probed - // communications interface really is 0. We do the same here. + // Android quirk: on many Android devices the CDC Union points to a nonexistent interface + // number, or there is no CDC functional descriptor at all. In this case Linux's + // android_rndis_quirk hard-codes "interface 0 = control, interface 1 = data", and + // requires that the probed communications interface really is 0. We do the same here. if (!resolved && candidate.control_interface == kAndroidQuirkControlInterface && HasDataInterface(*config, kAndroidQuirkDataInterface)) { candidate.data_interface = kAndroidQuirkDataInterface; @@ -211,9 +216,10 @@ Result> FindRndisDevices(const Context& context, continue; } - // DEBUG rather than INFO: enumeration is called periodically (the GUI scans every 2 seconds), - // and at INFO level this line would flood the log with a whole column of repeats. "What was found" is - // left to the caller to decide how to present -- the CLI prints the list itself, and the GUI shows it in the device card. + // DEBUG rather than INFO: enumeration is called periodically (the GUI scans every 2 + // seconds), and at INFO level this line would flood the log with a whole column of + // repeats. "What was found" is left to the caller to decide how to present; the CLI + // prints the list itself, and the GUI shows it in the device card. TETHERKITNEXT_DEBUG_TR( Msg::kUsbDeviceFound, candidate.Describe(), candidate.control_interface, candidate.data_interface, signature.interface_class, signature.interface_subclass, @@ -246,7 +252,8 @@ Result> Device::Open(const Context& context, const std::unique_ptr<::libusb_device*, void (*)(::libusb_device**)> list_guard( raw_list, [](::libusb_device** list) { ::libusb_free_device_list(list, 1); }); - // Locate the device by bus + address (more precise than VID:PID, and can distinguish multiple devices of the same model). + // Locate the device by bus + address (more precise than VID:PID, and can distinguish multiple + // devices of the same model). ::libusb_device* target = nullptr; for (ssize_t index = 0; index < count; ++index) { if (::libusb_get_bus_number(raw_list[index]) == candidate.bus_number && @@ -271,10 +278,12 @@ Result> Device::Open(const Context& context, Error::FromLibUsb(open_rc, Tr(Msg::kUsbOpenFailed, device->description_))); } - // **Deliberately not calling libusb_set_auto_detach_kernel_driver** -- see the header explanation: - // on macOS it triggers a destructive re-enumeration of the whole device, while nobody occupies the RNDIS interface to begin with. + // **Not calling libusb_set_auto_detach_kernel_driver**: see the header explanation: on macOS it + // triggers a destructive re-enumeration of the whole device, while nobody occupies the RNDIS + // interface to begin with. - // Claim the two interfaces. The communications interface comes first, because the control channel uses it. + // Claim the two interfaces. The communications interface comes first, because the control channel + // uses it. const auto claim = [&device](std::uint8_t interface_number, std::string_view role, bool& claimed_flag) -> Status { const int rc = ::libusb_claim_interface(device->handle_, interface_number); @@ -326,10 +335,11 @@ Device::~Device() { } // Order: release interfaces -> close handle. // - // WARNING: Precondition: all asynchronous transfers must already be fully reclaimed. libusb_close **will not** reclaim - // in-flight transfers for you (it just nulls dev_handle and prints a log), and afterwards IOKit aborts will still make - // callbacks run on libusb's internal thread -- if the transfer has been freed by then it is a UAF. - // Guaranteeing this is TransferPool's responsibility; see its Shutdown(). + // WARNING: Precondition: all asynchronous transfers must already be fully reclaimed. libusb_close + // **will not** reclaim in-flight transfers for you (it just nulls dev_handle and prints a log), + // and afterwards IOKit aborts will still make callbacks run on libusb's internal thread; if the + // transfer has been freed by then it is a UAF. Guaranteeing this is TransferPool's + // responsibility; see its Shutdown(). if (data_interface_claimed_) { ::libusb_release_interface(handle_, candidate_.data_interface); } @@ -386,7 +396,8 @@ Status Device::ResolveEndpoints(const ::libusb_config_descriptor& config) { if (bulk_max_packet_size_ == 0) { return std::unexpected(Error::Generic(Tr(Msg::kUsbBulkMaxPacketSizeZero))); } - // A missing interrupt endpoint is legal: Linux's host driver ignores it entirely and polls the control endpoint instead. + // A missing interrupt endpoint is legal: Linux's host driver ignores it entirely and polls the + // control endpoint instead. return Ok(); } @@ -423,7 +434,8 @@ Status Device::ClearHalt(std::uint8_t endpoint) { UsbControlChannel::UsbControlChannel(Device& device, std::uint32_t timeout_millis) : device_(&device), timeout_millis_(timeout_millis) { response_buffer_.resize(rndis::kControlBufferBytes); - // The buffer takes the endpoint's actual wMaxPacketSize (RNDIS notifications are 8 bytes, but do not hard-code this value). + // The buffer takes the endpoint's actual wMaxPacketSize (RNDIS notifications are 8 bytes, but do + // not hard-code this value). notification_buffer_.resize( std::max(rndis::kNotificationBytes, device.InterruptMaxPacketSize())); } @@ -440,7 +452,8 @@ UsbControlChannel::~UsbControlChannel() { // Asynchronous interrupt notification listening // // See the explanation in device.h: a synchronous interrupt transfer blocks forever on macOS, -// because darwin uses ReadPipeAsync (the no-timeout variant), and the timeout parameter is not honored. +// because darwin uses ReadPipeAsync (the no-timeout variant), and the timeout parameter is not +// honored. // ============================================================================= Status UsbControlChannel::StartNotificationListener() { @@ -457,8 +470,9 @@ Status UsbControlChannel::StartNotificationListener() { return std::unexpected(Error::Generic(Tr(Msg::kUsbAllocInterruptTransferFailed))); } - // Pass timeout 0: the interrupt endpoint is "only comes when something happens" anyway, and waiting forever is exactly the semantics we want. - // It will not hang any thread here -- the completion callback runs on the libusb event thread. + // Pass timeout 0: the interrupt endpoint is "only comes when something happens" anyway, and + // waiting forever is exactly the semantics we want. It will not hang any thread here; the + // completion callback runs on the libusb event thread. ::libusb_fill_interrupt_transfer( notification_transfer_, device_->Handle(), device_->InterruptInEndpoint(), reinterpret_cast(notification_buffer_.data()), @@ -488,8 +502,9 @@ void UsbControlChannel::StopNotificationListener() { } } - // Wait for the callback to come back. WARNING: same as for the data channel: **this function must not be called from the libusb event thread**, - // otherwise it is waiting on itself. After a timeout the transfer is not freed (better to leak than to use-after-free). + // Wait for the callback to come back. WARNING: same as for the data channel: **this function must + // not be called from the libusb event thread**, otherwise it is waiting on itself. After a + // timeout the transfer is not freed (better to leak than to use-after-free). constexpr int kMaxWaitMillis = 2000; for (int waited = 0; notification_in_flight_.load(std::memory_order_acquire) && waited < kMaxWaitMillis; @@ -498,7 +513,7 @@ void UsbControlChannel::StopNotificationListener() { } if (notification_in_flight_.load(std::memory_order_acquire)) { TETHERKITNEXT_ERROR_TR(Msg::kUsbInterruptReclaimTimeout); - notification_transfer_ = nullptr; // deliberate leak + notification_transfer_ = nullptr; // leak } } @@ -530,8 +545,9 @@ void UsbControlChannel::OnNotificationComplete() noexcept { break; case LIBUSB_TRANSFER_STALL: - // Interrupt endpoint STALL: clear it and continue. If it cannot be cleared, give up listening and degrade to polling the control endpoint - // (Linux's host driver does not use the interrupt endpoint at all, so this is not fatal). + // Interrupt endpoint STALL: clear it and continue. If it cannot be cleared, give up listening + // and degrade to polling the control endpoint (Linux's host driver does not use the interrupt + // endpoint at all, so this is not fatal). if (const auto status = device_->ClearHalt(device_->InterruptInEndpoint()); !status) { TETHERKITNEXT_WARN_TR(Msg::kUsbInterruptHaltClearFailed, status.error().ToString()); resubmit = false; @@ -579,7 +595,8 @@ Status UsbControlChannel::SendMessage(std::span message) { } Result> UsbControlChannel::ReceiveMessage() { - // Zero before every read: the device may write only part of it, and leftover old data would make the parser read phantom fields. + // Zero before every read: the device may write only part of it, and leftover old data would make + // the parser read phantom fields. std::memset(response_buffer_.data(), 0, response_buffer_.size()); // GET_ENCAPSULATED_RESPONSE: bmRequestType=0xA1 (IN|Class|Interface), @@ -595,9 +612,9 @@ Result> UsbControlChannel::ReceiveMessage() { Error::FromLibUsb(transferred, Tr(Msg::kUsbGetEncapsulatedFailed))); } - // Spec: when the device has no valid response yet it returns **1 byte of 0x00**, rather than a STALL. - // So any result shorter than an RNDIS message header (8 bytes) is always treated as "not ready yet", - // and an empty view is returned for the caller to retry -- this is **not** an error. + // Spec: when the device has no valid response yet it returns **1 byte of 0x00**, rather than a + // STALL. So any result shorter than an RNDIS message header (8 bytes) is always treated as "not + // ready yet", and an empty view is returned for the caller to retry; this is **not** an error. if (static_cast(transferred) < rndis::kMessageHeaderBytes) { return std::span{}; } @@ -610,8 +627,9 @@ rndis::NotificationResult UsbControlChannel::WaitForNotification(std::uint32_t t return rndis::NotificationResult::kNotSupported; } - // Only check (and consume) the atomic flag set by the event thread. **Never enter libusb's wait path** -- - // that is exactly the cause of the control thread hanging (see the explanation in device.h). + // Only check (and consume) the atomic flag set by the event thread. **Never enter libusb's wait + // path**: that is exactly the cause of the control thread hanging (see the explanation in + // device.h). if (notification_pending_.exchange(false, std::memory_order_acq_rel)) { return rndis::NotificationResult::kResponseAvailable; } @@ -619,8 +637,9 @@ rndis::NotificationResult UsbControlChannel::WaitForNotification(std::uint32_t t return rndis::NotificationResult::kTimeout; } - // When it needs to wait a while, poll this flag with our own small-step sleeps rather than letting libusb do the waiting. - // This way the worst case is only waiting an extra 1 ms, and it never blocks forever. + // When it needs to wait a while, poll this flag with our own small-step sleeps rather than + // letting libusb do the waiting. This way the worst case is only waiting an extra 1 ms, and it + // never blocks forever. for (std::uint32_t waited = 0; waited < timeout_millis; ++waited) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (notification_pending_.exchange(false, std::memory_order_acq_rel)) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c3f22c2..247aa29 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,9 +1,10 @@ -# tests -- unit tests +# tests: unit tests # # All tests are linked into a single executable, tetherkitnext_tests, because: # * doctest registration is global, so a single binary has the lowest startup overhead; # * running by module is possible just by filtering with doctest's --test-suite; -# * on the CTest side, multiple cases are registered per test-suite, so failures are still located precisely. +# * on the CTest side, multiple cases are registered per test-suite, so failures are still located +# precisely. add_executable( tetherkitnext_tests @@ -20,36 +21,35 @@ add_executable( test_rndis_state_machine.cc test_net_link.cc test_core_bridge.cc + test_core_peer_address.cc test_capi.cc) -# tk_rndis / tk_net both link tk_common PUBLICly, so there is no need to list it again (otherwise the linker reports -# "ignoring duplicate libraries"). -# tk_core links tk_common/tk_rndis/tk_net/tk_usb PUBLICly, so listing it alone is enough. -# tk_capi links tk_version and tk_core PUBLICly, so neither of those needs to be listed again. +# tk_rndis / tk_net both link tk_common PUBLICly, so there is no need to list it again (otherwise +# the linker reports "ignoring duplicate libraries"). tk_core links tk_common/tk_rndis/tk_net/tk_usb +# PUBLICly, so listing it alone is enough. tk_capi links tk_version and tk_core PUBLICly, so neither +# of those needs to be listed again. target_link_libraries(tetherkitnext_tests PRIVATE tetherkitnext_base doctest tk_capi) -# src/capi directory: capi_support.h is an internal implementation header and is not installed externally, but tests must be able to cover it directly. +# capi_support.h in src/capi is an internal header and is not installed, but tests cover it +# directly. target_include_directories(tetherkitnext_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}" "${PROJECT_SOURCE_DIR}/src/capi") # ------------------------------------------------------------------------------ # CTest registration # -# WARNING: We once hit a pitfall here where "the whole test suite silently stopped working yet everything was green"; pay attention to two points: +# Two rules keep the suite from passing while running nothing (AGENTS.md pitfalls 9 and 10): # -# 1. **The filter argument must not be quoted.** When written as `--test-suite="${_suite}"`, CMake passes -# the quotes through as part of the argument (measured: ctest -V showed it passing -# `"--test-suite="rndis.state_machine""`), and doctest matches no test case at all -- -# so "0 test cases ran", and doctest returns exit code 0 for zero matches, and ctest reports -# "Passed". The real failure is completely swallowed. +# 1. Do not quote the filter argument. With `--test-suite="${_suite}"` CMake passes the quotes +# through as part of the argument, so doctest matches no test case, runs zero tests, and still +# exits with code 0, which ctest reports as "Passed". # -# 2. So add one more safeguard: set **FAIL_REGULAR_EXPRESSION** on every case, failing as soon as -# "assertions: 0" appears in the output. Whoever mistypes a suite name in the future will turn it red immediately. -# Here you **must** use FAIL_ rather than PASS_REGULAR_EXPRESSION -- the latter -# **replaces** the exit-code judgment (documented CMake behavior); once set, real assertion failures are -# ignored instead, which digs the just-fixed pit right back. FAIL_ is layered on top of the exit code. +# 2. Set FAIL_REGULAR_EXPRESSION on every case so that "assertions: 0" in the output fails it; a +# mistyped suite name turns red immediately. Never use PASS_REGULAR_EXPRESSION: it replaces the +# exit-code judgment (documented CMake behavior), so real assertion failures would be ignored. +# FAIL_ is layered on top of the exit code. # -# In addition, a separate `all` case runs the whole binary as the **authoritative result** -- even if some suite -# was forgotten in the list below, it will still expose the failure. +# A separate `all` case runs the whole binary as the authoritative result, so a suite missing from +# the list below still exposes its failures. # ------------------------------------------------------------------------------ add_test(NAME all COMMAND tetherkitnext_tests) @@ -70,6 +70,7 @@ set(TETHERKITNEXT_TEST_SUITES net.loopback net.feth core.bridge + core.peer_address capi.support capi.basics capi.log_ring diff --git a/tests/language_guard.h b/tests/language_guard.h index da822c1..6083e87 100644 --- a/tests/language_guard.h +++ b/tests/language_guard.h @@ -1,13 +1,15 @@ // For tests: pins the interface language within a scope and restores it on exit. // -// * Why it is needed * +// Why it is needed: // -// Every test case that asserts "the error message mentions XXX" depends on the current language. And the language is **process-wide -// state**, whose default (English) may also be changed by other test cases -- without pinning, the success or failure of such cases -// depends on doctest's execution order, the hardest kind of intermittent failure to track down. +// Every test case that asserts "the error message mentions XXX" depends on the current language. +// And the language is **process-wide state**, whose default (English) may also be changed by +// other test cases, without pinning, the success or failure of such cases depends on doctest's +// execution order, the hardest kind of intermittent failure to track down. // -// So: whenever an assertion contains user-facing literal text, put a -// `const ScopedLanguage guard{Language::kChinese};` at the start of the test case. +// So: whenever an assertion contains user-facing literal text, pin the language the assertion is +// written in, e.g. `const ScopedLanguage guard{Language::kEnglish};`, at the start of the test +// case. #pragma once #include "tetherkitnext/common/i18n.h" diff --git a/tests/mock_control_channel.h b/tests/mock_control_channel.h index afd35af..d33e427 100644 --- a/tests/mock_control_channel.h +++ b/tests/mock_control_channel.h @@ -1,8 +1,9 @@ // In-memory RNDIS control channel, for driving the state machine offline. // -// It plays the "device" side: accepts requests sent by the host, replies with responses according to a script, and can also proactively insert -// INDICATE_STATUS and device-initiated KEEPALIVE -- exactly the paths that are extremely hard to reproduce on real hardware -// yet the easiest to get wrong. +// It plays the "device" side: accepts requests sent by the host, replies with responses according +// to a script, and can also proactively insert INDICATE_STATUS and device-initiated KEEPALIVE; +// exactly the paths that are extremely hard to reproduce on real hardware yet the easiest to get +// wrong. #pragma once #include @@ -36,7 +37,7 @@ class MockControlChannel final : public rndis::ControlChannel { if (send_failure_countdown_ > 0) { --send_failure_countdown_; if (send_failure_countdown_ == 0) { - return std::unexpected(Error::Generic("mock:按测试设置让发送失败")); + return std::unexpected(Error::Generic("mock: send failure injected by the test")); } } sent_messages_.emplace_back(message.begin(), message.end()); @@ -53,11 +54,12 @@ class MockControlChannel final : public rndis::ControlChannel { if (receive_failure_countdown_ > 0) { --receive_failure_countdown_; if (receive_failure_countdown_ == 0) { - return std::unexpected(Error::Generic("mock:按测试设置让接收失败")); + return std::unexpected(Error::Generic("mock: receive failure injected by the test")); } } if (pending_responses_.empty()) { - // Consistent with a real device: return empty when there is no response (on real hardware it is 1 byte of 0x00). + // Consistent with a real device: return empty when there is no response (on real hardware it + // is 1 byte of 0x00). return std::span{}; } current_response_ = std::move(pending_responses_.front()); @@ -68,8 +70,8 @@ class MockControlChannel final : public rndis::ControlChannel { [[nodiscard]] rndis::NotificationResult WaitForNotification( std::uint32_t timeout_millis) override { ++notification_call_count_; - // Record it for regression tests to assert: **any pass of 0 is a bug** -- - // on darwin libusb a timeout=0 means wait forever, which would hang the control thread permanently. + // Record it for regression tests to assert: **any pass of 0 is a bug**; on darwin libusb a + // timeout=0 means wait forever, which would hang the control thread permanently. notification_timeouts_.push_back(timeout_millis); if (!has_interrupt_endpoint_) { return rndis::NotificationResult::kNotSupported; @@ -138,7 +140,8 @@ class MockControlChannel final : public rndis::ControlChannel { return count; } - /// Finds the first SET message the host sent whose OID equals the given value; returns its LE32 payload. + /// Finds the first SET message the host sent whose OID equals the given value; returns its LE32 + /// payload. [[nodiscard]] bool FindSetUint32(rndis::Oid oid, std::uint32_t& out_value, std::size_t skip = 0) const { for (const std::vector& message : sent_messages_) { @@ -164,7 +167,8 @@ class MockControlChannel final : public rndis::ControlChannel { [[nodiscard]] std::uint32_t ReceiveCallCount() const noexcept { return receive_call_count_; } - /// The timeout values received by all WaitForNotification calls so far. Used to assert that 0 is never passed. + /// The timeout values received by all WaitForNotification calls so far. Used to assert that 0 is + /// never passed. [[nodiscard]] const std::vector& NotificationTimeouts() const noexcept { return notification_timeouts_; } @@ -176,7 +180,7 @@ class MockControlChannel final : public rndis::ControlChannel { void ClearSentMessages() { sent_messages_.clear(); } private: - std::string description_ = "mock 设备"; + std::string description_ = "mock device"; RequestHandler request_handler_; std::vector> sent_messages_; @@ -314,7 +318,8 @@ class MockControlChannel final : public rndis::ControlChannel { return message; } -/// Takes the RequestId from a request sent by the host (QUERY/SET/INITIALIZE/KEEPALIVE all have it at offset 8). +/// Takes the RequestId from a request sent by the host (QUERY/SET/INITIALIZE/KEEPALIVE all have it +/// at offset 8). [[nodiscard]] inline std::uint32_t RequestIdOf(std::span request) { if (request.size() < 12) { return 0; @@ -332,7 +337,8 @@ class MockControlChannel final : public rndis::ControlChannel { /// The request handling logic of a "well-behaved Android device". /// -/// Covers all OIDs the startup sequence needs, and replies NOT_SUPPORTED to any unknown OID (as real hardware does too). +/// Covers all OIDs the startup sequence needs, and replies NOT_SUPPORTED to any unknown OID (as +/// real hardware does too). [[nodiscard]] inline MockControlChannel::RequestHandler MakeWellBehavedDevice( const rndis::MacAddress& mac, std::uint32_t max_transfer_size = 2048, std::uint32_t max_packets = 1, std::uint32_t alignment_factor = 0) { diff --git a/tests/mock_data_channel.h b/tests/mock_data_channel.h index 3dfb9ca..7e3722f 100644 --- a/tests/mock_data_channel.h +++ b/tests/mock_data_channel.h @@ -1,12 +1,13 @@ // In-memory RNDIS data channel, for driving the bridge layer offline. // // It plays the "USB device" side: -// * After StartReceiving, InjectFromDevice can be used to inject "frames sent by the device", and an -// internal producer thread pushes them into the bridge layer's RX queue -- simulating the role of the libusb event thread; +// * After StartReceiving, InjectFromDevice can be used to inject "frames sent by the device", and +// an internal producer thread pushes them into the bridge layer's RX queue; simulating the role +// of the libusb event thread; // * SendFrames accepts "frames the host wants to send to the device", for tests to assert. // -// This way the bridge layer's threading model, batching, backpressure and statistics can be fully tested on machines without a USB device, -// including concurrency correctness under TSan. +// This way the bridge layer's threading model, batching, backpressure and statistics can be fully +// tested on machines without a USB device, including concurrency correctness under TSan. #pragma once #include @@ -50,10 +51,11 @@ class MockDataChannel final : public usb::DataChannel { [[nodiscard]] Result SendFrames(std::span frames) override { if (send_should_fail_.load(std::memory_order_acquire)) { - return std::unexpected(Error::Generic("mock:按测试设置让发送失败")); + return std::unexpected(Error::Generic("mock: send failure injected by the test")); } - // Simulates the limited capacity of the transfer pool: accepts at most accept_limit_ frames at a time, and anything beyond is backpressure. + // Simulates the limited capacity of the transfer pool: accepts at most accept_limit_ frames at + // a time, and anything beyond is backpressure. const std::uint32_t limit = accept_limit_.load(std::memory_order_acquire); const auto accepted = static_cast(std::min(frames.size(), limit)); @@ -84,7 +86,8 @@ class MockDataChannel final : public usb::DataChannel { void Shutdown() override { receiving_.store(false, std::memory_order_release); shutdown_called_.store(true, std::memory_order_release); - // Wakes threads that may be waiting for capacity in WaitForSendCapacity (the same empty-critical-section idiom as the real implementation). + // Wakes threads that may be waiting for capacity in WaitForSendCapacity (the same + // empty-critical-section idiom as the real implementation). { const std::lock_guard guard(wait_mutex_); } wait_cv_.notify_all(); } @@ -101,7 +104,8 @@ class MockDataChannel final : public usb::DataChannel { return async_send_errors_.load(std::memory_order_relaxed); } - /// Simulates errors happening in the asynchronous completion callback (in the real implementation they come from STALL / transfer failures). + /// Simulates errors happening in the asynchronous completion callback (in the real implementation + /// they come from STALL / transfer failures). void InjectAsyncSendError() noexcept { async_send_errors_.fetch_add(1, std::memory_order_relaxed); } @@ -112,8 +116,9 @@ class MockDataChannel final : public usb::DataChannel { /// Pushes a batch of "frames sent by the device" directly into the bridge layer's RX queue. /// - /// Goes through BatchWrite, consistent with the real libusb callback path. Returns the number of frames actually enqueued - /// (fewer than requested when the queue is full, which is exactly the drop path under test). + /// Goes through BatchWrite, consistent with the real libusb callback path. Returns the number of + /// frames actually enqueued (fewer than requested when the queue is full, which is exactly the + /// drop path under test). [[nodiscard]] std::uint32_t InjectFromDevice( const std::vector>& frames) { if (rx_ring_ == nullptr) { @@ -138,10 +143,11 @@ class MockDataChannel final : public usb::DataChannel { return accepted; } - /// Sets the maximum number of frames one SendFrames accepts. Setting 0 can simulate the transfer pool being completely full (backpressure). + /// Sets the maximum number of frames one SendFrames accepts. Setting 0 can simulate the transfer + /// pool being completely full (backpressure). /// - /// Going from 0 back to non-zero is equivalent to "transfer complete, slot returned", and wakes the bridge layer's TX thread - /// waiting in WaitForSendCapacity. + /// Going from 0 back to non-zero is equivalent to "transfer complete, slot returned", and wakes + /// the bridge layer's TX thread waiting in WaitForSendCapacity. void SetAcceptLimit(std::uint32_t limit) { accept_limit_.store(limit, std::memory_order_release); { const std::lock_guard guard(wait_mutex_); } @@ -180,7 +186,8 @@ class MockDataChannel final : public usb::DataChannel { return receiving_.load(std::memory_order_acquire); } - /// The number of times WaitForSendCapacity was called -- asserts that "the bridge layer really is waiting rather than dropping". + /// The number of times WaitForSendCapacity was called; asserts that "the bridge layer really is + /// waiting rather than dropping". [[nodiscard]] std::uint64_t WaitCalls() const noexcept { return wait_calls_.load(std::memory_order_relaxed); } diff --git a/tests/test_capi.cc b/tests/test_capi.cc index cb8cb66..c16df06 100644 --- a/tests/test_capi.cc +++ b/tests/test_capi.cc @@ -1,78 +1,87 @@ // Unit tests of the C ABI layer. // -// Covers the places where "a mistake does not crash on the spot, but shows up on the GUI as garbled text or a security hole": -// UTF-8 boundary truncation, NIC name validation, the drop semantics of the log ring buffer. +// Covers the places where "a mistake does not crash on the spot, but shows up on the GUI as garbled +// text or a security hole": UTF-8 boundary truncation, NIC name validation, the drop semantics of +// the log ring buffer. // -// Sessions and NIC configuration need root and a real device, so they are not tested here -- only their argument-validation branches are tested. +// Sessions and NIC configuration need root and a real device, so they are not tested here, only +// their argument-validation branches are tested. +#include "tetherkitnext/capi/tetherkitnext_c.h" +#include "tetherkitnext/common/logging.h" + +#include + +#include + #include #include #include -#include - #include "capi_support.h" +#include "language_guard.h" #include "process_runner.h" -#include "tetherkitnext/capi/tetherkitnext_c.h" -#include "tetherkitnext/common/logging.h" using tetherkitnext::capi::CopyText; using tetherkitnext::capi::IsValidFethName; TEST_SUITE("capi.support") { -TEST_CASE("CopyText 正常拷贝并补终止符") { +TEST_CASE("CopyText copies and NUL-terminates") { std::array buffer{}; CopyText(buffer.data(), buffer.size(), "feth0"); CHECK(std::string{buffer.data()} == "feth0"); } -TEST_CASE("CopyText 容量为 0 或目标为空时不写内存") { +TEST_CASE("CopyText writes nothing when capacity is 0 or the destination is null") { CopyText(nullptr, 16, "x"); // passing if it does not crash std::array buffer{'a', 'b', 'c', 'd'}; CopyText(buffer.data(), 0, "xyz"); CHECK(buffer[0] == 'a'); } -TEST_CASE("CopyText 截断落在 UTF-8 字符边界上") { - // "设备" ("device") = 6 bytes (3 bytes per character). With a capacity of 6 bytes (5 usable + the terminator), - // only the first character fits; cutting hard by bytes would leave half of "备", and on the Swift side the whole string would become replacement characters. +TEST_CASE("CopyText truncates on a UTF-8 character boundary") { + // "设备" ("device") = 6 bytes (3 bytes per character). With a capacity of 6 bytes (5 usable + the + // terminator), only the first character fits; cutting hard by bytes would leave half of "备", and + // on the Swift side the whole string would become replacement characters. std::array buffer{}; CopyText(buffer.data(), buffer.size(), "设备"); CHECK(std::string{buffer.data()} == "设"); CHECK(std::strlen(buffer.data()) == 3); } -TEST_CASE("CopyText 恰好装得下时不截断") { +TEST_CASE("CopyText does not truncate text that fits exactly") { std::array buffer{}; CopyText(buffer.data(), buffer.size(), "设备"); CHECK(std::string{buffer.data()} == "设备"); } -TEST_CASE("CopyText 首字符就装不下时得到空串而非半个字符") { +TEST_CASE( + "CopyText yields an empty string, not half a character, when even the first character does not " + "fit") { std::array buffer{}; // 2 usable bytes, cannot fit the 3-byte "设" CopyText(buffer.data(), buffer.size(), "设备"); CHECK(std::string{buffer.data()}.empty()); } -TEST_CASE("IsValidFethName 只接受 feth+数字") { +TEST_CASE("IsValidFethName accepts only feth + digits") { CHECK(IsValidFethName("feth0")); CHECK(IsValidFethName("feth12")); - SUBCASE("拒绝真实物理网卡 —— 防止误把用户的 Wi-Fi 配置冲掉") { + SUBCASE("rejects real interfaces, so the user's Wi-Fi settings are never wiped by mistake") { CHECK_FALSE(IsValidFethName("en0")); CHECK_FALSE(IsValidFethName("bridge0")); } - SUBCASE("拒绝缺少编号与非数字后缀") { + SUBCASE("rejects a missing number and non-numeric suffixes") { CHECK_FALSE(IsValidFethName("feth")); CHECK_FALSE(IsValidFethName("fethX")); CHECK_FALSE(IsValidFethName("feth0a")); } - SUBCASE("拒绝壳元字符与路径分隔符") { + SUBCASE("rejects shell metacharacters and path separators") { CHECK_FALSE(IsValidFethName("feth0; rm -rf /")); CHECK_FALSE(IsValidFethName("../feth0")); CHECK_FALSE(IsValidFethName("")); } - SUBCASE("拒绝超过 IFNAMSIZ 的名字") { + SUBCASE("rejects names longer than IFNAMSIZ") { CHECK_FALSE(IsValidFethName("feth123456789012345")); } } @@ -83,7 +92,8 @@ using tetherkitnext::capi::DeviceIdentity; using tetherkitnext::capi::ReconcileDeviceStrings; using tetherkitnext::capi::RememberedDeviceStrings; -/// Builds an enumeration result with identity and strings already filled in. Passing an empty string for a string means "not read this time". +/// Builds an enumeration result with identity and strings already filled in. Passing an empty +/// string for a string means "not read this time". tk_device_info_t DeviceInfo(const DeviceIdentity& identity, const char* manufacturer, const char* product, const char* serial) { tk_device_info_t info{}; @@ -99,9 +109,9 @@ tk_device_info_t DeviceInfo(const DeviceIdentity& identity, const char* manufact } // namespace -TEST_CASE("ReconcileDeviceStrings 在读不到时回填上次成功读到的名字") { - // The scenario is that real defect on the GUI: after connecting the device is held exclusively and strings cannot be read, - // and "vivo iQOO Z10x" degrades into "USB device 2d95:600b". +TEST_CASE("ReconcileDeviceStrings backfills the last name read successfully when a read fails") { + // The scenario is that real defect on the GUI: after connecting the device is held exclusively + // and strings cannot be read, and "vivo iQOO Z10x" degrades into "USB device 2d95:600b". const DeviceIdentity phone{.bus_number = 0, .device_address = 1, .vendor_id = 0x2d95, .product_id = 0x600b}; std::vector memory; @@ -119,7 +129,7 @@ TEST_CASE("ReconcileDeviceStrings 在读不到时回填上次成功读到的名 CHECK(std::string{infos[0].product} == "iQOO Z10x"); CHECK(std::string{infos[0].serial} == "10AFAC2X72005KT"); - SUBCASE("再次读到新值时覆盖记忆") { + SUBCASE("a newly read value replaces the remembered one") { infos = {DeviceInfo(phone, "vivo", "iQOO Z10x", "NEWSERIAL")}; ReconcileDeviceStrings(memory, present, infos); infos = {DeviceInfo(phone, "", "", "")}; @@ -128,7 +138,8 @@ TEST_CASE("ReconcileDeviceStrings 在读不到时回填上次成功读到的名 } } -TEST_CASE("ReconcileDeviceStrings 不把旧名字安给接替同一地址的另一台设备") { +TEST_CASE( + "ReconcileDeviceStrings does not give an old name to another device at the same address") { const DeviceIdentity old_phone{.bus_number = 0, .device_address = 1, .vendor_id = 0x2d95, .product_id = 0x600b}; std::vector memory; @@ -136,7 +147,7 @@ TEST_CASE("ReconcileDeviceStrings 不把旧名字安给接替同一地址的另 ReconcileDeviceStrings(memory, {std::vector{old_phone}}, infos); REQUIRE(memory.size() == 1); - SUBCASE("同地址但 VID:PID 不同 → 身份不同,不回填") { + SUBCASE("same address but a different VID:PID → different device, no backfill") { const DeviceIdentity other{.bus_number = 0, .device_address = 1, .vendor_id = 0x18d1, .product_id = 0x4ee4}; infos = {DeviceInfo(other, "", "", "")}; @@ -144,20 +155,23 @@ TEST_CASE("ReconcileDeviceStrings 不把旧名字安给接替同一地址的另 CHECK(std::string{infos[0].product}.empty()); } - SUBCASE("设备拔掉(不在场)→ 记忆清除;重插后读不到也不回填") { + SUBCASE( + "device unplugged (absent) → memory cleared; no backfill after replugging even if reads " + "fail") { // Unplugged: present is empty. infos.clear(); ReconcileDeviceStrings(memory, {}, infos); CHECK(memory.empty()); - // Re-plugged with the same identity (possibly already another device of the same model), cannot be read -> better to show VID:PID. + // Re-plugged with the same identity (possibly already another device of the same model), cannot + // be read -> better to show VID:PID. infos = {DeviceInfo(old_phone, "", "", "")}; ReconcileDeviceStrings(memory, {std::vector{old_phone}}, infos); CHECK(std::string{infos[0].product}.empty()); } } -TEST_CASE("ReconcileDeviceStrings 对没有字符串的设备保持诚实的空串") { +TEST_CASE("ReconcileDeviceStrings keeps an honest empty string for devices without strings") { const DeviceIdentity mute{.bus_number = 2, .device_address = 7, .vendor_id = 0x1234, .product_id = 0x5678}; std::vector memory; @@ -168,9 +182,9 @@ TEST_CASE("ReconcileDeviceStrings 对没有字符串的设备保持诚实的空 CHECK(std::string{infos[0].product}.empty()); } -TEST_CASE("ReconcileDeviceStrings 不清除仍在场但没被填出的设备的记忆") { - // When the caller's array capacity is insufficient, present is longer than infos -- the excess was merely not filled, - // not unplugged. +TEST_CASE("ReconcileDeviceStrings keeps the memory of a device that is present but not filled in") { + // When the caller's array capacity is insufficient, present is longer than infos; the excess was + // merely not filled, not unplugged. const DeviceIdentity first{.bus_number = 0, .device_address = 1, .vendor_id = 0x2d95, .product_id = 0x600b}; const DeviceIdentity second{.bus_number = 0, .device_address = 2, @@ -188,7 +202,8 @@ TEST_CASE("ReconcileDeviceStrings 不清除仍在场但没被填出的设备的 ReconcileDeviceStrings(memory, both, infos); CHECK(memory.size() == 2); - // Afterwards, when the second is filled again and cannot be read, the memory is still there and can backfill. + // Afterwards, when the second is filled again and cannot be read, the memory is still there and + // can backfill. infos = {DeviceInfo(second, "", "", "")}; ReconcileDeviceStrings(memory, both, infos); CHECK(std::string{infos[0].product} == "Pixel"); @@ -198,7 +213,7 @@ TEST_CASE("ReconcileDeviceStrings 不清除仍在场但没被填出的设备的 TEST_SUITE("capi.basics") { -TEST_CASE("tk_version 填出非空的版本串") { +TEST_CASE("tk_version fills in a non-empty version string") { tk_version_info_t version{}; tk_version(&version); CHECK(std::strlen(version.text) > 0); @@ -206,12 +221,12 @@ TEST_CASE("tk_version 填出非空的版本串") { CHECK(std::strlen(version.libusb) > 0); CHECK(version.major + version.minor + version.patch > 0); - SUBCASE("传 nullptr 是空操作而非崩溃") { + SUBCASE("nullptr is a no-op, not a crash") { tk_version(nullptr); } } -TEST_CASE("tk_check_environment 永远成功,只在字段里表达结论") { +TEST_CASE("tk_check_environment always succeeds and reports its findings in the fields") { tk_environment_t environment{}; CHECK(tk_check_environment(&environment) == TK_OK); // The test process is not root, so this one is certain. @@ -221,29 +236,32 @@ TEST_CASE("tk_check_environment 永远成功,只在字段里表达结论") { CHECK(std::strlen(environment.sysctl_detail) == 0); } - SUBCASE("传 nullptr 返回参数错误") { + SUBCASE("nullptr returns an argument error") { CHECK(tk_check_environment(nullptr) == TK_ERR_INVALID_ARGUMENT); } } -TEST_CASE("tk_list_devices 允许只统计数量") { +TEST_CASE("tk_list_devices can return just the count") { std::size_t count = 0; tk_error_t error{}; - // The development machine usually has no RNDIS device plugged in, so here we only verify "the call succeeds and does not write out of bounds", - // without asserting a specific count. + // The development machine usually has no RNDIS device plugged in, so here we only verify "the + // call succeeds and does not write out of bounds", without asserting a specific count. const tk_result_t result = tk_list_devices(nullptr, 0, &count, false, &error); CHECK(result == TK_OK); CHECK(std::strlen(error.message) == 0); - SUBCASE("缺少 out_count 时拒绝调用") { + SUBCASE("rejects the call without out_count") { CHECK(tk_list_devices(nullptr, 0, nullptr, false, nullptr) == TK_ERR_INVALID_ARGUMENT); } } -TEST_CASE("重复枚举不会反复初始化 libusb") { - // The GUI refreshes the device list periodically. If every enumeration created a new libusb context, every time it would - // start and stop one event thread and one IOKit runloop thread, and the log would be flooded with "libusb initialized" - // -- this problem really happened, and this test case pins the fix. +TEST_CASE("repeated enumeration does not reinitialize libusb") { + // The GUI refreshes the device list periodically. If every enumeration created a new libusb + // context, every time it would start and stop one event thread and one IOKit runloop thread, and + // the log would be flooded with "libusb initialized"; this problem really happened, and this test + // case pins the fix. The check below matches the English log text; without pinning it could never + // match under another language and would pass vacuously. + const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kEnglish}; tk_enable_log_capture(true); const tetherkitnext::LogLevel saved_level = tetherkitnext::GetLogLevel(); tetherkitnext::SetLogLevel(tetherkitnext::LogLevel::kInfo); @@ -252,7 +270,8 @@ TEST_CASE("重复枚举不会反复初始化 libusb") { std::array records{}; std::uint64_t dropped = 0; - // Enumerate once first and clear the log, making sure the shared context has been established (the first initialization is supposed to happen). + // Enumerate once first and clear the log, making sure the shared context has been established + // (the first initialization is supposed to happen). tk_list_devices(nullptr, 0, &count, false, nullptr); while (tk_drain_logs(records.data(), records.size(), &dropped) > 0) { } @@ -266,7 +285,7 @@ TEST_CASE("重复枚举不会反复初始化 libusb") { std::size_t taken = 0; while ((taken = tk_drain_logs(records.data(), records.size(), &dropped)) > 0) { for (std::size_t i = 0; i < taken; ++i) { - if (std::string{records[i].message}.find("libusb 已初始化") != std::string::npos) { + if (std::string{records[i].message}.find("libusb initialized") != std::string::npos) { ++initialization_lines; } } @@ -281,22 +300,22 @@ TEST_CASE("重复枚举不会反复初始化 libusb") { TEST_SUITE("capi.log_ring") { -TEST_CASE("日志捕获关闭时不产生记录") { +TEST_CASE("no records while log capture is off") { tk_enable_log_capture(false); - TETHERKITNEXT_ERROR("这条不该被捕获"); + TETHERKITNEXT_ERROR("this line must not be captured"); std::array records{}; std::uint64_t dropped = 0; CHECK(tk_drain_logs(records.data(), records.size(), &dropped) == 0); } -TEST_CASE("开启捕获后能按序取回日志") { +TEST_CASE("with capture on, logs are drained in order") { tk_enable_log_capture(true); const tetherkitnext::LogLevel saved_level = tetherkitnext::GetLogLevel(); tetherkitnext::SetLogLevel(tetherkitnext::LogLevel::kInfo); - TETHERKITNEXT_INFO("第一条"); - TETHERKITNEXT_WARN("第二条"); + TETHERKITNEXT_INFO("first"); + TETHERKITNEXT_WARN("second"); std::array records{}; std::uint64_t dropped = 0; @@ -304,13 +323,13 @@ TEST_CASE("开启捕获后能按序取回日志") { CHECK(taken == 2); CHECK(dropped == 0); - CHECK(std::string{records[0].message} == "第一条"); + CHECK(std::string{records[0].message} == "first"); CHECK(records[0].level == TK_LOG_INFO); - CHECK(std::string{records[1].message} == "第二条"); + CHECK(std::string{records[1].message} == "second"); CHECK(records[1].level == TK_LOG_WARN); CHECK(records[0].wall_nanos > 0); - SUBCASE("取空之后再取返回 0") { + SUBCASE("draining again after empty returns 0") { CHECK(tk_drain_logs(records.data(), records.size(), &dropped) == 0); } @@ -318,7 +337,7 @@ TEST_CASE("开启捕获后能按序取回日志") { tk_enable_log_capture(false); } -TEST_CASE("缓冲写满时丢最旧的并汇报丢弃数") { +TEST_CASE("a full buffer drops the oldest records and reports how many") { tk_enable_log_capture(true); const tetherkitnext::LogLevel saved_level = tetherkitnext::GetLogLevel(); tetherkitnext::SetLogLevel(tetherkitnext::LogLevel::kInfo); @@ -327,7 +346,7 @@ TEST_CASE("缓冲写满时丢最旧的并汇报丢弃数") { constexpr int kOverflow = 10; constexpr int kTotal = 256 + kOverflow; for (int i = 0; i < kTotal; ++i) { - TETHERKITNEXT_INFO("第 {} 条", i); + TETHERKITNEXT_INFO("record {}", i); } std::array records{}; @@ -337,10 +356,10 @@ TEST_CASE("缓冲写满时丢最旧的并汇报丢弃数") { CHECK(taken == 256); CHECK(dropped == kOverflow); // What remains should be the **newest** 256, so the first one is number 10. - CHECK(std::string{records[0].message} == "第 10 条"); - CHECK(std::string{records[taken - 1].message} == "第 265 条"); + CHECK(std::string{records[0].message} == "record 10"); + CHECK(std::string{records[taken - 1].message} == "record 265"); - SUBCASE("丢弃计数取走后归零") { + SUBCASE("the drop count resets once read") { std::uint64_t again = 1; tk_drain_logs(records.data(), records.size(), &again); CHECK(again == 0); @@ -354,7 +373,7 @@ TEST_CASE("缓冲写满时丢最旧的并汇报丢弃数") { TEST_SUITE("capi.session") { -TEST_CASE("tk_session_config_init 填出可直接使用的默认值") { +TEST_CASE("tk_session_config_init fills in usable defaults") { tk_session_config_t config{}; tk_session_config_init(&config); @@ -365,12 +384,13 @@ TEST_CASE("tk_session_config_init 填出可直接使用的默认值") { CHECK(config.rx_transfer_kib > 0); CHECK(config.max_transfer_kib > 0); CHECK(config.bpf_buffer_kib > 0); - // The device filter defaults to unrestricted, otherwise the GUI could not filter any device right from the start. + // The device filter defaults to unrestricted, otherwise the GUI could not filter any device right + // from the start. CHECK(config.vendor_id == 0); CHECK(config.product_id == 0); } -TEST_CASE("会话可创建、可查状态、可销毁(不需要 root)") { +TEST_CASE("a session can be created, queried and destroyed (no root needed)") { tk_session_config_t config{}; tk_session_config_init(&config); @@ -379,7 +399,7 @@ TEST_CASE("会话可创建、可查状态、可销毁(不需要 root)") { REQUIRE(session != nullptr); CHECK(std::strlen(error.message) == 0); - SUBCASE("未启动时是 IDLE,且各字段都是干净的零值") { + SUBCASE("before start it is IDLE and every field is zero") { tk_session_status_t status{}; REQUIRE(tk_session_status_get(session, &status) == TK_OK); CHECK(status.run_state == TK_RUN_IDLE); @@ -387,22 +407,23 @@ TEST_CASE("会话可创建、可查状态、可销毁(不需要 root)") { CHECK_FALSE(status.link_up); CHECK(std::strlen(status.system_interface) == 0); CHECK(std::strlen(status.fatal) == 0); + CHECK(std::strlen(status.peer_ipv4) == 0); CHECK(status.rx_frames == 0); CHECK(status.monotonic_nanos > 0); } - SUBCASE("未启动时事件队列是空的") { + SUBCASE("before start the event queue is empty") { std::array events{}; CHECK(tk_session_poll_events(session, events.data(), events.size()) == 0); } - SUBCASE("非 root 启动返回 TK_ERR_PERMISSION 而不是笼统的失败") { + SUBCASE("starting without root returns TK_ERR_PERMISSION, not a generic failure") { // The GUI relies on this code to distinguish "should pop up authorization" from "a real error". CHECK(tk_session_start(session, &error) == TK_ERR_PERMISSION); CHECK(std::strlen(error.message) > 0); } - SUBCASE("重复 stop 是幂等的") { + SUBCASE("repeated stop is idempotent") { CHECK(tk_session_stop(session) == TK_OK); CHECK(tk_session_stop(session) == TK_OK); } @@ -410,7 +431,7 @@ TEST_CASE("会话可创建、可查状态、可销毁(不需要 root)") { tk_session_destroy(session); } -TEST_CASE("会话接口对空指针一律安全") { +TEST_CASE("the session API is safe with null pointers") { tk_error_t error{}; CHECK(tk_session_create(nullptr, &error) == nullptr); CHECK(std::strlen(error.message) > 0); @@ -427,7 +448,7 @@ TEST_CASE("会话接口对空指针一律安全") { TEST_SUITE("capi.process") { -TEST_CASE("RunTool 收集子进程输出并带回退出码") { +TEST_CASE("RunTool collects the child's output and exit code") { const auto result = tetherkitnext::capi::RunTool("/bin/echo", {"你好", "世界"}); REQUIRE(result.has_value()); CHECK(result->exit_code == 0); @@ -435,8 +456,9 @@ TEST_CASE("RunTool 收集子进程输出并带回退出码") { CHECK(result->output == "你好 世界\n"); } -TEST_CASE("RunTool 合并 stderr,且非零退出不算调用失败") { - // sh -c 'echo boom >&2; exit 3': verifies that stderr is also collected and the exit code is carried back as-is. +TEST_CASE("RunTool merges stderr, and a non-zero exit is not a call failure") { + // sh -c 'echo boom >&2; exit 3': verifies that stderr is also collected and the exit code is + // carried back as-is. const auto result = tetherkitnext::capi::RunTool("/bin/sh", {"-c", "echo boom >&2; exit 3"}); REQUIRE(result.has_value()); @@ -445,9 +467,10 @@ TEST_CASE("RunTool 合并 stderr,且非零退出不算调用失败") { CHECK(result->output == "boom\n"); } -TEST_CASE("RunTool 读得下超过管道缓冲的大输出(不死锁)") { - // The pipe buffer is 64 KiB. It must be drained first and then waitpid, otherwise once the child fills it it blocks, - // and we wait on waitpid, and both sides freeze. This test case pins that order. +TEST_CASE("RunTool reads output larger than the pipe buffer (no deadlock)") { + // The pipe buffer is 64 KiB. It must be drained first and then waitpid, otherwise once the child + // fills it it blocks, and we wait on waitpid, and both sides freeze. This test case pins that + // order. const auto result = tetherkitnext::capi::RunTool( "/bin/sh", {"-c", "for i in $(seq 1 20000); do echo 0123456789; done"}); REQUIRE(result.has_value()); @@ -455,7 +478,29 @@ TEST_CASE("RunTool 读得下超过管道缓冲的大输出(不死锁)") { CHECK(result->output.size() == 20000 * 11); } -TEST_CASE("RunTool 对不存在的可执行文件返回错误而非崩溃") { +TEST_CASE("RunTool children inherit only stdin/stdout/stderr") { + // A descriptor without FD_CLOEXEC, like the daemon's BPF or routing sockets: + // POSIX_SPAWN_CLOEXEC_DEFAULT must keep it out of the child. + std::array leaked{-1, -1}; + REQUIRE(::pipe(leaked.data()) == 0); + const std::string probe = + "test -e /dev/fd/" + std::to_string(leaked[1]) + " && echo leaked || echo closed"; + const auto result = tetherkitnext::capi::RunTool("/bin/sh", {"-c", probe}); + ::close(leaked[0]); + ::close(leaked[1]); + REQUIRE(result.has_value()); + CHECK(result->output == "closed\n"); +} + +TEST_CASE("RunTool children read EOF on stdin") { + // stdin is /dev/null, not whatever the (root) parent had open. + const auto result = tetherkitnext::capi::RunTool( + "/bin/sh", {"-c", "if read line; then echo data; else echo eof; fi"}); + REQUIRE(result.has_value()); + CHECK(result->output == "eof\n"); +} + +TEST_CASE("RunTool returns an error, not a crash, for a missing executable") { const auto result = tetherkitnext::capi::RunTool("/nonexistent/tetherkitnext-test", {}); CHECK_FALSE(result.has_value()); } @@ -464,7 +509,7 @@ TEST_CASE("RunTool 对不存在的可执行文件返回错误而非崩溃") { TEST_SUITE("capi.net_config") { -TEST_CASE("tk_ip_config_init 默认 DHCP 且不抢全局默认路由") { +TEST_CASE("tk_ip_config_init defaults to DHCP without taking the global default route") { tk_ip_config_t config{}; tk_ip_config_init(&config); CHECK(config.mode == TK_IP_MODE_DHCP); @@ -473,12 +518,13 @@ TEST_CASE("tk_ip_config_init 默认 DHCP 且不抢全局默认路由") { CHECK(std::strlen(config.address) == 0); } -TEST_CASE("拒绝对非 feth 网卡下手") { +TEST_CASE("refuses to touch non-feth interfaces") { tk_ip_config_t config{}; tk_ip_config_init(&config); tk_error_t error{}; - // This is the most important line of defense of this module: mistakenly passing en0 would wipe out the user's Wi-Fi configuration. + // This is the most important line of defense of this module: mistakenly passing en0 would wipe + // out the user's Wi-Fi configuration. CHECK(tk_net_apply("en0", &config, &error) == TK_ERR_INVALID_ARGUMENT); CHECK(std::string{error.message}.find("en0") != std::string::npos); @@ -491,7 +537,7 @@ TEST_CASE("拒绝对非 feth 网卡下手") { CHECK(tk_net_apply("feth0", nullptr, &error) == TK_ERR_INVALID_ARGUMENT); } -TEST_CASE("非 root 下写操作返回 TK_ERR_PERMISSION") { +TEST_CASE("write operations without root return TK_ERR_PERMISSION") { tk_ip_config_t config{}; tk_ip_config_init(&config); tk_error_t error{}; @@ -505,9 +551,10 @@ TEST_CASE("非 root 下写操作返回 TK_ERR_PERMISSION") { CHECK(removed == 0); } -TEST_CASE("查询不存在的 feth 网卡是成功且全空,而不是报错") { - // The GUI also refreshes network state when a session has not started, and the NIC does not exist then -- this case must be - // "no address" rather than "query failed", otherwise a false error would hang on the UI forever. +TEST_CASE("querying a missing feth interface succeeds with empty results instead of failing") { + // The GUI also refreshes network state when a session has not started, and the NIC does not exist + // then; this case must be "no address" rather than "query failed", otherwise a false error would + // hang on the UI forever. tk_net_state_t state{}; tk_error_t error{}; CHECK(tk_net_query("feth99", &state, &error) == TK_OK); diff --git a/tests/test_common_byte_order.cc b/tests/test_common_byte_order.cc index fc4bbc2..3cce74a 100644 --- a/tests/test_common_byte_order.cc +++ b/tests/test_common_byte_order.cc @@ -1,6 +1,7 @@ // Unit tests of byte_order.h. // -// Key verification: unaligned access must be correct (the offset of an RNDIS message in the USB buffer is not guaranteed to be aligned). +// Key verification: unaligned access must be correct (the offset of an RNDIS message in the USB +// buffer is not guaranteed to be aligned). #include #include #include @@ -21,7 +22,7 @@ using tetherkitnext::StoreLe64; TEST_SUITE("common.byte_order") { -TEST_CASE("小端读取按规范解释字节序") { +TEST_CASE("little-endian loads follow the spec's byte order") { // The little-endian representation of 0x44332211 is 11 22 33 44. const std::array bytes{std::byte{0x11}, std::byte{0x22}, std::byte{0x33}, std::byte{0x44}, std::byte{0x55}, std::byte{0x66}, @@ -31,13 +32,13 @@ TEST_CASE("小端读取按规范解释字节序") { CHECK(LoadLe64(bytes.data()) == 0x8877665544332211ULL); } -TEST_CASE("大端读取按网络字节序解释") { +TEST_CASE("big-endian loads use network byte order") { const std::array bytes{std::byte{0x08}, std::byte{0x00}}; // 0x0800 = ETHERTYPE_IP CHECK(LoadBe16(bytes.data()) == 0x0800U); } -TEST_CASE("写入后读回保持一致") { +TEST_CASE("a stored value reads back unchanged") { std::array buffer{}; StoreLe32(buffer.data(), 0xDEADBEEFU); CHECK(LoadLe32(buffer.data()) == 0xDEADBEEFU); @@ -52,9 +53,10 @@ TEST_CASE("写入后读回保持一致") { CHECK(buffer[5] == std::byte{0xDD}); } -TEST_CASE("未对齐偏移上的读写同样正确") { - // This is the scenario most prone to errors in this project: the start offset of the Ethernet frame after REMOTE_NDIS_PACKET_MSG - // is determined by the device's DataOffset and may be arbitrary. +TEST_CASE("loads and stores at unaligned offsets are correct") { + // This is the scenario most prone to errors in this project: the start offset of the Ethernet + // frame after REMOTE_NDIS_PACKET_MSG is determined by the device's DataOffset and may be + // arbitrary. std::array buffer{}; for (std::size_t offset = 0; offset < 8; ++offset) { StoreLe32(buffer.data() + offset, 0xCAFEBABEU); @@ -65,13 +67,13 @@ TEST_CASE("未对齐偏移上的读写同样正确") { } } -TEST_CASE("单字节读写不做任何转换") { +TEST_CASE("single-byte loads and stores do no conversion") { std::array buffer{}; tetherkitnext::StoreLe(buffer.data(), 0xA5U); CHECK(tetherkitnext::LoadLe(buffer.data()) == 0xA5U); } -TEST_CASE("AlignUp 向上对齐到 2 的幂") { +TEST_CASE("AlignUp rounds up to a power of two") { CHECK(AlignUp(0, 4) == 0); CHECK(AlignUp(1, 4) == 4); CHECK(AlignUp(4, 4) == 4); @@ -81,7 +83,7 @@ TEST_CASE("AlignUp 向上对齐到 2 的幂") { CHECK(AlignUp(63, 64) == 64); } -TEST_CASE("IsPowerOfTwo 正确识别 2 的幂") { +TEST_CASE("IsPowerOfTwo recognizes powers of two") { CHECK_FALSE(IsPowerOfTwo(0)); CHECK(IsPowerOfTwo(1)); CHECK(IsPowerOfTwo(2)); diff --git a/tests/test_common_error.cc b/tests/test_common_error.cc index 646afed..724b214 100644 --- a/tests/test_common_error.cc +++ b/tests/test_common_error.cc @@ -17,7 +17,7 @@ using tetherkitnext::Status; namespace { Status FailingStep() { - return std::unexpected(Error::FromErrno(ENOENT, "打开 /dev/bpf0 失败")); + return std::unexpected(Error::FromErrno(ENOENT, "opening /dev/bpf0 failed")); } Status SucceedingStep() { @@ -33,7 +33,7 @@ Status PipelineWithFailure() { Result ProducingStep(bool succeed) { if (!succeed) { - return std::unexpected(Error::Generic("生产失败")); + return std::unexpected(Error::Generic("producing failed")); } return 42; } @@ -47,71 +47,72 @@ Result ConsumingPipeline(bool succeed) { TEST_SUITE("common.error") { -TEST_CASE("errno 域渲染出符号名与数值") { - const Error error = Error::FromErrno(EACCES, "打开 BPF 设备失败"); +TEST_CASE("the errno domain renders the symbolic name and number") { + const Error error = Error::FromErrno(EACCES, "opening the BPF device failed"); CHECK(error.Domain() == ErrorDomain::kErrno); CHECK(error.Code() == EACCES); const std::string text = error.ToString(); - CHECK(text.find("打开 BPF 设备失败") != std::string::npos); + CHECK(text.find("opening the BPF device failed") != std::string::npos); CHECK(text.find("errno") != std::string::npos); CHECK(text.find(std::to_string(EACCES)) != std::string::npos); } -TEST_CASE("errno 传 0 时自动读取全局 errno") { +TEST_CASE("errno 0 reads the global errno") { errno = EPERM; - const Error error = Error::FromErrno(0, "创建 feth 失败"); + const Error error = Error::FromErrno(0, "creating feth failed"); CHECK(error.Code() == EPERM); } -TEST_CASE("libusb 域渲染出 libusb 错误名") { +TEST_CASE("the libusb domain renders the libusb error name") { // LIBUSB_ERROR_ACCESS == -3 is this project's most common failure (not running as root). - const Error error = Error::FromLibUsb(-3, "声明 RNDIS 数据接口失败"); + const Error error = Error::FromLibUsb(-3, "claiming the RNDIS data interface failed"); CHECK(error.Domain() == ErrorDomain::kLibUsb); const std::string text = error.ToString(); CHECK(text.find("LIBUSB_ERROR_ACCESS") != std::string::npos); } -TEST_CASE("RNDIS 域输出原始状态码数值") { - // tk_common **deliberately does not know** the symbolic names of RNDIS status codes -- that table exists in only - // one place, rndis/protocol.cc (a single source, avoiding inconsistency between two places). So Error::ToString() - // here is only responsible for outputting the hexadecimal value; the symbolic name is spliced into the context string by the rndis layer when it constructs the Error - // (see MakeStatusError in rndis/messages.cc). - const Error error = Error::FromRndisStatus(0xC00000BBU, "查询 OID 失败"); +TEST_CASE("the RNDIS domain prints the raw status code") { + // tk_common **does not know** the symbolic names of RNDIS status codes; that table exists in only + // one place, rndis/protocol.cc (a single source, avoiding inconsistency between two places). So + // Error::ToString() here is only responsible for outputting the hexadecimal value; the symbolic + // name is spliced into the context string by the rndis layer when it constructs the Error (see + // MakeStatusError in rndis/messages.cc). + const Error error = Error::FromRndisStatus(0xC00000BBU, "querying the OID failed"); const std::string text = error.ToString(); - CHECK(text.find("查询 OID 失败") != std::string::npos); + CHECK(text.find("querying the OID failed") != std::string::npos); CHECK(text.find("0xc00000bb") != std::string::npos); CHECK(error.Domain() == ErrorDomain::kRndis); CHECK(error.Code() == 0xC00000BB); } -TEST_CASE("WithContext 形成外层到内层的原因链") { - Error inner = Error::FromErrno(ENODEV, "ioctl(BIOCSETIF) 失败"); - const Error outer = std::move(inner).WithContext("绑定 BPF 到 feth1"); +TEST_CASE("WithContext builds an outer-to-inner cause chain") { + Error inner = Error::FromErrno(ENODEV, "ioctl(BIOCSETIF) failed"); + const Error outer = std::move(inner).WithContext("binding BPF to feth1"); const std::string text = outer.ToString(); - const auto outer_pos = text.find("绑定 BPF 到 feth1"); - const auto inner_pos = text.find("ioctl(BIOCSETIF) 失败"); + const auto outer_pos = text.find("binding BPF to feth1"); + const auto inner_pos = text.find("ioctl(BIOCSETIF) failed"); REQUIRE(outer_pos != std::string::npos); REQUIRE(inner_pos != std::string::npos); CHECK(outer_pos < inner_pos); // the outer cause comes first } -TEST_CASE("RETURN_IF_ERROR 传播首个失败") { +TEST_CASE("RETURN_IF_ERROR propagates the first failure") { const Status status = PipelineWithFailure(); REQUIRE_FALSE(status.has_value()); CHECK(status.error().Code() == ENOENT); } -TEST_CASE("ASSIGN_OR_RETURN 成功时取值、失败时传播") { +TEST_CASE("ASSIGN_OR_RETURN yields the value on success and propagates failure") { const Result good = ConsumingPipeline(true); REQUIRE(good.has_value()); CHECK(good.value() == 84); const Result bad = ConsumingPipeline(false); REQUIRE_FALSE(bad.has_value()); - CHECK(bad.error().Context() == "生产失败"); + CHECK(bad.error().Context() == "producing failed"); } -TEST_CASE("日志级别设置与判断") { +TEST_CASE("setting and checking the log level") { const LogLevel original = tetherkitnext::GetLogLevel(); tetherkitnext::SetLogLevel(LogLevel::kWarn); @@ -126,7 +127,7 @@ TEST_CASE("日志级别设置与判断") { tetherkitnext::SetLogLevel(original); } -TEST_CASE("从 __FILE__ 截出文件名") { +TEST_CASE("extracting the file name from __FILE__") { CHECK(tetherkitnext::detail::BaseName("/a/b/c/bpf_link.cc") == "bpf_link.cc"); CHECK(tetherkitnext::detail::BaseName("bpf_link.cc") == "bpf_link.cc"); CHECK(tetherkitnext::detail::BaseName("") == ""); diff --git a/tests/test_common_frame_ring.cc b/tests/test_common_frame_ring.cc index 8e5fdc1..b9f49ae 100644 --- a/tests/test_common_frame_ring.cc +++ b/tests/test_common_frame_ring.cc @@ -1,7 +1,8 @@ // Unit tests of FrameRing. // -// FrameRing is the core of the RX path: the libusb callback thread writes the unpacked Ethernet frames into it, -// and the BPF write thread takes them out and write()s. So both semantics and concurrency are tested here. +// FrameRing is the core of the RX path: the libusb callback thread writes the unpacked Ethernet +// frames into it, and the BPF write thread takes them out and write()s. So both semantics and +// concurrency are tested here. #include #include #include @@ -21,7 +22,8 @@ using tetherkitnext::kCacheLineSize; namespace { -/// Builds a frame whose content is self-verifying: the first byte is the sequence number, and the rest are derived from the sequence number. +/// Builds a frame whose content is self-verifying: the first byte is the sequence number, and the +/// rest are derived from the sequence number. std::vector MakeFrame(std::uint32_t length, std::uint8_t tag) { std::vector frame(length); for (std::uint32_t i = 0; i < length; ++i) { @@ -43,22 +45,23 @@ bool VerifyFrame(std::span frame, std::uint8_t tag) { TEST_SUITE("common.frame_ring") { -TEST_CASE("容量向上取整并报告存储开销") { +TEST_CASE("capacity is rounded up and the storage cost reported") { FrameRing ring(100, 1514); CHECK(ring.Capacity() == 128); CHECK(ring.MaxFrameBytes() == 1514); - // Each slot = 128-byte header + 1514 bytes of data = 1642, rounded up to a multiple of 128 = 1664. + // Each slot = 128-byte header + 1514 bytes of data = 1642, rounded up to a multiple of 128 = + // 1664. CHECK(ring.StorageBytes() == 128 * 1664); } -TEST_CASE("空队列读取返回空视图") { +TEST_CASE("reading an empty queue returns an empty view") { FrameRing ring(4, 1514); const FrameView view = ring.BeginRead(); CHECK(view.Empty()); CHECK(view.data == nullptr); } -TEST_CASE("单帧入队出队内容一致") { +TEST_CASE("a single frame comes out as it went in") { FrameRing ring(4, 1514); const std::vector frame = MakeFrame(1514, 0x42); REQUIRE(ring.TryPush(frame)); @@ -71,7 +74,7 @@ TEST_CASE("单帧入队出队内容一致") { CHECK(ring.BeginRead().Empty()); } -TEST_CASE("超长帧被拒绝且不占用槽位") { +TEST_CASE("an oversized frame is rejected without using a slot") { FrameRing ring(4, 128); const std::vector too_long = MakeFrame(129, 0x01); CHECK_FALSE(ring.TryPush(too_long)); @@ -80,7 +83,7 @@ TEST_CASE("超长帧被拒绝且不占用槽位") { CHECK(ring.TryPush(MakeFrame(128, 0x02))); } -TEST_CASE("队列满后拒绝入队") { +TEST_CASE("a full queue rejects pushes") { FrameRing ring(4, 64); for (std::uint8_t i = 0; i < 4; ++i) { REQUIRE(ring.TryPush(MakeFrame(64, i))); @@ -89,7 +92,7 @@ TEST_CASE("队列满后拒绝入队") { CHECK_FALSE(ring.TryPush(MakeFrame(64, 9))); } -TEST_CASE("BeginWrite/CommitWrite 零拷贝路径") { +TEST_CASE("BeginWrite/CommitWrite zero-copy path") { FrameRing ring(4, 1514); const std::span dst = ring.BeginWrite(); REQUIRE(dst.size() == 1514); @@ -105,9 +108,10 @@ TEST_CASE("BeginWrite/CommitWrite 零拷贝路径") { ring.CommitRead(); } -TEST_CASE("变长帧混合、反复绕环不串数据") { +TEST_CASE("mixed frame sizes wrapping repeatedly never mix up data") { FrameRing ring(4, 2048); - // Capacity 4, run 500 rounds with a different length each round, forcing the indices to wrap around and reuse slots. + // Capacity 4, run 500 rounds with a different length each round, forcing the indices to wrap + // around and reuse slots. for (std::uint32_t round = 0; round < 500; ++round) { const auto length = static_cast(14 + (round * 37) % 2000); const auto tag = static_cast(round & 0xFFU); @@ -120,8 +124,9 @@ TEST_CASE("变长帧混合、反复绕环不串数据") { } } -TEST_CASE("每帧数据区起始地址按缓存行对齐") { - // Performance correctness assertion: frame data must land on cache line boundaries so that memcpy and write() take the optimal path. +TEST_CASE("every frame's data starts on a cache-line boundary") { + // Performance invariant: frame data must land on cache line boundaries so that memcpy and write() + // take the optimal path. FrameRing ring(8, 1514); for (int i = 0; i < 8; ++i) { const std::span dst = ring.BeginWrite(); @@ -196,7 +201,7 @@ TEST_CASE("park/wake handshake loses no wakeups under a bursty producer") { CHECK(received == kFrames); } -TEST_CASE("并发搬运 20 万帧不丢不乱序") { +TEST_CASE("200,000 frames across threads: none lost, none reordered") { constexpr std::uint32_t kTotal = 200'000; FrameRing ring(512, 512); @@ -210,7 +215,8 @@ TEST_CASE("并发搬运 20 万帧不丢不乱序") { std::this_thread::yield(); continue; } - // Both length and content are determined by the sequence number, so the consumer can verify independently. + // Both length and content are determined by the sequence number, so the consumer can verify + // independently. const auto length = static_cast(14 + (sent % 400)); const auto tag = static_cast(sent & 0xFFU); for (std::uint32_t i = 0; i < length; ++i) { @@ -250,7 +256,7 @@ TEST_CASE("并发搬运 20 万帧不丢不乱序") { TEST_SUITE("common.frame_ring_batch") { -TEST_CASE("批量写:暂存期间消费者看不到,发布后一次性可见") { +TEST_CASE("batch write: invisible while staged, visible all at once after publishing") { FrameRing ring(16, 1514); { auto batch = ring.BeginBatchWrite(); @@ -266,7 +272,7 @@ TEST_CASE("批量写:暂存期间消费者看不到,发布后一次性可见 CHECK(ring.SizeSnapshot() == 5); } -TEST_CASE("批量写:显式 Publish 后可继续暂存") { +TEST_CASE("batch write: staging continues after an explicit Publish") { FrameRing ring(16, 1514); auto batch = ring.BeginBatchWrite(); REQUIRE(batch.Push(MakeFrame(64, 1))); @@ -283,7 +289,7 @@ TEST_CASE("批量写:显式 Publish 后可继续暂存") { CHECK(ring.SizeSnapshot() == 3); } -TEST_CASE("批量写:队列满时 Begin 返回空,已暂存的仍会发布") { +TEST_CASE("batch write: Begin returns empty when full, and staged frames are still published") { FrameRing ring(4, 64); { auto batch = ring.BeginBatchWrite(); @@ -300,7 +306,7 @@ TEST_CASE("批量写:队列满时 Begin 返回空,已暂存的仍会发布") CHECK(ring.SizeSnapshot() == 4); } -TEST_CASE("批量读:释放前视图有效,释放后槽位才可复用") { +TEST_CASE("batch read: views stay valid until release, slots are reused only after it") { FrameRing ring(8, 1514); for (std::uint8_t i = 0; i < 4; ++i) { REQUIRE(ring.TryPush(MakeFrame(100, static_cast(0x20 + i)))); @@ -316,8 +322,9 @@ TEST_CASE("批量读:释放前视图有效,释放后槽位才可复用") { } CHECK(batch.Next().Empty()); // all taken CHECK(batch.Staged() == 4); - // Key semantics: not yet released, so all views still point to valid content that has not been overwritten. - // This is exactly the precondition for "gather a batch and write it out zero-copy". + // Key semantics: not yet released, so all views still point to valid content that has not been + // overwritten. This is exactly the precondition for "gather a batch and write it out + // zero-copy". for (std::size_t i = 0; i < views.size(); ++i) { CHECK(views[i].length == 100); CHECK(VerifyFrame(views[i].Bytes(), static_cast(0x20 + i))); @@ -328,7 +335,7 @@ TEST_CASE("批量读:释放前视图有效,释放后槽位才可复用") { CHECK(ring.SizeSnapshot() == 0); } -TEST_CASE("批量读:显式 Release 后可继续取") { +TEST_CASE("batch read: reading continues after an explicit Release") { FrameRing ring(8, 1514); for (std::uint8_t i = 0; i < 6; ++i) { REQUIRE(ring.TryPush(MakeFrame(64, i))); @@ -348,7 +355,7 @@ TEST_CASE("批量读:显式 Release 后可继续取") { CHECK(ring.SizeSnapshot() == 0); } -TEST_CASE("批量与逐帧接口混用仍保持 FIFO 与内容正确") { +TEST_CASE("mixing batch and per-frame APIs keeps FIFO order and content") { FrameRing ring(16, 1514); // First push 2 per frame, then push 3 in a batch, then read 5 in a batch. REQUIRE(ring.TryPush(MakeFrame(64, 0))); @@ -368,7 +375,7 @@ TEST_CASE("批量与逐帧接口混用仍保持 FIFO 与内容正确") { CHECK(batch.Next().Empty()); } -TEST_CASE("批量接口并发搬运 20 万帧不丢不乱序") { +TEST_CASE("batch API, 200,000 frames across threads: none lost, none reordered") { constexpr std::uint32_t kTotal = 200'000; constexpr std::uint32_t kBatch = 32; FrameRing ring(1024, 512); diff --git a/tests/test_common_i18n.cc b/tests/test_common_i18n.cc index 838b4b3..3df43c4 100644 --- a/tests/test_common_i18n.cc +++ b/tests/test_common_i18n.cc @@ -1,14 +1,16 @@ // Consistency check of the message table. // -// * The sole reason this suite exists * +// The sole reason this suite exists: // -// The format strings of Tr() come from a runtime table lookup, and the compiler **can no longer** check whether the placeholders match the arguments -- -// this is the price paid for replacing std::format with vformat. When placeholders do not match, vformat throws -// std::format_error (we swallow it in FormatMessage, degrading to the unsubstituted original text), -// so the error quietly turns into "one oddly shaped line in the log", which may go unnoticed for months. +// The format strings of Tr() come from a runtime table lookup, and the compiler **can no longer** +// check whether the placeholders match the arguments this is the price paid for replacing +// std::format with vformat. When placeholders do not match, vformat throws std::format_error (we +// swallow it in FormatMessage, degrading to the unsubstituted original text), so the error +// quietly turns into "one oddly shaped line in the log", which may go unnoticed for months. // -// So that safeguard must be made up here: compare, entry by entry, the argument indices and types referenced by the two languages. -// Every message added to messages.def is automatically covered by this suite, with no manual registration. +// So that safeguard must be made up here: compare, entry by entry, the argument indices and types +// referenced by the two languages. Every message added to messages.def is automatically covered +// by this suite, with no manual registration. #include #include #include @@ -32,17 +34,20 @@ constexpr std::size_t kMessageCount = static_cast(Msg::kMessageCoun struct ParsedFormat { /// Index -> the set of "presentation type" characters used by that index. /// - /// The presentation type is the last letter of the format spec (`x` / `f` / `d`...), and it determines what type - /// the argument must be. Width, alignment and fill are deliberately **not compared**: after a translation changes language, adjusting column width - /// is entirely legitimate and does not affect type safety. + /// The presentation type is the last letter of the format spec (`x` / `f` / `d`...), and it + /// determines what type the argument must be. Width, alignment and fill are **not compared**: + /// after a translation changes language, adjusting column width is entirely legitimate and does + /// not affect type safety. std::map types; - /// Whether automatic numbering and manual numbering are mixed in the same string (std::format throws directly). + /// Whether automatic numbering and manual numbering are mixed in the same string (std::format + /// throws directly). bool mixed_indexing = false; /// Whether there is an unclosed `{`. bool malformed = false; }; -/// Extracts the presentation type character from a format spec. Returns an empty string when there is no spec or the spec ends with a non-letter. +/// Extracts the presentation type character from a format spec. Returns an empty string when there +/// is no spec or the spec ends with a non-letter. [[nodiscard]] std::string PresentationType(std::string_view spec) { if (spec.empty()) { return {}; @@ -54,7 +59,8 @@ struct ParsedFormat { /// Parses a std::format format string and collects the replacement fields. /// /// Implements only the syntax subset our messages actually use: `{}`, `{n}`, `{:spec}`, `{n:spec}`, -/// plus the `{{` / `}}` escapes. Nested dynamic widths (`{:{}}`) do not exist in this table, and their appearance is treated as malformed. +/// plus the `{{` / `}}` escapes. Nested dynamic widths (`{:{}}`) do not exist in this table, and +/// their appearance is treated as malformed. [[nodiscard]] ParsedFormat ParseFormat(std::string_view text) { ParsedFormat parsed; std::size_t auto_index = 0; @@ -116,8 +122,9 @@ struct ParsedFormat { return parsed; } -/// A readable label for error reports. The message table does not store identifier names (the X-macro expands only the text), so it uses -/// the ordinal + the beginning of the English text, enough to locate which line of messages.def. +/// A readable label for error reports. The message table does not store identifier names (the +/// X-macro expands only the text), so it uses the ordinal + the beginning of the English text, +/// enough to locate which line of messages.def. [[nodiscard]] std::string Label(std::size_t index) { const std::string_view english = tetherkitnext::TextIn(Language::kEnglish, static_cast(index)); return std::format("message #{} (\"{}\")", index, english.substr(0, 48)); @@ -127,12 +134,13 @@ struct ParsedFormat { TEST_SUITE("common.i18n") { -TEST_CASE("语言切换与查表") { +TEST_CASE("switching language and looking up messages") { const Language original = tetherkitnext::GetLanguage(); tetherkitnext::SetLanguage(Language::kChinese); CHECK(tetherkitnext::GetLanguage() == Language::kChinese); - CHECK(tetherkitnext::Text(Msg::kCoreRunStateRunning) == "运行中"); + CHECK(tetherkitnext::Text(Msg::kCoreRunStateRunning) == + "运行中"); // the zh table entry ("running") tetherkitnext::SetLanguage(Language::kEnglish); CHECK(tetherkitnext::GetLanguage() == Language::kEnglish); @@ -141,7 +149,7 @@ TEST_CASE("语言切换与查表") { tetherkitnext::SetLanguage(original); } -TEST_CASE("Tr 按当前语言渲染并替换参数") { +TEST_CASE("Tr renders in the current language with arguments substituted") { const Language original = tetherkitnext::GetLanguage(); tetherkitnext::SetLanguage(Language::kChinese); @@ -156,7 +164,7 @@ TEST_CASE("Tr 按当前语言渲染并替换参数") { tetherkitnext::SetLanguage(original); } -TEST_CASE("每条文案两种语言都非空") { +TEST_CASE("every message is non-empty in both languages") { for (std::size_t i = 0; i < kMessageCount; ++i) { const auto id = static_cast(i); CAPTURE(i); @@ -165,14 +173,14 @@ TEST_CASE("每条文案两种语言都非空") { } } -TEST_CASE("越界的 Msg 返回空串而不是崩溃") { +TEST_CASE("an out-of-range Msg returns an empty string instead of crashing") { const auto out_of_range = static_cast(kMessageCount); CHECK(tetherkitnext::Text(out_of_range).empty()); CHECK(tetherkitnext::TextIn(Language::kChinese, out_of_range).empty()); } // The core of this suite: the thing the compiler no longer checks is checked here entry by entry. -TEST_CASE("两种语言的占位符下标与类型一致") { +TEST_CASE("placeholder indices and types match in both languages") { for (std::size_t i = 0; i < kMessageCount; ++i) { const auto id = static_cast(i); const ParsedFormat chinese = ParseFormat(tetherkitnext::TextIn(Language::kChinese, id)); @@ -181,21 +189,24 @@ TEST_CASE("两种语言的占位符下标与类型一致") { CAPTURE(Label(i)); CHECK_FALSE(chinese.malformed); CHECK_FALSE(english.malformed); - // Mixing `{}` and `{0}` in one string makes std::format throw directly, and the compile time cannot stop it. + // Mixing `{}` and `{0}` in one string makes std::format throw directly, and the compile time + // cannot stop it. CHECK_FALSE(chinese.mixed_indexing); CHECK_FALSE(english.mixed_indexing); - // The number and indices of arguments must match exactly: one fewer renders an incomplete sentence, one more throws directly. + // The number and indices of arguments must match exactly: one fewer renders an incomplete + // sentence, one more throws directly. CHECK(chinese.types.size() == english.types.size()); for (const auto& [index, type] : chinese.types) { const auto found = english.types.find(index); REQUIRE(found != english.types.end()); - // Different type characters mean the two sides expect different argument types, so one side is bound to throw. + // Different type characters mean the two sides expect different argument types, so one side + // is bound to throw. CHECK(found->second == type); } - // Indices must be consecutive 0..n-1: leaving a gap std::format can still render, but that means some - // argument is ignored by both languages at once, which is almost always a mistake. + // Indices must be consecutive 0..n-1: leaving a gap std::format can still render, but that + // means some argument is ignored by both languages at once, which is almost always a mistake. std::size_t expected = 0; for (const auto& [index, type] : chinese.types) { CHECK(index == expected); @@ -204,7 +215,7 @@ TEST_CASE("两种语言的占位符下标与类型一致") { } } -TEST_CASE("ParseLanguage 认得常见写法") { +TEST_CASE("ParseLanguage recognizes common spellings") { Language language = Language::kEnglish; CHECK(tetherkitnext::ParseLanguage("zh", &language)); @@ -231,7 +242,7 @@ TEST_CASE("ParseLanguage 认得常见写法") { CHECK_FALSE(tetherkitnext::ParseLanguage("zh", nullptr)); } -TEST_CASE("区域设置串只按 zh 前缀判定") { +TEST_CASE("locale strings are judged by the zh prefix only") { CHECK(tetherkitnext::LanguageFromLocaleString("zh_CN.UTF-8") == Language::kChinese); CHECK(tetherkitnext::LanguageFromLocaleString("ZH-hant") == Language::kChinese); CHECK(tetherkitnext::LanguageFromLocaleString("en_US.UTF-8") == Language::kEnglish); @@ -241,19 +252,20 @@ TEST_CASE("区域设置串只按 zh 前缀判定") { CHECK(tetherkitnext::LanguageFromLocaleString("en_zh") == Language::kEnglish); } -TEST_CASE("语言标签") { +TEST_CASE("language tags") { CHECK(tetherkitnext::LanguageTag(Language::kChinese) == "zh"); CHECK(tetherkitnext::LanguageTag(Language::kEnglish) == "en"); } -TEST_CASE("错误上下文的分隔符随语言变化") { +TEST_CASE("the error context separator follows the language") { const Language original = tetherkitnext::GetLanguage(); - // Context() returns a view, so the Error must first be put into a named variable before taking it, - // otherwise the temporary is destroyed at the end of the statement and the view dangles on the spot. + // Context() returns a view, so the Error must first be put into a named variable before taking + // it, otherwise the temporary is destroyed at the end of the statement and the view dangles on + // the spot. tetherkitnext::SetLanguage(Language::kChinese); const tetherkitnext::Error chinese = tetherkitnext::Error::Generic("inner").WithContext("outer"); - CHECK(chinese.Context().starts_with("outer:")); + CHECK(chinese.Context().starts_with("outer:")); // zh uses the full-width colon U+FF1A tetherkitnext::SetLanguage(Language::kEnglish); const tetherkitnext::Error english = tetherkitnext::Error::Generic("inner").WithContext("outer"); diff --git a/tests/test_common_spsc_ring.cc b/tests/test_common_spsc_ring.cc index 40c616a..e3386f2 100644 --- a/tests/test_common_spsc_ring.cc +++ b/tests/test_common_spsc_ring.cc @@ -16,7 +16,8 @@ using tetherkitnext::SpscRing; namespace { -/// Used to verify that "the element content is really transferred in full" rather than just the index. +/// Used to verify that "the element content is really transferred in full" rather than just the +/// index. struct Payload { std::uint64_t sequence; std::uint32_t checksum; @@ -30,14 +31,14 @@ constexpr std::uint32_t Checksum(std::uint64_t sequence) { TEST_SUITE("common.spsc_ring") { -TEST_CASE("容量向上取整到 2 的幂") { +TEST_CASE("capacity is rounded up to a power of two") { CHECK(SpscRing(1).Capacity() == 1); CHECK(SpscRing(3).Capacity() == 4); CHECK(SpscRing(4).Capacity() == 4); CHECK(SpscRing(1000).Capacity() == 1024); } -TEST_CASE("空队列出队失败") { +TEST_CASE("popping an empty queue fails") { SpscRing ring(4); std::uint32_t value = 0xFFFFFFFFU; CHECK_FALSE(ring.TryPop(value)); @@ -45,8 +46,9 @@ TEST_CASE("空队列出队失败") { CHECK(ring.SizeSnapshot() == 0); } -TEST_CASE("满队列入队失败且容量被完整利用") { - // One of the design goals of the freely incrementing counters: no wasted slots. Capacity 4 should hold 4. +TEST_CASE("pushing to a full queue fails and the whole capacity is used") { + // One of the design goals of the freely incrementing counters: no wasted slots. Capacity 4 should + // hold 4. SpscRing ring(4); for (std::uint32_t i = 0; i < 4; ++i) { CHECK(ring.TryPush(i)); @@ -55,7 +57,7 @@ TEST_CASE("满队列入队失败且容量被完整利用") { CHECK_FALSE(ring.TryPush(99)); } -TEST_CASE("FIFO 顺序与内容完整性") { +TEST_CASE("FIFO order and content integrity") { SpscRing ring(8); for (std::uint64_t i = 0; i < 8; ++i) { CHECK(ring.TryPush(Payload{.sequence = i, .checksum = Checksum(i)})); @@ -69,8 +71,9 @@ TEST_CASE("FIFO 顺序与内容完整性") { CHECK(ring.SizeSnapshot() == 0); } -TEST_CASE("反复绕环不丢数据") { - // Capacity 4, push 1000 elements, taking one immediately after each push, forcing the indices to wrap around repeatedly. +TEST_CASE("wrapping around repeatedly loses no data") { + // Capacity 4, push 1000 elements, taking one immediately after each push, forcing the indices to + // wrap around repeatedly. SpscRing ring(4); for (std::uint64_t i = 0; i < 1000; ++i) { REQUIRE(ring.TryPush(i)); @@ -80,18 +83,18 @@ TEST_CASE("反复绕环不丢数据") { } } -TEST_CASE("索引游标各字段落在不同缓存行") { +TEST_CASE("each index cursor sits on its own cache line") { // This is a performance correctness assertion: if false sharing regresses, this test case fails. SpscRing ring(8); const auto& cursor = ring.Cursor(); const auto base = reinterpret_cast(&cursor); - // SpscCursor's four indices each have alignas(kCacheLineSize), - // so the whole object must occupy at least 4 cache lines (plus the one for the read-only fields). + // SpscCursor's four indices each have alignas(kCacheLineSize), so the whole object must occupy at + // least 4 cache lines (plus the one for the read-only fields). CHECK(sizeof(tetherkitnext::SpscCursor) >= 4 * kCacheLineSize); CHECK(base % kCacheLineSize == 0); } -TEST_CASE("单生产者单消费者并发搬运不丢不重不乱序") { +TEST_CASE("single producer / single consumer: nothing lost, duplicated or reordered") { constexpr std::uint64_t kTotal = 200'000; SpscRing ring(1024); @@ -114,7 +117,8 @@ TEST_CASE("单生产者单消费者并发搬运不丢不重不乱序") { while (expected < kTotal) { Payload out{}; if (ring.TryPop(out)) { - // The order must be strictly increasing (FIFO), and the content must be self-consistent with the sequence number (no tearing). + // The order must be strictly increasing (FIFO), and the content must be self-consistent with + // the sequence number (no tearing). if (out.sequence != expected || out.checksum != Checksum(out.sequence)) { corrupted.store(true, std::memory_order_relaxed); break; diff --git a/tests/test_common_stats.cc b/tests/test_common_stats.cc index 4ff2cb7..76e183f 100644 --- a/tests/test_common_stats.cc +++ b/tests/test_common_stats.cc @@ -18,7 +18,7 @@ using tetherkitnext::Stopwatch; TEST_SUITE("common.stats") { -TEST_CASE("计数器累加与快照") { +TEST_CASE("counter accumulation and snapshots") { DirectionCounters counters; counters.AddFrame(1514); counters.AddFrame(64); @@ -37,7 +37,7 @@ TEST_CASE("计数器累加与快照") { CHECK(snapshot.TotalDropped() == 6); } -TEST_CASE("批次计数用于计算平均批大小") { +TEST_CASE("batch counts give the average batch size") { DirectionCounters counters; counters.AddBatch(10, 15140); counters.AddBatch(6, 9084); @@ -48,7 +48,7 @@ TEST_CASE("批次计数用于计算平均批大小") { CHECK(snapshot.batches == 2); } -TEST_CASE("快照相减得到窗口增量") { +TEST_CASE("subtracting snapshots gives the window delta") { DirectionCounters counters; counters.AddFrame(100); const auto first = Snapshot(counters); @@ -62,7 +62,7 @@ TEST_CASE("快照相减得到窗口增量") { CHECK(delta.dropped_full == 1); } -TEST_CASE("速率采样把字节数换算成 Mbps") { +TEST_CASE("rate sampling converts bytes to Mbps") { PathCounters counters; RateSampler sampler; @@ -72,14 +72,15 @@ TEST_CASE("速率采样把字节数换算成 Mbps") { const auto report = sampler.Sample(counters); CHECK(report.seconds > 0.0); - // It ran only about 20 ms, so the rate is amplified by about 50x; here we only verify whether the conversion relation is self-consistent. + // It ran only about 20 ms, so the rate is amplified by about 50x; here we only verify whether the + // conversion relation is self-consistent. const double expected_mbps = 12'500'000.0 * 8.0 / 1'000'000.0 / report.seconds; CHECK(report.rx_mbps == doctest::Approx(expected_mbps).epsilon(0.01)); CHECK(report.rx_avg_batch == doctest::Approx(8000.0)); CHECK(report.tx_pps == doctest::Approx(0.0)); } -TEST_CASE("秒表读数单调不减") { +TEST_CASE("stopwatch readings never decrease") { const Stopwatch watch; const auto first = watch.Elapsed(); std::this_thread::sleep_for(std::chrono::milliseconds(2)); @@ -88,7 +89,7 @@ TEST_CASE("秒表读数单调不减") { CHECK(watch.ElapsedMillis() >= 1.0); } -TEST_CASE("周期定时器的默认构造仍然是「构造即开始计时」") { +TEST_CASE("a default-constructed periodic timer still starts timing at construction") { PeriodicTimer timer(50 * kNanosPerMilli); // Should not be expired right after construction. CHECK_FALSE(timer.Expired()); @@ -96,10 +97,13 @@ TEST_CASE("周期定时器的默认构造仍然是「构造即开始计时」") CHECK(timer.Period() == 50 * kNanosPerMilli); } -TEST_CASE("周期定时器按累加期限推进,不随调度延迟漂移") { +TEST_CASE( + "the periodic timer advances by accumulated deadlines and does not drift with scheduling " + "delay") { const tetherkitnext::Nanos now = MonotonicNanos(); - // `now` must be passed in explicitly as the timing origin. If the constructor reads the clock itself, the moment it reads - // would be slightly later than `now` here, so "now + period" would not yet be expired, and the assertion would fail at random. + // `now` must be passed in explicitly as the timing origin. If the constructor reads the clock + // itself, the moment it reads would be slightly later than `now` here, so "now + period" would + // not yet be expired, and the assertion would fail at random. PeriodicTimer timer(10 * kNanosPerMilli, now); CHECK_FALSE(timer.Expired(now)); @@ -113,11 +117,12 @@ TEST_CASE("周期定时器按累加期限推进,不随调度延迟漂移") { CHECK(timer.Expired(now + 20 * kNanosPerMilli)); } -TEST_CASE("周期定时器落后超过一个周期时不补发一串触发") { +TEST_CASE("a periodic timer more than a period behind does not fire a burst of catch-up ticks") { const tetherkitnext::Nanos now = MonotonicNanos(); PeriodicTimer timer(10 * kNanosPerMilli, now); - // The thread wakes only after being suspended for 1 second: it should trigger only once, then align to after the current moment. + // The thread wakes only after being suspended for 1 second: it should trigger only once, then + // align to after the current moment. const tetherkitnext::Nanos late = now + 1000 * kNanosPerMilli; CHECK(timer.Expired(late)); CHECK_FALSE(timer.Expired(late)); diff --git a/tests/test_core_bridge.cc b/tests/test_core_bridge.cc index b79b640..fc61eaa 100644 --- a/tests/test_core_bridge.cc +++ b/tests/test_core_bridge.cc @@ -55,8 +55,9 @@ std::vector> MakeFrames(std::uint32_t count, std::uint32_ /// Polls and waits for a condition to hold, for at most `timeout`. /// -/// The data path is asynchronous, and one cannot "wait for it to finish" by sleeping a fixed duration -- that would -/// fail intermittently on slow machines. Here we wait for the condition rather than for time. +/// The data path is asynchronous, and one cannot "wait for it to finish" by sleeping a fixed +/// duration; that would fail intermittently on slow machines. Here we wait for the condition rather +/// than for time. template bool WaitFor(Predicate predicate, std::chrono::milliseconds timeout = std::chrono::seconds(5)) { const auto deadline = std::chrono::steady_clock::now() + timeout; @@ -69,7 +70,8 @@ bool WaitFor(Predicate predicate, std::chrono::milliseconds timeout = std::chron return predicate(); } -/// The bridge configuration used by tests: small queues and small batches, making boundaries easier to trigger. +/// The bridge configuration used by tests: small queues and small batches, making boundaries easier +/// to trigger. [[nodiscard]] BridgeConfig TestConfig() { BridgeConfig config; config.rx_ring_frames = 256; @@ -84,7 +86,7 @@ bool WaitFor(Predicate predicate, std::chrono::milliseconds timeout = std::chron TEST_SUITE("core.bridge") { -TEST_CASE("启动与停止:线程正常起停,停机时通道被关闭") { +TEST_CASE("start and stop: threads start and stop, and channels close on shutdown") { MockDataChannel channel; LoopbackLink link; Bridge bridge(channel, link, TestConfig()); @@ -105,7 +107,7 @@ TEST_CASE("启动与停止:线程正常起停,停机时通道被关闭") { bridge.Stop(); } -TEST_CASE("RX 方向:设备发来的帧被搬到链路上,内容完整") { +TEST_CASE("RX: frames from the device reach the link intact") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.sent_capacity = 4096}); Bridge bridge(channel, link, TestConfig()); @@ -131,7 +133,7 @@ TEST_CASE("RX 方向:设备发来的帧被搬到链路上,内容完整") { bridge.Stop(); } -TEST_CASE("TX 方向:链路收到的帧被提交给设备,内容完整") { +TEST_CASE("TX: frames from the link reach the device intact") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 4096, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); @@ -157,7 +159,7 @@ TEST_CASE("TX 方向:链路收到的帧被提交给设备,内容完整") { bridge.Stop(); } -TEST_CASE("双向同时跑,互不干扰") { +TEST_CASE("both directions at once do not interfere") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 8192, .sent_capacity = 8192, .max_frames_per_batch = 64}); @@ -198,9 +200,10 @@ TEST_CASE("双向同时跑,互不干扰") { bridge.Stop(); } -TEST_CASE("RX 队列满时丢弃并计数,不阻塞生产者") { +TEST_CASE("a full RX queue drops and counts without blocking the producer") { MockDataChannel channel; - // The link's write capacity is set very small, so the RX injection thread cannot write out and the queue fills up quickly. + // The link's write capacity is set very small, so the RX injection thread cannot write out and + // the queue fills up quickly. LoopbackLink link(LoopbackConfig{.sent_capacity = 8}); auto config = TestConfig(); config.rx_ring_frames = 16; @@ -221,16 +224,17 @@ TEST_CASE("RX 队列满时丢弃并计数,不阻塞生产者") { bridge.Stop(); } -TEST_CASE("TX 背压:传输池占满时等待而不丢弃,容量恢复后全部送达") { - // This is a regression test for the root cause of dropped frames on real hardware: the old implementation immediately dropped the batch's remaining frames when SendFrames returned 0 - // (bridge.cc once had a wrong argument that "waiting turns into invisible kernel drops"), - // dropping 30%+ of TX traffic at the door of the transfer pool under high load. The correct behavior is to wait for a slot to free up and then retry - // -- bursts are absorbed by the upstream kernel BPF buffer. +TEST_CASE( + "TX backpressure: waits instead of dropping when the pool is full, then delivers everything") { + // When SendFrames returns 0 (transfer pool full), the bridge must wait for a slot to free up and + // retry rather than drop the batch's remaining frames. Dropping would lose 30%+ of TX traffic + // under high load; bursts are absorbed by the kernel BPF buffer. MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 4096, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); - // Make the mock channel accept not a single frame -- simulating the transfer pool being completely full. + // Make the mock channel accept not a single frame; simulating the transfer pool being completely + // full. channel.SetAcceptLimit(0); REQUIRE(bridge.Start().has_value()); @@ -239,18 +243,20 @@ TEST_CASE("TX 背压:传输池占满时等待而不丢弃,容量恢复后全 REQUIRE(link.PushInbound(frame)); } - // The bridge layer should go into waiting: backpressure events rise and WaitForSendCapacity gets called, - // but not a single frame is dropped, and not a single frame is sent out. + // The bridge layer should go into waiting: backpressure events rise and WaitForSendCapacity gets + // called, but not a single frame is dropped, and not a single frame is sent out. REQUIRE(WaitFor([&] { return bridge.Snapshot().tx_backpressure_events > 0; })); REQUIRE(WaitFor([&] { return channel.WaitCalls() > 0; })); CHECK(bridge.Snapshot().tx.TotalDropped() == 0); CHECK(channel.SentFrameCount() == 0); - // Capacity is restored (equivalent to an in-flight transfer completing and the slot being returned): the frames that had been stuck at the door must - // be delivered **without losing a single frame**, and in the same order. - // The wait condition must cover both the mock count and the bridge-layer count: the mock increments inside SendFrames first, - // and the bridge layer only does AddBatch after returning, with no happens-before between the two -- waiting only on the mock count and - // then asserting the bridge-layer count would intermittently read an old value one slice behind on slow machines. + // Capacity is restored (equivalent to an in-flight transfer completing and the slot being + // returned): the frames that had been stuck at the door must be delivered **without losing a + // single frame**, and in the same order. The wait condition must cover both the mock count and + // the bridge-layer count: the mock increments inside SendFrames first, and the bridge layer only + // does AddBatch after returning, with no happens-before between the two; waiting only on the mock + // count and then asserting the bridge-layer count would intermittently read an old value one + // slice behind on slow machines. channel.SetAcceptLimit(0xFFFF'FFFFU); REQUIRE(WaitFor([&] { return channel.SentFrameCount() >= kFrameCount && @@ -272,9 +278,11 @@ TEST_CASE("TX 背压:传输池占满时等待而不丢弃,容量恢复后全 bridge.Stop(); } -TEST_CASE("TX 背压:部分接纳时剩余帧重试送达,不丢不乱序") { - // The pool is not full but cannot fit a whole slice at once (SendFrames partially accepts): the remaining frames must be retried in place. - // At most 7 frames each time and a slice of 32 frames, forcing out the path of "multiple partial accepts completing one slice". +TEST_CASE( + "TX backpressure: after a partial accept the rest is retried, with no loss or reordering") { + // The pool is not full but cannot fit a whole slice at once (SendFrames partially accepts): the + // remaining frames must be retried in place. At most 7 frames each time and a slice of 32 frames, + // forcing out the path of "multiple partial accepts completing one slice". MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 4096, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); @@ -300,9 +308,9 @@ TEST_CASE("TX 背压:部分接纳时剩余帧重试送达,不丢不乱序") bridge.Stop(); } -TEST_CASE("TX 背压:等待期间 Stop() 能及时返回") { - // The backpressure wait introduces a new blocking point, and shutdown must not be stuck by it: the TX thread must re-check the shutdown flag on every wakeup (at most about - // 50 ms). +TEST_CASE("TX backpressure: Stop() returns promptly while waiting") { + // The backpressure wait introduces a new blocking point, and shutdown must not be stuck by it: + // the TX thread must re-check the shutdown flag on every wakeup (at most about 50 ms). MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 4096, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); @@ -320,15 +328,19 @@ TEST_CASE("TX 背压:等待期间 Stop() 能及时返回") { const auto stop_elapsed = std::chrono::steady_clock::now() - stop_begin; CHECK_FALSE(bridge.Running()); - // The upper bound is "wait timeout + BPF read timeout + slack". The real constraint is on the order of tens of milliseconds, - // and it is relaxed to 2 seconds here only to avoid flaky failures on slow CI. + // The upper bound is "wait timeout + BPF read timeout + slack". The real constraint is on the + // order of tens of milliseconds, and it is relaxed to 2 seconds here only to avoid flaky failures + // on slow CI. CHECK(stop_elapsed < std::chrono::seconds(2)); - // Frames not sent out at shutdown are counted as drops -- the books must balance, and frames cannot vanish out of thin air. + // Frames not sent out at shutdown are counted as drops; the books must balance, and frames cannot + // vanish out of thin air. CHECK(bridge.Snapshot().tx.TotalDropped() > 0); } -TEST_CASE("TX 背压:等待期间落下暂停,剩余帧被丢弃且线程存活") { - // Pausing (RNDIS soft reset) takes priority over waiting: the device will discard outstanding packets anyway, and hoarding them is meaningless. +TEST_CASE( + "TX backpressure: pausing while waiting drops the remaining frames and the thread survives") { + // Pausing (RNDIS soft reset) takes priority over waiting: the device will discard outstanding + // packets anyway, and hoarding them is meaningless. MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 4096, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); @@ -346,7 +358,7 @@ TEST_CASE("TX 背压:等待期间落下暂停,剩余帧被丢弃且线程存 REQUIRE(WaitFor([&] { return bridge.Snapshot().tx.TotalDropped() > 0; })); CHECK(channel.SentFrameCount() == 0); - // After resuming, new frames are delivered as usual -- the thread is not stuck in a wait. + // After resuming, new frames are delivered as usual; the thread is not stuck in a wait. bridge.SetPaused(false); channel.SetAcceptLimit(0xFFFF'FFFFU); for (const std::vector& frame : MakeFrames(20, 512)) { @@ -357,7 +369,7 @@ TEST_CASE("TX 背压:等待期间落下暂停,剩余帧被丢弃且线程存 bridge.Stop(); } -TEST_CASE("暂停期间不搬运,恢复后 RX 队列里的帧继续送出") { +TEST_CASE("nothing moves while paused; queued RX frames go out after resuming") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.sent_capacity = 4096}); Bridge bridge(channel, link, TestConfig()); @@ -369,13 +381,14 @@ TEST_CASE("暂停期间不搬运,恢复后 RX 队列里的帧继续送出") { constexpr std::uint32_t kCount = 32; CHECK(channel.InjectFromDevice(MakeFrames(kCount, 256)) == kCount); - // No frames should be written to the link during the pause. Give the injection thread a bit of time to prove it really did not move. + // No frames should be written to the link during the pause. Give the injection thread a bit of + // time to prove it really did not move. std::this_thread::sleep_for(std::chrono::milliseconds(50)); CHECK(link.TotalSentFrames() == 0); // The frames are still in the queue and have not been dropped. CHECK(bridge.Snapshot().rx_queue_depth == kCount); - // After resuming they should all be sent out -- pausing does not lose frames. + // After resuming they should all be sent out; pausing does not lose frames. bridge.SetPaused(false); REQUIRE(WaitFor([&] { return link.TotalSentFrames() >= kCount; })); CHECK(bridge.Snapshot().rx.TotalDropped() == 0); @@ -383,12 +396,14 @@ TEST_CASE("暂停期间不搬运,恢复后 RX 队列里的帧继续送出") { bridge.Stop(); } -TEST_CASE("SetPaused 在任何生命周期阶段都不会挂死") { - // SetPaused(true) waits for the RX injection thread to confirm it has stopped. This wait has two hang risks, - // both far more severe than the frame-leak problem it is meant to fix (what hangs is the control path: link state changes, device soft reset): +TEST_CASE("SetPaused never hangs at any lifecycle stage") { + // SetPaused(true) waits for the RX injection thread to confirm it has stopped. This wait has two + // hang risks, both far more severe than the frame-leak problem it is meant to fix (what hangs is + // the control path: link state changes, device soft reset): // * when the thread is not running at all, nobody comes to set the acknowledgement bit; // * a leftover acknowledgement bit makes the wait logic itself go wrong. - // Here all three phases are walked through, and a hang at any point makes this test case time out rather than pass silently. + // Here all three phases are walked through, and a hang at any point makes this test case time out + // rather than pass silently. MockDataChannel channel; LoopbackLink link(LoopbackConfig{.sent_capacity = 4096}); Bridge bridge(channel, link, TestConfig()); @@ -400,8 +415,9 @@ TEST_CASE("SetPaused 在任何生命周期阶段都不会挂死") { REQUIRE(bridge.Start().has_value()); - // Phase two: rapid toggling while running. The acknowledgement bit is cleared at the start of every loop iteration, so that a later SetPaused(true) - // does not read the previous round's leftover value and return early -- returning early means the guarantee is void. + // Phase two: rapid toggling while running. The acknowledgement bit is cleared at the start of + // every loop iteration, so that a later SetPaused(true) does not read the previous round's + // leftover value and return early; returning early means the guarantee is void. for (int i = 0; i < 50; ++i) { bridge.SetPaused(true); bridge.SetPaused(false); @@ -421,9 +437,9 @@ TEST_CASE("SetPaused 在任何生命周期阶段都不会挂死") { CHECK(bridge.Paused()); } -TEST_CASE("暂停期间 TX 方向的帧被丢弃并计数") { - // Unlike RX: the TX side must drop while paused, because during an RNDIS reset the device discards all outstanding - // data packets, and hoarding them only wastes memory. +TEST_CASE("TX frames are dropped and counted while paused") { + // Unlike RX: the TX side must drop while paused, because during an RNDIS reset the device + // discards all outstanding data packets, and hoarding them only wastes memory. MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 512, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); @@ -440,7 +456,7 @@ TEST_CASE("暂停期间 TX 方向的帧被丢弃并计数") { bridge.Stop(); } -TEST_CASE("链路写失败不会让线程退出,恢复后继续工作") { +TEST_CASE("a failed link write does not stop the thread; it continues after recovery") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.sent_capacity = 4096}); link.FailWritesAfter(1); // fail starting from the 2nd write @@ -448,19 +464,23 @@ TEST_CASE("链路写失败不会让线程退出,恢复后继续工作") { REQUIRE(bridge.Start().has_value()); for (int round = 0; round < 5; ++round) { - // Here we do not care how many frames were enqueued; it is enough to generate traffic that "writes the link repeatedly". + // Here we do not care how many frames were enqueued; it is enough to generate traffic that + // "writes the link repeatedly". (void)channel.InjectFromDevice(MakeFrames(16, 256)); std::this_thread::sleep_for(std::chrono::milliseconds(5)); } // Key: the bridge layer is still running, and did not crash or exit because of write failures. CHECK(bridge.Running()); - CHECK(bridge.Snapshot().rx.io_errors > 0); + // The injector writes asynchronously; on a slow runner the failing write may not have happened + // yet when the loop above ends, so wait for it instead of sampling once. + CHECK(WaitFor([&] { return bridge.Snapshot().rx.io_errors > 0; })); + CHECK(bridge.Running()); bridge.Stop(); } -TEST_CASE("USB 提交失败被记为 I/O 错误,桥接层继续运行") { +TEST_CASE("a failed USB submit counts as an I/O error and the bridge keeps running") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 512, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); @@ -477,9 +497,9 @@ TEST_CASE("USB 提交失败被记为 I/O 错误,桥接层继续运行") { bridge.Stop(); } -TEST_CASE("统计行渲染出速率与丢包") { - // The statistics line is user-facing text; the assertions below are in Chinese, so pin the language first. - const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kChinese}; +TEST_CASE("the stats line shows rates and drops") { + // The statistics line is user-facing text; pin the language the assertions below expect. + const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kEnglish}; MockDataChannel channel; LoopbackLink link(LoopbackConfig{.sent_capacity = 4096}); Bridge bridge(channel, link, TestConfig()); @@ -496,19 +516,20 @@ TEST_CASE("统计行渲染出速率与丢包") { CHECK(line.find("TX") != std::string::npos); CHECK(line.find("pps") != std::string::npos); CHECK(line.find("Mbps") != std::string::npos); - CHECK(line.find("队列深度") != std::string::npos); + CHECK(line.find("queue depth") != std::string::npos); bridge.Stop(); } -TEST_CASE("停机时不丢已在队列里的统计,且能在有流量时安全停下") { +TEST_CASE("shutdown keeps queued statistics and stops safely under traffic") { MockDataChannel channel; LoopbackLink link(LoopbackConfig{.inbound_capacity = 8192, .sent_capacity = 8192, .max_frames_per_batch = 64}); Bridge bridge(channel, link, TestConfig()); REQUIRE(bridge.Start().has_value()); - // Shutting down while traffic flows -- this is the scenario that most easily exposes teardown-order problems. + // Shutting down while traffic flows: this is the scenario that most easily exposes teardown-order + // problems. std::atomic keep_going{true}; std::thread producer([&] { while (keep_going.load(std::memory_order_acquire)) { diff --git a/tests/test_core_peer_address.cc b/tests/test_core_peer_address.cc new file mode 100644 index 0000000..cd23c00 --- /dev/null +++ b/tests/test_core_peer_address.cc @@ -0,0 +1,125 @@ +// Passive discovery of the device's own IPv4 address (peer_address.h). +// +// The rules decide which frames prove "the device owns this address". A false positive would +// suggest a wrong subnet to the user (e.g. taking a remote web server's address that a phone +// forwarded); these cases pin that down. +#include "tetherkitnext/core/peer_address.h" + +#include + +#include +#include +#include +#include +#include + +namespace { + +using tetherkitnext::core::OnLinkSenderIpv4; +using tetherkitnext::core::PeerAddressObserver; + +constexpr std::uint32_t Ip(std::uint8_t a, std::uint8_t b, std::uint8_t c, std::uint8_t d) { + return (std::uint32_t{a} << 24) | (std::uint32_t{b} << 16) | (std::uint32_t{c} << 8) | d; +} + +void Put16(std::vector& frame, std::size_t offset, std::uint16_t value) { + frame[offset] = static_cast(value >> 8); + frame[offset + 1] = static_cast(value & 0xFF); +} + +void Put32(std::vector& frame, std::size_t offset, std::uint32_t value) { + for (std::size_t i = 0; i < 4; ++i) { + frame[offset + i] = static_cast((value >> (24 - 8 * i)) & 0xFF); + } +} + +std::vector ArpFrame(std::uint32_t sender, std::uint32_t target) { + std::vector frame(14 + 28); + Put16(frame, 12, 0x0806); + Put16(frame, 14, 1); // htype Ethernet + Put16(frame, 16, 0x0800); // ptype IPv4 + frame[18] = std::byte{6}; + frame[19] = std::byte{4}; + Put16(frame, 20, 1); // request + Put32(frame, 28, sender); + Put32(frame, 38, target); + return frame; +} + +std::vector Ipv4Frame(std::uint32_t source, std::uint32_t destination) { + std::vector frame(14 + 20); + Put16(frame, 12, 0x0800); + frame[14] = std::byte{0x45}; + Put32(frame, 26, source); + Put32(frame, 30, destination); + return frame; +} + +} // namespace + +TEST_SUITE("core.peer_address") { + +TEST_CASE("ARP sender address is the device's own address") { + CHECK(OnLinkSenderIpv4(ArpFrame(Ip(192, 168, 42, 2), Ip(192, 168, 42, 1))) == + Ip(192, 168, 42, 2)); +} + +TEST_CASE("ARP probes (sender 0.0.0.0) are ignored") { + CHECK(OnLinkSenderIpv4(ArpFrame(0, Ip(192, 168, 42, 2))) == 0); +} + +TEST_CASE("link-local addresses count: devices without DHCP often use 169.254/16") { + CHECK(OnLinkSenderIpv4(ArpFrame(Ip(169, 254, 10, 20), Ip(169, 254, 1, 1))) == + Ip(169, 254, 10, 20)); +} + +TEST_CASE("IPv4 to link-scoped destinations proves the source is on the link") { + // mDNS (224.0.0.251) and limited broadcast (DHCP server replies). + CHECK(OnLinkSenderIpv4(Ipv4Frame(Ip(10, 0, 0, 5), Ip(224, 0, 0, 251))) == Ip(10, 0, 0, 5)); + CHECK(OnLinkSenderIpv4(Ipv4Frame(Ip(10, 0, 0, 5), Ip(255, 255, 255, 255))) == Ip(10, 0, 0, 5)); +} + +TEST_CASE("routed unicast and global multicast do not count") { + // A phone forwards internet traffic: the source is a remote server. + CHECK(OnLinkSenderIpv4(Ipv4Frame(Ip(142, 250, 1, 1), Ip(172, 19, 0, 2))) == 0); + // Multicast beyond 224.0.0.0/24 can be routed. + CHECK(OnLinkSenderIpv4(Ipv4Frame(Ip(142, 250, 1, 1), Ip(239, 255, 255, 250))) == 0); +} + +TEST_CASE("implausible sources are rejected") { + CHECK(OnLinkSenderIpv4(Ipv4Frame(0, Ip(255, 255, 255, 255))) == 0); // DHCP DISCOVER + CHECK(OnLinkSenderIpv4(Ipv4Frame(Ip(127, 0, 0, 1), Ip(224, 0, 0, 1))) == 0); + CHECK(OnLinkSenderIpv4(Ipv4Frame(Ip(224, 0, 0, 5), Ip(224, 0, 0, 1))) == 0); +} + +TEST_CASE("truncated and foreign frames are ignored") { + std::vector arp = ArpFrame(Ip(192, 168, 1, 2), Ip(192, 168, 1, 1)); + arp.resize(30); + CHECK(OnLinkSenderIpv4(arp) == 0); + + std::vector ipv6(60); + Put16(ipv6, 12, 0x86DD); + CHECK(OnLinkSenderIpv4(ipv6) == 0); + + CHECK(OnLinkSenderIpv4({}) == 0); + + std::vector not_v4 = Ipv4Frame(Ip(10, 0, 0, 5), Ip(224, 0, 0, 251)); + not_v4[14] = std::byte{0x65}; + CHECK(OnLinkSenderIpv4(not_v4) == 0); +} + +TEST_CASE("observer keeps the latest address and ignores noise") { + PeerAddressObserver observer; + CHECK(observer.Latest() == 0); + observer.Observe(Ipv4Frame(Ip(142, 250, 1, 1), Ip(172, 19, 0, 2))); + CHECK(observer.Latest() == 0); + observer.Observe(ArpFrame(Ip(192, 168, 7, 2), Ip(192, 168, 7, 1))); + CHECK(observer.Latest() == Ip(192, 168, 7, 2)); + observer.Observe(ArpFrame(0, Ip(192, 168, 7, 1))); + CHECK(observer.Latest() == Ip(192, 168, 7, 2)); + // The device changed address (new DHCP lease, reconfiguration). + observer.Observe(Ipv4Frame(Ip(192, 168, 8, 2), Ip(224, 0, 0, 251))); + CHECK(observer.Latest() == Ip(192, 168, 8, 2)); +} + +} // TEST_SUITE("core.peer_address") diff --git a/tests/test_main.cc b/tests/test_main.cc index 2ceda1e..166f140 100644 --- a/tests/test_main.cc +++ b/tests/test_main.cc @@ -1,6 +1,6 @@ // doctest's main() implementation occupies a translation unit of its own. // -// This way modifying any test file does not require recompiling the implementation part of doctest's 7000-line header, -// noticeably shortening incremental build time. +// This way modifying any test file does not require recompiling the implementation part of +// doctest's 7000-line header, noticeably shortening incremental build time. #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include diff --git a/tests/test_net_link.cc b/tests/test_net_link.cc index 3466a8a..f1baaf7 100644 --- a/tests/test_net_link.cc +++ b/tests/test_net_link.cc @@ -1,9 +1,11 @@ // Link-layer tests. // // Divided into two parts: -// * loopback backend -- runs in any environment, is the infrastructure of the bridge layer tests, and must itself be reliable; -// * feth + BPF -- needs root, and is **skipped rather than failed** in non-root environments. -// Enabled explicitly with TETHERKITNEXT_ROOT_TESTS=1 (to avoid accidentally running real NIC operations on CI). +// * loopback backend: runs in any environment, is the infrastructure of the bridge layer tests, +// and must itself be reliable; +// * feth + BPF: needs root, and is **skipped rather than failed** in non-root environments. +// Enabled explicitly with TETHERKITNEXT_ROOT_TESTS=1 (to avoid accidentally running real NIC +// operations on CI). #include #include #include @@ -36,7 +38,8 @@ using namespace tetherkitnext::net; // NOLINT(google-build-using-namespace) namespace { -/// Builds a legal Ethernet frame: destination MAC, source MAC, EtherType, then a verifiable payload. +/// Builds a legal Ethernet frame: destination MAC, source MAC, EtherType, then a verifiable +/// payload. std::vector MakeEthernetFrame(std::uint32_t total_length, std::uint8_t tag) { std::vector frame(total_length); // Destination MAC: broadcast; source MAC: 02:00:00:00:00:tag (locally administered unicast). @@ -55,8 +58,8 @@ std::vector MakeEthernetFrame(std::uint32_t total_length, std::uint8_ /// Whether tests that need root are enabled. /// -/// getenv is not safe under multi-threading, but here it is a one-time read at the start of a test case, with no -/// concurrent setenv in the process, so the check is exempted. +/// getenv is not safe under multi-threading, but here it is a one-time read at the start of a test +/// case, with no concurrent setenv in the process, so the check is exempted. // NOLINTNEXTLINE(concurrency-mt-unsafe) bool RootTestsEnabled() { const char* flag = std::getenv("TETHERKITNEXT_ROOT_TESTS"); @@ -65,41 +68,47 @@ bool RootTestsEnabled() { /// Renders the error of a Result/Status into a string; returns an empty string on success. /// -/// Writing `r ? "" : r.error().ToString()` directly inside REQUIRE_MESSAGE does not compile -- -/// doctest's MessageBuilder swallows the ternary expression whole into the stream and then tries to convert it to bool. +/// Writing `r ? "" : r.error().ToString()` directly inside REQUIRE_MESSAGE does not compile; +/// doctest's MessageBuilder swallows the ternary expression whole into the stream and then tries to +/// convert it to bool. template std::string Why(const T& result) { return result.has_value() ? std::string{} : result.error().ToString(); } -/// Prints the skip reason, making "skipped" visible in the test output rather than passing silently. +/// Prints the skip reason, making "skipped" visible in the test output rather than passing +/// silently. /// /// First assemble a std::string with std::format and then hand it to MESSAGE: doctest's -/// MessageBuilder stringifies a `const char*` as a pointer, and streaming it in directly would print an address. +/// MessageBuilder stringifies a `const char*` as a pointer, and streaming it in directly would +/// print an address. void ReportSkip(std::string_view what) { const std::string message = - std::format("跳过 {}:需要 root 且需设置 TETHERKITNEXT_ROOT_TESTS=1(当前 euid={})", what, - IsRunningAsRoot() ? "0" : "非 0"); + std::format("skipping {}: needs root and TETHERKITNEXT_ROOT_TESTS=1 (current euid={})", what, + IsRunningAsRoot() ? "0" : "non-zero"); MESSAGE(message); } // --------------------------------------------------------------------------- // Small tools for the ARP round-trip loop // -// What this loop is to prove is far stronger than "cannot read back the frames we wrote ourselves": BPF's write() really delivered the frame -// into the **IP stack of the peer feth**, and did not merely write it into a black hole. The criterion is that the peer IP stack **actively -// answers** -- if it did not understand this frame it would not reply with an ARP reply. +// What this loop is to prove is far stronger than "cannot read back the frames we wrote ourselves": +// BPF's write() really delivered the frame into the **IP stack of the peer feth**, and did not +// merely write it into a black hole. The criterion is that the peer IP stack **actively answers**; +// if it did not understand this frame it would not reply with an ARP reply. // --------------------------------------------------------------------------- -/// Addresses used by the loop. 10.99.99/24 is chosen because it almost never conflicts with a real network. +/// Addresses used by the loop. 10.99.99/24 is chosen because it almost never conflicts with a real +/// network. constexpr const char* kArpSystemIp = "10.99.99.1"; ///< Configured on the system-side feth. constexpr const char* kArpProbeIp = "10.99.99.2"; ///< The asker we impersonate. /// Configures an IPv4 address on an interface. /// -/// SIOCAIFADDR is used directly here rather than going through capi's `ipconfig` path: the test wants an address that -/// takes effect immediately and disappears along with the feth when the process exits, needing no IPConfiguration -/// lease management, and a test should not spawn subprocesses either. +/// SIOCAIFADDR is used directly here rather than going through capi's `ipconfig` path: the test +/// wants an address that takes effect immediately and disappears along with the feth when the +/// process exits, needing no IPConfiguration lease management, and a test should not spawn +/// subprocesses either. [[nodiscard]] std::string AssignIpv4(std::string_view interface_name, const char* address, const char* netmask) { const int fd = ::socket(AF_INET, SOCK_DGRAM, 0); @@ -124,7 +133,7 @@ constexpr const char* kArpProbeIp = "10.99.99.2"; ///< The asker we impersonat if (!fill(request.ifra_addr, address) || !fill(request.ifra_mask, netmask)) { ::close(fd); - return "inet_pton 失败"; + return "inet_pton failed"; } const int result = ::ioctl(fd, SIOCAIFADDR, &request); @@ -197,9 +206,9 @@ std::vector MakeArpRequest(const MacAddress& sender_mac, const char* TEST_SUITE("net.abi") { -TEST_CASE("私有 ABI 的结构体大小与 ioctl 编号与实测值一致") { - // These are all static_asserts, and compiling means they hold; here they are confirmed once more at runtime, - // making the ABI assumptions **visible** in the test report. +TEST_CASE("private ABI struct sizes and ioctl numbers match the measured values") { + // These are all static_asserts, and compiling means they hold; here they are confirmed once more + // at runtime, making the ABI assumptions **visible** in the test report. CHECK(sizeof(IfDrv) == 40); CHECK(sizeof(FethRequest) == 160); CHECK(offsetof(FethRequest, u) == 32); @@ -211,7 +220,7 @@ TEST_CASE("私有 ABI 的结构体大小与 ioctl 编号与实测值一致") { CHECK(static_cast(FethGetCommand::kGetPeer) == 1); } -TEST_CASE("BPF 记录头的大小陷阱:sizeof 是 20 但 bh_hdrlen 是 18") { +TEST_CASE("BPF record header size trap: sizeof is 20 but bh_hdrlen is 18") { // This is where BPF parsing most easily goes wrong; pin it down with a test. CHECK(sizeof(struct bpf_hdr) == 20); CHECK(sizeof(struct BPF_TIMEVAL) == 8); @@ -221,12 +230,13 @@ TEST_CASE("BPF 记录头的大小陷阱:sizeof 是 20 但 bh_hdrlen 是 18") { CHECK(BPF_WORDALIGN(14 + kBpfHeaderMinBytes) - 14 == kBpfHeaderMinBytes); } -TEST_CASE("feth 创建期 sysctl 清单非空且都有说明") { +TEST_CASE("the feth creation-time sysctl list is non-empty and documented") { CHECK(std::size(kRequiredFethSysctls) > 0); for (const RequiredFethSysctl& entry : kRequiredFethSysctls) { CHECK(entry.name != nullptr); - // why stores a message identifier; both languages must really have a translation (a missing translation would render as an empty string, - // so that after "Reason:" in the sysctl error there would be nothing at all). + // why stores a message identifier; both languages must really have a translation (a missing + // translation would render as an empty string, so that after "Reason:" in the sysctl error + // there would be nothing at all). for (const auto language : {tetherkitnext::Language::kChinese, tetherkitnext::Language::kEnglish}) { const std::string_view why = tetherkitnext::TextIn(language, entry.why); // The explanation must be plain language, not just a single word. @@ -239,14 +249,14 @@ TEST_CASE("feth 创建期 sysctl 清单非空且都有说明") { TEST_SUITE("net.loopback") { -TEST_CASE("空队列读取返回空批次") { +TEST_CASE("reading an empty queue returns an empty batch") { LoopbackLink link; const auto batch = link.ReadFrames(); REQUIRE(batch.has_value()); CHECK(batch->frames.empty()); } -TEST_CASE("注入的帧能按 FIFO 顺序读出") { +TEST_CASE("injected frames are read in FIFO order") { LoopbackLink link; for (std::uint8_t i = 0; i < 5; ++i) { REQUIRE(link.PushInbound(MakeEthernetFrame(100, i))); @@ -261,7 +271,7 @@ TEST_CASE("注入的帧能按 FIFO 顺序读出") { } } -TEST_CASE("单批读取受 max_frames_per_batch 限制,剩余留到下一批") { +TEST_CASE("a batch read is capped at max_frames_per_batch; the rest waits for the next batch") { LoopbackLink link(LoopbackConfig{.max_frames_per_batch = 3}); for (std::uint8_t i = 0; i < 7; ++i) { REQUIRE(link.PushInbound(MakeEthernetFrame(64, i))); @@ -279,7 +289,7 @@ TEST_CASE("单批读取受 max_frames_per_batch 限制,剩余留到下一批") CHECK(third->frames.size() == 1); } -TEST_CASE("注入队列满时丢弃并计数") { +TEST_CASE("a full injection queue drops and counts") { LoopbackLink link(LoopbackConfig{.inbound_capacity = 2}); CHECK(link.PushInbound(MakeEthernetFrame(64, 1))); CHECK(link.PushInbound(MakeEthernetFrame(64, 2))); @@ -287,13 +297,13 @@ TEST_CASE("注入队列满时丢弃并计数") { CHECK(link.InboundDrops() == 1); } -TEST_CASE("超长帧被拒绝注入") { +TEST_CASE("oversized frames cannot be injected") { LoopbackLink link(LoopbackConfig{.max_frame_bytes = 128}); CHECK_FALSE(link.PushInbound(MakeEthernetFrame(129, 1))); CHECK(link.InboundDrops() == 1); } -TEST_CASE("写出的帧可被取回,内容完整") { +TEST_CASE("written frames can be read back intact") { LoopbackLink link; const auto frame_a = MakeEthernetFrame(1514, 0xA1); const auto frame_b = MakeEthernetFrame(64, 0xB2); @@ -319,7 +329,7 @@ TEST_CASE("写出的帧可被取回,内容完整") { CHECK(link.DrainSent().empty()); } -TEST_CASE("写出时跳过过短与过长的帧") { +TEST_CASE("writes skip frames that are too short or too long") { LoopbackLink link(LoopbackConfig{.max_frame_bytes = 200}); const auto too_short = MakeEthernetFrame(14, 1); std::vector shorter(13); @@ -342,7 +352,7 @@ TEST_CASE("写出时跳过过短与过长的帧") { CHECK(minimal_result->frames_written == 1); } -TEST_CASE("写出队列满时停止写入,如实反映已写数") { +TEST_CASE("writing stops when the output queue is full and reports the true count") { LoopbackLink link(LoopbackConfig{.sent_capacity = 2}); const auto frame = MakeEthernetFrame(64, 1); std::vector batch(5, FrameView{.data = frame.data(), .length = 64}); @@ -351,7 +361,7 @@ TEST_CASE("写出队列满时停止写入,如实反映已写数") { CHECK(result->frames_written == 2); } -TEST_CASE("Interrupt 后读取立即返回空批次") { +TEST_CASE("after Interrupt, reads return an empty batch immediately") { LoopbackLink link; REQUIRE(link.PushInbound(MakeEthernetFrame(64, 1))); link.Interrupt(); @@ -361,7 +371,7 @@ TEST_CASE("Interrupt 后读取立即返回空批次") { CHECK(batch->frames.empty()); } -TEST_CASE("可以注入写失败以测试错误传播") { +TEST_CASE("write failures can be injected to test error propagation") { LoopbackLink link; link.FailWritesAfter(1); // 1st succeeds, fails from the 2nd on const auto frame = MakeEthernetFrame(64, 1); @@ -371,7 +381,7 @@ TEST_CASE("可以注入写失败以测试错误传播") { CHECK_FALSE(link.WriteFrames(batch).has_value()); } -TEST_CASE("空批次写入是合法的空操作") { +TEST_CASE("writing an empty batch is a valid no-op") { LoopbackLink link; const auto result = link.WriteFrames({}); REQUIRE(result.has_value()); @@ -382,7 +392,7 @@ TEST_CASE("空批次写入是合法的空操作") { TEST_SUITE("net.feth" * doctest::skip(false)) { -TEST_CASE("查询 feth MTU 上限(只读 sysctl,无需 root)") { +TEST_CASE("query the feth MTU limit (read-only sysctl, no root)") { const auto max_mtu = QueryFethMaxMtu(); REQUIRE(max_mtu.has_value()); // The kernel guarantees >= ETHERMTU(1500). @@ -390,19 +400,20 @@ TEST_CASE("查询 feth MTU 上限(只读 sysctl,无需 root)") { MESSAGE(std::format("net.link.fake.max_mtu = {}", *max_mtu)); } -TEST_CASE("校验 feth 创建期 sysctl(只读,无需 root)") { +TEST_CASE("check the feth creation-time sysctls (read-only, no root)") { const auto status = VerifyFethSysctls(); if (!status) { - // Not a test failure -- this machine's sysctl has been modified. Report it so that people know. - MESSAGE(std::format("本机 feth sysctl 不满足要求:{}", status.error().ToString())); + // Not a test failure: the host's sysctl has been modified. Report it so that people know. + MESSAGE(std::format("this Mac's feth sysctls do not meet the requirements: {}", + status.error().ToString())); } // Passing as long as it can be read; the specific value depends on the machine configuration. CHECK(true); } -TEST_CASE("非 root 环境下创建 feth 必须给出明确的权限错误") { +TEST_CASE("creating feth without root gives a clear permission error") { if (IsRunningAsRoot()) { - MESSAGE("当前以 root 运行,跳过权限错误检查"); + MESSAGE("running as root; skipping the permission-error check"); return; } const auto pair = FethPair::Create(1500); @@ -412,15 +423,15 @@ TEST_CASE("非 root 环境下创建 feth 必须给出明确的权限错误") { CHECK((message.find("root") != std::string::npos || message.find("sudo") != std::string::npos)); } -TEST_CASE("MAC 格式化") { +TEST_CASE("MAC formatting") { const MacAddress mac{0x66, 0x65, 0x74, 0x68, 0x00, 0x00}; // The kernel assigned exactly this address to feth0 ('f','e','t','h', unit>>8, unit&0xff). CHECK(std::string{FormatMac(mac).data()} == "66:65:74:68:00:00"); } -TEST_CASE("完整生命周期:创建、配对、设 MTU/MAC、UP、销毁") { +TEST_CASE("full lifecycle: create, pair, set MTU/MAC, up, destroy") { if (!RootTestsEnabled()) { - ReportSkip("feth 完整生命周期测试"); + ReportSkip("feth full-lifecycle test"); return; } @@ -430,7 +441,7 @@ TEST_CASE("完整生命周期:创建、配对、设 MTU/MAC、UP、销毁") { const std::string system_name{pair->SystemSide().Name()}; const std::string driver_name{pair->DriverSide().Name()}; - MESSAGE(std::format("创建了 {} ←→ {}", system_name, driver_name)); + MESSAGE(std::format("created {} <-> {}", system_name, driver_name)); // The pairing relationship holds in both directions. const auto driver_peer = pair->DriverSide().QueryPeer(); @@ -444,7 +455,8 @@ TEST_CASE("完整生命周期:创建、配对、设 MTU/MAC、UP、销毁") { CHECK(pair->SystemSide().QueryMtu().value_or(0) == 1500); CHECK(pair->DriverSide().QueryMtu().value_or(0) == 1500); - // The system-side MAC is the one we set, and the driver side keeps the kernel-assigned one (the two must differ). + // The system-side MAC is the one we set, and the driver side keeps the kernel-assigned one (the + // two must differ). const auto system_mac = pair->SystemSide().QueryMacAddress(); REQUIRE(system_mac.has_value()); CHECK(*system_mac == device_mac); @@ -452,14 +464,14 @@ TEST_CASE("完整生命周期:创建、配对、设 MTU/MAC、UP、销毁") { REQUIRE(driver_mac.has_value()); CHECK(*driver_mac != device_mac); - // Both sides are UP -- bpfwrite strictly requires the driver side to be UP. + // Both sides are UP: bpfwrite strictly requires the driver side to be UP. CHECK(pair->SystemSide().IsUp().value_or(false)); CHECK(pair->DriverSide().IsUp().value_or(false)); } -TEST_CASE("BPF 打开配置全流程,并验证方向语义与回环抑制") { +TEST_CASE("full BPF open/configure flow, checking direction semantics and loop suppression") { if (!RootTestsEnabled()) { - ReportSkip("BPF 收发测试"); + ReportSkip("BPF send/receive test"); return; } @@ -470,19 +482,20 @@ TEST_CASE("BPF 打开配置全流程,并验证方向语义与回环抑制") { auto link = BpfLink::Open(pair->DriverSide().Name(), BpfConfig{}); REQUIRE_MESSAGE(link.has_value(), Why(link)); - MESSAGE(std::format("BPF 设备 {},内核缓冲 {} 字节,批量写 {}", (*link)->DevicePath(), - (*link)->KernelBufferBytes(), - (*link)->SupportsBatchWrite() ? "可用" : "不可用")); + MESSAGE(std::format("BPF device {}, kernel buffer {} bytes, batch write {}", + (*link)->DevicePath(), (*link)->KernelBufferBytes(), + (*link)->SupportsBatchWrite() ? "available" : "unavailable")); - // The buffer actually in effect in the kernel should not be 0, and should not exceed the 32 MiB upper limit. + // The buffer actually in effect in the kernel should not be 0, and should not exceed the 32 MiB + // upper limit. CHECK((*link)->KernelBufferBytes() > 0); CHECK((*link)->KernelBufferBytes() <= 32U * 1024 * 1024); const auto stats = (*link)->QueryKernelStats(); REQUIRE(stats.has_value()); - // Write one frame in -- it should enter the system side's input and **should not** be read back by ourselves - // (BIOCSSEESENT=0 filters out the output direction). + // Write one frame in: it should enter the system side's input and **should not** be read back by + // ourselves (BIOCSSEESENT=0 filters out the output direction). const auto frame = MakeEthernetFrame(200, 0x5A); const std::array batch{FrameView{.data = frame.data(), .length = 200}}; const auto written = (*link)->WriteFrames(batch); @@ -493,15 +506,16 @@ TEST_CASE("BPF 打开配置全流程,并验证方向语义与回环抑制") { const auto batch_read = (*link)->ReadFrames(); REQUIRE(batch_read.has_value()); for (const FrameView& view : batch_read->frames) { - // The source MAC byte 12 of the frame we wrote is 0x5A; reading it means loopback suppression has failed. + // The source MAC byte 12 of the frame we wrote is 0x5A; reading it means loopback suppression + // has failed. const bool is_our_frame = view.length == 200 && view.data[11] == std::byte{0x5A}; CHECK_FALSE(is_our_frame); } } -TEST_CASE("ARP 往返闭环:BPF 写入的帧确实进了对侧 feth 的 IP 栈") { +TEST_CASE("ARP round trip: frames written via BPF really reach the peer feth's IP stack") { if (!RootTestsEnabled()) { - ReportSkip("ARP 往返闭环测试"); + ReportSkip("ARP round-trip test"); return; } @@ -516,7 +530,7 @@ TEST_CASE("ARP 往返闭环:BPF 写入的帧确实进了对侧 feth 的 IP 栈 const auto system_mac = pair->SystemSide().QueryMacAddress(); REQUIRE_MESSAGE(system_mac.has_value(), Why(system_mac)); - // BPF attaches to the driver side -- this side plays the "device". + // BPF attaches to the driver side: this side plays the "device". auto link = BpfLink::Open(pair->DriverSide().Name(), BpfConfig{}); REQUIRE_MESSAGE(link.has_value(), Why(link)); @@ -529,8 +543,9 @@ TEST_CASE("ARP 往返闭环:BPF 写入的帧确实进了对侧 feth 的 IP 栈 REQUIRE_MESSAGE(written.has_value(), Why(written)); REQUIRE(written->frames_written == 1); - // Read several rounds before judging failure: ReadFrames waits only one read timeout per round, and although the IP stack's reply is fast, - // there is no guarantee that it falls in the first round. + // Read several rounds before judging failure: ReadFrames waits only one read timeout per round, + // and although the IP stack's reply is fast, there is no guarantee that it falls in the first + // round. bool saw_reply = false; MacAddress reply_mac{}; for (int attempt = 0; attempt < 20 && !saw_reply; ++attempt) { @@ -547,12 +562,16 @@ TEST_CASE("ARP 往返闭环:BPF 写入的帧确实进了对侧 feth 的 IP 栈 } } - // This one assertion is the core premise of the whole scheme: the peer IP stack **received and processed** the frame we wrote in. - CHECK_MESSAGE(saw_reply, "没有收到系统侧 feth 的 ARP reply —— BPF write 没能送达对侧 IP 栈"); + // This one assertion is the core premise of the whole scheme: the peer IP stack **received and + // processed** the frame we wrote in. + CHECK_MESSAGE( + saw_reply, + "no ARP reply from the system-side feth: the BPF write did not reach the peer IP stack"); if (saw_reply) { - // The responder must be exactly the system-side feth, and not a frame from some other interface leaking in. + // The responder must be exactly the system-side feth, and not a frame from some other interface + // leaking in. CHECK(reply_mac == *system_mac); - MESSAGE(std::format("{} 宣称拥有 {},MAC {}", pair->SystemSide().Name(), kArpSystemIp, + MESSAGE(std::format("{} claims {}, MAC {}", pair->SystemSide().Name(), kArpSystemIp, FormatMac(reply_mac).data())); } } diff --git a/tests/test_rndis_messages.cc b/tests/test_rndis_messages.cc index 4de2e80..7c2d23e 100644 --- a/tests/test_rndis_messages.cc +++ b/tests/test_rndis_messages.cc @@ -1,8 +1,9 @@ // Unit tests of RNDIS control message encoding/decoding. // // Key coverage: -// 1. The base point of offset fields is "message start + 8" -- this is RNDIS's number one trap; -// 2. RESET_MSG / RESET_CMPLT **have no** RequestId, and their field offsets differ from other messages; +// 1. The base point of offset fields is "message start + 8"; this is RNDIS's number one trap; +// 2. RESET_MSG / RESET_CMPLT **have no** RequestId, and their field offsets differ from other +// messages; // 3. The InformationBufferLength rules for variable-length / fixed-length OIDs are opposite; // 4. The base point of INDICATE_STATUS's StatusBufferOffset is contradictory in the spec; // 5. Normalization of device quirks (MaxPacketsPerMessage=0, alignment factor out of range, @@ -63,7 +64,7 @@ TEST_SUITE("rndis.messages") { // Constant self-checks // --------------------------------------------------------------------------- -TEST_CASE("协议常量与规范一致") { +TEST_CASE("protocol constants match the spec") { CHECK(ToRaw(MessageType::kPacket) == 0x0000'0001U); CHECK(ToRaw(MessageType::kInitialize) == 0x0000'0002U); CHECK(ToRaw(MessageType::kInitializeComplete) == 0x8000'0002U); @@ -90,7 +91,7 @@ TEST_CASE("协议常量与规范一致") { CHECK(kHardHeaderBytes == 58); } -TEST_CASE("偏移基准点常量:DataOffset 内联值必须是 36 而不是 44") { +TEST_CASE("offset base: the inline DataOffset must be 36, not 44") { // This is RNDIS's number one trap: the base point of offset fields is message start +8. CHECK(kPacketInlineDataOffset == 36); CHECK(kPacketMsgHeaderBytes == 44); @@ -99,26 +100,27 @@ TEST_CASE("偏移基准点常量:DataOffset 内联值必须是 36 而不是 44 CHECK(kQueryCmpltInlineInfoOffset == 16); } -TEST_CASE("MaxTransferSize 推导与 Linux 一致") { +TEST_CASE("MaxTransferSize is derived as on Linux") { CHECK(MaxTransferSizeFor(1500, 512) == 2048); // high speed CHECK(MaxTransferSizeFor(1500, 64) == 1600); // full speed CHECK(HardMtuFor(1500) == 1558); } -TEST_CASE("状态码与 OID 的名字可查") { +TEST_CASE("status codes and OIDs have names") { CHECK(StatusName(0xC000'00BBU) == "RNDIS_STATUS_NOT_SUPPORTED"); CHECK(StatusName(0x4001'000BU) == "RNDIS_STATUS_MEDIA_CONNECT"); CHECK(StatusName(0xDEAD'BEEFU).empty()); CHECK(OidName(0x0001'010EU) == "OID_GEN_CURRENT_PACKET_FILTER"); CHECK(OidName(0xDEAD'BEEFU).empty()); CHECK(MessageTypeName(0x8000'0002U) == "REMOTE_NDIS_INITIALIZE_CMPLT"); - // The CONDIS message family must be recognizable (even though unsupported), rather than reported as "unknown". + // The CONDIS message family must be recognizable (even though unsupported), rather than reported + // as "unknown". CHECK(MessageTypeName(0x0000'8001U) == "RNDIS_MSG_MP_CREATE_VC"); CHECK(IsCondis(0x0000'8001U)); CHECK_FALSE(IsCondis(ToRaw(MessageType::kPacket))); } -TEST_CASE("变长与定长 OID 的区分") { +TEST_CASE("variable- vs fixed-length OIDs") { CHECK(IsVariableLengthOid(Oid::kGenSupportedList)); CHECK(IsVariableLengthOid(Oid::kGenVendorDescription)); CHECK_FALSE(IsVariableLengthOid(Oid::kEthernetPermanentAddress)); @@ -129,7 +131,7 @@ TEST_CASE("变长与定长 OID 的区分") { // INITIALIZE // --------------------------------------------------------------------------- -TEST_CASE("编码 INITIALIZE_MSG") { +TEST_CASE("encode INITIALIZE_MSG") { std::array buffer{}; const auto written = Encode( InitializeRequest{.request_id = 7, .max_transfer_size = 2048}, buffer); @@ -144,12 +146,12 @@ TEST_CASE("编码 INITIALIZE_MSG") { CHECK(LoadLe32(buffer.data() + kInitializeMaxTransferSizeOffset) == 2048); } -TEST_CASE("编码 INITIALIZE_MSG 缓冲不足时报错") { +TEST_CASE("encoding INITIALIZE_MSG into a short buffer fails") { std::array too_small{}; CHECK_FALSE(Encode(InitializeRequest{}, too_small).has_value()); } -TEST_CASE("解码 INITIALIZE_CMPLT") { +TEST_CASE("decode INITIALIZE_CMPLT") { const auto buffer = MakeInitializeComplete(); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); @@ -160,7 +162,7 @@ TEST_CASE("解码 INITIALIZE_CMPLT") { CHECK(complete->max_packets_per_message == 1); } -TEST_CASE("解码 INITIALIZE_CMPLT:设备返回失败状态") { +TEST_CASE("decode INITIALIZE_CMPLT: device returns a failure status") { const auto buffer = MakeInitializeComplete(2048, 1, 0, ToRaw(StatusCode::kFailure)); const auto complete = DecodeInitializeComplete(buffer); REQUIRE_FALSE(complete.has_value()); @@ -169,29 +171,29 @@ TEST_CASE("解码 INITIALIZE_CMPLT:设备返回失败状态") { CHECK(complete.error().ToString().find("RNDIS_STATUS_FAILURE") != std::string::npos); } -TEST_CASE("解码 INITIALIZE_CMPLT:畸形输入一律报错不崩溃") { - SUBCASE("缓冲区太短") { +TEST_CASE("decode INITIALIZE_CMPLT: malformed input errors without crashing") { + SUBCASE("buffer too short") { std::array tiny{}; StoreLe32(tiny.data(), ToRaw(MessageType::kInitializeComplete)); StoreLe32(tiny.data() + 4, kInitializeCmpltBytes); CHECK_FALSE(DecodeInitializeComplete(tiny).has_value()); } - SUBCASE("消息类型不对") { + SUBCASE("wrong message type") { auto buffer = MakeInitializeComplete(); StoreLe32(buffer.data() + kMessageTypeOffset, ToRaw(MessageType::kQueryComplete)); CHECK_FALSE(DecodeInitializeComplete(buffer).has_value()); } - SUBCASE("MessageLength 超出缓冲") { + SUBCASE("MessageLength beyond the buffer") { auto buffer = MakeInitializeComplete(); StoreLe32(buffer.data() + kMessageLengthOffset, 0xFFFF'FFFFU); CHECK_FALSE(DecodeInitializeComplete(buffer).has_value()); } - SUBCASE("MessageLength 小于最小长度") { + SUBCASE("MessageLength below the minimum") { auto buffer = MakeInitializeComplete(); StoreLe32(buffer.data() + kMessageLengthOffset, 12); CHECK_FALSE(DecodeInitializeComplete(buffer).has_value()); } - SUBCASE("空缓冲") { + SUBCASE("empty buffer") { CHECK_FALSE(DecodeInitializeComplete({}).has_value()); } } @@ -200,7 +202,7 @@ TEST_CASE("解码 INITIALIZE_CMPLT:畸形输入一律报错不崩溃") { // Negotiation and normalization of device quirks // --------------------------------------------------------------------------- -TEST_CASE("协商:Android 主线 gadget 的典型参数") { +TEST_CASE("negotiation: typical mainline Android gadget parameters") { const auto buffer = MakeInitializeComplete(2048, 1, 0); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); @@ -213,7 +215,7 @@ TEST_CASE("协商:Android 主线 gadget 的典型参数") { CHECK(params->tx_alignment_bytes == 1); // factor 0 -> alignment of 1 byte } -TEST_CASE("协商 quirk:MaxPacketsPerMessage 为 0 时按 1 处理") { +TEST_CASE("negotiation quirk: MaxPacketsPerMessage 0 is treated as 1") { const auto buffer = MakeInitializeComplete(2048, 0, 0); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); @@ -222,7 +224,7 @@ TEST_CASE("协商 quirk:MaxPacketsPerMessage 为 0 时按 1 处理") { CHECK(params->max_packets_per_message == 1); } -TEST_CASE("协商 quirk:PacketAlignmentFactor 越界时钳到 7") { +TEST_CASE("negotiation quirk: an out-of-range PacketAlignmentFactor is clamped to 7") { const auto buffer = MakeInitializeComplete(2048, 1, 31); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); @@ -232,7 +234,7 @@ TEST_CASE("协商 quirk:PacketAlignmentFactor 越界时钳到 7") { CHECK(params->tx_alignment_bytes == 128); } -TEST_CASE("协商 quirk:高通聚合补丁报 MaxPacketsPerMessage=3") { +TEST_CASE("negotiation quirk: the Qualcomm aggregation patch reports MaxPacketsPerMessage=3") { const auto buffer = MakeInitializeComplete(3 * 1580, 3, 2); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); @@ -242,7 +244,8 @@ TEST_CASE("协商 quirk:高通聚合补丁报 MaxPacketsPerMessage=3") { CHECK(params->tx_alignment_bytes == 4); // 1 << 2 } -TEST_CASE("协商 quirk:设备 MaxTransferSize 小于满帧时下调 MTU") { +TEST_CASE( + "negotiation quirk: the MTU drops when the device's MaxTransferSize cannot hold a full frame") { // Measured case: the HTC Diamond reports 1536, less than hard_mtu(1558). const auto buffer = MakeInitializeComplete(1536, 1, 0); const auto complete = DecodeInitializeComplete(buffer); @@ -252,7 +255,7 @@ TEST_CASE("协商 quirk:设备 MaxTransferSize 小于满帧时下调 MTU") { CHECK(params->mtu == 1536 - kHardHeaderBytes); // 1478 } -TEST_CASE("协商 quirk:WinCE 报 16KB 巨帧时钳到 host 上限") { +TEST_CASE("negotiation quirk: WinCE's 16 KB jumbo frames are clamped to the host limit") { const auto buffer = MakeInitializeComplete(16384, 1, 0); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); @@ -262,14 +265,14 @@ TEST_CASE("协商 quirk:WinCE 报 16KB 巨帧时钳到 host 上限") { CHECK(params->mtu == 1500); // still fits a full frame, MTU unchanged } -TEST_CASE("协商失败:MaxTransferSize 装不下头部") { +TEST_CASE("negotiation fails: MaxTransferSize cannot hold the header") { const auto buffer = MakeInitializeComplete(40, 1, 0); const auto complete = DecodeInitializeComplete(buffer); REQUIRE(complete.has_value()); CHECK_FALSE(Negotiate(*complete, 1500, 65536).has_value()); } -TEST_CASE("协商失败:非以太网介质") { +TEST_CASE("negotiation fails: non-Ethernet medium") { const auto buffer = MakeInitializeComplete(2048, 1, 0, 0, static_cast(Medium::kWirelessLan)); const auto complete = DecodeInitializeComplete(buffer); @@ -277,7 +280,7 @@ TEST_CASE("协商失败:非以太网介质") { CHECK_FALSE(Negotiate(*complete, 1500, 65536).has_value()); } -TEST_CASE("协商失败:面向连接设备") { +TEST_CASE("negotiation fails: connection-oriented device") { const auto buffer = MakeInitializeComplete( 2048, 1, 0, 0, 0, static_cast(DeviceFlags::kConnectionOriented)); const auto complete = DecodeInitializeComplete(buffer); @@ -289,7 +292,8 @@ TEST_CASE("协商失败:面向连接设备") { // QUERY / SET // --------------------------------------------------------------------------- -TEST_CASE("编码 QUERY_MSG:定长 OID 必须带占位长度与尾部零字节") { +TEST_CASE( + "encode QUERY_MSG: fixed-length OIDs carry a placeholder length and trailing zero bytes") { std::array buffer{}; const auto written = Encode(QueryRequest{.request_id = 3, .oid = Oid::kEthernetPermanentAddress, @@ -305,8 +309,9 @@ TEST_CASE("编码 QUERY_MSG:定长 OID 必须带占位长度与尾部零字节 CHECK(LoadLe32(buffer.data() + kQuerySetDeviceVcHandleOffset) == 0); } -TEST_CASE("编码 QUERY_MSG:变长 OID 的长度必须为 0") { - // Undocumented behavior of ActiveSync: passing a non-zero length for a variable-length OID gets rejected. +TEST_CASE("encode QUERY_MSG: variable-length OIDs have length 0") { + // Undocumented behavior of ActiveSync: passing a non-zero length for a variable-length OID gets + // rejected. std::array buffer{}; const auto written = Encode(QueryRequest{.request_id = 4, .oid = Oid::kGenSupportedList, @@ -319,7 +324,7 @@ TEST_CASE("编码 QUERY_MSG:变长 OID 的长度必须为 0") { CHECK(LoadLe32(buffer.data() + kQuerySetInfoBufferOffsetOffset) == 0); } -TEST_CASE("解码 QUERY_CMPLT:按 +8 基准点定位信息缓冲区") { +TEST_CASE("decode QUERY_CMPLT: the information buffer is located from the +8 base") { auto buffer = MakeMessage(MessageType::kQueryComplete, kQueryCmpltHeaderBytes + 6); StoreLe32(buffer.data() + kQueryCmpltRequestIdOffset, 9); StoreLe32(buffer.data() + kQueryCmpltStatusOffset, 0); @@ -340,9 +345,9 @@ TEST_CASE("解码 QUERY_CMPLT:按 +8 基准点定位信息缓冲区") { CHECK(*parsed == MacAddress{0x02, 0x11, 0x22, 0x33, 0x44, 0x55}); } -TEST_CASE("解码 QUERY_CMPLT:设备返回不支持时不算致命错误") { - // An optional OID (such as OID_GEN_PHYSICAL_MEDIUM) returning NOT_SUPPORTED is a normal situation, - // and decoding must return successfully and hand the status to the caller to judge. +TEST_CASE("decode QUERY_CMPLT: 'not supported' from the device is not fatal") { + // An optional OID (such as OID_GEN_PHYSICAL_MEDIUM) returning NOT_SUPPORTED is a normal + // situation, and decoding must return successfully and hand the status to the caller to judge. auto buffer = MakeMessage(MessageType::kQueryComplete, kQueryCmpltHeaderBytes); StoreLe32(buffer.data() + kQueryCmpltStatusOffset, ToRaw(StatusCode::kNotSupported)); const auto complete = DecodeQueryComplete(buffer); @@ -351,7 +356,7 @@ TEST_CASE("解码 QUERY_CMPLT:设备返回不支持时不算致命错误") { CHECK(complete->information.empty()); } -TEST_CASE("解码 QUERY_CMPLT:信息缓冲区越界必须报错") { +TEST_CASE("decode QUERY_CMPLT: an out-of-bounds information buffer is an error") { auto buffer = MakeMessage(MessageType::kQueryComplete, kQueryCmpltHeaderBytes + 4); StoreLe32(buffer.data() + kQueryCmpltStatusOffset, 0); StoreLe32(buffer.data() + kQueryCmpltInfoBufferLengthOffset, 1024); // lie @@ -359,7 +364,7 @@ TEST_CASE("解码 QUERY_CMPLT:信息缓冲区越界必须报错") { CHECK_FALSE(DecodeQueryComplete(buffer).has_value()); } -TEST_CASE("编码 SET_MSG 与 SET 一个 LE32") { +TEST_CASE("encode SET_MSG and SET an LE32") { std::array buffer{}; const auto written = EncodeSetUint32(11, Oid::kGenCurrentPacketFilter, kDefaultPacketFilter, buffer); @@ -372,7 +377,7 @@ TEST_CASE("编码 SET_MSG 与 SET 一个 LE32") { CHECK(LoadLe32(buffer.data() + kQuerySetHeaderBytes) == kDefaultPacketFilter); } -TEST_CASE("解码 SET_CMPLT") { +TEST_CASE("decode SET_CMPLT") { auto buffer = MakeMessage(MessageType::kSetComplete, kSetCmpltBytes); StoreLe32(buffer.data() + kSetCmpltRequestIdOffset, 11); StoreLe32(buffer.data() + kSetCmpltStatusOffset, 0); @@ -383,10 +388,10 @@ TEST_CASE("解码 SET_CMPLT") { } // --------------------------------------------------------------------------- -// RESET -- field offsets differ from other messages +// RESET: field offsets differ from other messages // --------------------------------------------------------------------------- -TEST_CASE("编码 RESET_MSG:offset 8 是 Reserved 而非 RequestId") { +TEST_CASE("encode RESET_MSG: offset 8 is Reserved, not RequestId") { std::array buffer{}; buffer[kResetReservedOffset] = std::byte{0xFF}; // pollute first, to verify it gets zeroed const auto written = EncodeReset(buffer); @@ -397,7 +402,7 @@ TEST_CASE("编码 RESET_MSG:offset 8 是 Reserved 而非 RequestId") { CHECK(LoadLe32(buffer.data() + kResetReservedOffset) == 0); } -TEST_CASE("解码 RESET_CMPLT:Status 在 offset 8 而不是 12") { +TEST_CASE("decode RESET_CMPLT: Status is at offset 8, not 12") { auto buffer = MakeMessage(MessageType::kResetComplete, kResetCmpltBytes); StoreLe32(buffer.data() + kResetCmpltStatusOffset, 0); StoreLe32(buffer.data() + kResetCmpltAddressingResetOffset, 1); @@ -409,7 +414,7 @@ TEST_CASE("解码 RESET_CMPLT:Status 在 offset 8 而不是 12") { CHECK(complete->addressing_reset); } -TEST_CASE("解码 RESET_CMPLT:AddressingReset 为 0 时无需重放") { +TEST_CASE("decode RESET_CMPLT: no replay when AddressingReset is 0") { auto buffer = MakeMessage(MessageType::kResetComplete, kResetCmpltBytes); StoreLe32(buffer.data() + kResetCmpltAddressingResetOffset, 0); const auto complete = DecodeResetComplete(buffer); @@ -421,7 +426,7 @@ TEST_CASE("解码 RESET_CMPLT:AddressingReset 为 0 时无需重放") { // KEEPALIVE // --------------------------------------------------------------------------- -TEST_CASE("KEEPALIVE 往返") { +TEST_CASE("KEEPALIVE round trip") { std::array request{}; const auto written = EncodeKeepAlive(42, request); REQUIRE(written.has_value()); @@ -435,7 +440,7 @@ TEST_CASE("KEEPALIVE 往返") { CHECK(complete->request_id == 42); } -TEST_CASE("host 也要能编码 KEEPALIVE_CMPLT(设备可主动发起保活)") { +TEST_CASE("the host can encode KEEPALIVE_CMPLT too (the device may start a keep-alive)") { std::array buffer{}; const auto written = EncodeKeepAliveComplete(77, ToRaw(StatusCode::kSuccess), buffer); REQUIRE(written.has_value()); @@ -446,10 +451,10 @@ TEST_CASE("host 也要能编码 KEEPALIVE_CMPLT(设备可主动发起保活) } // --------------------------------------------------------------------------- -// INDICATE_STATUS -- tolerant handling of the contradictory base point +// INDICATE_STATUS: tolerant handling of the contradictory base point // --------------------------------------------------------------------------- -TEST_CASE("解码 INDICATE_STATUS:MEDIA_CONNECT 无负载") { +TEST_CASE("decode INDICATE_STATUS: MEDIA_CONNECT has no payload") { auto buffer = MakeMessage(MessageType::kIndicateStatus, kIndicateStatusHeaderBytes); StoreLe32(buffer.data() + kIndicateStatusStatusOffset, ToRaw(StatusCode::kMediaConnect)); StoreLe32(buffer.data() + kIndicateStatusBufferLengthOffset, 0); @@ -461,7 +466,7 @@ TEST_CASE("解码 INDICATE_STATUS:MEDIA_CONNECT 无负载") { CHECK_FALSE(indication->has_diagnostic_info); } -TEST_CASE("解码 INDICATE_STATUS:按 +8 基准点解释状态缓冲区") { +TEST_CASE("decode INDICATE_STATUS: the status buffer is read from the +8 base") { const std::uint32_t total = kIndicateStatusHeaderBytes + kDiagnosticInfoBytes; auto buffer = MakeMessage(MessageType::kIndicateStatus, total); StoreLe32(buffer.data() + kIndicateStatusStatusOffset, ToRaw(StatusCode::kInvalidData)); @@ -481,7 +486,7 @@ TEST_CASE("解码 INDICATE_STATUS:按 +8 基准点解释状态缓冲区") { CHECK(indication->diagnostic_error_offset == 36); } -TEST_CASE("解码 INDICATE_STATUS:按消息起始基准点解释也能工作") { +TEST_CASE("decode INDICATE_STATUS: reading from the message start also works") { // Some devices implement the MS documentation literally (base point = message start). const std::uint32_t total = kIndicateStatusHeaderBytes + kDiagnosticInfoBytes; auto buffer = MakeMessage(MessageType::kIndicateStatus, total); @@ -493,14 +498,15 @@ TEST_CASE("解码 INDICATE_STATUS:按消息起始基准点解释也能工作") const auto indication = DecodeIndicateStatus(buffer); REQUIRE(indication.has_value()); - // The +8 interpretation would go out of bounds (8+20+8=36 > 28), so fall back to the literal interpretation. + // The +8 interpretation would go out of bounds (8+20+8=36 > 28), so fall back to the literal + // interpretation. REQUIRE(indication->status_buffer.size() == kDiagnosticInfoBytes); CHECK(indication->diagnostic_status == 0xAAU); } -TEST_CASE("解码 INDICATE_STATUS:两种基准点都越界时仍返回成功") { - // Key behavior: the status itself is useful (it may be MEDIA_DISCONNECT), - // and the link must not be judged dead just because an optional payload cannot be parsed. +TEST_CASE("decode INDICATE_STATUS: succeeds even when both bases are out of bounds") { + // Key behavior: the status itself is useful (it may be MEDIA_DISCONNECT), and the link must not + // be judged dead just because an optional payload cannot be parsed. auto buffer = MakeMessage(MessageType::kIndicateStatus, kIndicateStatusHeaderBytes); StoreLe32(buffer.data() + kIndicateStatusStatusOffset, ToRaw(StatusCode::kMediaDisconnect)); StoreLe32(buffer.data() + kIndicateStatusBufferLengthOffset, 4096); // lie @@ -512,7 +518,7 @@ TEST_CASE("解码 INDICATE_STATUS:两种基准点都越界时仍返回成功") CHECK(indication->status_buffer.empty()); } -TEST_CASE("解码 INDICATE_STATUS:类型不对时报错") { +TEST_CASE("decode INDICATE_STATUS: wrong type is an error") { auto buffer = MakeMessage(MessageType::kQueryComplete, kIndicateStatusHeaderBytes); CHECK_FALSE(DecodeIndicateStatus(buffer).has_value()); } @@ -529,26 +535,26 @@ TEST_CASE("ParseUint32 / ParseCounter / ParseMac") { REQUIRE(value.has_value()); CHECK(*value == 0x0000'002DU); - SUBCASE("计数器 OID 返回 4 字节") { + SUBCASE("counter OID returns 4 bytes") { const auto counter = ParseCounter(std::span{payload}.first(4)); REQUIRE(counter.has_value()); CHECK(*counter == 0x0000'002DU); } - SUBCASE("计数器 OID 返回 8 字节") { + SUBCASE("counter OID returns 8 bytes") { StoreLe64(payload.data(), 0x0000'0001'0000'002DULL); const auto counter = ParseCounter(payload); REQUIRE(counter.has_value()); CHECK(*counter == 0x0000'0001'0000'002DULL); } - SUBCASE("计数器 OID 返回 2 字节应报错") { + SUBCASE("counter OID returning 2 bytes is an error") { CHECK_FALSE(ParseCounter(std::span{payload}.first(2)).has_value()); } - SUBCASE("MAC 长度不足应报错") { + SUBCASE("a short MAC is an error") { CHECK_FALSE(ParseMac(std::span{payload}.first(4)).has_value()); } } -TEST_CASE("FormatMac 输出规范格式") { +TEST_CASE("FormatMac prints the canonical form") { const MacAddress mac{0x02, 0x00, 0xAB, 0xCD, 0xEF, 0x01}; const auto text = FormatMac(mac); CHECK(std::string_view{text.data()} == "02:00:ab:cd:ef:01"); @@ -558,7 +564,7 @@ TEST_CASE("FormatMac 输出规范格式") { // USB descriptor signature recognition // --------------------------------------------------------------------------- -TEST_CASE("识别四种已知的 RNDIS 通信类接口签名") { +TEST_CASE("recognizes the four known RNDIS control interface signatures") { CHECK(IsRndisControlSignature({0x02, 0x02, 0xFF})); // standard MS RNDIS CHECK(IsRndisControlSignature({0xEF, 0x01, 0x01})); // ActiveSync CHECK(IsRndisControlSignature({0xE0, 0x01, 0x03})); // wireless RNDIS (phone tethering) diff --git a/tests/test_rndis_packet_codec.cc b/tests/test_rndis_packet_codec.cc index e7ad0b3..181e303 100644 --- a/tests/test_rndis_packet_codec.cc +++ b/tests/test_rndis_packet_codec.cc @@ -1,11 +1,15 @@ -// Unit tests of REMOTE_NDIS_PACKET_MSG encoding/decoding -- the line of defense for data hot path correctness. +// Unit tests of REMOTE_NDIS_PACKET_MSG encoding/decoding: the line of defense for data hot path +// correctness. // // Key coverage: -// 1. The DataOffset base point is message start +8 (encoding writes 36, decoding locates by 8+36); -// 2. Alignment rules for multi-packet aggregation: padding is attributed to the **previous** message's MessageLength, -// and the last message has no external padding; -// 3. ZLP avoidance: pad 1 byte when the transfer length is exactly an integer multiple of the endpoint's max packet size; -// 4. Decoding must tolerate trailing padding (otherwise every full transfer would give a false report once); +// 1. The DataOffset base point is message start +8 (encoding writes 36, decoding locates by +// 8+36); +// 2. Alignment rules for multi-packet aggregation: padding is attributed to the **previous** +// message's MessageLength, and the last message has no external padding; +// 3. ZLP avoidance: pad 1 byte when the transfer length is exactly an integer multiple of the +// endpoint's max packet size; +// 4. Decoding must tolerate trailing padding (otherwise every full transfer would give a false +// report once); // 5. All malformed inputs are recognized as kMalformed without reading out of bounds. #include #include @@ -100,7 +104,7 @@ TEST_SUITE("rndis.packet_codec") { // Encoding // --------------------------------------------------------------------------- -TEST_CASE("编码单帧:DataOffset 必须写 36") { +TEST_CASE("encode one frame: DataOffset is 36") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 2048, .max_messages = 1, .alignment_bytes = 1}, @@ -132,7 +136,7 @@ TEST_CASE("编码单帧:DataOffset 必须写 36") { CHECK(FrameMatches(std::span{transfer}.subspan(44, 1514), 1514, 0x11)); } -TEST_CASE("编码受 MaxPacketsPerMessage 限制") { +TEST_CASE("encoding respects MaxPacketsPerMessage") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 8192, .max_messages = 2, .alignment_bytes = 1}, @@ -143,7 +147,7 @@ TEST_CASE("编码受 MaxPacketsPerMessage 限制") { CHECK(writer.MessageCount() == 2); } -TEST_CASE("编码受设备 MaxTransferSize 限制") { +TEST_CASE("encoding respects the device's MaxTransferSize") { std::array transfer{}; // Only enough room for one 44+64=108-byte message (leaving 1 byte of ZLP margin). PacketMessageWriter writer(transfer, @@ -154,23 +158,24 @@ TEST_CASE("编码受设备 MaxTransferSize 限制") { CHECK(writer.MessageCount() == 1); } -TEST_CASE("编码空批次 Finish 返回 0") { +TEST_CASE("Finish on an empty batch returns 0") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 1024}, 512); CHECK(writer.Empty()); CHECK(writer.Finish() == 0); } -TEST_CASE("多包聚合:填充归入上一个消息,最后一个不含外部填充") { +TEST_CASE( + "aggregation: padding belongs to the previous message, the last has no trailing padding") { std::array transfer{}; // Align to 8 bytes (PacketAlignmentFactor = 3). PacketMessageWriter writer(transfer, {.max_transfer_bytes = 8192, .max_messages = 3, .alignment_bytes = 8}, 512); - // Frame length 61 -> message length 44+61 = 105. 105 is not a multiple of 8, and rounds up to 112 (14x8), - // so 7 bytes of padding are needed before the next message, and those 7 bytes must be swallowed into the **first** message's - // MessageLength. + // Frame length 61 -> message length 44+61 = 105. 105 is not a multiple of 8, and rounds up to 112 + // (14x8), so 7 bytes of padding are needed before the next message, and those 7 bytes must be + // swallowed into the **first** message's MessageLength. REQUIRE(writer.TryAppend(MakeFrame(61, 0xA0))); REQUIRE(writer.TryAppend(MakeFrame(70, 0xB0))); REQUIRE(writer.TryAppend(MakeFrame(64, 0xC0))); @@ -180,8 +185,8 @@ TEST_CASE("多包聚合:填充归入上一个消息,最后一个不含外部 CHECK(LoadLe32(transfer.data() + kMessageLengthOffset) == 112); CHECK(112 % 8 == 0); - // The second message starts at 112: 44+70 = 114 -> cumulative 226, rounded up to 232, - // so the second message's MessageLength is extended to 114 + 6 = 120. + // The second message starts at 112: 44+70 = 114 -> cumulative 226, rounded up to 232, so the + // second message's MessageLength is extended to 114 + 6 = 120. CHECK(LoadLe32(transfer.data() + 112 + kMessageLengthOffset) == 120); CHECK((112 + 120) % 8 == 0); @@ -191,7 +196,7 @@ TEST_CASE("多包聚合:填充归入上一个消息,最后一个不含外部 CHECK(writer.PayloadBytes() == 61 + 70 + 64); } -TEST_CASE("多包聚合:编码结果能被解码器完整还原") { +TEST_CASE("aggregation: the decoder restores what was encoded") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 8192, .max_messages = 4, .alignment_bytes = 8}, @@ -211,7 +216,7 @@ TEST_CASE("多包聚合:编码结果能被解码器完整还原") { } } -TEST_CASE("ZLP 规避:长度恰为端点最大包长整数倍时补 1 字节") { +TEST_CASE("ZLP avoidance: one byte is added when the length is a multiple of the max packet size") { std::array transfer{}; constexpr std::uint32_t kEndpointMaxPacket = 512; // Make the total length exactly 512: 44 + 468 = 512. @@ -229,7 +234,7 @@ TEST_CASE("ZLP 规避:长度恰为端点最大包长整数倍时补 1 字节") CHECK(LoadLe32(transfer.data() + kMessageLengthOffset) == 512); } -TEST_CASE("ZLP 规避:长度不是整数倍时不补字节") { +TEST_CASE("ZLP avoidance: nothing is added otherwise") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 4096, .max_messages = 1, .alignment_bytes = 1}, @@ -240,7 +245,7 @@ TEST_CASE("ZLP 规避:长度不是整数倍时不补字节") { CHECK(total == kPacketMsgHeaderBytes + 100); } -TEST_CASE("RemainingFrameCapacity 报告准确,可避免取帧后回退") { +TEST_CASE("RemainingFrameCapacity is exact, so frames never need to be put back") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 200, .max_messages = 5, .alignment_bytes = 1}, @@ -256,7 +261,7 @@ TEST_CASE("RemainingFrameCapacity 报告准确,可避免取帧后回退") { CHECK(writer.RemainingFrameCapacity() == 0); } -TEST_CASE("包数用满后 RemainingFrameCapacity 归零") { +TEST_CASE("RemainingFrameCapacity is 0 once the packet count is used up") { std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 8192, .max_messages = 1, .alignment_bytes = 1}, @@ -269,7 +274,7 @@ TEST_CASE("包数用满后 RemainingFrameCapacity 归零") { // Decoding // --------------------------------------------------------------------------- -TEST_CASE("解码单帧:按 8 + DataOffset 定位数据") { +TEST_CASE("decode one frame: data is at 8 + DataOffset") { std::vector transfer(kPacketMsgHeaderBytes + 1514); const auto frame = MakeFrame(1514, 0x22); WritePacketMessage(transfer, frame, kPacketInlineDataOffset, @@ -281,8 +286,9 @@ TEST_CASE("解码单帧:按 8 + DataOffset 定位数据") { CHECK(FrameMatches(summary.frames[0], 1514, 0x22)); } -TEST_CASE("解码:数据不紧跟头部(DataOffset 大于 36)") { - // The device is entirely free to leave a gap between the header and the data; the decoder must follow DataOffset. +TEST_CASE("decode: data not right after the header (DataOffset above 36)") { + // The device is entirely free to leave a gap between the header and the data; the decoder must + // follow DataOffset. constexpr std::uint32_t kGap = 16; constexpr std::uint32_t kFrameLength = 100; const std::uint32_t message_length = kPacketMsgHeaderBytes + kGap + kFrameLength; @@ -295,8 +301,9 @@ TEST_CASE("解码:数据不紧跟头部(DataOffset 大于 36)") { CHECK(FrameMatches(summary.frames[0], kFrameLength, 0x33)); } -TEST_CASE("解码:容忍尾部 1 字节 ZLP 规避填充") { - // This tolerance is required -- otherwise every full transfer would falsely report one malformed message. +TEST_CASE("decode: tolerates 1 trailing byte of ZLP padding") { + // This tolerance is required: otherwise every full transfer would falsely report one malformed + // message. std::vector transfer(kPacketMsgHeaderBytes + 64 + 1); WritePacketMessage(transfer, MakeFrame(64, 0x44), kPacketInlineDataOffset, kPacketMsgHeaderBytes + 64, 64); @@ -308,7 +315,7 @@ TEST_CASE("解码:容忍尾部 1 字节 ZLP 规避填充") { CHECK(summary.trailing_padding == 1); } -TEST_CASE("解码:容忍最多 43 字节的尾部垃圾") { +TEST_CASE("decode: tolerates up to 43 trailing garbage bytes") { // A tail shorter than one complete header (44 bytes) is always treated as padding. std::vector transfer(kPacketMsgHeaderBytes + 64 + 43); WritePacketMessage(transfer, MakeFrame(64, 0x45), kPacketInlineDataOffset, @@ -323,14 +330,14 @@ TEST_CASE("解码:容忍最多 43 字节的尾部垃圾") { CHECK(summary.trailing_padding == 43); } -TEST_CASE("解码空传输") { +TEST_CASE("decode an empty transfer") { const auto summary = DecodeAll({}); CHECK(summary.final_outcome == ReadOutcome::kEndOfTransfer); CHECK(summary.frames.empty()); } -TEST_CASE("解码畸形输入:全部被识别且不读越界") { - SUBCASE("MessageType 不是 PACKET_MSG") { +TEST_CASE("decode malformed input: every case is detected without reading out of bounds") { + SUBCASE("MessageType is not PACKET_MSG") { std::vector transfer(kPacketMsgHeaderBytes + 64); WritePacketMessage(transfer, MakeFrame(64, 1), kPacketInlineDataOffset, kPacketMsgHeaderBytes + 64, 64); @@ -340,7 +347,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { CHECK(summary.reason == MalformedReason::kNotPacketMessage); } - SUBCASE("MessageLength 小于 44") { + SUBCASE("MessageLength below 44") { std::vector transfer(kPacketMsgHeaderBytes + 64); WritePacketMessage(transfer, MakeFrame(64, 1), kPacketInlineDataOffset, 40, 64); const auto summary = DecodeAll(transfer); @@ -348,7 +355,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { CHECK(summary.reason == MalformedReason::kMessageTooShort); } - SUBCASE("MessageLength 超出剩余缓冲") { + SUBCASE("MessageLength beyond the remaining buffer") { std::vector transfer(kPacketMsgHeaderBytes + 64); WritePacketMessage(transfer, MakeFrame(64, 1), kPacketInlineDataOffset, 0xFFFF'FFFFU, 64); const auto summary = DecodeAll(transfer); @@ -356,7 +363,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { CHECK(summary.reason == MalformedReason::kMessageOverruns); } - SUBCASE("DataOffset + DataLength 越界") { + SUBCASE("DataOffset + DataLength out of bounds") { std::vector transfer(kPacketMsgHeaderBytes + 64); WritePacketMessage(transfer, {}, kPacketInlineDataOffset, kPacketMsgHeaderBytes + 64, 1000); const auto summary = DecodeAll(transfer); @@ -364,7 +371,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { CHECK(summary.reason == MalformedReason::kDataOutOfBounds); } - SUBCASE("DataOffset 巨大值不得整数溢出") { + SUBCASE("a huge DataOffset must not overflow") { std::vector transfer(kPacketMsgHeaderBytes + 64); WritePacketMessage(transfer, {}, 0xFFFF'FFF8U, kPacketMsgHeaderBytes + 64, 64); const auto summary = DecodeAll(transfer); @@ -372,7 +379,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { CHECK(summary.reason == MalformedReason::kDataOutOfBounds); } - SUBCASE("DataLength 小于以太头长度") { + SUBCASE("DataLength shorter than an Ethernet header") { std::vector transfer(kPacketMsgHeaderBytes + 64); WritePacketMessage(transfer, MakeFrame(13, 1), kPacketInlineDataOffset, kPacketMsgHeaderBytes + 64, 13); @@ -381,7 +388,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { CHECK(summary.reason == MalformedReason::kFrameTooShort); } - SUBCASE("DataLength 超过本机单帧上限") { + SUBCASE("DataLength above this host's frame limit") { const std::uint32_t message_length = kPacketMsgHeaderBytes + 3000; std::vector transfer(message_length); WritePacketMessage(transfer, {}, kPacketInlineDataOffset, message_length, 3000); @@ -391,8 +398,9 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { } } -TEST_CASE("解码:前几帧有效、中途畸形时保留已解出的帧") { - // Required behavior when a real device has a bug: the first 2 frames must not be dropped just because the 3rd message is bad. +TEST_CASE("decode: frames decoded before a malformed one are kept") { + // Required behavior when a real device has a bug: the first 2 frames must not be dropped just + // because the 3rd message is bad. std::array transfer{}; PacketMessageWriter writer(transfer, {.max_transfer_bytes = 8192, .max_messages = 3, .alignment_bytes = 1}, @@ -402,8 +410,8 @@ TEST_CASE("解码:前几帧有效、中途畸形时保留已解出的帧") { REQUIRE(writer.TryAppend(MakeFrame(64, 0x03))); const std::uint32_t total = writer.Finish(); - // Corrupt the type field of the third message. - // With 1-byte alignment messages are laid out back to back, and the third message's offset is the sum of the first two. + // Corrupt the type field of the third message. With 1-byte alignment messages are laid out back + // to back, and the third message's offset is the sum of the first two. const std::size_t third_offset = std::size_t{2} * (kPacketMsgHeaderBytes + 64); StoreLe32(transfer.data() + third_offset + kMessageTypeOffset, 0xDEAD'BEEFU); @@ -415,7 +423,7 @@ TEST_CASE("解码:前几帧有效、中途畸形时保留已解出的帧") { CHECK(FrameMatches(summary.frames[1], 64, 0x02)); } -TEST_CASE("解码:帧视图指向传输缓冲内部,无拷贝") { +TEST_CASE("decode: frame views point into the transfer buffer, no copy") { std::vector transfer(kPacketMsgHeaderBytes + 100); WritePacketMessage(transfer, MakeFrame(100, 0x77), kPacketInlineDataOffset, kPacketMsgHeaderBytes + 100, 100); @@ -429,10 +437,10 @@ TEST_CASE("解码:帧视图指向传输缓冲内部,无拷贝") { CHECK(reader.BytesConsumed() == kPacketMsgHeaderBytes + 100); } -TEST_CASE("MalformedReason 名字完整") { +TEST_CASE("every MalformedReason has a name") { // The name is user-facing text that changes with language, so pin the language before asserting. - const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kChinese}; - CHECK(MalformedReasonName(MalformedReason::kNone) == "无"); + const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kEnglish}; + CHECK(MalformedReasonName(MalformedReason::kNone) == "none"); CHECK_FALSE(MalformedReasonName(MalformedReason::kNotPacketMessage).empty()); CHECK_FALSE(MalformedReasonName(MalformedReason::kDataOutOfBounds).empty()); CHECK_FALSE(MalformedReasonName(MalformedReason::kFrameTooLong).empty()); @@ -442,7 +450,7 @@ TEST_CASE("MalformedReason 名字完整") { // Round-trip property tests // --------------------------------------------------------------------------- -TEST_CASE("往返:各种对齐因子与帧长组合都能无损还原") { +TEST_CASE("round trip: every alignment factor and frame length survives losslessly") { std::array transfer{}; for (std::uint32_t factor = 0; factor <= kMaxPacketAlignmentFactor; ++factor) { const std::uint32_t alignment = 1U << factor; diff --git a/tests/test_rndis_state_machine.cc b/tests/test_rndis_state_machine.cc index d673c1e..3860e4d 100644 --- a/tests/test_rndis_state_machine.cc +++ b/tests/test_rndis_state_machine.cc @@ -1,8 +1,9 @@ // Unit tests of the RNDIS state machine. // -// The state machine is the most logically complex part of the whole protocol implementation, and many of its paths are extremely hard to reproduce on real hardware -// (device cut-in pushes, keepalive failures, replay required after a reset). Here MockControlChannel plays -// the device side, covering all of these paths. +// The state machine is the most logically complex part of the whole protocol implementation, and +// many of its paths are extremely hard to reproduce on real hardware (device cut-in pushes, +// keepalive failures, replay required after a reset). Here MockControlChannel plays the device +// side, covering all of these paths. #include #include #include @@ -17,8 +18,8 @@ #include "tetherkitnext/rndis/state_machine.h" // Same reason as the same-named helper in test_net_link.cc: writing directly inside REQUIRE_MESSAGE -// `r ? "" : r.error().ToString()` does not compile -- doctest's MessageBuilder swallows -// the whole ternary expression into the stream and then tries to convert it to bool. +// `r ? "" : r.error().ToString()` does not compile: doctest's MessageBuilder swallows the whole +// ternary expression into the stream and then tries to convert it to bool. namespace { template std::string Why(const T& result) { @@ -60,7 +61,7 @@ constexpr MacAddress kDeviceMac{0x02, 0x1A, 0x11, 0x22, 0x33, 0x44}; TEST_SUITE("rndis.state_machine") { -TEST_CASE("状态名齐全") { +TEST_CASE("every state has a name") { CHECK_FALSE(StateName(State::kUninitialized).empty()); CHECK_FALSE(StateName(State::kInitializing).empty()); CHECK_FALSE(StateName(State::kInitialized).empty()); @@ -68,7 +69,7 @@ TEST_CASE("状态名齐全") { CHECK_FALSE(StateName(State::kHalting).empty()); } -TEST_CASE("完整启动序列:走到 kDataInitialized 并通报协商结果") { +TEST_CASE("full startup: reaches kDataInitialized and reports the negotiated parameters") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -92,7 +93,7 @@ TEST_CASE("完整启动序列:走到 kDataInitialized 并通报协商结果") CHECK(observer.parameters_snapshot.max_packets_per_message == 1); CHECK(observer.parameters_snapshot.tx_alignment_bytes == 1); - // Got the device MAC -- this is the address the host-side feth is to use. + // Got the device MAC: this is the address the host-side feth is to use. CHECK(machine.Info().has_permanent_address); CHECK(machine.Info().permanent_address == kDeviceMac); CHECK(machine.Info().LinkSpeedMbps() == doctest::Approx(480.0)); @@ -102,7 +103,7 @@ TEST_CASE("完整启动序列:走到 kDataInitialized 并通报协商结果") CHECK(observer.link_events[0]); } -TEST_CASE("启动序列的消息顺序:INITIALIZE 在最前,SET 包过滤在最后") { +TEST_CASE("startup message order: INITIALIZE first, the packet-filter SET last") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -112,21 +113,23 @@ TEST_CASE("启动序列的消息顺序:INITIALIZE 在最前,SET 包过滤在 REQUIRE_FALSE(channel.SentMessages().empty()); // The first must be INITIALIZE_MSG. CHECK(channel.SentMessageType(0) == ToRaw(MessageType::kInitialize)); - // The last must be SET (packet filter) -- only it puts the device into data-initialized. + // The last must be SET (packet filter), only it puts the device into data-initialized. const std::size_t last = channel.SentMessages().size() - 1; CHECK(channel.SentMessageType(last) == ToRaw(MessageType::kSet)); // Only one INITIALIZE was sent, with no repeats. CHECK(channel.CountSent(MessageType::kInitialize) == 1); - // The packet filter value set must be the one we requested (DIRECTED|BROADCAST|ALL_MULTICAST|PROMISCUOUS). + // The packet filter value set must be the one we requested + // (DIRECTED|BROADCAST|ALL_MULTICAST|PROMISCUOUS). std::uint32_t filter = 0; REQUIRE(channel.FindSetUint32(Oid::kGenCurrentPacketFilter, filter)); CHECK(filter == kDefaultPacketFilter); CHECK(filter == 0x0000'002DU); } -TEST_CASE("变长 OID 的 InformationBufferLength 必须为 0,定长必须非 0") { +TEST_CASE( + "InformationBufferLength is 0 for variable-length OIDs and non-zero for fixed-length ones") { MockControlChannel channel; std::vector> query_oid_and_length; channel.SetRequestHandler( @@ -146,11 +149,13 @@ TEST_CASE("变长 OID 的 InformationBufferLength 必须为 0,定长必须非 bool saw_variable = false; for (const auto& [oid, length] : query_oid_and_length) { if (IsVariableLengthOid(static_cast(oid))) { - // Passing a non-zero length for a variable-length OID gets rejected by the ActiveSync implementation. - CHECK_MESSAGE(length == 0, "变长 OID " << OidName(oid) << " 的长度应为 0"); + // Passing a non-zero length for a variable-length OID gets rejected by the ActiveSync + // implementation. + CHECK_MESSAGE(length == 0, "variable-length OID " << OidName(oid) << " must have length 0"); saw_variable = true; } else { - CHECK_MESSAGE(length > 0, "定长 OID " << OidName(oid) << " 的长度应大于 0"); + CHECK_MESSAGE(length > 0, + "fixed-length OID " << OidName(oid) << " must have a length above 0"); saw_fixed = true; } } @@ -158,7 +163,7 @@ TEST_CASE("变长 OID 的 InformationBufferLength 必须为 0,定长必须非 CHECK(saw_variable); // OID_GEN_VENDOR_DESCRIPTION was queried in the startup sequence } -TEST_CASE("可选 OID 返回 NOT_SUPPORTED 不影响启动") { +TEST_CASE("an optional OID returning NOT_SUPPORTED does not stop startup") { // OID_GEN_PHYSICAL_MEDIUM is optional, and the device replying unsupported is entirely normal. MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); @@ -170,7 +175,7 @@ TEST_CASE("可选 OID 返回 NOT_SUPPORTED 不影响启动") { CHECK(observer.fatal_errors.empty()); } -TEST_CASE("拿不到永久 MAC 是致命错误,且会发 HALT") { +TEST_CASE("no permanent MAC is fatal and sends HALT") { MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { const std::uint32_t type = LoadLe32(request.data() + kMessageTypeOffset); @@ -180,7 +185,7 @@ TEST_CASE("拿不到永久 MAC 是致命错误,且会发 HALT") { return; } if (type == ToRaw(MessageType::kQuery)) { - // All QUERYs reply unsupported -- including the permanent MAC. + // All QUERYs reply unsupported, including the permanent MAC. mock.EnqueueResponse( MakeQueryComplete(request_id, {}, ToRaw(StatusCode::kNotSupported))); } @@ -196,7 +201,7 @@ TEST_CASE("拿不到永久 MAC 是致命错误,且会发 HALT") { CHECK(channel.CountSent(MessageType::kHalt) == 1); } -TEST_CASE("设备拒绝初始化时不发 QUERY,直接失败") { +TEST_CASE("if the device rejects INITIALIZE, startup fails without any QUERY") { MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { const std::uint32_t type = LoadLe32(request.data() + kMessageTypeOffset); @@ -213,7 +218,7 @@ TEST_CASE("设备拒绝初始化时不发 QUERY,直接失败") { CHECK(channel.CountSent(MessageType::kQuery) == 0); } -TEST_CASE("非以太网介质被拒绝") { +TEST_CASE("a non-Ethernet medium is rejected") { MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { if (LoadLe32(request.data() + kMessageTypeOffset) == ToRaw(MessageType::kInitialize)) { @@ -228,8 +233,8 @@ TEST_CASE("非以太网介质被拒绝") { REQUIRE_FALSE(machine.Start().has_value()); } -TEST_CASE("设备在等响应期间插入 INDICATE_STATUS,不影响请求配对") { - // This is a path that is very common on real hardware but extremely hard to reproduce on purpose. +TEST_CASE("an INDICATE_STATUS while waiting for a response does not break request matching") { + // This is a path that is very common on real hardware but extremely hard to reproduce on demand. MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { const std::uint32_t type = LoadLe32(request.data() + kMessageTypeOffset); @@ -251,16 +256,18 @@ TEST_CASE("设备在等响应期间插入 INDICATE_STATUS,不影响请求配 // The cut-in message must be consumed and not pile up in the queue crowding out later responses. CHECK(channel.PendingResponseCount() == 0); - // About link events: link state is **edge-triggered**. The initial state assumed internally at startup is - // "not connected", so a MEDIA_DISCONNECT matches the current understanding -> correctly produces no event - // (deduplication). Afterwards QUERY OID_GEN_MEDIA_CONNECT_STATUS returns 0 (connected), - // which is the newer, authoritative state, so Start() reports "connected" once at the end. + // About link events: link state is **edge-triggered**. The initial state assumed internally at + // startup is "not connected", so a MEDIA_DISCONNECT matches the current understanding -> + // correctly produces no event (deduplication). Afterwards QUERY OID_GEN_MEDIA_CONNECT_STATUS + // returns 0 (connected), which is the newer, authoritative state, so Start() reports "connected" + // once at the end. REQUIRE(observer.link_events.size() == 1); CHECK(observer.link_events[0]); } -TEST_CASE("链路已 up 之后收到 MEDIA_DISCONNECT 才产生断开事件") { - // This is the scenario where MEDIA_DISCONNECT really should trigger an event: there is an up -> down edge. +TEST_CASE("a disconnect event fires only for MEDIA_DISCONNECT after the link is up") { + // This is the scenario where MEDIA_DISCONNECT really should trigger an event: there is an up -> + // down edge. MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -280,7 +287,7 @@ TEST_CASE("链路已 up 之后收到 MEDIA_DISCONNECT 才产生断开事件") { REQUIRE(observer.link_events.size() == 2); CHECK_FALSE(observer.link_events[1]); - // Push another identical report -- edge-triggered, it should not produce another event. + // Push another identical report: edge-triggered, it should not produce another event. channel.EnqueueResponse(MakeIndicateStatus(StatusCode::kMediaDisconnect)); REQUIRE(machine.Poll().has_value()); CHECK(observer.link_events.size() == 2); @@ -292,7 +299,7 @@ TEST_CASE("链路已 up 之后收到 MEDIA_DISCONNECT 才产生断开事件") { CHECK(observer.link_events[2]); } -TEST_CASE("设备主动发 KEEPALIVE_MSG 时主机必须回 KEEPALIVE_CMPLT") { +TEST_CASE("the host answers a device-initiated KEEPALIVE_MSG with KEEPALIVE_CMPLT") { // If it does not reply, the device may judge the host dead and disconnect. MockControlChannel channel; constexpr std::uint32_t kDeviceKeepAliveId = 0xABCD'1234; @@ -322,12 +329,12 @@ TEST_CASE("设备主动发 KEEPALIVE_MSG 时主机必须回 KEEPALIVE_CMPLT") { found = true; } } - CHECK_MESSAGE(found, "主机没有回复设备发起的 KEEPALIVE"); + CHECK_MESSAGE(found, "the host did not answer the device's KEEPALIVE"); } -TEST_CASE("面向连接设备的消息被明确拒绝") { - // The following asserts the Chinese wording of the error message, so pin the language first. - const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kChinese}; +TEST_CASE("connection-oriented device messages are rejected explicitly") { + // The following asserts the wording of the error message, so pin the language first. + const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kEnglish}; MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { if (LoadLe32(request.data() + kMessageTypeOffset) == ToRaw(MessageType::kInitialize)) { @@ -344,11 +351,12 @@ TEST_CASE("面向连接设备的消息被明确拒绝") { const auto status = machine.Start(); REQUIRE_FALSE(status.has_value()); - // The error message must explicitly point out that it is a connection-oriented device, rather than a vague "unknown message". - CHECK(status.error().ToString().find("面向连接") != std::string::npos); + // The error message must explicitly point out that it is a connection-oriented device, rather + // than a vague "unknown message". + CHECK(status.error().ToString().find("connection-oriented") != std::string::npos); } -TEST_CASE("保活正常时不报错,且设备活跃期间不发无谓保活") { +TEST_CASE("healthy keep-alives report nothing, and none are sent while the device is active") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -363,7 +371,7 @@ TEST_CASE("保活正常时不报错,且设备活跃期间不发无谓保活") CHECK(channel.CountSent(MessageType::kKeepAlive) == 0); } -TEST_CASE("保活到期时发 KEEPALIVE 并在成功后清零失败计数") { +TEST_CASE("a due keep-alive sends KEEPALIVE and clears the failure count on success") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -378,15 +386,16 @@ TEST_CASE("保活到期时发 KEEPALIVE 并在成功后清零失败计数") { CHECK(observer.fatal_errors.empty()); } -TEST_CASE("连续保活失败达到阈值后通报致命错误") { - // The following asserts the Chinese wording in the fatal error, so pin the language first. - const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kChinese}; +TEST_CASE("repeated keep-alive failures past the threshold are reported as fatal") { + // The following asserts the wording of the fatal error, so pin the language first. + const tetherkitnext::testing::ScopedLanguage guard{tetherkitnext::Language::kEnglish}; MockControlChannel channel; - // The device replies only to INITIALIZE / QUERY / SET, and never replies to KEEPALIVE -> times out every time. + // The device replies only to INITIALIZE / QUERY / SET, and never replies to KEEPALIVE -> times + // out every time. channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { const std::uint32_t type = LoadLe32(request.data() + kMessageTypeOffset); if (type == ToRaw(MessageType::kKeepAlive)) { - return; // deliberately does not reply + return; // does not reply } MakeWellBehavedDevice(kDeviceMac)(request, mock); }); @@ -406,10 +415,10 @@ TEST_CASE("连续保活失败达到阈值后通报致命错误") { const auto third = machine.Poll(); CHECK_FALSE(third.has_value()); REQUIRE(observer.fatal_errors.size() == 1); - CHECK(observer.fatal_errors[0].find("保活") != std::string::npos); + CHECK(observer.fatal_errors[0].find("keep-alive") != std::string::npos); } -TEST_CASE("软复位:AddressingReset 非零时必须重放包过滤") { +TEST_CASE("soft reset: the packet filter is replayed when AddressingReset is non-zero") { // This is the easiest one to miss: without replay, data would never flow again after a reset. MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); @@ -429,11 +438,11 @@ TEST_CASE("软复位:AddressingReset 非零时必须重放包过滤") { // And the packet filter must have been replayed. std::uint32_t filter = 0; REQUIRE_MESSAGE(channel.FindSetUint32(Oid::kGenCurrentPacketFilter, filter), - "复位后没有重放包过滤设置"); + "the packet filter was not replayed after the reset"); CHECK(filter == kDefaultPacketFilter); } -TEST_CASE("软复位:AddressingReset 为 0 时不必重放") { +TEST_CASE("soft reset: no replay when AddressingReset is 0") { MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { const std::uint32_t type = LoadLe32(request.data() + kMessageTypeOffset); @@ -456,7 +465,7 @@ TEST_CASE("软复位:AddressingReset 为 0 时不必重放") { CHECK_FALSE(channel.FindSetUint32(Oid::kGenCurrentPacketFilter, filter)); } -TEST_CASE("停机:先清零包过滤再发 HALT") { +TEST_CASE("shutdown: clear the packet filter, then send HALT") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -467,7 +476,8 @@ TEST_CASE("停机:先清零包过滤再发 HALT") { machine.Stop(); CHECK(machine.CurrentState() == State::kUninitialized); - // Must SET filter = 0 first (making the device fall back to initialized and stop sending data), then send HALT. + // Must SET filter = 0 first (making the device fall back to initialized and stop sending data), + // then send HALT. std::uint32_t filter = 0xFFFF'FFFFU; REQUIRE(channel.FindSetUint32(Oid::kGenCurrentPacketFilter, filter)); CHECK(filter == 0); @@ -477,7 +487,7 @@ TEST_CASE("停机:先清零包过滤再发 HALT") { CHECK(channel.SentMessageType(last) == ToRaw(MessageType::kHalt)); } -TEST_CASE("停机是幂等的") { +TEST_CASE("shutdown is idempotent") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -490,7 +500,7 @@ TEST_CASE("停机是幂等的") { CHECK(channel.SentMessages().size() == after_first); } -TEST_CASE("Start 只能在未初始化状态下调用") { +TEST_CASE("Start is only allowed when uninitialized") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -499,8 +509,9 @@ TEST_CASE("Start 只能在未初始化状态下调用") { CHECK_FALSE(machine.Start().has_value()); } -TEST_CASE("设备没有中断端点时退化为轮询,仍能完成启动") { - // Linux's host driver ignores the interrupt endpoint entirely and relies purely on polling the control endpoint. +TEST_CASE("without an interrupt endpoint it falls back to polling and still starts") { + // Linux's host driver ignores the interrupt endpoint entirely and relies purely on polling the + // control endpoint. MockControlChannel channel; channel.SetHasInterruptEndpoint(false); channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); @@ -512,7 +523,7 @@ TEST_CASE("设备没有中断端点时退化为轮询,仍能完成启动") { CHECK(machine.CurrentState() == State::kDataInitialized); } -TEST_CASE("控制通道发送失败时启动失败且不卡在中间状态") { +TEST_CASE("a failed control send fails startup without leaving an intermediate state") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); channel.FailSendOnCall(1); // the first INITIALIZE cannot even be sent @@ -523,7 +534,7 @@ TEST_CASE("控制通道发送失败时启动失败且不卡在中间状态") { CHECK(machine.CurrentState() == State::kUninitialized); } -TEST_CASE("设备 quirk:高通聚合补丁(MaxPacketsPerMessage=3、对齐因子 2)") { +TEST_CASE("device quirk: Qualcomm aggregation patch (MaxPacketsPerMessage=3, alignment factor 2)") { MockControlChannel channel; channel.SetRequestHandler( MakeWellBehavedDevice(kDeviceMac, /*max_transfer_size=*/3 * 1600, @@ -536,7 +547,7 @@ TEST_CASE("设备 quirk:高通聚合补丁(MaxPacketsPerMessage=3、对齐 CHECK(observer.parameters_snapshot.tx_alignment_bytes == 4); // 1 << 2 } -TEST_CASE("设备 quirk:对齐因子越界被钳到 7") { +TEST_CASE("device quirk: an out-of-range alignment factor is clamped to 7") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac, 2048, 1, /*alignment_factor=*/31)); RecordingObserver observer; @@ -545,7 +556,7 @@ TEST_CASE("设备 quirk:对齐因子越界被钳到 7") { CHECK(observer.parameters_snapshot.tx_alignment_bytes == 128); } -TEST_CASE("设备汇报的最大帧长小于协商 MTU 时下调 MTU") { +TEST_CASE("the MTU drops when the device's maximum frame size is below the negotiated MTU") { MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { const std::uint32_t type = LoadLe32(request.data() + kMessageTypeOffset); @@ -563,7 +574,7 @@ TEST_CASE("设备汇报的最大帧长小于协商 MTU 时下调 MTU") { CHECK(machine.Parameters().mtu == 1400); } -TEST_CASE("MillisUntilNextPoll 在保活周期内返回正值") { +TEST_CASE("MillisUntilNextPoll is positive within the keep-alive period") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -579,21 +590,20 @@ TEST_CASE("MillisUntilNextPoll 在保活周期内返回正值") { TEST_SUITE("rndis.state_machine_timeout") { -// * Regression cases for a class of hang defects that "the mock cannot catch" * +// Hang cases that the mock cannot catch on its own. // -// The defect: Poll() had WaitForNotification(0) written in it, meaning "do not wait, just probe", -// but on darwin libusb passes timeout to IOKit as both noDataTimeout and -// completionTimeout, and **0 means wait forever** -- -// the control loop would hang forever on libusb_wait_for_event, unable even to respond to SIGTERM. -// The reason the mock cannot catch it is that it returns immediately for any timeout. -// So here we directly assert on the "timeout value passed down" itself. - -TEST_CASE("绝不给 WaitForNotification 传 0(0 在 darwin 上是无限等待)") { +// On Darwin, libusb passes the timeout to IOKit as both noDataTimeout and completionTimeout, so a +// timeout of 0 means wait forever (AGENTS.md pitfalls 12 and 13). A Poll() that passed +// WaitForNotification(0) to mean "just probe" would hang the control loop in libusb_wait_for_event, +// unable even to respond to SIGTERM. The mock returns immediately for any timeout, so these tests +// assert on the timeout value passed down. + +TEST_CASE("never passes 0 to WaitForNotification (0 waits forever on Darwin)") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; - // Deliberately use a configuration that sets response_poll_interval_millis to 0 -- this is exactly the path where - // min(control_timeout, interval*4) in Transact() computed 0 back then. + // A zero response_poll_interval_millis is the path where min(control_timeout, interval*4) in + // Transact() would compute 0. auto config = FastConfig(); config.response_poll_interval_millis = 0; StateMachine machine(channel, observer, config); @@ -603,11 +613,12 @@ TEST_CASE("绝不给 WaitForNotification 传 0(0 在 darwin 上是无限等待 REQUIRE_FALSE(channel.NotificationTimeouts().empty()); for (const std::uint32_t timeout : channel.NotificationTimeouts()) { CHECK_MESSAGE(timeout > 0, - "WaitForNotification 收到了 0 —— 在 darwin 上等于无限等待,会卡死控制线程"); + "WaitForNotification got 0, which waits forever on Darwin and would hang the " + "control thread"); } } -TEST_CASE("kProbeOnlyTimeoutMillis 本身必须非零") { +TEST_CASE("kProbeOnlyTimeoutMillis is non-zero") { CHECK(kProbeOnlyTimeoutMillis > 0); } diff --git a/tests/test_version.cc b/tests/test_version.cc index 433c089..cf68121 100644 --- a/tests/test_version.cc +++ b/tests/test_version.cc @@ -5,12 +5,12 @@ TEST_SUITE("version") { -TEST_CASE("版本号非全零") { +TEST_CASE("the version is not all zeros") { const auto v = tetherkitnext::GetVersion(); CHECK((v.major != 0 || v.minor != 0 || v.patch != 0)); } -TEST_CASE("版本串包含项目名") { +TEST_CASE("the version string contains the project name") { const std::string_view s = tetherkitnext::GetVersionString(); CHECK(s.find("TetherKitNext") != std::string_view::npos); }