diff --git a/gearslip/build.gradle.kts b/gearslip/build.gradle.kts index 0047150..21d14cb 100644 --- a/gearslip/build.gradle.kts +++ b/gearslip/build.gradle.kts @@ -119,6 +119,8 @@ android { buildFeatures { buildConfig = true + // IShellService, the part of Gearslip that Shizuku runs with adb's powers. + aidl = true } // Lists each language that has a translation in the app's locale config, so Android 13+ @@ -200,6 +202,9 @@ dependencies { implementation(libs.androidx.webkit) // The map behind a place list (PlaceListMapTemplate), which the host draws, not the app. implementation(libs.maplibre.android) + // Shizuku, Apache 2.0. Optional: everything works without it, it only skips setup steps. + implementation(libs.shizuku.api) + implementation(libs.shizuku.provider) testImplementation(libs.junit) } diff --git a/gearslip/proguard-rules.pro b/gearslip/proguard-rules.pro index fcb05fc..b3a3821 100644 --- a/gearslip/proguard-rules.pro +++ b/gearslip/proguard-rules.pro @@ -11,3 +11,6 @@ # Speech-to-text: the native library calls back into these classes by name. -keep class com.k2fsa.sherpa.onnx.** { *; } + +# Shizuku starts the shell service in its own process by class name, with no caller R8 can see. +-keep class app.seb3thehacker.gearslip.shizuku.ShellService { (...); *; } diff --git a/gearslip/src/main/AndroidManifest.xml b/gearslip/src/main/AndroidManifest.xml index 6cd8de1..840c869 100644 --- a/gearslip/src/main/AndroidManifest.xml +++ b/gearslip/src/main/AndroidManifest.xml @@ -128,6 +128,8 @@ + + + + runOnUiThread { startWireless(socket) } } diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt index bb9e96c..bfcda66 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt @@ -663,6 +663,7 @@ class GearslipRunner( // A car known to switch Bluetooth music off gets it through Gearslip, whatever the setting. CarSettings.carConnected(ServiceDiscovery.findBluetoothService(serviceDiscoveryResponse)?.carAddress) BluetoothAudioCheck.onCarFound() + app.seb3thehacker.gearslip.car.CarEnvironment.appContext?.let { app.seb3thehacker.gearslip.shizuku.ShizukuSetup.recheckOnConnect(it) } if (CarSettings.pipesNow) { if (!CarSettings.pipeAudio.value) log.i("this car turns Bluetooth music off, so music goes through Gearslip") openChannel(media.serviceId) diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/shizuku/ShellService.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/shizuku/ShellService.kt new file mode 100644 index 0000000..a2c2353 --- /dev/null +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/shizuku/ShellService.kt @@ -0,0 +1,23 @@ +package app.seb3thehacker.gearslip.shizuku + +import androidx.annotation.Keep +import kotlin.system.exitProcess + +/** + * Runs in a process Shizuku starts as the shell user, so a command here has the same powers it + * would have typed over adb. Nothing in this class may touch the rest of Gearslip: it lives in a + * different process, with a different user, and only sees what [run] is handed. + */ +@Keep +class ShellService : IShellService.Stub() { + + override fun destroy() { + exitProcess(0) + } + + override fun run(command: String): Int { + val process = ProcessBuilder("sh", "-c", command).redirectErrorStream(true).start() + process.inputStream.readBytes() + return process.waitFor() + } +} diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/shizuku/ShizukuSetup.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/shizuku/ShizukuSetup.kt new file mode 100644 index 0000000..fc5f40f --- /dev/null +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/shizuku/ShizukuSetup.kt @@ -0,0 +1,182 @@ +package app.seb3thehacker.gearslip.shizuku + +import android.Manifest +import android.app.AppOpsManager +import android.content.ComponentName +import android.content.Context +import android.content.ServiceConnection +import android.content.pm.PackageManager +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import app.seb3thehacker.gearslip.BuildConfig +import app.seb3thehacker.gearslip.GearslipLog +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import rikka.shizuku.Shizuku + +/** + * Shizuku does Gearslip's one-time adb steps from the phone (issue #125). Both stick once done: + * + * - the PROJECT_MEDIA app-op, so Android stops asking to share the screen every drive + * - WRITE_SECURE_SETTINGS, so notifications stay readable while music is captured + * + * Everything works without Shizuku; this only saves the trip to a computer. Once both are in + * place Shizuku isn't needed again, but each car connection checks, and quietly puts back + * whatever went missing if Shizuku happens to be running. + */ +object ShizukuSetup { + + enum class State { + /** Shizuku isn't installed. Nothing about it is shown. */ + MISSING, + /** Installed, but its service isn't running. */ + STOPPED, + /** Running, and Gearslip hasn't been allowed to use it yet. */ + NEEDS_PERMISSION, + /** Running and allowed. */ + READY, + } + + private const val SHIZUKU_PACKAGE = "moe.shizuku.privileged.api" + private const val REQUEST_CODE = 125 + + private val main = Handler(Looper.getMainLooper()) + private val log = GearslipLog.tagged("shizuku") + + private val _state = MutableStateFlow(State.MISSING) + val state: StateFlow = _state + + private val _granted = MutableStateFlow(false) + /** True once both one-time steps are in place, by Shizuku or by adb. */ + val granted: StateFlow = _granted + + private val _working = MutableStateFlow(false) + val working: StateFlow = _working + + private var appContext: Context? = null + /** Waiting on the driver's answer to Shizuku's permission dialog. */ + private var afterPermission: (() -> Unit)? = null + + fun init(context: Context) { + if (appContext != null) return + appContext = context.applicationContext + Shizuku.addBinderReceivedListenerSticky { refresh() } + Shizuku.addBinderDeadListener { refresh() } + Shizuku.addRequestPermissionResultListener { code, result -> + if (code != REQUEST_CODE) return@addRequestPermissionResultListener + refresh() + val next = afterPermission + afterPermission = null + if (result == PackageManager.PERMISSION_GRANTED) next?.invoke() + else log.i("the driver didn't allow Gearslip to use Shizuku") + } + refresh() + } + + fun refresh() { + val context = appContext ?: return + _granted.value = hasProjectMedia(context) && hasSecureSettings(context) + _state.value = when { + !installed(context) -> State.MISSING + !runCatching { Shizuku.pingBinder() }.getOrDefault(false) -> State.STOPPED + runCatching { Shizuku.checkSelfPermission() }.getOrDefault(PackageManager.PERMISSION_DENIED) != + PackageManager.PERMISSION_GRANTED -> State.NEEDS_PERMISSION + else -> State.READY + } + } + + /** The button: asks Shizuku for permission if needed, then does both steps. */ + fun setUp() { + refresh() + when (_state.value) { + State.READY -> grant() + State.NEEDS_PERMISSION -> { + afterPermission = ::grant + runCatching { Shizuku.requestPermission(REQUEST_CODE) } + .onFailure { log.e("could not ask Shizuku for permission", it) } + } + else -> Unit + } + } + + /** A car connected: put back anything missing, without asking, if Shizuku is up and allowed. */ + fun recheckOnConnect(context: Context) = main.post { + init(context) + refresh() + if (!_granted.value && _state.value == State.READY) { + log.i("a one-time setup step is missing, and Shizuku is running, so Gearslip is putting it back") + grant() + } + } + + private fun grant() { + val context = appContext ?: return + if (_working.value) return + _working.value = true + val pkg = context.packageName + val commands = buildList { + if (!hasProjectMedia(context)) { + add("appops set $pkg PROJECT_MEDIA allow") + add("appops write-settings") + } + if (!hasSecureSettings(context)) add("pm grant $pkg ${Manifest.permission.WRITE_SECURE_SETTINGS}") + } + withShell( + onReady = { shell -> + for (command in commands) { + val code = runCatching { shell.run(command) }.getOrDefault(-1) + log.i("ran \"$command\" through Shizuku: exit $code") + } + }, + onDone = { + _working.value = false + refresh() + log.i(if (_granted.value) "one-time setup done through Shizuku" else "Shizuku ran, but the setup still isn't in place") + }, + ) + } + + /** Starts [ShellService] in Shizuku's shell process, runs [onReady] off the main thread, then stops it. */ + private fun withShell(onReady: (IShellService) -> Unit, onDone: () -> Unit) { + val context = appContext ?: return onDone() + val args = Shizuku.UserServiceArgs(ComponentName(context, ShellService::class.java)) + .daemon(false) + .processNameSuffix("shell") + .debuggable(BuildConfig.DEBUG) + .version(BuildConfig.VERSION_CODE) + val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, binder: IBinder?) { + val conn = this + val shell = binder?.let { IShellService.Stub.asInterface(it) } + Thread { + if (shell != null) onReady(shell) else log.w("Shizuku started the shell service without a binder") + main.post { + runCatching { Shizuku.unbindUserService(args, conn, true) } + onDone() + } + }.start() + } + + override fun onServiceDisconnected(name: ComponentName?) = Unit + } + runCatching { Shizuku.bindUserService(args, connection) }.onFailure { + log.e("could not start the shell service through Shizuku", it) + onDone() + } + } + + private fun installed(context: Context): Boolean = + runCatching { context.packageManager.getPackageInfo(SHIZUKU_PACKAGE, 0) }.isSuccess + + /** Checked the way the platform checks it; there is no public permission for it. */ + fun hasProjectMedia(context: Context): Boolean { + val ops = context.getSystemService(AppOpsManager::class.java) ?: return false + return runCatching { + ops.unsafeCheckOpNoThrow("android:project_media", android.os.Process.myUid(), context.packageName) + }.getOrDefault(AppOpsManager.MODE_IGNORED) == AppOpsManager.MODE_ALLOWED + } + + private fun hasSecureSettings(context: Context): Boolean = + context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED +} diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/AudioChoiceDialog.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/AudioChoiceDialog.kt index beebd4e..64b7ff1 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/AudioChoiceDialog.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/AudioChoiceDialog.kt @@ -43,6 +43,7 @@ fun AudioChoiceDialog(onUseBluetooth: () -> Unit, onKeepAsking: () -> Unit) { style = MaterialTheme.typography.bodyMedium, ) CopyableCommand("adb shell appops set ${BuildConfig.APPLICATION_ID} PROJECT_MEDIA allow") + ShizukuGrantButton() } // Stacked full width: three labels this long never fit the dialog's one button row. Column(Modifier.fillMaxWidth().padding(top = 4.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HelpScreen.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HelpScreen.kt index b6b4196..7a03024 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HelpScreen.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HelpScreen.kt @@ -166,6 +166,8 @@ private fun Steps(title: String, steps: List) { Text(stringResource(it), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } step.command?.let { CopyableCommand(it) } + // One button does both steps, so it sits under the first only. + if (step === USB_AUDIO.first()) ShizukuGrantButton(Modifier.padding(top = 4.dp)) if (step.onClick != null) { FilledTonalButton(onClick = step.onClick, modifier = Modifier.padding(top = 4.dp)) { Text(stringResource(step.buttonLabel ?: R.string.guide_open)) diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SetupGuideScreen.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SetupGuideScreen.kt index 98d9465..eb02ae7 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SetupGuideScreen.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SetupGuideScreen.kt @@ -547,7 +547,10 @@ fun SetupGuideScreen(onRequestCallScreening: () -> Unit, onDone: () -> Unit, onl color = c.onVariant, style = TextStyle(fontSize = cqSp(4.5f), lineHeight = cqSp(6.5f)), ) - page.command?.let { CopyableCommand(it) } + page.command?.let { + CopyableCommand(it) + ShizukuGrantButton() + } page.content?.invoke(GuideScale(c, ::cq, ::cqSp)) if (page.permissions != null && alreadyGranted) { Text( diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/ShizukuGrantButton.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/ShizukuGrantButton.kt new file mode 100644 index 0000000..c74092e --- /dev/null +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/ShizukuGrantButton.kt @@ -0,0 +1,45 @@ +package app.seb3thehacker.gearslip.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import app.seb3thehacker.gearslip.R +import app.seb3thehacker.gearslip.shizuku.ShizukuSetup + +/** + * Under an adb command: does the same from the phone, for drivers who run Shizuku. Shows nothing + * when Shizuku isn't installed, so everyone else sees the command alone, as before. + */ +@Composable +fun ShizukuGrantButton(modifier: Modifier = Modifier) { + val state by ShizukuSetup.state.collectAsState() + val granted by ShizukuSetup.granted.collectAsState() + val working by ShizukuSetup.working.collectAsState() + // Shizuku may have been started, or the grant done over adb, while Gearslip was away. + LifecycleResumeEffect(Unit) { + ShizukuSetup.refresh() + onPauseOrDispose { } + } + LaunchedEffect(Unit) { ShizukuSetup.refresh() } + if (state == ShizukuSetup.State.MISSING) return + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) { + when { + granted -> Text(stringResource(R.string.shizuku_done), style = MaterialTheme.typography.bodyMedium) + state == ShizukuSetup.State.STOPPED -> Text(stringResource(R.string.shizuku_stopped), style = MaterialTheme.typography.bodyMedium) + else -> OutlinedButton(onClick = ShizukuSetup::setUp, enabled = !working, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(if (working) R.string.shizuku_working else R.string.shizuku_set_up)) + } + } + } +} diff --git a/gearslip/src/main/res/values/strings.xml b/gearslip/src/main/res/values/strings.xml index bd89d46..d645b71 100644 --- a/gearslip/src/main/res/values/strings.xml +++ b/gearslip/src/main/res/values/strings.xml @@ -736,6 +736,10 @@ This page isn\'t encrypted. Anyone on the same network can see what you send it. Don\'t warn for this site Hide warning + Set up with Shizuku + Setting up… + Set up through Shizuku. Nothing more to do here. + Shizuku is installed but not running. Start it in the Shizuku app, then come back here. Start page Full screen diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7e77299..5c03279 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -19,6 +19,7 @@ kotlinxSerializationJson = "1.11.0" ossLicenses = "17.5.1" webkit = "1.16.0" androidxMedia = "1.6.0" +shizuku = "13.1.5" [libraries] maplibre-android = { group = "org.maplibre.gl", name = "android-sdk", version.ref = "maplibre" } @@ -54,6 +55,9 @@ okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhtt kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } google-oss-licenses = { group = "com.google.android.gms", name = "play-services-oss-licenses", version.ref = "ossLicenses" } androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" } +# Optional extras for drivers who run Shizuku: adb-level setup steps done from the phone. +shizuku-api = { group = "dev.rikka.shizuku", name = "api", version.ref = "shizuku" } +shizuku-provider = { group = "dev.rikka.shizuku", name = "provider", version.ref = "shizuku" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" }