Initial commit: capability prober + design docs

Monorepo root for Echolot. Contains the no-root capability prober
(Kotlin/Compose, app.echo_lot.prober) and the four design docs that act
as the contract for the production app and the Go server.

LICENSE is deliberately absent — still undecided, see docs/build-status.md.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
mrambossek
2026-07-30 08:54:28 +02:00
co-authored by Claude Opus 5
commit e3840f54fe
40 changed files with 2582 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
.gradle/
build/
/local.properties
/.idea/
*.iml
.DS_Store
/captures
.externalNativeBuild
.cxx
/app/release
+65
View File
@@ -0,0 +1,65 @@
# Echolot Capability Prober
A throwaway diagnostic app that runs the borderline **no-root** operations from the Echolot
feasibility matrix on a **real device** and reports what actually works on that Android build.
Its job is to turn "should work / needs verification" spec notes into observed facts before the
production app hardens around them. Several probes naturally evolve into the tier-detection code
the real app needs anyway.
Package / appId: `app.echo_lot.prober` (derived from the echo-lot.app domain; hyphen → underscore
because Android application IDs and Java packages cannot contain hyphens).
## What it probes
| Probe | Question it answers | Expected result |
|---|---|---|
| `link.snapshot` | What does `LinkProperties` expose per active network? | SUPPORTED |
| `icmp.ping4` / `icmp.ping6` | Does the unprivileged ICMP datagram socket work? | SUPPORTED (no root needed) |
| `sockopt.matrix` | Are IP_TTL, IP_TOS, IP_RECVERR, IP_MTU_DISCOVER accepted? | SUPPORTED / PARTIAL |
| `trace.errqueue_reachable` | Is errqueue traceroute reachable from the Os API? | likely PARTIAL → needs a small native shim |
| `multinetwork.request_and_bind` | Can we hold + bind Wi-Fi / cellular / ethernet concurrently? | SUPPORTED for links present now |
| `local.mdns_discover` | Does multicast reception / mDNS work with a MulticastLock? | SUPPORTED |
| `peer.ble_advertise` | Can this chipset advertise BLE (peer-mode channel)? | device-dependent |
| `shizuku.command_battery` | Does the Shizuku shell tier return neighbor table, RA routes, DHCP logs? | SUPPORTED if Shizuku running |
Each result carries a **verdict** (SUPPORTED / PARTIAL / UNSUPPORTED / INCONCLUSIVE / ERROR),
a one-line summary, and raw **evidence** (sockopt return codes, addresses, timings, and the actual
dump excerpts from the Shizuku commands — capturing the per-device format the real parsers must
handle). Export the whole run as JSON with the Export button and share it anywhere.
## Building
Needs Android Studio (Koala or newer) or a local Android SDK; **this repo was scaffolded without
network access to Google's Maven, so dependencies download on your first local build.**
```
# Point the build at your SDK (or let Android Studio create local.properties):
echo "sdk.dir=/path/to/Android/sdk" > local.properties
./gradlew :app:assembleDebug
./gradlew :app:installDebug # with a device/emulator attached
```
The debug APK lands in `app/build/outputs/apk/debug/`.
## Using the Shizuku tier
1. Install [Shizuku](https://shizuku.rikka.app/) and start it via **wireless ADB pairing** (no root).
2. Launch the prober, tap **Run all probes**. The Shizuku probe requests permission on first use.
3. If Shizuku isn't running the probe reports INCONCLUSIVE (everything else still runs).
## Notes / known gaps
- Errqueue traceroute (`MSG_ERRQUEUE` recvmsg + cmsg parse) is expected to need a native C-over-JNI
shim; this prober only confirms the sockopts + call-path availability. Wiring the shim is the
next spike if the verdict is PARTIAL.
- Multi-network probe can only bind transports physically present at run time. To exercise USB
ethernet, attach an adapter first.
- BLE advertising support is genuinely chipset-dependent; a UNSUPPORTED here is a real finding.
## Relationship to the specs
Result IDs mirror the `measurement-schema.md` test-type registry where one exists, and the JSON
report shape is a stripped-down cousin of the full measurement document. The specs live in
[`../docs/`](../docs/) — `feature-catalog-and-feasibility.md`, `measurement-schema.md`,
`probe-protocol.md`.
+53
View File
@@ -0,0 +1,53 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.serialization)
}
android {
namespace = "app.echo_lot.prober"
compileSdk = 35
defaultConfig {
applicationId = "app.echo_lot.prober"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
}
buildTypes {
release {
isMinifyEnabled = false
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
aidl = true
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
debugImplementation(libs.androidx.ui.tooling)
implementation(libs.shizuku.api)
implementation(libs.shizuku.provider)
implementation(libs.kotlinx.serialization.json)
implementation(libs.kotlinx.coroutines.android)
}
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- BLE (advertise capability probe). neverForLocation keeps us out of location gating. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE"
tools:targetApi="s" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"
tools:targetApi="s" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation"
tools:targetApi="s" />
<!-- Shizuku -->
<uses-permission android:name="moe.shizuku.manager.permission.API_V23" />
<application
android:allowBackup="false"
android:label="Echolot Prober"
android:supportsRtl="true"
android:theme="@style/Theme.EcholotProber">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<!-- Shizuku binder provider -->
<provider
android:name="rikka.shizuku.ShizukuProvider"
android:authorities="${applicationId}.shizuku"
android:multiprocess="false"
android:enabled="true"
android:exported="true"
android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />
</application>
</manifest>
@@ -0,0 +1,11 @@
// IUserService.aidl
package app.echo_lot.prober.shizuku;
interface IUserService {
// Runs when the service is unbound / destroyed.
void destroy() = 16777114; // Shizuku reserves this transaction id for destroy
// Execute a shell command line as the Shizuku process user (shell uid 2000, or root),
// returning combined stdout+stderr. Bounded output; the caller passes a timeout in ms.
String exec(String command, int timeoutMs) = 1;
}
@@ -0,0 +1,85 @@
package app.echo_lot.prober
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import app.echo_lot.prober.export.ReportWriter
import app.echo_lot.prober.probe.ProbeRegistry
import app.echo_lot.prober.probe.ProbeResult
import app.echo_lot.prober.probe.Verdict
import app.echo_lot.prober.ui.ProberScreen
import app.echo_lot.prober.ui.UiState
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
private var state by mutableStateOf(UiState())
private val permissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { /* proceed regardless */ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestRuntimePermissions()
setContent {
MaterialTheme {
Surface {
ProberScreen(
state = state,
onRun = ::runProbes,
onShare = ::shareReport,
)
}
}
}
}
private fun runProbes() {
if (state.running) return
state = state.copy(running = true, results = emptyList(), currentTitle = null)
lifecycleScope.launch {
val acc = mutableListOf<ProbeResult>()
for (probe in ProbeRegistry.all) {
state = state.copy(currentTitle = probe.title)
val result = try {
probe.run(this@MainActivity)
} catch (t: Throwable) {
ProbeResult.of(probe, Verdict.ERROR, "Uncaught: ${t.message ?: t.javaClass.simpleName}")
}
acc.add(result)
state = state.copy(results = acc.toList())
}
state = state.copy(running = false, currentTitle = null)
}
}
private fun shareReport() {
if (state.results.isEmpty()) return
val intent = ReportWriter.share(this, state.results)
startActivity(Intent.createChooser(intent, "Export Echolot prober report"))
}
private fun requestRuntimePermissions() {
val perms = mutableListOf(Manifest.permission.ACCESS_FINE_LOCATION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
perms += Manifest.permission.BLUETOOTH_ADVERTISE
perms += Manifest.permission.BLUETOOTH_CONNECT
}
val missing = perms.filter {
ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
}
if (missing.isNotEmpty()) permissionLauncher.launch(missing.toTypedArray())
}
}
@@ -0,0 +1,56 @@
package app.echo_lot.prober.export
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.FileProvider
import app.echo_lot.prober.probe.ProbeResult
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.File
@Serializable
data class Report(
val schema: String = "echolot/prober-report",
val schemaVersion: String = "0.1.0",
val device: DeviceInfo,
val results: List<ProbeResult>,
)
@Serializable
data class DeviceInfo(
val manufacturer: String,
val model: String,
val androidSdk: Int,
val androidRelease: String,
) {
companion object {
fun current() = DeviceInfo(
manufacturer = Build.MANUFACTURER,
model = Build.MODEL,
androidSdk = Build.VERSION.SDK_INT,
androidRelease = Build.VERSION.RELEASE,
)
}
}
object ReportWriter {
private val json = Json { prettyPrint = true; encodeDefaults = true }
fun toJson(results: List<ProbeResult>): String =
json.encodeToString(Report(device = DeviceInfo.current(), results = results))
/** Writes the report to cache and returns a share Intent (SEND, application/json). */
fun share(context: Context, results: List<ProbeResult>): Intent {
val dir = File(context.cacheDir, "reports").apply { mkdirs() }
val file = File(dir, "echolot-prober-${Build.MODEL.replace(' ', '_')}.json")
file.writeText(toJson(results))
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
return Intent(Intent.ACTION_SEND).apply {
type = "application/json"
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
}
@@ -0,0 +1,86 @@
package app.echo_lot.prober.probe
import android.bluetooth.BluetoothManager
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.content.Context
import android.content.pm.PackageManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.coroutines.resume
/**
* Probes BLE peripheral advertising — the out-of-band control channel for peer mode. Not every
* chipset supports LE advertising, so this is a real capability question. Requires runtime
* BLUETOOTH_ADVERTISE (Android 12+); if not granted, we report INCONCLUSIVE.
*/
class BleAdvertiseProbe : Probe {
override val id = "peer.ble_advertise"
override val title = "BLE peripheral advertising (peer-mode control channel)"
override val tier = Tier.APP
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.Main) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
try {
val hasFeature = context.packageManager
.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
ev["FEATURE_BLUETOOTH_LE"] = hasFeature.toString()
val bm = context.getSystemService(BluetoothManager::class.java)
val adapter = bm?.adapter
ev["adapter_enabled"] = (adapter?.isEnabled == true).toString()
ev["multi_advertisement_supported"] =
(adapter?.isMultipleAdvertisementSupported == true).toString()
val advertiser = adapter?.bluetoothLeAdvertiser
if (advertiser == null) {
return@withContext ProbeResult.of(this@BleAdvertiseProbe, Verdict.UNSUPPORTED,
"No BLE advertiser (chipset or adapter off)", ev,
(System.nanoTime() - start) / 1_000_000)
}
val settings = AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setConnectable(true)
.setTimeout(2000)
.build()
val data = AdvertiseData.Builder().setIncludeDeviceName(false).build()
val result = withTimeoutOrNull(4000) {
suspendCancellableCoroutine<String> { cont ->
val cb = object : AdvertiseCallback() {
override fun onStartSuccess(s: AdvertiseSettings?) {
if (cont.isActive) cont.resume("success")
}
override fun onStartFailure(errorCode: Int) {
if (cont.isActive) cont.resume("failure:$errorCode")
}
}
try {
advertiser.startAdvertising(settings, data, cb)
cont.invokeOnCancellation { runCatching { advertiser.stopAdvertising(cb) } }
} catch (se: SecurityException) {
if (cont.isActive) cont.resume("permission_denied")
}
}
}
ev["startAdvertising"] = result ?: "timeout"
val verdict = when (result) {
"success" -> Verdict.SUPPORTED
"permission_denied", null -> Verdict.INCONCLUSIVE
else -> Verdict.UNSUPPORTED
}
ProbeResult.of(this@BleAdvertiseProbe, verdict,
"Advertising start: ${ev["startAdvertising"]}", ev,
(System.nanoTime() - start) / 1_000_000)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
ProbeResult.of(this@BleAdvertiseProbe, Verdict.ERROR, "BLE probe failed", ev,
(System.nanoTime() - start) / 1_000_000)
}
}
}
@@ -0,0 +1,68 @@
package app.echo_lot.prober.probe
import android.content.Context
import android.system.Os
import android.system.OsConstants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.FileDescriptor
import java.net.InetAddress
/**
* Probes whether an errqueue-based traceroute is reachable from the Java/Kotlin Os surface.
* The full technique needs recvmsg(MSG_ERRQUEUE) with cmsg parsing to pull the ICMP
* time-exceeded source address. Os.recvmsg / StructMsghdr coverage varies by API level, so we
* detect the call path via reflection and record the verdict. If unreachable here, the finding
* is: "traceroute needs the native shim" (a few hundred lines of C over JNI) — which is exactly
* what the production plan already earmarks.
*/
class ErrqueueProbe : Probe {
override val id = "trace.errqueue_reachable"
override val title = "Traceroute via IP_RECVERR + MSG_ERRQUEUE"
override val tier = Tier.APP
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
var fd: FileDescriptor? = null
try {
fd = Os.socket(OsConstants.AF_INET, OsConstants.SOCK_DGRAM, OsConstants.IPPROTO_UDP)
val recverr = OsAbi.trySetIntOpt(fd, OsConstants.IPPROTO_IP, OsAbi.IP_RECVERR, 1)
ev["IP_RECVERR"] = recverr?.let { "reject: $it" } ?: "accepted"
val ttl = OsAbi.trySetIntOpt(fd, OsConstants.IPPROTO_IP, OsAbi.IP_TTL, 1)
ev["IP_TTL=1"] = ttl?.let { "reject: $it" } ?: "accepted"
// Fire one TTL=1 probe at a distant target so a first-hop router replies with
// time-exceeded, populating the error queue.
runCatching {
Os.sendto(fd, ByteArray(32), 0, 32, 0, InetAddress.getByName("1.1.1.1"), 33434)
}.onFailure { ev["sendto"] = it.message ?: "send failed" }
val hasMsghdr = classExists("android.system.StructMsghdr")
val hasRecvmsg = Os::class.java.methods.any { it.name == "recvmsg" }
ev["StructMsghdr"] = hasMsghdr.toString()
ev["Os.recvmsg"] = hasRecvmsg.toString()
val sockoptsOk = recverr == null && ttl == null
val verdict = when {
sockoptsOk && hasRecvmsg && hasMsghdr -> Verdict.SUPPORTED
sockoptsOk -> Verdict.PARTIAL // options work; error-queue read needs native shim
else -> Verdict.UNSUPPORTED
}
val summary = when (verdict) {
Verdict.SUPPORTED -> "Errqueue path fully reachable from Os API"
Verdict.PARTIAL -> "Sockopts OK; MSG_ERRQUEUE read needs native shim (expected)"
else -> "IP_RECVERR/IP_TTL not accepted"
}
ProbeResult.of(this@ErrqueueProbe, verdict, summary, ev, (System.nanoTime() - start) / 1_000_000)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
ProbeResult.of(this@ErrqueueProbe, Verdict.ERROR, "errqueue probe failed", ev,
(System.nanoTime() - start) / 1_000_000)
} finally {
fd?.let { runCatching { Os.close(it) } }
}
}
private fun classExists(name: String) = runCatching { Class.forName(name) }.isSuccess
}
@@ -0,0 +1,119 @@
package app.echo_lot.prober.probe
import android.content.Context
import android.system.Os
import android.system.OsConstants
import android.system.StructTimeval
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.FileDescriptor
import java.net.Inet4Address
import java.net.InetAddress
import java.nio.ByteBuffer
/**
* Probes the unprivileged ICMP echo path: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP).
* Android opens ping_group_range to all UIDs, so this should work without root or CAP_NET_RAW.
* If it does, the production app never needs to shell out to /system/bin/ping.
*/
class IcmpProbe(
private val v6: Boolean = false,
private val targetHost: String = if (v6) "2606:4700:4700::1111" else "1.1.1.1",
) : Probe {
override val id = if (v6) "icmp.ping6" else "icmp.ping4"
override val title = if (v6) "ICMPv6 echo (unprivileged datagram socket)"
else "ICMPv4 echo (unprivileged datagram socket)"
override val tier = Tier.APP
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
var fd: FileDescriptor? = null
try {
val proto = if (v6) OsConstants.IPPROTO_ICMPV6 else OsConstants.IPPROTO_ICMP
val family = if (v6) OsConstants.AF_INET6 else OsConstants.AF_INET
fd = Os.socket(family, OsConstants.SOCK_DGRAM, proto)
ev["socket"] = "opened family=$family proto=$proto"
Os.setsockoptTimeval(
fd, OsConstants.SOL_SOCKET, OsConstants.SO_RCVTIMEO,
StructTimeval.fromMillis(3000),
)
val addr = InetAddress.getByName(targetHost)
ev["target"] = addr.hostAddress ?: targetHost
val ident = (Os.getpid() and 0xFFFF)
val packet = buildEchoRequest(v6, ident.toShort(), seq = 1)
val t0 = System.nanoTime()
Os.sendto(fd, packet, 0, packet.size, 0, addr, 0)
val buf = ByteBuffer.allocate(1500)
val received = Os.recvfrom(fd, buf, 0, null)
val rttMs = (System.nanoTime() - t0) / 1_000_000.0
ev["bytes_received"] = received.toString()
ev["rtt_ms"] = "%.1f".format(rttMs)
// ICMP datagram (ping) sockets deliver the ICMP message with NO IP header, so the
// type byte is at offset 0 for both families. v4 echo reply = 0, v6 echo reply = 129.
val replyType = if (received > 0) buf.get(0).toInt() and 0xFF else -1
ev["reply_type"] = replyType.toString()
ev["reply_type_meaning"] = when (replyType) {
0 -> "echo reply (v4)"; 129 -> "echo reply (v6)"; else -> "other/$replyType"
}
ProbeResult.of(
this@IcmpProbe, Verdict.SUPPORTED,
"Echo reply from ${ev["target"]} in ${ev["rtt_ms"]} ms",
ev, (System.nanoTime() - start) / 1_000_000,
)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
val verdict = if (isPermissionLike(e)) Verdict.UNSUPPORTED else Verdict.ERROR
ProbeResult.of(
this@IcmpProbe, verdict,
"ICMP datagram socket failed: ${ev["error"]}",
ev, (System.nanoTime() - start) / 1_000_000,
)
} finally {
fd?.let { runCatching { Os.close(it) } }
}
}
private fun isPermissionLike(e: Throwable): Boolean {
val m = (e.message ?: "").uppercase()
return "EACCES" in m || "EPERM" in m || "EAFNOSUPPORT" in m || "EPROTONOSUPPORT" in m
}
/** Minimal ICMP echo request; kernel fills checksum for ICMPv6, we compute it for ICMPv4. */
private fun buildEchoRequest(v6: Boolean, ident: Short, seq: Short): ByteArray {
val type = if (v6) 128 else 8 // echo request
val payload = "echolot-prober".toByteArray()
val pkt = ByteBuffer.allocate(8 + payload.size)
pkt.put(type.toByte()) // type
pkt.put(0) // code
pkt.putShort(0) // checksum placeholder
pkt.putShort(ident)
pkt.putShort(seq)
pkt.put(payload)
val bytes = pkt.array()
if (!v6) {
val cs = checksum(bytes)
bytes[2] = (cs.toInt() shr 8).toByte()
bytes[3] = (cs.toInt() and 0xFF).toByte()
}
return bytes
}
private fun checksum(b: ByteArray): Short {
var sum = 0
var i = 0
while (i < b.size - 1) {
sum += ((b[i].toInt() and 0xFF) shl 8) or (b[i + 1].toInt() and 0xFF)
i += 2
}
if (i < b.size) sum += (b[i].toInt() and 0xFF) shl 8
while (sum shr 16 != 0) sum = (sum and 0xFFFF) + (sum shr 16)
return sum.inv().toShort()
}
}
@@ -0,0 +1,61 @@
package app.echo_lot.prober.probe
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.NetworkCapabilities
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Reads what the platform will hand us for free about every active Network: addresses, routes,
* DNS, MTU, NAT64 prefix, private-DNS state. This is the app-tier baseline the whole IPv4/IPv6
* config analysis is built on. Also surfaces DhcpInfo indirectly (via route/DNS/gateway).
*/
class LinkPropertiesProbe : Probe {
override val id = "link.snapshot"
override val title = "LinkProperties snapshot (all active networks)"
override val tier = Tier.APP
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
try {
val cm = context.getSystemService(ConnectivityManager::class.java)
val nets = cm.allNetworks
ev["network_count"] = nets.size.toString()
var idx = 0
for (n in nets) {
val caps: NetworkCapabilities? = cm.getNetworkCapabilities(n)
val lp: LinkProperties? = cm.getLinkProperties(n)
val transport = when {
caps == null -> "?"
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "wifi"
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "cellular"
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ethernet"
caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> "vpn"
else -> "other"
}
val p = "net$idx.$transport"
if (lp != null) {
ev["$p.iface"] = lp.interfaceName ?: "?"
ev["$p.mtu"] = lp.mtu.toString()
ev["$p.addrs"] = lp.linkAddresses.joinToString(", ") { it.toString() }
ev["$p.dns"] = lp.dnsServers.joinToString(", ") { it.hostAddress ?: "?" }
ev["$p.routes"] = lp.routes.joinToString(" | ") { it.toString() }
ev["$p.domains"] = lp.domains ?: ""
runCatching { ev["$p.nat64"] = lp.nat64Prefix?.toString() ?: "none" }
runCatching { ev["$p.private_dns"] = lp.privateDnsServerName ?: "off/opportunistic" }
}
idx++
}
val verdict = if (nets.isNotEmpty()) Verdict.SUPPORTED else Verdict.INCONCLUSIVE
ProbeResult.of(this@LinkPropertiesProbe, verdict,
"${nets.size} active network(s) read", ev, (System.nanoTime() - start) / 1_000_000)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
ProbeResult.of(this@LinkPropertiesProbe, Verdict.ERROR, "read failed", ev,
(System.nanoTime() - start) / 1_000_000)
}
}
}
@@ -0,0 +1,83 @@
package app.echo_lot.prober.probe
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.coroutines.resume
/**
* Probes the headline no-root feature: holding Wi-Fi, cellular, and USB ethernet up at once via
* requestNetwork, then binding a socket per network. This is what lets the app run the same
* battery over every path simultaneously and diff them. We request each transport and report
* which ones produced a bindable Network within a timeout.
*/
class MultiNetworkProbe : Probe {
override val id = "multinetwork.request_and_bind"
override val title = "Concurrent per-network binding (Wi-Fi / cellular / ethernet)"
override val tier = Tier.APP
private val transports = listOf(
"wifi" to NetworkCapabilities.TRANSPORT_WIFI,
"cellular" to NetworkCapabilities.TRANSPORT_CELLULAR,
"ethernet" to NetworkCapabilities.TRANSPORT_ETHERNET,
)
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
val cm = context.getSystemService(ConnectivityManager::class.java)
var bound = 0
try {
for ((name, transport) in transports) {
val net: Network? = withTimeoutOrNull(4000) { requestNetwork(cm, transport) }
if (net == null) {
ev[name] = "no network within 4s"
continue
}
val bindOk = runCatching {
val s = java.net.Socket()
net.bindSocket(s)
s.close()
true
}.getOrElse { false }
val caps = cm.getNetworkCapabilities(net)
val down = caps?.linkDownstreamBandwidthKbps ?: -1
ev[name] = "network acquired; bindSocket=${if (bindOk) "ok" else "FAILED"}; downKbps=$down"
if (bindOk) bound++
}
val verdict = when {
bound >= 2 -> Verdict.SUPPORTED
bound == 1 -> Verdict.PARTIAL
else -> Verdict.INCONCLUSIVE
}
ProbeResult.of(this@MultiNetworkProbe, verdict,
"$bound transport(s) acquired and bound (only currently-present links can bind)",
ev, (System.nanoTime() - start) / 1_000_000)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
ProbeResult.of(this@MultiNetworkProbe, Verdict.ERROR, "multi-network probe failed", ev,
(System.nanoTime() - start) / 1_000_000)
}
}
private suspend fun requestNetwork(cm: ConnectivityManager, transport: Int): Network =
suspendCancellableCoroutine { cont ->
val req = NetworkRequest.Builder()
.addTransportType(transport)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (cont.isActive) cont.resume(network)
}
}
cm.requestNetwork(req, cb)
cont.invokeOnCancellation { runCatching { cm.unregisterNetworkCallback(cb) } }
}
}
@@ -0,0 +1,65 @@
package app.echo_lot.prober.probe
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.net.wifi.WifiManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicInteger
/**
* Probes multicast reception (MulticastLock + NSD/mDNS discovery). Confirms the app can do the
* mDNS/SSDP/LLMNR service inventory that doubles as the VLAN-leakage detector. Uses NsdManager
* as the least-privileged path; a raw 224.0.0.251:5353 listener is the fuller implementation.
*/
class MulticastProbe : Probe {
override val id = "local.mdns_discover"
override val title = "Multicast reception (MulticastLock + mDNS/NSD)"
override val tier = Tier.APP
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
val wifi = context.getSystemService(WifiManager::class.java)
val lock = wifi?.createMulticastLock("echolot-prober")?.apply {
setReferenceCounted(false)
runCatching { acquire() }
}
ev["multicast_lock"] = if (lock?.isHeld == true) "acquired" else "not held"
val nsd = context.getSystemService(NsdManager::class.java)
val found = AtomicInteger(0)
val started = java.util.concurrent.atomic.AtomicBoolean(false)
val serviceType = "_services._dns-sd._udp." // meta-query: enumerates service types
val listener = object : NsdManager.DiscoveryListener {
override fun onStartDiscoveryFailed(t: String?, code: Int) {}
override fun onStopDiscoveryFailed(t: String?, code: Int) {}
override fun onDiscoveryStarted(t: String?) { started.set(true) }
override fun onDiscoveryStopped(t: String?) {}
override fun onServiceFound(s: NsdServiceInfo?) { found.incrementAndGet() }
override fun onServiceLost(s: NsdServiceInfo?) {}
}
try {
nsd.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, listener)
delay(4000)
runCatching { nsd.stopServiceDiscovery(listener) }
ev["discovery_started"] = started.get().toString()
ev["services_found"] = found.get().toString()
val verdict = when {
started.get() -> Verdict.SUPPORTED
else -> Verdict.INCONCLUSIVE
}
ProbeResult.of(this@MulticastProbe, verdict,
"mDNS discovery ${if (started.get()) "ran" else "did not start"}; ${found.get()} service type(s) seen",
ev, (System.nanoTime() - start) / 1_000_000)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
ProbeResult.of(this@MulticastProbe, Verdict.ERROR, "mDNS probe failed", ev,
(System.nanoTime() - start) / 1_000_000)
} finally {
runCatching { lock?.release() }
}
}
}
@@ -0,0 +1,50 @@
package app.echo_lot.prober.probe
import android.system.Os
import java.io.FileDescriptor
/**
* Linux socket-option ABI numbers that android.system.OsConstants does NOT reliably expose.
* These are stable across Android's supported ABIs at the IP/IPv6 protocol levels, which is
* exactly why a prober can hardcode them: if setsockoptInt with one of these succeeds, the
* kernel accepted the option; if it throws ErrnoException, it did not. Either outcome is data.
*/
object OsAbi {
// IP level
const val IP_TTL = 2
const val IP_MTU_DISCOVER = 10
const val IP_MTU = 14
const val IP_RECVERR = 11
const val IP_PMTUDISC_DO = 2 // set DF, honor PMTU
const val IP_PMTUDISC_PROBE = 3 // set DF, ignore PMTU (for probing)
// IPv6 level
const val IPV6_MTU_DISCOVER = 23
const val IPV6_MTU = 24
const val IPV6_RECVERR = 25
const val IPV6_UNICAST_HOPS = 16
const val IPV6_PMTUDISC_PROBE = 3
/** Try setsockoptInt; return null on success, or the errno name on failure. */
fun trySetIntOpt(fd: FileDescriptor, level: Int, opt: Int, value: Int): String? =
try {
Os.setsockoptInt(fd, level, opt, value)
null
} catch (e: Throwable) {
e.message ?: e.javaClass.simpleName
}
/**
* getsockoptInt is not part of the stable public Os surface on every API level, so we reach
* it via reflection and let the prober report whether the call path even exists.
*/
fun tryGetIntOpt(fd: FileDescriptor, level: Int, opt: Int): Result<Int> = runCatching {
val m = Os::class.java.getMethod(
"getsockoptInt",
FileDescriptor::class.java,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
)
m.invoke(null, fd, level, opt) as Int
}
}
@@ -0,0 +1,71 @@
package app.echo_lot.prober.probe
import android.content.Context
import kotlinx.serialization.Serializable
/**
* A capability probe. Each probe attempts one borderline no-root operation from the Echolot
* feasibility matrix and reports whether it worked on THIS device / Android build, plus the
* raw evidence needed to understand why.
*
* The prober's whole point is to turn the spec's "should work / needs verification" notes into
* observed facts on real hardware before the production app hardens around them.
*/
interface Probe {
/** Stable id, dotted, mirrors the measurement-schema test type where one exists. */
val id: String
/** One-line human description shown in the UI. */
val title: String
/** Which trust tier this probe exercises. */
val tier: Tier
suspend fun run(context: Context): ProbeResult
}
enum class Tier { APP, SHIZUKU }
enum class Verdict {
/** Capability confirmed working. */
SUPPORTED,
/** Capability partially works (e.g. sockopt accepted but result read needs native). */
PARTIAL,
/** Capability not available on this device/build. */
UNSUPPORTED,
/** Could not determine (missing permission, no matching network, timeout). */
INCONCLUSIVE,
/** Probe threw unexpectedly. */
ERROR,
}
@Serializable
data class ProbeResult(
val id: String,
val title: String,
val tier: String,
val verdict: String,
/** Short conclusion, e.g. "ICMP datagram socket usable; RTT 14 ms to 1.1.1.1". */
val summary: String,
/** Raw key/value evidence (sockopt return codes, addresses, dump excerpts, timings). */
val evidence: Map<String, String> = emptyMap(),
val durationMs: Long = 0,
) {
companion object {
fun of(
probe: Probe,
verdict: Verdict,
summary: String,
evidence: Map<String, String> = emptyMap(),
durationMs: Long = 0,
) = ProbeResult(
id = probe.id,
title = probe.title,
tier = probe.tier.name,
verdict = verdict.name,
summary = summary,
evidence = evidence,
durationMs = durationMs,
)
}
}
@@ -0,0 +1,16 @@
package app.echo_lot.prober.probe
/** All probes the app runs, in display order. */
object ProbeRegistry {
val all: List<Probe> = listOf(
LinkPropertiesProbe(),
IcmpProbe(v6 = false),
IcmpProbe(v6 = true),
SockOptProbe(),
ErrqueueProbe(),
MultiNetworkProbe(),
MulticastProbe(),
BleAdvertiseProbe(),
ShizukuProbe(),
)
}
@@ -0,0 +1,67 @@
package app.echo_lot.prober.probe
import android.content.Context
import app.echo_lot.prober.shizuku.ShizukuRunner
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Probes the Shizuku tier end to end: is the binder alive, is permission granted, does a bound
* UserService run as shell/root, and does the shell-privilege command battery actually return
* the data the production app wants (neighbor table, RA-derived routes with lifetimes, live
* netlink monitor, IpClient DHCP logs). Every command's output is captured as evidence so we can
* see the real, per-device dump format the parsers must handle.
*/
class ShizukuProbe : Probe {
override val id = "shizuku.command_battery"
override val title = "Shizuku shell tier (ip neigh / route / dumpsys network_stack)"
override val tier = Tier.SHIZUKU
// Kept short so the whole battery finishes quickly; ip monitor is time-bounded with timeout.
private val battery = listOf(
"id" to "id",
"ip_neigh" to "ip neigh show",
"ip6_route" to "ip -6 route show table all",
"ip_addr" to "ip addr show",
"ip_monitor" to "timeout 2 ip monitor all || true",
"dhcp_log" to "dumpsys network_stack 2>/dev/null | grep -iA2 -m 20 -e dhcp -e 'IpClient' || true",
"wifi_dump" to "dumpsys wifi 2>/dev/null | grep -iA1 -m 20 -e 'mDhcpResults' -e 'Gateway' -e 'DNS' || true",
)
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
val runner = ShizukuRunner(context)
val st = runner.status()
ev["binder_alive"] = st.binderAlive.toString()
ev["version"] = st.version.toString()
ev["runs_as"] = st.uidName
ev["permission"] = st.permissionGranted.toString()
if (!st.binderAlive) {
return@withContext ProbeResult.of(this@ShizukuProbe, Verdict.INCONCLUSIVE,
"Shizuku not running (start Shizuku via wireless ADB and retry)", ev,
(System.nanoTime() - start) / 1_000_000)
}
if (!st.permissionGranted) {
val granted = runner.requestPermission()
ev["permission_after_request"] = granted.toString()
if (!granted) {
return@withContext ProbeResult.of(this@ShizukuProbe, Verdict.INCONCLUSIVE,
"Shizuku permission not granted", ev, (System.nanoTime() - start) / 1_000_000)
}
}
var ok = 0
for ((key, cmd) in battery) {
val out = runner.exec(cmd, timeoutMs = 6000)
// Truncate each excerpt so evidence stays readable; full capture is future work.
ev[key] = out.trim().take(1200)
if (!out.startsWith("SHIZUKU_") && !out.startsWith("EXEC_") && out.isNotBlank()) ok++
}
val verdict = if (ok >= 4) Verdict.SUPPORTED else if (ok >= 1) Verdict.PARTIAL else Verdict.UNSUPPORTED
ProbeResult.of(this@ShizukuProbe, verdict,
"Shizuku runs as ${st.uidName}; $ok/${battery.size} commands returned data",
ev, (System.nanoTime() - start) / 1_000_000)
}
}
@@ -0,0 +1,75 @@
package app.echo_lot.prober.probe
import android.content.Context
import android.system.Os
import android.system.OsConstants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.FileDescriptor
import java.net.InetAddress
import java.net.InetSocketAddress
/**
* Probes the setsockopt families the production probe engine depends on: TTL control
* (traceroute), IP_RECVERR (errqueue-based traceroute + PMTUD), and DF / IP_MTU_DISCOVER
* (MTU probing). We only need to learn which options the kernel accepts here; actually
* reading the error queue is the native shim's job and is probed separately.
*/
class SockOptProbe : Probe {
override val id = "sockopt.matrix"
override val title = "Socket options: TTL, RECVERR, MTU_DISCOVER (DF)"
override val tier = Tier.APP
override suspend fun run(context: Context): ProbeResult = withContext(Dispatchers.IO) {
val start = System.nanoTime()
val ev = LinkedHashMap<String, String>()
var fd: FileDescriptor? = null
try {
fd = Os.socket(OsConstants.AF_INET, OsConstants.SOCK_DGRAM, OsConstants.IPPROTO_UDP)
ev["IP_TTL"] = OsAbi.trySetIntOpt(fd, OsConstants.IPPROTO_IP, OsAbi.IP_TTL, 5)
?.let { "reject: $it" } ?: "accepted (ttl=5)"
ev["IP_TOS/DSCP"] = OsAbi.trySetIntOpt(fd, OsConstants.IPPROTO_IP, OsConstants.IP_TOS, 0xB8)
?.let { "reject: $it" } ?: "accepted (EF/46)"
ev["IP_RECVERR"] = OsAbi.trySetIntOpt(fd, OsConstants.IPPROTO_IP, OsAbi.IP_RECVERR, 1)
?.let { "reject: $it" } ?: "accepted"
ev["IP_MTU_DISCOVER=PROBE"] = OsAbi.trySetIntOpt(
fd, OsConstants.IPPROTO_IP, OsAbi.IP_MTU_DISCOVER, OsAbi.IP_PMTUDISC_PROBE,
)?.let { "reject: $it" } ?: "accepted (DF set)"
// After connecting, IP_MTU should report the path MTU guess.
runCatching {
Os.connect(fd, InetAddress.getByName("1.1.1.1"), 33434)
}
val mtu = OsAbi.tryGetIntOpt(fd, OsConstants.IPPROTO_IP, OsAbi.IP_MTU)
ev["IP_MTU(read)"] = mtu.fold(
onSuccess = { "$it (getsockoptInt reachable)" },
onFailure = { "unreadable: ${it.message ?: it.javaClass.simpleName}" },
)
val accepted = ev.values.count { it.startsWith("accepted") }
val verdict = when {
accepted >= 4 -> Verdict.SUPPORTED
accepted >= 2 -> Verdict.PARTIAL
else -> Verdict.UNSUPPORTED
}
ProbeResult.of(
this@SockOptProbe, verdict,
"$accepted/4 core sockopts accepted; IP_MTU read=${mtu.isSuccess}",
ev, (System.nanoTime() - start) / 1_000_000,
)
} catch (e: Throwable) {
ev["error"] = e.message ?: e.javaClass.simpleName
ProbeResult.of(
this@SockOptProbe, Verdict.ERROR,
"sockopt probe failed: ${ev["error"]}", ev,
(System.nanoTime() - start) / 1_000_000,
)
} finally {
fd?.let { runCatching { Os.close(it) } }
}
}
}
@@ -0,0 +1,90 @@
package app.echo_lot.prober.shizuku
import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.IBinder
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeoutOrNull
import rikka.shizuku.Shizuku
/**
* Thin wrapper over the Shizuku binder + a bound UserService. Reports availability, permission,
* and can run shell commands as the shell/root user.
*/
class ShizukuRunner(private val context: Context) {
data class Status(
val binderAlive: Boolean,
val version: Int,
val uidName: String,
val permissionGranted: Boolean,
)
fun status(): Status {
val alive = runCatching { Shizuku.pingBinder() }.getOrDefault(false)
val version = if (alive) runCatching { Shizuku.getVersion() }.getOrDefault(-1) else -1
val uid = if (alive) runCatching { Shizuku.getUid() }.getOrDefault(-1) else -1
val uidName = when (uid) {
0 -> "root(0)"
2000 -> "shell(2000)"
-1 -> "unknown"
else -> "uid=$uid"
}
val granted = alive && runCatching {
Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED
}.getOrDefault(false)
return Status(alive, version, uidName, granted)
}
suspend fun requestPermission(): Boolean {
val s = status()
if (!s.binderAlive) return false
if (s.permissionGranted) return true
val deferred = CompletableDeferred<Boolean>()
val code = 0xE1
val listener = object : Shizuku.OnRequestPermissionResultListener {
override fun onRequestPermissionResult(requestCode: Int, grantResult: Int) {
if (requestCode == code) {
Shizuku.removeRequestPermissionResultListener(this)
deferred.complete(grantResult == PackageManager.PERMISSION_GRANTED)
}
}
}
Shizuku.addRequestPermissionResultListener(listener)
runCatching { Shizuku.requestPermission(code) }
return withTimeoutOrNull(30000) { deferred.await() } ?: false
}
private val serviceArgs = Shizuku.UserServiceArgs(
ComponentName(context.packageName, UserService::class.java.name),
)
.daemon(false)
.processNameSuffix("prober")
.version(1)
/** Bind the UserService, run one command, and return combined output (or an error string). */
suspend fun exec(command: String, timeoutMs: Int = 8000): String {
val bound = CompletableDeferred<IUserService?>()
val conn = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
bound.complete(
if (binder != null && binder.pingBinder()) IUserService.Stub.asInterface(binder) else null,
)
}
override fun onServiceDisconnected(name: ComponentName?) {}
}
return try {
Shizuku.bindUserService(serviceArgs, conn)
val svc = withTimeoutOrNull(10000) { bound.await() }
?: return "SHIZUKU_BIND_TIMEOUT"
withTimeoutOrNull(timeoutMs.toLong() + 4000) { svc.exec(command, timeoutMs) }
?: "EXEC_TIMEOUT"
} catch (e: Throwable) {
"SHIZUKU_ERROR: ${e.message ?: e.javaClass.simpleName}"
} finally {
runCatching { Shizuku.unbindUserService(serviceArgs, conn, true) }
}
}
}
@@ -0,0 +1,47 @@
package app.echo_lot.prober.shizuku
import kotlin.system.exitProcess
/**
* Runs inside the Shizuku-spawned process (uid = shell, 2000, or root if Shizuku was started via
* root). Because this process has the shell SELinux domain, commands here can read `ip neigh`,
* `ip monitor`, `dumpsys network_stack`, etc. — things the app UID cannot.
*
* This is the canonical Shizuku UserService pattern: a plain class with a matching constructor,
* implementing the AIDL Stub.
*/
class UserService : IUserService.Stub() {
// Required no-arg constructor for Shizuku UserService.
constructor()
override fun destroy() {
exitProcess(0)
}
override fun exec(command: String, timeoutMs: Int): String {
return try {
val proc = ProcessBuilder("sh", "-c", command)
.redirectErrorStream(true)
.start()
val output = StringBuilder()
val reader = proc.inputStream.bufferedReader()
val deadline = System.currentTimeMillis() + timeoutMs.coerceIn(500, 30000)
val readerThread = Thread {
runCatching {
reader.forEachLine { line ->
if (output.length < 64 * 1024) output.append(line).append('\n')
}
}
}
readerThread.start()
while (readerThread.isAlive && System.currentTimeMillis() < deadline) {
Thread.sleep(20)
}
if (proc.isAlive) proc.destroy()
"uid=" + android.os.Process.myUid() + "\n" + output.toString()
} catch (e: Throwable) {
"EXEC_ERROR: ${e.message ?: e.javaClass.simpleName}"
}
}
}
@@ -0,0 +1,118 @@
package app.echo_lot.prober.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.echo_lot.prober.probe.ProbeResult
data class UiState(
val running: Boolean = false,
val currentTitle: String? = null,
val results: List<ProbeResult> = emptyList(),
)
@Composable
fun ProberScreen(
state: UiState,
onRun: () -> Unit,
onShare: () -> Unit,
) {
Column(Modifier.fillMaxSize().padding(16.dp)) {
Text("Echolot Capability Prober", style = MaterialTheme.typography.headlineSmall)
Text(
"Runs the borderline no-root probes from the feasibility matrix on THIS device and reports what actually works.",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 4.dp, bottom = 12.dp),
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = onRun, enabled = !state.running) {
Text(if (state.running) "Running…" else "Run all probes")
}
OutlinedButton(onClick = onShare, enabled = state.results.isNotEmpty() && !state.running) {
Text("Export JSON")
}
}
if (state.running) {
Row(
Modifier.fillMaxWidth().padding(vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
CircularProgressIndicator(Modifier.padding(2.dp))
Text(state.currentTitle ?: "Starting…", style = MaterialTheme.typography.bodyMedium)
}
}
LazyColumn(
Modifier.fillMaxWidth().padding(top = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(state.results) { r -> ResultCard(r) }
}
}
}
@Composable
private fun ResultCard(r: ProbeResult) {
Card(
Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = verdictColor(r.verdict).copy(alpha = 0.10f)),
) {
Column(Modifier.padding(12.dp)) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(r.title, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f))
Text(
r.verdict,
color = verdictColor(r.verdict),
fontWeight = FontWeight.Bold,
fontSize = 12.sp,
)
}
Text("${r.id} · ${r.tier} · ${r.durationMs} ms", fontSize = 11.sp, color = Color.Gray)
Text(r.summary, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 4.dp))
if (r.evidence.isNotEmpty()) {
Column(Modifier.padding(top = 6.dp)) {
r.evidence.forEach { (k, v) ->
Text(
"$k = $v",
fontFamily = FontFamily.Monospace,
fontSize = 10.sp,
color = Color.DarkGray,
)
}
}
}
}
}
}
private fun verdictColor(v: String): Color = when (v) {
"SUPPORTED" -> Color(0xFF2E7D32)
"PARTIAL" -> Color(0xFFF9A825)
"UNSUPPORTED" -> Color(0xFFC62828)
"INCONCLUSIVE" -> Color(0xFF1565C0)
else -> Color(0xFF6A1B9A)
}
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">Echolot Prober</string>
</resources>
@@ -0,0 +1,3 @@
<resources>
<style name="Theme.EcholotProber" parent="android:Theme.Material.Light.NoActionBar" />
</resources>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="reports" path="reports/" />
</paths>
+6
View File
@@ -0,0 +1,6 @@
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.kotlin.serialization) apply false
}
+5
View File
@@ -0,0 +1,5 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
org.gradle.caching=true
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
+31
View File
@@ -0,0 +1,31 @@
[versions]
agp = "8.7.3"
kotlin = "2.0.21"
coreKtx = "1.13.1"
lifecycle = "2.8.7"
activityCompose = "1.9.3"
composeBom = "2024.10.01"
shizuku = "13.1.5"
kotlinxSerialization = "1.7.3"
kotlinxCoroutines = "1.9.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
shizuku-api = { group = "dev.rikka.shizuku", name = "api", version.ref = "shizuku" }
shizuku-provider = { group = "dev.rikka.shizuku", name = "provider", version.ref = "shizuku" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+23
View File
@@ -0,0 +1,23 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "EcholotProber"
include(":app")