forked from ThePedroo/ReLSPosed
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConfigManager.java
More file actions
1307 lines (1185 loc) · 54 KB
/
ConfigManager.java
File metadata and controls
1307 lines (1185 loc) · 54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of LSPosed.
*
* LSPosed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LSPosed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LSPosed. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (C) 2021 LSPosed Contributors
*/
package org.lsposed.lspd.service;
import static org.lsposed.lspd.service.PackageService.MATCH_ALL_FLAGS;
import static org.lsposed.lspd.service.PackageService.PER_USER_RANGE;
import static org.lsposed.lspd.service.ServiceManager.TAG;
import static org.lsposed.lspd.service.ServiceManager.existsInGlobalNamespace;
import static org.lsposed.lspd.service.ServiceManager.toGlobalNamespace;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteException;
import android.os.SELinux;
import android.os.SharedMemory;
import android.os.SystemClock;
import android.system.ErrnoException;
import android.system.Os;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.apache.commons.lang3.SerializationUtilsX;
import org.lsposed.daemon.BuildConfig;
import org.lsposed.lspd.models.Application;
import org.lsposed.lspd.models.Module;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import hidden.HiddenApiBridge;
public class ConfigManager {
private static ConfigManager instance = null;
private final SQLiteDatabase db = openDb();
static final Path basePath = Paths.get("/data/adb/lspd");
private boolean verboseLog = true;
private boolean logWatchdog = true;
private boolean dexObfuscate = true;
private boolean injectionHardening = true;
private boolean enableStatusNotification = true;
private Path miscPath = null;
private int managerUid = -1;
private final Handler cacheHandler;
private long lastModuleCacheTime = 0;
private long requestModuleCacheTime = 0;
private long lastScopeCacheTime = 0;
private long requestScopeCacheTime = 0;
private String api = "(???)";
static class ProcessScope {
final String processName;
final int uid;
ProcessScope(@NonNull String processName, int uid) {
this.processName = processName;
this.uid = uid;
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof ProcessScope) {
ProcessScope p = (ProcessScope) o;
return p.processName.equals(processName) && p.uid == uid;
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(processName) ^ uid;
}
}
private final SQLiteStatement createModulesTable = db.compileStatement("CREATE TABLE IF NOT EXISTS modules (" +
"mid integer PRIMARY KEY AUTOINCREMENT," +
"module_pkg_name text NOT NULL UNIQUE," +
"apk_path text NOT NULL, " +
"enabled BOOLEAN DEFAULT 0 " +
"CHECK (enabled IN (0, 1))," +
"auto_include BOOLEAN DEFAULT 0 " +
"CHECK (auto_include IN (0, 1))" +
");");
private final SQLiteStatement createScopeTable = db.compileStatement("CREATE TABLE IF NOT EXISTS scope (" +
"mid integer," +
"app_pkg_name text NOT NULL," +
"user_id integer NOT NULL," +
"PRIMARY KEY (mid, app_pkg_name, user_id)," +
"CONSTRAINT scope_module_constraint" +
" FOREIGN KEY (mid)" +
" REFERENCES modules (mid)" +
" ON DELETE CASCADE" +
");");
private final SQLiteStatement createConfigTable = db.compileStatement("CREATE TABLE IF NOT EXISTS configs (" +
"module_pkg_name text NOT NULL," +
"user_id integer NOT NULL," +
"`group` text NOT NULL," +
"`key` text NOT NULL," +
"data blob NOT NULL," +
"PRIMARY KEY (module_pkg_name, user_id, `group`, `key`)," +
"CONSTRAINT config_module_constraint" +
" FOREIGN KEY (module_pkg_name)" +
" REFERENCES modules (module_pkg_name)" +
" ON DELETE CASCADE" +
");");
private final Map<ProcessScope, List<Module>> cachedScope = new ConcurrentHashMap<>();
// packageName, Module
private final Map<String, Module> cachedModule = new ConcurrentHashMap<>();
// packageName, userId, group, key, value
private final Map<Pair<String, Integer>, Map<String, HashMap<String, Object>>> cachedConfig = new ConcurrentHashMap<>();
private Set<String> scopeRequestBlocked = new HashSet<>();
private static SQLiteDatabase openDb() {
var params = new SQLiteDatabase.OpenParams.Builder()
.addOpenFlags(SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING)
.setErrorHandler(sqLiteDatabase -> Log.w(TAG, "database corrupted"));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
params.setSynchronousMode("NORMAL");
}
return SQLiteDatabase.openDatabase(ConfigFileManager.dbPath.getAbsoluteFile(), params.build());
}
private void updateCaches(boolean sync) {
synchronized (cacheHandler) {
requestScopeCacheTime = requestModuleCacheTime = SystemClock.elapsedRealtime();
}
if (sync) {
cacheModules();
} else {
cacheHandler.post(this::cacheModules);
}
}
// for system server, cache is not yet ready, we need to query database for it
public boolean shouldSkipSystemServer() {
if (!SELinux.checkSELinuxAccess("u:r:system_server:s0", "u:r:system_server:s0", "process", "execmem")) {
Log.e(TAG, "skip injecting into android because sepolicy was not loaded properly");
return true; // skip
}
/*
try (Cursor cursor = db.query("scope INNER JOIN modules ON scope.mid = modules.mid", new String[]{"modules.mid"}, "app_pkg_name=? AND enabled=1", new String[]{"system"}, null, null, null)) {
return cursor == null || !cursor.moveToNext();
}*/
return false;
}
@SuppressLint("BlockedPrivateApi")
public List<Module> getModulesForSystemServer() {
List<Module> modules = new LinkedList<>();
try (Cursor cursor = db.query("scope INNER JOIN modules ON scope.mid = modules.mid", new String[]{"module_pkg_name", "apk_path"}, "app_pkg_name=? AND enabled=1", new String[]{"system"}, null, null, null)) {
int apkPathIdx = cursor.getColumnIndex("apk_path");
int pkgNameIdx = cursor.getColumnIndex("module_pkg_name");
while (cursor.moveToNext()) {
var module = new Module();
module.apkPath = cursor.getString(apkPathIdx);
module.packageName = cursor.getString(pkgNameIdx);
var cached = cachedModule.get(module.packageName);
if (cached != null) {
modules.add(cached);
continue;
}
var statPath = toGlobalNamespace("/data/user_de/0/" + module.packageName).getAbsolutePath();
try {
module.appId = Os.stat(statPath).st_uid;
} catch (ErrnoException e) {
Log.w(TAG, "cannot stat " + statPath, e);
module.appId = -1;
}
try {
var apkFile = new File(module.apkPath);
var pkg = new PackageParser().parsePackage(apkFile, 0, false);
module.applicationInfo = pkg.applicationInfo;
module.applicationInfo.sourceDir = module.apkPath;
module.applicationInfo.dataDir = statPath;
module.applicationInfo.deviceProtectedDataDir = statPath;
HiddenApiBridge.ApplicationInfo_credentialProtectedDataDir(module.applicationInfo, statPath);
module.applicationInfo.processName = module.packageName;
} catch (PackageParser.PackageParserException e) {
Log.w(TAG, "failed to parse " + module.apkPath, e);
}
module.service = new LSPInjectedModuleService(module.packageName);
modules.add(module);
}
}
return modules.parallelStream().filter(m -> {
var file = ConfigFileManager.loadModule(m.apkPath, dexObfuscate);
if (file == null) {
Log.w(TAG, "Can not load " + m.apkPath + ", skip!");
return false;
}
m.file = file;
cachedModule.putIfAbsent(m.packageName, m);
return true;
}).collect(Collectors.toList());
}
private synchronized void updateConfig() {
Map<String, Object> config = getModulePrefs("lspd", 0, "config");
Object bool = config.get("enable_verbose_log");
verboseLog = bool == null || (boolean) bool;
bool = config.get("enable_log_watchdog");
logWatchdog = bool == null || (boolean) bool;
bool = config.get("disable_injection_hardening");
injectionHardening = bool == null || (boolean) bool;
bool = config.get("enable_dex_obfuscate");
dexObfuscate = bool == null || (boolean) bool;
bool = config.get("enable_auto_add_shortcut");
if (bool != null) {
// TODO: remove
updateModulePrefs("lspd", 0, "config", "enable_auto_add_shortcut", null);
}
bool = config.get("enable_status_notification");
enableStatusNotification = bool == null || (boolean) bool;
var set = (Set<String>) config.get("scope_request_blocked");
scopeRequestBlocked = set == null ? new HashSet<>() : set;
// Don't migrate to ConfigFileManager, as XSharedPreferences will be restored soon
String string = (String) config.get("misc_path");
if (string == null) {
miscPath = Paths.get("/data", "misc", UUID.randomUUID().toString());
updateModulePrefs("lspd", 0, "config", "misc_path", miscPath.toString());
} else {
miscPath = Paths.get(string);
}
try {
var perms = PosixFilePermissions.fromString("rwx--x--x");
Files.createDirectories(miscPath, PosixFilePermissions.asFileAttribute(perms));
walkFileTree(miscPath, f -> SELinux.setFileContext(f.toString(), "u:object_r:xposed_data:s0"));
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
updateManager(false);
cacheHandler.post(this::getPreloadDex);
}
public synchronized void updateManager(boolean uninstalled) {
if (uninstalled) {
managerUid = -1;
return;
}
if (!PackageService.isAlive()) return;
try {
PackageInfo info = PackageService.getPackageInfo(BuildConfig.DEFAULT_MANAGER_PACKAGE_NAME, 0, 0);
if (info != null) {
managerUid = info.applicationInfo.uid;
} else {
managerUid = -1;
Log.i(TAG, "manager is not installed");
}
} catch (RemoteException ignored) {
}
}
static ConfigManager getInstance() {
if (instance == null)
instance = new ConfigManager();
boolean needCached;
synchronized (instance.cacheHandler) {
needCached = instance.lastModuleCacheTime == 0 || instance.lastScopeCacheTime == 0;
}
if (needCached) {
if (PackageService.isAlive() && UserService.isAlive()) {
Log.d(TAG, "pm & um are ready, updating cache");
// must ensure cache is valid for later usage
instance.updateCaches(true);
instance.updateManager(false);
}
}
return instance;
}
private ConfigManager() {
HandlerThread cacheThread = new HandlerThread("cache");
cacheThread.start();
cacheHandler = new Handler(cacheThread.getLooper());
initDB();
updateConfig();
// must ensure cache is valid for later usage
updateCaches(true);
}
private <T> T executeInTransaction(Supplier<T> execution) {
try {
db.beginTransaction();
var res = execution.get();
db.setTransactionSuccessful();
return res;
} finally {
db.endTransaction();
}
}
private void executeInTransaction(Runnable execution) {
executeInTransaction((Supplier<Void>) () -> {
execution.run();
return null;
});
}
private void initDB() {
try {
db.setForeignKeyConstraintsEnabled(true);
switch (db.getVersion()) {
case 0:
executeInTransaction(() -> {
createModulesTable.execute();
createScopeTable.execute();
createConfigTable.execute();
var values = new ContentValues();
values.put("module_pkg_name", "lspd");
values.put("apk_path", ConfigFileManager.managerApkPath.toString());
// dummy module for config
db.insertWithOnConflict("modules", null, values, SQLiteDatabase.CONFLICT_IGNORE);
db.setVersion(1);
});
case 1:
executeInTransaction(() -> {
db.compileStatement("DROP INDEX IF EXISTS configs_idx;").execute();
db.compileStatement("DROP TABLE IF EXISTS config;").execute();
db.compileStatement("ALTER TABLE scope RENAME TO old_scope;").execute();
db.compileStatement("ALTER TABLE configs RENAME TO old_configs;").execute();
createConfigTable.execute();
createScopeTable.execute();
db.compileStatement("CREATE INDEX IF NOT EXISTS configs_idx ON configs (module_pkg_name, user_id);").execute();
executeInTransaction(() -> {
try {
db.compileStatement("INSERT INTO scope SELECT * FROM old_scope;").execute();
} catch (Throwable e) {
Log.w(TAG, "migrate scope", e);
}
});
executeInTransaction(() -> {
try {
executeInTransaction(() -> db.compileStatement("INSERT INTO configs SELECT * FROM old_configs;").execute());
} catch (Throwable e) {
Log.w(TAG, "migrate config", e);
}
});
db.compileStatement("DROP TABLE old_scope;").execute();
db.compileStatement("DROP TABLE old_configs;").execute();
db.setVersion(2);
});
case 2:
executeInTransaction(() -> {
db.compileStatement("UPDATE scope SET app_pkg_name = 'system' WHERE app_pkg_name = 'android';").execute();
db.setVersion(3);
});
case 3:
try {
executeInTransaction(() -> {
db.compileStatement("ALTER TABLE modules ADD COLUMN auto_include BOOLEAN DEFAULT 0 CHECK (auto_include IN (0, 1));").execute();
db.setVersion(4);
});
} catch (SQLiteException ex) {
// Fix wrong init code for new column auto_include
if (ex.getMessage().startsWith("duplicate column name: auto_include")) {
db.setVersion(4);
} else {
throw ex;
}
}
default:
break;
}
} catch (Throwable e) {
Log.e(TAG, "init db", e);
}
}
private List<ProcessScope> getAssociatedProcesses(Application app) throws RemoteException {
Pair<Set<String>, Integer> result = PackageService.fetchProcessesWithUid(app);
List<ProcessScope> processes = new ArrayList<>();
if (app.packageName.equals("android")) {
// this is hardcoded for ResolverActivity
processes.add(new ProcessScope("system:ui", Process.SYSTEM_UID));
}
for (String processName : result.first) {
var uid = result.second;
if (uid == Process.SYSTEM_UID && processName.equals("system")) {
// code run in system_server
continue;
}
processes.add(new ProcessScope(processName, uid));
}
return processes;
}
private @NonNull
Map<String, HashMap<String, Object>> fetchModuleConfig(String name, int user_id) {
var config = new ConcurrentHashMap<String, HashMap<String, Object>>();
try (Cursor cursor = db.query("configs", new String[]{"`group`", "`key`", "data"},
"module_pkg_name = ? and user_id = ?", new String[]{name, String.valueOf(user_id)}, null, null, null)) {
if (cursor == null) {
Log.e(TAG, "db cache failed");
return config;
}
int groupIdx = cursor.getColumnIndex("group");
int keyIdx = cursor.getColumnIndex("key");
int dataIdx = cursor.getColumnIndex("data");
while (cursor.moveToNext()) {
var group = cursor.getString(groupIdx);
var key = cursor.getString(keyIdx);
var data = cursor.getBlob(dataIdx);
var object = SerializationUtilsX.deserialize(data);
if (object == null) continue;
config.computeIfAbsent(group, g -> new HashMap<>()).put(key, object);
}
}
return config;
}
public void updateModulePrefs(String moduleName, int userId, String group, String key, Object value) {
Map<String, Object> values = new HashMap<>();
values.put(key, value);
updateModulePrefs(moduleName, userId, group, values);
}
public void updateModulePrefs(String moduleName, int userId, String group, Map<String, Object> values) {
var config = cachedConfig.computeIfAbsent(new Pair<>(moduleName, userId), module -> fetchModuleConfig(module.first, module.second));
config.compute(group, (g, prefs) -> {
HashMap<String, Object> newPrefs = prefs == null ? new HashMap<>() : new HashMap<>(prefs);
executeInTransaction(() -> {
for (var entry : values.entrySet()) {
var key = entry.getKey();
var value = entry.getValue();
if (value instanceof Serializable) {
newPrefs.put(key, value);
var contents = new ContentValues();
contents.put("`group`", group);
contents.put("`key`", key);
contents.put("data", SerializationUtilsX.serialize((Serializable) value));
contents.put("module_pkg_name", moduleName);
contents.put("user_id", String.valueOf(userId));
db.insertWithOnConflict("configs", null, contents, SQLiteDatabase.CONFLICT_REPLACE);
} else {
newPrefs.remove(key);
db.delete("configs", "module_pkg_name=? and user_id=? and `group`=? and `key`=?", new String[]{moduleName, String.valueOf(userId), group, key});
}
}
var bundle = new Bundle();
bundle.putSerializable("config", (Serializable) config);
if (bundle.size() > 1024 * 1024) {
throw new IllegalArgumentException("Preference too large");
}
});
return newPrefs;
});
}
public void deleteModulePrefs(String moduleName, int userId, String group) {
db.delete("configs", "module_pkg_name=? and user_id=? and `group`=?", new String[]{moduleName, String.valueOf(userId), group});
var config = cachedConfig.getOrDefault(new Pair<>(moduleName, userId), null);
if (config != null) {
config.remove(group);
}
}
public HashMap<String, Object> getModulePrefs(String moduleName, int userId, String group) {
var config = cachedConfig.computeIfAbsent(new Pair<>(moduleName, userId), module -> fetchModuleConfig(module.first, module.second));
return config.getOrDefault(group, new HashMap<>());
}
private synchronized void clearCache() {
synchronized (cacheHandler) {
lastScopeCacheTime = 0;
lastModuleCacheTime = 0;
}
cachedModule.clear();
cachedScope.clear();
}
private synchronized void cacheModules() {
// skip caching when pm is not yet available
if (!PackageService.isAlive() || !UserService.isAlive()) return;
synchronized (cacheHandler) {
if (lastModuleCacheTime >= requestModuleCacheTime) return;
else lastModuleCacheTime = SystemClock.elapsedRealtime();
}
Set<SharedMemory> toClose = ConcurrentHashMap.newKeySet();
try (Cursor cursor = db.query(true, "modules", new String[]{"module_pkg_name", "apk_path"},
"enabled = 1", null, null, null, null, null)) {
if (cursor == null) {
Log.e(TAG, "db cache failed");
return;
}
int pkgNameIdx = cursor.getColumnIndex("module_pkg_name");
int apkPathIdx = cursor.getColumnIndex("apk_path");
Set<String> obsoleteModules = ConcurrentHashMap.newKeySet();
// packageName, apkPath
Map<String, String> obsoletePaths = new ConcurrentHashMap<>();
cachedModule.values().removeIf(m -> {
if (m.apkPath == null || !existsInGlobalNamespace(m.apkPath)) {
toClose.addAll(m.file.preLoadedDexes);
return true;
}
return false;
});
List<Module> modules = new ArrayList<>();
while (cursor.moveToNext()) {
String packageName = cursor.getString(pkgNameIdx);
String apkPath = cursor.getString(apkPathIdx);
if (packageName.equals("lspd")) continue;
var module = new Module();
module.packageName = packageName;
module.apkPath = apkPath;
modules.add(module);
}
modules.stream().parallel().filter(m -> {
var oldModule = cachedModule.get(m.packageName);
PackageInfo pkgInfo = null;
try {
pkgInfo = PackageService.getPackageInfoFromAllUsers(m.packageName, MATCH_ALL_FLAGS).values().stream().findFirst().orElse(null);
} catch (Throwable e) {
Log.w(TAG, "Get package info of " + m.packageName, e);
}
if (pkgInfo == null || pkgInfo.applicationInfo == null) {
Log.w(TAG, "Failed to find package info of " + m.packageName);
obsoleteModules.add(m.packageName);
return false;
}
if (oldModule != null &&
pkgInfo.applicationInfo.sourceDir != null &&
m.apkPath != null && oldModule.apkPath != null &&
existsInGlobalNamespace(m.apkPath) &&
Objects.equals(m.apkPath, oldModule.apkPath) &&
Objects.equals(new File(pkgInfo.applicationInfo.sourceDir).getParent(), new File(m.apkPath).getParent())) {
if (oldModule.appId != -1) {
Log.d(TAG, m.packageName + " did not change, skip caching it");
} else {
// cache from system server, update application info
oldModule.applicationInfo = pkgInfo.applicationInfo;
}
return false;
}
m.apkPath = getModuleApkPath(pkgInfo.applicationInfo);
if (m.apkPath == null) {
Log.w(TAG, "Failed to find path of " + m.packageName);
obsoleteModules.add(m.packageName);
return false;
} else {
obsoletePaths.put(m.packageName, m.apkPath);
}
m.appId = pkgInfo.applicationInfo.uid;
m.applicationInfo = pkgInfo.applicationInfo;
m.service = oldModule != null ? oldModule.service : new LSPInjectedModuleService(m.packageName);
return true;
}).forEach(m -> {
var file = ConfigFileManager.loadModule(m.apkPath, dexObfuscate);
if (file == null) {
Log.w(TAG, "failed to load module " + m.packageName);
obsoleteModules.add(m.packageName);
return;
}
m.file = file;
cachedModule.put(m.packageName, m);
});
if (PackageService.isAlive()) {
obsoleteModules.forEach(this::removeModuleWithoutCache);
obsoletePaths.forEach((packageName, path) -> updateModuleApkPath(packageName, path, true));
} else {
Log.w(TAG, "pm is dead while caching. invalidating...");
clearCache();
return;
}
}
Log.d(TAG, "cached modules");
for (var module : cachedModule.entrySet()) {
Log.d(TAG, module.getKey() + " " + module.getValue().apkPath);
}
cacheScopes();
toClose.forEach(SharedMemory::close);
}
private synchronized void cacheScopes() {
// skip caching when pm is not yet available
if (!PackageService.isAlive()) return;
synchronized (cacheHandler) {
if (lastScopeCacheTime >= requestScopeCacheTime) return;
else lastScopeCacheTime = SystemClock.elapsedRealtime();
}
cachedScope.clear();
try (Cursor cursor = db.query("scope INNER JOIN modules ON scope.mid = modules.mid", new String[]{"app_pkg_name", "module_pkg_name", "user_id"},
"enabled = 1", null, null, null, null)) {
int appPkgNameIdx = cursor.getColumnIndex("app_pkg_name");
int modulePkgNameIdx = cursor.getColumnIndex("module_pkg_name");
int userIdIdx = cursor.getColumnIndex("user_id");
final var obsoletePackages = new HashSet<Application>();
final var obsoleteModules = new HashSet<Application>();
final var moduleAvailability = new HashMap<Pair<String, Integer>, Boolean>();
final var cachedProcessScope = new HashMap<Pair<String, Integer>, List<ProcessScope>>();
final var denylist = new HashSet<>(getDenyListPackages());
while (cursor.moveToNext()) {
Application app = new Application();
app.packageName = cursor.getString(appPkgNameIdx);
app.userId = cursor.getInt(userIdIdx);
var modulePackageName = cursor.getString(modulePkgNameIdx);
// check if module is present in this user
if (!moduleAvailability.computeIfAbsent(new Pair<>(modulePackageName, app.userId), n -> {
var available = false;
try {
available = PackageService.isPackageAvailable(n.first, n.second, true) && cachedModule.containsKey(modulePackageName);
} catch (Throwable e) {
Log.w(TAG, "check package availability ", e);
}
if (!available) {
var obsoleteModule = new Application();
obsoleteModule.packageName = modulePackageName;
obsoleteModule.userId = app.userId;
obsoleteModules.add(obsoleteModule);
}
return available;
})) continue;
// system server always loads database
if (app.packageName.equals("system")) continue;
try {
List<ProcessScope> processesScope = cachedProcessScope.computeIfAbsent(new Pair<>(app.packageName, app.userId), (k) -> {
try {
if (denylist.contains(app.packageName))
Log.w(TAG, app.packageName + " is on denylist. It may not take effect.");
return getAssociatedProcesses(app);
} catch (RemoteException e) {
return Collections.emptyList();
}
});
if (processesScope.isEmpty()) {
obsoletePackages.add(app);
continue;
}
var module = cachedModule.get(modulePackageName);
assert module != null;
for (ProcessScope processScope : processesScope) {
cachedScope.computeIfAbsent(processScope,
ignored -> new LinkedList<>()).add(module);
// Always allow the module to inject itself
if (modulePackageName.equals(app.packageName)) {
var appId = processScope.uid % PER_USER_RANGE;
for (var user : UserService.getUsers()) {
var moduleUid = user.id * PER_USER_RANGE + appId;
if (moduleUid == processScope.uid) continue; // skip duplicate
var moduleSelf = new ProcessScope(processScope.processName, moduleUid);
cachedScope.computeIfAbsent(moduleSelf,
ignored -> new LinkedList<>()).add(module);
}
}
}
} catch (RemoteException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
}
if (PackageService.isAlive()) {
for (Application obsoletePackage : obsoletePackages) {
Log.d(TAG, "removing obsolete package: " + obsoletePackage.packageName + "/" + obsoletePackage.userId);
removeAppWithoutCache(obsoletePackage);
}
for (Application obsoleteModule : obsoleteModules) {
Log.d(TAG, "removing obsolete module: " + obsoleteModule.packageName + "/" + obsoleteModule.userId);
removeModuleScopeWithoutCache(obsoleteModule);
removeBlockedScopeRequest(obsoleteModule.packageName);
}
} else {
Log.w(TAG, "pm is dead while caching. invalidating...");
clearCache();
return;
}
}
Log.d(TAG, "cached scope");
cachedScope.forEach((ps, modules) -> {
Log.d(TAG, ps.processName + "/" + ps.uid);
modules.forEach(module -> Log.d(TAG, "\t" + module.packageName));
});
}
// This is called when a new process created, use the cached result
public List<Module> getModulesForProcess(String processName, int uid) {
return isManager(uid) ? Collections.emptyList() : cachedScope.getOrDefault(new ProcessScope(processName, uid), Collections.emptyList());
}
// This is called when a new process created, use the cached result
public boolean shouldSkipProcess(ProcessScope scope) {
return !cachedScope.containsKey(scope) && !isManager(scope.uid);
}
public boolean isUidHooked(int uid) {
return cachedScope.keySet().stream().reduce(false, (p, scope) -> p || scope.uid == uid, Boolean::logicalOr);
}
@Nullable
public List<Application> getModuleScope(String packageName) {
if (packageName.equals("lspd")) return null;
try (Cursor cursor = db.query("scope INNER JOIN modules ON scope.mid = modules.mid", new String[]{"app_pkg_name", "user_id"},
"modules.module_pkg_name = ?", new String[]{packageName}, null, null, null)) {
if (cursor == null) {
return null;
}
int userIdIdx = cursor.getColumnIndex("user_id");
int appPkgNameIdx = cursor.getColumnIndex("app_pkg_name");
ArrayList<Application> result = new ArrayList<>();
while (cursor.moveToNext()) {
Application scope = new Application();
scope.packageName = cursor.getString(appPkgNameIdx);
scope.userId = cursor.getInt(userIdIdx);
result.add(scope);
}
return result;
}
}
@Nullable
public String getModuleApkPath(ApplicationInfo info) {
String[] apks;
if (info.splitSourceDirs != null) {
apks = Arrays.copyOf(info.splitSourceDirs, info.splitSourceDirs.length + 1);
apks[info.splitSourceDirs.length] = info.sourceDir;
} else apks = new String[]{info.sourceDir};
var apkPath = Arrays.stream(apks).parallel().filter(apk -> {
if (apk == null) {
Log.w(TAG, info.packageName + " has null apk path???");
return false;
}
try (var zip = new ZipFile(toGlobalNamespace(apk))) {
return zip.getEntry("META-INF/xposed/java_init.list") != null || zip.getEntry("assets/xposed_init") != null;
} catch (IOException e) {
return false;
}
}).findFirst();
return apkPath.orElse(null);
}
public boolean updateModuleApkPath(String packageName, String apkPath, boolean force) {
if (apkPath == null || packageName.equals("lspd")) return false;
if (db.inTransaction()) {
Log.w(TAG, "update module apk path should not be called inside transaction");
return false;
}
ContentValues values = new ContentValues();
values.put("module_pkg_name", packageName);
values.put("apk_path", apkPath);
// insert or update in two step since insert or replace will change the autoincrement mid
int count = (int) db.insertWithOnConflict("modules", null, values, SQLiteDatabase.CONFLICT_IGNORE);
if (count < 0) {
var cached = cachedModule.getOrDefault(packageName, null);
if (force || cached == null || cached.apkPath == null || !cached.apkPath.equals(apkPath))
count = db.updateWithOnConflict("modules", values, "module_pkg_name=?", new String[]{packageName}, SQLiteDatabase.CONFLICT_IGNORE);
else
count = 0;
}
// force update is because cache is already update to date
// skip caching again
if (!force && count > 0) {
// Called by oneway binder
updateCaches(true);
return true;
}
return count > 0;
}
// Only be called before updating modules. No need to cache.
private int getModuleId(String packageName) {
if (packageName.equals("lspd")) return -1;
if (db.inTransaction()) {
Log.w(TAG, "get module id should not be called inside transaction");
return -1;
}
try (Cursor cursor = db.query("modules", new String[]{"mid"}, "module_pkg_name=?", new String[]{packageName}, null, null, null)) {
if (cursor == null) return -1;
if (cursor.getCount() != 1) return -1;
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndexOrThrow("mid"));
}
}
public boolean setModuleScope(String packageName, List<Application> scopes) throws RemoteException {
if (scopes == null) return false;
enableModule(packageName);
int mid = getModuleId(packageName);
if (mid == -1) return false;
executeInTransaction(() -> {
db.delete("scope", "mid = ?", new String[]{String.valueOf(mid)});
for (Application app : scopes) {
if (app.packageName.equals("system") && app.userId != 0) continue;
ContentValues values = new ContentValues();
values.put("mid", mid);
values.put("app_pkg_name", app.packageName);
values.put("user_id", app.userId);
db.insertWithOnConflict("scope", null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
});
// Called by manager, should be async
updateCaches(false);
return true;
}
public boolean setModuleScope(String packageName, String scopePackageName, int userId) {
if (scopePackageName == null) return false;
int mid = getModuleId(packageName);
if (mid == -1) return false;
if (scopePackageName.equals("system") && userId != 0) return false;
executeInTransaction(() -> {
ContentValues values = new ContentValues();
values.put("mid", mid);
values.put("app_pkg_name", scopePackageName);
values.put("user_id", userId);
db.insertWithOnConflict("scope", null, values, SQLiteDatabase.CONFLICT_IGNORE);
});
// Called by xposed service, should be async
updateCaches(false);
return true;
}
public boolean removeModuleScope(String packageName, String scopePackageName, int userId) {
if (scopePackageName == null) return false;
int mid = getModuleId(packageName);
if (mid == -1) return false;
if (scopePackageName.equals("system") && userId != 0) return false;
executeInTransaction(() -> {
db.delete("scope", "mid = ? AND app_pkg_name = ? AND user_id = ?", new String[]{String.valueOf(mid), scopePackageName, String.valueOf(userId)});
});
// Called by xposed service, should be async
updateCaches(false);
return true;
}
public String[] enabledModules() {
return listModules("enabled");
}
public boolean removeModule(String packageName) {
if (removeModuleWithoutCache(packageName)) {
// called by oneway binder
// Called only when the application is completely uninstalled
// If it's a module we need to return as soon as possible to broadcast to the manager
// for updating the module status
updateCaches(false);
return true;
}
return false;
}
private boolean removeModuleWithoutCache(String packageName) {
if (packageName.equals("lspd")) return false;
boolean res = executeInTransaction(() -> db.delete("modules", "module_pkg_name = ?", new String[]{packageName}) > 0);
try {
for (var user : UserService.getUsers()) {
removeModulePrefs(user.id, packageName);
}
} catch (Throwable e) {
Log.w(TAG, "remove module prefs for " + packageName);
}
return res;
}
private boolean removeModuleScopeWithoutCache(Application module) {
if (module.packageName.equals("lspd")) return false;
int mid = getModuleId(module.packageName);
if (mid == -1) return false;
boolean res = executeInTransaction(() -> db.delete("scope", "mid = ? and user_id = ?", new String[]{String.valueOf(mid), String.valueOf(module.userId)}) > 0);
try {
removeModulePrefs(module.userId, module.packageName);
} catch (IOException e) {
Log.w(TAG, "removeModulePrefs", e);
}
return res;
}
private boolean removeAppWithoutCache(Application app) {
return executeInTransaction(() -> db.delete("scope", "app_pkg_name = ? AND user_id=?",
new String[]{app.packageName, String.valueOf(app.userId)}) > 0);
}
public boolean disableModule(String packageName) {
if (packageName.equals("lspd")) return false;
boolean changed = executeInTransaction(() -> {
ContentValues values = new ContentValues();
values.put("enabled", 0);
return db.update("modules", values, "module_pkg_name = ?", new String[]{packageName}) > 0;
});
if (changed) {
// called by manager, should be async
updateCaches(false);
return true;
} else {
return false;
}
}
public boolean enableModule(String packageName) throws RemoteException {
if (packageName.equals("lspd")) return false;
PackageInfo pkgInfo = PackageService.getPackageInfoFromAllUsers(packageName, PackageService.MATCH_ALL_FLAGS).values().stream().findFirst().orElse(null);
if (pkgInfo == null || pkgInfo.applicationInfo == null) return false;
var modulePath = getModuleApkPath(pkgInfo.applicationInfo);
if (modulePath == null) return false;
boolean changed = updateModuleApkPath(packageName, modulePath, false);
changed = executeInTransaction(() -> {
ContentValues values = new ContentValues();
values.put("enabled", 1);
return db.update("modules", values, "module_pkg_name = ?", new String[]{packageName}) > 0;
}) || changed;
if (changed) {
// Called by manager, should be async
updateCaches(false);
return true;
} else {
return false;
}