blob: 258c96cf40be5094ebc827f7c31bf848773a000c [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;
Kweku Adamsb0886f32017-10-31 15:32:09 -070021import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070022import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070023import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080024import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070025import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080026import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070027import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentValues;
29import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070030import android.content.Intent;
31import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070033import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080034import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070036import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070037import android.content.res.Resources;
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;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010063import android.provider.Settings.Global;
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 Rathjen7599f132017-01-23 14:15:54 -080084import java.nio.ByteBuffer;
85import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000086import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080087import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070088import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000090import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000091import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080092import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080093import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010094import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Set;
96import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080097import javax.crypto.Mac;
98import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070099
Svetoslav Ganove080da92016-12-21 17:10:35 -0800100import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800101import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800102import static android.os.Process.SYSTEM_UID;
103
Svetoslav Ganove080da92016-12-21 17:10:35 -0800104
Svetoslav683914b2015-01-15 14:22:26 -0800105/**
106 * <p>
107 * This class is a content provider that publishes the system settings.
108 * It can be accessed via the content provider APIs or via custom call
109 * commands. The latter is a bit faster and is the preferred way to access
110 * the platform settings.
111 * </p>
112 * <p>
113 * There are three settings types, global (with signature level protection
114 * and shared across users), secure (with signature permission level
115 * protection and per user), and system (with dangerous permission level
116 * protection and per user). Global settings are stored under the device owner.
117 * Each of these settings is represented by a {@link
118 * com.android.providers.settings.SettingsState} object mapped to an integer
119 * key derived from the setting type in the most significant bits and user
120 * id in the least significant bits. Settings are synchronously loaded on
121 * instantiation of a SettingsState and asynchronously persisted on mutation.
122 * Settings are stored in the user specific system directory.
123 * </p>
124 * <p>
125 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
126 * and get a warning. Targeting higher API version prohibits this as the
127 * system settings are not a place for apps to save their state. When a package
128 * is removed the settings it added are deleted. Apps cannot delete system
129 * settings added by the platform. System settings values are validated to
130 * ensure the clients do not put bad values. Global and secure settings are
131 * changed only by trusted parties, therefore no validation is performed. Also
132 * there is a limit on the amount of app specific settings that can be added
133 * to prevent unlimited growth of the system process memory footprint.
134 * </p>
135 */
136@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700137public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700138 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700140 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800141
142 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700143
Christopher Tate06efb532012-08-24 15:29:27 -0700144 private static final String TABLE_SYSTEM = "system";
145 private static final String TABLE_SECURE = "secure";
146 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800147
148 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 private static final String TABLE_FAVORITES = "favorites";
150 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800151 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
152 private static final String TABLE_BOOKMARKS = "bookmarks";
153 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Svetoslav683914b2015-01-15 14:22:26 -0800155 // The set of removed legacy tables.
156 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700157 static {
Svetoslav683914b2015-01-15 14:22:26 -0800158 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
159 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
160 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
161 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
162 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
163 }
Christopher Tate06efb532012-08-24 15:29:27 -0700164
Svetoslav683914b2015-01-15 14:22:26 -0800165 private static final int MUTATION_OPERATION_INSERT = 1;
166 private static final int MUTATION_OPERATION_DELETE = 2;
167 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800168 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400169
Svetoslav683914b2015-01-15 14:22:26 -0800170 private static final String[] ALL_COLUMNS = new String[] {
171 Settings.NameValueTable._ID,
172 Settings.NameValueTable.NAME,
173 Settings.NameValueTable.VALUE
174 };
175
Svet Ganov53a441c2016-04-19 19:38:00 -0700176 public static final int SETTINGS_TYPE_GLOBAL = 0;
177 public static final int SETTINGS_TYPE_SYSTEM = 1;
178 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000179 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800180
Svet Ganov53a441c2016-04-19 19:38:00 -0700181 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
182 public static final int SETTINGS_TYPE_SHIFT = 28;
183
184 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
185 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700186
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700187 // Overlay specified settings whitelisted for Instant Apps
188 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
189 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
190 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
191
192 static {
193 for (String name : Resources.getSystem().getStringArray(
194 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
195 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
196 }
197 for (String name : Resources.getSystem().getStringArray(
198 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
199 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
200 }
201 for (String name : Resources.getSystem().getStringArray(
202 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
203 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
204 }
205 }
206
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800207 // Changes to these global settings are synchronously persisted
208 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
209 static {
210 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
211 }
212
213 // Changes to these secure settings are synchronously persisted
214 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
215 static {
216 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
217 }
218
Svetoslav683914b2015-01-15 14:22:26 -0800219 // Per user secure settings that moved to the for all users global settings.
220 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
221 static {
222 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700223 }
224
Svetoslav683914b2015-01-15 14:22:26 -0800225 // Per user system settings that moved to the for all users global settings.
226 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
227 static {
228 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229 }
230
Svetoslav683914b2015-01-15 14:22:26 -0800231 // Per user system settings that moved to the per user secure settings.
232 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
233 static {
234 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700235 }
236
Svetoslav683914b2015-01-15 14:22:26 -0800237 // Per all users global settings that moved to the per user secure settings.
238 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
239 static {
240 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700241 }
242
Svetoslav683914b2015-01-15 14:22:26 -0800243 // Per user secure settings that are cloned for the managed profiles of the user.
244 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
245 static {
246 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247 }
248
Svetoslav683914b2015-01-15 14:22:26 -0800249 // Per user system settings that are cloned for the managed profiles of the user.
250 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
251 static {
252 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400253 }
254
Andre Lago3fa139c2016-08-04 13:53:44 +0100255 // Per user system settings that are cloned from the profile's parent when a dependency
256 // in {@link Settings.Secure} is set to "1".
257 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
258 static {
259 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
260 }
261
Svetoslav683914b2015-01-15 14:22:26 -0800262 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700263
Svetoslav683914b2015-01-15 14:22:26 -0800264 @GuardedBy("mLock")
265 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700266
Svet Ganova8f90262016-05-10 08:44:48 -0700267 @GuardedBy("mLock")
268 private HandlerThread mHandlerThread;
269
Makoto Onuki73360ab2017-03-17 11:50:13 -0700270 @GuardedBy("mLock")
271 private Handler mHandler;
272
Svetoslav7ec28e82015-05-20 17:01:10 -0700273 // We have to call in the user manager with no lock held,
274 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800275
Svetoslav7ec28e82015-05-20 17:01:10 -0700276 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700277 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700278
Svet Ganov53a441c2016-04-19 19:38:00 -0700279 public static int makeKey(int type, int userId) {
280 return (type << SETTINGS_TYPE_SHIFT) | userId;
281 }
282
283 public static int getTypeFromKey(int key) {
284 return key >>> SETTINGS_TYPE_SHIFT;
285 }
286
287 public static int getUserIdFromKey(int key) {
288 return key & ~SETTINGS_TYPE_MASK;
289 }
290
291 public static String settingTypeToString(int type) {
292 switch (type) {
293 case SETTINGS_TYPE_GLOBAL: {
294 return "SETTINGS_GLOBAL";
295 }
296 case SETTINGS_TYPE_SECURE: {
297 return "SETTINGS_SECURE";
298 }
299 case SETTINGS_TYPE_SYSTEM: {
300 return "SETTINGS_SYSTEM";
301 }
Mark Rathjend891f012017-01-19 04:10:37 +0000302 case SETTINGS_TYPE_SSAID: {
303 return "SETTINGS_SSAID";
304 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700305 default: {
306 return "UNKNOWN";
307 }
308 }
309 }
310
311 public static String keyToString(int key) {
312 return "Key[user=" + getUserIdFromKey(key) + ";type="
313 + settingTypeToString(getTypeFromKey(key)) + "]";
314 }
315
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700316 @Override
317 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800318 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800319 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700320 mUserManager = UserManager.get(getContext());
321 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700322 mHandlerThread = new HandlerThread(LOG_TAG,
323 Process.THREAD_PRIORITY_BACKGROUND);
324 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700325 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800326 mSettingsRegistry = new SettingsRegistry();
327 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700328 mHandler.post(() -> {
329 registerBroadcastReceivers();
330 startWatchingUserRestrictionChanges();
331 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700332 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333 return true;
334 }
335
Svetoslav683914b2015-01-15 14:22:26 -0800336 @Override
337 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700338 final int requestingUserId = getRequestingUserId(args);
339 switch (method) {
340 case Settings.CALL_METHOD_GET_GLOBAL: {
341 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700342 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800343 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700344
345 case Settings.CALL_METHOD_GET_SECURE: {
346 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700347 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700348 }
349
350 case Settings.CALL_METHOD_GET_SYSTEM: {
351 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700352 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700353 }
354
355 case Settings.CALL_METHOD_PUT_GLOBAL: {
356 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800357 String tag = getSettingTag(args);
358 final boolean makeDefault = getSettingMakeDefault(args);
359 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700360 break;
361 }
362
363 case Settings.CALL_METHOD_PUT_SECURE: {
364 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800365 String tag = getSettingTag(args);
366 final boolean makeDefault = getSettingMakeDefault(args);
367 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700368 break;
369 }
370
371 case Settings.CALL_METHOD_PUT_SYSTEM: {
372 String value = getSettingValue(args);
373 insertSystemSetting(name, value, requestingUserId);
374 break;
375 }
376
Svetoslav Ganove080da92016-12-21 17:10:35 -0800377 case Settings.CALL_METHOD_RESET_GLOBAL: {
378 final int mode = getResetModeEnforcingPermission(args);
379 String tag = getSettingTag(args);
380 resetGlobalSetting(requestingUserId, mode, tag);
381 break;
382 }
383
384 case Settings.CALL_METHOD_RESET_SECURE: {
385 final int mode = getResetModeEnforcingPermission(args);
386 String tag = getSettingTag(args);
387 resetSecureSetting(requestingUserId, mode, tag);
388 break;
389 }
390
Svetoslav7ec28e82015-05-20 17:01:10 -0700391 default: {
392 Slog.w(LOG_TAG, "call() with invalid method: " + method);
393 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700394 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700395
Christopher Tate06efb532012-08-24 15:29:27 -0700396 return null;
397 }
398
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800399 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800400 public String getType(Uri uri) {
401 Arguments args = new Arguments(uri, null, null, true);
402 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403 return "vnd.android.cursor.dir/" + args.table;
404 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406 }
407 }
408
409 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800410 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
411 String order) {
412 if (DEBUG) {
413 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700414 }
415
Svetoslav683914b2015-01-15 14:22:26 -0800416 Arguments args = new Arguments(uri, where, whereArgs, true);
417 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700418
Svetoslav683914b2015-01-15 14:22:26 -0800419 // If a legacy table that is gone, done.
420 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
421 return new MatrixCursor(normalizedProjection, 0);
422 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700423
Svetoslav7ec28e82015-05-20 17:01:10 -0700424 switch (args.table) {
425 case TABLE_GLOBAL: {
426 if (args.name != null) {
427 Setting setting = getGlobalSetting(args.name);
428 return packageSettingForQuery(setting, normalizedProjection);
429 } else {
430 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700431 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700432 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700433
Svetoslav7ec28e82015-05-20 17:01:10 -0700434 case TABLE_SECURE: {
435 final int userId = UserHandle.getCallingUserId();
436 if (args.name != null) {
437 Setting setting = getSecureSetting(args.name, userId);
438 return packageSettingForQuery(setting, normalizedProjection);
439 } else {
440 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800441 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700442 }
Svetoslav683914b2015-01-15 14:22:26 -0800443
Svetoslav7ec28e82015-05-20 17:01:10 -0700444 case TABLE_SYSTEM: {
445 final int userId = UserHandle.getCallingUserId();
446 if (args.name != null) {
447 Setting setting = getSystemSetting(args.name, userId);
448 return packageSettingForQuery(setting, normalizedProjection);
449 } else {
450 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800451 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700452 }
Svetoslav683914b2015-01-15 14:22:26 -0800453
Svetoslav7ec28e82015-05-20 17:01:10 -0700454 default: {
455 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700456 }
457 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700458 }
459
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800461 public Uri insert(Uri uri, ContentValues values) {
462 if (DEBUG) {
463 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700464 }
465
Svetoslav683914b2015-01-15 14:22:26 -0800466 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700467
Svetoslav683914b2015-01-15 14:22:26 -0800468 // If a legacy table that is gone, done.
469 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 return null;
471 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700472
Svetoslav683914b2015-01-15 14:22:26 -0800473 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700474 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800475 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700476 }
477
Svetoslav683914b2015-01-15 14:22:26 -0800478 String value = values.getAsString(Settings.Secure.VALUE);
479
Svetoslav7ec28e82015-05-20 17:01:10 -0700480 switch (table) {
481 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800482 if (insertGlobalSetting(name, value, null, false,
483 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700484 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700485 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700486 } break;
487
488 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800489 if (insertSecureSetting(name, value, null, false,
490 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700491 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
492 }
493 } break;
494
495 case TABLE_SYSTEM: {
496 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
497 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
498 }
499 } break;
500
501 default: {
502 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700503 }
504 }
505
Svetoslav683914b2015-01-15 14:22:26 -0800506 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700507 }
508
509 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800510 public int bulkInsert(Uri uri, ContentValues[] allValues) {
511 if (DEBUG) {
512 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514
Svetoslav683914b2015-01-15 14:22:26 -0800515 int insertionCount = 0;
516 final int valuesCount = allValues.length;
517 for (int i = 0; i < valuesCount; i++) {
518 ContentValues values = allValues[i];
519 if (insert(uri, values) != null) {
520 insertionCount++;
521 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700522 }
Svetoslav683914b2015-01-15 14:22:26 -0800523
524 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700525 }
526
527 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800528 public int delete(Uri uri, String where, String[] whereArgs) {
529 if (DEBUG) {
530 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700532
Svetoslav683914b2015-01-15 14:22:26 -0800533 Arguments args = new Arguments(uri, where, whereArgs, false);
534
535 // If a legacy table that is gone, done.
536 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
537 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700538 }
Svetoslav683914b2015-01-15 14:22:26 -0800539
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700540 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800541 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700542 }
Svetoslav683914b2015-01-15 14:22:26 -0800543
Svetoslav7ec28e82015-05-20 17:01:10 -0700544 switch (args.table) {
545 case TABLE_GLOBAL: {
546 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700547 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700548 }
Svetoslav683914b2015-01-15 14:22:26 -0800549
Svetoslav7ec28e82015-05-20 17:01:10 -0700550 case TABLE_SECURE: {
551 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700552 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700553 }
Svetoslav683914b2015-01-15 14:22:26 -0800554
Svetoslav7ec28e82015-05-20 17:01:10 -0700555 case TABLE_SYSTEM: {
556 final int userId = UserHandle.getCallingUserId();
557 return deleteSystemSetting(args.name, userId) ? 1 : 0;
558 }
559
560 default: {
561 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800562 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700563 }
Svetoslav683914b2015-01-15 14:22:26 -0800564 }
565
566 @Override
567 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
568 if (DEBUG) {
569 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700570 }
Svetoslav683914b2015-01-15 14:22:26 -0800571
572 Arguments args = new Arguments(uri, where, whereArgs, false);
573
574 // If a legacy table that is gone, done.
575 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
576 return 0;
577 }
578
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700579 String name = values.getAsString(Settings.Secure.NAME);
580 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800581 return 0;
582 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700583 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800584
Svetoslav7ec28e82015-05-20 17:01:10 -0700585 switch (args.table) {
586 case TABLE_GLOBAL: {
587 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800588 return updateGlobalSetting(args.name, value, null, false,
589 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700590 }
Svetoslav683914b2015-01-15 14:22:26 -0800591
Svetoslav7ec28e82015-05-20 17:01:10 -0700592 case TABLE_SECURE: {
593 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800594 return updateSecureSetting(args.name, value, null, false,
595 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700596 }
Svetoslav683914b2015-01-15 14:22:26 -0800597
Svetoslav7ec28e82015-05-20 17:01:10 -0700598 case TABLE_SYSTEM: {
599 final int userId = UserHandle.getCallingUserId();
600 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
601 }
Svetoslav683914b2015-01-15 14:22:26 -0800602
Svetoslav7ec28e82015-05-20 17:01:10 -0700603 default: {
604 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800605 }
606 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700607 }
608
609 @Override
610 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100611 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
612 if (userId != UserHandle.getCallingUserId()) {
613 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
614 "Access files from the settings of another user");
615 }
616 uri = ContentProvider.getUriWithoutUserId(uri);
617
Andre Lago3fa139c2016-08-04 13:53:44 +0100618 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700619 final String cacheName;
620 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100621 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700622 cacheName = Settings.System.RINGTONE_CACHE;
623 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100624 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700625 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
626 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100627 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700628 cacheName = Settings.System.ALARM_ALERT_CACHE;
629 } else {
630 throw new FileNotFoundException("Direct file access no longer supported; "
631 + "ringtone playback is available through android.media.Ringtone");
632 }
633
Andre Lago3fa139c2016-08-04 13:53:44 +0100634 int actualCacheOwner;
635 // Redirect cache to parent if ringtone setting is owned by profile parent
636 synchronized (mLock) {
637 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
638 cacheRingtoneSetting);
639 }
640 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700641 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
642 }
643
644 private File getRingtoneCacheDir(int userId) {
645 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
646 cacheDir.mkdir();
647 SELinux.restorecon(cacheDir);
648 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700649 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800650
Eugene Suslad72c3972016-12-27 15:49:30 -0800651 /**
652 * Dump all settings as a proto buf.
653 *
654 * @param fd The file to dump to
655 */
656 void dumpProto(@NonNull FileDescriptor fd) {
657 ProtoOutputStream proto = new ProtoOutputStream(fd);
658
659 synchronized (mLock) {
660 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800661 }
662
663 proto.flush();
664 }
665
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700666 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800667 synchronized (mLock) {
668 final long identity = Binder.clearCallingIdentity();
669 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700670 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800671 final int userCount = users.size();
672 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700673 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800674 }
675 } finally {
676 Binder.restoreCallingIdentity(identity);
677 }
678 }
679 }
680
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700681 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700682 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800683 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700684 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
685 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700686 if (globalSettings != null) {
687 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800688 pw.println();
689 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700690 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800691 }
692
693 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700694 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
695 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700696 if (secureSettings != null) {
697 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800698 pw.println();
699 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700700 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700701
Svetoslavb505ccc2015-02-17 12:41:04 -0800702 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700703 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
704 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700705 if (systemSettings != null) {
706 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800707 pw.println();
708 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700709 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800710 }
711
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700712 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
713 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800714
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700715 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800716
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700717 for (int i = 0; i < nameCount; i++) {
718 String name = names.get(i);
719 Setting setting = settingsState.getSettingLocked(name);
720 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
721 pw.print(" name:"); pw.print(toDumpString(name));
722 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800723 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700724 }
725 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800726 if (setting.getDefaultValue() != null) {
727 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800728 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800729 }
730 if (setting.getTag() != null) {
731 pw.print(" tag:"); pw.print(setting.getTag());
732 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800733 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700734 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800735 }
736
Svetoslav7e0683b2015-08-03 16:02:52 -0700737 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700738 if (s != null) {
739 return s;
740 }
741 return "{null}";
742 }
743
Svetoslav683914b2015-01-15 14:22:26 -0800744 private void registerBroadcastReceivers() {
745 IntentFilter userFilter = new IntentFilter();
746 userFilter.addAction(Intent.ACTION_USER_REMOVED);
747 userFilter.addAction(Intent.ACTION_USER_STOPPED);
748
749 getContext().registerReceiver(new BroadcastReceiver() {
750 @Override
751 public void onReceive(Context context, Intent intent) {
752 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700753 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800754
755 switch (intent.getAction()) {
756 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700757 synchronized (mLock) {
758 mSettingsRegistry.removeUserStateLocked(userId, true);
759 }
Svetoslav683914b2015-01-15 14:22:26 -0800760 } break;
761
762 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700763 synchronized (mLock) {
764 mSettingsRegistry.removeUserStateLocked(userId, false);
765 }
Svetoslav683914b2015-01-15 14:22:26 -0800766 } break;
767 }
768 }
769 }, userFilter);
770
771 PackageMonitor monitor = new PackageMonitor() {
772 @Override
773 public void onPackageRemoved(String packageName, int uid) {
774 synchronized (mLock) {
775 mSettingsRegistry.onPackageRemovedLocked(packageName,
776 UserHandle.getUserId(uid));
777 }
778 }
Mark Rathjend891f012017-01-19 04:10:37 +0000779
780 @Override
781 public void onUidRemoved(int uid) {
782 synchronized (mLock) {
783 mSettingsRegistry.onUidRemovedLocked(uid);
784 }
785 }
Svetoslav683914b2015-01-15 14:22:26 -0800786 };
787
788 // package changes
789 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
790 UserHandle.ALL, true);
791 }
792
Svet Ganov53a441c2016-04-19 19:38:00 -0700793 private void startWatchingUserRestrictionChanges() {
794 // TODO: The current design of settings looking different based on user restrictions
795 // should be reworked to keep them separate and system code should check the setting
796 // first followed by checking the user restriction before performing an operation.
797 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
798 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
799 Bundle prevRestrictions) -> {
800 // We are changing the settings affected by restrictions to their current
801 // value with a forced update to ensure that all cross profile dependencies
802 // are taken into account. Also make sure the settings update to.. the same
803 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800804 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
805 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700806 final long identity = Binder.clearCallingIdentity();
807 try {
808 synchronized (mLock) {
809 Setting setting = getSecureSetting(
810 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
811 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800812 setting != null ? setting.getValue() : null, null,
813 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700814 }
815 } finally {
816 Binder.restoreCallingIdentity(identity);
817 }
818 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800819 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
820 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700821 final long identity = Binder.clearCallingIdentity();
822 try {
823 synchronized (mLock) {
824 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800825 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700826 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800827 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700828 }
829 } finally {
830 Binder.restoreCallingIdentity(identity);
831 }
832 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800833 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
834 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700835 final long identity = Binder.clearCallingIdentity();
836 try {
837 synchronized (mLock) {
838 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800839 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700840 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800841 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700842 }
843 } finally {
844 Binder.restoreCallingIdentity(identity);
845 }
846 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800847 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
848 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700849 final long identity = Binder.clearCallingIdentity();
850 try {
851 synchronized (mLock) {
852 Setting enable = getGlobalSetting(
853 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800854 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700855 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700857 Setting include = getGlobalSetting(
858 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800859 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700860 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800861 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700862 }
863 } finally {
864 Binder.restoreCallingIdentity(identity);
865 }
866 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800867 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
868 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700869 final long identity = Binder.clearCallingIdentity();
870 try {
871 synchronized (mLock) {
872 Setting setting = getGlobalSetting(
873 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800874 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700875 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800876 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700877 }
878 } finally {
879 Binder.restoreCallingIdentity(identity);
880 }
881 }
882 });
883 }
884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800886 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800888 }
889
Svetoslav7ec28e82015-05-20 17:01:10 -0700890 synchronized (mLock) {
891 // Get the settings.
892 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700893 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800894
Chad Brubaker97bccee2017-01-05 15:51:41 -0800895 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
896 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800897
Svetoslav7ec28e82015-05-20 17:01:10 -0700898 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800899
Svetoslav7ec28e82015-05-20 17:01:10 -0700900 String[] normalizedProjection = normalizeProjection(projection);
901 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800902
Svetoslav7ec28e82015-05-20 17:01:10 -0700903 // Anyone can get the global settings, so no security checks.
904 for (int i = 0; i < nameCount; i++) {
905 String name = names.get(i);
906 Setting setting = settingsState.getSettingLocked(name);
907 appendSettingToCursor(result, setting);
908 }
909
910 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800911 }
Svetoslav683914b2015-01-15 14:22:26 -0800912 }
913
Svetoslav7ec28e82015-05-20 17:01:10 -0700914 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800915 if (DEBUG) {
916 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
917 }
918
Chad Brubakera6830e72017-04-28 17:34:36 -0700919 // Ensure the caller can access the setting.
920 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
921
Svetoslav683914b2015-01-15 14:22:26 -0800922 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700923 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700924 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700925 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800926 }
Svetoslav683914b2015-01-15 14:22:26 -0800927 }
928
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 private boolean updateGlobalSetting(String name, String value, String tag,
930 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800931 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800932 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
933 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
934 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800935 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800936 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
937 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800938 }
939
Svetoslav Ganove080da92016-12-21 17:10:35 -0800940 private boolean insertGlobalSetting(String name, String value, String tag,
941 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700942 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800943 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
944 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
945 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700946 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800947 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
948 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700949 }
950
Svet Ganov53a441c2016-04-19 19:38:00 -0700951 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800952 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800953 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
954 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800955 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800956 return mutateGlobalSetting(name, null, null, false, requestingUserId,
957 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800958 }
959
Svetoslav Ganove080da92016-12-21 17:10:35 -0800960 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
961 if (DEBUG) {
962 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
963 + mode + ", " + tag + ")");
964 }
965 mutateGlobalSetting(null, null, tag, false, requestingUserId,
966 MUTATION_OPERATION_RESET, false, mode);
967 }
968
969 private boolean mutateGlobalSetting(String name, String value, String tag,
970 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
971 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800972 // Make sure the caller can change the settings - treated as secure.
973 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
974
Svetoslav683914b2015-01-15 14:22:26 -0800975 // Resolve the userId on whose behalf the call is made.
976 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
977
Makoto Onuki28da2e32015-11-20 11:30:44 -0800978 // If this is a setting that is currently restricted for this user, do not allow
979 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800980 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100981 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800982 return false;
983 }
984
985 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700986 synchronized (mLock) {
987 switch (operation) {
988 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800989 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
990 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800991 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700992 }
Svetoslav683914b2015-01-15 14:22:26 -0800993
Svetoslav7ec28e82015-05-20 17:01:10 -0700994 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700995 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800996 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 }
Svetoslav683914b2015-01-15 14:22:26 -0800998
Svetoslav7ec28e82015-05-20 17:01:10 -0700999 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1001 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001002 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001003 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001004
1005 case MUTATION_OPERATION_RESET: {
1006 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1007 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1008 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001009 }
1010 }
1011
1012 return false;
1013 }
1014
Christopher Tateb218e762017-04-05 16:34:07 -07001015 private PackageInfo getCallingPackageInfo(int userId) {
1016 try {
1017 return mPackageManager.getPackageInfo(getCallingPackage(),
1018 PackageManager.GET_SIGNATURES, userId);
1019 } catch (RemoteException e) {
1020 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1021 }
1022 }
1023
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001025 if (DEBUG) {
1026 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1027 }
1028
1029 // Resolve the userId on whose behalf the call is made.
1030 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1031
Christopher Tateb218e762017-04-05 16:34:07 -07001032 // The relevant "calling package" userId will be the owning userId for some
1033 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1034 // up front who the effective "new SSAID" user ID for that settings name will be.
1035 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1036 Settings.Secure.ANDROID_ID);
1037 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1038
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001040 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001041
Svetoslav7ec28e82015-05-20 17:01:10 -07001042 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001043
Svetoslav7ec28e82015-05-20 17:01:10 -07001044 String[] normalizedProjection = normalizeProjection(projection);
1045 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001046
Svetoslav7ec28e82015-05-20 17:01:10 -07001047 for (int i = 0; i < nameCount; i++) {
1048 String name = names.get(i);
1049 // Determine the owning user as some profile settings are cloned from the parent.
1050 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1051 name);
Svetoslav683914b2015-01-15 14:22:26 -08001052
Alex Klyubin1991f572017-03-03 14:08:36 -08001053 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1054 // This caller is not permitted to access this setting. Pretend the setting
1055 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001056 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001057 }
Svetoslav683914b2015-01-15 14:22:26 -08001058
Mark Rathjen7599f132017-01-23 14:15:54 -08001059 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001060 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1061 final Setting setting;
1062 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001063 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001064 } else {
1065 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1066 name);
1067 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001068 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001069 }
1070
Svetoslav7ec28e82015-05-20 17:01:10 -07001071 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001072 }
Svetoslav683914b2015-01-15 14:22:26 -08001073 }
1074
Svetoslav7ec28e82015-05-20 17:01:10 -07001075 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001076 if (DEBUG) {
1077 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1078 }
1079
1080 // Resolve the userId on whose behalf the call is made.
1081 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1082
Chad Brubakera6830e72017-04-28 17:34:36 -07001083 // Ensure the caller can access the setting.
1084 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1085
Svetoslav683914b2015-01-15 14:22:26 -08001086 // Determine the owning user as some profile settings are cloned from the parent.
1087 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1088
Alex Klyubin1991f572017-03-03 14:08:36 -08001089 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1090 // This caller is not permitted to access this setting. Pretend the setting doesn't
1091 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001092 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1093 owningUserId);
1094 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001095 }
1096
Christopher Tateb218e762017-04-05 16:34:07 -07001097 // As of Android O, the SSAID is read from an app-specific entry in table
1098 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1099 if (isNewSsaidSetting(name)) {
1100 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1101 synchronized (mLock) {
1102 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001103 }
Christopher Tateb218e762017-04-05 16:34:07 -07001104 }
Mark Rathjend891f012017-01-19 04:10:37 +00001105
Christopher Tateb218e762017-04-05 16:34:07 -07001106 // Not the SSAID; do a straight lookup
1107 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001108 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001109 owningUserId, name);
1110 }
Svetoslav683914b2015-01-15 14:22:26 -08001111 }
1112
Mark Rathjend891f012017-01-19 04:10:37 +00001113 private boolean isNewSsaidSetting(String name) {
1114 return Settings.Secure.ANDROID_ID.equals(name)
1115 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1116 }
1117
Christopher Tateb218e762017-04-05 16:34:07 -07001118 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001119 // Get uid of caller (key) used to store ssaid value
1120 String name = Integer.toString(
1121 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1122
1123 if (DEBUG) {
1124 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1125 }
1126
1127 // Retrieve the ssaid from the table if present.
1128 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1129 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001130 // If the app is an Instant App use its stored SSAID instead of our own.
1131 final String instantSsaid;
1132 final long token = Binder.clearCallingIdentity();
1133 try {
1134 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1135 owningUserId);
1136 } catch (RemoteException e) {
1137 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1138 return null;
1139 } finally {
1140 Binder.restoreCallingIdentity(token);
1141 }
Svet Ganov96c99462017-05-05 14:27:13 -07001142
1143 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1144 SETTINGS_TYPE_SSAID, owningUserId);
1145
Chad Brubaker0d277a72017-04-12 16:56:53 -07001146 if (instantSsaid != null) {
1147 // Use the stored value if it is still valid.
1148 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001149 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001150 }
1151 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001152 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1153 true, callingPkg.packageName);
1154 if (!success) {
1155 throw new IllegalStateException("Failed to update instant app android id");
1156 }
Svet Ganov96c99462017-05-05 14:27:13 -07001157 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1158 owningUserId, name);
1159 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001160 }
Mark Rathjend891f012017-01-19 04:10:37 +00001161
1162 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001163 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001164 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1165 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001166 }
1167
Svet Ganov96c99462017-05-05 14:27:13 -07001168 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1169 }
1170
1171 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1172 // SSAID settings are located in a dedicated table for internal bookkeeping
1173 // but for the world they reside in the secure table, so adjust the key here.
1174 // We have a special name when looking it up but want the world to see it as
1175 // "android_id".
1176 if (ssaidSetting != null) {
1177 return settingsState.new Setting(ssaidSetting) {
1178 @Override
1179 public int getKey() {
1180 final int userId = getUserIdFromKey(super.getKey());
1181 return makeKey(SETTINGS_TYPE_SECURE, userId);
1182 }
1183
1184 @Override
1185 public String getName() {
1186 return Settings.Secure.ANDROID_ID;
1187 }
1188 };
1189 }
1190 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001191 }
1192
Svetoslav Ganove080da92016-12-21 17:10:35 -08001193 private boolean insertSecureSetting(String name, String value, String tag,
1194 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001195 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001196 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001197 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1198 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001200 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1201 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001202 }
1203
Svet Ganov53a441c2016-04-19 19:38:00 -07001204 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001205 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001206 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1207 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001208 }
1209
Svetoslav Ganove080da92016-12-21 17:10:35 -08001210 return mutateSecureSetting(name, null, null, false, requestingUserId,
1211 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001212 }
1213
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214 private boolean updateSecureSetting(String name, String value, String tag,
1215 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001216 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001217 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001218 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1219 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001220 }
1221
Svetoslav Ganove080da92016-12-21 17:10:35 -08001222 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1223 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001224 }
1225
Svetoslav Ganove080da92016-12-21 17:10:35 -08001226 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1227 if (DEBUG) {
1228 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1229 + mode + ", " + tag + ")");
1230 }
1231
1232 mutateSecureSetting(null, null, tag, false, requestingUserId,
1233 MUTATION_OPERATION_RESET, false, mode);
1234 }
1235
1236 private boolean mutateSecureSetting(String name, String value, String tag,
1237 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1238 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001239 // Make sure the caller can change the settings.
1240 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1241
Svetoslav683914b2015-01-15 14:22:26 -08001242 // Resolve the userId on whose behalf the call is made.
1243 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1244
Makoto Onuki28da2e32015-11-20 11:30:44 -08001245 // If this is a setting that is currently restricted for this user, do not allow
1246 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001247 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001248 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001249 return false;
1250 }
1251
1252 // Determine the owning user as some profile settings are cloned from the parent.
1253 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1254
1255 // Only the owning user can change the setting.
1256 if (owningUserId != callingUserId) {
1257 return false;
1258 }
1259
1260 // Special cases for location providers (sigh).
1261 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001262 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1263 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001264 }
1265
1266 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001267 synchronized (mLock) {
1268 switch (operation) {
1269 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001270 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001271 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001272 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001273 }
Svetoslav683914b2015-01-15 14:22:26 -08001274
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001276 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001277 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001278 }
Svetoslav683914b2015-01-15 14:22:26 -08001279
Svetoslav7ec28e82015-05-20 17:01:10 -07001280 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001281 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001282 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001283 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001284 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001285
1286 case MUTATION_OPERATION_RESET: {
1287 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1288 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1289 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001290 }
1291 }
1292
1293 return false;
1294 }
1295
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001297 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001298 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001299 }
1300
1301 // Resolve the userId on whose behalf the call is made.
1302 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1303
Svetoslav7ec28e82015-05-20 17:01:10 -07001304 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001305 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001306
Svetoslav7ec28e82015-05-20 17:01:10 -07001307 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001308
Svetoslav7ec28e82015-05-20 17:01:10 -07001309 String[] normalizedProjection = normalizeProjection(projection);
1310 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001311
Svetoslav7ec28e82015-05-20 17:01:10 -07001312 for (int i = 0; i < nameCount; i++) {
1313 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001314
Svetoslav7ec28e82015-05-20 17:01:10 -07001315 // Determine the owning user as some profile settings are cloned from the parent.
1316 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1317 name);
Svetoslav683914b2015-01-15 14:22:26 -08001318
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001320 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001321 appendSettingToCursor(result, setting);
1322 }
1323
1324 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001325 }
Svetoslav683914b2015-01-15 14:22:26 -08001326 }
1327
Svetoslav7ec28e82015-05-20 17:01:10 -07001328 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001329 if (DEBUG) {
1330 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1331 }
1332
1333 // Resolve the userId on whose behalf the call is made.
1334 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1335
Chad Brubakera6830e72017-04-28 17:34:36 -07001336 // Ensure the caller can access the setting.
1337 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001338
Svetoslav683914b2015-01-15 14:22:26 -08001339 // Determine the owning user as some profile settings are cloned from the parent.
1340 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1341
1342 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001343 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001344 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001345 }
Svetoslav683914b2015-01-15 14:22:26 -08001346 }
1347
Svetoslav7ec28e82015-05-20 17:01:10 -07001348 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001349 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001350 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001351 + requestingUserId + ")");
1352 }
1353
Svetoslav7ec28e82015-05-20 17:01:10 -07001354 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001355 }
1356
Svetoslav7ec28e82015-05-20 17:01:10 -07001357 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001358 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001359 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001360 }
1361
Svetoslav7ec28e82015-05-20 17:01:10 -07001362 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001363 }
1364
Svetoslav7ec28e82015-05-20 17:01:10 -07001365 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001366 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001367 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001368 + requestingUserId + ")");
1369 }
1370
Svetoslav7ec28e82015-05-20 17:01:10 -07001371 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001372 }
1373
Svetoslav7ec28e82015-05-20 17:01:10 -07001374 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001375 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001376 if (!hasWriteSecureSettingsPermission()) {
1377 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1378 // operation is allowed for the calling package through appops.
1379 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1380 Binder.getCallingUid(), getCallingPackage(), true)) {
1381 return false;
1382 }
Svetoslav683914b2015-01-15 14:22:26 -08001383 }
1384
Svetoslav683914b2015-01-15 14:22:26 -08001385 // Resolve the userId on whose behalf the call is made.
1386 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1387
Svetoslavd8d25e02015-11-20 13:09:26 -08001388 // Enforce what the calling package can mutate the system settings.
1389 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1390
Svetoslav683914b2015-01-15 14:22:26 -08001391 // Determine the owning user as some profile settings are cloned from the parent.
1392 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1393
1394 // Only the owning user id can change the setting.
1395 if (owningUserId != callingUserId) {
1396 return false;
1397 }
1398
Jeff Sharkey413573a2016-02-22 17:52:45 -07001399 // Invalidate any relevant cache files
1400 String cacheName = null;
1401 if (Settings.System.RINGTONE.equals(name)) {
1402 cacheName = Settings.System.RINGTONE_CACHE;
1403 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1404 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1405 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1406 cacheName = Settings.System.ALARM_ALERT_CACHE;
1407 }
1408 if (cacheName != null) {
1409 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001410 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001411 cacheFile.delete();
1412 }
1413
Svetoslav683914b2015-01-15 14:22:26 -08001414 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001415 synchronized (mLock) {
1416 switch (operation) {
1417 case MUTATION_OPERATION_INSERT: {
1418 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001419 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001420 owningUserId, name, value, null, false, getCallingPackage(),
1421 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001422 }
1423
1424 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001425 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001426 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001427 }
1428
1429 case MUTATION_OPERATION_UPDATE: {
1430 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001431 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001432 owningUserId, name, value, null, false, getCallingPackage(),
1433 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001434 }
Svetoslav683914b2015-01-15 14:22:26 -08001435 }
1436
Svetoslav7ec28e82015-05-20 17:01:10 -07001437 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001438 }
Svetoslav683914b2015-01-15 14:22:26 -08001439 }
1440
Billy Lau6ad2d662015-07-18 00:26:58 +01001441 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001442 // Write secure settings is a more protected permission. If caller has it we are good.
1443 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1444 == PackageManager.PERMISSION_GRANTED) {
1445 return true;
1446 }
1447
Svetoslavf41334b2015-06-23 12:06:03 -07001448 return false;
1449 }
1450
Svetoslav683914b2015-01-15 14:22:26 -08001451 private void validateSystemSettingValue(String name, String value) {
1452 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1453 if (validator != null && !validator.validate(value)) {
1454 throw new IllegalArgumentException("Invalid value: " + value
1455 + " for setting: " + name);
1456 }
1457 }
1458
Alex Klyubin1991f572017-03-03 14:08:36 -08001459 /**
1460 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1461 */
1462 private boolean isSecureSettingAccessible(String name, int callingUserId,
1463 int owningUserId) {
1464 // Special case for location (sigh).
1465 // This check is not inside the name-based checks below because this method performs checks
1466 // only if the calling user ID is not the same as the owning user ID.
1467 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1468 return false;
1469 }
1470
1471 switch (name) {
1472 case "bluetooth_address":
1473 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1474 // address in this secure setting. Secure settings can normally be read by any app,
1475 // which thus enables them to bypass the recently introduced restrictions on access
1476 // to device identifiers.
1477 // To mitigate this we make this setting available only to callers privileged to see
1478 // this device's MAC addresses, same as through public API
1479 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1480 return getContext().checkCallingOrSelfPermission(
1481 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1482 default:
1483 return true;
1484 }
1485 }
1486
Svetoslav683914b2015-01-15 14:22:26 -08001487 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1488 int owningUserId) {
1489 // Optimization - location providers are restricted only for managed profiles.
1490 if (callingUserId == owningUserId) {
1491 return false;
1492 }
1493 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1494 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1495 new UserHandle(callingUserId))) {
1496 return true;
1497 }
1498 return false;
1499 }
1500
Makoto Onuki28da2e32015-11-20 11:30:44 -08001501 /**
1502 * Checks whether changing a setting to a value is prohibited by the corresponding user
1503 * restriction.
1504 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001505 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1506 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001507 *
1508 * @return true if the change is prohibited, false if the change is allowed.
1509 */
1510 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001511 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001512 String restriction;
1513 switch (setting) {
1514 case Settings.Secure.LOCATION_MODE:
1515 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1516 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1517 // here normally, but we still protect it here from a direct provider write.
1518 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1519 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1520 break;
1521
1522 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1523 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1524 // a provider, which should be allowed even if the user restriction is set.
1525 if (value != null && value.startsWith("-")) return false;
1526 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1527 break;
1528
1529 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1530 if ("0".equals(value)) return false;
1531 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1532 break;
1533
1534 case Settings.Global.ADB_ENABLED:
1535 if ("0".equals(value)) return false;
1536 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1537 break;
1538
1539 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1540 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1541 if ("1".equals(value)) return false;
1542 restriction = UserManager.ENSURE_VERIFY_APPS;
1543 break;
1544
1545 case Settings.Global.PREFERRED_NETWORK_MODE:
1546 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1547 break;
1548
Victor Chang9c7b7062016-07-12 23:47:29 +01001549 case Settings.Secure.ALWAYS_ON_VPN_APP:
1550 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1551 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001552 final int appId = UserHandle.getAppId(callingUid);
1553 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001554 return false;
1555 }
1556 restriction = UserManager.DISALLOW_CONFIG_VPN;
1557 break;
1558
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001559 case Settings.Global.SAFE_BOOT_DISALLOWED:
1560 if ("1".equals(value)) return false;
1561 restriction = UserManager.DISALLOW_SAFE_BOOT;
1562 break;
1563
Makoto Onuki28da2e32015-11-20 11:30:44 -08001564 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001565 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001566 if ("0".equals(value)) return false;
1567 restriction = UserManager.DISALLOW_DATA_ROAMING;
1568 break;
1569 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001570 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001571 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001572
1573 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001574 }
1575
1576 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1577 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1578 }
1579
1580 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001581 final int parentId;
1582 // Resolves dependency if setting has a dependency and the calling user has a parent
1583 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1584 && (parentId = getGroupParentLocked(userId)) != userId) {
1585 // The setting has a dependency and the profile has a parent
1586 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001587 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1588 final long token = Binder.clearCallingIdentity();
1589 try {
1590 Setting settingObj = getSecureSetting(dependency, userId);
1591 if (settingObj != null && settingObj.getValue().equals("1")) {
1592 return parentId;
1593 }
1594 } finally {
1595 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001596 }
1597 }
Svetoslav683914b2015-01-15 14:22:26 -08001598 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1599 }
1600
1601 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1602 final int parentId = getGroupParentLocked(userId);
1603 if (parentId != userId && keys.contains(name)) {
1604 return parentId;
1605 }
1606 return userId;
1607 }
1608
Svetoslavf41334b2015-06-23 12:06:03 -07001609 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001610 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001611 // System/root/shell can mutate whatever secure settings they want.
1612 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001613 final int appId = UserHandle.getAppId(callingUid);
1614 if (appId == android.os.Process.SYSTEM_UID
1615 || appId == Process.SHELL_UID
1616 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001617 return;
1618 }
1619
1620 switch (operation) {
1621 case MUTATION_OPERATION_INSERT:
1622 // Insert updates.
1623 case MUTATION_OPERATION_UPDATE: {
1624 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1625 return;
1626 }
1627
1628 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001629 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001630
1631 // Privileged apps can do whatever they want.
1632 if ((packageInfo.applicationInfo.privateFlags
1633 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1634 return;
1635 }
1636
1637 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1638 packageInfo.applicationInfo.targetSdkVersion, name);
1639 } break;
1640
1641 case MUTATION_OPERATION_DELETE: {
1642 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1643 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1644 throw new IllegalArgumentException("You cannot delete system defined"
1645 + " secure settings.");
1646 }
1647
1648 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001649 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001650
1651 // Privileged apps can do whatever they want.
1652 if ((packageInfo.applicationInfo.privateFlags &
1653 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1654 return;
1655 }
1656
1657 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1658 packageInfo.applicationInfo.targetSdkVersion, name);
1659 } break;
1660 }
1661 }
1662
Todd Kennedybe0b8892017-02-15 14:13:52 -08001663 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001664 switch (settingsType) {
1665 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001666 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001667 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001668 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001669 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001670 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001671 default:
1672 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1673 }
1674 }
1675
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001676 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1677 switch (settingsType) {
1678 case SETTINGS_TYPE_GLOBAL:
1679 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1680 case SETTINGS_TYPE_SYSTEM:
1681 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1682 case SETTINGS_TYPE_SECURE:
1683 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1684 default:
1685 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1686 }
1687 }
1688
Chad Brubaker97bccee2017-01-05 15:51:41 -08001689 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001690 boolean instantApp;
1691 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1692 instantApp = false;
1693 } else {
1694 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1695 instantApp = ai.isInstantApp();
1696 }
1697 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001698 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001699 } else {
1700 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1701 }
1702 }
1703
Chad Brubakera6830e72017-04-28 17:34:36 -07001704 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001705 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1706 return;
1707 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001708 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001709 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001710 return;
1711 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001712 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1713 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001714 throw new SecurityException("Setting " + settingName + " is not accessible from"
1715 + " ephemeral package " + getCallingPackage());
1716 }
1717 }
1718
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001719 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1720 // We always use the callingUid for this lookup. This means that if hypothetically an
1721 // app was installed in user A with cross user and in user B as an Instant App
1722 // the app in A would be able to see all the settings in user B. However since cross
1723 // user is a system permission and the app must be uninstalled in B and then installed as
1724 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001725 ApplicationInfo ai = null;
1726 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001727 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1728 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001729 } catch (RemoteException ignored) {
1730 }
1731 if (ai == null) {
1732 throw new IllegalStateException("Failed to lookup info for package "
1733 + getCallingPackage());
1734 }
1735 return ai;
1736 }
1737
Xiaohui Chen43765b72015-08-31 10:57:33 -07001738 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001739 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001740 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1741 getCallingPackage(), 0, userId);
1742 if (packageInfo != null) {
1743 return packageInfo;
1744 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001745 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001746 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001747 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001748 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001749 }
1750
1751 private int getGroupParentLocked(int userId) {
1752 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001753 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001754 return userId;
1755 }
1756 // We are in the same process with the user manager and the returned
1757 // user info is a cached instance, so just look up instead of cache.
1758 final long identity = Binder.clearCallingIdentity();
1759 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001760 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001761 UserInfo userInfo = mUserManager.getProfileParent(userId);
1762 return (userInfo != null) ? userInfo.id : userId;
1763 } finally {
1764 Binder.restoreCallingIdentity(identity);
1765 }
1766 }
1767
Svetoslav683914b2015-01-15 14:22:26 -08001768 private void enforceWritePermission(String permission) {
1769 if (getContext().checkCallingOrSelfPermission(permission)
1770 != PackageManager.PERMISSION_GRANTED) {
1771 throw new SecurityException("Permission denial: writing to settings requires:"
1772 + permission);
1773 }
1774 }
1775
1776 /*
1777 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1778 * This setting contains a list of the currently enabled location providers.
1779 * But helper functions in android.providers.Settings can enable or disable
1780 * a single provider by using a "+" or "-" prefix before the provider name.
1781 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001782 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1783 * is set, the said method will only allow values with the "-" prefix.
1784 *
Svetoslav683914b2015-01-15 14:22:26 -08001785 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001786 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001787 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1788 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001789 if (TextUtils.isEmpty(value)) {
1790 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001791 }
1792
Svetoslav683914b2015-01-15 14:22:26 -08001793 final char prefix = value.charAt(0);
1794 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001795 if (forceNotify) {
1796 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1797 mSettingsRegistry.notifyForSettingsChange(key,
1798 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1799 }
Svetoslav683914b2015-01-15 14:22:26 -08001800 return false;
1801 }
1802
1803 // skip prefix
1804 value = value.substring(1);
1805
Svetoslav7ec28e82015-05-20 17:01:10 -07001806 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001807 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001808 if (settingValue == null) {
1809 return false;
1810 }
Svetoslav683914b2015-01-15 14:22:26 -08001811
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001812 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001813
1814 int index = oldProviders.indexOf(value);
1815 int end = index + value.length();
1816
1817 // check for commas to avoid matching on partial string
1818 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1819 index = -1;
1820 }
1821
1822 // check for commas to avoid matching on partial string
1823 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1824 index = -1;
1825 }
1826
1827 String newProviders;
1828
1829 if (prefix == '+' && index < 0) {
1830 // append the provider to the list if not present
1831 if (oldProviders.length() == 0) {
1832 newProviders = value;
1833 } else {
1834 newProviders = oldProviders + ',' + value;
1835 }
1836 } else if (prefix == '-' && index >= 0) {
1837 // remove the provider from the list if present
1838 // remove leading or trailing comma
1839 if (index > 0) {
1840 index--;
1841 } else if (end < oldProviders.length()) {
1842 end++;
1843 }
1844
1845 newProviders = oldProviders.substring(0, index);
1846 if (end < oldProviders.length()) {
1847 newProviders += oldProviders.substring(end);
1848 }
1849 } else {
1850 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001851 if (forceNotify) {
1852 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1853 mSettingsRegistry.notifyForSettingsChange(key,
1854 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1855 }
Svetoslav683914b2015-01-15 14:22:26 -08001856 return false;
1857 }
1858
Svet Ganov53a441c2016-04-19 19:38:00 -07001859 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001860 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001861 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001862 }
1863
Svetoslav683914b2015-01-15 14:22:26 -08001864 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1865 int targetSdkVersion, String name) {
1866 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1867 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1868 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1869 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1870 + " This will soon become an error.");
1871 } else {
1872 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1873 + " This will soon become an error.");
1874 }
1875 } else {
1876 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1877 throw new IllegalArgumentException("You cannot change private secure settings.");
1878 } else {
1879 throw new IllegalArgumentException("You cannot keep your settings in"
1880 + " the secure settings.");
1881 }
1882 }
1883 }
1884
1885 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1886 if (requestingUserId == UserHandle.getCallingUserId()) {
1887 return requestingUserId;
1888 }
1889 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1890 Binder.getCallingUid(), requestingUserId, false, true,
1891 "get/set setting for user", null);
1892 }
1893
Svet Ganov53a441c2016-04-19 19:38:00 -07001894 private Bundle packageValueForCallResult(Setting setting,
1895 boolean trackingGeneration) {
1896 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001897 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001898 return NULL_SETTING_BUNDLE;
1899 }
1900 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001901 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001902 Bundle result = new Bundle();
1903 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001904 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001905
Svetoslav Ganove080da92016-12-21 17:10:35 -08001906 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001907 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001908 }
1909
1910 private static int getRequestingUserId(Bundle args) {
1911 final int callingUserId = UserHandle.getCallingUserId();
1912 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1913 : callingUserId;
1914 }
1915
Svet Ganov53a441c2016-04-19 19:38:00 -07001916 private boolean isTrackingGeneration(Bundle args) {
1917 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1918 }
1919
Svetoslav683914b2015-01-15 14:22:26 -08001920 private static String getSettingValue(Bundle args) {
1921 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1922 }
1923
Svetoslav Ganove080da92016-12-21 17:10:35 -08001924 private static String getSettingTag(Bundle args) {
1925 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1926 }
1927
1928 private static boolean getSettingMakeDefault(Bundle args) {
1929 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1930 }
1931
1932 private static int getResetModeEnforcingPermission(Bundle args) {
1933 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1934 switch (mode) {
1935 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1936 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1937 throw new SecurityException("Only system, shell/root on a "
1938 + "debuggable build can reset to untrusted defaults");
1939 }
1940 return mode;
1941 }
1942 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1943 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1944 throw new SecurityException("Only system, shell/root on a "
1945 + "debuggable build can reset untrusted changes");
1946 }
1947 return mode;
1948 }
1949 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1950 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1951 throw new SecurityException("Only system, shell/root on a "
1952 + "debuggable build can reset to trusted defaults");
1953 }
1954 return mode;
1955 }
1956 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1957 return mode;
1958 }
1959 }
1960 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1961 }
1962
1963 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1964 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1965 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1966 && (appId == SHELL_UID || appId == ROOT_UID));
1967 }
1968
Svetoslav683914b2015-01-15 14:22:26 -08001969 private static String getValidTableOrThrow(Uri uri) {
1970 if (uri.getPathSegments().size() > 0) {
1971 String table = uri.getPathSegments().get(0);
1972 if (DatabaseHelper.isValidTable(table)) {
1973 return table;
1974 }
1975 throw new IllegalArgumentException("Bad root path: " + table);
1976 }
1977 throw new IllegalArgumentException("Invalid URI:" + uri);
1978 }
1979
1980 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001981 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001982 return new MatrixCursor(projection, 0);
1983 }
1984 MatrixCursor cursor = new MatrixCursor(projection, 1);
1985 appendSettingToCursor(cursor, setting);
1986 return cursor;
1987 }
1988
1989 private static String[] normalizeProjection(String[] projection) {
1990 if (projection == null) {
1991 return ALL_COLUMNS;
1992 }
1993
1994 final int columnCount = projection.length;
1995 for (int i = 0; i < columnCount; i++) {
1996 String column = projection[i];
1997 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1998 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001999 }
2000 }
2001
Svetoslav683914b2015-01-15 14:22:26 -08002002 return projection;
2003 }
2004
2005 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002006 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002007 return;
2008 }
Svetoslav683914b2015-01-15 14:22:26 -08002009 final int columnCount = cursor.getColumnCount();
2010
2011 String[] values = new String[columnCount];
2012
2013 for (int i = 0; i < columnCount; i++) {
2014 String column = cursor.getColumnName(i);
2015
2016 switch (column) {
2017 case Settings.NameValueTable._ID: {
2018 values[i] = setting.getId();
2019 } break;
2020
2021 case Settings.NameValueTable.NAME: {
2022 values[i] = setting.getName();
2023 } break;
2024
2025 case Settings.NameValueTable.VALUE: {
2026 values[i] = setting.getValue();
2027 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002028 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002029 }
2030
Svetoslav683914b2015-01-15 14:22:26 -08002031 cursor.addRow(values);
2032 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002033
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002034 private static boolean isKeyValid(String key) {
2035 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2036 }
2037
Svetoslav683914b2015-01-15 14:22:26 -08002038 private static final class Arguments {
2039 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2040 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2041
2042 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2043 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2044
2045 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2046 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2047
2048 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2049 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2050
2051 public final String table;
2052 public final String name;
2053
2054 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2055 final int segmentSize = uri.getPathSegments().size();
2056 switch (segmentSize) {
2057 case 1: {
2058 if (where != null
2059 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2060 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2061 && whereArgs.length == 1) {
2062 name = whereArgs[0];
2063 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002064 return;
Svetoslav683914b2015-01-15 14:22:26 -08002065 } else if (where != null
2066 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2067 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2068 final int startIndex = Math.max(where.indexOf("'"),
2069 where.indexOf("\"")) + 1;
2070 final int endIndex = Math.max(where.lastIndexOf("'"),
2071 where.lastIndexOf("\""));
2072 name = where.substring(startIndex, endIndex);
2073 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002074 return;
Svetoslav683914b2015-01-15 14:22:26 -08002075 } else if (supportAll && where == null && whereArgs == null) {
2076 name = null;
2077 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002078 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002079 }
Svetoslav683914b2015-01-15 14:22:26 -08002080 } break;
2081
Svetoslav28494652015-02-12 14:11:42 -08002082 case 2: {
2083 if (where == null && whereArgs == null) {
2084 name = uri.getPathSegments().get(1);
2085 table = computeTableForSetting(uri, name);
2086 return;
2087 }
2088 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002089 }
Svetoslav28494652015-02-12 14:11:42 -08002090
2091 EventLogTags.writeUnsupportedSettingsQuery(
2092 uri.toSafeString(), where, Arrays.toString(whereArgs));
2093 String message = String.format( "Supported SQL:\n"
2094 + " uri content://some_table/some_property with null where and where args\n"
2095 + " uri content://some_table with query name=? and single name as arg\n"
2096 + " uri content://some_table with query name=some_name and null args\n"
2097 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2098 Arrays.toString(whereArgs));
2099 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002100 }
2101
Svetoslav28494652015-02-12 14:11:42 -08002102 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002103 String table = getValidTableOrThrow(uri);
2104
2105 if (name != null) {
2106 if (sSystemMovedToSecureSettings.contains(name)) {
2107 table = TABLE_SECURE;
2108 }
2109
2110 if (sSystemMovedToGlobalSettings.contains(name)) {
2111 table = TABLE_GLOBAL;
2112 }
2113
2114 if (sSecureMovedToGlobalSettings.contains(name)) {
2115 table = TABLE_GLOBAL;
2116 }
2117
2118 if (sGlobalMovedToSecureSettings.contains(name)) {
2119 table = TABLE_SECURE;
2120 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002121 }
Svetoslav683914b2015-01-15 14:22:26 -08002122
2123 return table;
2124 }
2125 }
2126
2127 final class SettingsRegistry {
2128 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2129
Svetoslav683914b2015-01-15 14:22:26 -08002130 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2131 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2132 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002133 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2134
2135 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002136
2137 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2138
Svet Ganov53a441c2016-04-19 19:38:00 -07002139 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002140
Svetoslav7e0683b2015-08-03 16:02:52 -07002141 private final Handler mHandler;
2142
Svet Ganov53a441c2016-04-19 19:38:00 -07002143 private final BackupManager mBackupManager;
2144
Amith Yamasani39452022017-03-21 15:23:47 -07002145 private String mSettingsCreationBuildId;
2146
Svetoslav683914b2015-01-15 14:22:26 -08002147 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002148 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002149 mGenerationRegistry = new GenerationRegistry(mLock);
2150 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002151 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002152 syncSsaidTableOnStart();
2153 }
2154
2155 private void generateUserKeyLocked(int userId) {
2156 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002157 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002158 final SecureRandom rand = new SecureRandom();
2159 rand.nextBytes(keyBytes);
2160
2161 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002162 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002163
2164 // Store the key in the ssaid table.
2165 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2166 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2167 true, SettingsState.SYSTEM_PACKAGE_NAME);
2168
2169 if (!success) {
2170 throw new IllegalStateException("Ssaid settings not accessible");
2171 }
2172 }
2173
Mark Rathjen7599f132017-01-23 14:15:54 -08002174 private byte[] getLengthPrefix(byte[] data) {
2175 return ByteBuffer.allocate(4).putInt(data.length).array();
2176 }
2177
Christopher Tateb218e762017-04-05 16:34:07 -07002178 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002179 // Read the user's key from the ssaid table.
2180 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002181 if (userKeySetting == null || userKeySetting.isNull()
2182 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002183 // Lazy initialize and store the user key.
2184 generateUserKeyLocked(userId);
2185 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002186 if (userKeySetting == null || userKeySetting.isNull()
2187 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002188 throw new IllegalStateException("User key not accessible");
2189 }
2190 }
2191 final String userKey = userKeySetting.getValue();
2192
2193 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002194 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2195
2196 // Validate that the key is of expected length.
2197 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2198 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002199 throw new IllegalStateException("User key invalid");
2200 }
2201
Mark Rathjen7599f132017-01-23 14:15:54 -08002202 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002203 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002204 m = Mac.getInstance("HmacSHA256");
2205 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002206 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002207 throw new IllegalStateException("HmacSHA256 is not available", e);
2208 } catch (InvalidKeyException e) {
2209 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002210 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002211
Mark Rathjenf42dd912017-06-05 19:04:34 -07002212 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002213 for (int i = 0; i < callingPkg.signatures.length; i++) {
2214 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002215 m.update(getLengthPrefix(sig), 0, 4);
2216 m.update(sig);
2217 }
Mark Rathjend891f012017-01-19 04:10:37 +00002218
2219 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002220 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2221 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002222
2223 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002224 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002225 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2226 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002227 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002228
2229 if (!success) {
2230 throw new IllegalStateException("Ssaid settings not accessible");
2231 }
2232
2233 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2234 }
2235
2236 public void syncSsaidTableOnStart() {
2237 synchronized (mLock) {
2238 // Verify that each user's packages and ssaid's are in sync.
2239 for (UserInfo user : mUserManager.getUsers(true)) {
2240 // Get all uids for the user's packages.
2241 final List<PackageInfo> packages;
2242 try {
2243 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2244 } catch (RemoteException e) {
2245 throw new IllegalStateException("Package manager not available");
2246 }
2247 final Set<String> appUids = new HashSet<>();
2248 for (PackageInfo info : packages) {
2249 appUids.add(Integer.toString(info.applicationInfo.uid));
2250 }
2251
2252 // Get all uids currently stored in the user's ssaid table.
2253 final Set<String> ssaidUids = new HashSet<>(
2254 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2255 ssaidUids.remove(SSAID_USER_KEY);
2256
2257 // Perform a set difference for the appUids and ssaidUids.
2258 ssaidUids.removeAll(appUids);
2259
2260 // If there are ssaidUids left over they need to be removed from the table.
2261 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2262 user.id);
2263 for (String uid : ssaidUids) {
2264 ssaidSettings.deleteSettingLocked(uid);
2265 }
2266 }
2267 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002268 }
2269
Svetoslav683914b2015-01-15 14:22:26 -08002270 public List<String> getSettingsNamesLocked(int type, int userId) {
2271 final int key = makeKey(type, userId);
2272 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002273 if (settingsState == null) {
2274 return new ArrayList<String>();
2275 }
Svetoslav683914b2015-01-15 14:22:26 -08002276 return settingsState.getSettingNamesLocked();
2277 }
2278
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002279 public SparseBooleanArray getKnownUsersLocked() {
2280 SparseBooleanArray users = new SparseBooleanArray();
2281 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2282 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2283 }
2284 return users;
2285 }
2286
Kweku Adamsb0886f32017-10-31 15:32:09 -07002287 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002288 public SettingsState getSettingsLocked(int type, int userId) {
2289 final int key = makeKey(type, userId);
2290 return peekSettingsStateLocked(key);
2291 }
2292
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002293 public boolean ensureSettingsForUserLocked(int userId) {
2294 // First make sure this user actually exists.
2295 if (mUserManager.getUserInfo(userId) == null) {
2296 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2297 return false;
2298 }
2299
Svetoslav683914b2015-01-15 14:22:26 -08002300 // Migrate the setting for this user if needed.
2301 migrateLegacySettingsForUserIfNeededLocked(userId);
2302
2303 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002304 if (userId == UserHandle.USER_SYSTEM) {
2305 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002306 ensureSettingsStateLocked(globalKey);
2307 }
2308
2309 // Ensure secure settings loaded.
2310 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2311 ensureSettingsStateLocked(secureKey);
2312
2313 // Make sure the secure settings have an Android id set.
2314 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2315 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2316
2317 // Ensure system settings loaded.
2318 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2319 ensureSettingsStateLocked(systemKey);
2320
Mark Rathjend891f012017-01-19 04:10:37 +00002321 // Ensure secure settings loaded.
2322 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2323 ensureSettingsStateLocked(ssaidKey);
2324
Svetoslav683914b2015-01-15 14:22:26 -08002325 // Upgrade the settings to the latest version.
2326 UpgradeController upgrader = new UpgradeController(userId);
2327 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002328 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002329 }
2330
2331 private void ensureSettingsStateLocked(int key) {
2332 if (mSettingsStates.get(key) == null) {
2333 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002334 SettingsState settingsState = new SettingsState(getContext(), mLock,
2335 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002336 mSettingsStates.put(key, settingsState);
2337 }
2338 }
2339
2340 public void removeUserStateLocked(int userId, boolean permanently) {
2341 // We always keep the global settings in memory.
2342
2343 // Nuke system settings.
2344 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2345 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2346 if (systemSettingsState != null) {
2347 if (permanently) {
2348 mSettingsStates.remove(systemKey);
2349 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002350 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002351 systemSettingsState.destroyLocked(new Runnable() {
2352 @Override
2353 public void run() {
2354 mSettingsStates.remove(systemKey);
2355 }
2356 });
2357 }
2358 }
2359
2360 // Nuke secure settings.
2361 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2362 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2363 if (secureSettingsState != null) {
2364 if (permanently) {
2365 mSettingsStates.remove(secureKey);
2366 secureSettingsState.destroyLocked(null);
2367 } else {
2368 secureSettingsState.destroyLocked(new Runnable() {
2369 @Override
2370 public void run() {
2371 mSettingsStates.remove(secureKey);
2372 }
2373 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002374 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002375 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002376
Mark Rathjend891f012017-01-19 04:10:37 +00002377 // Nuke ssaid settings.
2378 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2379 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2380 if (ssaidSettingsState != null) {
2381 if (permanently) {
2382 mSettingsStates.remove(ssaidKey);
2383 ssaidSettingsState.destroyLocked(null);
2384 } else {
2385 ssaidSettingsState.destroyLocked(new Runnable() {
2386 @Override
2387 public void run() {
2388 mSettingsStates.remove(ssaidKey);
2389 }
2390 });
2391 }
2392 }
2393
Svet Ganov53a441c2016-04-19 19:38:00 -07002394 // Nuke generation tracking data
2395 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002396 }
2397
Svetoslav683914b2015-01-15 14:22:26 -08002398 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002399 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2400 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002401 final int key = makeKey(type, userId);
2402
Svetoslav Ganove080da92016-12-21 17:10:35 -08002403 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002404 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002405 if (settingsState != null) {
2406 success = settingsState.insertSettingLocked(name, value,
2407 tag, makeDefault, packageName);
2408 }
Svetoslav683914b2015-01-15 14:22:26 -08002409
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002410 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2411 settingsState.persistSyncLocked();
2412 }
2413
Svet Ganov53a441c2016-04-19 19:38:00 -07002414 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002415 notifyForSettingsChange(key, name);
2416 }
2417 return success;
2418 }
2419
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002420 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2421 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002422 final int key = makeKey(type, userId);
2423
Svetoslav Ganove080da92016-12-21 17:10:35 -08002424 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002425 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002426 if (settingsState != null) {
2427 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002428 }
Svetoslav683914b2015-01-15 14:22:26 -08002429
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002430 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2431 settingsState.persistSyncLocked();
2432 }
2433
Svet Ganov53a441c2016-04-19 19:38:00 -07002434 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002435 notifyForSettingsChange(key, name);
2436 }
2437 return success;
2438 }
2439
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002440 public boolean updateSettingLocked(int type, int userId, String name, String value,
2441 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2442 Set<String> criticalSettings) {
2443 final int key = makeKey(type, userId);
2444
2445 boolean success = false;
2446 SettingsState settingsState = peekSettingsStateLocked(key);
2447 if (settingsState != null) {
2448 success = settingsState.updateSettingLocked(name, value, tag,
2449 makeDefault, packageName);
2450 }
2451
2452 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2453 settingsState.persistSyncLocked();
2454 }
2455
2456 if (forceNotify || success) {
2457 notifyForSettingsChange(key, name);
2458 }
2459
2460 return success;
2461 }
2462
Svetoslav683914b2015-01-15 14:22:26 -08002463 public Setting getSettingLocked(int type, int userId, String name) {
2464 final int key = makeKey(type, userId);
2465
2466 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002467 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002468 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002469 }
Mark Rathjend891f012017-01-19 04:10:37 +00002470
2471 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002472 return settingsState.getSettingLocked(name);
2473 }
2474
Svetoslav Ganove080da92016-12-21 17:10:35 -08002475 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2476 String tag) {
2477 final int key = makeKey(type, userId);
2478 SettingsState settingsState = peekSettingsStateLocked(key);
2479 if (settingsState == null) {
2480 return;
2481 }
2482
2483 switch (mode) {
2484 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2485 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002486 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002487 Setting setting = settingsState.getSettingLocked(name);
2488 if (packageName.equals(setting.getPackageName())) {
2489 if (tag != null && !tag.equals(setting.getTag())) {
2490 continue;
2491 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002492 if (settingsState.resetSettingLocked(name)) {
2493 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002494 notifyForSettingsChange(key, name);
2495 }
2496 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002497 if (someSettingChanged) {
2498 settingsState.persistSyncLocked();
2499 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002500 }
2501 } break;
2502
2503 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2504 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002505 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002506 Setting setting = settingsState.getSettingLocked(name);
2507 if (!SettingsState.isSystemPackage(getContext(),
2508 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002509 if (settingsState.resetSettingLocked(name)) {
2510 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002511 notifyForSettingsChange(key, name);
2512 }
2513 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002514 if (someSettingChanged) {
2515 settingsState.persistSyncLocked();
2516 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002517 }
2518 } break;
2519
2520 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2521 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002522 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002523 Setting setting = settingsState.getSettingLocked(name);
2524 if (!SettingsState.isSystemPackage(getContext(),
2525 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002526 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002527 if (settingsState.resetSettingLocked(name)) {
2528 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002529 notifyForSettingsChange(key, name);
2530 }
2531 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002532 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002533 notifyForSettingsChange(key, name);
2534 }
2535 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002536 if (someSettingChanged) {
2537 settingsState.persistSyncLocked();
2538 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002539 }
2540 } break;
2541
2542 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2543 for (String name : settingsState.getSettingNamesLocked()) {
2544 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002545 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002546 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002547 if (settingsState.resetSettingLocked(name)) {
2548 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002549 notifyForSettingsChange(key, name);
2550 }
2551 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002552 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002553 notifyForSettingsChange(key, name);
2554 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002555 if (someSettingChanged) {
2556 settingsState.persistSyncLocked();
2557 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002558 }
2559 } break;
2560 }
2561 }
2562
Svetoslav683914b2015-01-15 14:22:26 -08002563 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002564 // Global and secure settings are signature protected. Apps signed
2565 // by the platform certificate are generally not uninstalled and
2566 // the main exception is tests. We trust components signed
2567 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002568
2569 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2570 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002571 if (systemSettings != null) {
2572 systemSettings.onPackageRemovedLocked(packageName);
2573 }
Svetoslav683914b2015-01-15 14:22:26 -08002574 }
2575
Mark Rathjend891f012017-01-19 04:10:37 +00002576 public void onUidRemovedLocked(int uid) {
2577 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2578 UserHandle.getUserId(uid));
2579 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2580 }
2581
Kweku Adamsb0886f32017-10-31 15:32:09 -07002582 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002583 private SettingsState peekSettingsStateLocked(int key) {
2584 SettingsState settingsState = mSettingsStates.get(key);
2585 if (settingsState != null) {
2586 return settingsState;
2587 }
2588
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002589 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2590 return null;
2591 }
Svetoslav683914b2015-01-15 14:22:26 -08002592 return mSettingsStates.get(key);
2593 }
2594
2595 private void migrateAllLegacySettingsIfNeeded() {
2596 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002597 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002598 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002599 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002600 return;
2601 }
2602
Amith Yamasani39452022017-03-21 15:23:47 -07002603 mSettingsCreationBuildId = Build.ID;
2604
Svetoslav683914b2015-01-15 14:22:26 -08002605 final long identity = Binder.clearCallingIdentity();
2606 try {
2607 List<UserInfo> users = mUserManager.getUsers(true);
2608
2609 final int userCount = users.size();
2610 for (int i = 0; i < userCount; i++) {
2611 final int userId = users.get(i).id;
2612
2613 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2614 SQLiteDatabase database = dbHelper.getWritableDatabase();
2615 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2616
2617 // Upgrade to the latest version.
2618 UpgradeController upgrader = new UpgradeController(userId);
2619 upgrader.upgradeIfNeededLocked();
2620
2621 // Drop from memory if not a running user.
2622 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2623 removeUserStateLocked(userId, false);
2624 }
2625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(identity);
2628 }
2629 }
2630 }
2631
2632 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2633 // Every user has secure settings and if no file we need to migrate.
2634 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2635 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002636 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002637 return;
2638 }
2639
2640 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2641 SQLiteDatabase database = dbHelper.getWritableDatabase();
2642
2643 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2644 }
2645
2646 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2647 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002648 // Move over the system settings.
2649 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2650 ensureSettingsStateLocked(systemKey);
2651 SettingsState systemSettings = mSettingsStates.get(systemKey);
2652 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2653 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002654
2655 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002656 // Do this after System settings, since this is the first thing we check when deciding
2657 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002658 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2659 ensureSettingsStateLocked(secureKey);
2660 SettingsState secureSettings = mSettingsStates.get(secureKey);
2661 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2662 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2663 secureSettings.persistSyncLocked();
2664
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002665 // Move over the global settings if owner.
2666 // Do this last, since this is the first thing we check when deciding
2667 // to skip over migration from db to xml for owner user.
2668 if (userId == UserHandle.USER_SYSTEM) {
2669 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2670 ensureSettingsStateLocked(globalKey);
2671 SettingsState globalSettings = mSettingsStates.get(globalKey);
2672 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002673 // If this was just created
2674 if (mSettingsCreationBuildId != null) {
2675 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2676 mSettingsCreationBuildId, null, true,
2677 SettingsState.SYSTEM_PACKAGE_NAME);
2678 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002679 globalSettings.persistSyncLocked();
2680 }
Svetoslav683914b2015-01-15 14:22:26 -08002681
2682 // Drop the database as now all is moved and persisted.
2683 if (DROP_DATABASE_ON_MIGRATION) {
2684 dbHelper.dropDatabase();
2685 } else {
2686 dbHelper.backupDatabase();
2687 }
2688 }
2689
2690 private void migrateLegacySettingsLocked(SettingsState settingsState,
2691 SQLiteDatabase database, String table) {
2692 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2693 queryBuilder.setTables(table);
2694
2695 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2696 null, null, null, null, null);
2697
2698 if (cursor == null) {
2699 return;
2700 }
2701
2702 try {
2703 if (!cursor.moveToFirst()) {
2704 return;
2705 }
2706
2707 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2708 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2709
2710 settingsState.setVersionLocked(database.getVersion());
2711
2712 while (!cursor.isAfterLast()) {
2713 String name = cursor.getString(nameColumnIdx);
2714 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002715 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002716 SettingsState.SYSTEM_PACKAGE_NAME);
2717 cursor.moveToNext();
2718 }
2719 } finally {
2720 cursor.close();
2721 }
2722 }
2723
2724 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2725 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2726
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002727 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002728 return;
2729 }
2730
2731 final int userId = getUserIdFromKey(secureSettings.mKey);
2732
2733 final UserInfo user;
2734 final long identity = Binder.clearCallingIdentity();
2735 try {
2736 user = mUserManager.getUserInfo(userId);
2737 } finally {
2738 Binder.restoreCallingIdentity(identity);
2739 }
2740 if (user == null) {
2741 // Can happen due to races when deleting users - treat as benign.
2742 return;
2743 }
2744
2745 String androidId = Long.toHexString(new SecureRandom().nextLong());
2746 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002747 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002748
2749 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2750 + "] for user " + userId);
2751
2752 // Write a drop box entry if it's a restricted profile
2753 if (user.isRestricted()) {
2754 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2755 Context.DROPBOX_SERVICE);
2756 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2757 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2758 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2759 }
2760 }
2761 }
2762
2763 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002764 final int userId = getUserIdFromKey(key);
2765 Uri uri = getNotificationUriFor(key, name);
2766
Phil Weaver83fec002016-05-11 10:55:29 -07002767 mGenerationRegistry.incrementGeneration(key);
2768
Svetoslav7e0683b2015-08-03 16:02:52 -07002769 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2770 userId, 0, uri).sendToTarget();
2771
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002772 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002773 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2774 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002775 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2776 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002777 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002778 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2779 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002780 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002781
Svet Ganov53a441c2016-04-19 19:38:00 -07002782 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002783 }
2784
Svet Ganov53a441c2016-04-19 19:38:00 -07002785 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002786 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002787 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002788 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002789 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002790 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002791 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002792 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002793 final int key = makeKey(type, profileId);
2794 mGenerationRegistry.incrementGeneration(key);
2795
2796 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002797 }
2798 }
2799 }
Svetoslav683914b2015-01-15 14:22:26 -08002800 }
2801
Svetoslav683914b2015-01-15 14:22:26 -08002802 private boolean isGlobalSettingsKey(int key) {
2803 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2804 }
2805
2806 private boolean isSystemSettingsKey(int key) {
2807 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2808 }
2809
2810 private boolean isSecureSettingsKey(int key) {
2811 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2812 }
2813
Mark Rathjend891f012017-01-19 04:10:37 +00002814 private boolean isSsaidSettingsKey(int key) {
2815 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2816 }
2817
Svetoslav683914b2015-01-15 14:22:26 -08002818 private File getSettingsFile(int key) {
2819 if (isGlobalSettingsKey(key)) {
2820 final int userId = getUserIdFromKey(key);
2821 return new File(Environment.getUserSystemDirectory(userId),
2822 SETTINGS_FILE_GLOBAL);
2823 } else if (isSystemSettingsKey(key)) {
2824 final int userId = getUserIdFromKey(key);
2825 return new File(Environment.getUserSystemDirectory(userId),
2826 SETTINGS_FILE_SYSTEM);
2827 } else if (isSecureSettingsKey(key)) {
2828 final int userId = getUserIdFromKey(key);
2829 return new File(Environment.getUserSystemDirectory(userId),
2830 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002831 } else if (isSsaidSettingsKey(key)) {
2832 final int userId = getUserIdFromKey(key);
2833 return new File(Environment.getUserSystemDirectory(userId),
2834 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002835 } else {
2836 throw new IllegalArgumentException("Invalid settings key:" + key);
2837 }
2838 }
2839
2840 private Uri getNotificationUriFor(int key, String name) {
2841 if (isGlobalSettingsKey(key)) {
2842 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2843 : Settings.Global.CONTENT_URI;
2844 } else if (isSecureSettingsKey(key)) {
2845 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2846 : Settings.Secure.CONTENT_URI;
2847 } else if (isSystemSettingsKey(key)) {
2848 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2849 : Settings.System.CONTENT_URI;
2850 } else {
2851 throw new IllegalArgumentException("Invalid settings key:" + key);
2852 }
2853 }
2854
2855 private int getMaxBytesPerPackageForType(int type) {
2856 switch (type) {
2857 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002858 case SETTINGS_TYPE_SECURE:
2859 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002860 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2861 }
2862
2863 default: {
2864 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2865 }
2866 }
2867 }
2868
Svetoslav7e0683b2015-08-03 16:02:52 -07002869 private final class MyHandler extends Handler {
2870 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2871 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2872
2873 public MyHandler(Looper looper) {
2874 super(looper);
2875 }
2876
2877 @Override
2878 public void handleMessage(Message msg) {
2879 switch (msg.what) {
2880 case MSG_NOTIFY_URI_CHANGED: {
2881 final int userId = msg.arg1;
2882 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002883 try {
2884 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2885 } catch (SecurityException e) {
2886 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2887 }
Svetoslav7e0683b2015-08-03 16:02:52 -07002888 if (DEBUG) {
2889 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2890 }
2891 } break;
2892
2893 case MSG_NOTIFY_DATA_CHANGED: {
2894 mBackupManager.dataChanged();
2895 } break;
2896 }
2897 }
2898 }
2899
Svetoslav683914b2015-01-15 14:22:26 -08002900 private final class UpgradeController {
Jacky Cheung7076a312017-10-02 10:40:48 -07002901 private static final int SETTINGS_VERSION = 150;
Svetoslav683914b2015-01-15 14:22:26 -08002902
2903 private final int mUserId;
2904
2905 public UpgradeController(int userId) {
2906 mUserId = userId;
2907 }
2908
2909 public void upgradeIfNeededLocked() {
2910 // The version of all settings for a user is the same (all users have secure).
2911 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002912 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002913
2914 // Try an update from the current state.
2915 final int oldVersion = secureSettings.getVersionLocked();
2916 final int newVersion = SETTINGS_VERSION;
2917
Svet Ganovc9755bc2015-03-28 13:21:22 -07002918 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002919 if (oldVersion == newVersion) {
2920 return;
2921 }
2922
2923 // Try to upgrade.
2924 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2925
2926 // If upgrade failed start from scratch and upgrade.
2927 if (curVersion != newVersion) {
2928 // Drop state we have for this user.
2929 removeUserStateLocked(mUserId, true);
2930
2931 // Recreate the database.
2932 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2933 SQLiteDatabase database = dbHelper.getWritableDatabase();
2934 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2935
2936 // Migrate the settings for this user.
2937 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2938
2939 // Now upgrade should work fine.
2940 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002941
2942 // Make a note what happened, so we don't wonder why data was lost
2943 String reason = "Settings rebuilt! Current version: "
2944 + curVersion + " while expected: " + newVersion;
2945 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002946 Settings.Global.DATABASE_DOWNGRADE_REASON,
2947 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002948 }
2949
2950 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002951 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002952 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002953 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002954 globalSettings.setVersionLocked(newVersion);
2955 }
2956
2957 // Set the secure settings version.
2958 secureSettings.setVersionLocked(newVersion);
2959
2960 // Set the system settings version.
2961 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002962 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002963 systemSettings.setVersionLocked(newVersion);
2964 }
2965
2966 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002967 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002968 }
2969
2970 private SettingsState getSecureSettingsLocked(int userId) {
2971 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2972 }
2973
Mark Rathjend891f012017-01-19 04:10:37 +00002974 private SettingsState getSsaidSettingsLocked(int userId) {
2975 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2976 }
2977
Svetoslav683914b2015-01-15 14:22:26 -08002978 private SettingsState getSystemSettingsLocked(int userId) {
2979 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2980 }
2981
Jeff Brown503cffc2015-03-26 18:08:51 -07002982 /**
2983 * You must perform all necessary mutations to bring the settings
2984 * for this user from the old to the new version. When you add a new
2985 * upgrade step you *must* update SETTINGS_VERSION.
2986 *
2987 * This is an example of moving a setting from secure to global.
2988 *
2989 * // v119: Example settings changes.
2990 * if (currentVersion == 118) {
2991 * if (userId == UserHandle.USER_OWNER) {
2992 * // Remove from the secure settings.
2993 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2994 * String name = "example_setting_to_move";
2995 * String value = secureSettings.getSetting(name);
2996 * secureSettings.deleteSetting(name);
2997 *
2998 * // Add to the global settings.
2999 * SettingsState globalSettings = getGlobalSettingsLocked();
3000 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3001 * }
3002 *
3003 * // Update the current version.
3004 * currentVersion = 119;
3005 * }
3006 */
Svetoslav683914b2015-01-15 14:22:26 -08003007 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3008 if (DEBUG) {
3009 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3010 + oldVersion + " to version: " + newVersion);
3011 }
3012
Jeff Brown503cffc2015-03-26 18:08:51 -07003013 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003014
John Spurlocke11ae112015-05-11 16:09:03 -04003015 // v119: Reset zen + ringer mode.
3016 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003017 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003018 final SettingsState globalSettings = getGlobalSettingsLocked();
3019 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003020 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3021 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003022 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003023 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3024 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003025 }
3026 currentVersion = 119;
3027 }
3028
Jason Monk27bbb2d2015-03-31 16:46:39 -04003029 // v120: Add double tap to wake setting.
3030 if (currentVersion == 119) {
3031 SettingsState secureSettings = getSecureSettingsLocked(userId);
3032 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3033 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003034 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003035 SettingsState.SYSTEM_PACKAGE_NAME);
3036
3037 currentVersion = 120;
3038 }
3039
Svetoslav7e0683b2015-08-03 16:02:52 -07003040 if (currentVersion == 120) {
3041 // Before 121, we used a different string encoding logic. We just bump the
3042 // version here; SettingsState knows how to handle pre-version 120 files.
3043 currentVersion = 121;
3044 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003045
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003046 if (currentVersion == 121) {
3047 // Version 122: allow OEMs to set a default payment component in resources.
3048 // Note that we only write the default if no default has been set;
3049 // if there is, we just leave the default at whatever it currently is.
3050 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3051 String defaultComponent = (getContext().getResources().getString(
3052 R.string.def_nfc_payment_component));
3053 Setting currentSetting = secureSettings.getSettingLocked(
3054 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3055 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003056 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003057 secureSettings.insertSettingLocked(
3058 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003059 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003060 }
3061 currentVersion = 122;
3062 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003063
3064 if (currentVersion == 122) {
3065 // Version 123: Adding a default value for the ability to add a user from
3066 // the lock screen.
3067 if (userId == UserHandle.USER_SYSTEM) {
3068 final SettingsState globalSettings = getGlobalSettingsLocked();
3069 Setting currentSetting = globalSettings.getSettingLocked(
3070 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003071 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003072 globalSettings.insertSettingLocked(
3073 Settings.Global.ADD_USERS_WHEN_LOCKED,
3074 getContext().getResources().getBoolean(
3075 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003076 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003077 }
3078 }
3079 currentVersion = 123;
3080 }
Bryce Leebd179282015-12-17 19:01:37 -08003081
3082 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003083 final SettingsState globalSettings = getGlobalSettingsLocked();
3084 String defaultDisabledProfiles = (getContext().getResources().getString(
3085 R.string.def_bluetooth_disabled_profiles));
3086 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003087 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003088 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003089 }
3090
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003091 if (currentVersion == 124) {
3092 // Version 124: allow OEMs to set a default value for whether IME should be
3093 // shown when a physical keyboard is connected.
3094 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3095 Setting currentSetting = secureSettings.getSettingLocked(
3096 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003097 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003098 secureSettings.insertSettingLocked(
3099 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3100 getContext().getResources().getBoolean(
3101 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003102 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003103 }
3104 currentVersion = 125;
3105 }
3106
Ruben Brunk98576cf2016-03-07 18:54:28 -08003107 if (currentVersion == 125) {
3108 // Version 125: Allow OEMs to set the default VR service.
3109 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3110
3111 Setting currentSetting = secureSettings.getSettingLocked(
3112 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003113 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003114 ArraySet<ComponentName> l =
3115 SystemConfig.getInstance().getDefaultVrComponents();
3116
3117 if (l != null && !l.isEmpty()) {
3118 StringBuilder b = new StringBuilder();
3119 boolean start = true;
3120 for (ComponentName c : l) {
3121 if (!start) {
3122 b.append(':');
3123 }
3124 b.append(c.flattenToString());
3125 start = false;
3126 }
3127 secureSettings.insertSettingLocked(
3128 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003129 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003130 }
3131
3132 }
3133 currentVersion = 126;
3134 }
3135
Daniel U02ba6122016-04-01 18:41:42 +01003136 if (currentVersion == 126) {
3137 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3138 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3139 if (mUserManager.isManagedProfile(userId)) {
3140 final SettingsState systemSecureSettings =
3141 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3142
3143 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3144 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003145 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003146 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3147 secureSettings.insertSettingLocked(
3148 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003149 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003150 SettingsState.SYSTEM_PACKAGE_NAME);
3151 }
3152
3153 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3154 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003155 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003156 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3157 secureSettings.insertSettingLocked(
3158 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003159 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003160 SettingsState.SYSTEM_PACKAGE_NAME);
3161 }
3162 }
3163 currentVersion = 127;
3164 }
3165
Steven Ngdc20ba62016-04-26 18:19:04 +01003166 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003167 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003168 currentVersion = 128;
3169 }
3170
Julia Reynolds1f721e12016-07-11 08:50:58 -04003171 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003172 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003173 currentVersion = 129;
3174 }
3175
Dan Sandler71f85e92016-07-20 13:46:05 -04003176 if (currentVersion == 129) {
3177 // default longpress timeout changed from 500 to 400. If unchanged from the old
3178 // default, update to the new default.
3179 final SettingsState systemSecureSettings =
3180 getSecureSettingsLocked(userId);
3181 final String oldValue = systemSecureSettings.getSettingLocked(
3182 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3183 if (TextUtils.equals("500", oldValue)) {
3184 systemSecureSettings.insertSettingLocked(
3185 Settings.Secure.LONG_PRESS_TIMEOUT,
3186 String.valueOf(getContext().getResources().getInteger(
3187 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003188 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003189 }
3190 currentVersion = 130;
3191 }
3192
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003193 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003194 // Split Ambient settings
3195 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3196 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3197 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3198
3199 if (dozeExplicitlyDisabled) {
3200 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003201 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003202 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003203 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003204 }
3205 currentVersion = 131;
3206 }
3207
3208 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003209 // Initialize new multi-press timeout to default value
3210 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3211 final String oldValue = systemSecureSettings.getSettingLocked(
3212 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3213 if (TextUtils.equals(null, oldValue)) {
3214 systemSecureSettings.insertSettingLocked(
3215 Settings.Secure.MULTI_PRESS_TIMEOUT,
3216 String.valueOf(getContext().getResources().getInteger(
3217 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003218 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003219 }
3220
Adrian Roos69741a22016-10-21 14:49:17 -07003221 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003222 }
3223
Adrian Roos69741a22016-10-21 14:49:17 -07003224 if (currentVersion == 132) {
3225 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003226 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3227 String defaultSyncParentSounds = (getContext().getResources()
3228 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3229 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003230 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3231 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003232 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003233 }
3234
Adrian Roos69741a22016-10-21 14:49:17 -07003235 if (currentVersion == 133) {
3236 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003237 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3238 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3239 null) {
3240 String defaultEndButtonBehavior = Integer.toString(getContext()
3241 .getResources().getInteger(R.integer.def_end_button_behavior));
3242 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003243 defaultEndButtonBehavior, null, true,
3244 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003245 }
Adrian Roos69741a22016-10-21 14:49:17 -07003246 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003247 }
3248
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003249 if (currentVersion == 134) {
3250 // Remove setting that specifies if magnification values should be preserved.
3251 // This setting defaulted to true and never has a UI.
3252 getSecureSettingsLocked(userId).deleteSettingLocked(
3253 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3254 currentVersion = 135;
3255 }
3256
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003257 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003258 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003259 currentVersion = 136;
3260 }
3261
Mark Rathjend891f012017-01-19 04:10:37 +00003262 if (currentVersion == 136) {
3263 // Version 136: Store legacy SSAID for all apps currently installed on the
3264 // device as first step in migrating SSAID to be unique per application.
3265
3266 final boolean isUpgrade;
3267 try {
3268 isUpgrade = mPackageManager.isUpgrade();
3269 } catch (RemoteException e) {
3270 throw new IllegalStateException("Package manager not available");
3271 }
3272 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3273 // user data or first boot on a new device should use new ssaid generation.
3274 if (isUpgrade) {
3275 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003276 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3277 userId, Settings.Secure.ANDROID_ID);
3278 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3279 || legacySsaidSetting.getValue() == null) {
3280 throw new IllegalStateException("Legacy ssaid not accessible");
3281 }
3282 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003283
3284 // Fill each uid with the legacy ssaid to be backwards compatible.
3285 final List<PackageInfo> packages;
3286 try {
3287 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3288 } catch (RemoteException e) {
3289 throw new IllegalStateException("Package manager not available");
3290 }
3291
3292 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3293 for (PackageInfo info : packages) {
3294 // Check if the UID already has an entry in the table.
3295 final String uid = Integer.toString(info.applicationInfo.uid);
3296 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3297
3298 if (ssaid.isNull() || ssaid.getValue() == null) {
3299 // Android Id doesn't exist for this package so create it.
3300 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3301 info.packageName);
3302 }
3303 }
3304 }
3305
3306 currentVersion = 137;
3307 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003308 if (currentVersion == 137) {
3309 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3310 // default value set to 1. The user can no longer change the value of this
3311 // setting through the UI.
3312 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3313 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003314 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3315 && secureSetting.getSettingLocked(
3316 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3317
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003318 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3319 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003320 // For managed profiles with profile owners, DevicePolicyManagerService
3321 // may want to set the user restriction in this case
3322 secureSetting.insertSettingLocked(
3323 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3324 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003325 }
3326 currentVersion = 138;
3327 }
Mark Rathjend891f012017-01-19 04:10:37 +00003328
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003329 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003330 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003331 currentVersion = 139;
3332 }
3333
Phil Weaver385912e2017-02-10 10:06:56 -08003334 if (currentVersion == 139) {
3335 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3336 // the user can no longer change the value of this setting through the UI.
3337 // Force to true.
3338 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3339 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3340 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3341 currentVersion = 140;
3342 }
3343
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003344 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003345 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003346 currentVersion = 141;
3347 }
3348
Svet Ganov13701552017-02-23 12:45:17 -08003349 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003350 // This implementation was incorrectly setting the current value of
3351 // settings changed by non-system packages as the default which default
3352 // is set by the system. We add a new upgrade step at the end to properly
3353 // handle this case which would also fix incorrect changes made by the
3354 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003355 currentVersion = 142;
3356 }
3357
Stephen Chen5d0922f2017-03-27 10:28:04 -07003358 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003359 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003360 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
Felipe Lemeff355092017-04-03 12:55:02 -07003376 if (currentVersion == 143) {
3377 // Version 144: Set a default value for Autofill service.
3378 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3379 final Setting currentSetting = secureSettings
3380 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3381 if (currentSetting.isNull()) {
3382 final String defaultValue = getContext().getResources().getString(
3383 com.android.internal.R.string.config_defaultAutofillService);
3384 if (defaultValue != null) {
3385 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3386 + "for user " + userId);
3387 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3388 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3389 }
3390 }
3391
3392 currentVersion = 144;
3393 }
3394
Jeremy Joslin45caa252017-05-04 11:22:46 -07003395 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003396 // Version 145: Removed
3397 currentVersion = 145;
3398 }
3399
3400 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003401 // Version 146: In step 142 we had a bug where incorrectly
3402 // some settings were considered system set and as a result
3403 // made the default and marked as the default being set by
3404 // the system. Here reevaluate the default and default system
3405 // set flags. This would both fix corruption by the old impl
3406 // of step 142 and also properly handle devices which never
3407 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003408 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003409 SettingsState globalSettings = getGlobalSettingsLocked();
3410 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3411 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003412 }
3413
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003414 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3415 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3416 secureSettings.persistSyncLocked();
3417
3418 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3419 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3420 systemSettings.persistSyncLocked();
3421
Amin Shaikh86367962017-06-07 08:58:22 -07003422 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003423 }
3424
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003425 if (currentVersion == 146) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003426 // Version 147: Set the default value for WIFI_WAKEUP_AVAILABLE.
3427 if (userId == UserHandle.USER_SYSTEM) {
3428 final SettingsState globalSettings = getGlobalSettingsLocked();
3429 final Setting currentSetting = globalSettings.getSettingLocked(
3430 Settings.Global.WIFI_WAKEUP_AVAILABLE);
3431 if (currentSetting.getValue() == null) {
3432 final int defaultValue = getContext().getResources().getInteger(
3433 com.android.internal.R.integer.config_wifi_wakeup_available);
3434 globalSettings.insertSettingLocked(
3435 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3436 String.valueOf(defaultValue),
3437 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3438 }
3439 }
3440
3441 currentVersion = 147;
3442 }
3443
3444 if (currentVersion == 147) {
3445 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003446 if (userId == UserHandle.USER_SYSTEM) {
3447 final SettingsState globalSettings = getGlobalSettingsLocked();
3448 final Setting currentSetting = globalSettings.getSettingLocked(
3449 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3450 if (currentSetting.isNull()) {
3451 globalSettings.insertSettingLocked(
3452 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3453 getContext().getResources().getBoolean(
3454 R.bool.def_restrict_background_data) ? "1" : "0",
3455 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3456 }
3457 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003458 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003459 }
3460
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003461 if (currentVersion == 148) {
3462 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3463 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3464 final String oldValue = systemSecureSettings.getSettingLocked(
3465 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3466 if (TextUtils.equals(null, oldValue)) {
3467 final String defaultValue = getContext().getResources().getString(
3468 R.string.def_backup_manager_constants);
3469 if (!TextUtils.isEmpty(defaultValue)) {
3470 systemSecureSettings.insertSettingLocked(
3471 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3472 true, SettingsState.SYSTEM_PACKAGE_NAME);
3473 }
3474 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003475 currentVersion = 149;
3476 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003477
3478 if (currentVersion == 149) {
3479 // Version 150: Set a default value for mobile data always on
3480 final SettingsState globalSettings = getGlobalSettingsLocked();
3481 final Setting currentSetting = globalSettings.getSettingLocked(
3482 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3483 if (currentSetting.isNull()) {
3484 globalSettings.insertSettingLocked(
3485 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3486 getContext().getResources().getBoolean(
3487 R.bool.def_mobile_data_always_on) ? "1" : "0",
3488 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3489 }
3490
3491 currentVersion = 150;
3492 }
3493
Felipe Lemeff355092017-04-03 12:55:02 -07003494 // vXXX: Add new settings above this point.
3495
Dan Sandler71f85e92016-07-20 13:46:05 -04003496 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003497 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003498 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003499 + currentVersion +
3500 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3501 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003502 if (DEBUG) {
3503 throw new RuntimeException("db upgrade error");
3504 }
3505 }
3506
Jeff Brown503cffc2015-03-26 18:08:51 -07003507 // Return the current version.
3508 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003509 }
3510 }
Svet Ganov13701552017-02-23 12:45:17 -08003511
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003512 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3513 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003514 List<String> names = settings.getSettingNamesLocked();
3515 final int nameCount = names.size();
3516 for (int i = 0; i < nameCount; i++) {
3517 String name = names.get(i);
3518 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003519
3520 // In the upgrade case we pretend the call is made from the app
3521 // that made the last change to the setting to properly determine
3522 // whether the call has been made by a system component.
3523 int callingUid = -1;
3524 try {
3525 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3526 } catch (RemoteException e) {
3527 /* ignore - handled below */
3528 }
3529 if (callingUid < 0) {
3530 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3531 continue;
3532 }
3533 try {
3534 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3535 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003536 if (systemSet) {
3537 settings.insertSettingLocked(name, setting.getValue(),
3538 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003539 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3540 // We had a bug where changes by non-system packages were marked
3541 // as system made and as a result set as the default. Therefore, if
3542 // the package changed the setting last is not a system one but the
3543 // setting is marked as its default coming from the system we clear
3544 // the default and clear the system set flag.
3545 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003546 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003547 } catch (IllegalStateException e) {
3548 // If the package goes over its quota during the upgrade, don't
3549 // crash but just log the error as the system does the upgrade.
3550 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3551
Svet Ganov13701552017-02-23 12:45:17 -08003552 }
3553 }
3554 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003555 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003556}