-
Notifications
You must be signed in to change notification settings - Fork 695
Expand file tree
/
Copy pathXSharedPreferences.java
More file actions
592 lines (545 loc) · 20.5 KB
/
XSharedPreferences.java
File metadata and controls
592 lines (545 loc) · 20.5 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
package de.robv.android.xposed;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import org.lsposed.lspd.util.Utils.Log;
import org.matrix.vector.impl.core.VectorServiceClient;
import org.matrix.vector.impl.utils.VectorMetaDataReader;
import org.matrix.vector.legacy.BuildConfig;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.AccessDeniedException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import de.robv.android.xposed.services.FileResult;
/**
* This class is basically the same as SharedPreferencesImpl from AOSP, but
* read-only and without listeners support. Instead, it is made to be
* compatible with all ROMs.
*/
public final class XSharedPreferences implements SharedPreferences {
private static final String TAG = "XSharedPreferences";
private static final HashMap<WatchKey, PrefsData> sWatcherKeyInstances = new HashMap<>();
private static final Object sContent = new Object();
private static final Method sReadMapXmlMethod;
private static Thread sWatcherDaemon = null;
private static WatchService sWatcher;
private final HashMap<OnSharedPreferenceChangeListener, Object> mListeners = new HashMap<>();
private final File mFile;
private final String mFilename;
private Map<String, Object> mMap;
private boolean mLoaded = false;
private long mLastModified;
private long mFileSize;
private WatchKey mWatchKey;
static {
Method method = null;
try {
// Find the class and method once during class initialization
Class<?> xmlUtils = Class.forName("com.android.internal.util.XmlUtils");
method = xmlUtils.getDeclaredMethod("readMapXml", InputStream.class);
method.setAccessible(true);
} catch (Exception e) {
Log.e(TAG, "Failed to find com.android.internal.util.XmlUtils.readMapXml", e);
}
sReadMapXmlMethod = method;
}
private static void initWatcherDaemon() {
sWatcherDaemon = new Thread() {
@Override
public void run() {
if (BuildConfig.DEBUG) Log.d(TAG, "Watcher daemon thread started");
while (true) {
WatchKey key;
try {
key = sWatcher.take();
} catch (ClosedWatchServiceException ignored) {
if (BuildConfig.DEBUG) Log.d(TAG, "Watcher daemon thread finished");
sWatcher = null;
return;
} catch (InterruptedException ignored) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
Path dir = (Path) key.watchable();
Path path = dir.resolve((Path) event.context());
String pathStr = path.toString();
if (BuildConfig.DEBUG)
Log.v(TAG, "File " + path.toString() + " event: " + kind.name());
// We react to both real and backup files due to rare race conditions
if (pathStr.endsWith(".bak")) {
if (kind != StandardWatchEventKinds.ENTRY_DELETE) {
continue;
}
} else if (SELinuxHelper.getAppDataFileService().checkFileExists(pathStr + ".bak")) {
continue;
}
PrefsData data = sWatcherKeyInstances.get(key);
if (data != null && data.hasChanged()) {
for (OnSharedPreferenceChangeListener l : data.mPrefs.mListeners.keySet()) {
try {
l.onSharedPreferenceChanged(data.mPrefs, null);
} catch (Throwable t) {
if (BuildConfig.DEBUG)
Log.e(TAG, "Fail in preference change listener", t);
}
}
}
}
key.reset();
}
}
};
sWatcherDaemon.setName(TAG + "-Daemon");
sWatcherDaemon.setDaemon(true);
sWatcherDaemon.start();
}
/**
* Read settings from the specified file.
*
* @param prefFile The file to read the preferences from.
*/
public XSharedPreferences(File prefFile) {
mFile = prefFile;
mFilename = prefFile.getAbsolutePath();
init();
}
/**
* Read settings from the default preferences for a package.
* These preferences are returned by {@link PreferenceManager#getDefaultSharedPreferences}.
*
* @param packageName The package name.
*/
public XSharedPreferences(String packageName) {
this(packageName, packageName + "_preferences");
}
/**
* Read settings from a custom preferences file for a package.
* These preferences are returned by {@link Context#getSharedPreferences(String, int)}.
*
* @param packageName The package name.
* @param prefFileName The file name without ".xml".
*/
public XSharedPreferences(String packageName, String prefFileName) {
boolean newModule = false;
var m = XposedInit.getLoadedModules().getOrDefault(packageName, Optional.empty());
if (m.isPresent()) {
boolean isModule = false;
int xposedminversion = -1;
boolean xposedsharedprefs = false;
try {
Map<String, Object> metaData = VectorMetaDataReader.getMetaData(new File(m.get()));
isModule = metaData.containsKey("xposedminversion");
if (isModule) {
Object minVersionRaw = metaData.get("xposedminversion");
if (minVersionRaw instanceof Integer) {
xposedminversion = (Integer) minVersionRaw;
} else if (minVersionRaw instanceof String) {
xposedminversion = VectorMetaDataReader.extractIntPart((String) minVersionRaw);
}
xposedsharedprefs = metaData.containsKey("xposedsharedprefs");
}
} catch (NumberFormatException | IOException e) {
Log.w(TAG, "Apk parser fails: " + e);
}
newModule = isModule && (xposedminversion > 92 || xposedsharedprefs);
}
if (newModule) {
mFile = new File(VectorServiceClient.INSTANCE.getPrefsPath(packageName), prefFileName + ".xml");
} else {
mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml");
}
mFilename = mFile.getAbsolutePath();
init();
}
private void tryRegisterWatcher() {
if (mWatchKey != null && mWatchKey.isValid()) {
return;
}
synchronized (sWatcherKeyInstances) {
Path path = mFile.toPath();
try {
if (sWatcher == null) {
sWatcher = new File(VectorServiceClient.INSTANCE.getPrefsPath("")).toPath().getFileSystem().newWatchService();
if (BuildConfig.DEBUG) Log.d(TAG, "Created WatchService instance");
}
mWatchKey = path.getParent().register(sWatcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
sWatcherKeyInstances.put(mWatchKey, new PrefsData(this));
if (sWatcherDaemon == null || !sWatcherDaemon.isAlive()) {
initWatcherDaemon();
}
if (BuildConfig.DEBUG)
Log.d(TAG, "tryRegisterWatcher: registered file watcher for " + path);
} catch (AccessDeniedException accDeniedEx) {
if (BuildConfig.DEBUG) Log.e(TAG, "tryRegisterWatcher: access denied to " + path);
} catch (Exception e) {
Log.e(TAG, "tryRegisterWatcher: failed to register file watcher", e);
}
}
}
private void tryUnregisterWatcher() {
synchronized (sWatcherKeyInstances) {
if (mWatchKey != null) {
sWatcherKeyInstances.remove(mWatchKey);
mWatchKey.cancel();
mWatchKey = null;
}
boolean atLeastOneValid = false;
for (WatchKey key : sWatcherKeyInstances.keySet()) {
atLeastOneValid |= key.isValid();
}
if (!atLeastOneValid) {
try {
sWatcher.close();
} catch (Exception ignore) {
}
}
}
}
private void init() {
startLoadFromDisk();
}
private static long tryGetFileSize(String filename) {
try {
return SELinuxHelper.getAppDataFileService().getFileSize(filename);
} catch (IOException ignored) {
return 0;
}
}
private static byte[] tryGetFileHash(String filename) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = SELinuxHelper.getAppDataFileService().getFileInputStream(filename)) {
byte[] buf = new byte[4096];
int read;
while ((read = is.read(buf)) != -1) {
md.update(buf, 0, read);
}
}
return md.digest();
} catch (Exception ignored) {
return new byte[0];
}
}
/**
* Tries to make the preferences file world-readable.
*
* <p><strong>Warning:</strong> This is only meant to work around permission "fix" functions that are part
* of some recoveries. It doesn't replace the need to open preferences with {@code MODE_WORLD_READABLE}
* in the module's UI code. Otherwise, Android will set stricter permissions again during the next save.
*
* <p>This will only work if executed as root (e.g. {@code initZygote()}) and only if SELinux is disabled.
*
* @return {@code true} in case the file could be made world-readable.
*/
@SuppressLint("SetWorldReadable")
public boolean makeWorldReadable() {
if (!SELinuxHelper.getAppDataFileService().hasDirectFileAccess())
return false; // It doesn't make much sense to make the file readable if we wouldn't be able to access it anyway.
if (!mFile.exists()) // Just in case - the file should never be created if it doesn't exist.
return false;
if (!mFile.setReadable(true, false))
return false;
// Watcher service needs read access to parent directory (looks like execute is not enough)
if (mFile.getParentFile() != null) {
mFile.getParentFile().setReadable(true, false);
}
if (!mListeners.isEmpty()) {
tryRegisterWatcher();
}
return true;
}
/**
* Returns the file that is backing these preferences.
*
* <p><strong>Warning:</strong> The file might not be accessible directly.
*/
public File getFile() {
return mFile;
}
private void startLoadFromDisk() {
synchronized (this) {
mLoaded = false;
}
new Thread("XSharedPreferences-load") {
@Override
public void run() {
synchronized (XSharedPreferences.this) {
loadFromDiskLocked();
}
}
}.start();
}
private Map<?, ?> performReadMapXml(InputStream str) throws XmlPullParserException, IOException {
try {
if (sReadMapXmlMethod == null) throw new IOException("Internal API not found");
return (Map<?, ?>) sReadMapXmlMethod.invoke(null, str);
} catch (InvocationTargetException e) {
// Unwrap and throw the real error
Throwable cause = e.getCause();
if (cause instanceof XmlPullParserException) throw (XmlPullParserException) cause;
if (cause instanceof IOException) throw (IOException) cause;
if (cause instanceof RuntimeException) throw (RuntimeException) cause;
throw new RuntimeException(cause);
} catch (IllegalAccessException e) {
throw new IOException("Access denied to internal API", e);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void loadFromDiskLocked() {
if (mLoaded) {
return;
}
Map map = null;
FileResult result = null;
try {
result = SELinuxHelper.getAppDataFileService().getFileInputStream(mFilename, mFileSize, mLastModified);
if (result.stream != null) {
map = performReadMapXml(result.stream);
result.stream.close();
} else {
// The file is unchanged, keep the current values
map = mMap;
}
} catch (XmlPullParserException e) {
Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e);
} catch (FileNotFoundException ignored) {
// SharedPreferencesImpl has a canRead() check, so it doesn't log anything in case the file doesn't exist
} catch (IOException e) {
Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e);
} finally {
if (result != null && result.stream != null) {
try {
result.stream.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
mLoaded = true;
if (map != null) {
mMap = map;
mLastModified = result.mtime;
mFileSize = result.size;
} else {
mMap = new HashMap<>();
}
notifyAll();
}
/**
* Reload the settings from file if they have changed.
*
* <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive.
*/
public synchronized void reload() {
if (hasFileChanged()) {
init();
}
}
/**
* Check whether the file has changed since the last time it has been loaded.
*
* <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive.
*/
public synchronized boolean hasFileChanged() {
try {
FileResult result = SELinuxHelper.getAppDataFileService().statFile(mFilename);
return mLastModified != result.mtime || mFileSize != result.size;
} catch (FileNotFoundException ignored) {
// SharedPreferencesImpl doesn't log anything in case the file doesn't exist
return true;
} catch (IOException e) {
Log.w(TAG, "hasFileChanged", e);
return true;
}
}
private void awaitLoadedLocked() {
while (!mLoaded) {
try {
wait();
} catch (InterruptedException unused) {
}
}
}
/**
* @hide
*/
@Override
public Map<String, ?> getAll() {
synchronized (this) {
awaitLoadedLocked();
return new HashMap<>(mMap);
}
}
/**
* @hide
*/
@Override
public String getString(String key, String defValue) {
synchronized (this) {
awaitLoadedLocked();
String v = (String) mMap.get(key);
return v != null ? v : defValue;
}
}
/**
* @hide
*/
@Override
@SuppressWarnings("unchecked")
public Set<String> getStringSet(String key, Set<String> defValues) {
synchronized (this) {
awaitLoadedLocked();
Set<String> v = (Set<String>) mMap.get(key);
return v != null ? v : defValues;
}
}
/**
* @hide
*/
@Override
public int getInt(String key, int defValue) {
synchronized (this) {
awaitLoadedLocked();
Integer v = (Integer) mMap.get(key);
return v != null ? v : defValue;
}
}
/**
* @hide
*/
@Override
public long getLong(String key, long defValue) {
synchronized (this) {
awaitLoadedLocked();
Long v = (Long) mMap.get(key);
return v != null ? v : defValue;
}
}
/**
* @hide
*/
@Override
public float getFloat(String key, float defValue) {
synchronized (this) {
awaitLoadedLocked();
Float v = (Float) mMap.get(key);
return v != null ? v : defValue;
}
}
/**
* @hide
*/
@Override
public boolean getBoolean(String key, boolean defValue) {
synchronized (this) {
awaitLoadedLocked();
Boolean v = (Boolean) mMap.get(key);
return v != null ? v : defValue;
}
}
/**
* @hide
*/
@Override
public boolean contains(String key) {
synchronized (this) {
awaitLoadedLocked();
return mMap.containsKey(key);
}
}
/**
* @deprecated Not supported by this implementation.
*/
@Deprecated
@Override
public Editor edit() {
throw new UnsupportedOperationException("read-only implementation");
}
/**
* Registers a callback to be invoked when a change happens to a preference file.<br>
* Note that it is not possible to determine which preference changed exactly and thus
* preference key in callback invocation will always be null.
*
* @param listener The callback that will run.
* @see #unregisterOnSharedPreferenceChangeListener
*/
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
if (listener == null)
throw new IllegalArgumentException("listener cannot be null");
synchronized (this) {
if (mListeners.put(listener, sContent) == null) {
tryRegisterWatcher();
}
}
}
/**
* Unregisters a previous callback.
*
* @param listener The callback that should be unregistered.
* @see #registerOnSharedPreferenceChangeListener
*/
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
synchronized (this) {
if (mListeners.remove(listener) != null && mListeners.isEmpty()) {
tryUnregisterWatcher();
}
}
}
private static class PrefsData {
public final XSharedPreferences mPrefs;
private long mSize;
private byte[] mHash;
public PrefsData(XSharedPreferences prefs) {
mPrefs = prefs;
mSize = tryGetFileSize(prefs.mFilename);
mHash = tryGetFileHash(prefs.mFilename);
}
public boolean hasChanged() {
long size = tryGetFileSize(mPrefs.mFilename);
if (size < 1) {
if (BuildConfig.DEBUG) Log.d(TAG, "Ignoring empty prefs file");
return false;
}
if (size != mSize) {
mSize = size;
mHash = tryGetFileHash(mPrefs.mFilename);
if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file size changed");
return true;
}
byte[] hash = tryGetFileHash(mPrefs.mFilename);
if (!Arrays.equals(hash, mHash)) {
mHash = hash;
if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file hash changed");
return true;
}
if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file not changed");
return false;
}
}
}