blob: 10f84a973c5847c2094f5bbc37a1c70774e53170 [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;
Robin Lee7af9a742017-02-20 14:47:30 +000091import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080094import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010095import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080096import java.util.Set;
97import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080098import javax.crypto.Mac;
99import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700100
Svetoslav Ganove080da92016-12-21 17:10:35 -0800101import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800102import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800103import static android.os.Process.SYSTEM_UID;
104
Svetoslav Ganove080da92016-12-21 17:10:35 -0800105
Svetoslav683914b2015-01-15 14:22:26 -0800106/**
107 * <p>
108 * This class is a content provider that publishes the system settings.
109 * It can be accessed via the content provider APIs or via custom call
110 * commands. The latter is a bit faster and is the preferred way to access
111 * the platform settings.
112 * </p>
113 * <p>
114 * There are three settings types, global (with signature level protection
115 * and shared across users), secure (with signature permission level
116 * protection and per user), and system (with dangerous permission level
117 * protection and per user). Global settings are stored under the device owner.
118 * Each of these settings is represented by a {@link
119 * com.android.providers.settings.SettingsState} object mapped to an integer
120 * key derived from the setting type in the most significant bits and user
121 * id in the least significant bits. Settings are synchronously loaded on
122 * instantiation of a SettingsState and asynchronously persisted on mutation.
123 * Settings are stored in the user specific system directory.
124 * </p>
125 * <p>
126 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
127 * and get a warning. Targeting higher API version prohibits this as the
128 * system settings are not a place for apps to save their state. When a package
129 * is removed the settings it added are deleted. Apps cannot delete system
130 * settings added by the platform. System settings values are validated to
131 * ensure the clients do not put bad values. Global and secure settings are
132 * changed only by trusted parties, therefore no validation is performed. Also
133 * there is a limit on the amount of app specific settings that can be added
134 * to prevent unlimited growth of the system process memory footprint.
135 * </p>
136 */
137@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700139 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700141 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800142
143 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700144
Christopher Tate06efb532012-08-24 15:29:27 -0700145 private static final String TABLE_SYSTEM = "system";
146 private static final String TABLE_SECURE = "secure";
147 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800148
149 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private static final String TABLE_FAVORITES = "favorites";
151 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800152 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
153 private static final String TABLE_BOOKMARKS = "bookmarks";
154 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Svetoslav683914b2015-01-15 14:22:26 -0800156 // The set of removed legacy tables.
157 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700158 static {
Svetoslav683914b2015-01-15 14:22:26 -0800159 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
160 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
161 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
162 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
163 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
164 }
Christopher Tate06efb532012-08-24 15:29:27 -0700165
Svetoslav683914b2015-01-15 14:22:26 -0800166 private static final int MUTATION_OPERATION_INSERT = 1;
167 private static final int MUTATION_OPERATION_DELETE = 2;
168 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800169 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400170
Svetoslav683914b2015-01-15 14:22:26 -0800171 private static final String[] ALL_COLUMNS = new String[] {
172 Settings.NameValueTable._ID,
173 Settings.NameValueTable.NAME,
174 Settings.NameValueTable.VALUE
175 };
176
Svet Ganov53a441c2016-04-19 19:38:00 -0700177 public static final int SETTINGS_TYPE_GLOBAL = 0;
178 public static final int SETTINGS_TYPE_SYSTEM = 1;
179 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000180 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800181
Svet Ganov53a441c2016-04-19 19:38:00 -0700182 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
183 public static final int SETTINGS_TYPE_SHIFT = 28;
184
185 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
186 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700187
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800188 // Changes to these global settings are synchronously persisted
189 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
190 static {
191 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
192 }
193
194 // Changes to these secure settings are synchronously persisted
195 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
196 static {
197 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
198 }
199
Svetoslav683914b2015-01-15 14:22:26 -0800200 // Per user secure settings that moved to the for all users global settings.
201 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
202 static {
203 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700204 }
205
Svetoslav683914b2015-01-15 14:22:26 -0800206 // Per user system settings that moved to the for all users global settings.
207 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
208 static {
209 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700210 }
211
Svetoslav683914b2015-01-15 14:22:26 -0800212 // Per user system settings that moved to the per user secure settings.
213 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
214 static {
215 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700216 }
217
Svetoslav683914b2015-01-15 14:22:26 -0800218 // Per all users global settings that moved to the per user secure settings.
219 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
220 static {
221 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700222 }
223
Svetoslav683914b2015-01-15 14:22:26 -0800224 // Per user secure settings that are cloned for the managed profiles of the user.
225 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
226 static {
227 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700228 }
229
Svetoslav683914b2015-01-15 14:22:26 -0800230 // Per user system settings that are cloned for the managed profiles of the user.
231 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
232 static {
233 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400234 }
235
Andre Lago3fa139c2016-08-04 13:53:44 +0100236 // Per user system settings that are cloned from the profile's parent when a dependency
237 // in {@link Settings.Secure} is set to "1".
238 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
239 static {
240 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
241 }
242
Svetoslav683914b2015-01-15 14:22:26 -0800243 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700244
Svetoslav683914b2015-01-15 14:22:26 -0800245 @GuardedBy("mLock")
246 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700247
Svet Ganova8f90262016-05-10 08:44:48 -0700248 @GuardedBy("mLock")
249 private HandlerThread mHandlerThread;
250
Makoto Onuki73360ab2017-03-17 11:50:13 -0700251 @GuardedBy("mLock")
252 private Handler mHandler;
253
Svetoslav7ec28e82015-05-20 17:01:10 -0700254 // We have to call in the user manager with no lock held,
255 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800256
Svetoslav7ec28e82015-05-20 17:01:10 -0700257 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700258 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700259
Svet Ganov53a441c2016-04-19 19:38:00 -0700260 public static int makeKey(int type, int userId) {
261 return (type << SETTINGS_TYPE_SHIFT) | userId;
262 }
263
264 public static int getTypeFromKey(int key) {
265 return key >>> SETTINGS_TYPE_SHIFT;
266 }
267
268 public static int getUserIdFromKey(int key) {
269 return key & ~SETTINGS_TYPE_MASK;
270 }
271
272 public static String settingTypeToString(int type) {
273 switch (type) {
274 case SETTINGS_TYPE_GLOBAL: {
275 return "SETTINGS_GLOBAL";
276 }
277 case SETTINGS_TYPE_SECURE: {
278 return "SETTINGS_SECURE";
279 }
280 case SETTINGS_TYPE_SYSTEM: {
281 return "SETTINGS_SYSTEM";
282 }
Mark Rathjend891f012017-01-19 04:10:37 +0000283 case SETTINGS_TYPE_SSAID: {
284 return "SETTINGS_SSAID";
285 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700286 default: {
287 return "UNKNOWN";
288 }
289 }
290 }
291
292 public static String keyToString(int key) {
293 return "Key[user=" + getUserIdFromKey(key) + ";type="
294 + settingTypeToString(getTypeFromKey(key)) + "]";
295 }
296
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700297 @Override
298 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800299 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800300 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700301 mUserManager = UserManager.get(getContext());
302 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700303 mHandlerThread = new HandlerThread(LOG_TAG,
304 Process.THREAD_PRIORITY_BACKGROUND);
305 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700306 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800307 mSettingsRegistry = new SettingsRegistry();
308 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700309 mHandler.post(() -> {
310 registerBroadcastReceivers();
311 startWatchingUserRestrictionChanges();
312 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700313 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 return true;
315 }
316
Svetoslav683914b2015-01-15 14:22:26 -0800317 @Override
318 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700319 final int requestingUserId = getRequestingUserId(args);
320 switch (method) {
321 case Settings.CALL_METHOD_GET_GLOBAL: {
322 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700323 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800324 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700325
326 case Settings.CALL_METHOD_GET_SECURE: {
327 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700328 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700329 }
330
331 case Settings.CALL_METHOD_GET_SYSTEM: {
332 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700333 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700334 }
335
336 case Settings.CALL_METHOD_PUT_GLOBAL: {
337 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800338 String tag = getSettingTag(args);
339 final boolean makeDefault = getSettingMakeDefault(args);
340 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 break;
342 }
343
344 case Settings.CALL_METHOD_PUT_SECURE: {
345 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800346 String tag = getSettingTag(args);
347 final boolean makeDefault = getSettingMakeDefault(args);
348 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700349 break;
350 }
351
352 case Settings.CALL_METHOD_PUT_SYSTEM: {
353 String value = getSettingValue(args);
354 insertSystemSetting(name, value, requestingUserId);
355 break;
356 }
357
Svetoslav Ganove080da92016-12-21 17:10:35 -0800358 case Settings.CALL_METHOD_RESET_GLOBAL: {
359 final int mode = getResetModeEnforcingPermission(args);
360 String tag = getSettingTag(args);
361 resetGlobalSetting(requestingUserId, mode, tag);
362 break;
363 }
364
365 case Settings.CALL_METHOD_RESET_SECURE: {
366 final int mode = getResetModeEnforcingPermission(args);
367 String tag = getSettingTag(args);
368 resetSecureSetting(requestingUserId, mode, tag);
369 break;
370 }
371
Svetoslav7ec28e82015-05-20 17:01:10 -0700372 default: {
373 Slog.w(LOG_TAG, "call() with invalid method: " + method);
374 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700375 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700376
Christopher Tate06efb532012-08-24 15:29:27 -0700377 return null;
378 }
379
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800380 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800381 public String getType(Uri uri) {
382 Arguments args = new Arguments(uri, null, null, true);
383 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384 return "vnd.android.cursor.dir/" + args.table;
385 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700386 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700387 }
388 }
389
390 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800391 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
392 String order) {
393 if (DEBUG) {
394 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 }
396
Svetoslav683914b2015-01-15 14:22:26 -0800397 Arguments args = new Arguments(uri, where, whereArgs, true);
398 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700399
Svetoslav683914b2015-01-15 14:22:26 -0800400 // If a legacy table that is gone, done.
401 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
402 return new MatrixCursor(normalizedProjection, 0);
403 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700404
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 switch (args.table) {
406 case TABLE_GLOBAL: {
407 if (args.name != null) {
408 Setting setting = getGlobalSetting(args.name);
409 return packageSettingForQuery(setting, normalizedProjection);
410 } else {
411 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700412 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700413 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700414
Svetoslav7ec28e82015-05-20 17:01:10 -0700415 case TABLE_SECURE: {
416 final int userId = UserHandle.getCallingUserId();
417 if (args.name != null) {
418 Setting setting = getSecureSetting(args.name, userId);
419 return packageSettingForQuery(setting, normalizedProjection);
420 } else {
421 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800422 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700423 }
Svetoslav683914b2015-01-15 14:22:26 -0800424
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 case TABLE_SYSTEM: {
426 final int userId = UserHandle.getCallingUserId();
427 if (args.name != null) {
428 Setting setting = getSystemSetting(args.name, userId);
429 return packageSettingForQuery(setting, normalizedProjection);
430 } else {
431 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800432 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700433 }
Svetoslav683914b2015-01-15 14:22:26 -0800434
Svetoslav7ec28e82015-05-20 17:01:10 -0700435 default: {
436 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700437 }
438 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700439 }
440
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700441 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800442 public Uri insert(Uri uri, ContentValues values) {
443 if (DEBUG) {
444 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700445 }
446
Svetoslav683914b2015-01-15 14:22:26 -0800447 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700448
Svetoslav683914b2015-01-15 14:22:26 -0800449 // If a legacy table that is gone, done.
450 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 return null;
452 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700453
Svetoslav683914b2015-01-15 14:22:26 -0800454 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700455 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800456 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700457 }
458
Svetoslav683914b2015-01-15 14:22:26 -0800459 String value = values.getAsString(Settings.Secure.VALUE);
460
Svetoslav7ec28e82015-05-20 17:01:10 -0700461 switch (table) {
462 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800463 if (insertGlobalSetting(name, value, null, false,
464 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700465 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700466 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700467 } break;
468
469 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800470 if (insertSecureSetting(name, value, null, false,
471 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700472 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
473 }
474 } break;
475
476 case TABLE_SYSTEM: {
477 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
478 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
479 }
480 } break;
481
482 default: {
483 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700484 }
485 }
486
Svetoslav683914b2015-01-15 14:22:26 -0800487 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700488 }
489
490 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800491 public int bulkInsert(Uri uri, ContentValues[] allValues) {
492 if (DEBUG) {
493 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700495
Svetoslav683914b2015-01-15 14:22:26 -0800496 int insertionCount = 0;
497 final int valuesCount = allValues.length;
498 for (int i = 0; i < valuesCount; i++) {
499 ContentValues values = allValues[i];
500 if (insert(uri, values) != null) {
501 insertionCount++;
502 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700503 }
Svetoslav683914b2015-01-15 14:22:26 -0800504
505 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506 }
507
508 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800509 public int delete(Uri uri, String where, String[] whereArgs) {
510 if (DEBUG) {
511 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513
Svetoslav683914b2015-01-15 14:22:26 -0800514 Arguments args = new Arguments(uri, where, whereArgs, false);
515
516 // If a legacy table that is gone, done.
517 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
518 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700519 }
Svetoslav683914b2015-01-15 14:22:26 -0800520
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700521 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800522 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700523 }
Svetoslav683914b2015-01-15 14:22:26 -0800524
Svetoslav7ec28e82015-05-20 17:01:10 -0700525 switch (args.table) {
526 case TABLE_GLOBAL: {
527 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700528 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700529 }
Svetoslav683914b2015-01-15 14:22:26 -0800530
Svetoslav7ec28e82015-05-20 17:01:10 -0700531 case TABLE_SECURE: {
532 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700533 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700534 }
Svetoslav683914b2015-01-15 14:22:26 -0800535
Svetoslav7ec28e82015-05-20 17:01:10 -0700536 case TABLE_SYSTEM: {
537 final int userId = UserHandle.getCallingUserId();
538 return deleteSystemSetting(args.name, userId) ? 1 : 0;
539 }
540
541 default: {
542 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800543 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700544 }
Svetoslav683914b2015-01-15 14:22:26 -0800545 }
546
547 @Override
548 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
549 if (DEBUG) {
550 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700551 }
Svetoslav683914b2015-01-15 14:22:26 -0800552
553 Arguments args = new Arguments(uri, where, whereArgs, false);
554
555 // If a legacy table that is gone, done.
556 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
557 return 0;
558 }
559
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700560 String name = values.getAsString(Settings.Secure.NAME);
561 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800562 return 0;
563 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700564 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800565
Svetoslav7ec28e82015-05-20 17:01:10 -0700566 switch (args.table) {
567 case TABLE_GLOBAL: {
568 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800569 return updateGlobalSetting(args.name, value, null, false,
570 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700571 }
Svetoslav683914b2015-01-15 14:22:26 -0800572
Svetoslav7ec28e82015-05-20 17:01:10 -0700573 case TABLE_SECURE: {
574 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800575 return updateSecureSetting(args.name, value, null, false,
576 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700577 }
Svetoslav683914b2015-01-15 14:22:26 -0800578
Svetoslav7ec28e82015-05-20 17:01:10 -0700579 case TABLE_SYSTEM: {
580 final int userId = UserHandle.getCallingUserId();
581 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
582 }
Svetoslav683914b2015-01-15 14:22:26 -0800583
Svetoslav7ec28e82015-05-20 17:01:10 -0700584 default: {
585 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800586 }
587 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700588 }
589
590 @Override
591 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100592 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
593 if (userId != UserHandle.getCallingUserId()) {
594 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
595 "Access files from the settings of another user");
596 }
597 uri = ContentProvider.getUriWithoutUserId(uri);
598
Andre Lago3fa139c2016-08-04 13:53:44 +0100599 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700600 final String cacheName;
601 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100602 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700603 cacheName = Settings.System.RINGTONE_CACHE;
604 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100605 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700606 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
607 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100608 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700609 cacheName = Settings.System.ALARM_ALERT_CACHE;
610 } else {
611 throw new FileNotFoundException("Direct file access no longer supported; "
612 + "ringtone playback is available through android.media.Ringtone");
613 }
614
Andre Lago3fa139c2016-08-04 13:53:44 +0100615 int actualCacheOwner;
616 // Redirect cache to parent if ringtone setting is owned by profile parent
617 synchronized (mLock) {
618 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
619 cacheRingtoneSetting);
620 }
621 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700622 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
623 }
624
625 private File getRingtoneCacheDir(int userId) {
626 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
627 cacheDir.mkdir();
628 SELinux.restorecon(cacheDir);
629 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700630 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800631
Eugene Suslad72c3972016-12-27 15:49:30 -0800632 /**
633 * Dump all settings as a proto buf.
634 *
635 * @param fd The file to dump to
636 */
637 void dumpProto(@NonNull FileDescriptor fd) {
638 ProtoOutputStream proto = new ProtoOutputStream(fd);
639
640 synchronized (mLock) {
641 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
642
643 }
644
645 proto.flush();
646 }
647
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700648 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800649 synchronized (mLock) {
650 final long identity = Binder.clearCallingIdentity();
651 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700652 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800653 final int userCount = users.size();
654 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700655 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800656 }
657 } finally {
658 Binder.restoreCallingIdentity(identity);
659 }
660 }
661 }
662
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700663 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700664 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800665 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700666 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
667 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700668 if (globalSettings != null) {
669 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800670 pw.println();
671 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700672 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800673 }
674
675 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700676 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
677 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700678 if (secureSettings != null) {
679 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800680 pw.println();
681 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700682 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700683
Svetoslavb505ccc2015-02-17 12:41:04 -0800684 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700685 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
686 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700687 if (systemSettings != null) {
688 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800689 pw.println();
690 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700691 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800692 }
693
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700694 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
695 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800696
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700697 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800698
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700699 for (int i = 0; i < nameCount; i++) {
700 String name = names.get(i);
701 Setting setting = settingsState.getSettingLocked(name);
702 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
703 pw.print(" name:"); pw.print(toDumpString(name));
704 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800705 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700706 }
707 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800708 if (setting.getDefaultValue() != null) {
709 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800710 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800711 }
712 if (setting.getTag() != null) {
713 pw.print(" tag:"); pw.print(setting.getTag());
714 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800715 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700716 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800717 }
718
Svetoslav7e0683b2015-08-03 16:02:52 -0700719 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700720 if (s != null) {
721 return s;
722 }
723 return "{null}";
724 }
725
Svetoslav683914b2015-01-15 14:22:26 -0800726 private void registerBroadcastReceivers() {
727 IntentFilter userFilter = new IntentFilter();
728 userFilter.addAction(Intent.ACTION_USER_REMOVED);
729 userFilter.addAction(Intent.ACTION_USER_STOPPED);
730
731 getContext().registerReceiver(new BroadcastReceiver() {
732 @Override
733 public void onReceive(Context context, Intent intent) {
734 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700735 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800736
737 switch (intent.getAction()) {
738 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700739 synchronized (mLock) {
740 mSettingsRegistry.removeUserStateLocked(userId, true);
741 }
Svetoslav683914b2015-01-15 14:22:26 -0800742 } break;
743
744 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700745 synchronized (mLock) {
746 mSettingsRegistry.removeUserStateLocked(userId, false);
747 }
Svetoslav683914b2015-01-15 14:22:26 -0800748 } break;
749 }
750 }
751 }, userFilter);
752
753 PackageMonitor monitor = new PackageMonitor() {
754 @Override
755 public void onPackageRemoved(String packageName, int uid) {
756 synchronized (mLock) {
757 mSettingsRegistry.onPackageRemovedLocked(packageName,
758 UserHandle.getUserId(uid));
759 }
760 }
Mark Rathjend891f012017-01-19 04:10:37 +0000761
762 @Override
763 public void onUidRemoved(int uid) {
764 synchronized (mLock) {
765 mSettingsRegistry.onUidRemovedLocked(uid);
766 }
767 }
Svetoslav683914b2015-01-15 14:22:26 -0800768 };
769
770 // package changes
771 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
772 UserHandle.ALL, true);
773 }
774
Svet Ganov53a441c2016-04-19 19:38:00 -0700775 private void startWatchingUserRestrictionChanges() {
776 // TODO: The current design of settings looking different based on user restrictions
777 // should be reworked to keep them separate and system code should check the setting
778 // first followed by checking the user restriction before performing an operation.
779 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
780 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
781 Bundle prevRestrictions) -> {
782 // We are changing the settings affected by restrictions to their current
783 // value with a forced update to ensure that all cross profile dependencies
784 // are taken into account. Also make sure the settings update to.. the same
785 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800786 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
787 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700788 final long identity = Binder.clearCallingIdentity();
789 try {
790 synchronized (mLock) {
791 Setting setting = getSecureSetting(
792 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
793 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800794 setting != null ? setting.getValue() : null, null,
795 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700796 }
797 } finally {
798 Binder.restoreCallingIdentity(identity);
799 }
800 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800801 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
802 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 final long identity = Binder.clearCallingIdentity();
804 try {
805 synchronized (mLock) {
806 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800807 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700808 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800809 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700810 }
811 } finally {
812 Binder.restoreCallingIdentity(identity);
813 }
814 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
816 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 final long identity = Binder.clearCallingIdentity();
818 try {
819 synchronized (mLock) {
820 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800821 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700822 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800823 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700824 }
825 } finally {
826 Binder.restoreCallingIdentity(identity);
827 }
828 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800829 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
830 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 final long identity = Binder.clearCallingIdentity();
832 try {
833 synchronized (mLock) {
834 Setting enable = getGlobalSetting(
835 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800836 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700837 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800838 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700839 Setting include = getGlobalSetting(
840 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800841 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700842 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800843 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700844 }
845 } finally {
846 Binder.restoreCallingIdentity(identity);
847 }
848 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800849 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
850 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700851 final long identity = Binder.clearCallingIdentity();
852 try {
853 synchronized (mLock) {
854 Setting setting = getGlobalSetting(
855 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700857 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800858 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700859 }
860 } finally {
861 Binder.restoreCallingIdentity(identity);
862 }
863 }
864 });
865 }
866
Svetoslav7ec28e82015-05-20 17:01:10 -0700867 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800868 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700869 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800870 }
871
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 synchronized (mLock) {
873 // Get the settings.
874 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700875 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800876
Chad Brubaker97bccee2017-01-05 15:51:41 -0800877 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
878 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800879
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800881
Svetoslav7ec28e82015-05-20 17:01:10 -0700882 String[] normalizedProjection = normalizeProjection(projection);
883 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 // Anyone can get the global settings, so no security checks.
886 for (int i = 0; i < nameCount; i++) {
887 String name = names.get(i);
888 Setting setting = settingsState.getSettingLocked(name);
889 appendSettingToCursor(result, setting);
890 }
891
892 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800893 }
Svetoslav683914b2015-01-15 14:22:26 -0800894 }
895
Svetoslav7ec28e82015-05-20 17:01:10 -0700896 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800897 if (DEBUG) {
898 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
899 }
900
Chad Brubaker97bccee2017-01-05 15:51:41 -0800901 // Ensure the caller can access the setting.
902 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
903
Svetoslav683914b2015-01-15 14:22:26 -0800904 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700905 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700906 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700907 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800908 }
Svetoslav683914b2015-01-15 14:22:26 -0800909 }
910
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 private boolean updateGlobalSetting(String name, String value, String tag,
912 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800913 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800914 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
915 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
916 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800917 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
919 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800920 }
921
Svetoslav Ganove080da92016-12-21 17:10:35 -0800922 private boolean insertGlobalSetting(String name, String value, String tag,
923 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800925 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
926 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
927 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700928 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
930 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700931 }
932
Svet Ganov53a441c2016-04-19 19:38:00 -0700933 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800934 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800935 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
936 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800937 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800938 return mutateGlobalSetting(name, null, null, false, requestingUserId,
939 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800940 }
941
Svetoslav Ganove080da92016-12-21 17:10:35 -0800942 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
943 if (DEBUG) {
944 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
945 + mode + ", " + tag + ")");
946 }
947 mutateGlobalSetting(null, null, tag, false, requestingUserId,
948 MUTATION_OPERATION_RESET, false, mode);
949 }
950
951 private boolean mutateGlobalSetting(String name, String value, String tag,
952 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
953 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800954 // Make sure the caller can change the settings - treated as secure.
955 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
956
Svetoslav683914b2015-01-15 14:22:26 -0800957 // Resolve the userId on whose behalf the call is made.
958 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
959
Makoto Onuki28da2e32015-11-20 11:30:44 -0800960 // If this is a setting that is currently restricted for this user, do not allow
961 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800962 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100963 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800964 return false;
965 }
966
967 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700968 synchronized (mLock) {
969 switch (operation) {
970 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800971 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
972 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800973 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700974 }
Svetoslav683914b2015-01-15 14:22:26 -0800975
Svetoslav7ec28e82015-05-20 17:01:10 -0700976 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700977 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800978 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700979 }
Svetoslav683914b2015-01-15 14:22:26 -0800980
Svetoslav7ec28e82015-05-20 17:01:10 -0700981 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800982 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
983 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800984 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800986
987 case MUTATION_OPERATION_RESET: {
988 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
989 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
990 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800991 }
992 }
993
994 return false;
995 }
996
Christopher Tateb218e762017-04-05 16:34:07 -0700997 private PackageInfo getCallingPackageInfo(int userId) {
998 try {
999 return mPackageManager.getPackageInfo(getCallingPackage(),
1000 PackageManager.GET_SIGNATURES, userId);
1001 } catch (RemoteException e) {
1002 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1003 }
1004 }
1005
Svetoslav7ec28e82015-05-20 17:01:10 -07001006 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001007 if (DEBUG) {
1008 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1009 }
1010
1011 // Resolve the userId on whose behalf the call is made.
1012 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1013
Christopher Tateb218e762017-04-05 16:34:07 -07001014 // The relevant "calling package" userId will be the owning userId for some
1015 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1016 // up front who the effective "new SSAID" user ID for that settings name will be.
1017 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1018 Settings.Secure.ANDROID_ID);
1019 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1020
Svetoslav7ec28e82015-05-20 17:01:10 -07001021 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001022 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001023
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001025
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 String[] normalizedProjection = normalizeProjection(projection);
1027 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001028
Svetoslav7ec28e82015-05-20 17:01:10 -07001029 for (int i = 0; i < nameCount; i++) {
1030 String name = names.get(i);
1031 // Determine the owning user as some profile settings are cloned from the parent.
1032 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1033 name);
Svetoslav683914b2015-01-15 14:22:26 -08001034
Alex Klyubin1991f572017-03-03 14:08:36 -08001035 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1036 // This caller is not permitted to access this setting. Pretend the setting
1037 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001038 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 }
Svetoslav683914b2015-01-15 14:22:26 -08001040
Mark Rathjen7599f132017-01-23 14:15:54 -08001041 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001042 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1043 final Setting setting;
1044 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001045 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001046 } else {
1047 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1048 name);
1049 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001050 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001051 }
1052
Svetoslav7ec28e82015-05-20 17:01:10 -07001053 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001054 }
Svetoslav683914b2015-01-15 14:22:26 -08001055 }
1056
Svetoslav7ec28e82015-05-20 17:01:10 -07001057 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001058 if (DEBUG) {
1059 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1060 }
1061
1062 // Resolve the userId on whose behalf the call is made.
1063 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1064
Chad Brubaker97bccee2017-01-05 15:51:41 -08001065 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001066 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001067
Svetoslav683914b2015-01-15 14:22:26 -08001068 // Determine the owning user as some profile settings are cloned from the parent.
1069 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1070
Alex Klyubin1991f572017-03-03 14:08:36 -08001071 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1072 // This caller is not permitted to access this setting. Pretend the setting doesn't
1073 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001074 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1075 owningUserId);
1076 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001077 }
1078
Christopher Tateb218e762017-04-05 16:34:07 -07001079 // As of Android O, the SSAID is read from an app-specific entry in table
1080 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1081 if (isNewSsaidSetting(name)) {
1082 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1083 synchronized (mLock) {
1084 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001085 }
Christopher Tateb218e762017-04-05 16:34:07 -07001086 }
Mark Rathjend891f012017-01-19 04:10:37 +00001087
Christopher Tateb218e762017-04-05 16:34:07 -07001088 // Not the SSAID; do a straight lookup
1089 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001090 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001091 owningUserId, name);
1092 }
Svetoslav683914b2015-01-15 14:22:26 -08001093 }
1094
Mark Rathjend891f012017-01-19 04:10:37 +00001095 private boolean isNewSsaidSetting(String name) {
1096 return Settings.Secure.ANDROID_ID.equals(name)
1097 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1098 }
1099
Christopher Tateb218e762017-04-05 16:34:07 -07001100 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001101 // Get uid of caller (key) used to store ssaid value
1102 String name = Integer.toString(
1103 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1104
1105 if (DEBUG) {
1106 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1107 }
1108
1109 // Retrieve the ssaid from the table if present.
1110 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1111 name);
1112
1113 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001114 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Christopher Tateb218e762017-04-05 16:34:07 -07001115 return mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001116 }
1117
1118 return ssaid;
1119 }
1120
Svetoslav Ganove080da92016-12-21 17:10:35 -08001121 private boolean insertSecureSetting(String name, String value, String tag,
1122 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001123 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001124 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001125 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1126 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001127 }
1128
Svetoslav Ganove080da92016-12-21 17:10:35 -08001129 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1130 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001131 }
1132
Svet Ganov53a441c2016-04-19 19:38:00 -07001133 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001134 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001135 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1136 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001137 }
1138
Svetoslav Ganove080da92016-12-21 17:10:35 -08001139 return mutateSecureSetting(name, null, null, false, requestingUserId,
1140 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001141 }
1142
Svetoslav Ganove080da92016-12-21 17:10:35 -08001143 private boolean updateSecureSetting(String name, String value, String tag,
1144 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001145 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001146 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001147 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1148 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001149 }
1150
Svetoslav Ganove080da92016-12-21 17:10:35 -08001151 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1152 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001153 }
1154
Svetoslav Ganove080da92016-12-21 17:10:35 -08001155 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1156 if (DEBUG) {
1157 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1158 + mode + ", " + tag + ")");
1159 }
1160
1161 mutateSecureSetting(null, null, tag, false, requestingUserId,
1162 MUTATION_OPERATION_RESET, false, mode);
1163 }
1164
1165 private boolean mutateSecureSetting(String name, String value, String tag,
1166 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1167 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001168 // Make sure the caller can change the settings.
1169 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1170
Svetoslav683914b2015-01-15 14:22:26 -08001171 // Resolve the userId on whose behalf the call is made.
1172 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1173
Makoto Onuki28da2e32015-11-20 11:30:44 -08001174 // If this is a setting that is currently restricted for this user, do not allow
1175 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001176 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001177 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001178 return false;
1179 }
1180
1181 // Determine the owning user as some profile settings are cloned from the parent.
1182 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1183
1184 // Only the owning user can change the setting.
1185 if (owningUserId != callingUserId) {
1186 return false;
1187 }
1188
1189 // Special cases for location providers (sigh).
1190 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001191 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1192 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001193 }
1194
1195 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001196 synchronized (mLock) {
1197 switch (operation) {
1198 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001199 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001200 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001201 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001202 }
Svetoslav683914b2015-01-15 14:22:26 -08001203
Svetoslav7ec28e82015-05-20 17:01:10 -07001204 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001205 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001206 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 }
Svetoslav683914b2015-01-15 14:22:26 -08001208
Svetoslav7ec28e82015-05-20 17:01:10 -07001209 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001210 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001211 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001212 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214
1215 case MUTATION_OPERATION_RESET: {
1216 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1217 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1218 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001219 }
1220 }
1221
1222 return false;
1223 }
1224
Svetoslav7ec28e82015-05-20 17:01:10 -07001225 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001226 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001227 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001228 }
1229
1230 // Resolve the userId on whose behalf the call is made.
1231 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1232
Svetoslav7ec28e82015-05-20 17:01:10 -07001233 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001234 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001235
Svetoslav7ec28e82015-05-20 17:01:10 -07001236 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001237
Svetoslav7ec28e82015-05-20 17:01:10 -07001238 String[] normalizedProjection = normalizeProjection(projection);
1239 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001240
Svetoslav7ec28e82015-05-20 17:01:10 -07001241 for (int i = 0; i < nameCount; i++) {
1242 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001243
Svetoslav7ec28e82015-05-20 17:01:10 -07001244 // Determine the owning user as some profile settings are cloned from the parent.
1245 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1246 name);
Svetoslav683914b2015-01-15 14:22:26 -08001247
Svetoslav7ec28e82015-05-20 17:01:10 -07001248 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001249 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001250 appendSettingToCursor(result, setting);
1251 }
1252
1253 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001254 }
Svetoslav683914b2015-01-15 14:22:26 -08001255 }
1256
Svetoslav7ec28e82015-05-20 17:01:10 -07001257 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001258 if (DEBUG) {
1259 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1260 }
1261
1262 // Resolve the userId on whose behalf the call is made.
1263 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1264
Chad Brubaker97bccee2017-01-05 15:51:41 -08001265 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001266 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001267
Svetoslav683914b2015-01-15 14:22:26 -08001268 // Determine the owning user as some profile settings are cloned from the parent.
1269 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1270
1271 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001272 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001273 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 }
Svetoslav683914b2015-01-15 14:22:26 -08001275 }
1276
Svetoslav7ec28e82015-05-20 17:01:10 -07001277 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001278 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001279 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001280 + requestingUserId + ")");
1281 }
1282
Svetoslav7ec28e82015-05-20 17:01:10 -07001283 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001284 }
1285
Svetoslav7ec28e82015-05-20 17:01:10 -07001286 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001287 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001288 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001289 }
1290
Svetoslav7ec28e82015-05-20 17:01:10 -07001291 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001292 }
1293
Svetoslav7ec28e82015-05-20 17:01:10 -07001294 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001295 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001297 + requestingUserId + ")");
1298 }
1299
Svetoslav7ec28e82015-05-20 17:01:10 -07001300 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001301 }
1302
Svetoslav7ec28e82015-05-20 17:01:10 -07001303 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001304 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001305 if (!hasWriteSecureSettingsPermission()) {
1306 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1307 // operation is allowed for the calling package through appops.
1308 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1309 Binder.getCallingUid(), getCallingPackage(), true)) {
1310 return false;
1311 }
Svetoslav683914b2015-01-15 14:22:26 -08001312 }
1313
Svetoslav683914b2015-01-15 14:22:26 -08001314 // Resolve the userId on whose behalf the call is made.
1315 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1316
Svetoslavd8d25e02015-11-20 13:09:26 -08001317 // Enforce what the calling package can mutate the system settings.
1318 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1319
Svetoslav683914b2015-01-15 14:22:26 -08001320 // Determine the owning user as some profile settings are cloned from the parent.
1321 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1322
1323 // Only the owning user id can change the setting.
1324 if (owningUserId != callingUserId) {
1325 return false;
1326 }
1327
Jeff Sharkey413573a2016-02-22 17:52:45 -07001328 // Invalidate any relevant cache files
1329 String cacheName = null;
1330 if (Settings.System.RINGTONE.equals(name)) {
1331 cacheName = Settings.System.RINGTONE_CACHE;
1332 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1333 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1334 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1335 cacheName = Settings.System.ALARM_ALERT_CACHE;
1336 }
1337 if (cacheName != null) {
1338 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001339 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001340 cacheFile.delete();
1341 }
1342
Svetoslav683914b2015-01-15 14:22:26 -08001343 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001344 synchronized (mLock) {
1345 switch (operation) {
1346 case MUTATION_OPERATION_INSERT: {
1347 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001348 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001349 owningUserId, name, value, null, false, getCallingPackage(),
1350 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001351 }
1352
1353 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001354 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001355 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001356 }
1357
1358 case MUTATION_OPERATION_UPDATE: {
1359 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001360 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001361 owningUserId, name, value, null, false, getCallingPackage(),
1362 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001363 }
Svetoslav683914b2015-01-15 14:22:26 -08001364 }
1365
Svetoslav7ec28e82015-05-20 17:01:10 -07001366 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001367 }
Svetoslav683914b2015-01-15 14:22:26 -08001368 }
1369
Billy Lau6ad2d662015-07-18 00:26:58 +01001370 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001371 // Write secure settings is a more protected permission. If caller has it we are good.
1372 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1373 == PackageManager.PERMISSION_GRANTED) {
1374 return true;
1375 }
1376
Svetoslavf41334b2015-06-23 12:06:03 -07001377 return false;
1378 }
1379
Svetoslav683914b2015-01-15 14:22:26 -08001380 private void validateSystemSettingValue(String name, String value) {
1381 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1382 if (validator != null && !validator.validate(value)) {
1383 throw new IllegalArgumentException("Invalid value: " + value
1384 + " for setting: " + name);
1385 }
1386 }
1387
Alex Klyubin1991f572017-03-03 14:08:36 -08001388 /**
1389 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1390 */
1391 private boolean isSecureSettingAccessible(String name, int callingUserId,
1392 int owningUserId) {
1393 // Special case for location (sigh).
1394 // This check is not inside the name-based checks below because this method performs checks
1395 // only if the calling user ID is not the same as the owning user ID.
1396 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1397 return false;
1398 }
1399
1400 switch (name) {
1401 case "bluetooth_address":
1402 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1403 // address in this secure setting. Secure settings can normally be read by any app,
1404 // which thus enables them to bypass the recently introduced restrictions on access
1405 // to device identifiers.
1406 // To mitigate this we make this setting available only to callers privileged to see
1407 // this device's MAC addresses, same as through public API
1408 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1409 return getContext().checkCallingOrSelfPermission(
1410 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1411 default:
1412 return true;
1413 }
1414 }
1415
Svetoslav683914b2015-01-15 14:22:26 -08001416 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1417 int owningUserId) {
1418 // Optimization - location providers are restricted only for managed profiles.
1419 if (callingUserId == owningUserId) {
1420 return false;
1421 }
1422 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1423 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1424 new UserHandle(callingUserId))) {
1425 return true;
1426 }
1427 return false;
1428 }
1429
Makoto Onuki28da2e32015-11-20 11:30:44 -08001430 /**
1431 * Checks whether changing a setting to a value is prohibited by the corresponding user
1432 * restriction.
1433 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001434 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1435 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001436 *
1437 * @return true if the change is prohibited, false if the change is allowed.
1438 */
1439 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001440 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001441 String restriction;
1442 switch (setting) {
1443 case Settings.Secure.LOCATION_MODE:
1444 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1445 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1446 // here normally, but we still protect it here from a direct provider write.
1447 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1448 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1449 break;
1450
1451 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1452 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1453 // a provider, which should be allowed even if the user restriction is set.
1454 if (value != null && value.startsWith("-")) return false;
1455 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1456 break;
1457
1458 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1459 if ("0".equals(value)) return false;
1460 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1461 break;
1462
1463 case Settings.Global.ADB_ENABLED:
1464 if ("0".equals(value)) return false;
1465 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1466 break;
1467
1468 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1469 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1470 if ("1".equals(value)) return false;
1471 restriction = UserManager.ENSURE_VERIFY_APPS;
1472 break;
1473
1474 case Settings.Global.PREFERRED_NETWORK_MODE:
1475 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1476 break;
1477
Victor Chang9c7b7062016-07-12 23:47:29 +01001478 case Settings.Secure.ALWAYS_ON_VPN_APP:
1479 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1480 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001481 final int appId = UserHandle.getAppId(callingUid);
1482 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001483 return false;
1484 }
1485 restriction = UserManager.DISALLOW_CONFIG_VPN;
1486 break;
1487
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001488 case Settings.Global.SAFE_BOOT_DISALLOWED:
1489 if ("1".equals(value)) return false;
1490 restriction = UserManager.DISALLOW_SAFE_BOOT;
1491 break;
1492
Makoto Onuki28da2e32015-11-20 11:30:44 -08001493 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001494 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001495 if ("0".equals(value)) return false;
1496 restriction = UserManager.DISALLOW_DATA_ROAMING;
1497 break;
1498 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001499 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001500 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001501
1502 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001503 }
1504
1505 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1506 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1507 }
1508
1509 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001510 final int parentId;
1511 // Resolves dependency if setting has a dependency and the calling user has a parent
1512 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1513 && (parentId = getGroupParentLocked(userId)) != userId) {
1514 // The setting has a dependency and the profile has a parent
1515 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001516 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1517 final long token = Binder.clearCallingIdentity();
1518 try {
1519 Setting settingObj = getSecureSetting(dependency, userId);
1520 if (settingObj != null && settingObj.getValue().equals("1")) {
1521 return parentId;
1522 }
1523 } finally {
1524 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001525 }
1526 }
Svetoslav683914b2015-01-15 14:22:26 -08001527 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1528 }
1529
1530 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1531 final int parentId = getGroupParentLocked(userId);
1532 if (parentId != userId && keys.contains(name)) {
1533 return parentId;
1534 }
1535 return userId;
1536 }
1537
Svetoslavf41334b2015-06-23 12:06:03 -07001538 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001539 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001540 // System/root/shell can mutate whatever secure settings they want.
1541 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001542 final int appId = UserHandle.getAppId(callingUid);
1543 if (appId == android.os.Process.SYSTEM_UID
1544 || appId == Process.SHELL_UID
1545 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001546 return;
1547 }
1548
1549 switch (operation) {
1550 case MUTATION_OPERATION_INSERT:
1551 // Insert updates.
1552 case MUTATION_OPERATION_UPDATE: {
1553 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1554 return;
1555 }
1556
1557 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001558 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001559
1560 // Privileged apps can do whatever they want.
1561 if ((packageInfo.applicationInfo.privateFlags
1562 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1563 return;
1564 }
1565
1566 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1567 packageInfo.applicationInfo.targetSdkVersion, name);
1568 } break;
1569
1570 case MUTATION_OPERATION_DELETE: {
1571 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1572 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1573 throw new IllegalArgumentException("You cannot delete system defined"
1574 + " secure settings.");
1575 }
1576
1577 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001578 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001579
1580 // Privileged apps can do whatever they want.
1581 if ((packageInfo.applicationInfo.privateFlags &
1582 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1583 return;
1584 }
1585
1586 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1587 packageInfo.applicationInfo.targetSdkVersion, name);
1588 } break;
1589 }
1590 }
1591
Todd Kennedybe0b8892017-02-15 14:13:52 -08001592 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001593 switch (settingsType) {
1594 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001595 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001596 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001597 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001598 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001599 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001600 default:
1601 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1602 }
1603 }
1604
1605 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001606 boolean instantApp;
1607 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1608 instantApp = false;
1609 } else {
1610 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1611 instantApp = ai.isInstantApp();
1612 }
1613 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001614 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001615 } else {
1616 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1617 }
1618 }
1619
1620 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1621 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1622 return;
1623 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001624 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001625 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001626 return;
1627 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08001628 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001629 throw new SecurityException("Setting " + settingName + " is not accessible from"
1630 + " ephemeral package " + getCallingPackage());
1631 }
1632 }
1633
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001634 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1635 // We always use the callingUid for this lookup. This means that if hypothetically an
1636 // app was installed in user A with cross user and in user B as an Instant App
1637 // the app in A would be able to see all the settings in user B. However since cross
1638 // user is a system permission and the app must be uninstalled in B and then installed as
1639 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001640 ApplicationInfo ai = null;
1641 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001642 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1643 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001644 } catch (RemoteException ignored) {
1645 }
1646 if (ai == null) {
1647 throw new IllegalStateException("Failed to lookup info for package "
1648 + getCallingPackage());
1649 }
1650 return ai;
1651 }
1652
Xiaohui Chen43765b72015-08-31 10:57:33 -07001653 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001654 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001655 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1656 getCallingPackage(), 0, userId);
1657 if (packageInfo != null) {
1658 return packageInfo;
1659 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001660 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001661 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001662 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001663 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001664 }
1665
1666 private int getGroupParentLocked(int userId) {
1667 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001668 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001669 return userId;
1670 }
1671 // We are in the same process with the user manager and the returned
1672 // user info is a cached instance, so just look up instead of cache.
1673 final long identity = Binder.clearCallingIdentity();
1674 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001675 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001676 UserInfo userInfo = mUserManager.getProfileParent(userId);
1677 return (userInfo != null) ? userInfo.id : userId;
1678 } finally {
1679 Binder.restoreCallingIdentity(identity);
1680 }
1681 }
1682
Svetoslav683914b2015-01-15 14:22:26 -08001683 private void enforceWritePermission(String permission) {
1684 if (getContext().checkCallingOrSelfPermission(permission)
1685 != PackageManager.PERMISSION_GRANTED) {
1686 throw new SecurityException("Permission denial: writing to settings requires:"
1687 + permission);
1688 }
1689 }
1690
1691 /*
1692 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1693 * This setting contains a list of the currently enabled location providers.
1694 * But helper functions in android.providers.Settings can enable or disable
1695 * a single provider by using a "+" or "-" prefix before the provider name.
1696 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001697 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1698 * is set, the said method will only allow values with the "-" prefix.
1699 *
Svetoslav683914b2015-01-15 14:22:26 -08001700 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001701 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001702 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1703 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001704 if (TextUtils.isEmpty(value)) {
1705 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001706 }
1707
Svetoslav683914b2015-01-15 14:22:26 -08001708 final char prefix = value.charAt(0);
1709 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001710 if (forceNotify) {
1711 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1712 mSettingsRegistry.notifyForSettingsChange(key,
1713 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1714 }
Svetoslav683914b2015-01-15 14:22:26 -08001715 return false;
1716 }
1717
1718 // skip prefix
1719 value = value.substring(1);
1720
Svetoslav7ec28e82015-05-20 17:01:10 -07001721 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001722 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001723 if (settingValue == null) {
1724 return false;
1725 }
Svetoslav683914b2015-01-15 14:22:26 -08001726
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001727 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001728
1729 int index = oldProviders.indexOf(value);
1730 int end = index + value.length();
1731
1732 // check for commas to avoid matching on partial string
1733 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1734 index = -1;
1735 }
1736
1737 // check for commas to avoid matching on partial string
1738 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1739 index = -1;
1740 }
1741
1742 String newProviders;
1743
1744 if (prefix == '+' && index < 0) {
1745 // append the provider to the list if not present
1746 if (oldProviders.length() == 0) {
1747 newProviders = value;
1748 } else {
1749 newProviders = oldProviders + ',' + value;
1750 }
1751 } else if (prefix == '-' && index >= 0) {
1752 // remove the provider from the list if present
1753 // remove leading or trailing comma
1754 if (index > 0) {
1755 index--;
1756 } else if (end < oldProviders.length()) {
1757 end++;
1758 }
1759
1760 newProviders = oldProviders.substring(0, index);
1761 if (end < oldProviders.length()) {
1762 newProviders += oldProviders.substring(end);
1763 }
1764 } else {
1765 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001766 if (forceNotify) {
1767 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1768 mSettingsRegistry.notifyForSettingsChange(key,
1769 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1770 }
Svetoslav683914b2015-01-15 14:22:26 -08001771 return false;
1772 }
1773
Svet Ganov53a441c2016-04-19 19:38:00 -07001774 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001775 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001776 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001777 }
1778
Svetoslav683914b2015-01-15 14:22:26 -08001779 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1780 int targetSdkVersion, String name) {
1781 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1782 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1783 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1784 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1785 + " This will soon become an error.");
1786 } else {
1787 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1788 + " This will soon become an error.");
1789 }
1790 } else {
1791 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1792 throw new IllegalArgumentException("You cannot change private secure settings.");
1793 } else {
1794 throw new IllegalArgumentException("You cannot keep your settings in"
1795 + " the secure settings.");
1796 }
1797 }
1798 }
1799
1800 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1801 if (requestingUserId == UserHandle.getCallingUserId()) {
1802 return requestingUserId;
1803 }
1804 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1805 Binder.getCallingUid(), requestingUserId, false, true,
1806 "get/set setting for user", null);
1807 }
1808
Svet Ganov53a441c2016-04-19 19:38:00 -07001809 private Bundle packageValueForCallResult(Setting setting,
1810 boolean trackingGeneration) {
1811 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001812 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001813 return NULL_SETTING_BUNDLE;
1814 }
1815 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001816 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001817 Bundle result = new Bundle();
1818 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001819 !setting.isNull() ? setting.getValue() : null);
1820 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001821 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001822 }
1823
1824 private static int getRequestingUserId(Bundle args) {
1825 final int callingUserId = UserHandle.getCallingUserId();
1826 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1827 : callingUserId;
1828 }
1829
Svet Ganov53a441c2016-04-19 19:38:00 -07001830 private boolean isTrackingGeneration(Bundle args) {
1831 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1832 }
1833
Svetoslav683914b2015-01-15 14:22:26 -08001834 private static String getSettingValue(Bundle args) {
1835 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1836 }
1837
Svetoslav Ganove080da92016-12-21 17:10:35 -08001838 private static String getSettingTag(Bundle args) {
1839 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1840 }
1841
1842 private static boolean getSettingMakeDefault(Bundle args) {
1843 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1844 }
1845
1846 private static int getResetModeEnforcingPermission(Bundle args) {
1847 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1848 switch (mode) {
1849 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1850 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1851 throw new SecurityException("Only system, shell/root on a "
1852 + "debuggable build can reset to untrusted defaults");
1853 }
1854 return mode;
1855 }
1856 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1857 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1858 throw new SecurityException("Only system, shell/root on a "
1859 + "debuggable build can reset untrusted changes");
1860 }
1861 return mode;
1862 }
1863 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1864 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1865 throw new SecurityException("Only system, shell/root on a "
1866 + "debuggable build can reset to trusted defaults");
1867 }
1868 return mode;
1869 }
1870 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1871 return mode;
1872 }
1873 }
1874 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1875 }
1876
1877 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1878 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1879 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1880 && (appId == SHELL_UID || appId == ROOT_UID));
1881 }
1882
Svetoslav683914b2015-01-15 14:22:26 -08001883 private static String getValidTableOrThrow(Uri uri) {
1884 if (uri.getPathSegments().size() > 0) {
1885 String table = uri.getPathSegments().get(0);
1886 if (DatabaseHelper.isValidTable(table)) {
1887 return table;
1888 }
1889 throw new IllegalArgumentException("Bad root path: " + table);
1890 }
1891 throw new IllegalArgumentException("Invalid URI:" + uri);
1892 }
1893
1894 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001895 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001896 return new MatrixCursor(projection, 0);
1897 }
1898 MatrixCursor cursor = new MatrixCursor(projection, 1);
1899 appendSettingToCursor(cursor, setting);
1900 return cursor;
1901 }
1902
1903 private static String[] normalizeProjection(String[] projection) {
1904 if (projection == null) {
1905 return ALL_COLUMNS;
1906 }
1907
1908 final int columnCount = projection.length;
1909 for (int i = 0; i < columnCount; i++) {
1910 String column = projection[i];
1911 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1912 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001913 }
1914 }
1915
Svetoslav683914b2015-01-15 14:22:26 -08001916 return projection;
1917 }
1918
1919 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001920 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001921 return;
1922 }
Svetoslav683914b2015-01-15 14:22:26 -08001923 final int columnCount = cursor.getColumnCount();
1924
1925 String[] values = new String[columnCount];
1926
1927 for (int i = 0; i < columnCount; i++) {
1928 String column = cursor.getColumnName(i);
1929
1930 switch (column) {
1931 case Settings.NameValueTable._ID: {
1932 values[i] = setting.getId();
1933 } break;
1934
1935 case Settings.NameValueTable.NAME: {
1936 values[i] = setting.getName();
1937 } break;
1938
1939 case Settings.NameValueTable.VALUE: {
1940 values[i] = setting.getValue();
1941 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001942 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001943 }
1944
Svetoslav683914b2015-01-15 14:22:26 -08001945 cursor.addRow(values);
1946 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001947
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001948 private static boolean isKeyValid(String key) {
1949 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1950 }
1951
Svetoslav683914b2015-01-15 14:22:26 -08001952 private static final class Arguments {
1953 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1954 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1955
1956 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1957 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1958
1959 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1960 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1961
1962 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1963 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1964
1965 public final String table;
1966 public final String name;
1967
1968 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1969 final int segmentSize = uri.getPathSegments().size();
1970 switch (segmentSize) {
1971 case 1: {
1972 if (where != null
1973 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1974 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1975 && whereArgs.length == 1) {
1976 name = whereArgs[0];
1977 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001978 return;
Svetoslav683914b2015-01-15 14:22:26 -08001979 } else if (where != null
1980 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1981 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1982 final int startIndex = Math.max(where.indexOf("'"),
1983 where.indexOf("\"")) + 1;
1984 final int endIndex = Math.max(where.lastIndexOf("'"),
1985 where.lastIndexOf("\""));
1986 name = where.substring(startIndex, endIndex);
1987 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001988 return;
Svetoslav683914b2015-01-15 14:22:26 -08001989 } else if (supportAll && where == null && whereArgs == null) {
1990 name = null;
1991 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001992 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001993 }
Svetoslav683914b2015-01-15 14:22:26 -08001994 } break;
1995
Svetoslav28494652015-02-12 14:11:42 -08001996 case 2: {
1997 if (where == null && whereArgs == null) {
1998 name = uri.getPathSegments().get(1);
1999 table = computeTableForSetting(uri, name);
2000 return;
2001 }
2002 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002003 }
Svetoslav28494652015-02-12 14:11:42 -08002004
2005 EventLogTags.writeUnsupportedSettingsQuery(
2006 uri.toSafeString(), where, Arrays.toString(whereArgs));
2007 String message = String.format( "Supported SQL:\n"
2008 + " uri content://some_table/some_property with null where and where args\n"
2009 + " uri content://some_table with query name=? and single name as arg\n"
2010 + " uri content://some_table with query name=some_name and null args\n"
2011 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2012 Arrays.toString(whereArgs));
2013 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002014 }
2015
Svetoslav28494652015-02-12 14:11:42 -08002016 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002017 String table = getValidTableOrThrow(uri);
2018
2019 if (name != null) {
2020 if (sSystemMovedToSecureSettings.contains(name)) {
2021 table = TABLE_SECURE;
2022 }
2023
2024 if (sSystemMovedToGlobalSettings.contains(name)) {
2025 table = TABLE_GLOBAL;
2026 }
2027
2028 if (sSecureMovedToGlobalSettings.contains(name)) {
2029 table = TABLE_GLOBAL;
2030 }
2031
2032 if (sGlobalMovedToSecureSettings.contains(name)) {
2033 table = TABLE_SECURE;
2034 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002035 }
Svetoslav683914b2015-01-15 14:22:26 -08002036
2037 return table;
2038 }
2039 }
2040
2041 final class SettingsRegistry {
2042 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2043
Svetoslav683914b2015-01-15 14:22:26 -08002044 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2045 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2046 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002047 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2048
2049 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002050
2051 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2052
Svet Ganov53a441c2016-04-19 19:38:00 -07002053 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002054
Svetoslav7e0683b2015-08-03 16:02:52 -07002055 private final Handler mHandler;
2056
Svet Ganov53a441c2016-04-19 19:38:00 -07002057 private final BackupManager mBackupManager;
2058
Amith Yamasani39452022017-03-21 15:23:47 -07002059 private String mSettingsCreationBuildId;
2060
Svetoslav683914b2015-01-15 14:22:26 -08002061 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002062 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002063 mGenerationRegistry = new GenerationRegistry(mLock);
2064 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002065 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002066 syncSsaidTableOnStart();
2067 }
2068
2069 private void generateUserKeyLocked(int userId) {
2070 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002071 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002072 final SecureRandom rand = new SecureRandom();
2073 rand.nextBytes(keyBytes);
2074
2075 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002076 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002077
2078 // Store the key in the ssaid table.
2079 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2080 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2081 true, SettingsState.SYSTEM_PACKAGE_NAME);
2082
2083 if (!success) {
2084 throw new IllegalStateException("Ssaid settings not accessible");
2085 }
2086 }
2087
Mark Rathjen7599f132017-01-23 14:15:54 -08002088 private byte[] getLengthPrefix(byte[] data) {
2089 return ByteBuffer.allocate(4).putInt(data.length).array();
2090 }
2091
Christopher Tateb218e762017-04-05 16:34:07 -07002092 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002093 // Read the user's key from the ssaid table.
2094 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002095 if (userKeySetting == null || userKeySetting.isNull()
2096 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002097 // Lazy initialize and store the user key.
2098 generateUserKeyLocked(userId);
2099 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002100 if (userKeySetting == null || userKeySetting.isNull()
2101 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002102 throw new IllegalStateException("User key not accessible");
2103 }
2104 }
2105 final String userKey = userKeySetting.getValue();
2106
2107 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002108 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2109
2110 // Validate that the key is of expected length.
2111 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2112 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002113 throw new IllegalStateException("User key invalid");
2114 }
2115
Mark Rathjen7599f132017-01-23 14:15:54 -08002116 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002117 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002118 m = Mac.getInstance("HmacSHA256");
2119 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002120 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002121 throw new IllegalStateException("HmacSHA256 is not available", e);
2122 } catch (InvalidKeyException e) {
2123 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002124 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002125
2126 // Mac the package name and each of the signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002127 final String packageName = callingPkg.packageName;
2128 byte[] packageNameBytes = packageName.getBytes(StandardCharsets.UTF_8);
Mark Rathjen7599f132017-01-23 14:15:54 -08002129 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2130 m.update(packageNameBytes);
Christopher Tateb218e762017-04-05 16:34:07 -07002131 for (int i = 0; i < callingPkg.signatures.length; i++) {
2132 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002133 m.update(getLengthPrefix(sig), 0, 4);
2134 m.update(sig);
2135 }
Mark Rathjend891f012017-01-19 04:10:37 +00002136
2137 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002138 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2139 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002140
2141 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002142 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002143 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2144 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2145 packageName);
2146
2147 if (!success) {
2148 throw new IllegalStateException("Ssaid settings not accessible");
2149 }
2150
2151 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2152 }
2153
2154 public void syncSsaidTableOnStart() {
2155 synchronized (mLock) {
2156 // Verify that each user's packages and ssaid's are in sync.
2157 for (UserInfo user : mUserManager.getUsers(true)) {
2158 // Get all uids for the user's packages.
2159 final List<PackageInfo> packages;
2160 try {
2161 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2162 } catch (RemoteException e) {
2163 throw new IllegalStateException("Package manager not available");
2164 }
2165 final Set<String> appUids = new HashSet<>();
2166 for (PackageInfo info : packages) {
2167 appUids.add(Integer.toString(info.applicationInfo.uid));
2168 }
2169
2170 // Get all uids currently stored in the user's ssaid table.
2171 final Set<String> ssaidUids = new HashSet<>(
2172 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2173 ssaidUids.remove(SSAID_USER_KEY);
2174
2175 // Perform a set difference for the appUids and ssaidUids.
2176 ssaidUids.removeAll(appUids);
2177
2178 // If there are ssaidUids left over they need to be removed from the table.
2179 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2180 user.id);
2181 for (String uid : ssaidUids) {
2182 ssaidSettings.deleteSettingLocked(uid);
2183 }
2184 }
2185 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002186 }
2187
Svetoslav683914b2015-01-15 14:22:26 -08002188 public List<String> getSettingsNamesLocked(int type, int userId) {
2189 final int key = makeKey(type, userId);
2190 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002191 if (settingsState == null) {
2192 return new ArrayList<String>();
2193 }
Svetoslav683914b2015-01-15 14:22:26 -08002194 return settingsState.getSettingNamesLocked();
2195 }
2196
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002197 public SparseBooleanArray getKnownUsersLocked() {
2198 SparseBooleanArray users = new SparseBooleanArray();
2199 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2200 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2201 }
2202 return users;
2203 }
2204
Svetoslav683914b2015-01-15 14:22:26 -08002205 public SettingsState getSettingsLocked(int type, int userId) {
2206 final int key = makeKey(type, userId);
2207 return peekSettingsStateLocked(key);
2208 }
2209
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002210 public boolean ensureSettingsForUserLocked(int userId) {
2211 // First make sure this user actually exists.
2212 if (mUserManager.getUserInfo(userId) == null) {
2213 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2214 return false;
2215 }
2216
Svetoslav683914b2015-01-15 14:22:26 -08002217 // Migrate the setting for this user if needed.
2218 migrateLegacySettingsForUserIfNeededLocked(userId);
2219
2220 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002221 if (userId == UserHandle.USER_SYSTEM) {
2222 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002223 ensureSettingsStateLocked(globalKey);
2224 }
2225
2226 // Ensure secure settings loaded.
2227 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2228 ensureSettingsStateLocked(secureKey);
2229
2230 // Make sure the secure settings have an Android id set.
2231 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2232 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2233
2234 // Ensure system settings loaded.
2235 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2236 ensureSettingsStateLocked(systemKey);
2237
Mark Rathjend891f012017-01-19 04:10:37 +00002238 // Ensure secure settings loaded.
2239 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2240 ensureSettingsStateLocked(ssaidKey);
2241
Svetoslav683914b2015-01-15 14:22:26 -08002242 // Upgrade the settings to the latest version.
2243 UpgradeController upgrader = new UpgradeController(userId);
2244 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002245 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002246 }
2247
2248 private void ensureSettingsStateLocked(int key) {
2249 if (mSettingsStates.get(key) == null) {
2250 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002251 SettingsState settingsState = new SettingsState(getContext(), mLock,
2252 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002253 mSettingsStates.put(key, settingsState);
2254 }
2255 }
2256
2257 public void removeUserStateLocked(int userId, boolean permanently) {
2258 // We always keep the global settings in memory.
2259
2260 // Nuke system settings.
2261 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2262 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2263 if (systemSettingsState != null) {
2264 if (permanently) {
2265 mSettingsStates.remove(systemKey);
2266 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002267 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002268 systemSettingsState.destroyLocked(new Runnable() {
2269 @Override
2270 public void run() {
2271 mSettingsStates.remove(systemKey);
2272 }
2273 });
2274 }
2275 }
2276
2277 // Nuke secure settings.
2278 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2279 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2280 if (secureSettingsState != null) {
2281 if (permanently) {
2282 mSettingsStates.remove(secureKey);
2283 secureSettingsState.destroyLocked(null);
2284 } else {
2285 secureSettingsState.destroyLocked(new Runnable() {
2286 @Override
2287 public void run() {
2288 mSettingsStates.remove(secureKey);
2289 }
2290 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002291 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002292 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002293
Mark Rathjend891f012017-01-19 04:10:37 +00002294 // Nuke ssaid settings.
2295 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2296 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2297 if (ssaidSettingsState != null) {
2298 if (permanently) {
2299 mSettingsStates.remove(ssaidKey);
2300 ssaidSettingsState.destroyLocked(null);
2301 } else {
2302 ssaidSettingsState.destroyLocked(new Runnable() {
2303 @Override
2304 public void run() {
2305 mSettingsStates.remove(ssaidKey);
2306 }
2307 });
2308 }
2309 }
2310
Svet Ganov53a441c2016-04-19 19:38:00 -07002311 // Nuke generation tracking data
2312 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002313 }
2314
Svetoslav683914b2015-01-15 14:22:26 -08002315 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002316 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2317 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002318 final int key = makeKey(type, userId);
2319
Svetoslav Ganove080da92016-12-21 17:10:35 -08002320 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002321 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002322 if (settingsState != null) {
2323 success = settingsState.insertSettingLocked(name, value,
2324 tag, makeDefault, packageName);
2325 }
Svetoslav683914b2015-01-15 14:22:26 -08002326
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002327 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2328 settingsState.persistSyncLocked();
2329 }
2330
Svet Ganov53a441c2016-04-19 19:38:00 -07002331 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002332 notifyForSettingsChange(key, name);
2333 }
2334 return success;
2335 }
2336
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002337 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2338 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002339 final int key = makeKey(type, userId);
2340
Svetoslav Ganove080da92016-12-21 17:10:35 -08002341 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002342 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002343 if (settingsState != null) {
2344 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002345 }
Svetoslav683914b2015-01-15 14:22:26 -08002346
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002347 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2348 settingsState.persistSyncLocked();
2349 }
2350
Svet Ganov53a441c2016-04-19 19:38:00 -07002351 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002352 notifyForSettingsChange(key, name);
2353 }
2354 return success;
2355 }
2356
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002357 public boolean updateSettingLocked(int type, int userId, String name, String value,
2358 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2359 Set<String> criticalSettings) {
2360 final int key = makeKey(type, userId);
2361
2362 boolean success = false;
2363 SettingsState settingsState = peekSettingsStateLocked(key);
2364 if (settingsState != null) {
2365 success = settingsState.updateSettingLocked(name, value, tag,
2366 makeDefault, packageName);
2367 }
2368
2369 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2370 settingsState.persistSyncLocked();
2371 }
2372
2373 if (forceNotify || success) {
2374 notifyForSettingsChange(key, name);
2375 }
2376
2377 return success;
2378 }
2379
Svetoslav683914b2015-01-15 14:22:26 -08002380 public Setting getSettingLocked(int type, int userId, String name) {
2381 final int key = makeKey(type, userId);
2382
2383 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002384 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002385 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002386 }
Mark Rathjend891f012017-01-19 04:10:37 +00002387
2388 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002389 return settingsState.getSettingLocked(name);
2390 }
2391
Svetoslav Ganove080da92016-12-21 17:10:35 -08002392 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2393 String tag) {
2394 final int key = makeKey(type, userId);
2395 SettingsState settingsState = peekSettingsStateLocked(key);
2396 if (settingsState == null) {
2397 return;
2398 }
2399
2400 switch (mode) {
2401 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2402 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002403 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002404 Setting setting = settingsState.getSettingLocked(name);
2405 if (packageName.equals(setting.getPackageName())) {
2406 if (tag != null && !tag.equals(setting.getTag())) {
2407 continue;
2408 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002409 if (settingsState.resetSettingLocked(name)) {
2410 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002411 notifyForSettingsChange(key, name);
2412 }
2413 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002414 if (someSettingChanged) {
2415 settingsState.persistSyncLocked();
2416 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002417 }
2418 } break;
2419
2420 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2421 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002422 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002423 Setting setting = settingsState.getSettingLocked(name);
2424 if (!SettingsState.isSystemPackage(getContext(),
2425 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002426 if (settingsState.resetSettingLocked(name)) {
2427 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002428 notifyForSettingsChange(key, name);
2429 }
2430 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002431 if (someSettingChanged) {
2432 settingsState.persistSyncLocked();
2433 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002434 }
2435 } break;
2436
2437 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2438 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002439 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002440 Setting setting = settingsState.getSettingLocked(name);
2441 if (!SettingsState.isSystemPackage(getContext(),
2442 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002443 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002444 if (settingsState.resetSettingLocked(name)) {
2445 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002446 notifyForSettingsChange(key, name);
2447 }
2448 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002449 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002450 notifyForSettingsChange(key, name);
2451 }
2452 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002453 if (someSettingChanged) {
2454 settingsState.persistSyncLocked();
2455 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002456 }
2457 } break;
2458
2459 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2460 for (String name : settingsState.getSettingNamesLocked()) {
2461 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002462 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002463 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002464 if (settingsState.resetSettingLocked(name)) {
2465 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002466 notifyForSettingsChange(key, name);
2467 }
2468 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002469 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002470 notifyForSettingsChange(key, name);
2471 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002472 if (someSettingChanged) {
2473 settingsState.persistSyncLocked();
2474 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002475 }
2476 } break;
2477 }
2478 }
2479
Svetoslav683914b2015-01-15 14:22:26 -08002480 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002481 // Global and secure settings are signature protected. Apps signed
2482 // by the platform certificate are generally not uninstalled and
2483 // the main exception is tests. We trust components signed
2484 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002485
2486 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2487 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002488 if (systemSettings != null) {
2489 systemSettings.onPackageRemovedLocked(packageName);
2490 }
Svetoslav683914b2015-01-15 14:22:26 -08002491 }
2492
Mark Rathjend891f012017-01-19 04:10:37 +00002493 public void onUidRemovedLocked(int uid) {
2494 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2495 UserHandle.getUserId(uid));
2496 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2497 }
2498
Svetoslav683914b2015-01-15 14:22:26 -08002499 private SettingsState peekSettingsStateLocked(int key) {
2500 SettingsState settingsState = mSettingsStates.get(key);
2501 if (settingsState != null) {
2502 return settingsState;
2503 }
2504
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002505 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2506 return null;
2507 }
Svetoslav683914b2015-01-15 14:22:26 -08002508 return mSettingsStates.get(key);
2509 }
2510
2511 private void migrateAllLegacySettingsIfNeeded() {
2512 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002513 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002514 File globalFile = getSettingsFile(key);
2515 if (globalFile.exists()) {
2516 return;
2517 }
2518
Amith Yamasani39452022017-03-21 15:23:47 -07002519 mSettingsCreationBuildId = Build.ID;
2520
Svetoslav683914b2015-01-15 14:22:26 -08002521 final long identity = Binder.clearCallingIdentity();
2522 try {
2523 List<UserInfo> users = mUserManager.getUsers(true);
2524
2525 final int userCount = users.size();
2526 for (int i = 0; i < userCount; i++) {
2527 final int userId = users.get(i).id;
2528
2529 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2530 SQLiteDatabase database = dbHelper.getWritableDatabase();
2531 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2532
2533 // Upgrade to the latest version.
2534 UpgradeController upgrader = new UpgradeController(userId);
2535 upgrader.upgradeIfNeededLocked();
2536
2537 // Drop from memory if not a running user.
2538 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2539 removeUserStateLocked(userId, false);
2540 }
2541 }
2542 } finally {
2543 Binder.restoreCallingIdentity(identity);
2544 }
2545 }
2546 }
2547
2548 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2549 // Every user has secure settings and if no file we need to migrate.
2550 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2551 File secureFile = getSettingsFile(secureKey);
2552 if (secureFile.exists()) {
2553 return;
2554 }
2555
2556 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2557 SQLiteDatabase database = dbHelper.getWritableDatabase();
2558
2559 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2560 }
2561
2562 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2563 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002564 // Move over the system settings.
2565 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2566 ensureSettingsStateLocked(systemKey);
2567 SettingsState systemSettings = mSettingsStates.get(systemKey);
2568 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2569 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002570
2571 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002572 // Do this after System settings, since this is the first thing we check when deciding
2573 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002574 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2575 ensureSettingsStateLocked(secureKey);
2576 SettingsState secureSettings = mSettingsStates.get(secureKey);
2577 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2578 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2579 secureSettings.persistSyncLocked();
2580
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002581 // Move over the global settings if owner.
2582 // Do this last, since this is the first thing we check when deciding
2583 // to skip over migration from db to xml for owner user.
2584 if (userId == UserHandle.USER_SYSTEM) {
2585 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2586 ensureSettingsStateLocked(globalKey);
2587 SettingsState globalSettings = mSettingsStates.get(globalKey);
2588 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002589 // If this was just created
2590 if (mSettingsCreationBuildId != null) {
2591 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2592 mSettingsCreationBuildId, null, true,
2593 SettingsState.SYSTEM_PACKAGE_NAME);
2594 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002595 globalSettings.persistSyncLocked();
2596 }
Svetoslav683914b2015-01-15 14:22:26 -08002597
2598 // Drop the database as now all is moved and persisted.
2599 if (DROP_DATABASE_ON_MIGRATION) {
2600 dbHelper.dropDatabase();
2601 } else {
2602 dbHelper.backupDatabase();
2603 }
2604 }
2605
2606 private void migrateLegacySettingsLocked(SettingsState settingsState,
2607 SQLiteDatabase database, String table) {
2608 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2609 queryBuilder.setTables(table);
2610
2611 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2612 null, null, null, null, null);
2613
2614 if (cursor == null) {
2615 return;
2616 }
2617
2618 try {
2619 if (!cursor.moveToFirst()) {
2620 return;
2621 }
2622
2623 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2624 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2625
2626 settingsState.setVersionLocked(database.getVersion());
2627
2628 while (!cursor.isAfterLast()) {
2629 String name = cursor.getString(nameColumnIdx);
2630 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002631 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002632 SettingsState.SYSTEM_PACKAGE_NAME);
2633 cursor.moveToNext();
2634 }
2635 } finally {
2636 cursor.close();
2637 }
2638 }
2639
2640 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2641 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2642
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002643 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002644 return;
2645 }
2646
2647 final int userId = getUserIdFromKey(secureSettings.mKey);
2648
2649 final UserInfo user;
2650 final long identity = Binder.clearCallingIdentity();
2651 try {
2652 user = mUserManager.getUserInfo(userId);
2653 } finally {
2654 Binder.restoreCallingIdentity(identity);
2655 }
2656 if (user == null) {
2657 // Can happen due to races when deleting users - treat as benign.
2658 return;
2659 }
2660
2661 String androidId = Long.toHexString(new SecureRandom().nextLong());
2662 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002663 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002664
2665 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2666 + "] for user " + userId);
2667
2668 // Write a drop box entry if it's a restricted profile
2669 if (user.isRestricted()) {
2670 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2671 Context.DROPBOX_SERVICE);
2672 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2673 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2674 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2675 }
2676 }
2677 }
2678
2679 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002680 final int userId = getUserIdFromKey(key);
2681 Uri uri = getNotificationUriFor(key, name);
2682
Phil Weaver83fec002016-05-11 10:55:29 -07002683 mGenerationRegistry.incrementGeneration(key);
2684
Svetoslav7e0683b2015-08-03 16:02:52 -07002685 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2686 userId, 0, uri).sendToTarget();
2687
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002688 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002689 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2690 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002691 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2692 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002693 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002694 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2695 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002696 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002697
Svet Ganov53a441c2016-04-19 19:38:00 -07002698 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002699 }
2700
Svet Ganov53a441c2016-04-19 19:38:00 -07002701 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002702 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002703 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002704 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002705 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002706 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002707 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002708 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002709 final int key = makeKey(type, profileId);
2710 mGenerationRegistry.incrementGeneration(key);
2711
2712 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002713 }
2714 }
2715 }
Svetoslav683914b2015-01-15 14:22:26 -08002716 }
2717
Svetoslav683914b2015-01-15 14:22:26 -08002718 private boolean isGlobalSettingsKey(int key) {
2719 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2720 }
2721
2722 private boolean isSystemSettingsKey(int key) {
2723 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2724 }
2725
2726 private boolean isSecureSettingsKey(int key) {
2727 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2728 }
2729
Mark Rathjend891f012017-01-19 04:10:37 +00002730 private boolean isSsaidSettingsKey(int key) {
2731 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2732 }
2733
Svetoslav683914b2015-01-15 14:22:26 -08002734 private File getSettingsFile(int key) {
2735 if (isGlobalSettingsKey(key)) {
2736 final int userId = getUserIdFromKey(key);
2737 return new File(Environment.getUserSystemDirectory(userId),
2738 SETTINGS_FILE_GLOBAL);
2739 } else if (isSystemSettingsKey(key)) {
2740 final int userId = getUserIdFromKey(key);
2741 return new File(Environment.getUserSystemDirectory(userId),
2742 SETTINGS_FILE_SYSTEM);
2743 } else if (isSecureSettingsKey(key)) {
2744 final int userId = getUserIdFromKey(key);
2745 return new File(Environment.getUserSystemDirectory(userId),
2746 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002747 } else if (isSsaidSettingsKey(key)) {
2748 final int userId = getUserIdFromKey(key);
2749 return new File(Environment.getUserSystemDirectory(userId),
2750 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002751 } else {
2752 throw new IllegalArgumentException("Invalid settings key:" + key);
2753 }
2754 }
2755
2756 private Uri getNotificationUriFor(int key, String name) {
2757 if (isGlobalSettingsKey(key)) {
2758 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2759 : Settings.Global.CONTENT_URI;
2760 } else if (isSecureSettingsKey(key)) {
2761 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2762 : Settings.Secure.CONTENT_URI;
2763 } else if (isSystemSettingsKey(key)) {
2764 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2765 : Settings.System.CONTENT_URI;
2766 } else {
2767 throw new IllegalArgumentException("Invalid settings key:" + key);
2768 }
2769 }
2770
2771 private int getMaxBytesPerPackageForType(int type) {
2772 switch (type) {
2773 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002774 case SETTINGS_TYPE_SECURE:
2775 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002776 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2777 }
2778
2779 default: {
2780 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2781 }
2782 }
2783 }
2784
Svetoslav7e0683b2015-08-03 16:02:52 -07002785 private final class MyHandler extends Handler {
2786 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2787 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2788
2789 public MyHandler(Looper looper) {
2790 super(looper);
2791 }
2792
2793 @Override
2794 public void handleMessage(Message msg) {
2795 switch (msg.what) {
2796 case MSG_NOTIFY_URI_CHANGED: {
2797 final int userId = msg.arg1;
2798 Uri uri = (Uri) msg.obj;
2799 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2800 if (DEBUG) {
2801 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2802 }
2803 } break;
2804
2805 case MSG_NOTIFY_DATA_CHANGED: {
2806 mBackupManager.dataChanged();
2807 } break;
2808 }
2809 }
2810 }
2811
Svetoslav683914b2015-01-15 14:22:26 -08002812 private final class UpgradeController {
Stephen Chen5d0922f2017-03-27 10:28:04 -07002813 private static final int SETTINGS_VERSION = 143;
Svetoslav683914b2015-01-15 14:22:26 -08002814
2815 private final int mUserId;
2816
2817 public UpgradeController(int userId) {
2818 mUserId = userId;
2819 }
2820
2821 public void upgradeIfNeededLocked() {
2822 // The version of all settings for a user is the same (all users have secure).
2823 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002824 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002825
2826 // Try an update from the current state.
2827 final int oldVersion = secureSettings.getVersionLocked();
2828 final int newVersion = SETTINGS_VERSION;
2829
Svet Ganovc9755bc2015-03-28 13:21:22 -07002830 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002831 if (oldVersion == newVersion) {
2832 return;
2833 }
2834
2835 // Try to upgrade.
2836 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2837
2838 // If upgrade failed start from scratch and upgrade.
2839 if (curVersion != newVersion) {
2840 // Drop state we have for this user.
2841 removeUserStateLocked(mUserId, true);
2842
2843 // Recreate the database.
2844 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2845 SQLiteDatabase database = dbHelper.getWritableDatabase();
2846 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2847
2848 // Migrate the settings for this user.
2849 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2850
2851 // Now upgrade should work fine.
2852 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002853
2854 // Make a note what happened, so we don't wonder why data was lost
2855 String reason = "Settings rebuilt! Current version: "
2856 + curVersion + " while expected: " + newVersion;
2857 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002858 Settings.Global.DATABASE_DOWNGRADE_REASON,
2859 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002860 }
2861
2862 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002863 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002864 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002865 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002866 globalSettings.setVersionLocked(newVersion);
2867 }
2868
2869 // Set the secure settings version.
2870 secureSettings.setVersionLocked(newVersion);
2871
2872 // Set the system settings version.
2873 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002874 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002875 systemSettings.setVersionLocked(newVersion);
2876 }
2877
2878 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002879 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002880 }
2881
2882 private SettingsState getSecureSettingsLocked(int userId) {
2883 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2884 }
2885
Mark Rathjend891f012017-01-19 04:10:37 +00002886 private SettingsState getSsaidSettingsLocked(int userId) {
2887 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2888 }
2889
Svetoslav683914b2015-01-15 14:22:26 -08002890 private SettingsState getSystemSettingsLocked(int userId) {
2891 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2892 }
2893
Jeff Brown503cffc2015-03-26 18:08:51 -07002894 /**
2895 * You must perform all necessary mutations to bring the settings
2896 * for this user from the old to the new version. When you add a new
2897 * upgrade step you *must* update SETTINGS_VERSION.
2898 *
2899 * This is an example of moving a setting from secure to global.
2900 *
2901 * // v119: Example settings changes.
2902 * if (currentVersion == 118) {
2903 * if (userId == UserHandle.USER_OWNER) {
2904 * // Remove from the secure settings.
2905 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2906 * String name = "example_setting_to_move";
2907 * String value = secureSettings.getSetting(name);
2908 * secureSettings.deleteSetting(name);
2909 *
2910 * // Add to the global settings.
2911 * SettingsState globalSettings = getGlobalSettingsLocked();
2912 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2913 * }
2914 *
2915 * // Update the current version.
2916 * currentVersion = 119;
2917 * }
2918 */
Svetoslav683914b2015-01-15 14:22:26 -08002919 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2920 if (DEBUG) {
2921 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2922 + oldVersion + " to version: " + newVersion);
2923 }
2924
Jeff Brown503cffc2015-03-26 18:08:51 -07002925 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002926
John Spurlocke11ae112015-05-11 16:09:03 -04002927 // v119: Reset zen + ringer mode.
2928 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002929 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002930 final SettingsState globalSettings = getGlobalSettingsLocked();
2931 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002932 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2933 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002934 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002935 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2936 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002937 }
2938 currentVersion = 119;
2939 }
2940
Jason Monk27bbb2d2015-03-31 16:46:39 -04002941 // v120: Add double tap to wake setting.
2942 if (currentVersion == 119) {
2943 SettingsState secureSettings = getSecureSettingsLocked(userId);
2944 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2945 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002946 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002947 SettingsState.SYSTEM_PACKAGE_NAME);
2948
2949 currentVersion = 120;
2950 }
2951
Svetoslav7e0683b2015-08-03 16:02:52 -07002952 if (currentVersion == 120) {
2953 // Before 121, we used a different string encoding logic. We just bump the
2954 // version here; SettingsState knows how to handle pre-version 120 files.
2955 currentVersion = 121;
2956 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002957
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002958 if (currentVersion == 121) {
2959 // Version 122: allow OEMs to set a default payment component in resources.
2960 // Note that we only write the default if no default has been set;
2961 // if there is, we just leave the default at whatever it currently is.
2962 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2963 String defaultComponent = (getContext().getResources().getString(
2964 R.string.def_nfc_payment_component));
2965 Setting currentSetting = secureSettings.getSettingLocked(
2966 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2967 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002968 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002969 secureSettings.insertSettingLocked(
2970 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002971 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002972 }
2973 currentVersion = 122;
2974 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002975
2976 if (currentVersion == 122) {
2977 // Version 123: Adding a default value for the ability to add a user from
2978 // the lock screen.
2979 if (userId == UserHandle.USER_SYSTEM) {
2980 final SettingsState globalSettings = getGlobalSettingsLocked();
2981 Setting currentSetting = globalSettings.getSettingLocked(
2982 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002983 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002984 globalSettings.insertSettingLocked(
2985 Settings.Global.ADD_USERS_WHEN_LOCKED,
2986 getContext().getResources().getBoolean(
2987 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002988 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002989 }
2990 }
2991 currentVersion = 123;
2992 }
Bryce Leebd179282015-12-17 19:01:37 -08002993
2994 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002995 final SettingsState globalSettings = getGlobalSettingsLocked();
2996 String defaultDisabledProfiles = (getContext().getResources().getString(
2997 R.string.def_bluetooth_disabled_profiles));
2998 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002999 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003000 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003001 }
3002
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003003 if (currentVersion == 124) {
3004 // Version 124: allow OEMs to set a default value for whether IME should be
3005 // shown when a physical keyboard is connected.
3006 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3007 Setting currentSetting = secureSettings.getSettingLocked(
3008 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003009 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003010 secureSettings.insertSettingLocked(
3011 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3012 getContext().getResources().getBoolean(
3013 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003014 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003015 }
3016 currentVersion = 125;
3017 }
3018
Ruben Brunk98576cf2016-03-07 18:54:28 -08003019 if (currentVersion == 125) {
3020 // Version 125: Allow OEMs to set the default VR service.
3021 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3022
3023 Setting currentSetting = secureSettings.getSettingLocked(
3024 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003025 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003026 ArraySet<ComponentName> l =
3027 SystemConfig.getInstance().getDefaultVrComponents();
3028
3029 if (l != null && !l.isEmpty()) {
3030 StringBuilder b = new StringBuilder();
3031 boolean start = true;
3032 for (ComponentName c : l) {
3033 if (!start) {
3034 b.append(':');
3035 }
3036 b.append(c.flattenToString());
3037 start = false;
3038 }
3039 secureSettings.insertSettingLocked(
3040 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003041 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003042 }
3043
3044 }
3045 currentVersion = 126;
3046 }
3047
Daniel U02ba6122016-04-01 18:41:42 +01003048 if (currentVersion == 126) {
3049 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3050 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3051 if (mUserManager.isManagedProfile(userId)) {
3052 final SettingsState systemSecureSettings =
3053 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3054
3055 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3056 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003057 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003058 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3059 secureSettings.insertSettingLocked(
3060 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003061 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003062 SettingsState.SYSTEM_PACKAGE_NAME);
3063 }
3064
3065 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3066 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003067 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003068 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3069 secureSettings.insertSettingLocked(
3070 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003071 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003072 SettingsState.SYSTEM_PACKAGE_NAME);
3073 }
3074 }
3075 currentVersion = 127;
3076 }
3077
Steven Ngdc20ba62016-04-26 18:19:04 +01003078 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003079 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003080 currentVersion = 128;
3081 }
3082
Julia Reynolds1f721e12016-07-11 08:50:58 -04003083 if (currentVersion == 128) {
3084 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3085 // the new apps are appended to the list of already approved apps.
3086 final SettingsState systemSecureSettings =
3087 getSecureSettingsLocked(userId);
3088
3089 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3090 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3091 String defaultPolicyAccess = getContext().getResources().getString(
3092 com.android.internal.R.string.config_defaultDndAccessPackages);
3093 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3094 if (policyAccess.isNull()) {
3095 systemSecureSettings.insertSettingLocked(
3096 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003097 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003098 SettingsState.SYSTEM_PACKAGE_NAME);
3099 } else {
3100 StringBuilder currentSetting =
3101 new StringBuilder(policyAccess.getValue());
3102 currentSetting.append(":");
3103 currentSetting.append(defaultPolicyAccess);
3104 systemSecureSettings.updateSettingLocked(
3105 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003106 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003107 SettingsState.SYSTEM_PACKAGE_NAME);
3108 }
3109 }
3110
3111 currentVersion = 129;
3112 }
3113
Dan Sandler71f85e92016-07-20 13:46:05 -04003114 if (currentVersion == 129) {
3115 // default longpress timeout changed from 500 to 400. If unchanged from the old
3116 // default, update to the new default.
3117 final SettingsState systemSecureSettings =
3118 getSecureSettingsLocked(userId);
3119 final String oldValue = systemSecureSettings.getSettingLocked(
3120 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3121 if (TextUtils.equals("500", oldValue)) {
3122 systemSecureSettings.insertSettingLocked(
3123 Settings.Secure.LONG_PRESS_TIMEOUT,
3124 String.valueOf(getContext().getResources().getInteger(
3125 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003126 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003127 }
3128 currentVersion = 130;
3129 }
3130
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003131 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003132 // Split Ambient settings
3133 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3134 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3135 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3136
3137 if (dozeExplicitlyDisabled) {
3138 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003139 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003140 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003141 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003142 }
3143 currentVersion = 131;
3144 }
3145
3146 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003147 // Initialize new multi-press timeout to default value
3148 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3149 final String oldValue = systemSecureSettings.getSettingLocked(
3150 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3151 if (TextUtils.equals(null, oldValue)) {
3152 systemSecureSettings.insertSettingLocked(
3153 Settings.Secure.MULTI_PRESS_TIMEOUT,
3154 String.valueOf(getContext().getResources().getInteger(
3155 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003156 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003157 }
3158
Adrian Roos69741a22016-10-21 14:49:17 -07003159 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003160 }
3161
Adrian Roos69741a22016-10-21 14:49:17 -07003162 if (currentVersion == 132) {
3163 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003164 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3165 String defaultSyncParentSounds = (getContext().getResources()
3166 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3167 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003168 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3169 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003170 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003171 }
3172
Adrian Roos69741a22016-10-21 14:49:17 -07003173 if (currentVersion == 133) {
3174 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003175 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3176 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3177 null) {
3178 String defaultEndButtonBehavior = Integer.toString(getContext()
3179 .getResources().getInteger(R.integer.def_end_button_behavior));
3180 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003181 defaultEndButtonBehavior, null, true,
3182 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003183 }
Adrian Roos69741a22016-10-21 14:49:17 -07003184 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003185 }
3186
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003187 if (currentVersion == 134) {
3188 // Remove setting that specifies if magnification values should be preserved.
3189 // This setting defaulted to true and never has a UI.
3190 getSecureSettingsLocked(userId).deleteSettingLocked(
3191 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3192 currentVersion = 135;
3193 }
3194
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003195 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003196 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003197 currentVersion = 136;
3198 }
3199
Mark Rathjend891f012017-01-19 04:10:37 +00003200 if (currentVersion == 136) {
3201 // Version 136: Store legacy SSAID for all apps currently installed on the
3202 // device as first step in migrating SSAID to be unique per application.
3203
3204 final boolean isUpgrade;
3205 try {
3206 isUpgrade = mPackageManager.isUpgrade();
3207 } catch (RemoteException e) {
3208 throw new IllegalStateException("Package manager not available");
3209 }
3210 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3211 // user data or first boot on a new device should use new ssaid generation.
3212 if (isUpgrade) {
3213 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003214 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3215 userId, Settings.Secure.ANDROID_ID);
3216 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3217 || legacySsaidSetting.getValue() == null) {
3218 throw new IllegalStateException("Legacy ssaid not accessible");
3219 }
3220 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003221
3222 // Fill each uid with the legacy ssaid to be backwards compatible.
3223 final List<PackageInfo> packages;
3224 try {
3225 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3226 } catch (RemoteException e) {
3227 throw new IllegalStateException("Package manager not available");
3228 }
3229
3230 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3231 for (PackageInfo info : packages) {
3232 // Check if the UID already has an entry in the table.
3233 final String uid = Integer.toString(info.applicationInfo.uid);
3234 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3235
3236 if (ssaid.isNull() || ssaid.getValue() == null) {
3237 // Android Id doesn't exist for this package so create it.
3238 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3239 info.packageName);
3240 }
3241 }
3242 }
3243
3244 currentVersion = 137;
3245 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003246 if (currentVersion == 137) {
3247 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3248 // default value set to 1. The user can no longer change the value of this
3249 // setting through the UI.
3250 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3251 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003252 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3253 && secureSetting.getSettingLocked(
3254 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3255
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003256 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3257 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003258 // For managed profiles with profile owners, DevicePolicyManagerService
3259 // may want to set the user restriction in this case
3260 secureSetting.insertSettingLocked(
3261 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3262 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003263 }
3264 currentVersion = 138;
3265 }
Mark Rathjend891f012017-01-19 04:10:37 +00003266
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003267 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003268 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003269 currentVersion = 139;
3270 }
3271
Phil Weaver385912e2017-02-10 10:06:56 -08003272 if (currentVersion == 139) {
3273 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3274 // the user can no longer change the value of this setting through the UI.
3275 // Force to true.
3276 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3277 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3278 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3279 currentVersion = 140;
3280 }
3281
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003282 if (currentVersion == 140) {
3283 // Version 141: One-time grant of notification listener privileges
3284 // to packages specified in overlay.
3285 String defaultListenerAccess = getContext().getResources().getString(
3286 com.android.internal.R.string.config_defaultListenerAccessPackages);
3287 if (defaultListenerAccess != null) {
3288 StringBuffer newListeners = new StringBuffer();
3289 for (String whitelistPkg : defaultListenerAccess.split(":")) {
3290 // Gather all notification listener components for candidate pkgs.
3291 Intent serviceIntent =
3292 new Intent(NotificationListenerService.SERVICE_INTERFACE)
3293 .setPackage(whitelistPkg);
3294 List<ResolveInfo> installedServices =
3295 getContext().getPackageManager().queryIntentServicesAsUser(
3296 serviceIntent,
3297 PackageManager.GET_SERVICES
3298 | PackageManager.GET_META_DATA
3299 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3300 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
3301 userId);
3302
3303 for (int i = 0, count = installedServices.size(); i < count; i++) {
3304 ResolveInfo resolveInfo = installedServices.get(i);
3305 ServiceInfo info = resolveInfo.serviceInfo;
3306 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
3307 .equals(info.permission)) {
3308 continue;
3309 }
3310 newListeners.append(":")
3311 .append(info.getComponentName().flattenToString());
3312 }
3313 }
3314
3315 if (newListeners.length() > 0) {
3316 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3317 final Setting existingSetting = secureSetting.getSettingLocked(
3318 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
3319 if (existingSetting.isNull()) {
3320 secureSetting.insertSettingLocked(
3321 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3322 newListeners.toString(), null, true,
3323 SettingsState.SYSTEM_PACKAGE_NAME);
3324 } else {
3325 StringBuilder currentSetting =
3326 new StringBuilder(existingSetting.getValue());
3327 currentSetting.append(newListeners.toString());
3328 secureSetting.updateSettingLocked(
3329 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3330 currentSetting.toString(), null, true,
3331 SettingsState.SYSTEM_PACKAGE_NAME);
3332 }
3333 }
3334 }
3335 currentVersion = 141;
3336 }
3337
Svet Ganov13701552017-02-23 12:45:17 -08003338 if (currentVersion == 141) {
3339 // Version 141: We added the notion of a default and whether the system set
3340 // the setting. This is used for resetting the internal state and we need
3341 // to make sure this value is updated for the existing settings, otherwise
3342 // we would delete system set settings while they should stay unmodified.
3343 SettingsState globalSettings = getGlobalSettingsLocked();
3344 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3345 globalSettings.persistSyncLocked();
3346
3347 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3348 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3349 secureSettings.persistSyncLocked();
3350
3351 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3352 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3353 systemSettings.persistSyncLocked();
3354
3355 currentVersion = 142;
3356 }
3357
Stephen Chen5d0922f2017-03-27 10:28:04 -07003358 if (currentVersion == 142) {
3359 // Version 142: Set a default value for Wi-Fi wakeup feature.
3360 if (userId == UserHandle.USER_SYSTEM) {
3361 final SettingsState globalSettings = getGlobalSettingsLocked();
3362 Setting currentSetting = globalSettings.getSettingLocked(
3363 Settings.Global.WIFI_WAKEUP_ENABLED);
3364 if (currentSetting.isNull()) {
3365 globalSettings.insertSettingLocked(
3366 Settings.Global.WIFI_WAKEUP_ENABLED,
3367 getContext().getResources().getBoolean(
3368 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3369 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3370 }
3371 }
3372
3373 currentVersion = 143;
3374 }
3375
Dan Sandler71f85e92016-07-20 13:46:05 -04003376 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003377 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003378 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003379 + currentVersion +
3380 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3381 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003382 if (DEBUG) {
3383 throw new RuntimeException("db upgrade error");
3384 }
3385 }
3386
Jeff Brown503cffc2015-03-26 18:08:51 -07003387 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003388
Jeff Brown503cffc2015-03-26 18:08:51 -07003389 // Return the current version.
3390 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003391 }
3392 }
Svet Ganov13701552017-02-23 12:45:17 -08003393
3394 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3395 List<String> names = settings.getSettingNamesLocked();
3396 final int nameCount = names.size();
3397 for (int i = 0; i < nameCount; i++) {
3398 String name = names.get(i);
3399 Setting setting = settings.getSettingLocked(name);
3400 if (setting.getDefaultValue() == null) {
3401 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3402 setting.getPackageName());
3403 if (systemSet) {
3404 settings.insertSettingLocked(name, setting.getValue(),
3405 setting.getTag(), true, setting.getPackageName());
3406 }
3407 }
3408 }
3409 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003410 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003411}