Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .github/emulator/prepare.sh
Original file line number Diff line number Diff line change
@@ -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
85 changes: 72 additions & 13 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ defaults:

env:
RUSTC_BOOTSTRAP: "1"
SCCACHE_GHA_ENABLED: "true"
AWS_LC_SYS_PREBUILT_NASM: "1"

concurrency:
Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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'
Expand All @@ -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
Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<SHA>-<attempt>`,其中包含 `results.json`。

要在 runner 上交互排查,用 `gh run rerun <run-id> --job <emulator-job-id> --debug` 重跑模拟器作业。从 `Open Upterm for a debug re-run` 步骤复制 SSH 命令,使用 GitHub 账号已登记公钥对应的私钥连接。普通步骤结束后,Upterm 最多等待 15 分钟供调试者接入。

在已安装 `traffic-test` 调试 APK 和 androidTest APK 的设备上,也可以单独运行探针:

```sh
Expand Down
3 changes: 2 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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__")
100 changes: 78 additions & 22 deletions traffic-test/emulator/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Run the VPN/TPROXY traffic matrix on a disposable KernelSU emulator."""

import argparse
import ipaddress
import itertools
import json
Expand All @@ -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"
Expand Down Expand Up @@ -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):
Expand All @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -175,9 +206,6 @@ def prepare(device):
f'<map><string name="profile_path">{private}/files/matrix.yaml</string></map>')]:
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")


Expand All @@ -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")
Expand Down Expand Up @@ -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):
Expand All @@ -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():
Expand All @@ -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")]}
Expand Down
Loading
Loading