Commit c275326d authored by Viktor De Pasquale's avatar Viktor De Pasquale

Removed direct static usages of database from app

parent d4561507
...@@ -4,7 +4,6 @@ import android.annotation.SuppressLint ...@@ -4,7 +4,6 @@ import android.annotation.SuppressLint
import android.app.Activity import android.app.Activity
import android.app.Application import android.app.Application
import android.content.Context import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration import android.content.res.Configuration
import android.os.AsyncTask import android.os.AsyncTask
import android.os.Build import android.os.Build
...@@ -29,8 +28,6 @@ open class App : Application(), Application.ActivityLifecycleCallbacks { ...@@ -29,8 +28,6 @@ open class App : Application(), Application.ActivityLifecycleCallbacks {
lateinit var protectedContext: Context lateinit var protectedContext: Context
@Deprecated("Use dependency injection", level = DeprecationLevel.ERROR)
val prefs: SharedPreferences by inject()
@Deprecated("Use dependency injection", level = DeprecationLevel.ERROR) @Deprecated("Use dependency injection", level = DeprecationLevel.ERROR)
val DB: MagiskDB by inject() val DB: MagiskDB by inject()
......
package com.topjohnwu.magisk
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.AnyThread
import androidx.annotation.WorkerThread
import com.skoumal.teanity.extensions.subscribeK
import com.topjohnwu.magisk.data.repository.SettingRepository
import com.topjohnwu.magisk.data.repository.StringRepository
import com.topjohnwu.magisk.di.Protected
import com.topjohnwu.magisk.utils.inject
object ConfigLeanback {
@JvmStatic
val protectedContext: Context by inject(Protected)
@JvmStatic
val prefs: SharedPreferences by inject()
private val settingRepo: SettingRepository by inject()
private val stringRepo: StringRepository by inject()
@JvmStatic
@AnyThread
fun put(key: String, value: Int) {
settingRepo.put(key, value).subscribeK()
}
@JvmStatic
@WorkerThread
fun get(key: String, defaultValue: Int): Int =
settingRepo.fetch(key, defaultValue).blockingGet()
@JvmStatic
@AnyThread
fun put(key: String, value: String?) {
val task = value?.let { stringRepo.put(key, it) } ?: stringRepo.delete(key)
task.subscribeK()
}
@JvmStatic
@WorkerThread
fun get(key: String, defaultValue: String?): String =
stringRepo.fetch(key, defaultValue.orEmpty()).blockingGet()
@JvmStatic
@AnyThread
fun delete(key: String) {
settingRepo.delete(key).subscribeK()
}
}
\ No newline at end of file
...@@ -14,8 +14,8 @@ class SettingsDao : BaseDao() { ...@@ -14,8 +14,8 @@ class SettingsDao : BaseDao() {
values(key to value.toString()) values(key to value.toString())
}.ignoreElement() }.ignoreElement()
fun fetch(key: String) = query<Select> { fun fetch(key: String, default: Int = -1) = query<Select> {
condition { equals("key", key) } condition { equals("key", key) }
}.map { it.first().values.first().toIntOrNull() ?: -1 } }.map { it.firstOrNull()?.values?.firstOrNull()?.toIntOrNull() ?: default }
} }
\ No newline at end of file
...@@ -31,6 +31,8 @@ class LogRepository( ...@@ -31,6 +31,8 @@ class LogRepository(
.toSingle() .toSingle()
.map { it.exec() } .map { it.exec() }
fun put(log: MagiskLog) = logDao.put(log)
private fun List<MagiskLog>.wrap(): List<WrappedMagiskLog> { private fun List<MagiskLog>.wrap(): List<WrappedMagiskLog> {
val day = TimeUnit.DAYS.toMillis(1) val day = TimeUnit.DAYS.toMillis(1)
return groupBy { it.date.time / day } return groupBy { it.date.time / day }
......
...@@ -4,7 +4,7 @@ import com.topjohnwu.magisk.data.database.SettingsDao ...@@ -4,7 +4,7 @@ import com.topjohnwu.magisk.data.database.SettingsDao
class SettingRepository(private val settingsDao: SettingsDao) { class SettingRepository(private val settingsDao: SettingsDao) {
fun fetch(key: String) = settingsDao.fetch(key) fun fetch(key: String, default: Int) = settingsDao.fetch(key, default)
fun put(key: String, value: Int) = settingsDao.put(key, value) fun put(key: String, value: Int) = settingsDao.put(key, value)
fun delete(key: String) = settingsDao.delete(key) fun delete(key: String) = settingsDao.delete(key)
......
...@@ -4,7 +4,7 @@ import com.topjohnwu.magisk.data.database.StringDao ...@@ -4,7 +4,7 @@ import com.topjohnwu.magisk.data.database.StringDao
class StringRepository(private val stringDao: StringDao) { class StringRepository(private val stringDao: StringDao) {
fun fetch(key: String) = stringDao.fetch(key) fun fetch(key: String, default: String) = stringDao.fetch(key, default)
fun put(key: String, value: String) = stringDao.put(key, value) fun put(key: String, value: String) = stringDao.put(key, value)
fun delete(key: String) = stringDao.delete(key) fun delete(key: String) = stringDao.delete(key)
......
...@@ -12,8 +12,7 @@ val applicationModule = module { ...@@ -12,8 +12,7 @@ val applicationModule = module {
factory { get<Context>().resources } factory { get<Context>().resources }
factory { get<Context>() as App } factory { get<Context>() as App }
factory { get<Context>().packageManager } factory { get<Context>().packageManager }
single(SUTimeout) { factory(Protected) { get<App>().protectedContext }
get<App>().protectedContext.getSharedPreferences("su_timeout", 0) single(SUTimeout) { get<Context>(Protected).getSharedPreferences("su_timeout", 0) }
} single { PreferenceManager.getDefaultSharedPreferences(get<Context>(Protected)) }
single { PreferenceManager.getDefaultSharedPreferences(get<App>().protectedContext) }
} }
...@@ -2,4 +2,5 @@ package com.topjohnwu.magisk.di ...@@ -2,4 +2,5 @@ package com.topjohnwu.magisk.di
import org.koin.core.qualifier.named import org.koin.core.qualifier.named
val SUTimeout = named("su_timeout") val SUTimeout = named("su_timeout")
\ No newline at end of file val Protected = named("protected")
\ No newline at end of file
package com.topjohnwu.magisk.model.entity package com.topjohnwu.magisk.model.entity
import com.topjohnwu.magisk.model.entity.MagiskPolicy.Companion.ALLOW
import com.topjohnwu.magisk.utils.timeFormatTime import com.topjohnwu.magisk.utils.timeFormatTime
import com.topjohnwu.magisk.utils.toTime import com.topjohnwu.magisk.utils.toTime
import java.util.* import java.util.*
...@@ -47,4 +48,11 @@ fun MagiskLog.toMap() = mapOf( ...@@ -47,4 +48,11 @@ fun MagiskLog.toMap() = mapOf(
"command" to command, "command" to command,
"action" to action, "action" to action,
"time" to date "time" to date
).mapValues { it.toString() } ).mapValues { it.toString() }
\ No newline at end of file
fun MagiskPolicy.toLog(
toUid: Int,
fromPid: Int,
command: String,
date: Date
) = MagiskLog(uid, toUid, fromPid, packageName, appName, command, policy == ALLOW, date)
...@@ -2,18 +2,27 @@ package com.topjohnwu.magisk.model.entity ...@@ -2,18 +2,27 @@ package com.topjohnwu.magisk.model.entity
import android.content.pm.ApplicationInfo import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager import android.content.pm.PackageManager
import com.topjohnwu.magisk.model.entity.MagiskPolicy.Companion.INTERACTIVE
data class MagiskPolicy( data class MagiskPolicy(
val uid: Int, val uid: Int,
val packageName: String, val packageName: String,
val appName: String, val appName: String,
val policy: Int, val policy: Int = INTERACTIVE,
val until: Long, val until: Long = -1L,
val logging: Boolean, val logging: Boolean = true,
val notification: Boolean, val notification: Boolean = true,
val applicationInfo: ApplicationInfo val applicationInfo: ApplicationInfo
) ) {
companion object {
const val INTERACTIVE = 0
const val DENY = 1
const val ALLOW = 2
}
}
/*@Throws(PackageManager.NameNotFoundException::class) /*@Throws(PackageManager.NameNotFoundException::class)
fun ContentValues.toPolicy(pm: PackageManager): MagiskPolicy { fun ContentValues.toPolicy(pm: PackageManager): MagiskPolicy {
...@@ -64,11 +73,24 @@ fun Map<String, String>.toPolicy(pm: PackageManager): MagiskPolicy { ...@@ -64,11 +73,24 @@ fun Map<String, String>.toPolicy(pm: PackageManager): MagiskPolicy {
return MagiskPolicy( return MagiskPolicy(
uid = uid, uid = uid,
packageName = packageName, packageName = packageName,
policy = get("policy")?.toIntOrNull() ?: -1, policy = get("policy")?.toIntOrNull() ?: INTERACTIVE,
until = get("until")?.toLongOrNull() ?: -1L, until = get("until")?.toLongOrNull() ?: -1L,
logging = get("logging")?.toIntOrNull() != 0, logging = get("logging")?.toIntOrNull() != 0,
notification = get("notification")?.toIntOrNull() != 0, notification = get("notification")?.toIntOrNull() != 0,
applicationInfo = info, applicationInfo = info,
appName = info.loadLabel(pm).toString() appName = info.loadLabel(pm).toString()
) )
}
@Throws(PackageManager.NameNotFoundException::class)
fun Int.toPolicy(pm: PackageManager): MagiskPolicy {
val pkg = pm.getPackagesForUid(this)?.firstOrNull()
?: throw PackageManager.NameNotFoundException()
val info = pm.getApplicationInfo(pkg, 0)
return MagiskPolicy(
uid = this,
packageName = pkg,
applicationInfo = info,
appName = info.loadLabel(pm).toString()
)
} }
\ No newline at end of file
...@@ -15,11 +15,11 @@ public class SuLogEntry { ...@@ -15,11 +15,11 @@ public class SuLogEntry {
public boolean action; public boolean action;
public Date date; public Date date;
public SuLogEntry(Policy policy) { public SuLogEntry(MagiskPolicy policy) {
fromUid = policy.uid; fromUid = policy.getUid();
packageName = policy.packageName; packageName = policy.getPackageName();
appName = policy.appName; appName = policy.getAppName();
action = policy.policy == Policy.ALLOW; action = policy.getPolicy() == Policy.ALLOW;
} }
public SuLogEntry(ContentValues values) { public SuLogEntry(ContentValues values) {
......
package com.topjohnwu.magisk.model.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.topjohnwu.magisk.App;
import com.topjohnwu.magisk.ClassMap;
import com.topjohnwu.magisk.Config;
import com.topjohnwu.magisk.Const;
import com.topjohnwu.magisk.ui.surequest.SuRequestActivity;
import com.topjohnwu.magisk.utils.DownloadApp;
import com.topjohnwu.magisk.utils.SuLogger;
import com.topjohnwu.magisk.view.Notifications;
import com.topjohnwu.magisk.view.Shortcuts;
import com.topjohnwu.superuser.Shell;
public class GeneralReceiver extends BroadcastReceiver {
private String getPkg(Intent i) {
return i.getData() == null ? "" : i.getData().getEncodedSchemeSpecificPart();
}
@Override
public void onReceive(Context context, Intent intent) {
App app = App.self;
if (intent == null)
return;
String action = intent.getAction();
if (action == null)
return;
switch (action) {
case Intent.ACTION_REBOOT:
case Intent.ACTION_BOOT_COMPLETED:
action = intent.getStringExtra("action");
if (action == null) {
// Actual boot completed event
Shell.su("mm_patch_dtbo").submit(result -> {
if (result.isSuccess())
Notifications.dtboPatched();
});
break;
}
switch (action) {
case SuRequestActivity.REQUEST:
Intent i = new Intent(app, ClassMap.get(SuRequestActivity.class))
.setAction(action)
.putExtra("socket", intent.getStringExtra("socket"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
app.startActivity(i);
break;
case SuRequestActivity.LOG:
SuLogger.handleLogs(intent);
break;
case SuRequestActivity.NOTIFY:
SuLogger.handleNotify(intent);
break;
}
break;
case Intent.ACTION_PACKAGE_REPLACED:
// This will only work pre-O
if (Config.get(Config.Key.SU_REAUTH)) {
app.getDB().deletePolicy(getPkg(intent));
}
break;
case Intent.ACTION_PACKAGE_FULLY_REMOVED:
String pkg = getPkg(intent);
app.getDB().deletePolicy(pkg);
Shell.su("magiskhide --rm " + pkg).submit();
break;
case Intent.ACTION_LOCALE_CHANGED:
Shortcuts.setup(context);
break;
case Const.Key.BROADCAST_MANAGER_UPDATE:
Config.managerLink = intent.getStringExtra(Const.Key.INTENT_SET_LINK);
DownloadApp.upgrade(intent.getStringExtra(Const.Key.INTENT_SET_NAME));
break;
case Const.Key.BROADCAST_REBOOT:
Shell.su("/system/bin/reboot").submit();
break;
}
}
}
package com.topjohnwu.magisk.model.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.topjohnwu.magisk.ClassMap
import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.Const
import com.topjohnwu.magisk.data.database.base.su
import com.topjohnwu.magisk.data.repository.AppRepository
import com.topjohnwu.magisk.ui.surequest.SuRequestActivity
import com.topjohnwu.magisk.utils.DownloadApp
import com.topjohnwu.magisk.utils.SuLogger
import com.topjohnwu.magisk.utils.inject
import com.topjohnwu.magisk.view.Notifications
import com.topjohnwu.magisk.view.Shortcuts
import com.topjohnwu.superuser.Shell
open class GeneralReceiver : BroadcastReceiver() {
private val appRepo: AppRepository by inject()
private fun getPkg(i: Intent): String {
return if (i.data == null) "" else i.data!!.encodedSchemeSpecificPart
}
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null)
return
var action: String? = intent.action ?: return
when (action) {
Intent.ACTION_REBOOT, Intent.ACTION_BOOT_COMPLETED -> {
action = intent.getStringExtra("action")
if (action == null) {
// Actual boot completed event
Shell.su("mm_patch_dtbo").submit { result ->
if (result.isSuccess)
Notifications.dtboPatched()
}
return
}
when (action) {
SuRequestActivity.REQUEST -> {
val i = Intent(context, ClassMap.get<Any>(SuRequestActivity::class.java))
.setAction(action)
.putExtra("socket", intent.getStringExtra("socket"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
context.startActivity(i)
}
SuRequestActivity.LOG -> SuLogger.handleLogs(intent)
SuRequestActivity.NOTIFY -> SuLogger.handleNotify(intent)
}
}
Intent.ACTION_PACKAGE_REPLACED ->
// This will only work pre-O
if (Config.get<Boolean>(Config.Key.SU_REAUTH)!!) {
appRepo.delete(getPkg(intent)).blockingGet()
}
Intent.ACTION_PACKAGE_FULLY_REMOVED -> {
val pkg = getPkg(intent)
appRepo.delete(pkg).blockingGet()
"magiskhide --rm $pkg".su().blockingGet()
}
Intent.ACTION_LOCALE_CHANGED -> Shortcuts.setup(context)
Const.Key.BROADCAST_MANAGER_UPDATE -> {
Config.managerLink = intent.getStringExtra(Const.Key.INTENT_SET_LINK)
DownloadApp.upgrade(intent.getStringExtra(Const.Key.INTENT_SET_NAME))
}
Const.Key.BROADCAST_REBOOT -> Shell.su("/system/bin/reboot").submit()
}
}
}
package com.topjohnwu.magisk.utils;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Process;
import android.widget.Toast;
import com.topjohnwu.magisk.App;
import com.topjohnwu.magisk.Config;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.model.entity.Policy;
import com.topjohnwu.magisk.model.entity.SuLogEntry;
import java.util.Date;
public class SuLogger {
public static void handleLogs(Intent intent) {
int fromUid = intent.getIntExtra("from.uid", -1);
if (fromUid < 0) return;
if (fromUid == Process.myUid()) return;
App app = App.self;
PackageManager pm = app.getPackageManager();
Policy policy;
boolean notify;
Bundle data = intent.getExtras();
if (data.containsKey("notify")) {
notify = data.getBoolean("notify");
try {
policy = new Policy(fromUid, pm);
} catch (PackageManager.NameNotFoundException e) {
return;
}
} else {
// Doesn't report whether notify or not, check database ourselves
policy = app.getDB().getPolicy(fromUid);
if (policy == null)
return;
notify = policy.notification;
}
policy.policy = data.getInt("policy", -1);
if (policy.policy < 0)
return;
if (notify)
handleNotify(policy);
SuLogEntry log = new SuLogEntry(policy);
int toUid = intent.getIntExtra("to.uid", -1);
if (toUid < 0) return;
int pid = intent.getIntExtra("pid", -1);
if (pid < 0) return;
String command = intent.getStringExtra("command");
if (command == null) return;
log.toUid = toUid;
log.fromPid = pid;
log.command = command;
log.date = new Date();
app.getDB().addLog(log);
}
private static void handleNotify(Policy policy) {
if (policy.notification &&
(int) Config.get(Config.Key.SU_NOTIFICATION) == Config.Value.NOTIFICATION_TOAST) {
Utils.toast(App.self.getString(policy.policy == Policy.ALLOW ?
R.string.su_allow_toast : R.string.su_deny_toast, policy.appName),
Toast.LENGTH_SHORT);
}
}
public static void handleNotify(Intent intent) {
int fromUid = intent.getIntExtra("from.uid", -1);
if (fromUid < 0) return;
if (fromUid == Process.myUid()) return;
try {
Policy policy = new Policy(fromUid, App.self.getPackageManager());
policy.policy = intent.getIntExtra("policy", -1);
if (policy.policy >= 0)
handleNotify(policy);
} catch (PackageManager.NameNotFoundException ignored) {}
}
}
package com.topjohnwu.magisk.utils
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Process
import android.widget.Toast
import com.topjohnwu.magisk.App
import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.data.repository.AppRepository
import com.topjohnwu.magisk.data.repository.LogRepository
import com.topjohnwu.magisk.model.entity.MagiskPolicy
import com.topjohnwu.magisk.model.entity.Policy
import com.topjohnwu.magisk.model.entity.toLog
import com.topjohnwu.magisk.model.entity.toPolicy
import java.util.*
object SuLogger {
@JvmStatic
fun handleLogs(intent: Intent) {
val fromUid = intent.getIntExtra("from.uid", -1)
if (fromUid < 0) return
if (fromUid == Process.myUid()) return
val pm: PackageManager by inject()
val notify: Boolean
val data = intent.extras
val policy: MagiskPolicy = if (data!!.containsKey("notify")) {
notify = data.getBoolean("notify")
runCatching {
fromUid.toPolicy(pm)
}.getOrElse { return }
} else {
// Doesn't report whether notify or not, check database ourselves
val appRepo: AppRepository by inject()
val policy = appRepo.fetch(fromUid).blockingGet() ?: return
notify = policy.notification
policy
}.copy(policy = data.getInt("policy", -1))
if (policy.policy < 0)
return
if (notify)
handleNotify(policy)
val toUid = intent.getIntExtra("to.uid", -1)
if (toUid < 0) return
val pid = intent.getIntExtra("pid", -1)
if (pid < 0) return
val command = intent.getStringExtra("command") ?: return
val log = policy.toLog(
toUid = toUid,
fromPid = pid,
command = command,
date = Date()
)
val logRepo: LogRepository by inject()
logRepo.put(log).blockingGet()?.printStackTrace()
}
private fun handleNotify(policy: MagiskPolicy) {
if (policy.notification && Config.get<Any>(Config.Key.SU_NOTIFICATION) as Int == Config.Value.NOTIFICATION_TOAST) {
Utils.toast(
App.self.getString(
if (policy.policy == Policy.ALLOW)
R.string.su_allow_toast
else
R.string.su_deny_toast, policy.appName
),
Toast.LENGTH_SHORT
)
}
}
fun handleNotify(intent: Intent) {
val fromUid = intent.getIntExtra("from.uid", -1)
if (fromUid < 0) return
if (fromUid == Process.myUid()) return
runCatching {
val packageManager: PackageManager by inject()
val policy = fromUid.toPolicy(packageManager)
.copy(policy = intent.getIntExtra("policy", -1))
if (policy.policy >= 0)
handleNotify(policy)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment