diff --git a/.github/emulator/prepare.sh b/.github/emulator/prepare.sh new file mode 100644 index 0000000..c6ecdd4 --- /dev/null +++ b/.github/emulator/prepare.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +# A fresh hosted VM owns this AVD and its adb server. +work="$RUNNER_TEMP/clash-ksu" +export ANDROID_AVD_HOME="$work/avd" +mkdir -p "$ANDROID_AVD_HOME" +echo "ANDROID_AVD_HOME=$ANDROID_AVD_HOME" >> "$GITHUB_ENV" +cd "$work" +image="$ANDROID_HOME/system-images/android-35/google_apis_playstore/x86_64" +package='system-images;android-35;google_apis_playstore;x86_64' +export PATH="$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH" +sdkmanager "emulator" "$package" +# KernelSU's module is built for the kernel in revision 9 of this image. +echo "a204606cf2f458540c5437e9ba804b5012acf0a2916d00f099a03e1e553e697e $image/kernel-ranchu" | sha256sum -c - +echo "bb8cbb36481f2892c29929ed37bf51b904ddfdc796a76476364cd19aebea843b $image/ramdisk.img" | sha256sum -c - + +fetch() { + curl --fail --silent --show-error --location --retry 3 "$1" -o "$2" + echo "$3 $2" | sha256sum -c - +} +release=https://github.com/leemikepop/avd-kernelsu-x86_64/releases/download/kernelsu-v3.3.1 +fetch "$release/ksud-kernelsu-v3.3.1-x86_64-unknown-linux-musl" ksud 29b50f946a3cc40b04aef3dd587adad227fe0f70edf9c56b02c84479f0b0e954 +fetch "$release/a15-api35-6.6_kernelsu-v3.3.1_kernelsu.ko" kernelsu.ko 9cd4ab1591a6299a1a8c49714630bb00fc96c87ec896181791c8e0f989bf225a +fetch "$release/ksuinit-x86_64-kernelsu-v3.3.1" ksuinit 07df433255389dcf015dcec023aabee3d61df82055fa7eb4f66240f5d2c4a9c5 +fetch "https://github.com/tiann/KernelSU/releases/download/v3.3.1/KernelSU_v3.3.1_32680-release.apk" manager.apk b4a059ace71de2fa65cc7f12b1c58d55fc23ab25e057ee4230ce779742abe450 +chmod +x ksud +./ksud boot-patch -b "$image/ramdisk.img" --ramdisk --arch x86_64 -m kernelsu.ko -i ksuinit \ + --kmi android15-6.6 --allow-shell -o "$work" --out-name ramdisk.img +echo "CLASH_TEST_RAMDISK=$work/ramdisk.img" >> "$GITHUB_ENV" +echo "CLASH_TEST_KSU_MANAGER=$work/manager.apk" >> "$GITHUB_ENV" + +# Use the runner's upstream DNS instead of passing systemd-resolved's loopback stub to the guest. +if [[ -r /run/systemd/resolve/resolv.conf ]]; then + dns=$(awk '$1 == "nameserver" && $2 !~ /^127\./ && $2 != "::1" { print $2; exit }' /run/systemd/resolve/resolv.conf) + if [[ -n "$dns" ]]; then + echo "CLASH_TEST_DNS_SERVER=$dns" >> "$GITHUB_ENV" + fi +fi + +echo no | avdmanager create avd --name "$CLASH_TEST_AVD" --package "$package" --device pixel_6 +"$ANDROID_HOME/emulator/emulator" -list-avds | grep -Fx "$CLASH_TEST_AVD" +printf 'KERNEL=="kvm", OWNER="%s", GROUP="kvm", MODE="0660", OPTIONS+="static_node=kvm"\n' "$(id -un)" \ + | sudo tee /etc/udev/rules.d/99-clash-emulator-kvm.rules >/dev/null +sudo udevadm control --reload-rules +sudo udevadm trigger --name-match=kvm +sudo udevadm settle +test -r /dev/kvm && test -w /dev/kvm diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37276ec..e6545de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,6 @@ defaults: env: RUSTC_BOOTSTRAP: "1" - SCCACHE_GHA_ENABLED: "true" AWS_LC_SYS_PREBUILT_NASM: "1" concurrency: @@ -27,6 +26,10 @@ concurrency: jobs: build: runs-on: ubuntu-latest + env: + RUSTC_WRAPPER: sccache + SCCACHE_DIR: /tmp/sccache + SCCACHE_CACHE_SIZE: 2G steps: - name: Checkout code @@ -74,12 +77,18 @@ jobs: echo "ANDROID_NDK_ROOT=$ndk" >> "$GITHUB_ENV" echo "ANDROID_NDK=$ndk" >> "$GITHUB_ENV" - - name: Setup sccache-cache - uses: mozilla-actions/sccache-action@v0.0.11 - - uses: taiki-e/install-action@v2.90.11 with: - tool: cargo-ndk,just + tool: cargo-ndk,just,sccache + + - name: Cache the local sccache directory + uses: actions/cache@v6.1.0 + with: + path: ${{ env.SCCACHE_DIR }} + key: android-sccache-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.cachekey }}-${{ hashFiles('uniffi/Cargo.lock', 'kernelsu/Cargo.lock') }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + android-sccache-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.cachekey }}-${{ hashFiles('uniffi/Cargo.lock', 'kernelsu/Cargo.lock') }}- + android-sccache-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.cachekey }}- - name: Build Rust workspaces with a shared Cargo target directory run: echo "CARGO_BUILD_TARGET_DIR=$RUNNER_TEMP/cargo-target" >> "$GITHUB_ENV" @@ -99,8 +108,6 @@ jobs: - name: Generate Rust bindings if: steps.bindings.outputs.cache-hit != 'true' - env: - RUSTC_WRAPPER: sccache run: just generate-bindings --locked - name: Decode Keystore @@ -120,10 +127,24 @@ jobs: echo "version=dev-$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT fi - - name: Build Debug APK - if: github.event_name == 'pull_request' + - name: Build emulator test packages + if: "!startsWith(github.ref, 'refs/tags/')" run: | - ./gradlew --build-cache app:assembleDebug + ./gradlew --build-cache :app:assembleDebug :app:packageKernelSuModule :traffic-test:assembleDebug :traffic-test:assembleDebugAndroidTest + + - name: Pass test packages to the emulator + if: "!startsWith(github.ref, 'refs/tags/')" + uses: actions/upload-artifact@v7 + with: + name: emulator-packages + path: | + app/build/outputs/apk/debug/app-debug.apk + build/kernelsu/clash-android-tproxy.zip + traffic-test/build/outputs/apk/debug/traffic-test-debug.apk + traffic-test/build/outputs/apk/androidTest/debug/traffic-test-debug-androidTest.apk + if-no-files-found: error + retention-days: 3 + compression-level: 0 - name: Build Release APKs if: github.event_name != 'pull_request' @@ -147,6 +168,9 @@ jobs: bash .github/verify-native-symbols.sh release ./gradlew :app:uploadCrashlyticsSymbolFileRelease + - name: Show local compiler cache statistics + run: sccache --show-stats + - name: Archive matching native symbols and R8 mapping if: github.event_name != 'pull_request' uses: actions/upload-artifact@v7 @@ -243,6 +267,41 @@ jobs: gh release edit "$TAG_NAME" --draft=false --prerelease --notes-file CHANGELOG.md fi - - - + emulator: + name: Android emulator traffic matrix + needs: build + if: "!startsWith(github.ref, 'refs/tags/')" + runs-on: ubuntu-24.04 + permissions: + contents: read + timeout-minutes: 40 + env: + CLASH_TEST_AVD: ClashKsu35 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@v8 + with: + name: emulator-packages + - uses: taiki-e/install-action@v2.90.11 + with: + tool: just,uv + - name: Open Upterm for a debug re-run + if: github.run_attempt != '1' && runner.debug == '1' + uses: owenthereal/action-upterm@6c2d60e09009f59cb4c45c88767c78701f14d121 # v2.8.1 + with: + limit-access-to-actor: true + detached: true + wait-timeout-minutes: 15 + upterm-version: v0.41.1 + - name: Prepare disposable API 35 KernelSU AVD + run: bash .github/emulator/prepare.sh + - name: Run all eight traffic combinations + run: just test-emulator --prebuilt + - name: Upload emulator JSON report + uses: actions/upload-artifact@v7 + with: + name: emulator-report-${{ github.sha }}-${{ github.run_attempt }} + path: build/emulator-tests/*/results.json + if-no-files-found: error diff --git a/README.md b/README.md index 96503cb..f1753e3 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,10 @@ Clash Android 是基于 clash-rs 的 Android 代理客户端,支持 Android 7. 运行需要项目的 Android 构建环境、`just`、`uv` 和一个 API 35 KernelSU 测试 AVD。AVD 需要支持 `adb shell su 0`,并预先向调试包 `rs.clash.android.dev` 授予 root,能通过 `10.0.2.2` 和 `fec0::2` 访问宿主机,并能解析和连接 `example.com:443`。默认使用 `ClashKsu35` 和 `~/.android/ksu-clash-api35/ramdisk-ksu.img`,可用 `CLASH_TEST_AVD`、`CLASH_TEST_RAMDISK` 指定匹配的 AVD 和 ramdisk。命令会在宿主机的两个回环地址上启动端口为 `39007` 的回显服务,并在结束后关闭服务和测试模拟器。 +GitHub Actions 在 PR 和主分支构建中将同一次构建的调试 APK 和模块交给独立的 Ubuntu runner。它创建一次性的 API 35 KernelSU AVD,执行 `just test-emulator --prebuilt`。八组测试全部通过后,可在该次运行的 Artifacts 中下载 `emulator-report--`,其中包含 `results.json`。 + +要在 runner 上交互排查,用 `gh run rerun --job --debug` 重跑模拟器作业。从 `Open Upterm for a debug re-run` 步骤复制 SSH 命令,使用 GitHub 账号已登记公钥对应的私钥连接。普通步骤结束后,Upterm 最多等待 15 分钟供调试者接入。 + 在已安装 `traffic-test` 调试 APK 和 androidTest APK 的设备上,也可以单独运行探针: ```sh diff --git a/justfile b/justfile index 6954022..d3ebae1 100644 --- a/justfile +++ b/justfile @@ -30,7 +30,8 @@ module: phone: ./gradlew -PphoneArm64=true :app:assembleDebug +[positional-arguments] [script("uv", "run", "--no-project", "python")] -test-emulator: +test-emulator *args: import runpy runpy.run_path("traffic-test/emulator", run_name="__main__") diff --git a/traffic-test/emulator/__main__.py b/traffic-test/emulator/__main__.py index 7419a20..5678956 100644 --- a/traffic-test/emulator/__main__.py +++ b/traffic-test/emulator/__main__.py @@ -1,5 +1,6 @@ """Run the VPN/TPROXY traffic matrix on a disposable KernelSU emulator.""" +import argparse import ipaddress import itertools import json @@ -16,6 +17,7 @@ from contextlib import ExitStack, contextmanager from clash_ui import ClashUi +from ksu_manager import authorize ROOT = Path(__file__).resolve().parents[2] CLASH = "rs.clash.android.dev" @@ -76,6 +78,17 @@ def shell(self, *args, **kwargs): def root(self, *args): return self.shell("su", "0", *args) + def install(self, apk, *options): + for attempt in range(2): + try: + self.adb("install", "-r", *options, apk, timeout=120) + return + except RuntimeError as error: + # adbd may restart during a streamed install on the first boot. + if attempt or "INSTALL_" in str(error): + raise + self.adb("wait-for-device", timeout=120) + @contextmanager def emulator(sdk, directory): @@ -91,9 +104,11 @@ def emulator(sdk, directory): console.listen(1) console.settimeout(1) report = f"tcp:{console.getsockname()[1]},max=60" + dns_server = os.environ.get("CLASH_TEST_DNS_SERVER") + dns_args = ["-dns-server", dns_server] if dns_server else [] process = subprocess.Popen([sdk / "emulator" / ("emulator" + binary), "-avd", name, "-ramdisk", ramdisk.resolve(), "-read-only", "-no-snapshot", - "-no-window", "-no-audio", "-no-boot-anim", "-report-console", report], + "-no-window", "-no-audio", "-no-boot-anim", "-report-console", report, *dns_args], stdin=subprocess.DEVNULL, stdout=log, stderr=log) device = None try: @@ -110,17 +125,27 @@ def connect(): with connection.makefile("rb") as stream: port = int(stream.read(16).strip()) device = Device(adb, f"emulator-{port}") - device.adb("wait-for-device", timeout=120) - wait_for(lambda: device.shell("getprop", "sys.boot_completed") == "1", "Android boot", 180) + def booted(): + if process.poll() is not None: + raise RuntimeError(f"Emulator exited during boot; see {log.name}") + # adbd can disconnect and reconnect during the first boot of a new AVD. + probe = subprocess.run([*device.command, "shell", "getprop", "sys.boot_completed"], + capture_output=True, timeout=30) + return probe.returncode == 0 and probe.stdout.strip() == b"1" + + wait_for(booted, "Android boot", 240) if device.adb("emu", "avd", "name").splitlines()[0] != name: raise RuntimeError("Unexpected AVD name") try: yield device except Exception: - (directory / "logcat.txt").write_text( - device.shell("logcat", "-d", "-t", "4000", "-s", "AndroidRuntime:E", "TestRunner:E", "ClashTproxy:E", "clash:E"), - encoding="utf-8", - ) + try: + (directory / "logcat.txt").write_text( + device.shell("logcat", "-d", "-t", "4000", "-s", "AndroidRuntime:E", "TestRunner:E", "ClashTproxy:E", "clash:E"), + encoding="utf-8", + ) + except (RuntimeError, subprocess.TimeoutExpired) as diagnostic: + print(f"Could not collect logcat: {diagnostic}", file=sys.stderr) raise finally: if device is not None: @@ -153,15 +178,21 @@ def ready(): def prepare(device): abi = device.shell("getprop", "ro.product.cpu.abi") - device.adb("install", "-r", "--abi", abi, ROOT / "app/build/outputs/apk/debug/app-debug.apk") - device.adb("install", "-r", ROOT / "traffic-test/build/outputs/apk/debug/traffic-test-debug.apk") - device.adb("install", "-r", ROOT / "traffic-test/build/outputs/apk/androidTest/debug/traffic-test-debug-androidTest.apk") + device.install(ROOT / "app/build/outputs/apk/debug/app-debug.apk", "--abi", abi) # Only the read-only AVD overlay is changed. Preserve the pre-authorized app UID. device.shell("pm", "clear", CLASH) device.shell("pm", "grant", CLASH, "android.permission.POST_NOTIFICATIONS") device.shell("cmd", "locale", "set-app-locales", CLASH, "--locales", "en-US") + device.shell("input", "keyevent", "KEYCODE_WAKEUP") + device.shell("wm", "dismiss-keyguard") + device.shell("svc", "power", "stayon", "true") + manager = os.environ.get("CLASH_TEST_KSU_MANAGER") + if manager: + authorize(device, manager, CLASH, abi) if device.shell("run-as", CLASH, "su", "-c", "id -u") != "0": - raise RuntimeError(f"KernelSU must grant {CLASH} root in the base AVD") + raise RuntimeError(f"KernelSU must grant {CLASH} root in the test AVD") + device.install(ROOT / "traffic-test/build/outputs/apk/debug/traffic-test-debug.apk") + device.install(ROOT / "traffic-test/build/outputs/apk/androidTest/debug/traffic-test-debug-androidTest.apk") module = "/data/local/tmp/clash-test-module.zip" device.adb("push", ROOT / "build/kernelsu/clash-android-tproxy.zip", module) device.root("/data/adb/ksud", "module", "install", module) @@ -175,9 +206,6 @@ def prepare(device): f'{private}/files/matrix.yaml')]: device.shell("run-as", CLASH, "mkdir", "-p", path.split("/")[0]) device.shell("run-as", CLASH, "sh", "-c", f"cat > {path}", input=contents.encode()) - device.shell("input", "keyevent", "KEYCODE_WAKEUP") - device.shell("wm", "dismiss-keyguard") - device.shell("svc", "power", "stayon", "true") device.shell("am", "start", "-W", "-n", f"{CLASH}/rs.clash.android.MainActivity") @@ -200,9 +228,14 @@ def network(device): def wait_network(device, mode, ipv6=False): vpn, tproxy = mode == "vpn", mode == "tproxy" wanted = dict(tun=vpn, tun4=vpn, tun6=vpn and ipv6, v4=tproxy, v6=tproxy and ipv6, block6=tproxy and not ipv6) - last = {} + last = None def ready(): - last.update(network(device)) + nonlocal last + try: + last = network(device) + except (RuntimeError, subprocess.TimeoutExpired) as error: + last = str(error) + return None return last if last == wanted else None try: return wait_for(ready, f"{mode} network") @@ -284,7 +317,26 @@ def measure(device, case, logs): def baseline(device, logs, report, name): case = report[name] = dict(mode="off", ipv6=True, fakeIp=False) case["network"] = wait_network(device, "off") - measure(device, case, logs) + # A fresh AVD can reach sys.boot_completed before Android routes app traffic. + # Wait only for the initial unproxied probe. Every matrix case and the final + # restoration check must pass on their first measurement. + deadline = time.monotonic() + 120 + while True: + try: + measure(device, case, logs) + return + except AssertionError: + if name != "before" or time.monotonic() >= deadline: + raise + results = case["probes"] + transient = {"ConnectException", "NoRouteToHostException", "SocketException", + "PortUnreachableException", "DnsException", "timeout"} + checks = [results[family][protocol] for family in ("v4", "v6") for protocol in ("tcp", "udp")] + checks.append(results["dns"]) + if not any(check.get("error") in transient for check in checks): + raise + print("Waiting for the initial unproxied network", flush=True) + time.sleep(2) def check_settings(device, mode, ipv6, fake_ip): @@ -296,6 +348,9 @@ def check_settings(device, mode, ipv6, fake_ip): def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prebuilt", action="store_true", help="use test packages already built for this checkout") + args = parser.parse_args() sdk_path = os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") properties = ROOT / "local.properties" if not sdk_path and properties.is_file(): @@ -320,11 +375,12 @@ def save(): env.pop("KEYSTORE_FILE", None) env.pop("ANDROID_SPLIT_ABI_ENABLE", None) try: - if not (ROOT / "core/src/main/java/uniffi/clash_android_ffi/clash_android_ffi.kt").is_file(): - subprocess.run(["just", "generate-bindings", "--locked"], cwd=ROOT, env=env, check=True) - subprocess.run([ROOT / ("gradlew.bat" if os.name == "nt" else "gradlew"), ":app:assembleDebug", - ":app:packageKernelSuModule", ":traffic-test:assembleDebug", ":traffic-test:assembleDebugAndroidTest"], - cwd=ROOT, env=env, check=True) + if not args.prebuilt: + if not (ROOT / "core/src/main/java/uniffi/clash_android_ffi/clash_android_ffi.kt").is_file(): + subprocess.run(["just", "generate-bindings", "--locked"], cwd=ROOT, env=env, check=True) + subprocess.run([ROOT / ("gradlew.bat" if os.name == "nt" else "gradlew"), ":app:assembleDebug", + ":app:packageKernelSuModule", ":traffic-test:assembleDebug", ":traffic-test:assembleDebugAndroidTest"], + cwd=ROOT, env=env, check=True) with ExitStack() as stack: logs = {family: stack.enter_context(echo_server(directory, family, address)) for family, address in [("v4", "127.0.0.1"), ("v6", "::1")]} diff --git a/traffic-test/emulator/ksu_manager.py b/traffic-test/emulator/ksu_manager.py new file mode 100644 index 0000000..d88dfaf --- /dev/null +++ b/traffic-test/emulator/ksu_manager.py @@ -0,0 +1,61 @@ +"""Authorize only the installed debug app in the pinned KernelSU Manager on the CI AVD.""" + +import re +import time +import xml.etree.ElementTree as ET + +MANAGER = "me.weishu.kernelsu" + + +def screen(shell): + path = "/data/local/tmp/ksu-profile.xml" + shell("uiautomator", "dump", path) + return ET.fromstring(shell("cat", path)) + + +def find(tree, text): + return next((n for n in tree.iter("node") if n.get("package") == MANAGER + and text in (n.get("text"), n.get("content-desc"))), None) + + +def tap(shell, node): + x, y, right, bottom = map(int, re.findall(r"\d+", node.get("bounds"))) + shell("input", "tap", str((x + right) // 2), str((y + bottom) // 2)) + + +def authorize(device, apk, package, abi): + shell = device.shell + device.install(apk, "--abi", abi) + shell("wm", "size", "1080x2400") + shell("wm", "density", "420") + shell("am", "start", "-W", "-n", f"{MANAGER}/.ui.MainActivity") + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + tree = screen(shell) + if find(tree, "Working") is not None: + tap(shell, find(tree, "Superuser")) + break + else: + raise RuntimeError("KernelSU Manager did not report a working kernel module") + + # The pinned manager's paged app list may omit its rows from the accessibility + # tree. Clash is the only installed third-party client on the fresh 1080x2400 AVD. + # Always verify the package on the profile screen before touching a grant. + while time.monotonic() < deadline: + tree = screen(shell) + if find(tree, "App Profile") is not None: + if find(tree, package) is None: + raise RuntimeError("Unexpected package on the KernelSU grant screen") + switches = tree.findall(f".//node[@package='{MANAGER}'][@checkable='true']") + if len(switches) != 1: + raise RuntimeError("Unexpected KernelSU profile controls") + if switches[0].get("checked") != "true": + tap(shell, switches[0]) + break + row = find(tree, package) + if row is not None: + tap(shell, row) + else: + shell("input", "tap", "386", "640") + else: + raise RuntimeError("Clash profile did not open") diff --git a/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt b/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt index ab0658c..b9ce3ee 100644 --- a/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt +++ b/traffic-test/src/androidTest/java/rs/clash/traffictest/TrafficProbeTest.kt @@ -1,5 +1,6 @@ package rs.clash.traffictest +import android.net.DnsResolver import android.os.Bundle import android.os.SystemClock import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -56,6 +57,8 @@ class TrafficProbeTest { result.put("error", context.resources.getResourceEntryName(e.messageRes)).put("detail", context.getString(e.messageRes, *e.args)) } catch (e: java.io.IOException) { result.put("error", e.javaClass.simpleName).put("detail", e.message) + } catch (e: DnsResolver.DnsException) { + result.put("error", e.javaClass.simpleName).put("detail", e.message).put("code", e.code) } return result.put("elapsedMs", SystemClock.elapsedRealtime() - start) }