blob: 93a00fec9765aaf43339e6c01f5a72d3628b1ada [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;
Julia Reynoldsad0d9e02017-02-15 08:41:48 -050035import android.content.pm.ResolveInfo;
36import android.content.pm.ServiceInfo;
Christopher Tate38e7a602013-09-03 16:57:34 -070037import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040043import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080047import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070048import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080049import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070051import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070052import android.os.Looper;
53import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070055import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070056import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070057import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070058import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.os.UserHandle;
60import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070061import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.provider.Settings;
Julia Reynoldsad0d9e02017-02-15 08:41:48 -050063import android.service.notification.NotificationListenerService;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010065import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080066import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000067import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070068import android.util.Slog;
69import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070070import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080071import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040072
Svetoslav683914b2015-01-15 14:22:26 -080073import com.android.internal.annotations.GuardedBy;
74import com.android.internal.content.PackageMonitor;
75import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080076import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070077import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080078import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040079
Svetoslav683914b2015-01-15 14:22:26 -080080import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080081import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080082import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080083import java.io.PrintWriter;
Mark Rathjend891f012017-01-19 04:10:37 +000084import java.nio.charset.StandardCharsets;
Mark Rathjen7599f132017-01-23 14:15:54 -080085import java.nio.ByteBuffer;
86import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000087import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070089import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080090import java.util.Arrays;
Mark Rathjend891f012017-01-19 04:10:37 +000091import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080092import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080093import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010094import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Set;
96import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080097import javax.crypto.Mac;
98import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070099
Svetoslav Ganove080da92016-12-21 17:10:35 -0800100import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800101import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800102import static android.os.Process.SYSTEM_UID;
103
Svetoslav Ganove080da92016-12-21 17:10:35 -0800104
Svetoslav683914b2015-01-15 14:22:26 -0800105/**
106 * <p>
107 * This class is a content provider that publishes the system settings.
108 * It can be accessed via the content provider APIs or via custom call
109 * commands. The latter is a bit faster and is the preferred way to access
110 * the platform settings.
111 * </p>
112 * <p>
113 * There are three settings types, global (with signature level protection
114 * and shared across users), secure (with signature permission level
115 * protection and per user), and system (with dangerous permission level
116 * protection and per user). Global settings are stored under the device owner.
117 * Each of these settings is represented by a {@link
118 * com.android.providers.settings.SettingsState} object mapped to an integer
119 * key derived from the setting type in the most significant bits and user
120 * id in the least significant bits. Settings are synchronously loaded on
121 * instantiation of a SettingsState and asynchronously persisted on mutation.
122 * Settings are stored in the user specific system directory.
123 * </p>
124 * <p>
125 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
126 * and get a warning. Targeting higher API version prohibits this as the
127 * system settings are not a place for apps to save their state. When a package
128 * is removed the settings it added are deleted. Apps cannot delete system
129 * settings added by the platform. System settings values are validated to
130 * ensure the clients do not put bad values. Global and secure settings are
131 * changed only by trusted parties, therefore no validation is performed. Also
132 * there is a limit on the amount of app specific settings that can be added
133 * to prevent unlimited growth of the system process memory footprint.
134 * </p>
135 */
136@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700137public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700138 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700140 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800141
142 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700143
Christopher Tate06efb532012-08-24 15:29:27 -0700144 private static final String TABLE_SYSTEM = "system";
145 private static final String TABLE_SECURE = "secure";
146 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800147
148 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 private static final String TABLE_FAVORITES = "favorites";
150 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800151 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
152 private static final String TABLE_BOOKMARKS = "bookmarks";
153 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Svetoslav683914b2015-01-15 14:22:26 -0800155 // The set of removed legacy tables.
156 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700157 static {
Svetoslav683914b2015-01-15 14:22:26 -0800158 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
159 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
160 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
161 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
162 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
163 }
Christopher Tate06efb532012-08-24 15:29:27 -0700164
Svetoslav683914b2015-01-15 14:22:26 -0800165 private static final int MUTATION_OPERATION_INSERT = 1;
166 private static final int MUTATION_OPERATION_DELETE = 2;
167 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800168 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400169
Svetoslav683914b2015-01-15 14:22:26 -0800170 private static final String[] ALL_COLUMNS = new String[] {
171 Settings.NameValueTable._ID,
172 Settings.NameValueTable.NAME,
173 Settings.NameValueTable.VALUE
174 };
175
Svet Ganov53a441c2016-04-19 19:38:00 -0700176 public static final int SETTINGS_TYPE_GLOBAL = 0;
177 public static final int SETTINGS_TYPE_SYSTEM = 1;
178 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000179 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800180
Svet Ganov53a441c2016-04-19 19:38:00 -0700181 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
182 public static final int SETTINGS_TYPE_SHIFT = 28;
183
184 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
185 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700186
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800187 // Changes to these global settings are synchronously persisted
188 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
189 static {
190 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
191 }
192
193 // Changes to these secure settings are synchronously persisted
194 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
195 static {
196 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
197 }
198
Svetoslav683914b2015-01-15 14:22:26 -0800199 // Per user secure settings that moved to the for all users global settings.
200 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
201 static {
202 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700203 }
204
Svetoslav683914b2015-01-15 14:22:26 -0800205 // Per user system settings that moved to the for all users global settings.
206 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
207 static {
208 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700209 }
210
Svetoslav683914b2015-01-15 14:22:26 -0800211 // Per user system settings that moved to the per user secure settings.
212 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
213 static {
214 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700215 }
216
Svetoslav683914b2015-01-15 14:22:26 -0800217 // Per all users global settings that moved to the per user secure settings.
218 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
219 static {
220 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700221 }
222
Svetoslav683914b2015-01-15 14:22:26 -0800223 // Per user secure settings that are cloned for the managed profiles of the user.
224 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
225 static {
226 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700227 }
228
Svetoslav683914b2015-01-15 14:22:26 -0800229 // Per user system settings that are cloned for the managed profiles of the user.
230 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
231 static {
232 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400233 }
234
Andre Lago3fa139c2016-08-04 13:53:44 +0100235 // Per user system settings that are cloned from the profile's parent when a dependency
236 // in {@link Settings.Secure} is set to "1".
237 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
238 static {
239 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
240 }
241
Svetoslav683914b2015-01-15 14:22:26 -0800242 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700243
Svetoslav683914b2015-01-15 14:22:26 -0800244 @GuardedBy("mLock")
245 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700246
Svet Ganova8f90262016-05-10 08:44:48 -0700247 @GuardedBy("mLock")
248 private HandlerThread mHandlerThread;
249
Svetoslav7ec28e82015-05-20 17:01:10 -0700250 // We have to call in the user manager with no lock held,
251 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800252
Svetoslav7ec28e82015-05-20 17:01:10 -0700253 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700254 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700255
Svet Ganov53a441c2016-04-19 19:38:00 -0700256 public static int makeKey(int type, int userId) {
257 return (type << SETTINGS_TYPE_SHIFT) | userId;
258 }
259
260 public static int getTypeFromKey(int key) {
261 return key >>> SETTINGS_TYPE_SHIFT;
262 }
263
264 public static int getUserIdFromKey(int key) {
265 return key & ~SETTINGS_TYPE_MASK;
266 }
267
268 public static String settingTypeToString(int type) {
269 switch (type) {
270 case SETTINGS_TYPE_GLOBAL: {
271 return "SETTINGS_GLOBAL";
272 }
273 case SETTINGS_TYPE_SECURE: {
274 return "SETTINGS_SECURE";
275 }
276 case SETTINGS_TYPE_SYSTEM: {
277 return "SETTINGS_SYSTEM";
278 }
Mark Rathjend891f012017-01-19 04:10:37 +0000279 case SETTINGS_TYPE_SSAID: {
280 return "SETTINGS_SSAID";
281 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700282 default: {
283 return "UNKNOWN";
284 }
285 }
286 }
287
288 public static String keyToString(int key) {
289 return "Key[user=" + getUserIdFromKey(key) + ";type="
290 + settingTypeToString(getTypeFromKey(key)) + "]";
291 }
292
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293 @Override
294 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800295 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800296 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700297 mUserManager = UserManager.get(getContext());
298 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700299 mHandlerThread = new HandlerThread(LOG_TAG,
300 Process.THREAD_PRIORITY_BACKGROUND);
301 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800302 mSettingsRegistry = new SettingsRegistry();
303 }
304 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700305 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700306 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700307 return true;
308 }
309
Svetoslav683914b2015-01-15 14:22:26 -0800310 @Override
311 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700312 final int requestingUserId = getRequestingUserId(args);
313 switch (method) {
314 case Settings.CALL_METHOD_GET_GLOBAL: {
315 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700316 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800317 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700318
319 case Settings.CALL_METHOD_GET_SECURE: {
320 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700321 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700322 }
323
324 case Settings.CALL_METHOD_GET_SYSTEM: {
325 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700326 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700327 }
328
329 case Settings.CALL_METHOD_PUT_GLOBAL: {
330 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800331 String tag = getSettingTag(args);
332 final boolean makeDefault = getSettingMakeDefault(args);
333 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700334 break;
335 }
336
337 case Settings.CALL_METHOD_PUT_SECURE: {
338 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800339 String tag = getSettingTag(args);
340 final boolean makeDefault = getSettingMakeDefault(args);
341 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700342 break;
343 }
344
345 case Settings.CALL_METHOD_PUT_SYSTEM: {
346 String value = getSettingValue(args);
347 insertSystemSetting(name, value, requestingUserId);
348 break;
349 }
350
Svetoslav Ganove080da92016-12-21 17:10:35 -0800351 case Settings.CALL_METHOD_RESET_GLOBAL: {
352 final int mode = getResetModeEnforcingPermission(args);
353 String tag = getSettingTag(args);
354 resetGlobalSetting(requestingUserId, mode, tag);
355 break;
356 }
357
358 case Settings.CALL_METHOD_RESET_SECURE: {
359 final int mode = getResetModeEnforcingPermission(args);
360 String tag = getSettingTag(args);
361 resetSecureSetting(requestingUserId, mode, tag);
362 break;
363 }
364
Svetoslav7ec28e82015-05-20 17:01:10 -0700365 default: {
366 Slog.w(LOG_TAG, "call() with invalid method: " + method);
367 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700368 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700369
Christopher Tate06efb532012-08-24 15:29:27 -0700370 return null;
371 }
372
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800373 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800374 public String getType(Uri uri) {
375 Arguments args = new Arguments(uri, null, null, true);
376 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700377 return "vnd.android.cursor.dir/" + args.table;
378 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700379 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700380 }
381 }
382
383 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800384 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
385 String order) {
386 if (DEBUG) {
387 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700388 }
389
Svetoslav683914b2015-01-15 14:22:26 -0800390 Arguments args = new Arguments(uri, where, whereArgs, true);
391 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392
Svetoslav683914b2015-01-15 14:22:26 -0800393 // If a legacy table that is gone, done.
394 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
395 return new MatrixCursor(normalizedProjection, 0);
396 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700397
Svetoslav7ec28e82015-05-20 17:01:10 -0700398 switch (args.table) {
399 case TABLE_GLOBAL: {
400 if (args.name != null) {
401 Setting setting = getGlobalSetting(args.name);
402 return packageSettingForQuery(setting, normalizedProjection);
403 } else {
404 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700405 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700406 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700407
Svetoslav7ec28e82015-05-20 17:01:10 -0700408 case TABLE_SECURE: {
409 final int userId = UserHandle.getCallingUserId();
410 if (args.name != null) {
411 Setting setting = getSecureSetting(args.name, userId);
412 return packageSettingForQuery(setting, normalizedProjection);
413 } else {
414 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800415 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700416 }
Svetoslav683914b2015-01-15 14:22:26 -0800417
Svetoslav7ec28e82015-05-20 17:01:10 -0700418 case TABLE_SYSTEM: {
419 final int userId = UserHandle.getCallingUserId();
420 if (args.name != null) {
421 Setting setting = getSystemSetting(args.name, userId);
422 return packageSettingForQuery(setting, normalizedProjection);
423 } else {
424 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800425 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700426 }
Svetoslav683914b2015-01-15 14:22:26 -0800427
Svetoslav7ec28e82015-05-20 17:01:10 -0700428 default: {
429 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700430 }
431 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700432 }
433
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700434 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800435 public Uri insert(Uri uri, ContentValues values) {
436 if (DEBUG) {
437 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700438 }
439
Svetoslav683914b2015-01-15 14:22:26 -0800440 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700441
Svetoslav683914b2015-01-15 14:22:26 -0800442 // If a legacy table that is gone, done.
443 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 return null;
445 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700446
Svetoslav683914b2015-01-15 14:22:26 -0800447 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700448 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800449 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700450 }
451
Svetoslav683914b2015-01-15 14:22:26 -0800452 String value = values.getAsString(Settings.Secure.VALUE);
453
Svetoslav7ec28e82015-05-20 17:01:10 -0700454 switch (table) {
455 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800456 if (insertGlobalSetting(name, value, null, false,
457 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700458 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700459 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700460 } break;
461
462 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800463 if (insertSecureSetting(name, value, null, false,
464 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700465 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
466 }
467 } break;
468
469 case TABLE_SYSTEM: {
470 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
471 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
472 }
473 } break;
474
475 default: {
476 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700477 }
478 }
479
Svetoslav683914b2015-01-15 14:22:26 -0800480 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700481 }
482
483 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800484 public int bulkInsert(Uri uri, ContentValues[] allValues) {
485 if (DEBUG) {
486 Slog.v(LOG_TAG, "bulkInsert() 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 int insertionCount = 0;
490 final int valuesCount = allValues.length;
491 for (int i = 0; i < valuesCount; i++) {
492 ContentValues values = allValues[i];
493 if (insert(uri, values) != null) {
494 insertionCount++;
495 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700496 }
Svetoslav683914b2015-01-15 14:22:26 -0800497
498 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700499 }
500
501 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800502 public int delete(Uri uri, String where, String[] whereArgs) {
503 if (DEBUG) {
504 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506
Svetoslav683914b2015-01-15 14:22:26 -0800507 Arguments args = new Arguments(uri, where, whereArgs, false);
508
509 // If a legacy table that is gone, done.
510 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
511 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700512 }
Svetoslav683914b2015-01-15 14:22:26 -0800513
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700514 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800515 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700516 }
Svetoslav683914b2015-01-15 14:22:26 -0800517
Svetoslav7ec28e82015-05-20 17:01:10 -0700518 switch (args.table) {
519 case TABLE_GLOBAL: {
520 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700521 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700522 }
Svetoslav683914b2015-01-15 14:22:26 -0800523
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 case TABLE_SECURE: {
525 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700526 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700527 }
Svetoslav683914b2015-01-15 14:22:26 -0800528
Svetoslav7ec28e82015-05-20 17:01:10 -0700529 case TABLE_SYSTEM: {
530 final int userId = UserHandle.getCallingUserId();
531 return deleteSystemSetting(args.name, userId) ? 1 : 0;
532 }
533
534 default: {
535 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800536 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700537 }
Svetoslav683914b2015-01-15 14:22:26 -0800538 }
539
540 @Override
541 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
542 if (DEBUG) {
543 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700544 }
Svetoslav683914b2015-01-15 14:22:26 -0800545
546 Arguments args = new Arguments(uri, where, whereArgs, false);
547
548 // If a legacy table that is gone, done.
549 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
550 return 0;
551 }
552
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700553 String name = values.getAsString(Settings.Secure.NAME);
554 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800555 return 0;
556 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700557 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800558
Svetoslav7ec28e82015-05-20 17:01:10 -0700559 switch (args.table) {
560 case TABLE_GLOBAL: {
561 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800562 return updateGlobalSetting(args.name, value, null, false,
563 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700564 }
Svetoslav683914b2015-01-15 14:22:26 -0800565
Svetoslav7ec28e82015-05-20 17:01:10 -0700566 case TABLE_SECURE: {
567 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800568 return updateSecureSetting(args.name, value, null, false,
569 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700570 }
Svetoslav683914b2015-01-15 14:22:26 -0800571
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 case TABLE_SYSTEM: {
573 final int userId = UserHandle.getCallingUserId();
574 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
575 }
Svetoslav683914b2015-01-15 14:22:26 -0800576
Svetoslav7ec28e82015-05-20 17:01:10 -0700577 default: {
578 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800579 }
580 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700581 }
582
583 @Override
584 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100585 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
586 if (userId != UserHandle.getCallingUserId()) {
587 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
588 "Access files from the settings of another user");
589 }
590 uri = ContentProvider.getUriWithoutUserId(uri);
591
Andre Lago3fa139c2016-08-04 13:53:44 +0100592 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700593 final String cacheName;
594 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100595 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700596 cacheName = Settings.System.RINGTONE_CACHE;
597 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100598 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700599 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
600 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100601 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700602 cacheName = Settings.System.ALARM_ALERT_CACHE;
603 } else {
604 throw new FileNotFoundException("Direct file access no longer supported; "
605 + "ringtone playback is available through android.media.Ringtone");
606 }
607
Andre Lago3fa139c2016-08-04 13:53:44 +0100608 int actualCacheOwner;
609 // Redirect cache to parent if ringtone setting is owned by profile parent
610 synchronized (mLock) {
611 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
612 cacheRingtoneSetting);
613 }
614 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700615 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
616 }
617
618 private File getRingtoneCacheDir(int userId) {
619 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
620 cacheDir.mkdir();
621 SELinux.restorecon(cacheDir);
622 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700623 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800624
Eugene Suslad72c3972016-12-27 15:49:30 -0800625 /**
626 * Dump all settings as a proto buf.
627 *
628 * @param fd The file to dump to
629 */
630 void dumpProto(@NonNull FileDescriptor fd) {
631 ProtoOutputStream proto = new ProtoOutputStream(fd);
632
633 synchronized (mLock) {
634 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
635
636 }
637
638 proto.flush();
639 }
640
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700641 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800642 synchronized (mLock) {
643 final long identity = Binder.clearCallingIdentity();
644 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700645 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800646 final int userCount = users.size();
647 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700648 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800649 }
650 } finally {
651 Binder.restoreCallingIdentity(identity);
652 }
653 }
654 }
655
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700656 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700657 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800658 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700659 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
660 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700661 if (globalSettings != null) {
662 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800663 pw.println();
664 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700665 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800666 }
667
668 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700669 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
670 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700671 if (secureSettings != null) {
672 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800673 pw.println();
674 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700675 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700676
Svetoslavb505ccc2015-02-17 12:41:04 -0800677 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700678 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
679 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700680 if (systemSettings != null) {
681 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800682 pw.println();
683 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700684 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800685 }
686
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700687 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
688 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800689
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700690 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800691
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700692 for (int i = 0; i < nameCount; i++) {
693 String name = names.get(i);
694 Setting setting = settingsState.getSettingLocked(name);
695 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
696 pw.print(" name:"); pw.print(toDumpString(name));
697 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800698 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700699 }
700 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800701 if (setting.getDefaultValue() != null) {
702 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800703 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800704 }
705 if (setting.getTag() != null) {
706 pw.print(" tag:"); pw.print(setting.getTag());
707 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800708 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700709 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800710 }
711
Svetoslav7e0683b2015-08-03 16:02:52 -0700712 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700713 if (s != null) {
714 return s;
715 }
716 return "{null}";
717 }
718
Svetoslav683914b2015-01-15 14:22:26 -0800719 private void registerBroadcastReceivers() {
720 IntentFilter userFilter = new IntentFilter();
721 userFilter.addAction(Intent.ACTION_USER_REMOVED);
722 userFilter.addAction(Intent.ACTION_USER_STOPPED);
723
724 getContext().registerReceiver(new BroadcastReceiver() {
725 @Override
726 public void onReceive(Context context, Intent intent) {
727 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700728 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800729
730 switch (intent.getAction()) {
731 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700732 synchronized (mLock) {
733 mSettingsRegistry.removeUserStateLocked(userId, true);
734 }
Svetoslav683914b2015-01-15 14:22:26 -0800735 } break;
736
737 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700738 synchronized (mLock) {
739 mSettingsRegistry.removeUserStateLocked(userId, false);
740 }
Svetoslav683914b2015-01-15 14:22:26 -0800741 } break;
742 }
743 }
744 }, userFilter);
745
746 PackageMonitor monitor = new PackageMonitor() {
747 @Override
748 public void onPackageRemoved(String packageName, int uid) {
749 synchronized (mLock) {
750 mSettingsRegistry.onPackageRemovedLocked(packageName,
751 UserHandle.getUserId(uid));
752 }
753 }
Mark Rathjend891f012017-01-19 04:10:37 +0000754
755 @Override
756 public void onUidRemoved(int uid) {
757 synchronized (mLock) {
758 mSettingsRegistry.onUidRemovedLocked(uid);
759 }
760 }
Svetoslav683914b2015-01-15 14:22:26 -0800761 };
762
763 // package changes
764 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
765 UserHandle.ALL, true);
766 }
767
Svet Ganov53a441c2016-04-19 19:38:00 -0700768 private void startWatchingUserRestrictionChanges() {
769 // TODO: The current design of settings looking different based on user restrictions
770 // should be reworked to keep them separate and system code should check the setting
771 // first followed by checking the user restriction before performing an operation.
772 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
773 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
774 Bundle prevRestrictions) -> {
775 // We are changing the settings affected by restrictions to their current
776 // value with a forced update to ensure that all cross profile dependencies
777 // are taken into account. Also make sure the settings update to.. the same
778 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800779 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
780 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700781 final long identity = Binder.clearCallingIdentity();
782 try {
783 synchronized (mLock) {
784 Setting setting = getSecureSetting(
785 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
786 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800787 setting != null ? setting.getValue() : null, null,
788 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700789 }
790 } finally {
791 Binder.restoreCallingIdentity(identity);
792 }
793 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800794 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
795 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700796 final long identity = Binder.clearCallingIdentity();
797 try {
798 synchronized (mLock) {
799 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800800 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700801 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800802 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 }
804 } finally {
805 Binder.restoreCallingIdentity(identity);
806 }
807 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800808 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
809 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700810 final long identity = Binder.clearCallingIdentity();
811 try {
812 synchronized (mLock) {
813 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800814 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700815 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800816 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 }
818 } finally {
819 Binder.restoreCallingIdentity(identity);
820 }
821 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800822 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
823 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700824 final long identity = Binder.clearCallingIdentity();
825 try {
826 synchronized (mLock) {
827 Setting enable = getGlobalSetting(
828 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800829 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700830 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800831 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700832 Setting include = getGlobalSetting(
833 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800834 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700835 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800836 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700837 }
838 } finally {
839 Binder.restoreCallingIdentity(identity);
840 }
841 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800842 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
843 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700844 final long identity = Binder.clearCallingIdentity();
845 try {
846 synchronized (mLock) {
847 Setting setting = getGlobalSetting(
848 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800849 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700850 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800851 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700852 }
853 } finally {
854 Binder.restoreCallingIdentity(identity);
855 }
856 }
857 });
858 }
859
Svetoslav7ec28e82015-05-20 17:01:10 -0700860 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800861 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700862 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800863 }
864
Svetoslav7ec28e82015-05-20 17:01:10 -0700865 synchronized (mLock) {
866 // Get the settings.
867 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700868 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800869
Chad Brubaker97bccee2017-01-05 15:51:41 -0800870 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
871 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800872
Svetoslav7ec28e82015-05-20 17:01:10 -0700873 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800874
Svetoslav7ec28e82015-05-20 17:01:10 -0700875 String[] normalizedProjection = normalizeProjection(projection);
876 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800877
Svetoslav7ec28e82015-05-20 17:01:10 -0700878 // Anyone can get the global settings, so no security checks.
879 for (int i = 0; i < nameCount; i++) {
880 String name = names.get(i);
881 Setting setting = settingsState.getSettingLocked(name);
882 appendSettingToCursor(result, setting);
883 }
884
885 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800886 }
Svetoslav683914b2015-01-15 14:22:26 -0800887 }
888
Svetoslav7ec28e82015-05-20 17:01:10 -0700889 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800890 if (DEBUG) {
891 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
892 }
893
Chad Brubaker97bccee2017-01-05 15:51:41 -0800894 // Ensure the caller can access the setting.
895 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
896
Svetoslav683914b2015-01-15 14:22:26 -0800897 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700898 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700899 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700900 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800901 }
Svetoslav683914b2015-01-15 14:22:26 -0800902 }
903
Svetoslav Ganove080da92016-12-21 17:10:35 -0800904 private boolean updateGlobalSetting(String name, String value, String tag,
905 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800906 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800907 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
908 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
909 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800910 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
912 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800913 }
914
Svetoslav Ganove080da92016-12-21 17:10:35 -0800915 private boolean insertGlobalSetting(String name, String value, String tag,
916 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700917 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
919 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
920 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700921 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800922 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
923 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 }
925
Svet Ganov53a441c2016-04-19 19:38:00 -0700926 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800927 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800928 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
929 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800930 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800931 return mutateGlobalSetting(name, null, null, false, requestingUserId,
932 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800933 }
934
Svetoslav Ganove080da92016-12-21 17:10:35 -0800935 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
936 if (DEBUG) {
937 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
938 + mode + ", " + tag + ")");
939 }
940 mutateGlobalSetting(null, null, tag, false, requestingUserId,
941 MUTATION_OPERATION_RESET, false, mode);
942 }
943
944 private boolean mutateGlobalSetting(String name, String value, String tag,
945 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
946 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800947 // Make sure the caller can change the settings - treated as secure.
948 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
949
Svetoslav683914b2015-01-15 14:22:26 -0800950 // Resolve the userId on whose behalf the call is made.
951 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
952
Makoto Onuki28da2e32015-11-20 11:30:44 -0800953 // If this is a setting that is currently restricted for this user, do not allow
954 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800955 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100956 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800957 return false;
958 }
959
960 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700961 synchronized (mLock) {
962 switch (operation) {
963 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800964 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
965 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800966 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700967 }
Svetoslav683914b2015-01-15 14:22:26 -0800968
Svetoslav7ec28e82015-05-20 17:01:10 -0700969 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700970 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800971 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700972 }
Svetoslav683914b2015-01-15 14:22:26 -0800973
Svetoslav7ec28e82015-05-20 17:01:10 -0700974 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800975 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
976 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800977 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700978 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800979
980 case MUTATION_OPERATION_RESET: {
981 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
982 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
983 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800984 }
985 }
986
987 return false;
988 }
989
Svetoslav7ec28e82015-05-20 17:01:10 -0700990 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800991 if (DEBUG) {
992 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
993 }
994
995 // Resolve the userId on whose behalf the call is made.
996 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
997
Svetoslav7ec28e82015-05-20 17:01:10 -0700998 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800999 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001000
Svetoslav7ec28e82015-05-20 17:01:10 -07001001 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001002
Svetoslav7ec28e82015-05-20 17:01:10 -07001003 String[] normalizedProjection = normalizeProjection(projection);
1004 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001005
Svetoslav7ec28e82015-05-20 17:01:10 -07001006 for (int i = 0; i < nameCount; i++) {
1007 String name = names.get(i);
1008 // Determine the owning user as some profile settings are cloned from the parent.
1009 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1010 name);
Svetoslav683914b2015-01-15 14:22:26 -08001011
Svetoslav7ec28e82015-05-20 17:01:10 -07001012 // Special case for location (sigh).
1013 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001014 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001015 }
Svetoslav683914b2015-01-15 14:22:26 -08001016
Mark Rathjen7599f132017-01-23 14:15:54 -08001017 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001018 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1019 final Setting setting;
1020 if (isNewSsaidSetting(name)) {
1021 setting = getSsaidSettingLocked(owningUserId);
1022 } else {
1023 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1024 name);
1025 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001027 }
1028
Svetoslav7ec28e82015-05-20 17:01:10 -07001029 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001030 }
Svetoslav683914b2015-01-15 14:22:26 -08001031 }
1032
Svetoslav7ec28e82015-05-20 17:01:10 -07001033 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001034 if (DEBUG) {
1035 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1036 }
1037
1038 // Resolve the userId on whose behalf the call is made.
1039 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1040
Chad Brubaker97bccee2017-01-05 15:51:41 -08001041 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001042 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001043
Svetoslav683914b2015-01-15 14:22:26 -08001044 // Determine the owning user as some profile settings are cloned from the parent.
1045 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1046
1047 // Special case for location (sigh).
1048 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001049 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1050 owningUserId);
1051 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001052 }
1053
1054 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001055 synchronized (mLock) {
Mark Rathjen7599f132017-01-23 14:15:54 -08001056 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001057 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1058 if (isNewSsaidSetting(name)) {
1059 return getSsaidSettingLocked(owningUserId);
1060 }
1061
Svet Ganov53a441c2016-04-19 19:38:00 -07001062 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001063 owningUserId, name);
1064 }
Svetoslav683914b2015-01-15 14:22:26 -08001065 }
1066
Mark Rathjend891f012017-01-19 04:10:37 +00001067 private boolean isNewSsaidSetting(String name) {
1068 return Settings.Secure.ANDROID_ID.equals(name)
1069 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1070 }
1071
1072 private Setting getSsaidSettingLocked(int owningUserId) {
1073 // Get uid of caller (key) used to store ssaid value
1074 String name = Integer.toString(
1075 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1076
1077 if (DEBUG) {
1078 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1079 }
1080
1081 // Retrieve the ssaid from the table if present.
1082 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1083 name);
1084
1085 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001086 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001087 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1088 }
1089
1090 return ssaid;
1091 }
1092
Svetoslav Ganove080da92016-12-21 17:10:35 -08001093 private boolean insertSecureSetting(String name, String value, String tag,
1094 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001095 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001096 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001097 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1098 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001099 }
1100
Svetoslav Ganove080da92016-12-21 17:10:35 -08001101 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1102 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001103 }
1104
Svet Ganov53a441c2016-04-19 19:38:00 -07001105 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001106 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001107 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1108 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001109 }
1110
Svetoslav Ganove080da92016-12-21 17:10:35 -08001111 return mutateSecureSetting(name, null, null, false, requestingUserId,
1112 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001113 }
1114
Svetoslav Ganove080da92016-12-21 17:10:35 -08001115 private boolean updateSecureSetting(String name, String value, String tag,
1116 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001117 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001118 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001119 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1120 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001121 }
1122
Svetoslav Ganove080da92016-12-21 17:10:35 -08001123 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1124 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001125 }
1126
Svetoslav Ganove080da92016-12-21 17:10:35 -08001127 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1128 if (DEBUG) {
1129 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1130 + mode + ", " + tag + ")");
1131 }
1132
1133 mutateSecureSetting(null, null, tag, false, requestingUserId,
1134 MUTATION_OPERATION_RESET, false, mode);
1135 }
1136
1137 private boolean mutateSecureSetting(String name, String value, String tag,
1138 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1139 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001140 // Make sure the caller can change the settings.
1141 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1142
Svetoslav683914b2015-01-15 14:22:26 -08001143 // Resolve the userId on whose behalf the call is made.
1144 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1145
Makoto Onuki28da2e32015-11-20 11:30:44 -08001146 // If this is a setting that is currently restricted for this user, do not allow
1147 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001148 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001149 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001150 return false;
1151 }
1152
1153 // Determine the owning user as some profile settings are cloned from the parent.
1154 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1155
1156 // Only the owning user can change the setting.
1157 if (owningUserId != callingUserId) {
1158 return false;
1159 }
1160
1161 // Special cases for location providers (sigh).
1162 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001163 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1164 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001165 }
1166
1167 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001168 synchronized (mLock) {
1169 switch (operation) {
1170 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001171 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001172 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001173 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001174 }
Svetoslav683914b2015-01-15 14:22:26 -08001175
Svetoslav7ec28e82015-05-20 17:01:10 -07001176 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001177 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001178 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001179 }
Svetoslav683914b2015-01-15 14:22:26 -08001180
Svetoslav7ec28e82015-05-20 17:01:10 -07001181 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001182 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001183 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001184 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001185 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001186
1187 case MUTATION_OPERATION_RESET: {
1188 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1189 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1190 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001191 }
1192 }
1193
1194 return false;
1195 }
1196
Svetoslav7ec28e82015-05-20 17:01:10 -07001197 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001198 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001199 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001200 }
1201
1202 // Resolve the userId on whose behalf the call is made.
1203 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1204
Svetoslav7ec28e82015-05-20 17:01:10 -07001205 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001206 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001207
Svetoslav7ec28e82015-05-20 17:01:10 -07001208 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001209
Svetoslav7ec28e82015-05-20 17:01:10 -07001210 String[] normalizedProjection = normalizeProjection(projection);
1211 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001212
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 for (int i = 0; i < nameCount; i++) {
1214 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001215
Svetoslav7ec28e82015-05-20 17:01:10 -07001216 // Determine the owning user as some profile settings are cloned from the parent.
1217 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1218 name);
Svetoslav683914b2015-01-15 14:22:26 -08001219
Svetoslav7ec28e82015-05-20 17:01:10 -07001220 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001221 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001222 appendSettingToCursor(result, setting);
1223 }
1224
1225 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001226 }
Svetoslav683914b2015-01-15 14:22:26 -08001227 }
1228
Svetoslav7ec28e82015-05-20 17:01:10 -07001229 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001230 if (DEBUG) {
1231 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1232 }
1233
1234 // Resolve the userId on whose behalf the call is made.
1235 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1236
Chad Brubaker97bccee2017-01-05 15:51:41 -08001237 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001238 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001239
Svetoslav683914b2015-01-15 14:22:26 -08001240 // Determine the owning user as some profile settings are cloned from the parent.
1241 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1242
1243 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001244 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001245 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001246 }
Svetoslav683914b2015-01-15 14:22:26 -08001247 }
1248
Svetoslav7ec28e82015-05-20 17:01:10 -07001249 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001250 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001251 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001252 + requestingUserId + ")");
1253 }
1254
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001256 }
1257
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001259 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001260 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001261 }
1262
Svetoslav7ec28e82015-05-20 17:01:10 -07001263 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001264 }
1265
Svetoslav7ec28e82015-05-20 17:01:10 -07001266 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001267 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001268 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001269 + requestingUserId + ")");
1270 }
1271
Svetoslav7ec28e82015-05-20 17:01:10 -07001272 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001273 }
1274
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001276 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001277 if (!hasWriteSecureSettingsPermission()) {
1278 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1279 // operation is allowed for the calling package through appops.
1280 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1281 Binder.getCallingUid(), getCallingPackage(), true)) {
1282 return false;
1283 }
Svetoslav683914b2015-01-15 14:22:26 -08001284 }
1285
Svetoslav683914b2015-01-15 14:22:26 -08001286 // Resolve the userId on whose behalf the call is made.
1287 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1288
Svetoslavd8d25e02015-11-20 13:09:26 -08001289 // Enforce what the calling package can mutate the system settings.
1290 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1291
Svetoslav683914b2015-01-15 14:22:26 -08001292 // Determine the owning user as some profile settings are cloned from the parent.
1293 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1294
1295 // Only the owning user id can change the setting.
1296 if (owningUserId != callingUserId) {
1297 return false;
1298 }
1299
Jeff Sharkey413573a2016-02-22 17:52:45 -07001300 // Invalidate any relevant cache files
1301 String cacheName = null;
1302 if (Settings.System.RINGTONE.equals(name)) {
1303 cacheName = Settings.System.RINGTONE_CACHE;
1304 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1305 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1306 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1307 cacheName = Settings.System.ALARM_ALERT_CACHE;
1308 }
1309 if (cacheName != null) {
1310 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001311 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001312 cacheFile.delete();
1313 }
1314
Svetoslav683914b2015-01-15 14:22:26 -08001315 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001316 synchronized (mLock) {
1317 switch (operation) {
1318 case MUTATION_OPERATION_INSERT: {
1319 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001320 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001321 owningUserId, name, value, null, false, getCallingPackage(),
1322 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001323 }
1324
1325 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001326 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001327 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001328 }
1329
1330 case MUTATION_OPERATION_UPDATE: {
1331 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001332 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001333 owningUserId, name, value, null, false, getCallingPackage(),
1334 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001335 }
Svetoslav683914b2015-01-15 14:22:26 -08001336 }
1337
Svetoslav7ec28e82015-05-20 17:01:10 -07001338 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001339 }
Svetoslav683914b2015-01-15 14:22:26 -08001340 }
1341
Billy Lau6ad2d662015-07-18 00:26:58 +01001342 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001343 // Write secure settings is a more protected permission. If caller has it we are good.
1344 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1345 == PackageManager.PERMISSION_GRANTED) {
1346 return true;
1347 }
1348
Svetoslavf41334b2015-06-23 12:06:03 -07001349 return false;
1350 }
1351
Svetoslav683914b2015-01-15 14:22:26 -08001352 private void validateSystemSettingValue(String name, String value) {
1353 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1354 if (validator != null && !validator.validate(value)) {
1355 throw new IllegalArgumentException("Invalid value: " + value
1356 + " for setting: " + name);
1357 }
1358 }
1359
1360 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1361 int owningUserId) {
1362 // Optimization - location providers are restricted only for managed profiles.
1363 if (callingUserId == owningUserId) {
1364 return false;
1365 }
1366 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1367 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1368 new UserHandle(callingUserId))) {
1369 return true;
1370 }
1371 return false;
1372 }
1373
Makoto Onuki28da2e32015-11-20 11:30:44 -08001374 /**
1375 * Checks whether changing a setting to a value is prohibited by the corresponding user
1376 * restriction.
1377 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001378 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1379 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001380 *
1381 * @return true if the change is prohibited, false if the change is allowed.
1382 */
1383 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001384 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001385 String restriction;
1386 switch (setting) {
1387 case Settings.Secure.LOCATION_MODE:
1388 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1389 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1390 // here normally, but we still protect it here from a direct provider write.
1391 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1392 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1393 break;
1394
1395 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1396 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1397 // a provider, which should be allowed even if the user restriction is set.
1398 if (value != null && value.startsWith("-")) return false;
1399 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1400 break;
1401
1402 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1403 if ("0".equals(value)) return false;
1404 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1405 break;
1406
1407 case Settings.Global.ADB_ENABLED:
1408 if ("0".equals(value)) return false;
1409 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1410 break;
1411
1412 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1413 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1414 if ("1".equals(value)) return false;
1415 restriction = UserManager.ENSURE_VERIFY_APPS;
1416 break;
1417
1418 case Settings.Global.PREFERRED_NETWORK_MODE:
1419 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1420 break;
1421
Victor Chang9c7b7062016-07-12 23:47:29 +01001422 case Settings.Secure.ALWAYS_ON_VPN_APP:
1423 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1424 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001425 final int appId = UserHandle.getAppId(callingUid);
1426 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001427 return false;
1428 }
1429 restriction = UserManager.DISALLOW_CONFIG_VPN;
1430 break;
1431
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001432 case Settings.Global.SAFE_BOOT_DISALLOWED:
1433 if ("1".equals(value)) return false;
1434 restriction = UserManager.DISALLOW_SAFE_BOOT;
1435 break;
1436
Makoto Onuki28da2e32015-11-20 11:30:44 -08001437 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001438 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001439 if ("0".equals(value)) return false;
1440 restriction = UserManager.DISALLOW_DATA_ROAMING;
1441 break;
1442 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001443 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001444 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001445
1446 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001447 }
1448
1449 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1450 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1451 }
1452
1453 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001454 final int parentId;
1455 // Resolves dependency if setting has a dependency and the calling user has a parent
1456 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1457 && (parentId = getGroupParentLocked(userId)) != userId) {
1458 // The setting has a dependency and the profile has a parent
1459 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001460 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1461 final long token = Binder.clearCallingIdentity();
1462 try {
1463 Setting settingObj = getSecureSetting(dependency, userId);
1464 if (settingObj != null && settingObj.getValue().equals("1")) {
1465 return parentId;
1466 }
1467 } finally {
1468 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001469 }
1470 }
Svetoslav683914b2015-01-15 14:22:26 -08001471 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1472 }
1473
1474 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1475 final int parentId = getGroupParentLocked(userId);
1476 if (parentId != userId && keys.contains(name)) {
1477 return parentId;
1478 }
1479 return userId;
1480 }
1481
Svetoslavf41334b2015-06-23 12:06:03 -07001482 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001483 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001484 // System/root/shell can mutate whatever secure settings they want.
1485 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001486 final int appId = UserHandle.getAppId(callingUid);
1487 if (appId == android.os.Process.SYSTEM_UID
1488 || appId == Process.SHELL_UID
1489 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001490 return;
1491 }
1492
1493 switch (operation) {
1494 case MUTATION_OPERATION_INSERT:
1495 // Insert updates.
1496 case MUTATION_OPERATION_UPDATE: {
1497 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1498 return;
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 case MUTATION_OPERATION_DELETE: {
1515 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1516 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1517 throw new IllegalArgumentException("You cannot delete system defined"
1518 + " secure settings.");
1519 }
1520
1521 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001522 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001523
1524 // Privileged apps can do whatever they want.
1525 if ((packageInfo.applicationInfo.privateFlags &
1526 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1527 return;
1528 }
1529
1530 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1531 packageInfo.applicationInfo.targetSdkVersion, name);
1532 } break;
1533 }
1534 }
1535
Todd Kennedybe0b8892017-02-15 14:13:52 -08001536 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001537 switch (settingsType) {
1538 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001539 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001540 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001541 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001542 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001543 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001544 default:
1545 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1546 }
1547 }
1548
1549 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
1550 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001551 if (ai.isInstantApp()) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001552 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001553 } else {
1554 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1555 }
1556 }
1557
1558 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1559 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1560 return;
1561 }
1562 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001563 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001564 return;
1565 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08001566 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001567 throw new SecurityException("Setting " + settingName + " is not accessible from"
1568 + " ephemeral package " + getCallingPackage());
1569 }
1570 }
1571
1572 private ApplicationInfo getCallingApplicationInfoOrThrow(int userId) {
1573 ApplicationInfo ai = null;
1574 try {
1575 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0 , userId);
1576 } catch (RemoteException ignored) {
1577 }
1578 if (ai == null) {
1579 throw new IllegalStateException("Failed to lookup info for package "
1580 + getCallingPackage());
1581 }
1582 return ai;
1583 }
1584
Xiaohui Chen43765b72015-08-31 10:57:33 -07001585 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001586 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001587 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1588 getCallingPackage(), 0, userId);
1589 if (packageInfo != null) {
1590 return packageInfo;
1591 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001592 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001593 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001594 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001595 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001596 }
1597
1598 private int getGroupParentLocked(int userId) {
1599 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001600 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001601 return userId;
1602 }
1603 // We are in the same process with the user manager and the returned
1604 // user info is a cached instance, so just look up instead of cache.
1605 final long identity = Binder.clearCallingIdentity();
1606 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001607 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001608 UserInfo userInfo = mUserManager.getProfileParent(userId);
1609 return (userInfo != null) ? userInfo.id : userId;
1610 } finally {
1611 Binder.restoreCallingIdentity(identity);
1612 }
1613 }
1614
Svetoslav683914b2015-01-15 14:22:26 -08001615 private void enforceWritePermission(String permission) {
1616 if (getContext().checkCallingOrSelfPermission(permission)
1617 != PackageManager.PERMISSION_GRANTED) {
1618 throw new SecurityException("Permission denial: writing to settings requires:"
1619 + permission);
1620 }
1621 }
1622
1623 /*
1624 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1625 * This setting contains a list of the currently enabled location providers.
1626 * But helper functions in android.providers.Settings can enable or disable
1627 * a single provider by using a "+" or "-" prefix before the provider name.
1628 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001629 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1630 * is set, the said method will only allow values with the "-" prefix.
1631 *
Svetoslav683914b2015-01-15 14:22:26 -08001632 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001633 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001634 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1635 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001636 if (TextUtils.isEmpty(value)) {
1637 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001638 }
1639
Svetoslav683914b2015-01-15 14:22:26 -08001640 final char prefix = value.charAt(0);
1641 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001642 if (forceNotify) {
1643 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1644 mSettingsRegistry.notifyForSettingsChange(key,
1645 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1646 }
Svetoslav683914b2015-01-15 14:22:26 -08001647 return false;
1648 }
1649
1650 // skip prefix
1651 value = value.substring(1);
1652
Svetoslav7ec28e82015-05-20 17:01:10 -07001653 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001654 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001655 if (settingValue == null) {
1656 return false;
1657 }
Svetoslav683914b2015-01-15 14:22:26 -08001658
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001659 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001660
1661 int index = oldProviders.indexOf(value);
1662 int end = index + value.length();
1663
1664 // check for commas to avoid matching on partial string
1665 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1666 index = -1;
1667 }
1668
1669 // check for commas to avoid matching on partial string
1670 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1671 index = -1;
1672 }
1673
1674 String newProviders;
1675
1676 if (prefix == '+' && index < 0) {
1677 // append the provider to the list if not present
1678 if (oldProviders.length() == 0) {
1679 newProviders = value;
1680 } else {
1681 newProviders = oldProviders + ',' + value;
1682 }
1683 } else if (prefix == '-' && index >= 0) {
1684 // remove the provider from the list if present
1685 // remove leading or trailing comma
1686 if (index > 0) {
1687 index--;
1688 } else if (end < oldProviders.length()) {
1689 end++;
1690 }
1691
1692 newProviders = oldProviders.substring(0, index);
1693 if (end < oldProviders.length()) {
1694 newProviders += oldProviders.substring(end);
1695 }
1696 } else {
1697 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001698 if (forceNotify) {
1699 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1700 mSettingsRegistry.notifyForSettingsChange(key,
1701 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1702 }
Svetoslav683914b2015-01-15 14:22:26 -08001703 return false;
1704 }
1705
Svet Ganov53a441c2016-04-19 19:38:00 -07001706 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001707 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001708 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001709 }
1710
Svetoslav683914b2015-01-15 14:22:26 -08001711 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1712 int targetSdkVersion, String name) {
1713 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1714 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1715 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1716 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1717 + " This will soon become an error.");
1718 } else {
1719 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1720 + " This will soon become an error.");
1721 }
1722 } else {
1723 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1724 throw new IllegalArgumentException("You cannot change private secure settings.");
1725 } else {
1726 throw new IllegalArgumentException("You cannot keep your settings in"
1727 + " the secure settings.");
1728 }
1729 }
1730 }
1731
1732 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1733 if (requestingUserId == UserHandle.getCallingUserId()) {
1734 return requestingUserId;
1735 }
1736 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1737 Binder.getCallingUid(), requestingUserId, false, true,
1738 "get/set setting for user", null);
1739 }
1740
Svet Ganov53a441c2016-04-19 19:38:00 -07001741 private Bundle packageValueForCallResult(Setting setting,
1742 boolean trackingGeneration) {
1743 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001744 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001745 return NULL_SETTING_BUNDLE;
1746 }
1747 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001748 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001749 Bundle result = new Bundle();
1750 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001751 !setting.isNull() ? setting.getValue() : null);
1752 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001753 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001754 }
1755
1756 private static int getRequestingUserId(Bundle args) {
1757 final int callingUserId = UserHandle.getCallingUserId();
1758 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1759 : callingUserId;
1760 }
1761
Svet Ganov53a441c2016-04-19 19:38:00 -07001762 private boolean isTrackingGeneration(Bundle args) {
1763 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1764 }
1765
Svetoslav683914b2015-01-15 14:22:26 -08001766 private static String getSettingValue(Bundle args) {
1767 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1768 }
1769
Svetoslav Ganove080da92016-12-21 17:10:35 -08001770 private static String getSettingTag(Bundle args) {
1771 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1772 }
1773
1774 private static boolean getSettingMakeDefault(Bundle args) {
1775 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1776 }
1777
1778 private static int getResetModeEnforcingPermission(Bundle args) {
1779 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1780 switch (mode) {
1781 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1782 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1783 throw new SecurityException("Only system, shell/root on a "
1784 + "debuggable build can reset to untrusted defaults");
1785 }
1786 return mode;
1787 }
1788 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1789 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1790 throw new SecurityException("Only system, shell/root on a "
1791 + "debuggable build can reset untrusted changes");
1792 }
1793 return mode;
1794 }
1795 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1796 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1797 throw new SecurityException("Only system, shell/root on a "
1798 + "debuggable build can reset to trusted defaults");
1799 }
1800 return mode;
1801 }
1802 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1803 return mode;
1804 }
1805 }
1806 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1807 }
1808
1809 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1810 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1811 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1812 && (appId == SHELL_UID || appId == ROOT_UID));
1813 }
1814
Svetoslav683914b2015-01-15 14:22:26 -08001815 private static String getValidTableOrThrow(Uri uri) {
1816 if (uri.getPathSegments().size() > 0) {
1817 String table = uri.getPathSegments().get(0);
1818 if (DatabaseHelper.isValidTable(table)) {
1819 return table;
1820 }
1821 throw new IllegalArgumentException("Bad root path: " + table);
1822 }
1823 throw new IllegalArgumentException("Invalid URI:" + uri);
1824 }
1825
1826 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001827 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001828 return new MatrixCursor(projection, 0);
1829 }
1830 MatrixCursor cursor = new MatrixCursor(projection, 1);
1831 appendSettingToCursor(cursor, setting);
1832 return cursor;
1833 }
1834
1835 private static String[] normalizeProjection(String[] projection) {
1836 if (projection == null) {
1837 return ALL_COLUMNS;
1838 }
1839
1840 final int columnCount = projection.length;
1841 for (int i = 0; i < columnCount; i++) {
1842 String column = projection[i];
1843 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1844 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001845 }
1846 }
1847
Svetoslav683914b2015-01-15 14:22:26 -08001848 return projection;
1849 }
1850
1851 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001852 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001853 return;
1854 }
Svetoslav683914b2015-01-15 14:22:26 -08001855 final int columnCount = cursor.getColumnCount();
1856
1857 String[] values = new String[columnCount];
1858
1859 for (int i = 0; i < columnCount; i++) {
1860 String column = cursor.getColumnName(i);
1861
1862 switch (column) {
1863 case Settings.NameValueTable._ID: {
1864 values[i] = setting.getId();
1865 } break;
1866
1867 case Settings.NameValueTable.NAME: {
1868 values[i] = setting.getName();
1869 } break;
1870
1871 case Settings.NameValueTable.VALUE: {
1872 values[i] = setting.getValue();
1873 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001874 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001875 }
1876
Svetoslav683914b2015-01-15 14:22:26 -08001877 cursor.addRow(values);
1878 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001879
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001880 private static boolean isKeyValid(String key) {
1881 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1882 }
1883
Svetoslav683914b2015-01-15 14:22:26 -08001884 private static final class Arguments {
1885 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1886 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1887
1888 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1889 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1890
1891 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1892 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1893
1894 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1895 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1896
1897 public final String table;
1898 public final String name;
1899
1900 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1901 final int segmentSize = uri.getPathSegments().size();
1902 switch (segmentSize) {
1903 case 1: {
1904 if (where != null
1905 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1906 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1907 && whereArgs.length == 1) {
1908 name = whereArgs[0];
1909 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001910 return;
Svetoslav683914b2015-01-15 14:22:26 -08001911 } else if (where != null
1912 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1913 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1914 final int startIndex = Math.max(where.indexOf("'"),
1915 where.indexOf("\"")) + 1;
1916 final int endIndex = Math.max(where.lastIndexOf("'"),
1917 where.lastIndexOf("\""));
1918 name = where.substring(startIndex, endIndex);
1919 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001920 return;
Svetoslav683914b2015-01-15 14:22:26 -08001921 } else if (supportAll && where == null && whereArgs == null) {
1922 name = null;
1923 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001924 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001925 }
Svetoslav683914b2015-01-15 14:22:26 -08001926 } break;
1927
Svetoslav28494652015-02-12 14:11:42 -08001928 case 2: {
1929 if (where == null && whereArgs == null) {
1930 name = uri.getPathSegments().get(1);
1931 table = computeTableForSetting(uri, name);
1932 return;
1933 }
1934 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001935 }
Svetoslav28494652015-02-12 14:11:42 -08001936
1937 EventLogTags.writeUnsupportedSettingsQuery(
1938 uri.toSafeString(), where, Arrays.toString(whereArgs));
1939 String message = String.format( "Supported SQL:\n"
1940 + " uri content://some_table/some_property with null where and where args\n"
1941 + " uri content://some_table with query name=? and single name as arg\n"
1942 + " uri content://some_table with query name=some_name and null args\n"
1943 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1944 Arrays.toString(whereArgs));
1945 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001946 }
1947
Svetoslav28494652015-02-12 14:11:42 -08001948 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001949 String table = getValidTableOrThrow(uri);
1950
1951 if (name != null) {
1952 if (sSystemMovedToSecureSettings.contains(name)) {
1953 table = TABLE_SECURE;
1954 }
1955
1956 if (sSystemMovedToGlobalSettings.contains(name)) {
1957 table = TABLE_GLOBAL;
1958 }
1959
1960 if (sSecureMovedToGlobalSettings.contains(name)) {
1961 table = TABLE_GLOBAL;
1962 }
1963
1964 if (sGlobalMovedToSecureSettings.contains(name)) {
1965 table = TABLE_SECURE;
1966 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001967 }
Svetoslav683914b2015-01-15 14:22:26 -08001968
1969 return table;
1970 }
1971 }
1972
1973 final class SettingsRegistry {
1974 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1975
Svetoslav683914b2015-01-15 14:22:26 -08001976 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1977 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1978 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00001979 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
1980
1981 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08001982
1983 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1984
Svet Ganov53a441c2016-04-19 19:38:00 -07001985 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001986
Svetoslav7e0683b2015-08-03 16:02:52 -07001987 private final Handler mHandler;
1988
Svet Ganov53a441c2016-04-19 19:38:00 -07001989 private final BackupManager mBackupManager;
1990
Svetoslav683914b2015-01-15 14:22:26 -08001991 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001992 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001993 mGenerationRegistry = new GenerationRegistry(mLock);
1994 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001995 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00001996 syncSsaidTableOnStart();
1997 }
1998
1999 private void generateUserKeyLocked(int userId) {
2000 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002001 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002002 final SecureRandom rand = new SecureRandom();
2003 rand.nextBytes(keyBytes);
2004
2005 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002006 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002007
2008 // Store the key in the ssaid table.
2009 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2010 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2011 true, SettingsState.SYSTEM_PACKAGE_NAME);
2012
2013 if (!success) {
2014 throw new IllegalStateException("Ssaid settings not accessible");
2015 }
2016 }
2017
Mark Rathjen7599f132017-01-23 14:15:54 -08002018 private byte[] getLengthPrefix(byte[] data) {
2019 return ByteBuffer.allocate(4).putInt(data.length).array();
2020 }
2021
Mark Rathjend891f012017-01-19 04:10:37 +00002022 public Setting generateSsaidLocked(String packageName, int userId) {
2023 final PackageInfo packageInfo;
2024 try {
2025 packageInfo = mPackageManager.getPackageInfo(packageName,
2026 PackageManager.GET_SIGNATURES, userId);
2027 } catch (RemoteException e) {
2028 throw new IllegalStateException("Package info doesn't exist");
2029 }
2030
2031 // Read the user's key from the ssaid table.
2032 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002033 if (userKeySetting == null || userKeySetting.isNull()
2034 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002035 // Lazy initialize and store the user key.
2036 generateUserKeyLocked(userId);
2037 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002038 if (userKeySetting == null || userKeySetting.isNull()
2039 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002040 throw new IllegalStateException("User key not accessible");
2041 }
2042 }
2043 final String userKey = userKeySetting.getValue();
2044
2045 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002046 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2047
2048 // Validate that the key is of expected length.
2049 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2050 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002051 throw new IllegalStateException("User key invalid");
2052 }
2053
Mark Rathjen7599f132017-01-23 14:15:54 -08002054 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002055 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002056 m = Mac.getInstance("HmacSHA256");
2057 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002058 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002059 throw new IllegalStateException("HmacSHA256 is not available", e);
2060 } catch (InvalidKeyException e) {
2061 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002062 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002063
2064 // Mac the package name and each of the signatures.
2065 byte[] packageNameBytes = packageInfo.packageName.getBytes(StandardCharsets.UTF_8);
2066 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2067 m.update(packageNameBytes);
2068 for (int i = 0; i < packageInfo.signatures.length; i++) {
2069 byte[] sig = packageInfo.signatures[i].toByteArray();
2070 m.update(getLengthPrefix(sig), 0, 4);
2071 m.update(sig);
2072 }
Mark Rathjend891f012017-01-19 04:10:37 +00002073
2074 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002075 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2076 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002077
2078 // Save the ssaid in the ssaid table.
2079 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2080 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2081 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2082 packageName);
2083
2084 if (!success) {
2085 throw new IllegalStateException("Ssaid settings not accessible");
2086 }
2087
2088 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2089 }
2090
2091 public void syncSsaidTableOnStart() {
2092 synchronized (mLock) {
2093 // Verify that each user's packages and ssaid's are in sync.
2094 for (UserInfo user : mUserManager.getUsers(true)) {
2095 // Get all uids for the user's packages.
2096 final List<PackageInfo> packages;
2097 try {
2098 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2099 } catch (RemoteException e) {
2100 throw new IllegalStateException("Package manager not available");
2101 }
2102 final Set<String> appUids = new HashSet<>();
2103 for (PackageInfo info : packages) {
2104 appUids.add(Integer.toString(info.applicationInfo.uid));
2105 }
2106
2107 // Get all uids currently stored in the user's ssaid table.
2108 final Set<String> ssaidUids = new HashSet<>(
2109 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2110 ssaidUids.remove(SSAID_USER_KEY);
2111
2112 // Perform a set difference for the appUids and ssaidUids.
2113 ssaidUids.removeAll(appUids);
2114
2115 // If there are ssaidUids left over they need to be removed from the table.
2116 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2117 user.id);
2118 for (String uid : ssaidUids) {
2119 ssaidSettings.deleteSettingLocked(uid);
2120 }
2121 }
2122 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002123 }
2124
Svetoslav683914b2015-01-15 14:22:26 -08002125 public List<String> getSettingsNamesLocked(int type, int userId) {
2126 final int key = makeKey(type, userId);
2127 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002128 if (settingsState == null) {
2129 return new ArrayList<String>();
2130 }
Svetoslav683914b2015-01-15 14:22:26 -08002131 return settingsState.getSettingNamesLocked();
2132 }
2133
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002134 public SparseBooleanArray getKnownUsersLocked() {
2135 SparseBooleanArray users = new SparseBooleanArray();
2136 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2137 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2138 }
2139 return users;
2140 }
2141
Svetoslav683914b2015-01-15 14:22:26 -08002142 public SettingsState getSettingsLocked(int type, int userId) {
2143 final int key = makeKey(type, userId);
2144 return peekSettingsStateLocked(key);
2145 }
2146
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002147 public boolean ensureSettingsForUserLocked(int userId) {
2148 // First make sure this user actually exists.
2149 if (mUserManager.getUserInfo(userId) == null) {
2150 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2151 return false;
2152 }
2153
Svetoslav683914b2015-01-15 14:22:26 -08002154 // Migrate the setting for this user if needed.
2155 migrateLegacySettingsForUserIfNeededLocked(userId);
2156
2157 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002158 if (userId == UserHandle.USER_SYSTEM) {
2159 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002160 ensureSettingsStateLocked(globalKey);
2161 }
2162
2163 // Ensure secure settings loaded.
2164 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2165 ensureSettingsStateLocked(secureKey);
2166
2167 // Make sure the secure settings have an Android id set.
2168 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2169 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2170
2171 // Ensure system settings loaded.
2172 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2173 ensureSettingsStateLocked(systemKey);
2174
Mark Rathjend891f012017-01-19 04:10:37 +00002175 // Ensure secure settings loaded.
2176 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2177 ensureSettingsStateLocked(ssaidKey);
2178
Svetoslav683914b2015-01-15 14:22:26 -08002179 // Upgrade the settings to the latest version.
2180 UpgradeController upgrader = new UpgradeController(userId);
2181 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002182 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002183 }
2184
2185 private void ensureSettingsStateLocked(int key) {
2186 if (mSettingsStates.get(key) == null) {
2187 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002188 SettingsState settingsState = new SettingsState(getContext(), mLock,
2189 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002190 mSettingsStates.put(key, settingsState);
2191 }
2192 }
2193
2194 public void removeUserStateLocked(int userId, boolean permanently) {
2195 // We always keep the global settings in memory.
2196
2197 // Nuke system settings.
2198 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2199 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2200 if (systemSettingsState != null) {
2201 if (permanently) {
2202 mSettingsStates.remove(systemKey);
2203 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002204 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002205 systemSettingsState.destroyLocked(new Runnable() {
2206 @Override
2207 public void run() {
2208 mSettingsStates.remove(systemKey);
2209 }
2210 });
2211 }
2212 }
2213
2214 // Nuke secure settings.
2215 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2216 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2217 if (secureSettingsState != null) {
2218 if (permanently) {
2219 mSettingsStates.remove(secureKey);
2220 secureSettingsState.destroyLocked(null);
2221 } else {
2222 secureSettingsState.destroyLocked(new Runnable() {
2223 @Override
2224 public void run() {
2225 mSettingsStates.remove(secureKey);
2226 }
2227 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002228 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002229 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002230
Mark Rathjend891f012017-01-19 04:10:37 +00002231 // Nuke ssaid settings.
2232 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2233 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2234 if (ssaidSettingsState != null) {
2235 if (permanently) {
2236 mSettingsStates.remove(ssaidKey);
2237 ssaidSettingsState.destroyLocked(null);
2238 } else {
2239 ssaidSettingsState.destroyLocked(new Runnable() {
2240 @Override
2241 public void run() {
2242 mSettingsStates.remove(ssaidKey);
2243 }
2244 });
2245 }
2246 }
2247
Svet Ganov53a441c2016-04-19 19:38:00 -07002248 // Nuke generation tracking data
2249 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002250 }
2251
Svetoslav683914b2015-01-15 14:22:26 -08002252 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002253 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2254 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002255 final int key = makeKey(type, userId);
2256
Svetoslav Ganove080da92016-12-21 17:10:35 -08002257 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002258 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002259 if (settingsState != null) {
2260 success = settingsState.insertSettingLocked(name, value,
2261 tag, makeDefault, packageName);
2262 }
Svetoslav683914b2015-01-15 14:22:26 -08002263
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002264 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2265 settingsState.persistSyncLocked();
2266 }
2267
Svet Ganov53a441c2016-04-19 19:38:00 -07002268 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002269 notifyForSettingsChange(key, name);
2270 }
2271 return success;
2272 }
2273
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002274 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2275 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002276 final int key = makeKey(type, userId);
2277
Svetoslav Ganove080da92016-12-21 17:10:35 -08002278 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002279 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002280 if (settingsState != null) {
2281 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002282 }
Svetoslav683914b2015-01-15 14:22:26 -08002283
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002284 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2285 settingsState.persistSyncLocked();
2286 }
2287
Svet Ganov53a441c2016-04-19 19:38:00 -07002288 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002289 notifyForSettingsChange(key, name);
2290 }
2291 return success;
2292 }
2293
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002294 public boolean updateSettingLocked(int type, int userId, String name, String value,
2295 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2296 Set<String> criticalSettings) {
2297 final int key = makeKey(type, userId);
2298
2299 boolean success = false;
2300 SettingsState settingsState = peekSettingsStateLocked(key);
2301 if (settingsState != null) {
2302 success = settingsState.updateSettingLocked(name, value, tag,
2303 makeDefault, packageName);
2304 }
2305
2306 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2307 settingsState.persistSyncLocked();
2308 }
2309
2310 if (forceNotify || success) {
2311 notifyForSettingsChange(key, name);
2312 }
2313
2314 return success;
2315 }
2316
Svetoslav683914b2015-01-15 14:22:26 -08002317 public Setting getSettingLocked(int type, int userId, String name) {
2318 final int key = makeKey(type, userId);
2319
2320 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002321 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002322 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002323 }
Mark Rathjend891f012017-01-19 04:10:37 +00002324
2325 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002326 return settingsState.getSettingLocked(name);
2327 }
2328
Svetoslav Ganove080da92016-12-21 17:10:35 -08002329 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2330 String tag) {
2331 final int key = makeKey(type, userId);
2332 SettingsState settingsState = peekSettingsStateLocked(key);
2333 if (settingsState == null) {
2334 return;
2335 }
2336
2337 switch (mode) {
2338 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2339 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002340 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002341 Setting setting = settingsState.getSettingLocked(name);
2342 if (packageName.equals(setting.getPackageName())) {
2343 if (tag != null && !tag.equals(setting.getTag())) {
2344 continue;
2345 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002346 if (settingsState.resetSettingLocked(name)) {
2347 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002348 notifyForSettingsChange(key, name);
2349 }
2350 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002351 if (someSettingChanged) {
2352 settingsState.persistSyncLocked();
2353 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002354 }
2355 } break;
2356
2357 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2358 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002359 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002360 Setting setting = settingsState.getSettingLocked(name);
2361 if (!SettingsState.isSystemPackage(getContext(),
2362 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002363 if (settingsState.resetSettingLocked(name)) {
2364 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002365 notifyForSettingsChange(key, name);
2366 }
2367 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002368 if (someSettingChanged) {
2369 settingsState.persistSyncLocked();
2370 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002371 }
2372 } break;
2373
2374 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2375 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002376 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002377 Setting setting = settingsState.getSettingLocked(name);
2378 if (!SettingsState.isSystemPackage(getContext(),
2379 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002380 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002381 if (settingsState.resetSettingLocked(name)) {
2382 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002383 notifyForSettingsChange(key, name);
2384 }
2385 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002386 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002387 notifyForSettingsChange(key, name);
2388 }
2389 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002390 if (someSettingChanged) {
2391 settingsState.persistSyncLocked();
2392 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002393 }
2394 } break;
2395
2396 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2397 for (String name : settingsState.getSettingNamesLocked()) {
2398 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002399 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002400 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002401 if (settingsState.resetSettingLocked(name)) {
2402 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002403 notifyForSettingsChange(key, name);
2404 }
2405 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002406 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002407 notifyForSettingsChange(key, name);
2408 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002409 if (someSettingChanged) {
2410 settingsState.persistSyncLocked();
2411 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002412 }
2413 } break;
2414 }
2415 }
2416
Svetoslav683914b2015-01-15 14:22:26 -08002417 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002418 // Global and secure settings are signature protected. Apps signed
2419 // by the platform certificate are generally not uninstalled and
2420 // the main exception is tests. We trust components signed
2421 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002422
2423 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2424 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002425 if (systemSettings != null) {
2426 systemSettings.onPackageRemovedLocked(packageName);
2427 }
Svetoslav683914b2015-01-15 14:22:26 -08002428 }
2429
Mark Rathjend891f012017-01-19 04:10:37 +00002430 public void onUidRemovedLocked(int uid) {
2431 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2432 UserHandle.getUserId(uid));
2433 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2434 }
2435
Svetoslav683914b2015-01-15 14:22:26 -08002436 private SettingsState peekSettingsStateLocked(int key) {
2437 SettingsState settingsState = mSettingsStates.get(key);
2438 if (settingsState != null) {
2439 return settingsState;
2440 }
2441
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002442 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2443 return null;
2444 }
Svetoslav683914b2015-01-15 14:22:26 -08002445 return mSettingsStates.get(key);
2446 }
2447
2448 private void migrateAllLegacySettingsIfNeeded() {
2449 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002450 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002451 File globalFile = getSettingsFile(key);
2452 if (globalFile.exists()) {
2453 return;
2454 }
2455
2456 final long identity = Binder.clearCallingIdentity();
2457 try {
2458 List<UserInfo> users = mUserManager.getUsers(true);
2459
2460 final int userCount = users.size();
2461 for (int i = 0; i < userCount; i++) {
2462 final int userId = users.get(i).id;
2463
2464 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2465 SQLiteDatabase database = dbHelper.getWritableDatabase();
2466 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2467
2468 // Upgrade to the latest version.
2469 UpgradeController upgrader = new UpgradeController(userId);
2470 upgrader.upgradeIfNeededLocked();
2471
2472 // Drop from memory if not a running user.
2473 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2474 removeUserStateLocked(userId, false);
2475 }
2476 }
2477 } finally {
2478 Binder.restoreCallingIdentity(identity);
2479 }
2480 }
2481 }
2482
2483 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2484 // Every user has secure settings and if no file we need to migrate.
2485 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2486 File secureFile = getSettingsFile(secureKey);
2487 if (secureFile.exists()) {
2488 return;
2489 }
2490
2491 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2492 SQLiteDatabase database = dbHelper.getWritableDatabase();
2493
2494 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2495 }
2496
2497 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2498 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002499 // Move over the system settings.
2500 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2501 ensureSettingsStateLocked(systemKey);
2502 SettingsState systemSettings = mSettingsStates.get(systemKey);
2503 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2504 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002505
2506 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002507 // Do this after System settings, since this is the first thing we check when deciding
2508 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002509 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2510 ensureSettingsStateLocked(secureKey);
2511 SettingsState secureSettings = mSettingsStates.get(secureKey);
2512 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2513 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2514 secureSettings.persistSyncLocked();
2515
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002516 // Move over the global settings if owner.
2517 // Do this last, since this is the first thing we check when deciding
2518 // to skip over migration from db to xml for owner user.
2519 if (userId == UserHandle.USER_SYSTEM) {
2520 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2521 ensureSettingsStateLocked(globalKey);
2522 SettingsState globalSettings = mSettingsStates.get(globalKey);
2523 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2524 globalSettings.persistSyncLocked();
2525 }
Svetoslav683914b2015-01-15 14:22:26 -08002526
2527 // Drop the database as now all is moved and persisted.
2528 if (DROP_DATABASE_ON_MIGRATION) {
2529 dbHelper.dropDatabase();
2530 } else {
2531 dbHelper.backupDatabase();
2532 }
2533 }
2534
2535 private void migrateLegacySettingsLocked(SettingsState settingsState,
2536 SQLiteDatabase database, String table) {
2537 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2538 queryBuilder.setTables(table);
2539
2540 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2541 null, null, null, null, null);
2542
2543 if (cursor == null) {
2544 return;
2545 }
2546
2547 try {
2548 if (!cursor.moveToFirst()) {
2549 return;
2550 }
2551
2552 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2553 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2554
2555 settingsState.setVersionLocked(database.getVersion());
2556
2557 while (!cursor.isAfterLast()) {
2558 String name = cursor.getString(nameColumnIdx);
2559 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002560 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002561 SettingsState.SYSTEM_PACKAGE_NAME);
2562 cursor.moveToNext();
2563 }
2564 } finally {
2565 cursor.close();
2566 }
2567 }
2568
2569 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2570 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2571
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002572 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002573 return;
2574 }
2575
2576 final int userId = getUserIdFromKey(secureSettings.mKey);
2577
2578 final UserInfo user;
2579 final long identity = Binder.clearCallingIdentity();
2580 try {
2581 user = mUserManager.getUserInfo(userId);
2582 } finally {
2583 Binder.restoreCallingIdentity(identity);
2584 }
2585 if (user == null) {
2586 // Can happen due to races when deleting users - treat as benign.
2587 return;
2588 }
2589
2590 String androidId = Long.toHexString(new SecureRandom().nextLong());
2591 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002592 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002593
2594 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2595 + "] for user " + userId);
2596
2597 // Write a drop box entry if it's a restricted profile
2598 if (user.isRestricted()) {
2599 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2600 Context.DROPBOX_SERVICE);
2601 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2602 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2603 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2604 }
2605 }
2606 }
2607
2608 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002609 final int userId = getUserIdFromKey(key);
2610 Uri uri = getNotificationUriFor(key, name);
2611
Phil Weaver83fec002016-05-11 10:55:29 -07002612 mGenerationRegistry.incrementGeneration(key);
2613
Svetoslav7e0683b2015-08-03 16:02:52 -07002614 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2615 userId, 0, uri).sendToTarget();
2616
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002617 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002618 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2619 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002620 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002621 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2622 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002623 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002624
Svet Ganov53a441c2016-04-19 19:38:00 -07002625 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002626 }
2627
Svet Ganov53a441c2016-04-19 19:38:00 -07002628 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002629 Set<String> keysCloned) {
2630 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002631 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002632 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002633 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002634 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002635 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002636 final int key = makeKey(type, profileId);
2637 mGenerationRegistry.incrementGeneration(key);
2638
2639 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002640 }
2641 }
2642 }
Svetoslav683914b2015-01-15 14:22:26 -08002643 }
2644
Svetoslav683914b2015-01-15 14:22:26 -08002645 private boolean isGlobalSettingsKey(int key) {
2646 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2647 }
2648
2649 private boolean isSystemSettingsKey(int key) {
2650 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2651 }
2652
2653 private boolean isSecureSettingsKey(int key) {
2654 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2655 }
2656
Mark Rathjend891f012017-01-19 04:10:37 +00002657 private boolean isSsaidSettingsKey(int key) {
2658 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2659 }
2660
Svetoslav683914b2015-01-15 14:22:26 -08002661 private File getSettingsFile(int key) {
2662 if (isGlobalSettingsKey(key)) {
2663 final int userId = getUserIdFromKey(key);
2664 return new File(Environment.getUserSystemDirectory(userId),
2665 SETTINGS_FILE_GLOBAL);
2666 } else if (isSystemSettingsKey(key)) {
2667 final int userId = getUserIdFromKey(key);
2668 return new File(Environment.getUserSystemDirectory(userId),
2669 SETTINGS_FILE_SYSTEM);
2670 } else if (isSecureSettingsKey(key)) {
2671 final int userId = getUserIdFromKey(key);
2672 return new File(Environment.getUserSystemDirectory(userId),
2673 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002674 } else if (isSsaidSettingsKey(key)) {
2675 final int userId = getUserIdFromKey(key);
2676 return new File(Environment.getUserSystemDirectory(userId),
2677 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002678 } else {
2679 throw new IllegalArgumentException("Invalid settings key:" + key);
2680 }
2681 }
2682
2683 private Uri getNotificationUriFor(int key, String name) {
2684 if (isGlobalSettingsKey(key)) {
2685 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2686 : Settings.Global.CONTENT_URI;
2687 } else if (isSecureSettingsKey(key)) {
2688 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2689 : Settings.Secure.CONTENT_URI;
2690 } else if (isSystemSettingsKey(key)) {
2691 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2692 : Settings.System.CONTENT_URI;
2693 } else {
2694 throw new IllegalArgumentException("Invalid settings key:" + key);
2695 }
2696 }
2697
2698 private int getMaxBytesPerPackageForType(int type) {
2699 switch (type) {
2700 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002701 case SETTINGS_TYPE_SECURE:
2702 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002703 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2704 }
2705
2706 default: {
2707 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2708 }
2709 }
2710 }
2711
Svetoslav7e0683b2015-08-03 16:02:52 -07002712 private final class MyHandler extends Handler {
2713 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2714 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2715
2716 public MyHandler(Looper looper) {
2717 super(looper);
2718 }
2719
2720 @Override
2721 public void handleMessage(Message msg) {
2722 switch (msg.what) {
2723 case MSG_NOTIFY_URI_CHANGED: {
2724 final int userId = msg.arg1;
2725 Uri uri = (Uri) msg.obj;
2726 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2727 if (DEBUG) {
2728 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2729 }
2730 } break;
2731
2732 case MSG_NOTIFY_DATA_CHANGED: {
2733 mBackupManager.dataChanged();
2734 } break;
2735 }
2736 }
2737 }
2738
Svetoslav683914b2015-01-15 14:22:26 -08002739 private final class UpgradeController {
Svet Ganov13701552017-02-23 12:45:17 -08002740 private static final int SETTINGS_VERSION = 142;
Svetoslav683914b2015-01-15 14:22:26 -08002741
2742 private final int mUserId;
2743
2744 public UpgradeController(int userId) {
2745 mUserId = userId;
2746 }
2747
2748 public void upgradeIfNeededLocked() {
2749 // The version of all settings for a user is the same (all users have secure).
2750 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002751 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002752
2753 // Try an update from the current state.
2754 final int oldVersion = secureSettings.getVersionLocked();
2755 final int newVersion = SETTINGS_VERSION;
2756
Svet Ganovc9755bc2015-03-28 13:21:22 -07002757 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002758 if (oldVersion == newVersion) {
2759 return;
2760 }
2761
2762 // Try to upgrade.
2763 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2764
2765 // If upgrade failed start from scratch and upgrade.
2766 if (curVersion != newVersion) {
2767 // Drop state we have for this user.
2768 removeUserStateLocked(mUserId, true);
2769
2770 // Recreate the database.
2771 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2772 SQLiteDatabase database = dbHelper.getWritableDatabase();
2773 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2774
2775 // Migrate the settings for this user.
2776 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2777
2778 // Now upgrade should work fine.
2779 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002780
2781 // Make a note what happened, so we don't wonder why data was lost
2782 String reason = "Settings rebuilt! Current version: "
2783 + curVersion + " while expected: " + newVersion;
2784 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002785 Settings.Global.DATABASE_DOWNGRADE_REASON,
2786 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002787 }
2788
2789 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002790 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002791 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002792 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002793 globalSettings.setVersionLocked(newVersion);
2794 }
2795
2796 // Set the secure settings version.
2797 secureSettings.setVersionLocked(newVersion);
2798
2799 // Set the system settings version.
2800 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002801 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002802 systemSettings.setVersionLocked(newVersion);
2803 }
2804
2805 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002806 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002807 }
2808
2809 private SettingsState getSecureSettingsLocked(int userId) {
2810 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2811 }
2812
Mark Rathjend891f012017-01-19 04:10:37 +00002813 private SettingsState getSsaidSettingsLocked(int userId) {
2814 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2815 }
2816
Svetoslav683914b2015-01-15 14:22:26 -08002817 private SettingsState getSystemSettingsLocked(int userId) {
2818 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2819 }
2820
Jeff Brown503cffc2015-03-26 18:08:51 -07002821 /**
2822 * You must perform all necessary mutations to bring the settings
2823 * for this user from the old to the new version. When you add a new
2824 * upgrade step you *must* update SETTINGS_VERSION.
2825 *
2826 * This is an example of moving a setting from secure to global.
2827 *
2828 * // v119: Example settings changes.
2829 * if (currentVersion == 118) {
2830 * if (userId == UserHandle.USER_OWNER) {
2831 * // Remove from the secure settings.
2832 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2833 * String name = "example_setting_to_move";
2834 * String value = secureSettings.getSetting(name);
2835 * secureSettings.deleteSetting(name);
2836 *
2837 * // Add to the global settings.
2838 * SettingsState globalSettings = getGlobalSettingsLocked();
2839 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2840 * }
2841 *
2842 * // Update the current version.
2843 * currentVersion = 119;
2844 * }
2845 */
Svetoslav683914b2015-01-15 14:22:26 -08002846 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2847 if (DEBUG) {
2848 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2849 + oldVersion + " to version: " + newVersion);
2850 }
2851
Jeff Brown503cffc2015-03-26 18:08:51 -07002852 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002853
John Spurlocke11ae112015-05-11 16:09:03 -04002854 // v119: Reset zen + ringer mode.
2855 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002856 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002857 final SettingsState globalSettings = getGlobalSettingsLocked();
2858 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002859 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2860 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002861 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002862 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2863 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002864 }
2865 currentVersion = 119;
2866 }
2867
Jason Monk27bbb2d2015-03-31 16:46:39 -04002868 // v120: Add double tap to wake setting.
2869 if (currentVersion == 119) {
2870 SettingsState secureSettings = getSecureSettingsLocked(userId);
2871 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2872 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002873 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002874 SettingsState.SYSTEM_PACKAGE_NAME);
2875
2876 currentVersion = 120;
2877 }
2878
Svetoslav7e0683b2015-08-03 16:02:52 -07002879 if (currentVersion == 120) {
2880 // Before 121, we used a different string encoding logic. We just bump the
2881 // version here; SettingsState knows how to handle pre-version 120 files.
2882 currentVersion = 121;
2883 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002884
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002885 if (currentVersion == 121) {
2886 // Version 122: allow OEMs to set a default payment component in resources.
2887 // Note that we only write the default if no default has been set;
2888 // if there is, we just leave the default at whatever it currently is.
2889 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2890 String defaultComponent = (getContext().getResources().getString(
2891 R.string.def_nfc_payment_component));
2892 Setting currentSetting = secureSettings.getSettingLocked(
2893 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2894 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002895 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002896 secureSettings.insertSettingLocked(
2897 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002898 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002899 }
2900 currentVersion = 122;
2901 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002902
2903 if (currentVersion == 122) {
2904 // Version 123: Adding a default value for the ability to add a user from
2905 // the lock screen.
2906 if (userId == UserHandle.USER_SYSTEM) {
2907 final SettingsState globalSettings = getGlobalSettingsLocked();
2908 Setting currentSetting = globalSettings.getSettingLocked(
2909 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002910 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002911 globalSettings.insertSettingLocked(
2912 Settings.Global.ADD_USERS_WHEN_LOCKED,
2913 getContext().getResources().getBoolean(
2914 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002915 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002916 }
2917 }
2918 currentVersion = 123;
2919 }
Bryce Leebd179282015-12-17 19:01:37 -08002920
2921 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002922 final SettingsState globalSettings = getGlobalSettingsLocked();
2923 String defaultDisabledProfiles = (getContext().getResources().getString(
2924 R.string.def_bluetooth_disabled_profiles));
2925 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002926 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002927 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002928 }
2929
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002930 if (currentVersion == 124) {
2931 // Version 124: allow OEMs to set a default value for whether IME should be
2932 // shown when a physical keyboard is connected.
2933 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2934 Setting currentSetting = secureSettings.getSettingLocked(
2935 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002936 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002937 secureSettings.insertSettingLocked(
2938 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2939 getContext().getResources().getBoolean(
2940 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002941 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002942 }
2943 currentVersion = 125;
2944 }
2945
Ruben Brunk98576cf2016-03-07 18:54:28 -08002946 if (currentVersion == 125) {
2947 // Version 125: Allow OEMs to set the default VR service.
2948 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2949
2950 Setting currentSetting = secureSettings.getSettingLocked(
2951 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002952 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002953 ArraySet<ComponentName> l =
2954 SystemConfig.getInstance().getDefaultVrComponents();
2955
2956 if (l != null && !l.isEmpty()) {
2957 StringBuilder b = new StringBuilder();
2958 boolean start = true;
2959 for (ComponentName c : l) {
2960 if (!start) {
2961 b.append(':');
2962 }
2963 b.append(c.flattenToString());
2964 start = false;
2965 }
2966 secureSettings.insertSettingLocked(
2967 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002968 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002969 }
2970
2971 }
2972 currentVersion = 126;
2973 }
2974
Daniel U02ba6122016-04-01 18:41:42 +01002975 if (currentVersion == 126) {
2976 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2977 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2978 if (mUserManager.isManagedProfile(userId)) {
2979 final SettingsState systemSecureSettings =
2980 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2981
2982 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2983 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002984 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002985 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2986 secureSettings.insertSettingLocked(
2987 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002988 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002989 SettingsState.SYSTEM_PACKAGE_NAME);
2990 }
2991
2992 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2993 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002994 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002995 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2996 secureSettings.insertSettingLocked(
2997 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002998 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002999 SettingsState.SYSTEM_PACKAGE_NAME);
3000 }
3001 }
3002 currentVersion = 127;
3003 }
3004
Steven Ngdc20ba62016-04-26 18:19:04 +01003005 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003006 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003007 currentVersion = 128;
3008 }
3009
Julia Reynolds1f721e12016-07-11 08:50:58 -04003010 if (currentVersion == 128) {
3011 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3012 // the new apps are appended to the list of already approved apps.
3013 final SettingsState systemSecureSettings =
3014 getSecureSettingsLocked(userId);
3015
3016 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3017 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3018 String defaultPolicyAccess = getContext().getResources().getString(
3019 com.android.internal.R.string.config_defaultDndAccessPackages);
3020 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3021 if (policyAccess.isNull()) {
3022 systemSecureSettings.insertSettingLocked(
3023 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003024 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003025 SettingsState.SYSTEM_PACKAGE_NAME);
3026 } else {
3027 StringBuilder currentSetting =
3028 new StringBuilder(policyAccess.getValue());
3029 currentSetting.append(":");
3030 currentSetting.append(defaultPolicyAccess);
3031 systemSecureSettings.updateSettingLocked(
3032 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003033 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003034 SettingsState.SYSTEM_PACKAGE_NAME);
3035 }
3036 }
3037
3038 currentVersion = 129;
3039 }
3040
Dan Sandler71f85e92016-07-20 13:46:05 -04003041 if (currentVersion == 129) {
3042 // default longpress timeout changed from 500 to 400. If unchanged from the old
3043 // default, update to the new default.
3044 final SettingsState systemSecureSettings =
3045 getSecureSettingsLocked(userId);
3046 final String oldValue = systemSecureSettings.getSettingLocked(
3047 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3048 if (TextUtils.equals("500", oldValue)) {
3049 systemSecureSettings.insertSettingLocked(
3050 Settings.Secure.LONG_PRESS_TIMEOUT,
3051 String.valueOf(getContext().getResources().getInteger(
3052 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003053 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003054 }
3055 currentVersion = 130;
3056 }
3057
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003058 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003059 // Split Ambient settings
3060 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3061 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3062 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3063
3064 if (dozeExplicitlyDisabled) {
3065 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003066 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003067 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003068 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003069 }
3070 currentVersion = 131;
3071 }
3072
3073 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003074 // Initialize new multi-press timeout to default value
3075 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3076 final String oldValue = systemSecureSettings.getSettingLocked(
3077 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3078 if (TextUtils.equals(null, oldValue)) {
3079 systemSecureSettings.insertSettingLocked(
3080 Settings.Secure.MULTI_PRESS_TIMEOUT,
3081 String.valueOf(getContext().getResources().getInteger(
3082 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003083 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003084 }
3085
Adrian Roos69741a22016-10-21 14:49:17 -07003086 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003087 }
3088
Adrian Roos69741a22016-10-21 14:49:17 -07003089 if (currentVersion == 132) {
3090 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003091 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3092 String defaultSyncParentSounds = (getContext().getResources()
3093 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3094 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003095 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3096 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003097 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003098 }
3099
Adrian Roos69741a22016-10-21 14:49:17 -07003100 if (currentVersion == 133) {
3101 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003102 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3103 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3104 null) {
3105 String defaultEndButtonBehavior = Integer.toString(getContext()
3106 .getResources().getInteger(R.integer.def_end_button_behavior));
3107 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003108 defaultEndButtonBehavior, null, true,
3109 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003110 }
Adrian Roos69741a22016-10-21 14:49:17 -07003111 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003112 }
3113
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003114 if (currentVersion == 134) {
3115 // Remove setting that specifies if magnification values should be preserved.
3116 // This setting defaulted to true and never has a UI.
3117 getSecureSettingsLocked(userId).deleteSettingLocked(
3118 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3119 currentVersion = 135;
3120 }
3121
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003122 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003123 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003124 currentVersion = 136;
3125 }
3126
Mark Rathjend891f012017-01-19 04:10:37 +00003127 if (currentVersion == 136) {
3128 // Version 136: Store legacy SSAID for all apps currently installed on the
3129 // device as first step in migrating SSAID to be unique per application.
3130
3131 final boolean isUpgrade;
3132 try {
3133 isUpgrade = mPackageManager.isUpgrade();
3134 } catch (RemoteException e) {
3135 throw new IllegalStateException("Package manager not available");
3136 }
3137 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3138 // user data or first boot on a new device should use new ssaid generation.
3139 if (isUpgrade) {
3140 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003141 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3142 userId, Settings.Secure.ANDROID_ID);
3143 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3144 || legacySsaidSetting.getValue() == null) {
3145 throw new IllegalStateException("Legacy ssaid not accessible");
3146 }
3147 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003148
3149 // Fill each uid with the legacy ssaid to be backwards compatible.
3150 final List<PackageInfo> packages;
3151 try {
3152 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3153 } catch (RemoteException e) {
3154 throw new IllegalStateException("Package manager not available");
3155 }
3156
3157 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3158 for (PackageInfo info : packages) {
3159 // Check if the UID already has an entry in the table.
3160 final String uid = Integer.toString(info.applicationInfo.uid);
3161 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3162
3163 if (ssaid.isNull() || ssaid.getValue() == null) {
3164 // Android Id doesn't exist for this package so create it.
3165 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3166 info.packageName);
3167 }
3168 }
3169 }
3170
3171 currentVersion = 137;
3172 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003173 if (currentVersion == 137) {
3174 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3175 // default value set to 1. The user can no longer change the value of this
3176 // setting through the UI.
3177 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3178 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003179 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3180 && secureSetting.getSettingLocked(
3181 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3182
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003183 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3184 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003185 // For managed profiles with profile owners, DevicePolicyManagerService
3186 // may want to set the user restriction in this case
3187 secureSetting.insertSettingLocked(
3188 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3189 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003190 }
3191 currentVersion = 138;
3192 }
Mark Rathjend891f012017-01-19 04:10:37 +00003193
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003194 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003195 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003196 currentVersion = 139;
3197 }
3198
Phil Weaver385912e2017-02-10 10:06:56 -08003199 if (currentVersion == 139) {
3200 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3201 // the user can no longer change the value of this setting through the UI.
3202 // Force to true.
3203 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3204 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3205 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3206 currentVersion = 140;
3207 }
3208
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003209 if (currentVersion == 140) {
3210 // Version 141: One-time grant of notification listener privileges
3211 // to packages specified in overlay.
3212 String defaultListenerAccess = getContext().getResources().getString(
3213 com.android.internal.R.string.config_defaultListenerAccessPackages);
3214 if (defaultListenerAccess != null) {
3215 StringBuffer newListeners = new StringBuffer();
3216 for (String whitelistPkg : defaultListenerAccess.split(":")) {
3217 // Gather all notification listener components for candidate pkgs.
3218 Intent serviceIntent =
3219 new Intent(NotificationListenerService.SERVICE_INTERFACE)
3220 .setPackage(whitelistPkg);
3221 List<ResolveInfo> installedServices =
3222 getContext().getPackageManager().queryIntentServicesAsUser(
3223 serviceIntent,
3224 PackageManager.GET_SERVICES
3225 | PackageManager.GET_META_DATA
3226 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3227 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
3228 userId);
3229
3230 for (int i = 0, count = installedServices.size(); i < count; i++) {
3231 ResolveInfo resolveInfo = installedServices.get(i);
3232 ServiceInfo info = resolveInfo.serviceInfo;
3233 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
3234 .equals(info.permission)) {
3235 continue;
3236 }
3237 newListeners.append(":")
3238 .append(info.getComponentName().flattenToString());
3239 }
3240 }
3241
3242 if (newListeners.length() > 0) {
3243 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3244 final Setting existingSetting = secureSetting.getSettingLocked(
3245 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
3246 if (existingSetting.isNull()) {
3247 secureSetting.insertSettingLocked(
3248 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3249 newListeners.toString(), null, true,
3250 SettingsState.SYSTEM_PACKAGE_NAME);
3251 } else {
3252 StringBuilder currentSetting =
3253 new StringBuilder(existingSetting.getValue());
3254 currentSetting.append(newListeners.toString());
3255 secureSetting.updateSettingLocked(
3256 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3257 currentSetting.toString(), null, true,
3258 SettingsState.SYSTEM_PACKAGE_NAME);
3259 }
3260 }
3261 }
3262 currentVersion = 141;
3263 }
3264
Svet Ganov13701552017-02-23 12:45:17 -08003265 if (currentVersion == 141) {
3266 // Version 141: We added the notion of a default and whether the system set
3267 // the setting. This is used for resetting the internal state and we need
3268 // to make sure this value is updated for the existing settings, otherwise
3269 // we would delete system set settings while they should stay unmodified.
3270 SettingsState globalSettings = getGlobalSettingsLocked();
3271 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3272 globalSettings.persistSyncLocked();
3273
3274 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3275 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3276 secureSettings.persistSyncLocked();
3277
3278 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3279 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3280 systemSettings.persistSyncLocked();
3281
3282 currentVersion = 142;
3283 }
3284
Dan Sandler71f85e92016-07-20 13:46:05 -04003285 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003286 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003287 + newVersion + " left it at "
3288 + currentVersion + " instead; this is probably a bug", new Throwable());
3289 if (DEBUG) {
3290 throw new RuntimeException("db upgrade error");
3291 }
3292 }
3293
Jeff Brown503cffc2015-03-26 18:08:51 -07003294 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003295
Jeff Brown503cffc2015-03-26 18:08:51 -07003296 // Return the current version.
3297 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003298 }
3299 }
Svet Ganov13701552017-02-23 12:45:17 -08003300
3301 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3302 List<String> names = settings.getSettingNamesLocked();
3303 final int nameCount = names.size();
3304 for (int i = 0; i < nameCount; i++) {
3305 String name = names.get(i);
3306 Setting setting = settings.getSettingLocked(name);
3307 if (setting.getDefaultValue() == null) {
3308 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3309 setting.getPackageName());
3310 if (systemSet) {
3311 settings.insertSettingLocked(name, setting.getValue(),
3312 setting.getTag(), true, setting.getPackageName());
3313 }
3314 }
3315 }
3316 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003317 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003318}