-
Notifications
You must be signed in to change notification settings - Fork 2
/
frameworks.diff
4352 lines (4323 loc) · 193 KB
/
frameworks.diff
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
diff -Npru --exclude='.git*' cyanogen/frameworks/base/Android.mk pang/frameworks/base/Android.mk
--- cyanogen/frameworks/base/Android.mk 2012-07-13 09:01:06.894080670 -0700
+++ pang/frameworks/base/Android.mk 2012-07-13 10:18:29.375676051 -0700
@@ -73,6 +73,7 @@ LOCAL_SRC_FILES := $(filter-out \
## across process boundaries.
##
## READ ME: ########################################################
+# BEGIN privacy-added: IPrivacySettingsManager.aidl
LOCAL_SRC_FILES += \
core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl \
core/java/android/accessibilityservice/IAccessibilityServiceClient.aidl \
@@ -215,6 +216,7 @@ LOCAL_SRC_FILES += \
media/java/android/media/IRemoteControlDisplay.aidl \
media/java/android/media/IRemoteVolumeObserver.aidl \
media/java/android/media/IRingtonePlayer.aidl \
+ privacy/java/android/privacy/IPrivacySettingsManager.aidl \
telephony/java/com/android/internal/telephony/IPhoneStateListener.aidl \
telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl \
telephony/java/com/android/internal/telephony/ITelephony.aidl \
@@ -229,6 +231,7 @@ LOCAL_SRC_FILES += \
voip/java/android/net/sip/ISipSessionListener.aidl \
voip/java/android/net/sip/ISipService.aidl
#
+# END privacy-added: IPrivacySettingsManager.aidl
# FRAMEWORKS_BASE_JAVA_SRC_DIRS comes from build/core/pathmap.mk
@@ -272,6 +275,7 @@ framework_built += $(call java-lib-deps,
# AIDL files to be preprocessed and included in the SDK,
# relative to the root of the build tree.
# ============================================================
+# BEGIN privacy-added: PrivacySettings.aidl
aidl_files := \
frameworks/base/core/java/android/accounts/IAccountManager.aidl \
frameworks/base/core/java/android/accounts/IAccountManagerResponse.aidl \
@@ -317,11 +321,13 @@ aidl_files := \
frameworks/base/graphics/java/android/graphics/Region.aidl \
frameworks/base/location/java/android/location/Criteria.aidl \
frameworks/base/location/java/android/location/Location.aidl \
+ frameworks/base/privacy/java/android/privacy/PrivacySettings.aidl \
frameworks/base/telephony/java/android/telephony/ServiceState.aidl \
frameworks/base/telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl \
frameworks/base/telephony/java/com/android/internal/telephony/ITelephony.aidl \
gen := $(TARGET_OUT_COMMON_INTERMEDIATES)/framework.aidl
+# END privacy-added: PrivacySettings.aidl
$(gen): PRIVATE_SRC_FILES := $(aidl_files)
ALL_SDK_FILES += $(gen)
$(gen): $(aidl_files) | $(AIDL)
diff -Npru --exclude='.git*' cyanogen/frameworks/base/core/java/android/app/ContextImpl.java pang/frameworks/base/core/java/android/app/ContextImpl.java
--- cyanogen/frameworks/base/core/java/android/app/ContextImpl.java 2012-07-13 09:01:07.581243949 -0700
+++ pang/frameworks/base/core/java/android/app/ContextImpl.java 2012-07-13 10:18:29.378676754 -0700
@@ -95,6 +95,13 @@ import android.os.UserId;
import android.os.SystemVibrator;
import android.os.SystemProperties;
import android.os.storage.StorageManager;
+// BEGIN privacy-added
+import android.privacy.IPrivacySettingsManager;
+import android.privacy.PrivacySettingsManager;
+import android.privacy.surrogate.PrivacyAccountManager;
+import android.privacy.surrogate.PrivacyLocationManager;
+import android.privacy.surrogate.PrivacyTelephonyManager;
+// END privacy-added
import android.telephony.TelephonyManager;
import android.content.ClipboardManager;
import android.util.*;
@@ -165,6 +172,7 @@ class ContextImpl extends Context {
private Resources mResources;
/*package*/ ActivityThread mMainThread;
private Context mOuterContext;
+ private static Context sOuterContext;
private IBinder mActivityToken = null;
private ApplicationContentResolver mContentResolver;
private int mThemeResource = 0;
@@ -278,7 +286,9 @@ class ContextImpl extends Context {
public Object createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
IAccountManager service = IAccountManager.Stub.asInterface(b);
- return new AccountManager(ctx, service);
+ // BEGIN privacy-modified
+ return new PrivacyAccountManager(ctx, service);
+ // END privacy-modified
}});
registerService(ACTIVITY_SERVICE, new ServiceFetcher() {
@@ -373,7 +383,10 @@ class ContextImpl extends Context {
registerService(LOCATION_SERVICE, new ServiceFetcher() {
public Object createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(LOCATION_SERVICE);
- return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
+ // BEGIN privacy-modified
+ ILocationManager service = ILocationManager.Stub.asInterface(b);
+ return new PrivacyLocationManager(service, ctx);
+ // END privacy-modified
}});
registerService(NETWORK_POLICY_SERVICE, new ServiceFetcher() {
@@ -443,7 +456,9 @@ class ContextImpl extends Context {
registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
public Object createService(ContextImpl ctx) {
- return new TelephonyManager(ctx.getOuterContext());
+ // BEGIN privacy-modified
+ return new PrivacyTelephonyManager(ctx.getOuterContext());
+ // END privacy-modified
}});
registerService(THROTTLE_SERVICE, new StaticServiceFetcher() {
@@ -505,6 +520,16 @@ class ContextImpl extends Context {
public Object createService(ContextImpl ctx) {
return WimaxHelper.createWimaxService(ctx, ctx.mMainThread.getHandler());
}});
+
+ // BEGIN privacy-added
+ registerService("privacy", new StaticServiceFetcher() {
+ public Object createStaticService() {
+ IBinder b = ServiceManager.getService("privacy");
+ IPrivacySettingsManager service = IPrivacySettingsManager.Stub.asInterface(b);
+ return new PrivacySettingsManager(getStaticOuterContext(),service);
+ }});
+ // END privacy-added
+
}
static ContextImpl getImpl(Context context) {
@@ -1572,7 +1597,7 @@ class ContextImpl extends Context {
}
ContextImpl() {
- mOuterContext = this;
+ sOuterContext = mOuterContext = this;
}
/**
@@ -1587,7 +1612,7 @@ class ContextImpl extends Context {
mResources = context.mResources;
mMainThread = context.mMainThread;
mContentResolver = context.mContentResolver;
- mOuterContext = this;
+ sOuterContext = mOuterContext = this;
}
static void init(ActivityThread thread) {
@@ -1737,13 +1762,17 @@ class ContextImpl extends Context {
}
final void setOuterContext(Context context) {
- mOuterContext = context;
+ sOuterContext = mOuterContext = context;
}
final Context getOuterContext() {
return mOuterContext;
}
+ final static Context getStaticOuterContext() {
+ return sOuterContext;
+ }
+
final IBinder getActivityToken() {
return mActivityToken;
}
diff -Npru --exclude='.git*' cyanogen/frameworks/base/core/java/android/content/ContentResolver.java pang/frameworks/base/core/java/android/content/ContentResolver.java
--- cyanogen/frameworks/base/core/java/android/content/ContentResolver.java 2012-07-13 09:01:07.723277695 -0700
+++ pang/frameworks/base/core/java/android/content/ContentResolver.java 2012-07-13 10:18:29.381677468 -0700
@@ -39,6 +39,9 @@ import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
+// BEGIN privacy-added
+import android.privacy.surrogate.PrivacyContentResolver;
+// END privacy-added
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
@@ -381,6 +384,10 @@ public abstract class ContentResolver {
qCursor = stableProvider.query(uri, projection,
selection, selectionArgs, sortOrder, remoteCancellationSignal);
}
+ // BEGIN privacy-added
+// qCursor = PrivacyContentResolver.enforcePrivacyPermission(uri, mContext, qCursor);
+ qCursor = PrivacyContentResolver.enforcePrivacyPermission(uri, projection, mContext, qCursor);
+ // END privacy-added
if (qCursor == null) {
return null;
}
diff -Npru --exclude='.git*' cyanogen/frameworks/base/preloaded-classes pang/frameworks/base/preloaded-classes
--- cyanogen/frameworks/base/preloaded-classes 2012-07-13 09:01:37.346316218 -0700
+++ pang/frameworks/base/preloaded-classes 2012-07-13 10:18:29.383677944 -0700
@@ -652,6 +652,10 @@ android.provider.Settings$NameValueCache
android.provider.Settings$NameValueTable
android.provider.Settings$Secure
android.provider.Settings$System
+# BEGIN privacy-added
+android.privacy.PrivacySettingsManager
+android.privacy.PrivacySettings
+# END privacy-added
android.renderscript.RenderScript
android.server.BluetoothA2dpService
android.server.BluetoothEventLoop
diff -Npru --exclude='.git*' cyanogen/frameworks/base/privacy/java/android/privacy/IPrivacySettingsManager.aidl pang/frameworks/base/privacy/java/android/privacy/IPrivacySettingsManager.aidl
--- cyanogen/frameworks/base/privacy/java/android/privacy/IPrivacySettingsManager.aidl 1969-12-31 16:00:00.000000000 -0800
+++ pang/frameworks/base/privacy/java/android/privacy/IPrivacySettingsManager.aidl 2012-07-13 10:18:29.385678417 -0700
@@ -0,0 +1,18 @@
+package android.privacy;
+import android.privacy.PrivacySettings;
+
+/** {@hide} */
+interface IPrivacySettingsManager
+{
+ PrivacySettings getSettings(String packageName);
+ boolean saveSettings(in PrivacySettings settings);
+ boolean deleteSettings(String packageName);
+ void notification(String packageName, byte accessMode, String dataType, String output);
+ void registerObservers();
+ void addObserver(String packageName);
+ boolean purgeSettings();
+ double getVersion();
+ boolean setEnabled(boolean enable);
+ boolean setNotificationsEnabled(boolean enable);
+ void setBootCompleted();
+}
diff -Npru --exclude='.git*' cyanogen/frameworks/base/privacy/java/android/privacy/PrivacyFileObserver.java pang/frameworks/base/privacy/java/android/privacy/PrivacyFileObserver.java
--- cyanogen/frameworks/base/privacy/java/android/privacy/PrivacyFileObserver.java 1969-12-31 16:00:00.000000000 -0800
+++ pang/frameworks/base/privacy/java/android/privacy/PrivacyFileObserver.java 2012-07-13 10:18:29.386678654 -0700
@@ -0,0 +1,89 @@
+package android.privacy;
+
+import android.os.FileObserver;
+import android.util.Log;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.StringTokenizer;
+
+/** {@hide} */
+public class PrivacyFileObserver extends FileObserver {
+
+ public static final String TAG = "PrivacyFileObserver";
+
+ public static final int PACKAGE_PATH_INDEX = 3;
+
+ public String absolutePath;
+
+ private PrivacySettingsManagerService pSetManServ;
+
+ public HashMap<String, PrivacyFileObserver> children;
+
+ public PrivacyFileObserver(String path, PrivacySettingsManagerService pSetManServ) {
+ super(path, FileObserver.ALL_EVENTS);
+ this.absolutePath = path;
+ this.pSetManServ = pSetManServ;
+
+ this.children = new HashMap<String, PrivacyFileObserver>();
+ File thisFile = new File(absolutePath);
+ if (thisFile.isDirectory()) {
+ File[] subfiles = thisFile.listFiles();
+ for (File file : subfiles) {
+ String observePath = file.getAbsolutePath();
+ PrivacyFileObserver child = new PrivacyFileObserver(observePath, pSetManServ);
+ children.put(observePath, child);
+ // don't watch directories, only the settings files
+ if (file.isFile()) child.startWatching();
+ }
+ }
+
+ }
+
+ @Override
+ public void onEvent(int event, String path) {
+ if ((FileObserver.ACCESS & event) != 0) { // data was read from a file
+// Log.d(TAG, "onEvent - file accessed: " + absolutePath);
+ StringTokenizer tokenizer = new StringTokenizer(absolutePath, "/");
+ for (int i = 0; i < PACKAGE_PATH_INDEX && tokenizer.hasMoreElements(); i++) {
+ tokenizer.nextToken();
+ }
+
+ // get the package and UID of accessing application
+ String packageName = tokenizer.nextToken();
+// int uid = 0;
+// try {
+// uid = Integer.parseInt(tokenizer.nextToken());
+// } catch (NumberFormatException e) {
+// Log.e(TAG, "onEvent - could not get the UID of accessing application", e);
+// // we still can continue, UID is optional here
+// }
+
+ // read the setting
+ PrivacySettings pSet = pSetManServ.getSettings(packageName);
+ pSetManServ.notification(packageName, pSet.getSystemLogsSetting(), PrivacySettings.DATA_SYSTEM_LOGS, null);
+ }
+
+ }
+
+ public void addObserver(String relativePath) {
+ String observePath = absolutePath + "/" + relativePath;
+ // remove existing observer(s) if any
+ children.remove(observePath); // child observers should be destroyed at next GC
+ // create new observer(s)
+ PrivacyFileObserver child = new PrivacyFileObserver(observePath, pSetManServ);
+ children.put(observePath, child);
+ }
+
+ @Override
+ public void startWatching() {
+// Log.d("PrivacyFileObserver", "PrivacyFileObserver - observing directory: " + absolutePath);
+ super.startWatching();
+ }
+
+// public void verifyObserver() {
+// Log.d(TAG, "verifyObservers - observer path: " + absolutePath);
+// for (PrivacyFileObserver obs : children.values()) obs.verifyObserver();
+// }
+
+}
\ No newline at end of file
diff -Npru --exclude='.git*' cyanogen/frameworks/base/privacy/java/android/privacy/PrivacyPersistenceAdapter.java pang/frameworks/base/privacy/java/android/privacy/PrivacyPersistenceAdapter.java
--- cyanogen/frameworks/base/privacy/java/android/privacy/PrivacyPersistenceAdapter.java 1969-12-31 16:00:00.000000000 -0800
+++ pang/frameworks/base/privacy/java/android/privacy/PrivacyPersistenceAdapter.java 2012-07-13 10:18:29.388679130 -0700
@@ -0,0 +1,792 @@
+package android.privacy;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.database.SQLException;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteException;
+import android.os.FileUtils;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Responsible for persisting privacy settings to built-in memory
+ * @author Svyatoslav Hresyk
+ * {@hide}
+ */
+public class PrivacyPersistenceAdapter {
+
+ private static final String TAG = "PrivacyPersistenceAdapter";
+
+ private static final int RETRY_QUERY_COUNT = 5;
+
+ private static final String DATABASE_FILE = "/data/system/privacy.db";
+
+ private static final int DATABASE_VERSION = 3;
+
+ public static final int DUMMY_UID = -1;
+
+ /**
+ * Number of threads currently reading the database
+ */
+ public static Integer readingThreads = 0;
+
+ /**
+ * Used to save settings for access from core libraries
+ */
+ public static final String SETTINGS_DIRECTORY = "/data/system/privacy";
+
+ private static final String TABLE_SETTINGS = "settings";
+
+ private static final String TABLE_MAP = "map";
+
+ private static final String TABLE_ALLOWED_CONTACTS = "allowed_contacts";
+
+ private static final String TABLE_VERSION = "version";
+
+ private static final String CREATE_TABLE_SETTINGS =
+ "CREATE TABLE IF NOT EXISTS " + TABLE_SETTINGS + " ( " +
+ " _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
+ " packageName TEXT, " +
+ " uid INTEGER, " +
+ " deviceIdSetting INTEGER, " +
+ " deviceId TEXT, " +
+ " line1NumberSetting INTEGER, " +
+ " line1Number TEXT, " +
+ " locationGpsSetting INTEGER, " +
+ " locationGpsLat TEXT, " +
+ " locationGpsLon TEXT, " +
+ " locationNetworkSetting INTEGER, " +
+ " locationNetworkLat TEXT, " +
+ " locationNetworkLon TEXT, " +
+ " networkInfoSetting INTEGER, " +
+ " simInfoSetting INTEGER, " +
+ " simSerialNumberSetting INTEGER, " +
+ " simSerialNumber TEXT, " +
+ " subscriberIdSetting INTEGER, " +
+ " subscriberId TEXT, " +
+ " accountsSetting INTEGER, " +
+ " accountsAuthTokensSetting INTEGER, " +
+ " outgoingCallsSetting INTEGER, " +
+ " incomingCallsSetting INTEGER, " +
+ " contactsSetting INTEGER, " +
+ " calendarSetting INTEGER, " +
+ " mmsSetting INTEGER, " +
+ " smsSetting INTEGER, " +
+ " callLogSetting INTEGER, " +
+ " bookmarksSetting INTEGER, " +
+ " systemLogsSetting INTEGER, " +
+ " externalStorageSetting INTEGER, " +
+ " cameraSetting INTEGER, " +
+ " recordAudioSetting INTEGER, " +
+ " notificationSetting INTEGER, " +
+ " intentBootCompletedSetting INTEGER" +
+ ");";
+
+ private static final String CREATE_TABLE_MAP =
+ "CREATE TABLE IF NOT EXISTS " + TABLE_MAP + " ( name TEXT PRIMARY KEY, value TEXT );";
+
+ private static final String CREATE_TABLE_ALLOWED_CONTACTS =
+ "CREATE TABLE IF NOT EXISTS " + TABLE_ALLOWED_CONTACTS + " ( settings_id, contact_id, PRIMARY KEY(settings_id, contact_id) );";
+
+ private static final String INSERT_VERSION =
+ "INSERT OR REPLACE INTO " + TABLE_MAP + " (name, value) " + "VALUES (\"db_version\", " + DATABASE_VERSION + ");";
+
+ private static final String INSERT_ENABLED =
+ "INSERT OR REPLACE INTO " + TABLE_MAP + " (name, value) " + "VALUES (\"enabled\", \"1\");";
+
+ private static final String INSERT_NOTIFICATIONS_ENABLED =
+ "INSERT OR REPLACE INTO " + TABLE_MAP + " (name, value) " + "VALUES (\"notifications_enabled\", \"1\");";
+
+ private static final String[] DATABASE_FIELDS = new String[] { "_id", "packageName", "uid",
+ "deviceIdSetting", "deviceId", "line1NumberSetting", "line1Number", "locationGpsSetting",
+ "locationGpsLat", "locationGpsLon", "locationNetworkSetting", "locationNetworkLat",
+ "locationNetworkLon", "networkInfoSetting", "simInfoSetting", "simSerialNumberSetting",
+ "simSerialNumber", "subscriberIdSetting", "subscriberId", "accountsSetting", "accountsAuthTokensSetting",
+ "outgoingCallsSetting", "incomingCallsSetting", "contactsSetting", "calendarSetting",
+ "mmsSetting", "smsSetting", "callLogSetting", "bookmarksSetting", "systemLogsSetting",
+ "externalStorageSetting", "cameraSetting", "recordAudioSetting", "notificationSetting",
+ "intentBootCompletedSetting" };
+
+ public static final String SETTING_ENABLED = "enabled";
+ public static final String SETTING_NOTIFICATIONS_ENABLED = "notifications_enabled";
+ public static final String SETTING_DB_VERSION = "db_version";
+ public static final String VALUE_TRUE = "1";
+ public static final String VALUE_FALSE = "0";
+
+ private SQLiteDatabase db;
+
+ private Context context;
+
+ public PrivacyPersistenceAdapter(Context context) {
+ this.context = context;
+ // check write permission for /data/system/
+ boolean canWrite = new File("/data/system/").canWrite();
+// Log.d(TAG, "Constructing " + TAG + " for package: " + context.getPackageName() +
+// " UID: " + Binder.getCallingUid() + "; Write permission for /data/system/: " + canWrite);
+ // create the database and settings directory if we have write permission and they do not exist
+ if (canWrite) {
+ if (!new File(DATABASE_FILE).exists()) createDatabase();
+ if (!new File(SETTINGS_DIRECTORY).exists()) createSettingsDir();
+ // upgrade if needed
+ int currentVersion = getDbVersion();
+// Log.d(TAG, "PrivacyPersistenceAdapter - current DB version: " + currentVersion);
+ if (currentVersion < DATABASE_VERSION) upgradeDatabase(currentVersion);
+ }
+ }
+
+ private synchronized void upgradeDatabase(int currentVersion) {
+ Log.i(TAG, "upgradeDatabase - upgrading DB from version " + currentVersion + " to " + DATABASE_VERSION);
+
+ // backup current database file
+ File dbFile = new File(DATABASE_FILE);
+ File dbBackupFile = new File(DATABASE_FILE + ".bak");
+ // remove old backup
+ try {
+ dbBackupFile.delete();
+ } catch (SecurityException e) {
+ Log.w(TAG, "upgradeDatabase - could not remove old backup");
+ }
+ // backup current DB file
+ FileUtils.copyFile(dbFile, dbBackupFile);
+ // make sure a backup was created
+ if (System.currentTimeMillis() - dbBackupFile.lastModified() > 2000) {
+ Log.e(TAG, "upgradeDatabase - could not create a database backup, aborting...");
+ return;
+ }
+
+ SQLiteDatabase db = getWritableDatabase();
+ db.beginTransaction();
+
+ switch (currentVersion) {
+ case 1:
+ case 2:
+ try {
+ if (db != null && db.isOpen()) {
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_VERSION + ";");
+ db.execSQL(CREATE_TABLE_ALLOWED_CONTACTS);
+ db.execSQL(CREATE_TABLE_MAP);
+ db.execSQL(INSERT_VERSION);
+ db.execSQL(INSERT_ENABLED);
+ db.execSQL(INSERT_NOTIFICATIONS_ENABLED);
+
+ // remove uid dirs from the settings directory
+ File settingsDir = new File(SETTINGS_DIRECTORY);
+ for (File packageDir : settingsDir.listFiles()) {
+ for (File uidDir : packageDir.listFiles()) {
+ if (uidDir.isDirectory()) {
+ File[] settingsFiles = uidDir.listFiles();
+ // copy the first found (most likely the only one) one level up
+ if (settingsFiles[0] != null) {
+ File newPath = new File(packageDir + "/" + settingsFiles[0].getName());
+ newPath.delete();
+ settingsFiles[0].renameTo(newPath);
+ deleteRecursive(uidDir);
+ }
+ }
+ }
+ }
+
+ db.setTransactionSuccessful();
+ }
+ } catch (Exception e) {
+ if (db != null && db.isOpen()) {
+ db.endTransaction();
+ db.close();
+ }
+ Log.w(TAG, "upgradeDatabase - could not upgrade DB; will restore backup", e);
+ FileUtils.copyFile(dbBackupFile, dbFile);
+ dbBackupFile.delete();
+ }
+
+
+ break;
+
+ case 3:
+ // most current version, do nothing
+ Log.w(TAG, "upgradeDatabase - trying to upgrade most current DB version");
+ break;
+ }
+
+ if (db != null && db.isOpen()) {
+ db.endTransaction();
+ db.close();
+ } else {
+ Log.e(TAG, "upgradeDatabase - database is null or closed; cant call endTransaction()");
+ }
+
+ purgeSettings();
+ }
+
+ private int getDbVersion() {
+ int version = -1;
+ // check if the table "map" exists; if it doesn't -> return version 1
+ readingThreads++;
+ SQLiteDatabase db = getReadableDatabase();
+ try {
+ Cursor c = rawQuery(db, "SELECT name FROM sqlite_master WHERE type='table' AND name='" + TABLE_MAP + "';");
+ if (c != null) {
+ if (c.getCount() == 0) {
+ // table map does not exist
+ version = 1;
+ }
+ c.close();
+ synchronized (readingThreads) {
+ readingThreads--;
+ // only close DB if no other threads are reading
+ if (readingThreads == 0 && db != null && db.isOpen()) {
+ db.close();
+ }
+ }
+ } else {
+ Log.e(TAG, "getDbVersion - failed to check if table map exists (cursor is null)");
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "getDbVersion - failed to check if table map exists (exception)");
+ }
+ if (version == 1) return version;
+
+ String versionString = getValue(SETTING_DB_VERSION);
+ if (versionString == null) return 1;
+
+ int versionNum;
+ try {
+ versionNum = Integer.parseInt(versionString);
+ } catch (Exception e) {
+ Log.e(TAG, "getDbVersion - failed to parse database version; returning 1");
+ return 1;
+ }
+
+ return versionNum;
+ }
+
+ public String getValue(String name) {
+ readingThreads++;
+ SQLiteDatabase db = getReadableDatabase();
+ Cursor c;
+ String output = null;
+
+ try {
+ c = query(db, TABLE_MAP, new String[] { "value" }, "name=?",
+ new String[] { name }, null, null, null, null);
+ if (c != null && c.getCount() > 0 && c.moveToFirst()) {
+ output = c.getString(c.getColumnIndex("value"));
+ c.close();
+ } else {
+ Log.w(TAG, "getValue - could not get value for name: " + name);
+ }
+ } catch (Exception e) {
+ Log.w(TAG, "getValue - could not get value for name: " + name, e);
+ }
+
+ synchronized (readingThreads) {
+ readingThreads--;
+ // only close DB if no other threads are reading
+ if (readingThreads == 0 && db != null && db.isOpen()) {
+ db.close();
+ }
+ }
+ return output;
+ }
+
+ public synchronized boolean setValue(String name, String value) {
+ Log.e(TAG, "setValue - name " + name + " value " + value);
+ ContentValues values = new ContentValues();
+ values.put("name", name);
+ values.put("value", value);
+ SQLiteDatabase db = getWritableDatabase();
+ boolean success = db.replace(TABLE_MAP, null, values) != -1;
+ if (readingThreads == 0 && db != null && db.isOpen()) db.close();
+ return success;
+ }
+
+ public synchronized PrivacySettings getSettings(String packageName, boolean forceCloseDB) {
+ PrivacySettings s = null;
+
+ if (packageName == null) {
+ Log.e(TAG, "getSettings - insufficient application identifier - package name is required");
+ return s;
+ }
+
+ // indicate that the DB is being read to prevent closing by other threads
+ readingThreads++;
+// Log.d(TAG, "getSettings - settings request for package: " + packageName + " readingThreads: " + readingThreads);
+
+ SQLiteDatabase db;
+ try {
+ db = getReadableDatabase();
+ } catch (SQLiteException e) {
+ Log.e(TAG, "getSettings - database could not be opened", e);
+ readingThreads--;
+ return s;
+ }
+
+ Cursor c = null;
+
+ try {
+ c = query(db, TABLE_SETTINGS, DATABASE_FIELDS, "packageName=?", new String[] { packageName }, null, null, null, null);
+
+ if (c != null && c.moveToFirst()) {
+ s = new PrivacySettings(c.getInt(0), c.getString(1), c.getInt(2), (byte)c.getShort(3), c.getString(4),
+ (byte)c.getShort(5), c.getString(6), (byte)c.getShort(7), c.getString(8), c.getString(9), (byte)c.getShort(10),
+ c.getString(11), c.getString(12), (byte)c.getShort(13), (byte)c.getShort(14), (byte)c.getShort(15),
+ c.getString(16), (byte)c.getShort(17), c.getString(18), (byte)c.getShort(19), (byte)c.getShort(20),
+ (byte)c.getShort(21), (byte)c.getShort(22), (byte)c.getShort(23), (byte)c.getShort(24), (byte)c.getShort(25),
+ (byte)c.getShort(26), (byte)c.getShort(27), (byte)c.getShort(28), (byte)c.getShort(29), (byte)c.getShort(30),
+ (byte)c.getShort(31), (byte)c.getShort(32), (byte)c.getShort(33), (byte)c.getShort(34), null);
+
+ // get allowed contacts IDs if necessary
+// Log.d(TAG, "getSettings - looking for allowed contacts for " + s.get_id());
+// c = query(db, TABLE_ALLOWED_CONTACTS, null,
+// "settings_id=?", new String[] { Integer.toString(s.get_id()) }, null, null, null, null);
+ c = rawQuery(db, "SELECT * FROM allowed_contacts WHERE settings_id=" + Integer.toString(s.get_id()) + ";");
+
+ if (c != null && c.getCount() > 0) {
+// Log.d(TAG, "getSettings - found allowed contacts");
+ int[] allowedContacts = new int[c.getCount()];
+ while (c.moveToNext()) allowedContacts[c.getPosition()] = c.getInt(1);
+ s.setAllowedContacts(allowedContacts);
+ }
+// Log.d(TAG, "getSettings - found settings entry for package: " + packageName + " UID: " + uid);
+ }
+// else {
+// Log.e(TAG, "getSettings - no settings found for package: " + packageName);
+// }
+ } catch (Exception e) {
+ Log.e(TAG, "getSettings - failed to get settings for package: " + packageName, e);
+ e.printStackTrace();
+ if (c != null) c.close();
+ } finally {
+ if (c != null) c.close();
+// if (forceCloseDB && db != null && db.isOpen()) {
+// db.close();
+// } else {
+ synchronized (readingThreads) {
+ readingThreads--;
+ // only close DB if no other threads are reading
+ if (readingThreads == 0 && db != null && db.isOpen()) {
+ db.close();
+ }
+ }
+// }
+ }
+
+// Log.d(TAG, "getSettings - returning settings: " + s);
+ return s;
+ }
+
+ /**
+ * Saves the settings object fields into DB and into plain text files where applicable.
+ * The DB changes will not be made persistent if saving settings to plain text files
+ * fails.
+ * @param s settings object
+ * @return true if settings were saved successfully, false otherwise
+ */
+ public synchronized boolean saveSettings(PrivacySettings s) {
+ boolean result = true;
+ String packageName = s.getPackageName();
+// Integer uid = s.getUid();
+// Log.d(TAG, "saveSettings - settings save request : " + s);
+
+ if (packageName == null || packageName.isEmpty()/* || uid == null*/) {
+ Log.e(TAG, "saveSettings - either package name, UID or both is missing");
+ return false;
+ }
+
+ ContentValues values = new ContentValues();
+ values.put("packageName", packageName);
+// values.put("uid", uid);
+ values.put("uid", DUMMY_UID);
+
+ values.put("deviceIdSetting", s.getDeviceIdSetting());
+ values.put("deviceId", s.getDeviceId());
+
+ values.put("line1NumberSetting", s.getLine1NumberSetting());
+ values.put("line1Number", s.getLine1Number());
+
+ values.put("locationGpsSetting", s.getLocationGpsSetting());
+ values.put("locationGpsLat", s.getLocationGpsLat());
+ values.put("locationGpsLon", s.getLocationGpsLon());
+
+ values.put("locationNetworkSetting", s.getLocationNetworkSetting());
+ values.put("locationNetworkLat", s.getLocationNetworkLat());
+ values.put("locationNetworkLon", s.getLocationNetworkLon());
+
+ values.put("networkInfoSetting", s.getNetworkInfoSetting());
+ values.put("simInfoSetting", s.getSimInfoSetting());
+
+ values.put("simSerialNumberSetting", s.getSimSerialNumberSetting());
+ values.put("simSerialNumber", s.getSimSerialNumber());
+ values.put("subscriberIdSetting", s.getSubscriberIdSetting());
+ values.put("subscriberId", s.getSubscriberId());
+
+ values.put("accountsSetting", s.getAccountsSetting());
+ values.put("accountsAuthTokensSetting", s.getAccountsAuthTokensSetting());
+ values.put("outgoingCallsSetting", s.getOutgoingCallsSetting());
+ values.put("incomingCallsSetting", s.getIncomingCallsSetting());
+
+ values.put("contactsSetting", s.getContactsSetting());
+ values.put("calendarSetting", s.getCalendarSetting());
+ values.put("mmsSetting", s.getMmsSetting());
+ values.put("smsSetting", s.getSmsSetting());
+ values.put("callLogSetting", s.getCallLogSetting());
+ values.put("bookmarksSetting", s.getBookmarksSetting());
+ values.put("systemLogsSetting", s.getSystemLogsSetting());
+ values.put("notificationSetting", s.getNotificationSetting());
+ values.put("intentBootCompletedSetting", s.getIntentBootCompletedSetting());
+// values.put("externalStorageSetting", s.getExternalStorageSetting());
+// values.put("cameraSetting", s.getCameraSetting());
+// values.put("recordAudioSetting", s.getRecordAudioSetting());
+
+ readingThreads++;
+ SQLiteDatabase db = getWritableDatabase();
+ db.beginTransaction(); // make sure this ends up in a consistent state (DB and plain text files)
+ Cursor c = null;
+ try {
+ // save settings to the DB
+// Log.d(TAG, "saveSettings - checking if entry exists already");
+ Integer id = s.get_id();
+ if (id != null) { // existing entry -> update
+// Log.d(TAG, "saveSettings - updating existing entry");
+ if (db.update(TABLE_SETTINGS, values, "_id=?", new String[] { id.toString() }) < 1) {
+ throw new Exception("saveSettings - failed to update database entry");
+ }
+
+ db.delete(TABLE_ALLOWED_CONTACTS, "settings_id=?", new String[] { id.toString() });
+ int[] allowedContacts = s.getAllowedContacts();
+ if (allowedContacts != null) {
+ ContentValues contactsValues = new ContentValues();
+ for (int i = 0; i < allowedContacts.length; i++) {
+ contactsValues.put("settings_id", id);
+ contactsValues.put("contact_id", allowedContacts[i]);
+ if (db.insert(TABLE_ALLOWED_CONTACTS, null, contactsValues) == -1)
+ throw new Exception("saveSettings - failed to update database entry (contacts)");
+ }
+ }
+
+ } else { // new entry -> insert if no duplicates exist
+// Log.d(TAG, "saveSettings - new entry; verifying if duplicates exist");
+ c = db.query(TABLE_SETTINGS, new String[] { "_id" }, "packageName=?",
+ new String[] { s.getPackageName() }, null, null, null);
+
+ if (c != null) {
+ if (c.getCount() == 1) { // exactly one entry
+ // exists -> update
+// Log.d(TAG, "saveSettings - updating existing entry");
+ if (db.update(TABLE_SETTINGS, values, "packageName=?",
+ new String[] { s.getPackageName() }) < 1) {
+ throw new Exception("saveSettings - failed to update database entry");
+ }
+
+ if (c.moveToFirst()) {
+ Integer idAlt = c.getInt(0); // id of the found duplicate entry
+ db.delete(TABLE_ALLOWED_CONTACTS, "settings_id=?", new String[] { idAlt.toString() });
+ int[] allowedContacts = s.getAllowedContacts();
+ if (allowedContacts != null) {
+ ContentValues contactsValues = new ContentValues();
+ for (int i = 0; i < allowedContacts.length; i++) {
+ contactsValues.put("settings_id", idAlt);
+ contactsValues.put("contact_id", allowedContacts[i]);
+ if (db.insert(TABLE_ALLOWED_CONTACTS, null, contactsValues) == -1)
+ throw new Exception("saveSettings - failed to update database entry (contacts)");
+ }
+ }
+ }
+ } else if (c.getCount() == 0) { // no entries -> insert
+// Log.d(TAG, "saveSettings - inserting new entry");
+ long rowId = db.insert(TABLE_SETTINGS, null, values);
+ if (rowId == -1) {
+ throw new Exception("saveSettings - failed to insert new record into DB");
+ }
+
+ db.delete(TABLE_ALLOWED_CONTACTS, "settings_id=?", new String[] { Long.toString(rowId) });
+ int[] allowedContacts = s.getAllowedContacts();
+ if (allowedContacts != null) {
+ ContentValues contactsValues = new ContentValues();
+ for (int i = 0; i < allowedContacts.length; i++) {
+ contactsValues.put("settings_id", rowId);
+ contactsValues.put("contact_id", allowedContacts[i]);
+ if (db.insert(TABLE_ALLOWED_CONTACTS, null, contactsValues) == -1)
+ throw new Exception("saveSettings - failed to update database entry (contacts)");
+ }
+ }
+ } else { // something went totally wrong and there are multiple entries for same identifier
+ result = false;
+ throw new Exception("saveSettings - duplicate entries in the privacy.db");
+ }
+ } else {
+ result = false;
+ // jump to catch block to avoid marking transaction as successful
+ throw new Exception("saveSettings - cursor is null, database access failed");
+ }
+ }
+
+ // save settings to plain text file (for access from core libraries)
+// Log.d(TAG, "saveSettings - saving to plain text file");
+// File settingsUidDir = new File("/data/system/privacy/" + packageName + "/" + uid + "/");
+ File settingsPackageDir = new File("/data/system/privacy/" + packageName + "/");
+ File systemLogsSettingFile = new File("/data/system/privacy/" + packageName + "/" + "/systemLogsSetting");
+ try {
+ // create all parent directories on the file path
+// settingsUidDir.mkdirs();
+ // make the directory readable (requires it to be executable as well)
+// settingsUidDir.setReadable(true, false);
+// settingsUidDir.setExecutable(true, false);
+ // make the parent directory readable (requires it to be executable as well)
+ settingsPackageDir.mkdirs();
+ settingsPackageDir.setReadable(true, false);
+ settingsPackageDir.setExecutable(true, false);
+ // create the setting files and make them readable
+ systemLogsSettingFile.createNewFile();
+ systemLogsSettingFile.setReadable(true, false);
+ // write settings to files
+// Log.d(TAG, "saveSettings - writing to file");
+ OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(systemLogsSettingFile));
+ writer.append(s.getSystemLogsSetting() + "");
+ writer.flush();
+ writer.close();
+ } catch (IOException e) {
+ result = false;
+ // jump to catch block to avoid marking transaction as successful
+ throw new Exception("saveSettings - could not write settings to file", e);
+ }
+ // mark DB transaction successful (commit the changes)
+ db.setTransactionSuccessful();
+// Log.d(TAG, "saveSettings - completing transaction");
+ } catch (Exception e) {
+ result = false;
+// Log.d(TAG, "saveSettings - could not save settings", e);
+ } finally {
+ db.endTransaction();
+ if (c != null) c.close();
+ synchronized (readingThreads) {
+ readingThreads--;
+ // only close DB if no other threads are reading
+ if (readingThreads == 0 && db != null && db.isOpen()) {
+ db.close();
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Deletes a settings entry from the DB
+ * @return true if settings were deleted successfully, false otherwise
+ */
+ public synchronized boolean deleteSettings(String packageName) {
+ boolean result = true;
+
+ SQLiteDatabase db = getWritableDatabase();
+ db.beginTransaction(); // make sure this ends up in a consistent state (DB and plain text files)
+ try {
+// Log.d(TAG, "deleteSettings - deleting database entry for " + packageName + " (" + uid + ")");
+ // try deleting contacts allowed entries; do not fail if deletion not possible
+ Cursor c = db.query(TABLE_SETTINGS, new String[] { "_id" }, "packageName=?",
+ new String[] { packageName }, null, null, null);
+ if (c != null && c.getCount() > 0 && c.moveToFirst()) {
+ int id = c.getInt(0);
+ db.delete(TABLE_ALLOWED_CONTACTS, "settings_id=?", new String[] { Integer.toString(id) });
+ c.close();
+ }
+
+ if (db.delete(TABLE_SETTINGS, "packageName=?", new String[] { packageName }) == 0) {
+ Log.e(TAG, "deleteSettings - database entry for " + packageName + " not found");
+ return false;
+ }
+
+ // delete settings from plain text file (for access from core libraries)
+// File settingsUidDir = new File("/data/system/privacy/" + packageName + "/" + uid + "/");
+ File settingsPackageDir = new File("/data/system/privacy/" + packageName + "/");
+ File systemLogsSettingFile = new File("/data/system/privacy/" + packageName + "/systemLogsSetting");
+ // delete the setting files
+ systemLogsSettingFile.delete();
+ // delete the parent directories
+// settingsUidDir.delete();
+ if (settingsPackageDir.list() == null || settingsPackageDir.list().length == 0) settingsPackageDir.delete();
+ // mark DB transaction successful (commit the changes)
+ db.setTransactionSuccessful();
+ } catch (Exception e) {
+ result = false;
+ Log.e(TAG, "deleteSettings - could not delete settings", e);
+ } finally {
+ db.endTransaction();
+ if (db != null && db.isOpen()) db.close();
+ }
+
+ return result;
+ }
+
+ private Cursor query(SQLiteDatabase db, String table, String[] columns, String selection,
+ String[] selectionArgs, String groupBy, String having, String orderBy, String limit) throws Exception {
+ Cursor c = null;
+ // make sure getting settings does not fail because of IllegalStateException (db already closed)
+ boolean success = false;
+ for (int i = 0; success == false && i < RETRY_QUERY_COUNT; i++) {
+ try {
+ if (c != null) c.close();
+ c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
+ success = true;
+ } catch (IllegalStateException e) {
+ success = false;
+ if (db != null && db.isOpen()) db.close();
+ db = getReadableDatabase();
+ }
+ }
+ if (success == false) throw new Exception("query - failed to execute query on the DB");
+ return c;
+ }
+
+ private Cursor rawQuery(SQLiteDatabase db, String sql) throws Exception {
+ Cursor c = null;
+ // make sure getting settings does not fail because of IllegalStateException (db already closed)
+ boolean success = false;
+ for (int i = 0; success == false && i < RETRY_QUERY_COUNT; i++) {
+ try {
+ if (c != null) c.close();
+ c = db.rawQuery(sql, null);
+ success = true;
+ } catch (IllegalStateException e) {
+ success = false;
+ if (db != null && db.isOpen()) db.close();
+ db = getReadableDatabase();
+ }
+ }
+ if (success == false) throw new Exception("query - failed to execute query on the DB");
+ return c;
+ }
+
+ /**
+ * Removes obsolete entries from the DB and file system. Should not be used in methods, which rely on the DB
+ * being open after this method has finished. It will close the DB if no other threads has increased
+ * the readingThread count.
+ * @return true if purge was successful, false otherwise.
+ */
+ public boolean purgeSettings() {
+ boolean result = true;
+// Log.d(TAG, "purgeSettings - begin purging settings");
+ // get installed apps
+ List<String> apps = new ArrayList<String>();
+ PackageManager pMan = context.getPackageManager();