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/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..be3fac0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,19 +42,26 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-15, macos-26, macos-15-intel] + # xcode-27 is GitHub's macOS 27 (Golden Gate) image: Apple silicon only. + os: [macos-15, macos-26, macos-15-intel, xcode-27] steps: - - uses: actions/checkout@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" @@ -86,11 +93,21 @@ jobs: runs-on: macos-26 timeout-minutes: 45 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - - name: Select the newest Xcode + # Newest Xcode *26*, deliberately 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 @@ -126,7 +143,7 @@ jobs: fi plutil -p "$app/Contents/Library/LaunchDaemons/com.tetherkitnext.helperd.plist" - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: TetherKitNext-dmg path: | @@ -135,20 +152,27 @@ 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 + name: DMG on ${{ matrix.os }} needs: package - runs-on: macos-15-intel + 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,10 +181,11 @@ 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" # ---------------------------------------------------------------------------- @@ -180,7 +205,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,12 +237,60 @@ 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) + 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 on purpose. + 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. # ---------------------------------------------------------------------------- @@ -226,7 +299,9 @@ jobs: runs-on: macos-26 timeout-minutes: 45 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Build libusb run: ./scripts/build-libusb.sh "$PWD/build-tsan/libusb-universal" - name: Configure & build @@ -250,9 +325,12 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-15, macos-26, macos-15-intel] + # xcode-27 is GitHub's macOS 27 (Golden Gate) image: Apple silicon only. + os: [macos-15, macos-26, macos-15-intel, xcode-27] steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Build run: | ./scripts/build-libusb.sh "$PWD/build/libusb-universal" @@ -262,15 +340,18 @@ jobs: - name: Disable feth hardware checksum offload run: sudo sysctl -w net.link.fake.hwcsum=0 - name: Run 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 "需要 root 且需设置" abi.log; then + 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 - # kNetCreated. (The previous gate grepped for "创建了 feth", a string + # kNetCreated. (The previous gate grepped for a Chinese message ("feth created"), a string # that stopped existing when log messages were localized — it could # never pass.) if ! grep -q "created virtual interface feth" abi.log; then @@ -294,7 +375,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 +389,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 new file mode 100644 index 0000000..598722c --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,101 @@ +# CodeQL: static security analysis of the C++ driver/C ABI, the Swift app and +# root daemon, and these GitHub Actions workflows. Results appear under +# Security › Code scanning. +# +# Toolchain: macOS 26 + Xcode 26 on purpose. 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. +# +# libusb is built *before* `init`, so CodeQL traces only our own code. + +name: CodeQL + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: "27 3 * * 1" # weekly, so new queries also run on unchanged code + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + analyze: + name: CodeQL · ${{ matrix.language }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + permissions: + contents: read + actions: read + security-events: write + strategy: + fail-fast: false + matrix: + include: + - 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 + steps: + - 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" + + # The Swift package links libtetherkitnext, so build the C++ side first, + # outside the trace (the c-cpp job analyzes it). + - name: Build the C++ library for the Swift package (not analyzed) + if: matrix.language == 'swift' + run: | + 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: Initialize CodeQL + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + queries: security-extended + + - 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)" + + - name: Build Swift (traced) + if: matrix.language == 'swift' + run: TETHERKITNEXT_LIB_DIR="$PWD/build/lib" swift build --package-path gui + + - 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..96d26f5 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,130 @@ +# 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. +# +# 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: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ 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" + + clang-tidy: + name: clang-tidy (changed files, advisory) + if: github.event_name == 'pull_request' + runs-on: macos-26 + timeout-minutes: 30 + 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}" + + - name: Configure (compile_commands.json) + if: steps.files.outputs.list != '' + 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 + if: steps.files.outputs.list != '' + env: + FILES: ${{ steps.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..af66eef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -42,7 +42,9 @@ jobs: runs-on: macos-26 timeout-minutes: 90 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Check if release already exists id: existing @@ -90,10 +92,18 @@ jobs: exit 1 fi - - name: Select the newest Xcode + # Newest Xcode *26*, deliberately 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 @@ -154,6 +164,12 @@ 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) fi if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then # Creates the tag on the commit that was just built and tested. diff --git a/AGENTS.md b/AGENTS.md index 31692ed..f4f8d50 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,6 +98,7 @@ Verified on: macOS 26.5.1 (Darwin 25.5.0), Apple Silicon `arm64`, Apple Clang 21 TetherKitNext/ ├── AGENTS.md Agent and maintainer working memory ├── README.md User-facing documentation (English) +├── 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 +106,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 +122,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 +│ ├── Tests/ TetherKitNextIPCTests, TetherKitNextUIModelTests (XCTest) │ ├── Resources/ App-Info.plist, LaunchDaemon plist, AppIcon │ └── Scripts/ Build and helper uninstall scripts +├── scripts/ libusb build, release build, CI certificate import, DMG packaging (dmg/ assets) +├── .github/ CI + release workflows (SHA-pinned actions), Dependabot, release notes template ├── 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,12 +246,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)`: SHA-pinned CI actions, spawn fd hygiene, macOS 27 CI, AppKit-owned main window, SDK stamp, opt-in Advanced → Interfaces, local-link devices | 🚧 | Draft PR. libusb 1.0.30 still latest (hash re-verified). Local-link devices (drones, controllers, goggles, gadget boards): live `LinkAssessment`, passive peer IPv4 (`peer_address.h`, `tk_session_status_t.peer_ipv4`), service demotion when no router, session-only address. Then a deep cleanup: remaining Chinese translated (tests, CMake, benchmarks, CI), review-driven fixes (pitfalls 37-42), dead code removed. Then ideas from upstream XiaoMiku01/TetherKit PRs #6, #19, #22-#25 (pitfalls 43-44). See docs/MACOS-27.md, docs/ADVANCED-TOOLS.md, docs/LOCAL-DEVICES.md, SECURITY-AUDIT addendum | -### Current Status (TetherKitNext, 2026-10-06) +### Current Status (TetherKitNext, 2026-11-07) - **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). - **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. +- **Tests**: 24 CTest suites (incl. `core.peer_address`); SwiftPM suites `TetherKitNextIPCTests` and `TetherKitNextUIModelTests` (panes, interface traffic, link assessment). Test names and messages are English; only test data that checks multibyte handling or the zh table itself is Chinese. +- **CI**: 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; 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). ### Historical Upstream Status (Recorded at v0.1.5) @@ -367,6 +377,25 @@ 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. --- diff --git a/CMakeLists.txt b/CMakeLists.txt index 57363e1..0c4fa38 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.24) project( TetherKitNext VERSION 1.2.0 - DESCRIPTION "macOS 用户态 RNDIS 驱动:libusb + feth + BPF" + DESCRIPTION "User-space RNDIS driver for macOS: libusb + feth + BPF" LANGUAGES CXX) # ------------------------------------------------------------------------------ @@ -12,7 +12,7 @@ project( # 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() # ------------------------------------------------------------------------------ @@ -38,14 +38,14 @@ 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. @@ -68,15 +68,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) @@ -125,7 +125,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 +136,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/README.md b/README.md index 593f55b..65c83e5 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 @@ -123,7 +139,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,6 +157,33 @@ 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. +### 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 and tells you when there's a new version. You can turn this off in Settings. It never downloads or installs anything by itself. @@ -181,7 +230,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 +253,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. diff --git a/benchmarks/bench_common.cc b/benchmarks/bench_common.cc index 4b5041e..149fcde 100644 --- a/benchmarks/bench_common.cc +++ b/benchmarks/bench_common.cc @@ -245,48 +245,50 @@ 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". 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..8ea01e8 100644 --- a/benchmarks/bench_main.cc +++ b/benchmarks/bench_main.cc @@ -23,24 +23,26 @@ int main() { 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 @@ -48,17 +50,18 @@ int main() { 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)"); + 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..7a8e88b 100644 --- a/benchmarks/bench_net.cc +++ b/benchmarks/bench_net.cc @@ -130,7 +130,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; @@ -245,7 +245,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 +253,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,7 +277,7 @@ 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(); @@ -288,12 +288,12 @@ bool RegisterNetBenchmarks(Runner& runner, std::string& skip_reason) { 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 +301,28 @@ 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); }); + 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; } diff --git a/benchmarks/bench_rndis.cc b/benchmarks/bench_rndis.cc index 2cf4973..da4f101 100644 --- a/benchmarks/bench_rndis.cc +++ b/benchmarks/bench_rndis.cc @@ -166,18 +166,17 @@ void RegisterRndisBenchmarks(Runner& runner) { // 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", + 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); }); @@ -185,21 +184,20 @@ void RegisterRndisBenchmarks(Runner& runner) { // 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..32cfed7 100644 --- a/benchmarks/harness.cc +++ b/benchmarks/harness.cc @@ -82,21 +82,22 @@ 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; @@ -112,8 +113,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..36214a3 100644 --- a/benchmarks/harness.h +++ b/benchmarks/harness.h @@ -99,7 +99,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; diff --git a/cmake/Optimizations.cmake b/cmake/Optimizations.cmake index 99e9f9e..5436ba9 100644 --- a/cmake/Optimizations.cmake +++ b/cmake/Optimizations.cmake @@ -29,7 +29,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 +40,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..819c86c 100644 --- a/cmake/Sanitizers.cmake +++ b/cmake/Sanitizers.cmake @@ -12,7 +12,7 @@ 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 "") @@ -37,7 +37,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/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/GUI-ARCHITECTURE.md b/docs/GUI-ARCHITECTURE.md index 6601894..3fce44c 100644 --- a/docs/GUI-ARCHITECTURE.md +++ b/docs/GUI-ARCHITECTURE.md @@ -73,8 +73,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 +│ ├── TetherKitNextUIModel/ Testable UI logic: sidebar panes, interface traffic sampling +│ └── TetherKitNextApp/ SwiftUI application (main window owned by MainWindowController) ├── Tests/TetherKitNextIPCTests/ Auth token lifetime, code signing, and i18n placeholder tests +├── Tests/TetherKitNextUIModelTests/ Sidebar/selection rules, rate tracker, live getifaddrs/sysctl smoke ├── Resources/ App-Info.plist, LaunchDaemon plist, AppIcon └── Scripts/ GUI packaging and helper uninstallation scripts ``` @@ -159,6 +161,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,17 +182,13 @@ 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. - -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. +`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 pre-1.0 installer based on `AuthorizationExecuteWithPrivileges` and a setuid trampoline was removed in 1.0; docs/GUI-SPIKE.md keeps its history. ### 4.10 Update Checker (`UpdateChecker.swift`) @@ -280,6 +282,7 @@ Troubleshooting quick reference: | 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`). | +| Double-clicking Finder icon does nothing in Menu Bar Only mode | Fixed: with the AppKit-owned main window `applicationShouldHandleReopen` reaches `AppDelegate` and reopens it. | +| 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/LOCAL-DEVICES.md b/docs/LOCAL-DEVICES.md new file mode 100644 index 0000000..0139b71 --- /dev/null +++ b/docs/LOCAL-DEVICES.md @@ -0,0 +1,83 @@ +# 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**. + +## What goes wrong without this + +| Device behavior | Old result | +|---|---| +| No DHCP server (fixed address) | "DHCP got no lease within 10 s" alert: looks broken. | +| DHCP without a router | Connected but "no internet". With *Route all traffic* on, our service stayed **first in the service order**, so the device could outrank the Mac's real internet. | +| Fixed address | The user had to guess the device's subnet. | + +## 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..fe3e1e8 --- /dev/null +++ b/docs/MACOS-27.md @@ -0,0 +1,110 @@ +# macOS 27 Golden Gate compatibility review + +Date: 2026-11-07 · Sources: Apple's [macOS 27](https://developer.apple.com/documentation/macos-release-notes/macos-27-release-notes), +[27.2](https://developer.apple.com/documentation/macos-release-notes/macos-27_2-release-notes) and +[27.3 beta](https://developer.apple.com/documentation/macos-release-notes/macos-27_3-release-notes) release notes. + +Every release-note item that touches something TetherKitNext uses was checked +against the code. **None of the documented changes breaks TetherKitNext.** +One item (launchd and quarantined property lists) needs a check on a real +machine before release, because the notes don't say whether it covers +`SMAppService` daemons inside a notarized app. + +## How support is verified + +| Layer | How | Status | +|---|---|---| +| C++ driver builds with `-Werror`, all CTest suites pass | CI `native` job on the `xcode-27` runner (macOS 27, Apple silicon) | Automated | +| Private kernel ABI (`if_fake` peer pairing, BPF private ioctls) | CI `abi-check` job on `xcode-27`: creates, pairs and destroys a real `feth` pair as root | Automated | +| GUI builds against the macOS 27 SDK (Swift 6, Xcode 27's `@State` macro) and its unit tests pass | CI `gui-macos-27` job | Automated | +| The bundled app launches and stays up | CI `gui-macos-27` launch smoke test | Automated | +| Real RNDIS session (Android phone) on macOS 27 | Manual, on hardware | **Open** | +| Downloaded, notarized DMG installs and the background component registers | Manual, on hardware | **Open** (see launchd item) | + +Say "runs on macOS 27 Golden Gate" once all CI jobs above are green **and** +the two manual items are ticked. + +## 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 now applies to us because the app is stamped with the macOS 26+ SDK (see below). | +| **SwiftUI `@State` macro** (105893279, Xcode 27) | `@State` becomes a macro. A value set both at the declaration and in an initializer no longer compiles, and neither does the synthesized private memberwise init. | None found: every `@State` has an initial value and no initializer assigns it. The `gui-macos-27` CI job compiles the GUI with Xcode 27. | +| **System Integrity Protection / TCC** | Other teams' app containers are denied by default; the TCC database can't be read directly. | None. We touch neither. | +| **Network Security** (176055825) | Stricter TLS requirements for system MDM / install / update processes. | None. Only system processes are affected. Our one outbound call (the optional GitHub release check) is TLS 1.3. | +| **DriverKit / SCSIControllerDriverKit** (27.3) | API additions and deprecations. | None. We ship no driver extension. | +| **NEURLFilter** (27.3) | Info.plist requirements for URL filter providers. | None. We ship no network extension. | + +## Related change: SDK stamp and window chrome + +macOS 26 and later choose the window chrome (traffic-light size and spacing, +title bar metrics, Liquid Glass) from the `sdk` field of the executable's +`LC_BUILD_VERSION`, not from what the code was compiled against. A SwiftPM +link can stamp the deployment target (14.0) there, which gives the whole app +the compatibility look. `gui/Scripts/build-gui.sh` now reads the stamp after +linking. If it is older than the SDK in use, the script rewrites only `sdk` +with `vtool`, using the SDK version actually in use (nothing hard-coded); +`minos` stays 14.0. The script then fails the build if the shipped binary +isn't stamped with SDK 26 or later. Check it on any build: + +```bash +otool -l dist/TetherKitNext.app/Contents/MacOS/TetherKitNext | grep -A4 LC_BUILD_VERSION +``` + +## Backward compatibility of this change + +Deployment targets are unchanged: the app needs macOS 14.0 +(`LSMinimumSystemVersion`, `platforms: [.macOS(.v14)]`); the CLI and +`libtetherkitnext` need 13.3. Every API this change adds was checked against +Apple's availability data: + +| API | Introduced | Used in | +|---|---|---| +| `NSHostingController.sceneBridgingOptions` | macOS 14.0 | `MainWindowController` | +| `NSHostingController.sizingOptions`, `.minSize` | macOS 13.0 | `MainWindowController` | +| `NSWindow.toolbarStyle` | macOS 11.0 | `MainWindowController` | +| `NSApplication.activate()` | macOS 14.0 | `MainWindowController.present` (already used before) | +| `Scene.commands` on `MenuBarExtra` | macOS 13.0 (`MenuBarExtra`) | `TetherKitNextApplication` | +| `ContinuousClock`, `Duration.components` | macOS 13.0 | `InterfaceMonitor` | +| `UnsafeRawPointer.loadUnaligned` | inlinable, back-deploys to all | `InterfaceSampler.counters64` | +| `getifaddrs`, `NET_RT_IFLIST2` / `if_msghdr2`, `if_indextoname` | Mac OS X era | `InterfaceSampler` | +| `POSIX_SPAWN_CLOEXEC_DEFAULT`, `posix_spawn_file_actions_addopen` | Mac OS X 10.7 | `process_runner.cc` | + +Behavior notes for older systems: + +* **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.** The sidebar selection moved from `@SceneStorage` to a + new `@AppStorage` key and the window frame to a new autosave name. On the + first launch after upgrading, the app opens on Overview at the default size. +* **CLI.** The only C++ change is the spawn flag and stdin. It is 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/SECURITY-AUDIT.md b/docs/SECURITY-AUDIT.md index cb459a9..3e1ef2b 100644 --- a/docs/SECURITY-AUDIT.md +++ b/docs/SECURITY-AUDIT.md @@ -153,3 +153,71 @@ a string that disappeared when log messages were localized. It now pins of people who can act is unchanged. The residual risk moves to the app: a bug that skips `UserPresence.confirm` before a privileged call would skip the prompt. Keep every privileged call behind `AppModel.authorized`. + +--- + +## Addendum: 2026-11-07 re-scan + +Re-scan prompted by the recent run of supply-chain attacks (hijacked +GitHub Action tags, poisoned release tarballs). Base: `2e92841` (1.2.0). + +### Dependencies + +| Component | Pinned | Latest upstream | Verdict | +|---|---|---|---| +| libusb | 1.0.30 (`scripts/build-libusb.sh`) | **1.0.30** (2026-05-17); no newer release or release candidate | Up to date. The pinned SHA-256 was re-checked against the GitHub release asset: `fea36f34…dbaf`, match. | +| doctest | 2.4.12 (vendored, test-only) | n/a | Not shipped. | + +libusb `master` has darwin fixes since 1.0.30 (interface claim/re-claim +bookkeeping after a failed state restore, run-loop reference handling, +parent-session refresh on re-enumeration) and a memory-safety fix in +`libusb_get_port_numbers` (`1110f3a`, a write before the caller's array +when a re-enumerated device's parent chain grows between two passes). +TetherKitNext calls none of `libusb_get_port_numbers`, +`libusb_set_configuration` or `libusb_reset_device`, so none of these is +reachable from our code. **Decision: stay on the signed 1.0.30 release** and +take 1.0.31 when it is tagged, rather than shipping an untagged snapshot. + +### CI supply chain (fixed) + +**S1. GitHub Actions were referenced by mutable tags** (`actions/checkout@v5`, +…). A moved tag runs new code in jobs that hold the Developer ID certificate +and notary key. All `uses:` are now pinned to full commit SHAs (same major +versions, latest patch: checkout v5.1.0, cache v4.3.0, upload-artifact v4.6.2, +download-artifact v4.3.0), with `.github/dependabot.yml` proposing updates. + +**S2. `actions/checkout` persisted the job token in `.git/config`.** No job +pushes with git (the prerelease job uses `GH_TOKEN` via `gh`), so every +checkout now sets `persist-credentials: false`; a compromised build step can +no longer read the token from disk. + +Reviewed and fine: workflow-level `permissions: contents: read` with +`contents: write` only on the release/prerelease jobs; no +`pull_request_target`; secrets only reach non-PR events, so fork PRs build +ad-hoc signed; the libusb tarball is hash-verified before use. + +### Code (fixed) + +**L3. Root child processes inherited every open descriptor.** +`posix_spawn` without `POSIX_SPAWN_CLOEXEC_DEFAULT` passes the daemon's +descriptors that lack `FD_CLOEXEC` (BPF device, routing / `feth` sockets, +libusb's internal pipes) to `ipconfig` and `route`. Those are +Apple binaries, so this was not exploitable on its own, but a root process +should hand a child exactly stdin/stdout/stderr. `process_runner.cc` now sets +`POSIX_SPAWN_CLOEXEC_DEFAULT` and gives the child `/dev/null` as stdin. + +### Re-reviewed with no new issue + +* RNDIS decoding of device data (`packet_codec.h`, `messages.cc`): 64-bit + bounds arithmetic, `MessageLength ≥ 44` guarantees forward progress, + alignment factor and transfer size clamps intact. +* XPC: Team-ID requirement on every connection for signed builds; privileged + calls re-verify an authorization or the presence path (`admin` group); + unauthenticated calls are read-only (`queryNetwork` validates the interface + name in the C ABI). +* CLI symlink: `lstat`/`readlink`/`symlink` never follow links; foreign + entries are reported, not replaced. +* New in this change: the Advanced → Interfaces page reads `getifaddrs` and + the `NET_RT_IFLIST2` sysctl in the unprivileged app. It parses kernel data + with bounds checks (`ifm_msglen` validated against the buffer before each + step) and sends nothing to the daemon or the network. diff --git a/gui/Package.swift b/gui/Package.swift index 6b063e6..9ec19f0 100644 --- a/gui/Package.swift +++ b/gui/Package.swift @@ -103,9 +103,17 @@ let package = Package( // The SwiftUI App that users see (running as an ordinary user). .executableTarget(name: "TetherKitNextApp", - dependencies: ["TetherKitNextCore", "TetherKitNextIPC"]), + dependencies: ["TetherKitNextCore", "TetherKitNextIPC", + "TetherKitNextUIModel"]), + + // UI logic that deserves unit tests: sidebar composition and + // persisted-selection rules, interface traffic sampling. A library of + // its own because an executable target cannot be @testable-imported. + // No libtetherkitnext dependency, so its tests run without the C++ build. + .target(name: "TetherKitNextUIModel", dependencies: ["TetherKitNextIPC"]), - // Tests only TetherKitNextIPC: it is the only "pure logic, touches no hardware and needs no root" layer. + // Tests cover the pure-logic layers (TetherKitNextIPC, TetherKitNextUIModel): no hardware, no root. // Tests of sessions and NIC configuration are on the C++ side (tests/test_capi.cc), and are not repeated here. .testTarget(name: "TetherKitNextIPCTests", dependencies: ["TetherKitNextIPC"]), + .testTarget(name: "TetherKitNextUIModelTests", dependencies: ["TetherKitNextUIModel"]), ]) diff --git a/gui/Resources/App-Info.plist b/gui/Resources/App-Info.plist index 55ed1bf..cc7d02f 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 diff --git a/gui/Scripts/build-gui.sh b/gui/Scripts/build-gui.sh index 4d9d841..6b9e2e8 100755 --- a/gui/Scripts/build-gui.sh +++ b/gui/Scripts/build-gui.sh @@ -80,13 +80,54 @@ swift_build() { ${SWIFT_BUILD_FLAGS[@]+"${SWIFT_BUILD_FLAGS[@]}"} "${@:2}" } +# ------------------------------------------------------------------------------ +# SDK stamp (LC_BUILD_VERSION). +# +# macOS 26+ picks a window's chrome (traffic lights, title bar metrics, glass) +# from the `sdk` field of the executable's LC_BUILD_VERSION, independently of +# what was actually compiled against: an app stamped with an older SDK gets the +# compatibility ("legacy") appearance. Xcode stamps the SDK in use; a SwiftPM +# link can end up stamping the deployment target instead. The deployment +# target (`minos`) is what decides where the app runs and is left untouched. +# +# Read both fields, and if the stamp is older than the SDK we just built with, +# rewrite only `sdk` (vtool, Xcode command line tools). The bundle is signed +# afterwards, so invalidating the linker's ad-hoc signature here is harmless. +# ------------------------------------------------------------------------------ +SDK_VERSION="$(xcrun --sdk macosx --show-sdk-version)" +SDK_MAJOR="${SDK_VERSION%%.*}" + +build_version_field() { # + otool -l "$1" | awk -v field="$2" ' + $1 == "cmd" && $2 == "LC_BUILD_VERSION" { inside = 1; next } + $1 == "cmd" { inside = 0 } + inside && $1 == field { print $2; exit }' +} + +stamp_sdk() { # + local minos sdk + minos="$(build_version_field "$1" minos)" + sdk="$(build_version_field "$1" sdk)" + [[ -n "${minos}" && -n "${sdk}" ]] || die "no LC_BUILD_VERSION in $1" + if [[ "${sdk%%.*}" -lt "${SDK_MAJOR}" ]]; then + echo " sdk stamp ${sdk} -> ${SDK_VERSION} (minos ${minos} unchanged): $(basename "$1")" + vtool -set-build-version macos "${minos}" "${SDK_VERSION}" -replace -output "$2" "$1" + else + cp "$1" "$2" + fi +} + +STAMP_DIR="$(mktemp -d)" +trap 'rm -rf "${STAMP_DIR}"' EXIT + APP_SLICES=() HELPER_SLICES=() for arch in "${ARCHS[@]}"; do log "Compiling Swift targets for ${arch}" swift_build "${arch}" bin_path="$(swift_build "${arch}" --show-bin-path)" - APP_SLICES+=("${bin_path}/TetherKitNextApp") + stamp_sdk "${bin_path}/TetherKitNextApp" "${STAMP_DIR}/TetherKitNextApp-${arch}" + APP_SLICES+=("${STAMP_DIR}/TetherKitNextApp-${arch}") HELPER_SLICES+=("${bin_path}/tetherkitnext-helper") done @@ -234,6 +275,18 @@ ln -s "${CONTENTS}/MacOS/tetherkitnext-cli" "${probe_dir}/tetherkitnext-cli" rm -rf "${probe_dir}" echo " ✓ CLI runs through a symlink" +# The SDK stamp decides the window chrome on macOS 26+ (see "SDK stamp" above). +# Checked on the final, signed binary so a later step cannot silently undo it. +for arch in "${ARCHS[@]}"; do + thin="${STAMP_DIR}/verify-${arch}" + lipo -thin "${arch}" "${CONTENTS}/MacOS/TetherKitNext" -output "${thin}" 2>/dev/null \ + || cp "${CONTENTS}/MacOS/TetherKitNext" "${thin}" + stamped="$(build_version_field "${thin}" sdk)" + [[ "${stamped%%.*}" -ge 26 ]] \ + || die "TetherKitNext (${arch}) is stamped sdk ${stamped:-none}; macOS 26+ would draw legacy window chrome" +done +echo " ✓ app is stamped with the macOS ${SDK_VERSION} SDK (modern window chrome on macOS 26+)" + cat < 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 @@ -338,12 +327,21 @@ final class AppModel { } helperAvailability = .available(version: version) helperVersionMismatch = Self.versionMismatch(installed: version, build: build) + // A daemon that just appeared (installed, 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. if isRestartingHelper { return } + languageSyncedDaemon = nil helperAvailability = .missing(reason: error.localizedDescription) helperVersionMismatch = nil helperNeedsApproval = HelperInstaller.needsApproval @@ -406,11 +404,17 @@ final class AppModel { 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 } @@ -453,6 +457,77 @@ 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: 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 that have 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 session-only address and the auto-configure note are cleared by the apply + /// itself, and only if it succeeds. + func retrySavedNetworkConfiguration() async { + await applyNetworkConfiguration() + } + var selectedDevice: DeviceDescriptor? { if let selectedDeviceID { return devices.first { $0.id == selectedDeviceID } @@ -483,11 +558,18 @@ final class AppModel { isBusy = true defer { isBusy = false } + // 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 } @@ -541,8 +623,17 @@ 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 without a 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 } } @@ -574,12 +665,17 @@ 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. 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. @@ -594,11 +690,15 @@ 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). @@ -607,6 +707,9 @@ final class AppModel { 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. @@ -674,6 +777,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() diff --git a/gui/Sources/TetherKitNextApp/DesignSystem.swift b/gui/Sources/TetherKitNextApp/DesignSystem.swift index a29f91a..3a363d4 100644 --- a/gui/Sources/TetherKitNextApp/DesignSystem.swift +++ b/gui/Sources/TetherKitNextApp/DesignSystem.swift @@ -207,20 +207,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)) diff --git a/gui/Sources/TetherKitNextApp/HelperClient.swift b/gui/Sources/TetherKitNextApp/HelperClient.swift index 3d1126e..c481211 100644 --- a/gui/Sources/TetherKitNextApp/HelperClient.swift +++ b/gui/Sources/TetherKitNextApp/HelperClient.swift @@ -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 } @@ -47,7 +42,7 @@ 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. + /// 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? @@ -96,11 +91,29 @@ final class HelperClient: @unchecked Sendable { // 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 } + // + // 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 @@ -114,6 +127,13 @@ final class HelperClient: @unchecked Sendable { ) 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)) } diff --git a/gui/Sources/TetherKitNextApp/HelperInstaller.swift b/gui/Sources/TetherKitNextApp/HelperInstaller.swift index b465a81..9e2d505 100644 --- a/gui/Sources/TetherKitNextApp/HelperInstaller.swift +++ b/gui/Sources/TetherKitNextApp/HelperInstaller.swift @@ -60,6 +60,7 @@ enum HelperInstaller { /// 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 { @@ -70,6 +71,24 @@ enum HelperInstaller { } } + /// 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 drop + /// the attribute from this one file before registering (as XiaoMiku01/TetherKit#6 + /// does for its installer). 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. /// diff --git a/gui/Sources/TetherKitNextApp/MainWindowController.swift b/gui/Sources/TetherKitNextApp/MainWindowController.swift new file mode 100644 index 0000000..099005f --- /dev/null +++ b/gui/Sources/TetherKitNextApp/MainWindowController.swift @@ -0,0 +1,143 @@ +import AppKit +import SwiftUI +import TetherKitNextIPC + +/// Owns the main window as a plain AppKit `NSWindow`. +/// +/// ★ Why not a SwiftUI `Window` scene ★ +/// +/// * With a `MenuBarExtra` alongside, SwiftUI recreates a closed `Window` +/// scene whenever the windowless app is activated, which clicking the menu +/// bar item does. Dismissing the resurrected window after the fact still let +/// it flash. With no window scene, SwiftUI has nothing to resurrect. +/// * Presentation becomes deterministic: the window exists from +/// `applicationDidFinishLaunching`, also for bare `swift run` binaries, and +/// `applicationShouldHandleReopen` (Dock / Finder double-click while in +/// menu-bar-only mode) reaches us, so reopening brings it back. +/// +/// SwiftUI still renders everything inside it: an `NSHostingController` +/// with toolbar and title bridging, so `.toolbar` / `.navigationTitle` in +/// ContentView keep working. +/// +/// ★ Closing ★ +/// +/// `isReleasedWhenClosed = false`: the red button, File ▸ Close (⌘W) and +/// `close()` only order the window out. The SwiftUI view tree stays alive +/// (cheap, and reopening is instant); AppDelegate's window notifications +/// drop the app to the `.accessory` policy (menu-bar-only mode). +/// +/// ★ Size stability ★ +/// +/// `sizingOptions = [.minSize]`: the hosting controller pushes only the +/// content's minimum size into the window. Its default also publishes the +/// preferred (intrinsic) size, and pages have different intrinsic heights, +/// so switching pages would resize the window, which macOS 26 animates in +/// step with the content change. Set before the controller becomes the +/// window's content, so the first layout already uses it. +@MainActor +final class MainWindowController: NSObject, NSWindowDelegate { + /// Set once at launch by AppDelegate; nil only before that. + private(set) static var shared: MainWindowController? + + private let model: AppModel + private let window: NSWindow + + /// Frame autosave name: the window reopens where the user left it. + private static let autosaveName = "TetherKitNextMainWindow" + + static func install(model: AppModel) -> MainWindowController { + if let shared { return shared } + let controller = MainWindowController(model: model) + shared = controller + return controller + } + + private init(model: AppModel) { + self.model = model + + let hosting = NSHostingController(rootView: MainWindowRoot(model: model)) + hosting.sizingOptions = [.minSize] + hosting.sceneBridgingOptions = [.toolbars, .title] + + window = NSWindow( + contentRect: NSRect(x: 0, y: 0, + width: Design.Window.defaultWidth, + height: Design.Window.defaultHeight), + styleMask: [.titled, .closable, .miniaturizable, .resizable, + .fullSizeContentView], + backing: .buffered, + defer: false) + window.title = "TetherKitNext" + window.toolbarStyle = .unified + window.isReleasedWhenClosed = false + window.contentMinSize = NSSize(width: Design.Window.minWidth, + height: Design.Window.minHeight) + window.contentViewController = hosting + // contentViewController adopts the controller's view size; put the + // design size back before restoring any saved frame. + window.setContentSize(NSSize(width: Design.Window.defaultWidth, + height: Design.Window.defaultHeight)) + window.center() + window.setFrameAutosaveName(Self.autosaveName) + + super.init() + window.delegate = self + } + + var isVisible: Bool { window.isVisible || window.isMiniaturized } + + /// Shows the window and brings the app forward. Idempotent: safe from + /// launch, the menu bar panel, and Dock / Finder reopen alike. + func present() { + if NSApp.activationPolicy() != .regular { + NSApp.setActivationPolicy(.regular) + } + if window.isMiniaturized { + window.deminiaturize(nil) + } + window.makeKeyAndOrderFront(nil) + NSApp.activate() + } + + /// File ▸ Close (⌘W). A minimized main window is never key, so + /// `NSApp.keyWindow?.performClose` alone would do nothing for it; fall + /// back to closing the main window when nothing else is key. + func closeFrontWindow() { + if let key = NSApp.keyWindow { + key.performClose(nil) + } else if window.isMiniaturized { + window.close() + } + } + + // MARK: NSWindowDelegate + + func windowDidBecomeKey(_ notification: Notification) { + model.windowDidAppear() + } + + func windowWillClose(_ notification: Notification) { + model.windowDidDisappear() + } + + func windowDidMiniaturize(_ notification: Notification) { + model.windowDidDisappear() + } + + func windowDidDeminiaturize(_ notification: Notification) { + model.windowDidAppear() + } +} + +/// The SwiftUI content of the main window. +private struct MainWindowRoot: View { + var model: AppModel + + var body: some View { + ContentView(model: model) + .frame(minWidth: Design.Window.minWidth, minHeight: Design.Window.minHeight) + // Rebuild on a language switch (SwiftUI cannot see the global + // string table change; docs/GUI-ARCHITECTURE.md). + .id(model.languageRevision) + } +} diff --git a/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift b/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift index 94c546c..c027070 100644 --- a/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift +++ b/gui/Sources/TetherKitNextApp/TetherKitNextApp.swift @@ -19,36 +19,28 @@ import TetherKitNextIPC @main struct TetherKitNextApplication: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate - @State private var model = AppModel() var body: some Scene { - // Window, not WindowGroup: one connection panel. Several windows would - // just poll the same daemon several times. - Window("TetherKitNext", id: WindowID.main) { - MainWindowRoot(model: model) - } - .defaultSize(width: Design.Window.defaultWidth, height: Design.Window.defaultHeight) - .windowResizability(.contentMinSize) - .windowToolbarStyle(.unified) - .commands { - CommandGroup(replacing: .newItem) {} - CommandGroup(replacing: .appInfo) { AboutMenuItem(model: model) } - CommandGroup(after: .appInfo) { AppMenuItems(model: model) } - } - + // No Window scene: the main window is an AppKit NSWindow owned by + // MainWindowController (see there for why). The menu bar extra is the + // only SwiftUI scene; app-wide commands attach to it. MenuBarExtra { - MenuBarPanel(model: model) + MenuBarPanel(model: appDelegate.model) } label: { - MenuBarLabel(model: model) + MenuBarLabel(model: appDelegate.model) } .menuBarExtraStyle(.window) + .commands { + CommandGroup(replacing: .newItem) {} + // Without a Window scene SwiftUI provides no File ▸ Close; ⌘W + // hides the window like the red button (menu-bar-only mode). + CommandGroup(after: .newItem) { CloseWindowMenuItem(model: appDelegate.model) } + CommandGroup(replacing: .appInfo) { AboutMenuItem(model: appDelegate.model) } + CommandGroup(after: .appInfo) { AppMenuItems(model: appDelegate.model) } + } } } -enum WindowID { - static let main = "main" -} - /// Keeps the Dock icon in sync with the main window. /// /// The previous implementation flipped the activation policy from SwiftUI's @@ -58,9 +50,40 @@ enum WindowID { /// visible, non-panel window → `.regular`; none → `.accessory`. @MainActor final class AppDelegate: NSObject, NSApplicationDelegate { + /// The single app model, shared by the main window and the menu bar + /// extra. Owned here (not by the App struct) because the AppKit-owned + /// main window is created from `applicationDidFinishLaunching`. + let model = AppModel() private var observers: [NSObjectProtocol] = [] + /// 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) { + 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 +103,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { false } + /// Dock icon click or Finder double-click while the app is running. + /// Reaches us now that SwiftUI owns no window scene; reopen the main + /// window instead of doing nothing (menu-bar-only mode has no Dock icon, + /// but a Finder double-click still lands here). + func applicationShouldHandleReopen(_ sender: NSApplication, + hasVisibleWindows flag: Bool) -> Bool { + if !(MainWindowController.shared?.isVisible ?? true) { + MainWindowController.shared?.present() + } + return true + } + static func updateActivationPolicy(excluding closing: NSWindow? = nil) { let hasAppWindow = NSApp.windows.contains { window in window !== closing && isAppWindow(window) @@ -155,39 +190,13 @@ struct LanguagePicker: View { } } -private struct MainWindowRoot: View { +/// File ▸ Close (⌘W). +private struct CloseWindowMenuItem: View { var model: AppModel - @Environment(\.dismissWindow) private var dismissWindow var body: some View { - ContentView(model: model) - .frame(minWidth: Design.Window.minWidth, minHeight: Design.Window.minHeight) - .id(model.languageRevision) - .task { - model.start() - } - .onAppear { - // SwiftUI resurrects the Window scene when a windowless app is - // activated (clicking the menu bar item does that). Only keep - // windows we asked for. - guard model.isWindowPresentationExpected() else { - dismissWindow(id: WindowID.main) - return - } - model.windowDidAppear() - AppDelegate.updateActivationPolicy() - } - .onDisappear { - model.windowDidDisappear() - } + let _ = model.languageRevision + Button(L(.closeWindow)) { MainWindowController.shared?.closeFrontWindow() } + .keyboardShortcut("w") } } - -/// Opens (or brings forward) the main window from the menu bar. -@MainActor -func presentMainWindow(_ model: AppModel, _ openWindow: OpenWindowAction) { - model.expectWindowPresentation() - NSApp.setActivationPolicy(.regular) - openWindow(id: WindowID.main) - NSApp.activate() -} diff --git a/gui/Sources/TetherKitNextApp/Views/ContentView.swift b/gui/Sources/TetherKitNextApp/Views/ContentView.swift index d7e0b2d..bbab361 100644 --- a/gui/Sources/TetherKitNextApp/Views/ContentView.swift +++ b/gui/Sources/TetherKitNextApp/Views/ContentView.swift @@ -1,46 +1,25 @@ import AppKit import SwiftUI import TetherKitNextIPC - -/// Sidebar destinations. -/// -/// The old single dashboard crammed five cards into one screen under a hard -/// "fits in 700 pt" budget. Splitting by task — look at the connection, pick a -/// device, set up addressing, read logs, manage the app — gives each page room -/// and makes the window resizable without layout gymnastics. -enum Pane: String, CaseIterable, Identifiable, Hashable { - case overview, device, network, activity, settings - - var id: Self { self } - - var title: String { - switch self { - case .overview: return L(.paneOverview) - case .device: return L(.paneDevice) - case .network: return L(.paneNetwork) - case .activity: return L(.paneActivity) - case .settings: return L(.paneSettings) - } - } - - var symbol: String { - switch self { - case .overview: return "gauge.with.dots.needle.67percent" - case .device: return "cable.connector" - case .network: return "network" - case .activity: return "list.bullet.rectangle" - case .settings: return "gearshape" - } - } -} +import TetherKitNextUIModel struct ContentView: View { @Bindable var model: AppModel - @SceneStorage("selectedPane") private var pane: Pane = .overview + // @AppStorage rather than @SceneStorage: the window is an AppKit-owned + // NSWindow (MainWindowController), which has no SwiftUI scene to store in. + @AppStorage(PreferenceKey.selectedPane) private var storedPane = Pane.overview.rawValue + @AppStorage(PreferenceKey.advancedToolsEnabled) private var advancedToolsEnabled = false @State private var confirmingHelperUninstall = false @State private var confirmingHelperUpdate = false + /// The selected page. Resolution drops stale values (renamed pages, an + /// advanced page after advanced tools were turned off) to the overview. + private var pane: Pane { + get { Pane.resolveStored(storedPane, advancedToolsEnabled: advancedToolsEnabled) } + nonmutating set { storedPane = newValue.rawValue } + } + var body: some View { Group { if model.helperAvailability.isAvailable { @@ -50,6 +29,13 @@ struct ContentView: View { } } .animation(.smooth(duration: 0.25), value: model.helperAvailability) + .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 +78,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 +134,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 +147,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, @@ -258,7 +251,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/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/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/MenuBarPanel.swift b/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift index e598bfc..1ef3cba 100644 --- a/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift +++ b/gui/Sources/TetherKitNextApp/Views/MenuBarPanel.swift @@ -34,7 +34,6 @@ struct MenuBarLabel: View { /// (open the main window, quit). Configuration, charts and logs all stay in the main window -- the panel is not a second UI. struct MenuBarPanel: View { var model: AppModel - @Environment(\.openWindow) private var openWindow @Environment(\.dismiss) private var dismiss private var status: SessionStatus { model.status } @@ -78,7 +77,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,7 +119,7 @@ struct MenuBarPanel: View { HStack { Button(L(.openMainWindow)) { dismiss() - presentMainWindow(model, openWindow) + MainWindowController.shared?.present() } .secondaryActionButtonStyle() .controlSize(.small) diff --git a/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift b/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift index 343e9a3..c506044 100644 --- a/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/NetworkCard.swift @@ -135,15 +135,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") } diff --git a/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift b/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift index 803cc89..860a257 100644 --- a/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift +++ b/gui/Sources/TetherKitNextApp/Views/SettingsPage.swift @@ -10,6 +10,13 @@ enum PreferenceKey { static let menuBarShowsSpeed = "menuBarShowsSpeed" /// Existing key: `defaults write com.tetherkitnext.app updateCheckDisabled -bool YES`. static let updateCheckDisabled = "updateCheckDisabled" + /// Opt-in "Advanced" sidebar section (network diagnostics). Off by default + /// so everyday users only ever see the tethering flow. + static let advancedToolsEnabled = "advancedToolsEnabled" + /// Interfaces page: also list interfaces that are down or have no address. + static let interfacesShowInactive = "interfacesShowInactive" + /// Last selected sidebar page (`Pane.rawValue`). + static let selectedPane = "selectedPane" } /// Everything about the app itself, gathered in one place instead of @@ -22,6 +29,7 @@ struct SettingsPage: View { @AppStorage(PreferenceKey.menuBarShowsSpeed) private var menuBarShowsSpeed = true @AppStorage(PreferenceKey.updateCheckDisabled) private var updateCheckDisabled = false @AppStorage(AppModel.autoConfigureNetworkKey) private var autoConfigureNetwork = true + @AppStorage(PreferenceKey.advancedToolsEnabled) private var advancedToolsEnabled = false @State private var launchAtLogin = SMAppService.mainApp.status == .enabled @State private var showingLicenses = false @State private var copiedPayPal = false @@ -135,11 +143,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() diff --git a/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift b/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift index 98b660c..ceff2a4 100644 --- a/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/StatusHeroCard.swift @@ -32,7 +32,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 { diff --git a/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift b/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift index 174de02..ad27ac9 100644 --- a/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift +++ b/gui/Sources/TetherKitNextApp/Views/ThroughputCard.swift @@ -97,6 +97,9 @@ 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. .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). From XiaoMiku01/TetherKit#25. + .animation(nil, value: model.throughputHistory) .frame(height: 120) } else { RoundedRectangle(cornerRadius: Design.Radius.control) diff --git a/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift b/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift index 307f0f7..725f2a8 100644 --- a/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift +++ b/gui/Sources/TetherKitNextCore/NetworkConfigurator.swift @@ -99,6 +99,9 @@ public enum NetworkValidator { var address = in_addr() guard text.withCString({ inet_pton(AF_INET, $0, &address) }) == 1 else { return false } let host = UInt32(bigEndian: address.s_addr) + // 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 } // 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). let inverted = ~host return inverted & (inverted &+ 1) == 0 diff --git a/gui/Sources/TetherKitNextCore/TetherKitNextError.swift b/gui/Sources/TetherKitNextCore/TetherKitNextError.swift index 5ff2bbe..b9f8ec3 100644 --- a/gui/Sources/TetherKitNextCore/TetherKitNextError.swift +++ b/gui/Sources/TetherKitNextCore/TetherKitNextError.swift @@ -21,9 +21,6 @@ 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 diff --git a/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift b/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift index 0aa291f..e5624c5 100644 --- a/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift +++ b/gui/Sources/TetherKitNextCore/TetherKitNextLibrary.swift @@ -13,7 +13,7 @@ public enum TetherKitNextLibrary { /// 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. /// /// Consistent with 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 @@ -84,11 +84,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 diff --git a/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift b/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift index 6acb0ad..b2b26e0 100644 --- a/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift +++ b/gui/Sources/TetherKitNextCore/TetherKitNextSession.swift @@ -14,7 +14,7 @@ import TetherKitNextIPC 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 { @@ -80,10 +80,14 @@ 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 to read. /// /// 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. diff --git a/gui/Sources/TetherKitNextHelper/HelperService.swift b/gui/Sources/TetherKitNextHelper/HelperService.swift index d161906..b3719c9 100644 --- a/gui/Sources/TetherKitNextHelper/HelperService.swift +++ b/gui/Sources/TetherKitNextHelper/HelperService.swift @@ -28,7 +28,7 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen /// **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. 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 @@ -133,7 +133,7 @@ final class HelperService: NSObject, TetherKitNextHelperProtocol, @unchecked Sen // 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. + // connect again, and only reinstalling the helper would help. This happened in practice. if let existing = self.withState({ $0 }) { let state = existing.status().runState guard state == .failed || state == .stopped else { diff --git a/gui/Sources/TetherKitNextIPC/Authorization.swift b/gui/Sources/TetherKitNextIPC/Authorization.swift index 90d9f19..306e09f 100644 --- a/gui/Sources/TetherKitNextIPC/Authorization.swift +++ b/gui/Sources/TetherKitNextIPC/Authorization.swift @@ -26,13 +26,13 @@ import Security /// 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. +/// and letting ARC free it 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. +/// The token crosses actors (AppModel awaits XPC calls that complete on XPC queues). There is no +/// mutable state here -- both stored properties are `let`; the AuthorizationRef itself is +/// thread-safe per the Authorization Services documentation (the state lives in securityd and +/// cross-process calls are serialized); 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,15 +44,6 @@ 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, diff --git a/gui/Sources/TetherKitNextIPC/HelperProtocol.swift b/gui/Sources/TetherKitNextIPC/HelperProtocol.swift index 5617af2..e4fa646 100644 --- a/gui/Sources/TetherKitNextIPC/HelperProtocol.swift +++ b/gui/Sources/TetherKitNextIPC/HelperProtocol.swift @@ -55,7 +55,7 @@ import Foundation /// Reads back the IP state the NIC 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 diff --git a/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift b/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift index ad096d1..2db50b6 100644 --- a/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift +++ b/gui/Sources/TetherKitNextIPC/LocalizedStrings.swift @@ -124,6 +124,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 +200,6 @@ public enum L10nKey: String, CaseIterable, Sendable { case updateCheckFailed case updateDevBuild case uninstallWhileRunningWarning - case helperComponentVersion case helperVersionMismatch case helperUpdateBadge case checkingHelper @@ -382,6 +411,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 +487,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…" @@ -627,6 +685,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 +761,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…" @@ -872,6 +959,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 +1035,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 "正在检查特权组件……" @@ -1117,6 +1233,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 +1309,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 "特権ヘルパーを確認中…" @@ -1362,6 +1507,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 +1583,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…" @@ -1607,6 +1781,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 +1857,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 "권한 있는 헬퍼 확인 중…" diff --git a/gui/Sources/TetherKitNextIPC/Models.swift b/gui/Sources/TetherKitNextIPC/Models.swift index 8e77540..5a4fba3 100644 --- a/gui/Sources/TetherKitNextIPC/Models.swift +++ b/gui/Sources/TetherKitNextIPC/Models.swift @@ -99,6 +99,13 @@ public struct SessionStatus: Codable, Hashable, Sendable { /// 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 an older daemon's JSON (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 +121,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 +144,7 @@ public struct SessionStatus: Codable, Hashable, Sendable { self.txBackpressure = txBackpressure self.monotonicNanos = monotonicNanos self.fatalMessage = fatalMessage + self.peerAddress = peerAddress } } @@ -313,7 +321,7 @@ 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. 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/Tests/TetherKitNextIPCTests/AuthorizationTests.swift b/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift index 8f16f43..3c3d9f8 100644 --- a/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift +++ b/gui/Tests/TetherKitNextIPCTests/AuthorizationTests.swift @@ -19,7 +19,7 @@ final class AuthorizationTests: XCTestCase { 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,7 +47,7 @@ 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) {} } @@ -69,6 +69,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..6355cf0 100644 --- a/gui/Tests/TetherKitNextIPCTests/HelperConstantsTests.swift +++ b/gui/Tests/TetherKitNextIPCTests/HelperConstantsTests.swift @@ -30,7 +30,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 diff --git a/gui/Tests/TetherKitNextUIModelTests/InterfaceTrafficTests.swift b/gui/Tests/TetherKitNextUIModelTests/InterfaceTrafficTests.swift new file mode 100644 index 0000000..997cb97 --- /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 old 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/include/tetherkitnext/capi/tetherkitnext_c.h b/include/tetherkitnext/capi/tetherkitnext_c.h index 15b5385..77e1980 100644 --- a/include/tetherkitnext/capi/tetherkitnext_c.h +++ b/include/tetherkitnext/capi/tetherkitnext_c.h @@ -243,11 +243,12 @@ TK_API void tk_set_log_level(int32_t level); /// `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); @@ -373,6 +374,12 @@ typedef struct tk_session_status { /// 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. @@ -403,10 +410,12 @@ 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); diff --git a/include/tetherkitnext/common/logging.h b/include/tetherkitnext/common/logging.h index 6c3bfab..5872f9d 100644 --- a/include/tetherkitnext/common/logging.h +++ b/include/tetherkitnext/common/logging.h @@ -52,8 +52,9 @@ void SetLogColorEnabled(bool enabled) noexcept; /// 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); @@ -61,7 +62,8 @@ void SetCurrentThreadName(std::string_view name) noexcept; /// (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; 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/time.h b/include/tetherkitnext/common/time.h index 3d54af0..b95e427 100644 --- a/include/tetherkitnext/common/time.h +++ b/include/tetherkitnext/common/time.h @@ -40,10 +40,6 @@ class Stopwatch { return static_cast(Elapsed()) / static_cast(kNanosPerMilli); } - [[nodiscard]] double ElapsedSeconds() const noexcept { - return static_cast(Elapsed()) / static_cast(kNanosPerSecond); - } - private: Nanos start_; }; diff --git a/include/tetherkitnext/core/bridge.h b/include/tetherkitnext/core/bridge.h index 603edf8..8d67f27 100644 --- a/include/tetherkitnext/core/bridge.h +++ b/include/tetherkitnext/core/bridge.h @@ -45,18 +45,19 @@ // 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. @@ -107,6 +108,9 @@ struct BridgeStats { /// 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. 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. @@ -137,9 +141,6 @@ 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 @@ -177,6 +178,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}; @@ -196,6 +201,9 @@ class Bridge { /// 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..74bd3ae --- /dev/null +++ b/include/tetherkitnext/core/peer_address.h @@ -0,0 +1,111 @@ +// 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..9457cf7 100644 --- a/include/tetherkitnext/core/runtime.h +++ b/include/tetherkitnext/core/runtime.h @@ -286,9 +286,12 @@ class Runtime final : public rndis::StateMachineObserver { 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..32e645d 100644 --- a/include/tetherkitnext/net/bpf_link.h +++ b/include/tetherkitnext/net/bpf_link.h @@ -77,9 +77,11 @@ struct BpfConfig { /// 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+). diff --git a/include/tetherkitnext/net/darwin_abi.h b/include/tetherkitnext/net/darwin_abi.h index 5fbd332..23e31de 100644 --- a/include/tetherkitnext/net/darwin_abi.h +++ b/include/tetherkitnext/net/darwin_abi.h @@ -49,7 +49,7 @@ struct IfDrv { // 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 编号会算错"); +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); @@ -59,8 +59,8 @@ 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 @@ -116,7 +116,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); @@ -135,14 +135,15 @@ static_assert(alignof(FethRequest) == 8); /// /// 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. 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); @@ -170,16 +171,16 @@ 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** +/// 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 diff --git a/include/tetherkitnext/rndis/protocol.h b/include/tetherkitnext/rndis/protocol.h index 9be36d2..0cd94b3 100644 --- a/include/tetherkitnext/rndis/protocol.h +++ b/include/tetherkitnext/rndis/protocol.h @@ -104,11 +104,6 @@ template 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 && @@ -234,7 +229,8 @@ 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.** 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. inline constexpr std::uint32_t kDeviceToHostPacketAlignment = 8; @@ -321,11 +317,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; diff --git a/include/tetherkitnext/rndis/state_machine.h b/include/tetherkitnext/rndis/state_machine.h index 6739cbb..f4d8d52 100644 --- a/include/tetherkitnext/rndis/state_machine.h +++ b/include/tetherkitnext/rndis/state_machine.h @@ -311,6 +311,11 @@ 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; diff --git a/include/tetherkitnext/usb/data_channel.h b/include/tetherkitnext/usb/data_channel.h index a8969da..a923a27 100644 --- a/include/tetherkitnext/usb/data_channel.h +++ b/include/tetherkitnext/usb/data_channel.h @@ -251,9 +251,16 @@ 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. + /// 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; diff --git a/include/tetherkitnext/usb/device.h b/include/tetherkitnext/usb/device.h index ad2eccf..2ec07a8 100644 --- a/include/tetherkitnext/usb/device.h +++ b/include/tetherkitnext/usb/device.h @@ -153,9 +153,7 @@ 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. diff --git a/src/app/main.cc b/src/app/main.cc index e2074dd..3da95ea 100644 --- a/src/app/main.cc +++ b/src/app/main.cc @@ -126,6 +126,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 +213,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 +240,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 +257,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") { diff --git a/src/capi/log_ring.cc b/src/capi/log_ring.cc index 77baace..d6bd91d 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 diff --git a/src/capi/managed_network_service.cc b/src/capi/managed_network_service.cc index f042f74..a59a19b 100644 --- a/src/capi/managed_network_service.cc +++ b/src/capi/managed_network_service.cc @@ -284,6 +284,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..90f5601 100644 --- a/src/capi/managed_network_service.h +++ b/src/capi/managed_network_service.h @@ -23,6 +23,14 @@ namespace tetherkitnext::capi { [[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..69d4373 100644 --- a/src/capi/net_config.cc +++ b/src/capi/net_config.cc @@ -17,14 +17,20 @@ // 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 +#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 +45,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 { @@ -436,6 +439,17 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, // 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. if (!QueryAddress(interface_name, SIOCGIFADDR).has_value()) { @@ -448,11 +462,20 @@ void TryPublishDns(SCDynamicStoreRef store, std::string_view service_id, 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,12 +539,63 @@ 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; @@ -550,19 +624,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; } diff --git a/src/capi/net_config.h b/src/capi/net_config.h new file mode 100644 index 0000000..f00320d --- /dev/null +++ b/src/capi/net_config.h @@ -0,0 +1,26 @@ +// 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..9b7e4a4 100644 --- a/src/capi/orphan_cleanup.cc +++ b/src/capi/orphan_cleanup.cc @@ -11,13 +11,18 @@ // * 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 { @@ -103,12 +105,42 @@ void WriteRegistry(const std::vector& entries) noexcept { ::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()); } } @@ -139,12 +171,19 @@ void OnInterfaceChanged(std::string_view name, bool created) noexcept { 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; }); } @@ -161,6 +200,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); } } diff --git a/src/capi/process_runner.cc b/src/capi/process_runner.cc index 80df01d..6dc0191 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 @@ -59,7 +61,9 @@ 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); @@ -74,9 +78,25 @@ Result Spawn(std::string_view executable, static char kLangVar[] = "LANG=C"; std::array clean_environment{kPathVar, kLangVar, nullptr}; + // POSIX_SPAWN_CLOEXEC_DEFAULT (Darwin): the child inherits only the + // descriptors the file actions above set up (stdin/stdout/stderr). Without + // it every descriptor this root process holds that lacks FD_CLOEXEC -- the + // BPF device, feth control sockets, libusb's pipes, the XPC listener's + // descriptors -- would leak into ipconfig / route. + ::posix_spawnattr_t attributes{}; + if (const int rc = ::posix_spawnattr_init(&attributes); rc != 0) { + ::posix_spawn_file_actions_destroy(&actions); + ::close(pipe_fds[0]); + ::close(pipe_fds[1]); + return std::unexpected(Error::FromErrno(rc, Tr(Msg::kCapiSpawnAttributesFailed))); + } + // NOLINTNEXTLINE(google-runtime-int): posix_spawnattr_setflags takes a short. + ::posix_spawnattr_setflags(&attributes, static_cast(POSIX_SPAWN_CLOEXEC_DEFAULT)); + ::pid_t child = -1; - const int spawn_rc = ::posix_spawn(&child, executable_path.c_str(), &actions, nullptr, + const int spawn_rc = ::posix_spawn(&child, executable_path.c_str(), &actions, &attributes, argv.data(), clean_environment.data()); + ::posix_spawnattr_destroy(&attributes); ::posix_spawn_file_actions_destroy(&actions); // The parent process must close the write end immediately, otherwise ReadAll will never see EOF -- it is itself still holding a // write end, so the pipe never closes. This is the classic pipe deadlock. diff --git a/src/capi/session.cc b/src/capi/session.cc index 01b8299..7f1b84e 100644 --- a/src/capi/session.cc +++ b/src/capi/session.cc @@ -2,10 +2,18 @@ // // 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 +22,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 { @@ -105,6 +107,13 @@ 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 @@ -131,11 +140,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; @@ -267,6 +276,11 @@ tk_result_t tk_session_status_get(tk_session_t* session, tk_session_status_t* ou 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/core/bridge.cc b/src/core/bridge.cc index 59f94a4..db01f5e 100644 --- a/src/core/bridge.cc +++ b/src/core/bridge.cc @@ -56,7 +56,14 @@ Status Bridge::Start() { // 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)); + 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(); }); @@ -190,22 +197,28 @@ 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). } 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); + 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. @@ -315,17 +328,25 @@ 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". 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..7b3efb3 100644 --- a/src/core/runtime.cc +++ b/src/core/runtime.cc @@ -46,7 +46,9 @@ 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))); } @@ -73,11 +75,10 @@ void Runtime::WaitUntilStopped() { } void Runtime::Stop() { - if (stopped_) { + if (stopped_.exchange(true)) { return; } - stopped_ = true; - if (!started_) { + if (!started_.load()) { return; } @@ -221,6 +222,16 @@ Status Runtime::RunStartSequence() { 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,6 +242,7 @@ 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; @@ -255,7 +267,20 @@ void Runtime::RunControlLoop() { 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 (idea from + // XiaoMiku01/TetherKit#23); 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; } @@ -475,11 +500,19 @@ 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}); diff --git a/src/rndis/state_machine.cc b/src/rndis/state_machine.cc index 1916b57..701f2b7 100644 --- a/src/rndis/state_machine.cc +++ b/src/rndis/state_machine.cc @@ -122,6 +122,18 @@ Result StateMachine::PumpOnce(std::optional expected_reply, // ---- 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; } @@ -135,6 +147,17 @@ 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. diff --git a/src/usb/data_channel.cc b/src/usb/data_channel.cc index bed2628..926e859 100644 --- a/src/usb/data_channel.cc +++ b/src/usb/data_channel.cc @@ -281,7 +281,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,8 +296,9 @@ 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)) { + 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; @@ -340,9 +342,10 @@ Result UsbDataChannel::SendFrames(std::span frames ++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,9 +364,7 @@ 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))); } @@ -382,7 +383,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,6 +411,14 @@ 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. + // (Idea from XiaoMiku01/TetherKit#24.) + 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)); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c3f22c2..0cf028f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,6 +20,7 @@ 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 @@ -70,6 +71,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..4f1a25e 100644 --- a/tests/language_guard.h +++ b/tests/language_guard.h @@ -2,12 +2,14 @@ // // * 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..41ee5c8 100644 --- a/tests/mock_control_channel.h +++ b/tests/mock_control_channel.h @@ -36,7 +36,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,7 +53,7 @@ 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()) { @@ -176,7 +176,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_; diff --git a/tests/mock_data_channel.h b/tests/mock_data_channel.h index 3dfb9ca..4fd24a8 100644 --- a/tests/mock_data_channel.h +++ b/tests/mock_data_channel.h @@ -50,7 +50,7 @@ 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. diff --git a/tests/test_capi.cc b/tests/test_capi.cc index cb8cb66..8289eaa 100644 --- a/tests/test_capi.cc +++ b/tests/test_capi.cc @@ -4,36 +4,40 @@ // 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. +#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 字符边界上") { +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{}; @@ -42,37 +46,39 @@ TEST_CASE("CopyText 截断落在 UTF-8 字符边界上") { 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")); } } @@ -99,7 +105,7 @@ tk_device_info_t DeviceInfo(const DeviceIdentity& identity, const char* manufact } // namespace -TEST_CASE("ReconcileDeviceStrings 在读不到时回填上次成功读到的名字") { +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, @@ -119,7 +125,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 +134,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 +143,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,7 +151,9 @@ 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); @@ -157,7 +166,7 @@ TEST_CASE("ReconcileDeviceStrings 不把旧名字安给接替同一地址的另 } } -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,7 +177,7 @@ TEST_CASE("ReconcileDeviceStrings 对没有字符串的设备保持诚实的空 CHECK(std::string{infos[0].product}.empty()); } -TEST_CASE("ReconcileDeviceStrings 不清除仍在场但没被填出的设备的记忆") { +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, @@ -198,7 +207,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 +215,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,12 +230,12 @@ 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", @@ -235,15 +244,19 @@ TEST_CASE("tk_list_devices 允许只统计数量") { 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" +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); @@ -266,7 +279,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 +294,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 +317,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 +331,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 +340,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 +350,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 +367,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); @@ -370,7 +383,7 @@ TEST_CASE("tk_session_config_init 填出可直接使用的默认值") { 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 +392,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 +400,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 +424,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 +441,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,7 +449,7 @@ TEST_CASE("RunTool 收集子进程输出并带回退出码") { CHECK(result->output == "你好 世界\n"); } -TEST_CASE("RunTool 合并 stderr,且非零退出不算调用失败") { +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"}); @@ -445,7 +459,7 @@ TEST_CASE("RunTool 合并 stderr,且非零退出不算调用失败") { CHECK(result->output == "boom\n"); } -TEST_CASE("RunTool 读得下超过管道缓冲的大输出(不死锁)") { +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( @@ -455,7 +469,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 +500,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,7 +509,7 @@ 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{}; @@ -491,7 +527,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,7 +541,7 @@ TEST_CASE("非 root 下写操作返回 TK_ERR_PERMISSION") { CHECK(removed == 0); } -TEST_CASE("查询不存在的 feth 网卡是成功且全空,而不是报错") { +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{}; diff --git a/tests/test_common_byte_order.cc b/tests/test_common_byte_order.cc index fc4bbc2..2eced41 100644 --- a/tests/test_common_byte_order.cc +++ b/tests/test_common_byte_order.cc @@ -21,7 +21,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 +31,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,7 +52,7 @@ TEST_CASE("写入后读回保持一致") { CHECK(buffer[5] == std::byte{0xDD}); } -TEST_CASE("未对齐偏移上的读写同样正确") { +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{}; @@ -65,13 +65,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 +81,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..51eff96 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,71 @@ 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 域输出原始状态码数值") { +TEST_CASE("the RNDIS domain prints the raw status code") { // 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 失败"); + 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 +126,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..6e0809a 100644 --- a/tests/test_common_frame_ring.cc +++ b/tests/test_common_frame_ring.cc @@ -43,7 +43,7 @@ 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); @@ -51,14 +51,14 @@ TEST_CASE("容量向上取整并报告存储开销") { 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 +71,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 +80,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 +89,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,7 +105,7 @@ 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. for (std::uint32_t round = 0; round < 500; ++round) { @@ -120,8 +120,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 +197,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); @@ -250,7 +251,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 +267,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 +284,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 +301,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)))); @@ -328,7 +329,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 +349,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 +369,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..41e52d3 100644 --- a/tests/test_common_i18n.cc +++ b/tests/test_common_i18n.cc @@ -127,12 +127,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 +142,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 +157,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 +166,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)); @@ -204,7 +205,7 @@ TEST_CASE("两种语言的占位符下标与类型一致") { } } -TEST_CASE("ParseLanguage 认得常见写法") { +TEST_CASE("ParseLanguage recognizes common spellings") { Language language = Language::kEnglish; CHECK(tetherkitnext::ParseLanguage("zh", &language)); @@ -231,7 +232,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 +242,19 @@ 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. 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..df8a096 100644 --- a/tests/test_common_spsc_ring.cc +++ b/tests/test_common_spsc_ring.cc @@ -30,14 +30,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,7 +45,7 @@ TEST_CASE("空队列出队失败") { CHECK(ring.SizeSnapshot() == 0); } -TEST_CASE("满队列入队失败且容量被完整利用") { +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) { @@ -55,7 +55,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,7 +69,7 @@ TEST_CASE("FIFO 顺序与内容完整性") { CHECK(ring.SizeSnapshot() == 0); } -TEST_CASE("反复绕环不丢数据") { +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) { @@ -80,7 +80,7 @@ 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(); @@ -91,7 +91,7 @@ TEST_CASE("索引游标各字段落在不同缓存行") { 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); diff --git a/tests/test_common_stats.cc b/tests/test_common_stats.cc index 4ff2cb7..be2b02a 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; @@ -79,7 +79,7 @@ TEST_CASE("速率采样把字节数换算成 Mbps") { 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 +88,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,7 +96,9 @@ 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. @@ -113,7 +115,7 @@ 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); diff --git a/tests/test_core_bridge.cc b/tests/test_core_bridge.cc index b79b640..b848712 100644 --- a/tests/test_core_bridge.cc +++ b/tests/test_core_bridge.cc @@ -84,7 +84,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 +105,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 +131,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 +157,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,7 +198,7 @@ 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. LoopbackLink link(LoopbackConfig{.sent_capacity = 8}); @@ -221,7 +221,8 @@ TEST_CASE("RX 队列满时丢弃并计数,不阻塞生产者") { bridge.Stop(); } -TEST_CASE("TX 背压:传输池占满时等待而不丢弃,容量恢复后全部送达") { +TEST_CASE( + "TX backpressure: waits instead of dropping when the pool is full, then delivers everything") { // 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 @@ -272,7 +273,8 @@ TEST_CASE("TX 背压:传输池占满时等待而不丢弃,容量恢复后全 bridge.Stop(); } -TEST_CASE("TX 背压:部分接纳时剩余帧重试送达,不丢不乱序") { +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; @@ -300,7 +302,7 @@ TEST_CASE("TX 背压:部分接纳时剩余帧重试送达,不丢不乱序") bridge.Stop(); } -TEST_CASE("TX 背压:等待期间 Stop() 能及时返回") { +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; @@ -327,7 +329,8 @@ TEST_CASE("TX 背压:等待期间 Stop() 能及时返回") { CHECK(bridge.Snapshot().tx.TotalDropped() > 0); } -TEST_CASE("TX 背压:等待期间落下暂停,剩余帧被丢弃且线程存活") { +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}); @@ -357,7 +360,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()); @@ -383,7 +386,7 @@ TEST_CASE("暂停期间不搬运,恢复后 RX 队列里的帧继续送出") { bridge.Stop(); } -TEST_CASE("SetPaused 在任何生命周期阶段都不会挂死") { +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; @@ -421,7 +424,7 @@ TEST_CASE("SetPaused 在任何生命周期阶段都不会挂死") { CHECK(bridge.Paused()); } -TEST_CASE("暂停期间 TX 方向的帧被丢弃并计数") { +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; @@ -440,7 +443,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 @@ -455,12 +458,15 @@ TEST_CASE("链路写失败不会让线程退出,恢复后继续工作") { // 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 +483,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,12 +502,12 @@ 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}); diff --git a/tests/test_core_peer_address.cc b/tests/test_core_peer_address.cc new file mode 100644 index 0000000..cb27fad --- /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_net_link.cc b/tests/test_net_link.cc index 3466a8a..87d58f3 100644 --- a/tests/test_net_link.cc +++ b/tests/test_net_link.cc @@ -78,8 +78,8 @@ std::string Why(const T& result) { /// 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); } @@ -124,7 +124,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,7 +197,7 @@ std::vector MakeArpRequest(const MacAddress& sender_mac, const char* TEST_SUITE("net.abi") { -TEST_CASE("私有 ABI 的结构体大小与 ioctl 编号与实测值一致") { +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); @@ -211,7 +211,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,7 +221,7 @@ 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); @@ -239,14 +239,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 +261,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 +279,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 +287,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 +319,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 +342,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 +351,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 +361,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 +371,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 +382,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 +390,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())); + 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 +413,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 +431,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(); @@ -457,9 +458,9 @@ TEST_CASE("完整生命周期:创建、配对、设 MTU/MAC、UP、销毁") { 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,9 +471,9 @@ 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. CHECK((*link)->KernelBufferBytes() > 0); @@ -499,9 +500,9 @@ TEST_CASE("BPF 打开配置全流程,并验证方向语义与回环抑制") { } } -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; } @@ -548,11 +549,13 @@ 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 栈"); + 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. 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..31f0ad4 100644 --- a/tests/test_rndis_messages.cc +++ b/tests/test_rndis_messages.cc @@ -63,7 +63,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 +90,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,13 +99,13 @@ 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()); @@ -118,7 +118,7 @@ TEST_CASE("状态码与 OID 的名字可查") { 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 +129,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 +144,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 +160,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 +169,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 +200,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 +213,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 +222,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 +232,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 +242,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 +253,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 +263,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 +278,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 +290,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,7 +307,7 @@ TEST_CASE("编码 QUERY_MSG:定长 OID 必须带占位长度与尾部零字节 CHECK(LoadLe32(buffer.data() + kQuerySetDeviceVcHandleOffset) == 0); } -TEST_CASE("编码 QUERY_MSG:变长 OID 的长度必须为 0") { +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, @@ -319,7 +321,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,7 +342,7 @@ TEST_CASE("解码 QUERY_CMPLT:按 +8 基准点定位信息缓冲区") { CHECK(*parsed == MacAddress{0x02, 0x11, 0x22, 0x33, 0x44, 0x55}); } -TEST_CASE("解码 QUERY_CMPLT:设备返回不支持时不算致命错误") { +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); @@ -351,7 +353,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 +361,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 +374,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); @@ -386,7 +388,7 @@ TEST_CASE("解码 SET_CMPLT") { // 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 +399,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 +411,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 +423,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 +437,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()); @@ -449,7 +451,7 @@ TEST_CASE("host 也要能编码 KEEPALIVE_CMPLT(设备可主动发起保活) // 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 +463,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 +483,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); @@ -498,7 +500,7 @@ TEST_CASE("解码 INDICATE_STATUS:按消息起始基准点解释也能工作") CHECK(indication->diagnostic_status == 0xAAU); } -TEST_CASE("解码 INDICATE_STATUS:两种基准点都越界时仍返回成功") { +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); @@ -512,7 +514,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 +531,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 +560,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..62dd636 100644 --- a/tests/test_rndis_packet_codec.cc +++ b/tests/test_rndis_packet_codec.cc @@ -100,7 +100,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 +132,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 +143,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,14 +154,15 @@ 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, @@ -191,7 +192,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 +212,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 +230,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 +241,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 +257,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 +270,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,7 +282,7 @@ TEST_CASE("解码单帧:按 8 + DataOffset 定位数据") { CHECK(FrameMatches(summary.frames[0], 1514, 0x22)); } -TEST_CASE("解码:数据不紧跟头部(DataOffset 大于 36)") { +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; @@ -295,7 +296,7 @@ TEST_CASE("解码:数据不紧跟头部(DataOffset 大于 36)") { CHECK(FrameMatches(summary.frames[0], kFrameLength, 0x33)); } -TEST_CASE("解码:容忍尾部 1 字节 ZLP 规避填充") { +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, @@ -308,7 +309,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 +324,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 +341,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 +349,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 +357,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 +365,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 +373,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 +382,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,7 +392,7 @@ TEST_CASE("解码畸形输入:全部被识别且不读越界") { } } -TEST_CASE("解码:前几帧有效、中途畸形时保留已解出的帧") { +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, @@ -415,7 +416,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 +430,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 +443,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..0652dbb 100644 --- a/tests/test_rndis_state_machine.cc +++ b/tests/test_rndis_state_machine.cc @@ -60,7 +60,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 +68,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; @@ -102,7 +102,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; @@ -126,7 +126,8 @@ TEST_CASE("启动序列的消息顺序:INITIALIZE 在最前,SET 包过滤在 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( @@ -147,10 +148,11 @@ TEST_CASE("变长 OID 的 InformationBufferLength 必须为 0,定长必须非 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"); + 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 +160,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 +172,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); @@ -196,7 +198,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 +215,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,7 +230,7 @@ TEST_CASE("非以太网介质被拒绝") { REQUIRE_FALSE(machine.Start().has_value()); } -TEST_CASE("设备在等响应期间插入 INDICATE_STATUS,不影响请求配对") { +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 purpose. MockControlChannel channel; channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { @@ -259,7 +261,7 @@ TEST_CASE("设备在等响应期间插入 INDICATE_STATUS,不影响请求配 CHECK(observer.link_events[0]); } -TEST_CASE("链路已 up 之后收到 MEDIA_DISCONNECT 才产生断开事件") { +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)); @@ -292,7 +294,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 +324,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)) { @@ -345,10 +347,10 @@ 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); + 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 +365,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,9 +380,9 @@ 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. channel.SetRequestHandler([](std::span request, MockControlChannel& mock) { @@ -406,10 +408,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 +431,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 +458,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; @@ -477,7 +479,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 +492,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,7 +501,7 @@ TEST_CASE("Start 只能在未初始化状态下调用") { CHECK_FALSE(machine.Start().has_value()); } -TEST_CASE("设备没有中断端点时退化为轮询,仍能完成启动") { +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); @@ -512,7 +514,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 +525,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 +538,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 +547,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 +565,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; @@ -588,7 +590,7 @@ TEST_SUITE("rndis.state_machine_timeout") { // 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 上是无限等待)") { +TEST_CASE("never passes 0 to WaitForNotification (0 waits forever on Darwin)") { MockControlChannel channel; channel.SetRequestHandler(MakeWellBehavedDevice(kDeviceMac)); RecordingObserver observer; @@ -603,11 +605,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); }