blob: 697999526c234aef14bbc379f0e7454ab27e2623 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
Svetoslav683914b2015-01-15 14:22:26 -080019import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080020import android.annotation.NonNull;
Christopher Tated5fe1472012-09-10 15:48:38 -070021import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070022import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080023import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070024import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080025import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070026import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070027import android.content.ContentValues;
28import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.Intent;
30import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080031import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070032import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080033import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070035import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080037import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.sqlite.SQLiteDatabase;
39import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080040import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040041import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070043import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080044import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070046import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080047import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070048import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070049import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Looper;
51import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070053import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070054import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070055import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070056import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070057import android.os.UserHandle;
58import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070059import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060import android.provider.Settings;
Jeremy Joslin8bdad342016-12-14 11:46:47 -080061import android.provider.Settings.Global;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010063import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080064import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000065import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070066import android.util.Slog;
67import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070068import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080069import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040070
Svetoslav683914b2015-01-15 14:22:26 -080071import com.android.internal.annotations.GuardedBy;
72import com.android.internal.content.PackageMonitor;
73import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080074import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070075import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080076import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040077
Svetoslav683914b2015-01-15 14:22:26 -080078import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080079import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080080import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080081import java.io.PrintWriter;
Mark Rathjend891f012017-01-19 04:10:37 +000082import java.nio.charset.StandardCharsets;
83import java.security.MessageDigest;
84import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080085import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070086import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080087import java.util.Arrays;
Mark Rathjend891f012017-01-19 04:10:37 +000088import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.util.List;
Andre Lago3fa139c2016-08-04 13:53:44 +010090import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.util.Set;
92import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070093
Svetoslav Ganove080da92016-12-21 17:10:35 -080094import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -080095import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -080096import static android.os.Process.SYSTEM_UID;
97
Svetoslav Ganove080da92016-12-21 17:10:35 -080098
Svetoslav683914b2015-01-15 14:22:26 -080099/**
100 * <p>
101 * This class is a content provider that publishes the system settings.
102 * It can be accessed via the content provider APIs or via custom call
103 * commands. The latter is a bit faster and is the preferred way to access
104 * the platform settings.
105 * </p>
106 * <p>
107 * There are three settings types, global (with signature level protection
108 * and shared across users), secure (with signature permission level
109 * protection and per user), and system (with dangerous permission level
110 * protection and per user). Global settings are stored under the device owner.
111 * Each of these settings is represented by a {@link
112 * com.android.providers.settings.SettingsState} object mapped to an integer
113 * key derived from the setting type in the most significant bits and user
114 * id in the least significant bits. Settings are synchronously loaded on
115 * instantiation of a SettingsState and asynchronously persisted on mutation.
116 * Settings are stored in the user specific system directory.
117 * </p>
118 * <p>
119 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
120 * and get a warning. Targeting higher API version prohibits this as the
121 * system settings are not a place for apps to save their state. When a package
122 * is removed the settings it added are deleted. Apps cannot delete system
123 * settings added by the platform. System settings values are validated to
124 * ensure the clients do not put bad values. Global and secure settings are
125 * changed only by trusted parties, therefore no validation is performed. Also
126 * there is a limit on the amount of app specific settings that can be added
127 * to prevent unlimited growth of the system process memory footprint.
128 * </p>
129 */
130@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700131public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700132 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700134 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800135
136 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700137
Christopher Tate06efb532012-08-24 15:29:27 -0700138 private static final String TABLE_SYSTEM = "system";
139 private static final String TABLE_SECURE = "secure";
140 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800141
142 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 private static final String TABLE_FAVORITES = "favorites";
144 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800145 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
146 private static final String TABLE_BOOKMARKS = "bookmarks";
147 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Svetoslav683914b2015-01-15 14:22:26 -0800149 // The set of removed legacy tables.
150 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700151 static {
Svetoslav683914b2015-01-15 14:22:26 -0800152 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
153 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
154 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
155 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
156 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
157 }
Christopher Tate06efb532012-08-24 15:29:27 -0700158
Svetoslav683914b2015-01-15 14:22:26 -0800159 private static final int MUTATION_OPERATION_INSERT = 1;
160 private static final int MUTATION_OPERATION_DELETE = 2;
161 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800162 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400163
Svetoslav683914b2015-01-15 14:22:26 -0800164 private static final String[] ALL_COLUMNS = new String[] {
165 Settings.NameValueTable._ID,
166 Settings.NameValueTable.NAME,
167 Settings.NameValueTable.VALUE
168 };
169
Svet Ganov53a441c2016-04-19 19:38:00 -0700170 public static final int SETTINGS_TYPE_GLOBAL = 0;
171 public static final int SETTINGS_TYPE_SYSTEM = 1;
172 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000173 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800174
Svet Ganov53a441c2016-04-19 19:38:00 -0700175 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
176 public static final int SETTINGS_TYPE_SHIFT = 28;
177
178 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
179 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700180
Svetoslav683914b2015-01-15 14:22:26 -0800181 // Per user secure settings that moved to the for all users global settings.
182 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
183 static {
184 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700185 }
186
Svetoslav683914b2015-01-15 14:22:26 -0800187 // Per user system settings that moved to the for all users global settings.
188 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
189 static {
190 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700191 }
192
Svetoslav683914b2015-01-15 14:22:26 -0800193 // Per user system settings that moved to the per user secure settings.
194 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
195 static {
196 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700197 }
198
Svetoslav683914b2015-01-15 14:22:26 -0800199 // Per all users global settings that moved to the per user secure settings.
200 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
201 static {
202 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700203 }
204
Svetoslav683914b2015-01-15 14:22:26 -0800205 // Per user secure settings that are cloned for the managed profiles of the user.
206 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
207 static {
208 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700209 }
210
Svetoslav683914b2015-01-15 14:22:26 -0800211 // Per user system settings that are cloned for the managed profiles of the user.
212 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
213 static {
214 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400215 }
216
Andre Lago3fa139c2016-08-04 13:53:44 +0100217 // Per user system settings that are cloned from the profile's parent when a dependency
218 // in {@link Settings.Secure} is set to "1".
219 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
220 static {
221 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
222 }
223
Svetoslav683914b2015-01-15 14:22:26 -0800224 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700225
Svetoslav683914b2015-01-15 14:22:26 -0800226 @GuardedBy("mLock")
227 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700228
Svet Ganova8f90262016-05-10 08:44:48 -0700229 @GuardedBy("mLock")
230 private HandlerThread mHandlerThread;
231
Svetoslav7ec28e82015-05-20 17:01:10 -0700232 // We have to call in the user manager with no lock held,
233 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800234
Svetoslav7ec28e82015-05-20 17:01:10 -0700235 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700236 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700237
Svet Ganov53a441c2016-04-19 19:38:00 -0700238 public static int makeKey(int type, int userId) {
239 return (type << SETTINGS_TYPE_SHIFT) | userId;
240 }
241
242 public static int getTypeFromKey(int key) {
243 return key >>> SETTINGS_TYPE_SHIFT;
244 }
245
246 public static int getUserIdFromKey(int key) {
247 return key & ~SETTINGS_TYPE_MASK;
248 }
249
250 public static String settingTypeToString(int type) {
251 switch (type) {
252 case SETTINGS_TYPE_GLOBAL: {
253 return "SETTINGS_GLOBAL";
254 }
255 case SETTINGS_TYPE_SECURE: {
256 return "SETTINGS_SECURE";
257 }
258 case SETTINGS_TYPE_SYSTEM: {
259 return "SETTINGS_SYSTEM";
260 }
Mark Rathjend891f012017-01-19 04:10:37 +0000261 case SETTINGS_TYPE_SSAID: {
262 return "SETTINGS_SSAID";
263 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700264 default: {
265 return "UNKNOWN";
266 }
267 }
268 }
269
270 public static String keyToString(int key) {
271 return "Key[user=" + getUserIdFromKey(key) + ";type="
272 + settingTypeToString(getTypeFromKey(key)) + "]";
273 }
274
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700275 @Override
276 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800277 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800278 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700279 mUserManager = UserManager.get(getContext());
280 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700281 mHandlerThread = new HandlerThread(LOG_TAG,
282 Process.THREAD_PRIORITY_BACKGROUND);
283 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800284 mSettingsRegistry = new SettingsRegistry();
285 }
286 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700287 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700288 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700289 return true;
290 }
291
Svetoslav683914b2015-01-15 14:22:26 -0800292 @Override
293 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700294 final int requestingUserId = getRequestingUserId(args);
295 switch (method) {
296 case Settings.CALL_METHOD_GET_GLOBAL: {
297 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700298 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800299 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700300
301 case Settings.CALL_METHOD_GET_SECURE: {
302 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700303 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700304 }
305
306 case Settings.CALL_METHOD_GET_SYSTEM: {
307 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700308 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700309 }
310
311 case Settings.CALL_METHOD_PUT_GLOBAL: {
312 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800313 String tag = getSettingTag(args);
314 final boolean makeDefault = getSettingMakeDefault(args);
315 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700316 break;
317 }
318
319 case Settings.CALL_METHOD_PUT_SECURE: {
320 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800321 String tag = getSettingTag(args);
322 final boolean makeDefault = getSettingMakeDefault(args);
323 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700324 break;
325 }
326
327 case Settings.CALL_METHOD_PUT_SYSTEM: {
328 String value = getSettingValue(args);
329 insertSystemSetting(name, value, requestingUserId);
330 break;
331 }
332
Svetoslav Ganove080da92016-12-21 17:10:35 -0800333 case Settings.CALL_METHOD_RESET_GLOBAL: {
334 final int mode = getResetModeEnforcingPermission(args);
335 String tag = getSettingTag(args);
336 resetGlobalSetting(requestingUserId, mode, tag);
337 break;
338 }
339
340 case Settings.CALL_METHOD_RESET_SECURE: {
341 final int mode = getResetModeEnforcingPermission(args);
342 String tag = getSettingTag(args);
343 resetSecureSetting(requestingUserId, mode, tag);
344 break;
345 }
346
Svetoslav7ec28e82015-05-20 17:01:10 -0700347 default: {
348 Slog.w(LOG_TAG, "call() with invalid method: " + method);
349 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700350 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700351
Christopher Tate06efb532012-08-24 15:29:27 -0700352 return null;
353 }
354
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800355 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800356 public String getType(Uri uri) {
357 Arguments args = new Arguments(uri, null, null, true);
358 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 return "vnd.android.cursor.dir/" + args.table;
360 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700361 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700362 }
363 }
364
365 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800366 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
367 String order) {
368 if (DEBUG) {
369 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370 }
371
Svetoslav683914b2015-01-15 14:22:26 -0800372 Arguments args = new Arguments(uri, where, whereArgs, true);
373 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374
Svetoslav683914b2015-01-15 14:22:26 -0800375 // If a legacy table that is gone, done.
376 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
377 return new MatrixCursor(normalizedProjection, 0);
378 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700379
Svetoslav7ec28e82015-05-20 17:01:10 -0700380 switch (args.table) {
381 case TABLE_GLOBAL: {
382 if (args.name != null) {
383 Setting setting = getGlobalSetting(args.name);
384 return packageSettingForQuery(setting, normalizedProjection);
385 } else {
386 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700387 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700388 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700389
Svetoslav7ec28e82015-05-20 17:01:10 -0700390 case TABLE_SECURE: {
391 final int userId = UserHandle.getCallingUserId();
392 if (args.name != null) {
393 Setting setting = getSecureSetting(args.name, userId);
394 return packageSettingForQuery(setting, normalizedProjection);
395 } else {
396 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800397 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700398 }
Svetoslav683914b2015-01-15 14:22:26 -0800399
Svetoslav7ec28e82015-05-20 17:01:10 -0700400 case TABLE_SYSTEM: {
401 final int userId = UserHandle.getCallingUserId();
402 if (args.name != null) {
403 Setting setting = getSystemSetting(args.name, userId);
404 return packageSettingForQuery(setting, normalizedProjection);
405 } else {
406 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800407 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700408 }
Svetoslav683914b2015-01-15 14:22:26 -0800409
Svetoslav7ec28e82015-05-20 17:01:10 -0700410 default: {
411 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700412 }
413 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700414 }
415
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700416 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800417 public Uri insert(Uri uri, ContentValues values) {
418 if (DEBUG) {
419 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700420 }
421
Svetoslav683914b2015-01-15 14:22:26 -0800422 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700423
Svetoslav683914b2015-01-15 14:22:26 -0800424 // If a legacy table that is gone, done.
425 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 return null;
427 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700428
Svetoslav683914b2015-01-15 14:22:26 -0800429 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700430 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800431 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700432 }
433
Svetoslav683914b2015-01-15 14:22:26 -0800434 String value = values.getAsString(Settings.Secure.VALUE);
435
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 switch (table) {
437 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800438 if (insertGlobalSetting(name, value, null, false,
439 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700440 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700441 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700442 } break;
443
444 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800445 if (insertSecureSetting(name, value, null, false,
446 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700447 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
448 }
449 } break;
450
451 case TABLE_SYSTEM: {
452 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
453 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
454 }
455 } break;
456
457 default: {
458 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700459 }
460 }
461
Svetoslav683914b2015-01-15 14:22:26 -0800462 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700463 }
464
465 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800466 public int bulkInsert(Uri uri, ContentValues[] allValues) {
467 if (DEBUG) {
468 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700470
Svetoslav683914b2015-01-15 14:22:26 -0800471 int insertionCount = 0;
472 final int valuesCount = allValues.length;
473 for (int i = 0; i < valuesCount; i++) {
474 ContentValues values = allValues[i];
475 if (insert(uri, values) != null) {
476 insertionCount++;
477 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700478 }
Svetoslav683914b2015-01-15 14:22:26 -0800479
480 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700481 }
482
483 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800484 public int delete(Uri uri, String where, String[] whereArgs) {
485 if (DEBUG) {
486 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700488
Svetoslav683914b2015-01-15 14:22:26 -0800489 Arguments args = new Arguments(uri, where, whereArgs, false);
490
491 // If a legacy table that is gone, done.
492 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
493 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700494 }
Svetoslav683914b2015-01-15 14:22:26 -0800495
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700496 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800497 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700498 }
Svetoslav683914b2015-01-15 14:22:26 -0800499
Svetoslav7ec28e82015-05-20 17:01:10 -0700500 switch (args.table) {
501 case TABLE_GLOBAL: {
502 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700503 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700504 }
Svetoslav683914b2015-01-15 14:22:26 -0800505
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 case TABLE_SECURE: {
507 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700508 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700509 }
Svetoslav683914b2015-01-15 14:22:26 -0800510
Svetoslav7ec28e82015-05-20 17:01:10 -0700511 case TABLE_SYSTEM: {
512 final int userId = UserHandle.getCallingUserId();
513 return deleteSystemSetting(args.name, userId) ? 1 : 0;
514 }
515
516 default: {
517 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800518 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700519 }
Svetoslav683914b2015-01-15 14:22:26 -0800520 }
521
522 @Override
523 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
524 if (DEBUG) {
525 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700526 }
Svetoslav683914b2015-01-15 14:22:26 -0800527
528 Arguments args = new Arguments(uri, where, whereArgs, false);
529
530 // If a legacy table that is gone, done.
531 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
532 return 0;
533 }
534
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700535 String name = values.getAsString(Settings.Secure.NAME);
536 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800537 return 0;
538 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700539 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800540
Svetoslav7ec28e82015-05-20 17:01:10 -0700541 switch (args.table) {
542 case TABLE_GLOBAL: {
543 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800544 return updateGlobalSetting(args.name, value, null, false,
545 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700546 }
Svetoslav683914b2015-01-15 14:22:26 -0800547
Svetoslav7ec28e82015-05-20 17:01:10 -0700548 case TABLE_SECURE: {
549 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800550 return updateSecureSetting(args.name, value, null, false,
551 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 }
Svetoslav683914b2015-01-15 14:22:26 -0800553
Svetoslav7ec28e82015-05-20 17:01:10 -0700554 case TABLE_SYSTEM: {
555 final int userId = UserHandle.getCallingUserId();
556 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
557 }
Svetoslav683914b2015-01-15 14:22:26 -0800558
Svetoslav7ec28e82015-05-20 17:01:10 -0700559 default: {
560 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800561 }
562 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 }
564
565 @Override
566 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100567 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
568 if (userId != UserHandle.getCallingUserId()) {
569 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
570 "Access files from the settings of another user");
571 }
572 uri = ContentProvider.getUriWithoutUserId(uri);
573
Andre Lago3fa139c2016-08-04 13:53:44 +0100574 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700575 final String cacheName;
576 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100577 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700578 cacheName = Settings.System.RINGTONE_CACHE;
579 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100580 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700581 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
582 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100583 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700584 cacheName = Settings.System.ALARM_ALERT_CACHE;
585 } else {
586 throw new FileNotFoundException("Direct file access no longer supported; "
587 + "ringtone playback is available through android.media.Ringtone");
588 }
589
Andre Lago3fa139c2016-08-04 13:53:44 +0100590 int actualCacheOwner;
591 // Redirect cache to parent if ringtone setting is owned by profile parent
592 synchronized (mLock) {
593 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
594 cacheRingtoneSetting);
595 }
596 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700597 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
598 }
599
600 private File getRingtoneCacheDir(int userId) {
601 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
602 cacheDir.mkdir();
603 SELinux.restorecon(cacheDir);
604 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700605 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800606
Eugene Suslad72c3972016-12-27 15:49:30 -0800607 /**
608 * Dump all settings as a proto buf.
609 *
610 * @param fd The file to dump to
611 */
612 void dumpProto(@NonNull FileDescriptor fd) {
613 ProtoOutputStream proto = new ProtoOutputStream(fd);
614
615 synchronized (mLock) {
616 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
617
618 }
619
620 proto.flush();
621 }
622
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700623 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800624 synchronized (mLock) {
625 final long identity = Binder.clearCallingIdentity();
626 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700627 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800628 final int userCount = users.size();
629 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700630 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800631 }
632 } finally {
633 Binder.restoreCallingIdentity(identity);
634 }
635 }
636 }
637
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700638 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700639 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800640 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700641 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
642 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700643 if (globalSettings != null) {
644 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800645 pw.println();
646 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700647 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800648 }
649
650 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700651 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
652 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700653 if (secureSettings != null) {
654 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800655 pw.println();
656 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700657 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700658
Svetoslavb505ccc2015-02-17 12:41:04 -0800659 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700660 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
661 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700662 if (systemSettings != null) {
663 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800664 pw.println();
665 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700666 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800667 }
668
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700669 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
670 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800671
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700672 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800673
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700674 for (int i = 0; i < nameCount; i++) {
675 String name = names.get(i);
676 Setting setting = settingsState.getSettingLocked(name);
677 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
678 pw.print(" name:"); pw.print(toDumpString(name));
679 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800680 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700681 }
682 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800683 if (setting.getDefaultValue() != null) {
684 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800685 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800686 }
687 if (setting.getTag() != null) {
688 pw.print(" tag:"); pw.print(setting.getTag());
689 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800690 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700691 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800692 }
693
Svetoslav7e0683b2015-08-03 16:02:52 -0700694 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700695 if (s != null) {
696 return s;
697 }
698 return "{null}";
699 }
700
Svetoslav683914b2015-01-15 14:22:26 -0800701 private void registerBroadcastReceivers() {
702 IntentFilter userFilter = new IntentFilter();
703 userFilter.addAction(Intent.ACTION_USER_REMOVED);
704 userFilter.addAction(Intent.ACTION_USER_STOPPED);
705
706 getContext().registerReceiver(new BroadcastReceiver() {
707 @Override
708 public void onReceive(Context context, Intent intent) {
709 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700710 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800711
712 switch (intent.getAction()) {
713 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700714 synchronized (mLock) {
715 mSettingsRegistry.removeUserStateLocked(userId, true);
716 }
Svetoslav683914b2015-01-15 14:22:26 -0800717 } break;
718
719 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700720 synchronized (mLock) {
721 mSettingsRegistry.removeUserStateLocked(userId, false);
722 }
Svetoslav683914b2015-01-15 14:22:26 -0800723 } break;
724 }
725 }
726 }, userFilter);
727
728 PackageMonitor monitor = new PackageMonitor() {
729 @Override
730 public void onPackageRemoved(String packageName, int uid) {
731 synchronized (mLock) {
732 mSettingsRegistry.onPackageRemovedLocked(packageName,
733 UserHandle.getUserId(uid));
734 }
735 }
Mark Rathjend891f012017-01-19 04:10:37 +0000736
737 @Override
738 public void onUidRemoved(int uid) {
739 synchronized (mLock) {
740 mSettingsRegistry.onUidRemovedLocked(uid);
741 }
742 }
Svetoslav683914b2015-01-15 14:22:26 -0800743 };
744
745 // package changes
746 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
747 UserHandle.ALL, true);
748 }
749
Svet Ganov53a441c2016-04-19 19:38:00 -0700750 private void startWatchingUserRestrictionChanges() {
751 // TODO: The current design of settings looking different based on user restrictions
752 // should be reworked to keep them separate and system code should check the setting
753 // first followed by checking the user restriction before performing an operation.
754 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
755 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
756 Bundle prevRestrictions) -> {
757 // We are changing the settings affected by restrictions to their current
758 // value with a forced update to ensure that all cross profile dependencies
759 // are taken into account. Also make sure the settings update to.. the same
760 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800761 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
762 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700763 final long identity = Binder.clearCallingIdentity();
764 try {
765 synchronized (mLock) {
766 Setting setting = getSecureSetting(
767 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
768 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800769 setting != null ? setting.getValue() : null, null,
770 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700771 }
772 } finally {
773 Binder.restoreCallingIdentity(identity);
774 }
775 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800776 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
777 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700778 final long identity = Binder.clearCallingIdentity();
779 try {
780 synchronized (mLock) {
781 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800782 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700783 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800784 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700785 }
786 } finally {
787 Binder.restoreCallingIdentity(identity);
788 }
789 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800790 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
791 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700792 final long identity = Binder.clearCallingIdentity();
793 try {
794 synchronized (mLock) {
795 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800796 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700797 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800798 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700799 }
800 } finally {
801 Binder.restoreCallingIdentity(identity);
802 }
803 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800804 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
805 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700806 final long identity = Binder.clearCallingIdentity();
807 try {
808 synchronized (mLock) {
809 Setting enable = getGlobalSetting(
810 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800811 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700812 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800813 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700814 Setting include = getGlobalSetting(
815 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800816 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800818 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700819 }
820 } finally {
821 Binder.restoreCallingIdentity(identity);
822 }
823 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800824 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
825 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700826 final long identity = Binder.clearCallingIdentity();
827 try {
828 synchronized (mLock) {
829 Setting setting = getGlobalSetting(
830 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800831 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700832 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800833 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700834 }
835 } finally {
836 Binder.restoreCallingIdentity(identity);
837 }
838 }
839 });
840 }
841
Svetoslav7ec28e82015-05-20 17:01:10 -0700842 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800843 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700844 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800845 }
846
Svetoslav7ec28e82015-05-20 17:01:10 -0700847 synchronized (mLock) {
848 // Get the settings.
849 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700850 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800851
Chad Brubaker97bccee2017-01-05 15:51:41 -0800852 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
853 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800854
Svetoslav7ec28e82015-05-20 17:01:10 -0700855 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800856
Svetoslav7ec28e82015-05-20 17:01:10 -0700857 String[] normalizedProjection = normalizeProjection(projection);
858 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800859
Svetoslav7ec28e82015-05-20 17:01:10 -0700860 // Anyone can get the global settings, so no security checks.
861 for (int i = 0; i < nameCount; i++) {
862 String name = names.get(i);
863 Setting setting = settingsState.getSettingLocked(name);
864 appendSettingToCursor(result, setting);
865 }
866
867 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800868 }
Svetoslav683914b2015-01-15 14:22:26 -0800869 }
870
Svetoslav7ec28e82015-05-20 17:01:10 -0700871 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800872 if (DEBUG) {
873 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
874 }
875
Chad Brubaker97bccee2017-01-05 15:51:41 -0800876 // Ensure the caller can access the setting.
877 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
878
Svetoslav683914b2015-01-15 14:22:26 -0800879 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700881 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700882 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800883 }
Svetoslav683914b2015-01-15 14:22:26 -0800884 }
885
Svetoslav Ganove080da92016-12-21 17:10:35 -0800886 private boolean updateGlobalSetting(String name, String value, String tag,
887 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800888 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800889 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
890 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
891 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800892 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800893 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
894 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800895 }
896
Svetoslav Ganove080da92016-12-21 17:10:35 -0800897 private boolean insertGlobalSetting(String name, String value, String tag,
898 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700899 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800900 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
901 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
902 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700903 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800904 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
905 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700906 }
907
Svet Ganov53a441c2016-04-19 19:38:00 -0700908 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800909 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800910 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
911 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800912 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800913 return mutateGlobalSetting(name, null, null, false, requestingUserId,
914 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800915 }
916
Svetoslav Ganove080da92016-12-21 17:10:35 -0800917 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
918 if (DEBUG) {
919 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
920 + mode + ", " + tag + ")");
921 }
922 mutateGlobalSetting(null, null, tag, false, requestingUserId,
923 MUTATION_OPERATION_RESET, false, mode);
924 }
925
926 private boolean mutateGlobalSetting(String name, String value, String tag,
927 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
928 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800929 // Make sure the caller can change the settings - treated as secure.
930 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
931
Svetoslav683914b2015-01-15 14:22:26 -0800932 // Resolve the userId on whose behalf the call is made.
933 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
934
Makoto Onuki28da2e32015-11-20 11:30:44 -0800935 // If this is a setting that is currently restricted for this user, do not allow
936 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800937 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100938 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800939 return false;
940 }
941
942 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 synchronized (mLock) {
944 switch (operation) {
945 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800946 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
947 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
948 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700949 }
Svetoslav683914b2015-01-15 14:22:26 -0800950
Svetoslav7ec28e82015-05-20 17:01:10 -0700951 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700952 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
953 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700954 }
Svetoslav683914b2015-01-15 14:22:26 -0800955
Svetoslav7ec28e82015-05-20 17:01:10 -0700956 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800957 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
958 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
959 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800961
962 case MUTATION_OPERATION_RESET: {
963 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
964 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
965 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800966 }
967 }
968
969 return false;
970 }
971
Svetoslav7ec28e82015-05-20 17:01:10 -0700972 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800973 if (DEBUG) {
974 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
975 }
976
977 // Resolve the userId on whose behalf the call is made.
978 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
979
Svetoslav7ec28e82015-05-20 17:01:10 -0700980 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800981 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800982
Svetoslav7ec28e82015-05-20 17:01:10 -0700983 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800984
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 String[] normalizedProjection = normalizeProjection(projection);
986 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800987
Svetoslav7ec28e82015-05-20 17:01:10 -0700988 for (int i = 0; i < nameCount; i++) {
989 String name = names.get(i);
990 // Determine the owning user as some profile settings are cloned from the parent.
991 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
992 name);
Svetoslav683914b2015-01-15 14:22:26 -0800993
Svetoslav7ec28e82015-05-20 17:01:10 -0700994 // Special case for location (sigh).
995 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700996 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 }
Svetoslav683914b2015-01-15 14:22:26 -0800998
Mark Rathjend891f012017-01-19 04:10:37 +0000999 // As of Android O (API 24), the SSAID is read from an app-specific entry in table
1000 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1001 final Setting setting;
1002 if (isNewSsaidSetting(name)) {
1003 setting = getSsaidSettingLocked(owningUserId);
1004 } else {
1005 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1006 name);
1007 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001008 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001009 }
1010
Svetoslav7ec28e82015-05-20 17:01:10 -07001011 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001012 }
Svetoslav683914b2015-01-15 14:22:26 -08001013 }
1014
Svetoslav7ec28e82015-05-20 17:01:10 -07001015 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001016 if (DEBUG) {
1017 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1018 }
1019
1020 // Resolve the userId on whose behalf the call is made.
1021 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1022
Chad Brubaker97bccee2017-01-05 15:51:41 -08001023 // Ensure the caller can access the setting.
1024 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, callingUserId);
1025
Svetoslav683914b2015-01-15 14:22:26 -08001026 // Determine the owning user as some profile settings are cloned from the parent.
1027 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1028
1029 // Special case for location (sigh).
1030 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001031 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1032 owningUserId);
1033 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001034 }
1035
1036 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001037 synchronized (mLock) {
Mark Rathjend891f012017-01-19 04:10:37 +00001038 // As of Android O (API 24), the SSAID is read from an app-specific entry in table
1039 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1040 if (isNewSsaidSetting(name)) {
1041 return getSsaidSettingLocked(owningUserId);
1042 }
1043
Svet Ganov53a441c2016-04-19 19:38:00 -07001044 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001045 owningUserId, name);
1046 }
Svetoslav683914b2015-01-15 14:22:26 -08001047 }
1048
Mark Rathjend891f012017-01-19 04:10:37 +00001049 private boolean isNewSsaidSetting(String name) {
1050 return Settings.Secure.ANDROID_ID.equals(name)
1051 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1052 }
1053
1054 private Setting getSsaidSettingLocked(int owningUserId) {
1055 // Get uid of caller (key) used to store ssaid value
1056 String name = Integer.toString(
1057 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1058
1059 if (DEBUG) {
1060 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1061 }
1062
1063 // Retrieve the ssaid from the table if present.
1064 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1065 name);
1066
1067 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001068 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001069 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1070 }
1071
1072 return ssaid;
1073 }
1074
Svetoslav Ganove080da92016-12-21 17:10:35 -08001075 private boolean insertSecureSetting(String name, String value, String tag,
1076 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001077 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001078 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001079 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1080 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001081 }
1082
Svetoslav Ganove080da92016-12-21 17:10:35 -08001083 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1084 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001085 }
1086
Svet Ganov53a441c2016-04-19 19:38:00 -07001087 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001088 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001089 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1090 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001091 }
1092
Svetoslav Ganove080da92016-12-21 17:10:35 -08001093 return mutateSecureSetting(name, null, null, false, requestingUserId,
1094 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001095 }
1096
Svetoslav Ganove080da92016-12-21 17:10:35 -08001097 private boolean updateSecureSetting(String name, String value, String tag,
1098 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001099 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001100 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001101 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1102 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001103 }
1104
Svetoslav Ganove080da92016-12-21 17:10:35 -08001105 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1106 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001107 }
1108
Svetoslav Ganove080da92016-12-21 17:10:35 -08001109 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1110 if (DEBUG) {
1111 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1112 + mode + ", " + tag + ")");
1113 }
1114
1115 mutateSecureSetting(null, null, tag, false, requestingUserId,
1116 MUTATION_OPERATION_RESET, false, mode);
1117 }
1118
1119 private boolean mutateSecureSetting(String name, String value, String tag,
1120 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1121 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001122 // Make sure the caller can change the settings.
1123 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1124
Svetoslav683914b2015-01-15 14:22:26 -08001125 // Resolve the userId on whose behalf the call is made.
1126 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1127
Makoto Onuki28da2e32015-11-20 11:30:44 -08001128 // If this is a setting that is currently restricted for this user, do not allow
1129 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001130 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001131 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001132 return false;
1133 }
1134
1135 // Determine the owning user as some profile settings are cloned from the parent.
1136 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1137
1138 // Only the owning user can change the setting.
1139 if (owningUserId != callingUserId) {
1140 return false;
1141 }
1142
1143 // Special cases for location providers (sigh).
1144 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001145 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1146 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001147 }
1148
1149 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001150 synchronized (mLock) {
1151 switch (operation) {
1152 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001153 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001154 owningUserId, name, value, tag, makeDefault,
1155 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001156 }
Svetoslav683914b2015-01-15 14:22:26 -08001157
Svetoslav7ec28e82015-05-20 17:01:10 -07001158 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001159 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
1160 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001161 }
Svetoslav683914b2015-01-15 14:22:26 -08001162
Svetoslav7ec28e82015-05-20 17:01:10 -07001163 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001164 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001165 owningUserId, name, value, tag, makeDefault,
1166 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001167 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001168
1169 case MUTATION_OPERATION_RESET: {
1170 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1171 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1172 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001173 }
1174 }
1175
1176 return false;
1177 }
1178
Svetoslav7ec28e82015-05-20 17:01:10 -07001179 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001180 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001181 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001182 }
1183
1184 // Resolve the userId on whose behalf the call is made.
1185 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1186
Svetoslav7ec28e82015-05-20 17:01:10 -07001187 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001188 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001189
Svetoslav7ec28e82015-05-20 17:01:10 -07001190 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001191
Svetoslav7ec28e82015-05-20 17:01:10 -07001192 String[] normalizedProjection = normalizeProjection(projection);
1193 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001194
Svetoslav7ec28e82015-05-20 17:01:10 -07001195 for (int i = 0; i < nameCount; i++) {
1196 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001197
Svetoslav7ec28e82015-05-20 17:01:10 -07001198 // Determine the owning user as some profile settings are cloned from the parent.
1199 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1200 name);
Svetoslav683914b2015-01-15 14:22:26 -08001201
Svetoslav7ec28e82015-05-20 17:01:10 -07001202 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001203 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001204 appendSettingToCursor(result, setting);
1205 }
1206
1207 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001208 }
Svetoslav683914b2015-01-15 14:22:26 -08001209 }
1210
Svetoslav7ec28e82015-05-20 17:01:10 -07001211 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001212 if (DEBUG) {
1213 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1214 }
1215
1216 // Resolve the userId on whose behalf the call is made.
1217 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1218
Chad Brubaker97bccee2017-01-05 15:51:41 -08001219 // Ensure the caller can access the setting.
1220 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, callingUserId);
1221
Svetoslav683914b2015-01-15 14:22:26 -08001222 // Determine the owning user as some profile settings are cloned from the parent.
1223 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1224
1225 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001226 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001227 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001228 }
Svetoslav683914b2015-01-15 14:22:26 -08001229 }
1230
Svetoslav7ec28e82015-05-20 17:01:10 -07001231 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001232 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001233 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001234 + requestingUserId + ")");
1235 }
1236
Svetoslav7ec28e82015-05-20 17:01:10 -07001237 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001238 }
1239
Svetoslav7ec28e82015-05-20 17:01:10 -07001240 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001241 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001242 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001243 }
1244
Svetoslav7ec28e82015-05-20 17:01:10 -07001245 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001246 }
1247
Svetoslav7ec28e82015-05-20 17:01:10 -07001248 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001249 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001250 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001251 + requestingUserId + ")");
1252 }
1253
Svetoslav7ec28e82015-05-20 17:01:10 -07001254 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001255 }
1256
Svetoslav7ec28e82015-05-20 17:01:10 -07001257 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001258 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001259 if (!hasWriteSecureSettingsPermission()) {
1260 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1261 // operation is allowed for the calling package through appops.
1262 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1263 Binder.getCallingUid(), getCallingPackage(), true)) {
1264 return false;
1265 }
Svetoslav683914b2015-01-15 14:22:26 -08001266 }
1267
Svetoslav683914b2015-01-15 14:22:26 -08001268 // Resolve the userId on whose behalf the call is made.
1269 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1270
Svetoslavd8d25e02015-11-20 13:09:26 -08001271 // Enforce what the calling package can mutate the system settings.
1272 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1273
Svetoslav683914b2015-01-15 14:22:26 -08001274 // Determine the owning user as some profile settings are cloned from the parent.
1275 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1276
1277 // Only the owning user id can change the setting.
1278 if (owningUserId != callingUserId) {
1279 return false;
1280 }
1281
Jeff Sharkey413573a2016-02-22 17:52:45 -07001282 // Invalidate any relevant cache files
1283 String cacheName = null;
1284 if (Settings.System.RINGTONE.equals(name)) {
1285 cacheName = Settings.System.RINGTONE_CACHE;
1286 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1287 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1288 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1289 cacheName = Settings.System.ALARM_ALERT_CACHE;
1290 }
1291 if (cacheName != null) {
1292 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001293 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001294 cacheFile.delete();
1295 }
1296
Svetoslav683914b2015-01-15 14:22:26 -08001297 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001298 synchronized (mLock) {
1299 switch (operation) {
1300 case MUTATION_OPERATION_INSERT: {
1301 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001302 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001303 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001304 }
1305
1306 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001307 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1308 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001309 }
1310
1311 case MUTATION_OPERATION_UPDATE: {
1312 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001313 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001314 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001315 }
Svetoslav683914b2015-01-15 14:22:26 -08001316 }
1317
Svetoslav7ec28e82015-05-20 17:01:10 -07001318 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001319 }
Svetoslav683914b2015-01-15 14:22:26 -08001320 }
1321
Billy Lau6ad2d662015-07-18 00:26:58 +01001322 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001323 // Write secure settings is a more protected permission. If caller has it we are good.
1324 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1325 == PackageManager.PERMISSION_GRANTED) {
1326 return true;
1327 }
1328
Svetoslavf41334b2015-06-23 12:06:03 -07001329 return false;
1330 }
1331
Svetoslav683914b2015-01-15 14:22:26 -08001332 private void validateSystemSettingValue(String name, String value) {
1333 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1334 if (validator != null && !validator.validate(value)) {
1335 throw new IllegalArgumentException("Invalid value: " + value
1336 + " for setting: " + name);
1337 }
1338 }
1339
1340 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1341 int owningUserId) {
1342 // Optimization - location providers are restricted only for managed profiles.
1343 if (callingUserId == owningUserId) {
1344 return false;
1345 }
1346 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1347 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1348 new UserHandle(callingUserId))) {
1349 return true;
1350 }
1351 return false;
1352 }
1353
Makoto Onuki28da2e32015-11-20 11:30:44 -08001354 /**
1355 * Checks whether changing a setting to a value is prohibited by the corresponding user
1356 * restriction.
1357 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001358 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1359 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001360 *
1361 * @return true if the change is prohibited, false if the change is allowed.
1362 */
1363 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001364 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001365 String restriction;
1366 switch (setting) {
1367 case Settings.Secure.LOCATION_MODE:
1368 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1369 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1370 // here normally, but we still protect it here from a direct provider write.
1371 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1372 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1373 break;
1374
1375 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1376 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1377 // a provider, which should be allowed even if the user restriction is set.
1378 if (value != null && value.startsWith("-")) return false;
1379 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1380 break;
1381
1382 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1383 if ("0".equals(value)) return false;
1384 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1385 break;
1386
1387 case Settings.Global.ADB_ENABLED:
1388 if ("0".equals(value)) return false;
1389 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1390 break;
1391
1392 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1393 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1394 if ("1".equals(value)) return false;
1395 restriction = UserManager.ENSURE_VERIFY_APPS;
1396 break;
1397
1398 case Settings.Global.PREFERRED_NETWORK_MODE:
1399 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1400 break;
1401
Victor Chang9c7b7062016-07-12 23:47:29 +01001402 case Settings.Secure.ALWAYS_ON_VPN_APP:
1403 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1404 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001405 final int appId = UserHandle.getAppId(callingUid);
1406 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001407 return false;
1408 }
1409 restriction = UserManager.DISALLOW_CONFIG_VPN;
1410 break;
1411
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001412 case Settings.Global.SAFE_BOOT_DISALLOWED:
1413 if ("1".equals(value)) return false;
1414 restriction = UserManager.DISALLOW_SAFE_BOOT;
1415 break;
1416
Makoto Onuki28da2e32015-11-20 11:30:44 -08001417 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001418 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001419 if ("0".equals(value)) return false;
1420 restriction = UserManager.DISALLOW_DATA_ROAMING;
1421 break;
1422 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001423 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001424 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001425
1426 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001427 }
1428
1429 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1430 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1431 }
1432
1433 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001434 final int parentId;
1435 // Resolves dependency if setting has a dependency and the calling user has a parent
1436 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1437 && (parentId = getGroupParentLocked(userId)) != userId) {
1438 // The setting has a dependency and the profile has a parent
1439 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001440 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1441 final long token = Binder.clearCallingIdentity();
1442 try {
1443 Setting settingObj = getSecureSetting(dependency, userId);
1444 if (settingObj != null && settingObj.getValue().equals("1")) {
1445 return parentId;
1446 }
1447 } finally {
1448 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001449 }
1450 }
Svetoslav683914b2015-01-15 14:22:26 -08001451 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1452 }
1453
1454 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1455 final int parentId = getGroupParentLocked(userId);
1456 if (parentId != userId && keys.contains(name)) {
1457 return parentId;
1458 }
1459 return userId;
1460 }
1461
Svetoslavf41334b2015-06-23 12:06:03 -07001462 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001463 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001464 // System/root/shell can mutate whatever secure settings they want.
1465 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001466 final int appId = UserHandle.getAppId(callingUid);
1467 if (appId == android.os.Process.SYSTEM_UID
1468 || appId == Process.SHELL_UID
1469 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001470 return;
1471 }
1472
1473 switch (operation) {
1474 case MUTATION_OPERATION_INSERT:
1475 // Insert updates.
1476 case MUTATION_OPERATION_UPDATE: {
1477 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1478 return;
1479 }
1480
1481 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001482 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001483
1484 // Privileged apps can do whatever they want.
1485 if ((packageInfo.applicationInfo.privateFlags
1486 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1487 return;
1488 }
1489
1490 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1491 packageInfo.applicationInfo.targetSdkVersion, name);
1492 } break;
1493
1494 case MUTATION_OPERATION_DELETE: {
1495 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1496 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1497 throw new IllegalArgumentException("You cannot delete system defined"
1498 + " secure settings.");
1499 }
1500
1501 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001502 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001503
1504 // Privileged apps can do whatever they want.
1505 if ((packageInfo.applicationInfo.privateFlags &
1506 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1507 return;
1508 }
1509
1510 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1511 packageInfo.applicationInfo.targetSdkVersion, name);
1512 } break;
1513 }
1514 }
1515
Chad Brubaker97bccee2017-01-05 15:51:41 -08001516 private Set<String> getEphemeralAccessibleSettings(int settingsType) {
1517 switch (settingsType) {
1518 case SETTINGS_TYPE_GLOBAL:
1519 return Settings.Global.EPHEMERAL_SETTINGS;
1520 case SETTINGS_TYPE_SECURE:
1521 return Settings.Secure.EPHEMERAL_SETTINGS;
1522 case SETTINGS_TYPE_SYSTEM:
1523 return Settings.System.EPHEMERAL_SETTINGS;
1524 default:
1525 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1526 }
1527 }
1528
1529 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
1530 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
1531 if (ai.isEphemeralApp()) {
1532 return new ArrayList<String>(getEphemeralAccessibleSettings(settingsType));
1533 } else {
1534 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1535 }
1536 }
1537
1538 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1539 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1540 return;
1541 }
1542 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
1543 if (!ai.isEphemeralApp()) {
1544 return;
1545 }
1546 if (!getEphemeralAccessibleSettings(settingsType).contains(settingName)) {
1547 throw new SecurityException("Setting " + settingName + " is not accessible from"
1548 + " ephemeral package " + getCallingPackage());
1549 }
1550 }
1551
1552 private ApplicationInfo getCallingApplicationInfoOrThrow(int userId) {
1553 ApplicationInfo ai = null;
1554 try {
1555 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0 , userId);
1556 } catch (RemoteException ignored) {
1557 }
1558 if (ai == null) {
1559 throw new IllegalStateException("Failed to lookup info for package "
1560 + getCallingPackage());
1561 }
1562 return ai;
1563 }
1564
Xiaohui Chen43765b72015-08-31 10:57:33 -07001565 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001566 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001567 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1568 getCallingPackage(), 0, userId);
1569 if (packageInfo != null) {
1570 return packageInfo;
1571 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001572 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001573 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001574 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001575 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001576 }
1577
1578 private int getGroupParentLocked(int userId) {
1579 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001580 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001581 return userId;
1582 }
1583 // We are in the same process with the user manager and the returned
1584 // user info is a cached instance, so just look up instead of cache.
1585 final long identity = Binder.clearCallingIdentity();
1586 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001587 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001588 UserInfo userInfo = mUserManager.getProfileParent(userId);
1589 return (userInfo != null) ? userInfo.id : userId;
1590 } finally {
1591 Binder.restoreCallingIdentity(identity);
1592 }
1593 }
1594
Svetoslav683914b2015-01-15 14:22:26 -08001595 private void enforceWritePermission(String permission) {
1596 if (getContext().checkCallingOrSelfPermission(permission)
1597 != PackageManager.PERMISSION_GRANTED) {
1598 throw new SecurityException("Permission denial: writing to settings requires:"
1599 + permission);
1600 }
1601 }
1602
1603 /*
1604 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1605 * This setting contains a list of the currently enabled location providers.
1606 * But helper functions in android.providers.Settings can enable or disable
1607 * a single provider by using a "+" or "-" prefix before the provider name.
1608 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001609 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1610 * is set, the said method will only allow values with the "-" prefix.
1611 *
Svetoslav683914b2015-01-15 14:22:26 -08001612 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001613 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001614 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1615 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001616 if (TextUtils.isEmpty(value)) {
1617 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001618 }
1619
Svetoslav683914b2015-01-15 14:22:26 -08001620 final char prefix = value.charAt(0);
1621 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001622 if (forceNotify) {
1623 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1624 mSettingsRegistry.notifyForSettingsChange(key,
1625 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1626 }
Svetoslav683914b2015-01-15 14:22:26 -08001627 return false;
1628 }
1629
1630 // skip prefix
1631 value = value.substring(1);
1632
Svetoslav7ec28e82015-05-20 17:01:10 -07001633 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001634 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001635 if (settingValue == null) {
1636 return false;
1637 }
Svetoslav683914b2015-01-15 14:22:26 -08001638
1639 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1640
1641 int index = oldProviders.indexOf(value);
1642 int end = index + value.length();
1643
1644 // check for commas to avoid matching on partial string
1645 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1646 index = -1;
1647 }
1648
1649 // check for commas to avoid matching on partial string
1650 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1651 index = -1;
1652 }
1653
1654 String newProviders;
1655
1656 if (prefix == '+' && index < 0) {
1657 // append the provider to the list if not present
1658 if (oldProviders.length() == 0) {
1659 newProviders = value;
1660 } else {
1661 newProviders = oldProviders + ',' + value;
1662 }
1663 } else if (prefix == '-' && index >= 0) {
1664 // remove the provider from the list if present
1665 // remove leading or trailing comma
1666 if (index > 0) {
1667 index--;
1668 } else if (end < oldProviders.length()) {
1669 end++;
1670 }
1671
1672 newProviders = oldProviders.substring(0, index);
1673 if (end < oldProviders.length()) {
1674 newProviders += oldProviders.substring(end);
1675 }
1676 } else {
1677 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001678 if (forceNotify) {
1679 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1680 mSettingsRegistry.notifyForSettingsChange(key,
1681 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1682 }
Svetoslav683914b2015-01-15 14:22:26 -08001683 return false;
1684 }
1685
Svet Ganov53a441c2016-04-19 19:38:00 -07001686 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001687 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001688 tag, makeDefault, getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001689 }
1690
Svetoslav683914b2015-01-15 14:22:26 -08001691 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1692 int targetSdkVersion, String name) {
1693 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1694 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1695 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1696 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1697 + " This will soon become an error.");
1698 } else {
1699 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1700 + " This will soon become an error.");
1701 }
1702 } else {
1703 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1704 throw new IllegalArgumentException("You cannot change private secure settings.");
1705 } else {
1706 throw new IllegalArgumentException("You cannot keep your settings in"
1707 + " the secure settings.");
1708 }
1709 }
1710 }
1711
1712 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1713 if (requestingUserId == UserHandle.getCallingUserId()) {
1714 return requestingUserId;
1715 }
1716 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1717 Binder.getCallingUid(), requestingUserId, false, true,
1718 "get/set setting for user", null);
1719 }
1720
Svet Ganov53a441c2016-04-19 19:38:00 -07001721 private Bundle packageValueForCallResult(Setting setting,
1722 boolean trackingGeneration) {
1723 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001724 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001725 return NULL_SETTING_BUNDLE;
1726 }
1727 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001728 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001729 Bundle result = new Bundle();
1730 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001731 !setting.isNull() ? setting.getValue() : null);
1732 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001733 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001734 }
1735
1736 private static int getRequestingUserId(Bundle args) {
1737 final int callingUserId = UserHandle.getCallingUserId();
1738 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1739 : callingUserId;
1740 }
1741
Svet Ganov53a441c2016-04-19 19:38:00 -07001742 private boolean isTrackingGeneration(Bundle args) {
1743 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1744 }
1745
Svetoslav683914b2015-01-15 14:22:26 -08001746 private static String getSettingValue(Bundle args) {
1747 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1748 }
1749
Svetoslav Ganove080da92016-12-21 17:10:35 -08001750 private static String getSettingTag(Bundle args) {
1751 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1752 }
1753
1754 private static boolean getSettingMakeDefault(Bundle args) {
1755 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1756 }
1757
1758 private static int getResetModeEnforcingPermission(Bundle args) {
1759 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1760 switch (mode) {
1761 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1762 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1763 throw new SecurityException("Only system, shell/root on a "
1764 + "debuggable build can reset to untrusted defaults");
1765 }
1766 return mode;
1767 }
1768 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1769 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1770 throw new SecurityException("Only system, shell/root on a "
1771 + "debuggable build can reset untrusted changes");
1772 }
1773 return mode;
1774 }
1775 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1776 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1777 throw new SecurityException("Only system, shell/root on a "
1778 + "debuggable build can reset to trusted defaults");
1779 }
1780 return mode;
1781 }
1782 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1783 return mode;
1784 }
1785 }
1786 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1787 }
1788
1789 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1790 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1791 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1792 && (appId == SHELL_UID || appId == ROOT_UID));
1793 }
1794
Svetoslav683914b2015-01-15 14:22:26 -08001795 private static String getValidTableOrThrow(Uri uri) {
1796 if (uri.getPathSegments().size() > 0) {
1797 String table = uri.getPathSegments().get(0);
1798 if (DatabaseHelper.isValidTable(table)) {
1799 return table;
1800 }
1801 throw new IllegalArgumentException("Bad root path: " + table);
1802 }
1803 throw new IllegalArgumentException("Invalid URI:" + uri);
1804 }
1805
1806 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001807 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001808 return new MatrixCursor(projection, 0);
1809 }
1810 MatrixCursor cursor = new MatrixCursor(projection, 1);
1811 appendSettingToCursor(cursor, setting);
1812 return cursor;
1813 }
1814
1815 private static String[] normalizeProjection(String[] projection) {
1816 if (projection == null) {
1817 return ALL_COLUMNS;
1818 }
1819
1820 final int columnCount = projection.length;
1821 for (int i = 0; i < columnCount; i++) {
1822 String column = projection[i];
1823 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1824 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001825 }
1826 }
1827
Svetoslav683914b2015-01-15 14:22:26 -08001828 return projection;
1829 }
1830
1831 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001832 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001833 return;
1834 }
Svetoslav683914b2015-01-15 14:22:26 -08001835 final int columnCount = cursor.getColumnCount();
1836
1837 String[] values = new String[columnCount];
1838
1839 for (int i = 0; i < columnCount; i++) {
1840 String column = cursor.getColumnName(i);
1841
1842 switch (column) {
1843 case Settings.NameValueTable._ID: {
1844 values[i] = setting.getId();
1845 } break;
1846
1847 case Settings.NameValueTable.NAME: {
1848 values[i] = setting.getName();
1849 } break;
1850
1851 case Settings.NameValueTable.VALUE: {
1852 values[i] = setting.getValue();
1853 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001854 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001855 }
1856
Svetoslav683914b2015-01-15 14:22:26 -08001857 cursor.addRow(values);
1858 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001859
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001860 private static boolean isKeyValid(String key) {
1861 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1862 }
1863
Svetoslav683914b2015-01-15 14:22:26 -08001864 private static final class Arguments {
1865 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1866 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1867
1868 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1869 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1870
1871 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1872 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1873
1874 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1875 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1876
1877 public final String table;
1878 public final String name;
1879
1880 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1881 final int segmentSize = uri.getPathSegments().size();
1882 switch (segmentSize) {
1883 case 1: {
1884 if (where != null
1885 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1886 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1887 && whereArgs.length == 1) {
1888 name = whereArgs[0];
1889 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001890 return;
Svetoslav683914b2015-01-15 14:22:26 -08001891 } else if (where != null
1892 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1893 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1894 final int startIndex = Math.max(where.indexOf("'"),
1895 where.indexOf("\"")) + 1;
1896 final int endIndex = Math.max(where.lastIndexOf("'"),
1897 where.lastIndexOf("\""));
1898 name = where.substring(startIndex, endIndex);
1899 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001900 return;
Svetoslav683914b2015-01-15 14:22:26 -08001901 } else if (supportAll && where == null && whereArgs == null) {
1902 name = null;
1903 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001904 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001905 }
Svetoslav683914b2015-01-15 14:22:26 -08001906 } break;
1907
Svetoslav28494652015-02-12 14:11:42 -08001908 case 2: {
1909 if (where == null && whereArgs == null) {
1910 name = uri.getPathSegments().get(1);
1911 table = computeTableForSetting(uri, name);
1912 return;
1913 }
1914 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001915 }
Svetoslav28494652015-02-12 14:11:42 -08001916
1917 EventLogTags.writeUnsupportedSettingsQuery(
1918 uri.toSafeString(), where, Arrays.toString(whereArgs));
1919 String message = String.format( "Supported SQL:\n"
1920 + " uri content://some_table/some_property with null where and where args\n"
1921 + " uri content://some_table with query name=? and single name as arg\n"
1922 + " uri content://some_table with query name=some_name and null args\n"
1923 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1924 Arrays.toString(whereArgs));
1925 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001926 }
1927
Svetoslav28494652015-02-12 14:11:42 -08001928 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001929 String table = getValidTableOrThrow(uri);
1930
1931 if (name != null) {
1932 if (sSystemMovedToSecureSettings.contains(name)) {
1933 table = TABLE_SECURE;
1934 }
1935
1936 if (sSystemMovedToGlobalSettings.contains(name)) {
1937 table = TABLE_GLOBAL;
1938 }
1939
1940 if (sSecureMovedToGlobalSettings.contains(name)) {
1941 table = TABLE_GLOBAL;
1942 }
1943
1944 if (sGlobalMovedToSecureSettings.contains(name)) {
1945 table = TABLE_SECURE;
1946 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001947 }
Svetoslav683914b2015-01-15 14:22:26 -08001948
1949 return table;
1950 }
1951 }
1952
1953 final class SettingsRegistry {
1954 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1955
Svetoslav683914b2015-01-15 14:22:26 -08001956 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1957 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1958 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00001959 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
1960
1961 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08001962
1963 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1964
Svet Ganov53a441c2016-04-19 19:38:00 -07001965 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001966
Svetoslav7e0683b2015-08-03 16:02:52 -07001967 private final Handler mHandler;
1968
Svet Ganov53a441c2016-04-19 19:38:00 -07001969 private final BackupManager mBackupManager;
1970
Svetoslav683914b2015-01-15 14:22:26 -08001971 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001972 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001973 mGenerationRegistry = new GenerationRegistry(mLock);
1974 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001975 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00001976 syncSsaidTableOnStart();
1977 }
1978
1979 private void generateUserKeyLocked(int userId) {
1980 // Generate a random key for each user used for creating a new ssaid.
1981 final byte[] keyBytes = new byte[16];
1982 final SecureRandom rand = new SecureRandom();
1983 rand.nextBytes(keyBytes);
1984
1985 // Convert to string for storage in settings table.
1986 final String userKey = ByteStringUtils.toString(keyBytes);
1987
1988 // Store the key in the ssaid table.
1989 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1990 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
1991 true, SettingsState.SYSTEM_PACKAGE_NAME);
1992
1993 if (!success) {
1994 throw new IllegalStateException("Ssaid settings not accessible");
1995 }
1996 }
1997
1998 public Setting generateSsaidLocked(String packageName, int userId) {
1999 final PackageInfo packageInfo;
2000 try {
2001 packageInfo = mPackageManager.getPackageInfo(packageName,
2002 PackageManager.GET_SIGNATURES, userId);
2003 } catch (RemoteException e) {
2004 throw new IllegalStateException("Package info doesn't exist");
2005 }
2006
2007 // Read the user's key from the ssaid table.
2008 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002009 if (userKeySetting == null || userKeySetting.isNull()
2010 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002011 // Lazy initialize and store the user key.
2012 generateUserKeyLocked(userId);
2013 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002014 if (userKeySetting == null || userKeySetting.isNull()
2015 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002016 throw new IllegalStateException("User key not accessible");
2017 }
2018 }
2019 final String userKey = userKeySetting.getValue();
2020
2021 // Convert the user's key back to a byte array.
2022 final byte[] keyBytes = ByteStringUtils.toByteArray(userKey);
2023 if (keyBytes == null || keyBytes.length != 16) {
2024 throw new IllegalStateException("User key invalid");
2025 }
2026
2027 final MessageDigest md;
2028 try {
2029 // Hash package name and signature.
2030 md = MessageDigest.getInstance("SHA-256");
2031 } catch (NoSuchAlgorithmException e) {
2032 throw new IllegalStateException("HmacSHA256 is not available");
2033 }
2034 md.update(keyBytes);
2035 md.update(packageInfo.packageName.getBytes(StandardCharsets.UTF_8));
2036 md.update(packageInfo.signatures[0].toByteArray());
2037
2038 // Convert result to a string for storage in settings table. Only want first 64 bits.
2039 final String ssaid = ByteStringUtils.toString(md.digest()).substring(0, 16)
2040 .toLowerCase();
2041
2042 // Save the ssaid in the ssaid table.
2043 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2044 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2045 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2046 packageName);
2047
2048 if (!success) {
2049 throw new IllegalStateException("Ssaid settings not accessible");
2050 }
2051
2052 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2053 }
2054
2055 public void syncSsaidTableOnStart() {
2056 synchronized (mLock) {
2057 // Verify that each user's packages and ssaid's are in sync.
2058 for (UserInfo user : mUserManager.getUsers(true)) {
2059 // Get all uids for the user's packages.
2060 final List<PackageInfo> packages;
2061 try {
2062 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2063 } catch (RemoteException e) {
2064 throw new IllegalStateException("Package manager not available");
2065 }
2066 final Set<String> appUids = new HashSet<>();
2067 for (PackageInfo info : packages) {
2068 appUids.add(Integer.toString(info.applicationInfo.uid));
2069 }
2070
2071 // Get all uids currently stored in the user's ssaid table.
2072 final Set<String> ssaidUids = new HashSet<>(
2073 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2074 ssaidUids.remove(SSAID_USER_KEY);
2075
2076 // Perform a set difference for the appUids and ssaidUids.
2077 ssaidUids.removeAll(appUids);
2078
2079 // If there are ssaidUids left over they need to be removed from the table.
2080 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2081 user.id);
2082 for (String uid : ssaidUids) {
2083 ssaidSettings.deleteSettingLocked(uid);
2084 }
2085 }
2086 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002087 }
2088
Svetoslav683914b2015-01-15 14:22:26 -08002089 public List<String> getSettingsNamesLocked(int type, int userId) {
2090 final int key = makeKey(type, userId);
2091 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002092 if (settingsState == null) {
2093 return new ArrayList<String>();
2094 }
Svetoslav683914b2015-01-15 14:22:26 -08002095 return settingsState.getSettingNamesLocked();
2096 }
2097
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002098 public SparseBooleanArray getKnownUsersLocked() {
2099 SparseBooleanArray users = new SparseBooleanArray();
2100 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2101 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2102 }
2103 return users;
2104 }
2105
Svetoslav683914b2015-01-15 14:22:26 -08002106 public SettingsState getSettingsLocked(int type, int userId) {
2107 final int key = makeKey(type, userId);
2108 return peekSettingsStateLocked(key);
2109 }
2110
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002111 public boolean ensureSettingsForUserLocked(int userId) {
2112 // First make sure this user actually exists.
2113 if (mUserManager.getUserInfo(userId) == null) {
2114 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2115 return false;
2116 }
2117
Svetoslav683914b2015-01-15 14:22:26 -08002118 // Migrate the setting for this user if needed.
2119 migrateLegacySettingsForUserIfNeededLocked(userId);
2120
2121 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002122 if (userId == UserHandle.USER_SYSTEM) {
2123 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002124 ensureSettingsStateLocked(globalKey);
2125 }
2126
2127 // Ensure secure settings loaded.
2128 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2129 ensureSettingsStateLocked(secureKey);
2130
2131 // Make sure the secure settings have an Android id set.
2132 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2133 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2134
2135 // Ensure system settings loaded.
2136 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2137 ensureSettingsStateLocked(systemKey);
2138
Mark Rathjend891f012017-01-19 04:10:37 +00002139 // Ensure secure settings loaded.
2140 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2141 ensureSettingsStateLocked(ssaidKey);
2142
Svetoslav683914b2015-01-15 14:22:26 -08002143 // Upgrade the settings to the latest version.
2144 UpgradeController upgrader = new UpgradeController(userId);
2145 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002146 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002147 }
2148
2149 private void ensureSettingsStateLocked(int key) {
2150 if (mSettingsStates.get(key) == null) {
2151 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002152 SettingsState settingsState = new SettingsState(getContext(), mLock,
2153 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002154 mSettingsStates.put(key, settingsState);
2155 }
2156 }
2157
2158 public void removeUserStateLocked(int userId, boolean permanently) {
2159 // We always keep the global settings in memory.
2160
2161 // Nuke system settings.
2162 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2163 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2164 if (systemSettingsState != null) {
2165 if (permanently) {
2166 mSettingsStates.remove(systemKey);
2167 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002168 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002169 systemSettingsState.destroyLocked(new Runnable() {
2170 @Override
2171 public void run() {
2172 mSettingsStates.remove(systemKey);
2173 }
2174 });
2175 }
2176 }
2177
2178 // Nuke secure settings.
2179 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2180 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2181 if (secureSettingsState != null) {
2182 if (permanently) {
2183 mSettingsStates.remove(secureKey);
2184 secureSettingsState.destroyLocked(null);
2185 } else {
2186 secureSettingsState.destroyLocked(new Runnable() {
2187 @Override
2188 public void run() {
2189 mSettingsStates.remove(secureKey);
2190 }
2191 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002192 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002193 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002194
Mark Rathjend891f012017-01-19 04:10:37 +00002195 // Nuke ssaid settings.
2196 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2197 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2198 if (ssaidSettingsState != null) {
2199 if (permanently) {
2200 mSettingsStates.remove(ssaidKey);
2201 ssaidSettingsState.destroyLocked(null);
2202 } else {
2203 ssaidSettingsState.destroyLocked(new Runnable() {
2204 @Override
2205 public void run() {
2206 mSettingsStates.remove(ssaidKey);
2207 }
2208 });
2209 }
2210 }
2211
Svet Ganov53a441c2016-04-19 19:38:00 -07002212 // Nuke generation tracking data
2213 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002214 }
2215
Svetoslav683914b2015-01-15 14:22:26 -08002216 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002217 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002218 final int key = makeKey(type, userId);
2219
Svetoslav Ganove080da92016-12-21 17:10:35 -08002220 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002221 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002222 if (settingsState != null) {
2223 success = settingsState.insertSettingLocked(name, value,
2224 tag, makeDefault, packageName);
2225 }
Svetoslav683914b2015-01-15 14:22:26 -08002226
Svet Ganov53a441c2016-04-19 19:38:00 -07002227 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002228 notifyForSettingsChange(key, name);
2229 }
2230 return success;
2231 }
2232
Svet Ganov53a441c2016-04-19 19:38:00 -07002233 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002234 final int key = makeKey(type, userId);
2235
Svetoslav Ganove080da92016-12-21 17:10:35 -08002236 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002237 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002238 if (settingsState != null) {
2239 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002240 }
Svetoslav683914b2015-01-15 14:22:26 -08002241
Svet Ganov53a441c2016-04-19 19:38:00 -07002242 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002243 notifyForSettingsChange(key, name);
2244 }
2245 return success;
2246 }
2247
2248 public Setting getSettingLocked(int type, int userId, String name) {
2249 final int key = makeKey(type, userId);
2250
2251 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002252 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002253 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002254 }
Mark Rathjend891f012017-01-19 04:10:37 +00002255
2256 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002257 return settingsState.getSettingLocked(name);
2258 }
2259
2260 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002261 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002262 final int key = makeKey(type, userId);
2263
Svetoslav Ganove080da92016-12-21 17:10:35 -08002264 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002265 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002266 if (settingsState != null) {
2267 success = settingsState.updateSettingLocked(name, value, tag,
2268 makeDefault, packageName);
2269 }
Svetoslav683914b2015-01-15 14:22:26 -08002270
Svet Ganov53a441c2016-04-19 19:38:00 -07002271 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002272 notifyForSettingsChange(key, name);
2273 }
2274
2275 return success;
2276 }
2277
Svetoslav Ganove080da92016-12-21 17:10:35 -08002278 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2279 String tag) {
2280 final int key = makeKey(type, userId);
2281 SettingsState settingsState = peekSettingsStateLocked(key);
2282 if (settingsState == null) {
2283 return;
2284 }
2285
2286 switch (mode) {
2287 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2288 for (String name : settingsState.getSettingNamesLocked()) {
2289 Setting setting = settingsState.getSettingLocked(name);
2290 if (packageName.equals(setting.getPackageName())) {
2291 if (tag != null && !tag.equals(setting.getTag())) {
2292 continue;
2293 }
2294 if (settingsState.resetSettingLocked(name, packageName)) {
2295 notifyForSettingsChange(key, name);
2296 }
2297 }
2298 }
2299 } break;
2300
2301 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2302 for (String name : settingsState.getSettingNamesLocked()) {
2303 Setting setting = settingsState.getSettingLocked(name);
2304 if (!SettingsState.isSystemPackage(getContext(),
2305 setting.getPackageName())) {
2306 if (settingsState.resetSettingLocked(name, packageName)) {
2307 notifyForSettingsChange(key, name);
2308 }
2309 }
2310 }
2311 } break;
2312
2313 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2314 for (String name : settingsState.getSettingNamesLocked()) {
2315 Setting setting = settingsState.getSettingLocked(name);
2316 if (!SettingsState.isSystemPackage(getContext(),
2317 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002318 if (setting.isDefaultFromSystem()) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002319 if (settingsState.resetSettingLocked(name, packageName)) {
2320 notifyForSettingsChange(key, name);
2321 }
2322 } else if (settingsState.deleteSettingLocked(name)) {
2323 notifyForSettingsChange(key, name);
2324 }
2325 }
2326 }
2327 } break;
2328
2329 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2330 for (String name : settingsState.getSettingNamesLocked()) {
2331 Setting setting = settingsState.getSettingLocked(name);
Eugene Suslad72c3972016-12-27 15:49:30 -08002332 if (setting.isDefaultFromSystem()) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002333 if (settingsState.resetSettingLocked(name, packageName)) {
2334 notifyForSettingsChange(key, name);
2335 }
2336 } else if (settingsState.deleteSettingLocked(name)) {
2337 notifyForSettingsChange(key, name);
2338 }
2339 }
2340 } break;
2341 }
2342 }
2343
Svetoslav683914b2015-01-15 14:22:26 -08002344 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002345 // Global and secure settings are signature protected. Apps signed
2346 // by the platform certificate are generally not uninstalled and
2347 // the main exception is tests. We trust components signed
2348 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002349
2350 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2351 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002352 if (systemSettings != null) {
2353 systemSettings.onPackageRemovedLocked(packageName);
2354 }
Svetoslav683914b2015-01-15 14:22:26 -08002355 }
2356
Mark Rathjend891f012017-01-19 04:10:37 +00002357 public void onUidRemovedLocked(int uid) {
2358 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2359 UserHandle.getUserId(uid));
2360 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2361 }
2362
Svetoslav683914b2015-01-15 14:22:26 -08002363 private SettingsState peekSettingsStateLocked(int key) {
2364 SettingsState settingsState = mSettingsStates.get(key);
2365 if (settingsState != null) {
2366 return settingsState;
2367 }
2368
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002369 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2370 return null;
2371 }
Svetoslav683914b2015-01-15 14:22:26 -08002372 return mSettingsStates.get(key);
2373 }
2374
2375 private void migrateAllLegacySettingsIfNeeded() {
2376 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002377 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002378 File globalFile = getSettingsFile(key);
2379 if (globalFile.exists()) {
2380 return;
2381 }
2382
2383 final long identity = Binder.clearCallingIdentity();
2384 try {
2385 List<UserInfo> users = mUserManager.getUsers(true);
2386
2387 final int userCount = users.size();
2388 for (int i = 0; i < userCount; i++) {
2389 final int userId = users.get(i).id;
2390
2391 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2392 SQLiteDatabase database = dbHelper.getWritableDatabase();
2393 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2394
2395 // Upgrade to the latest version.
2396 UpgradeController upgrader = new UpgradeController(userId);
2397 upgrader.upgradeIfNeededLocked();
2398
2399 // Drop from memory if not a running user.
2400 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2401 removeUserStateLocked(userId, false);
2402 }
2403 }
2404 } finally {
2405 Binder.restoreCallingIdentity(identity);
2406 }
2407 }
2408 }
2409
2410 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2411 // Every user has secure settings and if no file we need to migrate.
2412 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2413 File secureFile = getSettingsFile(secureKey);
2414 if (secureFile.exists()) {
2415 return;
2416 }
2417
2418 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2419 SQLiteDatabase database = dbHelper.getWritableDatabase();
2420
2421 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2422 }
2423
2424 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2425 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002426 // Move over the system settings.
2427 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2428 ensureSettingsStateLocked(systemKey);
2429 SettingsState systemSettings = mSettingsStates.get(systemKey);
2430 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2431 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002432
2433 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002434 // Do this after System settings, since this is the first thing we check when deciding
2435 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002436 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2437 ensureSettingsStateLocked(secureKey);
2438 SettingsState secureSettings = mSettingsStates.get(secureKey);
2439 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2440 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2441 secureSettings.persistSyncLocked();
2442
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002443 // Move over the global settings if owner.
2444 // Do this last, since this is the first thing we check when deciding
2445 // to skip over migration from db to xml for owner user.
2446 if (userId == UserHandle.USER_SYSTEM) {
2447 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2448 ensureSettingsStateLocked(globalKey);
2449 SettingsState globalSettings = mSettingsStates.get(globalKey);
2450 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2451 globalSettings.persistSyncLocked();
2452 }
Svetoslav683914b2015-01-15 14:22:26 -08002453
2454 // Drop the database as now all is moved and persisted.
2455 if (DROP_DATABASE_ON_MIGRATION) {
2456 dbHelper.dropDatabase();
2457 } else {
2458 dbHelper.backupDatabase();
2459 }
2460 }
2461
2462 private void migrateLegacySettingsLocked(SettingsState settingsState,
2463 SQLiteDatabase database, String table) {
2464 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2465 queryBuilder.setTables(table);
2466
2467 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2468 null, null, null, null, null);
2469
2470 if (cursor == null) {
2471 return;
2472 }
2473
2474 try {
2475 if (!cursor.moveToFirst()) {
2476 return;
2477 }
2478
2479 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2480 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2481
2482 settingsState.setVersionLocked(database.getVersion());
2483
2484 while (!cursor.isAfterLast()) {
2485 String name = cursor.getString(nameColumnIdx);
2486 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002487 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002488 SettingsState.SYSTEM_PACKAGE_NAME);
2489 cursor.moveToNext();
2490 }
2491 } finally {
2492 cursor.close();
2493 }
2494 }
2495
2496 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2497 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2498
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002499 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002500 return;
2501 }
2502
2503 final int userId = getUserIdFromKey(secureSettings.mKey);
2504
2505 final UserInfo user;
2506 final long identity = Binder.clearCallingIdentity();
2507 try {
2508 user = mUserManager.getUserInfo(userId);
2509 } finally {
2510 Binder.restoreCallingIdentity(identity);
2511 }
2512 if (user == null) {
2513 // Can happen due to races when deleting users - treat as benign.
2514 return;
2515 }
2516
2517 String androidId = Long.toHexString(new SecureRandom().nextLong());
2518 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002519 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002520
2521 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2522 + "] for user " + userId);
2523
2524 // Write a drop box entry if it's a restricted profile
2525 if (user.isRestricted()) {
2526 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2527 Context.DROPBOX_SERVICE);
2528 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2529 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2530 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2531 }
2532 }
2533 }
2534
2535 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002536 final int userId = getUserIdFromKey(key);
2537 Uri uri = getNotificationUriFor(key, name);
2538
Phil Weaver83fec002016-05-11 10:55:29 -07002539 mGenerationRegistry.incrementGeneration(key);
2540
Svetoslav7e0683b2015-08-03 16:02:52 -07002541 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2542 userId, 0, uri).sendToTarget();
2543
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002544 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002545 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2546 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002547 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002548 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2549 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002550 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002551
Svet Ganov53a441c2016-04-19 19:38:00 -07002552 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002553 }
2554
Svet Ganov53a441c2016-04-19 19:38:00 -07002555 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002556 Set<String> keysCloned) {
2557 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002558 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002559 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002560 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002561 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002562 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002563 final int key = makeKey(type, profileId);
2564 mGenerationRegistry.incrementGeneration(key);
2565
2566 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002567 }
2568 }
2569 }
Svetoslav683914b2015-01-15 14:22:26 -08002570 }
2571
Svetoslav683914b2015-01-15 14:22:26 -08002572 private boolean isGlobalSettingsKey(int key) {
2573 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2574 }
2575
2576 private boolean isSystemSettingsKey(int key) {
2577 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2578 }
2579
2580 private boolean isSecureSettingsKey(int key) {
2581 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2582 }
2583
Mark Rathjend891f012017-01-19 04:10:37 +00002584 private boolean isSsaidSettingsKey(int key) {
2585 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2586 }
2587
Svetoslav683914b2015-01-15 14:22:26 -08002588 private File getSettingsFile(int key) {
2589 if (isGlobalSettingsKey(key)) {
2590 final int userId = getUserIdFromKey(key);
2591 return new File(Environment.getUserSystemDirectory(userId),
2592 SETTINGS_FILE_GLOBAL);
2593 } else if (isSystemSettingsKey(key)) {
2594 final int userId = getUserIdFromKey(key);
2595 return new File(Environment.getUserSystemDirectory(userId),
2596 SETTINGS_FILE_SYSTEM);
2597 } else if (isSecureSettingsKey(key)) {
2598 final int userId = getUserIdFromKey(key);
2599 return new File(Environment.getUserSystemDirectory(userId),
2600 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002601 } else if (isSsaidSettingsKey(key)) {
2602 final int userId = getUserIdFromKey(key);
2603 return new File(Environment.getUserSystemDirectory(userId),
2604 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002605 } else {
2606 throw new IllegalArgumentException("Invalid settings key:" + key);
2607 }
2608 }
2609
2610 private Uri getNotificationUriFor(int key, String name) {
2611 if (isGlobalSettingsKey(key)) {
2612 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2613 : Settings.Global.CONTENT_URI;
2614 } else if (isSecureSettingsKey(key)) {
2615 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2616 : Settings.Secure.CONTENT_URI;
2617 } else if (isSystemSettingsKey(key)) {
2618 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2619 : Settings.System.CONTENT_URI;
2620 } else {
2621 throw new IllegalArgumentException("Invalid settings key:" + key);
2622 }
2623 }
2624
2625 private int getMaxBytesPerPackageForType(int type) {
2626 switch (type) {
2627 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002628 case SETTINGS_TYPE_SECURE:
2629 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002630 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2631 }
2632
2633 default: {
2634 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2635 }
2636 }
2637 }
2638
Svetoslav7e0683b2015-08-03 16:02:52 -07002639 private final class MyHandler extends Handler {
2640 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2641 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2642
2643 public MyHandler(Looper looper) {
2644 super(looper);
2645 }
2646
2647 @Override
2648 public void handleMessage(Message msg) {
2649 switch (msg.what) {
2650 case MSG_NOTIFY_URI_CHANGED: {
2651 final int userId = msg.arg1;
2652 Uri uri = (Uri) msg.obj;
2653 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2654 if (DEBUG) {
2655 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2656 }
2657 } break;
2658
2659 case MSG_NOTIFY_DATA_CHANGED: {
2660 mBackupManager.dataChanged();
2661 } break;
2662 }
2663 }
2664 }
2665
Svetoslav683914b2015-01-15 14:22:26 -08002666 private final class UpgradeController {
Mark Rathjend891f012017-01-19 04:10:37 +00002667 private static final int SETTINGS_VERSION = 137;
Svetoslav683914b2015-01-15 14:22:26 -08002668
2669 private final int mUserId;
2670
2671 public UpgradeController(int userId) {
2672 mUserId = userId;
2673 }
2674
2675 public void upgradeIfNeededLocked() {
2676 // The version of all settings for a user is the same (all users have secure).
2677 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002678 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002679
2680 // Try an update from the current state.
2681 final int oldVersion = secureSettings.getVersionLocked();
2682 final int newVersion = SETTINGS_VERSION;
2683
Svet Ganovc9755bc2015-03-28 13:21:22 -07002684 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002685 if (oldVersion == newVersion) {
2686 return;
2687 }
2688
2689 // Try to upgrade.
2690 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2691
2692 // If upgrade failed start from scratch and upgrade.
2693 if (curVersion != newVersion) {
2694 // Drop state we have for this user.
2695 removeUserStateLocked(mUserId, true);
2696
2697 // Recreate the database.
2698 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2699 SQLiteDatabase database = dbHelper.getWritableDatabase();
2700 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2701
2702 // Migrate the settings for this user.
2703 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2704
2705 // Now upgrade should work fine.
2706 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002707
2708 // Make a note what happened, so we don't wonder why data was lost
2709 String reason = "Settings rebuilt! Current version: "
2710 + curVersion + " while expected: " + newVersion;
2711 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002712 Settings.Global.DATABASE_DOWNGRADE_REASON,
2713 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002714 }
2715
2716 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002717 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002718 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002719 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002720 globalSettings.setVersionLocked(newVersion);
2721 }
2722
2723 // Set the secure settings version.
2724 secureSettings.setVersionLocked(newVersion);
2725
2726 // Set the system settings version.
2727 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002728 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002729 systemSettings.setVersionLocked(newVersion);
2730 }
2731
2732 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002733 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002734 }
2735
2736 private SettingsState getSecureSettingsLocked(int userId) {
2737 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2738 }
2739
Mark Rathjend891f012017-01-19 04:10:37 +00002740 private SettingsState getSsaidSettingsLocked(int userId) {
2741 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2742 }
2743
Svetoslav683914b2015-01-15 14:22:26 -08002744 private SettingsState getSystemSettingsLocked(int userId) {
2745 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2746 }
2747
Jeff Brown503cffc2015-03-26 18:08:51 -07002748 /**
2749 * You must perform all necessary mutations to bring the settings
2750 * for this user from the old to the new version. When you add a new
2751 * upgrade step you *must* update SETTINGS_VERSION.
2752 *
2753 * This is an example of moving a setting from secure to global.
2754 *
2755 * // v119: Example settings changes.
2756 * if (currentVersion == 118) {
2757 * if (userId == UserHandle.USER_OWNER) {
2758 * // Remove from the secure settings.
2759 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2760 * String name = "example_setting_to_move";
2761 * String value = secureSettings.getSetting(name);
2762 * secureSettings.deleteSetting(name);
2763 *
2764 * // Add to the global settings.
2765 * SettingsState globalSettings = getGlobalSettingsLocked();
2766 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2767 * }
2768 *
2769 * // Update the current version.
2770 * currentVersion = 119;
2771 * }
2772 */
Svetoslav683914b2015-01-15 14:22:26 -08002773 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2774 if (DEBUG) {
2775 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2776 + oldVersion + " to version: " + newVersion);
2777 }
2778
Jeff Brown503cffc2015-03-26 18:08:51 -07002779 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002780
John Spurlocke11ae112015-05-11 16:09:03 -04002781 // v119: Reset zen + ringer mode.
2782 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002783 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002784 final SettingsState globalSettings = getGlobalSettingsLocked();
2785 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002786 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2787 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002788 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002789 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2790 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002791 }
2792 currentVersion = 119;
2793 }
2794
Jason Monk27bbb2d2015-03-31 16:46:39 -04002795 // v120: Add double tap to wake setting.
2796 if (currentVersion == 119) {
2797 SettingsState secureSettings = getSecureSettingsLocked(userId);
2798 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2799 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002800 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002801 SettingsState.SYSTEM_PACKAGE_NAME);
2802
2803 currentVersion = 120;
2804 }
2805
Svetoslav7e0683b2015-08-03 16:02:52 -07002806 if (currentVersion == 120) {
2807 // Before 121, we used a different string encoding logic. We just bump the
2808 // version here; SettingsState knows how to handle pre-version 120 files.
2809 currentVersion = 121;
2810 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002811
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002812 if (currentVersion == 121) {
2813 // Version 122: allow OEMs to set a default payment component in resources.
2814 // Note that we only write the default if no default has been set;
2815 // if there is, we just leave the default at whatever it currently is.
2816 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2817 String defaultComponent = (getContext().getResources().getString(
2818 R.string.def_nfc_payment_component));
2819 Setting currentSetting = secureSettings.getSettingLocked(
2820 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2821 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002822 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002823 secureSettings.insertSettingLocked(
2824 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002825 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002826 }
2827 currentVersion = 122;
2828 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002829
2830 if (currentVersion == 122) {
2831 // Version 123: Adding a default value for the ability to add a user from
2832 // the lock screen.
2833 if (userId == UserHandle.USER_SYSTEM) {
2834 final SettingsState globalSettings = getGlobalSettingsLocked();
2835 Setting currentSetting = globalSettings.getSettingLocked(
2836 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002837 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002838 globalSettings.insertSettingLocked(
2839 Settings.Global.ADD_USERS_WHEN_LOCKED,
2840 getContext().getResources().getBoolean(
2841 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002842 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002843 }
2844 }
2845 currentVersion = 123;
2846 }
Bryce Leebd179282015-12-17 19:01:37 -08002847
2848 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002849 final SettingsState globalSettings = getGlobalSettingsLocked();
2850 String defaultDisabledProfiles = (getContext().getResources().getString(
2851 R.string.def_bluetooth_disabled_profiles));
2852 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002853 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002854 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002855 }
2856
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002857 if (currentVersion == 124) {
2858 // Version 124: allow OEMs to set a default value for whether IME should be
2859 // shown when a physical keyboard is connected.
2860 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2861 Setting currentSetting = secureSettings.getSettingLocked(
2862 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002863 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002864 secureSettings.insertSettingLocked(
2865 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2866 getContext().getResources().getBoolean(
2867 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002868 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002869 }
2870 currentVersion = 125;
2871 }
2872
Ruben Brunk98576cf2016-03-07 18:54:28 -08002873 if (currentVersion == 125) {
2874 // Version 125: Allow OEMs to set the default VR service.
2875 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2876
2877 Setting currentSetting = secureSettings.getSettingLocked(
2878 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002879 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002880 ArraySet<ComponentName> l =
2881 SystemConfig.getInstance().getDefaultVrComponents();
2882
2883 if (l != null && !l.isEmpty()) {
2884 StringBuilder b = new StringBuilder();
2885 boolean start = true;
2886 for (ComponentName c : l) {
2887 if (!start) {
2888 b.append(':');
2889 }
2890 b.append(c.flattenToString());
2891 start = false;
2892 }
2893 secureSettings.insertSettingLocked(
2894 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002895 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002896 }
2897
2898 }
2899 currentVersion = 126;
2900 }
2901
Daniel U02ba6122016-04-01 18:41:42 +01002902 if (currentVersion == 126) {
2903 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2904 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2905 if (mUserManager.isManagedProfile(userId)) {
2906 final SettingsState systemSecureSettings =
2907 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2908
2909 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2910 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002911 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002912 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2913 secureSettings.insertSettingLocked(
2914 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002915 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002916 SettingsState.SYSTEM_PACKAGE_NAME);
2917 }
2918
2919 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2920 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002921 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002922 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2923 secureSettings.insertSettingLocked(
2924 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002925 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002926 SettingsState.SYSTEM_PACKAGE_NAME);
2927 }
2928 }
2929 currentVersion = 127;
2930 }
2931
Steven Ngdc20ba62016-04-26 18:19:04 +01002932 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002933 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002934 currentVersion = 128;
2935 }
2936
Julia Reynolds1f721e12016-07-11 08:50:58 -04002937 if (currentVersion == 128) {
2938 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2939 // the new apps are appended to the list of already approved apps.
2940 final SettingsState systemSecureSettings =
2941 getSecureSettingsLocked(userId);
2942
2943 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2944 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2945 String defaultPolicyAccess = getContext().getResources().getString(
2946 com.android.internal.R.string.config_defaultDndAccessPackages);
2947 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2948 if (policyAccess.isNull()) {
2949 systemSecureSettings.insertSettingLocked(
2950 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002951 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002952 SettingsState.SYSTEM_PACKAGE_NAME);
2953 } else {
2954 StringBuilder currentSetting =
2955 new StringBuilder(policyAccess.getValue());
2956 currentSetting.append(":");
2957 currentSetting.append(defaultPolicyAccess);
2958 systemSecureSettings.updateSettingLocked(
2959 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002960 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002961 SettingsState.SYSTEM_PACKAGE_NAME);
2962 }
2963 }
2964
2965 currentVersion = 129;
2966 }
2967
Dan Sandler71f85e92016-07-20 13:46:05 -04002968 if (currentVersion == 129) {
2969 // default longpress timeout changed from 500 to 400. If unchanged from the old
2970 // default, update to the new default.
2971 final SettingsState systemSecureSettings =
2972 getSecureSettingsLocked(userId);
2973 final String oldValue = systemSecureSettings.getSettingLocked(
2974 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2975 if (TextUtils.equals("500", oldValue)) {
2976 systemSecureSettings.insertSettingLocked(
2977 Settings.Secure.LONG_PRESS_TIMEOUT,
2978 String.valueOf(getContext().getResources().getInteger(
2979 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002980 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04002981 }
2982 currentVersion = 130;
2983 }
2984
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002985 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07002986 // Split Ambient settings
2987 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2988 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
2989 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
2990
2991 if (dozeExplicitlyDisabled) {
2992 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002993 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002994 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002995 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002996 }
2997 currentVersion = 131;
2998 }
2999
3000 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003001 // Initialize new multi-press timeout to default value
3002 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3003 final String oldValue = systemSecureSettings.getSettingLocked(
3004 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3005 if (TextUtils.equals(null, oldValue)) {
3006 systemSecureSettings.insertSettingLocked(
3007 Settings.Secure.MULTI_PRESS_TIMEOUT,
3008 String.valueOf(getContext().getResources().getInteger(
3009 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003010 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003011 }
3012
Adrian Roos69741a22016-10-21 14:49:17 -07003013 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003014 }
3015
Adrian Roos69741a22016-10-21 14:49:17 -07003016 if (currentVersion == 132) {
3017 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003018 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3019 String defaultSyncParentSounds = (getContext().getResources()
3020 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3021 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003022 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3023 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003024 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003025 }
3026
Adrian Roos69741a22016-10-21 14:49:17 -07003027 if (currentVersion == 133) {
3028 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003029 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3030 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3031 null) {
3032 String defaultEndButtonBehavior = Integer.toString(getContext()
3033 .getResources().getInteger(R.integer.def_end_button_behavior));
3034 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003035 defaultEndButtonBehavior, null, true,
3036 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003037 }
Adrian Roos69741a22016-10-21 14:49:17 -07003038 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003039 }
3040
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003041 if (currentVersion == 134) {
3042 // Remove setting that specifies if magnification values should be preserved.
3043 // This setting defaulted to true and never has a UI.
3044 getSecureSettingsLocked(userId).deleteSettingLocked(
3045 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3046 currentVersion = 135;
3047 }
3048
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003049 if (currentVersion == 135) {
3050 // Version 135: Migrating the NETWORK_SCORER_APP setting to the
3051 // NETWORK_RECOMMENDATIONS_ENABLED setting.
3052 if (userId == UserHandle.USER_SYSTEM) {
3053 final SettingsState globalSettings = getGlobalSettingsLocked();
3054 Setting currentSetting = globalSettings.getSettingLocked(
3055 Global.NETWORK_SCORER_APP);
3056 if (!currentSetting.isNull()) {
3057 // A scorer was set so enable recommendations.
3058 globalSettings.insertSettingLocked(
3059 Global.NETWORK_RECOMMENDATIONS_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003060 "1", null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003061 SettingsState.SYSTEM_PACKAGE_NAME);
3062
3063 // and clear the scorer setting since it's no longer needed.
3064 globalSettings.insertSettingLocked(
3065 Global.NETWORK_SCORER_APP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003066 null, null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003067 SettingsState.SYSTEM_PACKAGE_NAME);
3068 }
3069 }
3070 currentVersion = 136;
3071 }
3072
Mark Rathjend891f012017-01-19 04:10:37 +00003073 if (currentVersion == 136) {
3074 // Version 136: Store legacy SSAID for all apps currently installed on the
3075 // device as first step in migrating SSAID to be unique per application.
3076
3077 final boolean isUpgrade;
3078 try {
3079 isUpgrade = mPackageManager.isUpgrade();
3080 } catch (RemoteException e) {
3081 throw new IllegalStateException("Package manager not available");
3082 }
3083 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3084 // user data or first boot on a new device should use new ssaid generation.
3085 if (isUpgrade) {
3086 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003087 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3088 userId, Settings.Secure.ANDROID_ID);
3089 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3090 || legacySsaidSetting.getValue() == null) {
3091 throw new IllegalStateException("Legacy ssaid not accessible");
3092 }
3093 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003094
3095 // Fill each uid with the legacy ssaid to be backwards compatible.
3096 final List<PackageInfo> packages;
3097 try {
3098 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3099 } catch (RemoteException e) {
3100 throw new IllegalStateException("Package manager not available");
3101 }
3102
3103 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3104 for (PackageInfo info : packages) {
3105 // Check if the UID already has an entry in the table.
3106 final String uid = Integer.toString(info.applicationInfo.uid);
3107 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3108
3109 if (ssaid.isNull() || ssaid.getValue() == null) {
3110 // Android Id doesn't exist for this package so create it.
3111 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3112 info.packageName);
3113 }
3114 }
3115 }
3116
3117 currentVersion = 137;
3118 }
3119
Dan Sandler71f85e92016-07-20 13:46:05 -04003120 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003121 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003122 + newVersion + " left it at "
3123 + currentVersion + " instead; this is probably a bug", new Throwable());
3124 if (DEBUG) {
3125 throw new RuntimeException("db upgrade error");
3126 }
3127 }
3128
Jeff Brown503cffc2015-03-26 18:08:51 -07003129 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003130
Jeff Brown503cffc2015-03-26 18:08:51 -07003131 // Return the current version.
3132 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003133 }
3134 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003135 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003136}